blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e8b8cb43f732195b631ce0c9a08f9c8bc836d89c | 02439f359d5952b966729c6f756ef8ffc65ed36a | /src/pure-tx.cpp | 0fc401df5444ba7b914cc61dbc6da50b76fa2803 | [
"MIT"
] | permissive | fusionfoto/pure-v2 | aef21ed238a2cccc4b975738c164ea19988f7efa | 785aa2dea6d218cbf526855bb689edad36a1d5ce | refs/heads/master | 2020-03-22T16:17:58.479171 | 2018-05-18T08:58:20 | 2018-05-18T08:58:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,268 | cpp | // Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "clientversion.h"
#include "coins.h"
#include "core_io.h"
#include "keystore.h"
#include "primitives/block.h" // for MAX_BLOCK_SIZE
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/sign.h"
#include "ui_interface.h" // for _(...)
#include "univalue/univalue.h"
#include "util.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include <stdio.h>
#include <boost/algorithm/string.hpp>
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
using namespace std;
static bool fCreateBlank;
static map<string, UniValue> registers;
CClientUIInterface uiInterface;
static bool AppInitRawTx(int argc, char* argv[])
{
//
// Parameters
//
ParseParameters(argc, argv);
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
if (!SelectParamsFromCommandLine()) {
fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
return false;
}
fCreateBlank = GetBoolArg("-create", false);
if (argc < 2 || mapArgs.count("-?") || mapArgs.count("-help")) {
// First part of help message is specific to this utility
std::string strUsage = _("Pure pure-tx utility version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" pure-tx [options] <hex-tx> [commands] " + _("Update hex-encoded pure transaction") + "\n" +
" pure-tx [options] -create [commands] " + _("Create hex-encoded pure transaction") + "\n" +
"\n";
fprintf(stdout, "%s", strUsage.c_str());
strUsage = HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-create", _("Create new, empty TX."));
strUsage += HelpMessageOpt("-json", _("Select JSON output"));
strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction."));
strUsage += HelpMessageOpt("-regtest", _("Enter regression test mode, which uses a special chain in which blocks can be solved instantly."));
strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
fprintf(stdout, "%s", strUsage.c_str());
strUsage = HelpMessageGroup(_("Commands:"));
strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX"));
strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX"));
strUsage += HelpMessageOpt("in=TXID:VOUT", _("Add input to TX"));
strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N"));
strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT", _("Add raw script output to TX"));
strUsage += HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
_("This command requires JSON registers:") +
_("prevtxs=JSON object") + ", " +
_("privatekeys=JSON object") + ". " +
_("See signrawtransaction docs for format of sighash flags, JSON objects."));
fprintf(stdout, "%s", strUsage.c_str());
strUsage = HelpMessageGroup(_("Register Commands:"));
strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
return true;
}
static void RegisterSetJson(const string& key, const string& rawJson)
{
UniValue val;
if (!val.read(rawJson)) {
string strErr = "Cannot parse JSON for key " + key;
throw runtime_error(strErr);
}
registers[key] = val;
}
static void RegisterSet(const string& strInput)
{
// separate NAME:VALUE in string
size_t pos = strInput.find(':');
if ((pos == string::npos) ||
(pos == 0) ||
(pos == (strInput.size() - 1)))
throw runtime_error("Register input requires NAME:VALUE");
string key = strInput.substr(0, pos);
string valStr = strInput.substr(pos + 1, string::npos);
RegisterSetJson(key, valStr);
}
static void RegisterLoad(const string& strInput)
{
// separate NAME:FILENAME in string
size_t pos = strInput.find(':');
if ((pos == string::npos) ||
(pos == 0) ||
(pos == (strInput.size() - 1)))
throw runtime_error("Register load requires NAME:FILENAME");
string key = strInput.substr(0, pos);
string filename = strInput.substr(pos + 1, string::npos);
FILE* f = fopen(filename.c_str(), "r");
if (!f) {
string strErr = "Cannot open file " + filename;
throw runtime_error(strErr);
}
// load file chunks into one big buffer
string valStr;
while ((!feof(f)) && (!ferror(f))) {
char buf[4096];
int bread = fread(buf, 1, sizeof(buf), f);
if (bread <= 0)
break;
valStr.insert(valStr.size(), buf, bread);
}
if (ferror(f)) {
string strErr = "Error reading file " + filename;
throw runtime_error(strErr);
}
fclose(f);
// evaluate as JSON buffer register
RegisterSetJson(key, valStr);
}
static void MutateTxVersion(CMutableTransaction& tx, const string& cmdVal)
{
int64_t newVersion = atoi64(cmdVal);
if (newVersion < 1 || newVersion > CTransaction::CURRENT_VERSION)
throw runtime_error("Invalid TX version requested");
tx.nVersion = (int)newVersion;
}
static void MutateTxLocktime(CMutableTransaction& tx, const string& cmdVal)
{
int64_t newLocktime = atoi64(cmdVal);
if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
throw runtime_error("Invalid TX locktime requested");
tx.nLockTime = (unsigned int)newLocktime;
}
static void MutateTxAddInput(CMutableTransaction& tx, const string& strInput)
{
// separate TXID:VOUT in string
size_t pos = strInput.find(':');
if ((pos == string::npos) ||
(pos == 0) ||
(pos == (strInput.size() - 1)))
throw runtime_error("TX input missing separator");
// extract and validate TXID
string strTxid = strInput.substr(0, pos);
if ((strTxid.size() != 64) || !IsHex(strTxid))
throw runtime_error("invalid TX input txid");
uint256 txid(strTxid);
static const unsigned int minTxOutSz = 9;
static const unsigned int maxVout = MAX_BLOCK_SIZE / minTxOutSz;
// extract and validate vout
string strVout = strInput.substr(pos + 1, string::npos);
int vout = atoi(strVout);
if ((vout < 0) || (vout > (int)maxVout))
throw runtime_error("invalid TX input vout");
// append to transaction input list
CTxIn txin(txid, vout);
tx.vin.push_back(txin);
}
static void MutateTxAddOutAddr(CMutableTransaction& tx, const string& strInput)
{
// separate VALUE:ADDRESS in string
size_t pos = strInput.find(':');
if ((pos == string::npos) ||
(pos == 0) ||
(pos == (strInput.size() - 1)))
throw runtime_error("TX output missing separator");
// extract and validate VALUE
string strValue = strInput.substr(0, pos);
CAmount value;
if (!ParseMoney(strValue, value))
throw runtime_error("invalid TX output value");
// extract and validate ADDRESS
string strAddr = strInput.substr(pos + 1, string::npos);
CBitcoinAddress addr(strAddr);
if (!addr.IsValid())
throw runtime_error("invalid TX output address");
// build standard output script via GetScriptForDestination()
CScript scriptPubKey = GetScriptForDestination(addr.Get());
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutScript(CMutableTransaction& tx, const string& strInput)
{
// separate VALUE:SCRIPT in string
size_t pos = strInput.find(':');
if ((pos == string::npos) ||
(pos == 0))
throw runtime_error("TX output missing separator");
// extract and validate VALUE
string strValue = strInput.substr(0, pos);
CAmount value;
if (!ParseMoney(strValue, value))
throw runtime_error("invalid TX output value");
// extract and validate script
string strScript = strInput.substr(pos + 1, string::npos);
CScript scriptPubKey = ParseScript(strScript); // throws on err
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxDelInput(CMutableTransaction& tx, const string& strInIdx)
{
// parse requested deletion index
int inIdx = atoi(strInIdx);
if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
string strErr = "Invalid TX input index '" + strInIdx + "'";
throw runtime_error(strErr.c_str());
}
// delete input from transaction
tx.vin.erase(tx.vin.begin() + inIdx);
}
static void MutateTxDelOutput(CMutableTransaction& tx, const string& strOutIdx)
{
// parse requested deletion index
int outIdx = atoi(strOutIdx);
if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
string strErr = "Invalid TX output index '" + strOutIdx + "'";
throw runtime_error(strErr.c_str());
}
// delete output from transaction
tx.vout.erase(tx.vout.begin() + outIdx);
}
static const unsigned int N_SIGHASH_OPTS = 6;
static const struct {
const char* flagStr;
int flags;
} sighashOptions[N_SIGHASH_OPTS] = {
{"ALL", SIGHASH_ALL},
{"NONE", SIGHASH_NONE},
{"SINGLE", SIGHASH_SINGLE},
{"ALL|ANYONECANPAY", SIGHASH_ALL | SIGHASH_ANYONECANPAY},
{"NONE|ANYONECANPAY", SIGHASH_NONE | SIGHASH_ANYONECANPAY},
{"SINGLE|ANYONECANPAY", SIGHASH_SINGLE | SIGHASH_ANYONECANPAY},
};
static bool findSighashFlags(int& flags, const string& flagStr)
{
flags = 0;
for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
if (flagStr == sighashOptions[i].flagStr) {
flags = sighashOptions[i].flags;
return true;
}
}
return false;
}
uint256 ParseHashUO(map<string, UniValue>& o, string strKey)
{
if (!o.count(strKey))
return 0;
return ParseHashUV(o[strKey], strKey);
}
vector<unsigned char> ParseHexUO(map<string, UniValue>& o, string strKey)
{
if (!o.count(strKey)) {
vector<unsigned char> emptyVec;
return emptyVec;
}
return ParseHexUV(o[strKey], strKey);
}
static void MutateTxSign(CMutableTransaction& tx, const string& flagStr)
{
int nHashType = SIGHASH_ALL;
if (flagStr.size() > 0)
if (!findSighashFlags(nHashType, flagStr))
throw runtime_error("unknown sighash flag/sign option");
vector<CTransaction> txVariants;
txVariants.push_back(tx);
// mergedTx will end up with all the signatures; it
// starts as a clone of the raw tx:
CMutableTransaction mergedTx(txVariants[0]);
bool fComplete = true;
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
if (!registers.count("privatekeys"))
throw runtime_error("privatekeys register variable must be set.");
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
UniValue keysObj = registers["privatekeys"];
fGivenKeys = true;
for (unsigned int kidx = 0; kidx < keysObj.count(); kidx++) {
if (!keysObj[kidx].isStr())
throw runtime_error("privatekey not a string");
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
if (!fGood)
throw runtime_error("privatekey not valid");
CKey key = vchSecret.GetKey();
tempKeystore.AddKey(key);
}
// Add previous txouts given in the RPC call:
if (!registers.count("prevtxs"))
throw runtime_error("prevtxs register variable must be set.");
UniValue prevtxsObj = registers["prevtxs"];
{
for (unsigned int previdx = 0; previdx < prevtxsObj.count(); previdx++) {
UniValue prevOut = prevtxsObj[previdx];
if (!prevOut.isObject())
throw runtime_error("expected prevtxs internal object");
map<string, UniValue::VType> types = map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR);
if (!prevOut.checkObject(types))
throw runtime_error("prevtxs internal object typecheck fail");
uint256 txid = ParseHashUV(prevOut["txid"], "txid");
int nOut = atoi(prevOut["vout"].getValStr());
if (nOut < 0)
throw runtime_error("vout must be positive");
vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
CCoinsModifier coins = view.ModifyCoins(txid);
if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n" +
scriptPubKey.ToString();
throw runtime_error(err);
}
if ((unsigned int)nOut >= coins->vout.size())
coins->vout.resize(nOut + 1);
coins->vout[nOut].scriptPubKey = scriptPubKey;
coins->vout[nOut].nValue = 0; // we don't know the actual output value
}
// if redeemScript given and private keys given,
// add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash() &&
prevOut.exists("redeemScript")) {
UniValue v = prevOut["redeemScript"];
vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
const CKeyStore& keystore = tempKeystore;
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
if (!coins || !coins->IsAvailable(txin.prevout.n)) {
fComplete = false;
continue;
}
const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH (const CTransaction& txv, txVariants) {
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i)))
fComplete = false;
}
if (fComplete) {
// do nothing... for now
// perhaps store this for later optional JSON output
}
tx = mergedTx;
}
static void MutateTx(CMutableTransaction& tx, const string& command, const string& commandVal)
{
if (command == "nversion")
MutateTxVersion(tx, commandVal);
else if (command == "locktime")
MutateTxLocktime(tx, commandVal);
else if (command == "delin")
MutateTxDelInput(tx, commandVal);
else if (command == "in")
MutateTxAddInput(tx, commandVal);
else if (command == "delout")
MutateTxDelOutput(tx, commandVal);
else if (command == "outaddr")
MutateTxAddOutAddr(tx, commandVal);
else if (command == "outscript")
MutateTxAddOutScript(tx, commandVal);
else if (command == "sign")
MutateTxSign(tx, commandVal);
else if (command == "load")
RegisterLoad(commandVal);
else if (command == "set")
RegisterSet(commandVal);
else
throw runtime_error("unknown command");
}
static void OutputTxJSON(const CTransaction& tx)
{
UniValue entry(UniValue::VOBJ);
TxToUniv(tx, 0, entry);
string jsonOutput = entry.write(4);
fprintf(stdout, "%s\n", jsonOutput.c_str());
}
static void OutputTxHash(const CTransaction& tx)
{
string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
fprintf(stdout, "%s\n", strHexHash.c_str());
}
static void OutputTxHex(const CTransaction& tx)
{
string strHex = EncodeHexTx(tx);
fprintf(stdout, "%s\n", strHex.c_str());
}
static void OutputTx(const CTransaction& tx)
{
if (GetBoolArg("-json", false))
OutputTxJSON(tx);
else if (GetBoolArg("-txid", false))
OutputTxHash(tx);
else
OutputTxHex(tx);
}
static string readStdin()
{
char buf[4096];
string ret;
while (!feof(stdin)) {
size_t bread = fread(buf, 1, sizeof(buf), stdin);
ret.append(buf, bread);
if (bread < sizeof(buf))
break;
}
if (ferror(stdin))
throw runtime_error("error reading stdin");
boost::algorithm::trim_right(ret);
return ret;
}
static int CommandLineRawTx(int argc, char* argv[])
{
string strPrint;
int nRet = 0;
try {
// Skip switches; Permit common stdin convention "-"
while (argc > 1 && IsSwitchChar(argv[1][0]) &&
(argv[1][1] != 0)) {
argc--;
argv++;
}
CTransaction txDecodeTmp;
int startArg;
if (!fCreateBlank) {
// require at least one param
if (argc < 2)
throw runtime_error("too few parameters");
// param: hex-encoded pure transaction
string strHexTx(argv[1]);
if (strHexTx == "-") // "-" implies standard input
strHexTx = readStdin();
if (!DecodeHexTx(txDecodeTmp, strHexTx))
throw runtime_error("invalid transaction encoding");
startArg = 2;
} else
startArg = 1;
CMutableTransaction tx(txDecodeTmp);
for (int i = startArg; i < argc; i++) {
string arg = argv[i];
string key, value;
size_t eqpos = arg.find('=');
if (eqpos == string::npos)
key = arg;
else {
key = arg.substr(0, eqpos);
value = arg.substr(eqpos + 1);
}
MutateTx(tx, key, value);
}
OutputTx(tx);
}
catch (boost::thread_interrupted) {
throw;
} catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(NULL, "CommandLineRawTx()");
throw;
}
if (strPrint != "") {
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
try {
if (!AppInitRawTx(argc, argv))
return EXIT_FAILURE;
} catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInitRawTx()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(NULL, "AppInitRawTx()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineRawTx(argc, argv);
} catch (std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRawTx()");
} catch (...) {
PrintExceptionContinue(NULL, "CommandLineRawTx()");
}
return ret;
}
| [
"puredev321@gmail.com"
] | puredev321@gmail.com |
9f2c1f002cf39741cc2695d351e36c6f1405dd85 | 18c67c69cc70fc56e76a24e358e6ea241fd782bc | /libopenmpt.mod/openmpt/soundlib/Dlsbank.h | d9c3fde2722c5cf56ee86204967d4652020bd7f1 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bmx-ng/audio.mod | 3882377171e35294e6f24b71562e22c1cda85ef5 | f65767cdc695f4386c5e7e3cdcd7bc0095570eb4 | refs/heads/master | 2023-07-23T13:42:10.196858 | 2023-07-10T07:39:21 | 2023-07-10T07:39:21 | 221,508,885 | 1 | 3 | null | 2023-07-10T07:39:23 | 2019-11-13T16:53:24 | C | UTF-8 | C++ | false | false | 4,877 | h | /*
* DLSBank.h
* ---------
* Purpose: Sound bank loading.
* Notes : Supported sound bank types: DLS (including embedded DLS in MSS & RMI), SF2
* Authors: Olivier Lapicque
* OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#pragma once
#include "openmpt/all/BuildSettings.hpp"
OPENMPT_NAMESPACE_BEGIN
class CSoundFile;
OPENMPT_NAMESPACE_END
#include "Snd_defs.h"
OPENMPT_NAMESPACE_BEGIN
#ifdef MODPLUG_TRACKER
struct DLSREGION
{
uint32 ulLoopStart;
uint32 ulLoopEnd;
uint16 nWaveLink;
uint16 uPercEnv;
uint16 usVolume; // 0..256
uint16 fuOptions; // flags + key group
int16 sFineTune; // +128 = +1 semitone
int16 panning = -1; // -1= unset (DLS), otherwise 0...256
uint8 uKeyMin;
uint8 uKeyMax;
uint8 uUnityNote;
uint8 tuning = 100;
constexpr bool IsDummy() const noexcept { return uKeyMin == 0xFF || nWaveLink == Util::MaxValueOfType(nWaveLink); }
};
struct DLSENVELOPE
{
// Volume Envelope
uint16 wVolAttack; // Attack Time: 0-1000, 1 = 20ms (1/50s) -> [0-20s]
uint16 wVolDecay; // Decay Time: 0-1000, 1 = 20ms (1/50s) -> [0-20s]
uint16 wVolRelease; // Release Time: 0-1000, 1 = 20ms (1/50s) -> [0-20s]
uint8 nVolSustainLevel; // Sustain Level: 0-128, 128=100%
uint8 nDefPan; // Default Pan
};
// Special Bank bits
#define F_INSTRUMENT_DRUMS 0x80000000
struct DLSINSTRUMENT
{
uint32 ulBank = 0, ulInstrument = 0;
uint32 nMelodicEnv = 0;
std::vector<DLSREGION> Regions;
char szName[32];
// SF2 stuff (DO NOT USE! -> used internally by the SF2 loader)
uint16 wPresetBagNdx = 0, wPresetBagNum = 0;
};
struct DLSSAMPLEEX
{
char szName[20];
uint32 dwLen;
uint32 dwStartloop;
uint32 dwEndloop;
uint32 dwSampleRate;
uint8 byOriginalPitch;
int8 chPitchCorrection;
bool compressed = false;
};
#define SOUNDBANK_TYPE_INVALID 0
#define SOUNDBANK_TYPE_DLS 0x01
#define SOUNDBANK_TYPE_SF2 0x02
struct SOUNDBANKINFO
{
std::string szBankName,
szCopyRight,
szComments,
szEngineer,
szSoftware, // ISFT: Software
szDescription; // ISBJ: Subject
};
struct IFFCHUNK;
struct SF2LoaderInfo;
class CDLSBank
{
protected:
SOUNDBANKINFO m_BankInfo;
mpt::PathString m_szFileName;
size_t m_dwWavePoolOffset;
uint32 m_nType;
// DLS Information
uint32 m_nMaxWaveLink;
uint32 m_sf2version = 0;
std::vector<size_t> m_WaveForms;
std::vector<DLSINSTRUMENT> m_Instruments;
std::vector<DLSSAMPLEEX> m_SamplesEx;
std::vector<DLSENVELOPE> m_Envelopes;
public:
CDLSBank();
bool operator==(const CDLSBank &other) const noexcept { return !mpt::PathString::CompareNoCase(m_szFileName, other.m_szFileName); }
static bool IsDLSBank(const mpt::PathString &filename);
static uint32 MakeMelodicCode(uint32 bank, uint32 instr) { return ((bank << 16) | (instr));}
static uint32 MakeDrumCode(uint32 rgn, uint32 instr) { return (0x80000000 | (rgn << 16) | (instr));}
public:
bool Open(const mpt::PathString &filename);
bool Open(FileReader file);
mpt::PathString GetFileName() const { return m_szFileName; }
uint32 GetBankType() const { return m_nType; }
const SOUNDBANKINFO &GetBankInfo() const { return m_BankInfo; }
public:
uint32 GetNumInstruments() const { return static_cast<uint32>(m_Instruments.size()); }
uint32 GetNumSamples() const { return static_cast<uint32>(m_WaveForms.size()); }
const DLSINSTRUMENT *GetInstrument(uint32 iIns) const { return iIns < m_Instruments.size() ? &m_Instruments[iIns] : nullptr; }
const DLSINSTRUMENT *FindInstrument(bool isDrum, uint32 bank = 0xFF, uint32 program = 0xFF, uint32 key = 0xFF, uint32 *pInsNo = nullptr) const;
bool FindAndExtract(CSoundFile &sndFile, const INSTRUMENTINDEX ins, const bool isDrum) const;
uint32 GetRegionFromKey(uint32 nIns, uint32 nKey) const;
bool ExtractWaveForm(uint32 nIns, uint32 nRgn, std::vector<uint8> &waveData, uint32 &length) const;
bool ExtractSample(CSoundFile &sndFile, SAMPLEINDEX nSample, uint32 nIns, uint32 nRgn, int transpose = 0) const;
bool ExtractInstrument(CSoundFile &sndFile, INSTRUMENTINDEX nInstr, uint32 nIns, uint32 nDrumRgn) const;
const char *GetRegionName(uint32 nIns, uint32 nRgn) const;
uint16 GetPanning(uint32 ins, uint32 region) const;
// Internal Loader Functions
protected:
bool UpdateInstrumentDefinition(DLSINSTRUMENT *pDlsIns, FileReader chunk);
bool UpdateSF2PresetData(SF2LoaderInfo &sf2info, const IFFCHUNK &header, FileReader &chunk);
bool ConvertSF2ToDLS(SF2LoaderInfo &sf2info);
public:
// DLS Unit conversion
static int32 DLS32BitTimeCentsToMilliseconds(int32 lTimeCents);
static int32 DLS32BitRelativeGainToLinear(int32 lCentibels); // 0dB = 0x10000
static int32 DLS32BitRelativeLinearToGain(int32 lGain); // 0dB = 0x10000
static int32 DLSMidiVolumeToLinear(uint32 nMidiVolume); // [0-127] -> [0-0x10000]
};
#endif // MODPLUG_TRACKER
OPENMPT_NAMESPACE_END
| [
"woollybah@gmail.com"
] | woollybah@gmail.com |
fc256aacd8eb879e0baab09e12fc1e38cb0bf741 | 6019a4be65f55703c6960c31533c79a485d6144e | /STO_login/database/databasehandle.h | b33d773aab041c88b4482a3147fe918f0fef2257 | [] | no_license | yqzzj/sto | 8c6ee4d067ed72dcf9de49fdf88a6744855aa204 | 9d92704a3c6aa122ada5433cafb85560856f1ee9 | refs/heads/master | 2020-04-17T22:34:48.691440 | 2016-08-31T13:40:49 | 2016-08-31T13:40:49 | 66,055,306 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,746 | h | #ifndef DATABASEHANDLE_H
#define DATABASEHANDLE_H
#include <QSqlError>
#include <QMutex>
#include "database/DataBase.h"
class DatabaseHandle : public QObject
{
Q_OBJECT
public:
explicit DatabaseHandle(QObject *parent = 0);
static bool createDBConnection();
static void closeDBConnection();
static QString &cat_str_sql(const QString &in);
static QString execDBSql(const QString &sqlStr, const int tableFlag);
//!注册用户
//新注册用户将数据插入表格,手动分配UserID
static QString insert_UserManagementTable(const int UserID,
const QString &UserName,
const QString &UserPassword,
const QString &MobilePhoneNum,
const QString &EmailNum,
const QString &LoginFlag,
const QString &LoginIP,
const QString &LoginMAC,
const QString &UserLevel,
const QString &UsedTimes,
const QString &RegistrationTime);
//新注册用户将数据插入表格,自递增分配UserID
static QString insert_UserManagementTable_Auto(const QString &UserName,
const QString &UserPassword,
const QString &MobilePhoneNum,
const QString &EmailNum,
const QString &LoginFlag,
const QString &LoginIP,
const QString &LoginMAC,
const QString &UserLevel,
const QString &UsedTimes,
const QString &RegistrationTime);
//查询用户是否已被注册
static int inquireUserNameExist(const QString &userName);
//查询用户密码
static QString inquireUserPassword(const QString &userName);
//查询用户ID
static QString inquireUserID(const QString &userName);
//查询用户是否已经登陆
static QString inquireLoginFlag(const QString &userName);
//更新用户登陆标示,上线1\下线0
static bool updateLoginFlag(const QString &userName,
const QString &loginFlag);
//查询手机号是否已被注册
static int inquireMobilePhoneNumExist(const QString &phone);
//查询邮箱是否已被注册
static int inquireEmailNumExist(const QString &email);
signals:
public slots:
};
#endif // DATABASEHANDLE_H
| [
"632533979@qq.com"
] | 632533979@qq.com |
4b5b5ced4c4f65710448fe4830363591baf08789 | 78bae575fe525533c5bb0f6ac0c8075b11a4271d | /338 Counting Bits.cpp | e0d79a173fd2ac9a00a0fbc4d3e741ffc01075b6 | [] | no_license | Shubhamrawat5/LeetCode | 23eba3bfd3a03451d0f04014cb47de12504b6399 | 939b5f33ad5aef78df761e930d6ff873324eb4bb | refs/heads/master | 2023-07-18T00:01:21.140280 | 2021-08-21T18:51:27 | 2021-08-21T18:51:27 | 280,733,721 | 1 | 3 | null | 2020-10-21T11:18:24 | 2020-07-18T20:26:20 | C++ | UTF-8 | C++ | false | false | 857 | cpp | #include<iostream>
#include<vector>
using namespace std;
vector <int> countBits(int num)
{
vector <int> ans;
if(num<0) return ans;
ans.push_back(0);
int two; //for power of 2s
int i;
/*Logic:- using dynamic programming
generating a table from 0 to n and for every index i , use previous values available in table.
find the 2s values like 1,2,4,8,16,32 as it has always 1 bits, now for number like 10 is 8+2 so number 8 has bits number 2 has 1 bits which we already found in table
*/
for(i=1;i<=num;++i)
{
if((i & (i-1)) ==0) two=i; //to find and update power of 2s
ans.push_back(ans[i-two]+1); //now use last power of 2s no. of bit + remaining subtracted no. of bits by table
}
return ans;
}
int main()
{
int n=10;
vector<int> v=countBits(n);
vector<int>::iterator it;
for(it=v.begin();it!=v.end();++it)
cout<<(*it)<<" ";
} | [
"sr856161@gmail.com"
] | sr856161@gmail.com |
07982da1db1ceed3283f07af553d2fe207378cb3 | 5c26ce906f0bd186ccbddf0b8406eb32abf762c9 | /Course1_DivideAndConquer/CountInversion.cpp | 8536a4445056405255655360a5fba5b31c943a42 | [] | no_license | hchaozhe/Algorithms_course_codes | 41bd9808b9949e3305ab351ec6a01c9391f04b02 | 769b7c3ca65a05da4014ed7c18b56e9ac007433b | refs/heads/master | 2023-04-05T03:36:59.568393 | 2021-04-06T03:44:22 | 2021-04-06T03:44:22 | 346,228,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,645 | cpp | #include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>
using namespace std;
// #define DEBUGLL
#define DEBUGSS
void PlotHelp(vector<int> &num, int from, int to, long long int inv){
for (int i = from; i<=to;i++){
cout << num[i] << " ";
}
cout<< " with inversion " << inv << endl;
}
void PlotHelp2(int from, int to, long long int inv){
cout<< " from " << from <<" to " << to <<" inversion " << inv << endl;
}
long long int sort_and_count(vector<int> &v, int from, int to){
if (from == to){
return 0;
}
long long int inversion_count = 0;
int n = to - from+1; // size of the sorted section
vector<int> sorted(n,0);
// devide
int from_left = from;
int to_left = (from + to)/2;
int from_right = to_left+1;
int to_right = to;
long long int inversion_left = 0;
long long int inversion_right = 0;
inversion_left = sort_and_count(v,from_left,to_left);
inversion_right = sort_and_count(v,from_right,to_right);
inversion_count = inversion_right+ inversion_left;
#ifdef DEBUGLL
cout << "left: " ;
PlotHelp(v,from_left,to_left, inversion_left);
cout << "right: " ;
PlotHelp(v,from_right,to_right, inversion_right);
#endif
#ifdef DEBUGSS
if (n>=5000){
PlotHelp2(from_left,to_left, inversion_left);
PlotHelp2(from_right,to_right, inversion_right);
}
#endif
// merge sort
int l=from_left;
int r=from_right;
int left_num = 0;
int right_num = 0;
for(int i =0;i<n;i++){
if (l<=to_left && r<=to_right){
// there are still left
left_num = v[l];
right_num = v[r];
if (left_num<=right_num){
// no inversion
sorted[i] = left_num;
l++;
}else{
// there are inversions
sorted[i] = right_num;
inversion_count = inversion_count +
( (long long int) (to_left - l + 1) );
r++;
}
}else if(r<=to_right){
// left is all gone, no more inversion
sorted[i] = v[r];
r++;
}else{
// right is all gone, no more inversion
sorted[i] = v[l];
l++;
}
}
// after sort and merged, override v
for (int i = 0;i<n;i++){
v[from + i]=sorted[i];
}
#ifdef DEBUGLL
// cout << "merged: " ;
// PlotHelp(v,from,to, inversion_count);
#endif
#ifdef DEBUGSS
if (n>=5000){
PlotHelp2(from,to, inversion_count);
}
#endif
return inversion_count;
}
int main(){
//vector<int> numbers{ 9,8,7,6,5,4,3,2,1,0};
vector<int> numbers;
ifstream File;
cout<< INT_MAX << endl;
File.open("IntegerArray.txt");
int x;
if (File.is_open()){
while(File >> x )
{
numbers.push_back(x);
}
File.close();
for (int i =0;i<numbers.size();i=i+1000){
cout << i+1 << ": " << numbers[i] <<endl;
}
cout << numbers.size() << ": " << numbers[numbers.size()-1] <<endl;
}else{
cout << "cannot open file" << endl;
}
long long int inversion = 0;
cout << inversion <<endl;
int from = 0;
// int to = 4999;
// int from = 0;
int to = numbers.size()-1;
inversion = sort_and_count(numbers, from, to);
cout<< "Final result: ";
// cout<< "Final result: "; // my answer is 2407905288
#ifdef DEBUGLL
PlotHelp(numbers, from, to, inversion);
#endif
#ifdef DEBUGSS
PlotHelp2(from, to, inversion);
#endif
return 0;
} | [
"hchaozhe@umich.edu"
] | hchaozhe@umich.edu |
061addf7085798b5c0f061745e56459234128649 | 87cfed8101402f0991cd2b2412a5f69da90a955e | /daq/daq/src/mwnidaq/nid2a.h | e1814f9caacff9fbb3e761b19496e52810d15686 | [] | no_license | dedan/clock_stimulus | d94a52c650e9ccd95dae4fef7c61bb13fdcbd027 | 890ec4f7a205c8f7088c1ebe0de55e035998df9d | refs/heads/master | 2020-05-20T03:21:23.873840 | 2010-06-22T12:13:39 | 2010-06-22T12:13:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,821 | h | // Copyright 1998-2003 The MathWorks, Inc.
// $Revision: 1.3.4.6 $ $Date: 2003/12/22 00:48:14 $
// nid2a.h: Definition of the nid2a class
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_NID2A_H__D0C329D5_E0FF_11D1_A21F_00A024E7DC56__INCLUDED_)
#define AFX_NID2A_H__D0C329D5_E0FF_11D1_A21F_00A024E7DC56__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#pragma warning(disable:4996) // no warnings: CComModule::UpdateRegistryClass was declared deprecated
#include "mwnidaq.h"
#include "resource.h" // main symbols
#include "daqtypes.h"
#include "daqmex.h"
//#include "evtmsg.h"
#include "AdaptorKit.h"
#include "nidisp.h"
#include "cirbuf.h"
#include "messagew.h"
/////////////////////////////////////////////////////////////////////////////
// nid2a
class ATL_NO_VTABLE Cnid2a :
public CmwDevice,
public ImwOutput,
public CComCoClass<Cnid2a,&CLSID_Cnid2a>,
public CniDisp
{
public:
unsigned long _buffersDone;
short * _chanList;
double *_chanRange[2];
ShortProp _clockSrc;
//ShortProp _whichClock;
TRemoteProp<long> _timeBase;
TRemoteProp<long> _interval;
//ShortProp _delayMode;
std::vector<double> _defaultValues;
HWND _hWnd;
long _nChannels;
CEnumProp _outOfDataMode;
IntProp _refSource;
DoubleProp _refVoltage;
bool _isConfig;
bool _running;
bool _underrun;
TCachedProp<double> _sampleRate;
__int64 _samplesOutput;
__int64 _samplesPut;
IntProp _timeOut;
IntProp _triggerType;
short _updateMode;
DoubleProp _updateRate;
ShortProp _waveformGroup;
short * _polarityList;
//short * _buffer;
long _EngineBufferSamples;
IntProp _xferMode;
bool _LastBufferLoaded;
long _ptsTfr;
long _fifoSize;
enum CHANPROPS
{
HWCHAN=1,
OUTPUTRANGE,
DEFAULT_VALUE
};
CComPtr<IPropRoot> _defaultChannelValueIProp;
static MessageWindow *_Nid2aWnd;
long _triggersPosted;
public:
HRESULT SetNIDAQError(short status,const IID& iid = IID_ImwOutput)
{ return status!=0 ? Error(status,iid) : S_OK;};
Cnid2a();
~Cnid2a();
int ReallocCGLists();
template <class PT>
CComPtr<IProp> RegisterProperty(LPWSTR name, PT &prop)
{
return prop.Attach(_EnginePropRoot,name,USER_VAL(prop));
}
void SetupChannels();
int SetWaveformGenMsgParams(int mode);
short GetID() { return _id; }
long Channels() { return _nChannels; }
short *ChanList() { return _chanList; }
void setRunning(bool running) { _running = running; }
bool Running() { return _running; }
long GetFifoSizePoints() {return _fifoSize;}
__int64 SamplesOutput() { return _samplesOutput; }
void UpdateSamplesOutput(unsigned long ItersDone,unsigned long PointsDone)
{
_samplesOutput=((__int64)((unsigned __int64)ItersDone*GetBufferSizePoints())+PointsDone-GetFifoSizePoints())/_nChannels;
}
void SamplesOutput(__int64 s) { _samplesOutput=s; }
bool Underrun() { return _underrun; }
long PointsPerSecond() { return (long)(_sampleRate*_nChannels);}
void CleanUp();
HRESULT Initialize();
virtual HRESULT Configure();
int SetOutputRangeDefault(short polarity);
int SetOutputRange( VARIANT*, short);
int LoadOutputRanges();
void SetAllPolarities(short polarity);
int SetXferMode();
int TriggerSetup();
long PtsTfr() { return _ptsTfr; }
int SetDaqHwInfo();
virtual void LoadData()=0; // load/update data in the device buffer
virtual void SyncAndLoadData()=0; // take care of all dynamic stuff
HRESULT Open(IDaqEngine * Interface,int _ID,DevCaps* DeviceCaps);
int SetConversionOffset(short polarity);
BEGIN_COM_MAP(Cnid2a)
COM_INTERFACE_ENTRY(ImwOutput)
COM_INTERFACE_ENTRY(ImwDevice)
COM_INTERFACE_ENTRY_CHAIN(CniDisp)
END_COM_MAP()
//DECLARE_NOT_AGGREGATABLE(nid2a)
// Remove the comment from the line above if you don't want your object to
// support aggregation.
//DECLARE_REGISTRY_RESOURCEID(IDR_nid2a)
DECLARE_REGISTRY( Cnid2a, "mwnidaq.output.1", "mwnidaq.output", IDS_NID2A_DESC, THREADFLAGS_BOTH )
HRESULT InternalStart();
// IOutput
public:
STDMETHOD(GetStatus)(hyper*, BOOL*);
STDMETHOD(PutSingleValues)(VARIANT*);
STDMETHOD(Start)();
STDMETHOD(Stop)();
STDMETHOD(Trigger)();
STDMETHOD(TranslateError)(VARIANT * eCode, VARIANT *retVal);
STDMETHOD(SetChannelProperty)(long User,NESTABLEPROP * pChan, VARIANT * NewValue);
STDMETHOD(SetProperty)(long User, VARIANT *newVal);
STDMETHOD(ChildChange)(DWORD typeofchange, NESTABLEPROP *pChan);
// functions that depend on the data type
virtual void InitBuffering(int Points)=0;
virtual long GetBufferSizePoints()=0;
virtual void *GetBufferPtr()=0;
virtual HRESULT DeviceSpecificSetup() { return S_OK; }
private:
};
template <typename NativeDataType>
class ATL_NO_VTABLE Tnid2a :public Cnid2a
{
public:
typedef TCircBuffer<NativeDataType> CIRCBUFFER;
CIRCBUFFER _CircBuff;
std::vector<NativeDataType> StoppedValue;
void InitBuffering(int Points)
{
_CircBuff.Initialize(Points);
StoppedValue.resize(_nChannels);
}
long GetBufferSizePoints()
{
return _CircBuff.GetBufferSize();
}
void *GetBufferPtr()
{
return _CircBuff.GetPtr();
}
virtual void LoadData(); // load/update data in the device buffer
virtual void SyncAndLoadData(); // take care of all dynamic stuff
};
//extern template class Tnid2a<short>;
//extern template class Tnid2a<long>;
class ATL_NO_VTABLE CESeriesOutput :public Tnid2a<short>
{
public:
// STDMETHOD(Trigger)();
// virtual void ProcessSamples(int samples);
};
class ATL_NO_VTABLE CDSAOutput :public Tnid2a<long>
{
public:
// STDMETHOD(Trigger)();
// virtual void ProcessSamples(int samples);
HRESULT DeviceSpecificSetup();
STDMETHOD(PutSingleValues)(VARIANT*) { return E_NOTIMPL;}
STDMETHOD(SetProperty)(long User, VARIANT *newVal);
};
#endif // !defined(AFX_NID2A_H__D0C329D5_E0FF_11D1_A21F_00A024E7DC56__INCLUDED_)
| [
"stephan.gabler@gmail.com"
] | stephan.gabler@gmail.com |
e1346509cdb529f91bce2cf37b99b799d8d05cf7 | 3bedf49f6d6e95c45779541aae4e518299ab68a7 | /Geant4-Example5-NeutronInteractions/main/src/MyDetectorConstruction.cpp | fb9c90bda2657fdaff214789e20ce17c1844a343 | [] | no_license | DrWLucky/GEANT4-Example5-NeutronInteractions | 8df90bd7a12a197356da4c13b81a774964face55 | cb44e6534c436dd210097ab20d4bb1e1493db638 | refs/heads/master | 2022-01-12T19:55:02.094010 | 2019-07-13T12:53:08 | 2019-07-13T12:53:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,467 | cpp | #include "MyDetectorConstruction.hh"
#include "MyDetectorMessenger.hh"
#include "G4VPhysicalVolume.hh"
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4Box.hh"
#include "G4Trd.hh"
#include "G4Tubs.hh"
#include "G4NistManager.hh"
#include "G4VisAttributes.hh"
#include "G4RunManager.hh"
#include "G4RotationMatrix.hh"
MyDetectorConstruction::MyDetectorConstruction()
:
G4VUserDetectorConstruction(),
halfLabSize(G4ThreeVector(30*cm, 30*cm, 30*cm))
{
myDetectorMessenger = new MyDetectorMessenger(this);
SetActiveRotationAxisAngle(G4ThreeVector(0, 1, 0), 5*deg);
}
MyDetectorConstruction::~MyDetectorConstruction()
{
delete myDetectorMessenger;
}
G4VPhysicalVolume* MyDetectorConstruction::Construct()
{
DefineMaterials();
return ConstructDetector();
}
void MyDetectorConstruction::DefineMaterials()
{
G4NistManager *nist = G4NistManager::Instance();
G4Material *vacuum = nist->FindOrBuildMaterial("G4_Galactic");
G4Material *air = nist->FindOrBuildMaterial("G4_AIR");
G4Material *G4H2Oliquid = nist->FindOrBuildMaterial("G4_WATER");
G4Material *G4H2Osteam = nist->FindOrBuildMaterial("G4_WATER_VAPOR");
G4Material *G4Pb = nist->FindOrBuildMaterial("G4_Pb");
G4Material *G4Concrete = nist->FindOrBuildMaterial("G4_CONCRETE");
G4Material *skin = nist->FindOrBuildMaterial("G4_SKIN_ICRP");
G4Material *softTissue = nist->FindOrBuildMaterial("G4_TISSUE_SOFT_ICRP");
G4Material *muscle = nist->FindOrBuildMaterial("G4_MUSCLE_WITH_SUCROSE");
G4Material *bone = nist->FindOrBuildMaterial("G4_BONE_COMPACT_ICRU");
G4String name, symbol;
G4double abundance, density, temperature, pressure;
G4double a; // mass of a mole
G4double z; // atomic number (number of protons);
G4int components, nucleons, numberOfIsotopes, numberOfAtoms, fractionmass;
G4Material *Al = new G4Material("Aluminium", z=13, a=26.98*g/mole, density=2.7*g/cm3);
G4Material *Pb = new G4Material("Lead", z=82, a= 207.19*g/mole, density= 11.35*g/cm3);
G4Material *Ti = new G4Material("Titanium", z=22, a=47.867*g/mole, density=4.54*g/cm3);
G4Element *Cs = new G4Element("Cesium", symbol="Cs", z=55, a=132.9*g/mole);
G4Element *I = new G4Element("Iodine", symbol="I", z=53, a=126.9*g/mole);
G4Material *CsI = new G4Material("CsI", density=4.51*g/cm3, components=2);
CsI->AddElement(I, .5);
CsI->AddElement(Cs, .5);
// graphite
G4Isotope* C12isotope = new G4Isotope("C12", z=6, nucleons=12);
G4Element* C12element = new G4Element("Graphite","C12", components=1);
C12element->AddIsotope(C12isotope, 100.*perCent);
G4Material* graphite = new G4Material("graphite",
density=2.27*g/cm3,
components=1,
kStateSolid,
temperature=293*kelvin,
pressure=1*atmosphere);
graphite->AddElement(C12element, numberOfAtoms=1);
// pressurized water
G4Element *H = new G4Element("Hydrogen","H", z=1, a=1.0079*g/mole);
G4Element *O = new G4Element("Oxygen","O", z=8, a=16.00*g/mole);
G4Material *H2Opressurised = new G4Material("pressurised water",
density=1.000*g/cm3,
components=2,
kStateLiquid,
temperature=593*kelvin,
pressure=150*bar);
H2Opressurised->AddElement(H, numberOfAtoms=2);
H2Opressurised->AddElement(O, numberOfAtoms=1);
H2Opressurised->GetIonisation()->SetMeanExcitationEnergy(78.0*eV);
// heavy water
G4Isotope* Deuteron = new G4Isotope("Deuteron", z=1, nucleons=2);
G4Element* Deuterium = new G4Element("Deuterium", "Deuterium", numberOfIsotopes=1);
Deuterium->AddIsotope(Deuteron, 100*perCent);
G4Material* D2O = new G4Material("heavy water",
density=1.11*g/cm3,
components=2,
kStateLiquid,
temperature=293.15*kelvin,
pressure=1*atmosphere);
D2O->AddElement(Deuterium, numberOfAtoms=2);
D2O->AddElement(O, numberOfAtoms=1);
G4Isotope *U5 = new G4Isotope(name="U235", z=92, nucleons=235, a=235.01*g/mole);
G4Isotope *U8 = new G4Isotope(name="U238", z=92, nucleons=238, a=238.03*g/mole);
G4Element *UraniumElementEnriched10perCent =
new G4Element(name="10% enriched Uranium", symbol="U", components=2);
UraniumElementEnriched10perCent->AddIsotope(U5, abundance=90.*perCent);
UraniumElementEnriched10perCent->AddIsotope(U8, abundance=10.*perCent);
G4Element *UraniumElementEnriched20perCent =
new G4Element(name="20% enriched Uranium", symbol="U", components=2);
UraniumElementEnriched20perCent->AddIsotope(U5, abundance=80*perCent);
UraniumElementEnriched20perCent->AddIsotope(U8, abundance=20*perCent);
G4Material *UraniumMaterialEnriched10perCent =
new G4Material(name="10% enriched Uranium",
density=18.95*g/cm3, // verify this density!!
components=1);
UraniumMaterialEnriched10perCent->AddElement(UraniumElementEnriched10perCent, fractionmass=1);
G4Material *UraniumMaterialEnriched20perCent =
new G4Material(name="20% enriched Uranium",
density=19.050*g/cm3, // from http://geant4.in2p3.fr/2007/prog/GiovanniSantin/GSantin_Geant4_Paris07_Materials_v08.pdf
components=1,
kStateSolid);
UraniumMaterialEnriched20perCent->AddElement(UraniumElementEnriched20perCent, fractionmass=1);
G4Element *F = new G4Element("Fluorine", "F", z=9., a=18.998*g/mole);
G4Material *UraniumHexaFluoride = new G4Material("Uranium hexafluoride",
density=5.09*g/cm3,
components=2,
kStateGas,
temperature=640*kelvin,
pressure=1.5e7*pascal);
UraniumHexaFluoride->AddElement(F, 6);
UraniumHexaFluoride->AddElement(UraniumElementEnriched10perCent, 1); // UF_6
// Prevent changing materials to default values if they were adjusted at run time:
if (labMaterial == nullptr)
labMaterial = H2Opressurised;
if (targetMaterial == nullptr)
targetMaterial = UraniumMaterialEnriched10perCent;
if (shieldMaterial == nullptr)
shieldMaterial = D2O; // i.e. Heavy Water
// shieldMaterial = G4Concrete;
}
G4VPhysicalVolume* MyDetectorConstruction::ConstructDetector()
{
G4bool checkOverlaps = true;
G4double opacity = 0.4;
G4VisAttributes* invisible = new G4VisAttributes(G4Colour(1, 1, 1));
invisible->SetVisibility(false);
G4VisAttributes *orange = new G4VisAttributes(G4Colour(1, 0.65, 0, opacity));
orange->SetVisibility(true);
orange->SetForceWireframe(true); // Whichever is last overwrites the previous one!
orange->SetForceSolid(true); // Whichever is last overwrites the previous one!
G4VisAttributes *yellow = new G4VisAttributes(G4Colour(1, 1, 0, opacity));
yellow->SetVisibility(true);
yellow->SetForceSolid(true);
G4VisAttributes *brown = new G4VisAttributes(G4Colour(0.71, 0.4, 0.11, opacity));
brown->SetVisibility(true);
brown->SetForceSolid(true);
G4VisAttributes *green = new G4VisAttributes(G4Colour(0, 1, 0, opacity));
green->SetVisibility(true);
green->SetForceSolid(true);
solidLab = new G4Box("Lab", // name
halfLabSize.x(), halfLabSize.y(), halfLabSize.z());
logicalLab = new G4LogicalVolume(solidLab,
labMaterial,
"Lab"); //name
physicalLab = new G4PVPlacement(nullptr, //no rotation
G4ThreeVector(), //at (0,0,0)
logicalLab, //its logical volume
"Lab", //its name
nullptr, //its mother volume
false, //no boolean operation
0); //copy number
// logicalLab->SetVisAttributes(invisible);
G4double halfLengthX1 = 13*cm, halfLengthX2 = 7*cm;
G4double halfLengthY1 = 8*cm, halfLengthY2 = 14*cm;
G4double halfLengthZ = 5*cm;
solidTarget = new G4Trd("Target",
halfLengthX1, halfLengthX2,
halfLengthY1, halfLengthY2,
halfLengthZ);
logicalTarget = new G4LogicalVolume(solidTarget,
targetMaterial,
"Target");
G4RotationMatrix *rotationAxisAngle = new G4RotationMatrix(rotationAxis, rotationAngle);
new G4PVPlacement(rotationAxisAngle, // rotation
G4ThreeVector(0, 0, 15*cm), // at (x,y,z)
logicalTarget, // logical volume
"Target", // name
logicalLab, // logical mother volume
false, // no boolean operations
0, // copy number
checkOverlaps); // checking overlaps
logicalTarget->SetVisAttributes(yellow);
if (shieldOn)
{
G4double innerRadius = 0, outerRadius = 12*cm;
G4double angleMin = 0, angleMax = 360*deg;
solidShield = new G4Tubs("Shield",
innerRadius, outerRadius,
shieldThickness,
angleMin, angleMax);
logicalShield = new G4LogicalVolume(solidShield,
shieldMaterial,
"Shield",
0, 0, 0);
new G4PVPlacement(nullptr, // no rotation
G4ThreeVector(0, 0, -11*cm), // at (x,y,z)
logicalShield, // its logical volume
"Shield", // its name
logicalLab, // logical mother volume
false, // no boolean operations
0, // copy number
checkOverlaps); // checking overlaps
logicalShield->SetVisAttributes(brown);
}
return physicalLab;
}
void MyDetectorConstruction::SetLabMaterial(const G4String& labMaterial)
{
G4Material *ptrToMaterial = G4NistManager::Instance()->FindOrBuildMaterial(labMaterial);
if (ptrToMaterial)
{
this->labMaterial = ptrToMaterial;
if (logicalLab)
{
logicalLab->SetMaterial(this->labMaterial);
G4RunManager::GetRunManager()->PhysicsHasBeenModified();
G4cout << "Lab material changed to: " << GetLabMaterial() << G4endl;
}
}
else
{
G4cerr << "Material not found" << G4endl;
}
}
void MyDetectorConstruction::SetTargetMaterial(const G4String& targetMaterial)
{
G4Material *ptrToMaterial = G4NistManager::Instance()->FindOrBuildMaterial(targetMaterial);
if (ptrToMaterial)
{
this->targetMaterial = ptrToMaterial;
if (logicalTarget)
{
logicalTarget->SetMaterial(this->targetMaterial);
G4RunManager::GetRunManager()->PhysicsHasBeenModified();
G4cout << "Target material changed to: " << GetTargetMaterial() << G4endl;
}
}
else
{
G4cerr << "Material not found" << G4endl;
}
}
void MyDetectorConstruction::SetShieldMaterial(const G4String& shieldMaterial)
{
G4Material *ptrToMaterial = G4NistManager::Instance()->FindOrBuildMaterial(shieldMaterial);
if (ptrToMaterial)
{
this->shieldMaterial = ptrToMaterial;
if (logicalShield)
{
logicalShield->SetMaterial(this->shieldMaterial);
G4RunManager::GetRunManager()->PhysicsHasBeenModified();
G4cout << "Shield material changed to: " << GetShieldMaterial() << G4endl;
}
}
else
{
G4cerr << "Material not found" << G4endl;
}
}
void MyDetectorConstruction::SetShieldOn(G4bool shieldOn)
{
this->shieldOn = shieldOn;
G4RunManager::GetRunManager()->ReinitializeGeometry();
}
void MyDetectorConstruction::SetShieldThickness(G4double shieldThickness)
{
this->shieldThickness = shieldThickness;
G4RunManager::GetRunManager()->ReinitializeGeometry();
}
void MyDetectorConstruction::SetActiveRotationAxisAngle(G4ThreeVector rotationAxis, G4double rotationAngle)
{
// Force this to be an active rather than a passive rotation
this->rotationAxis = -rotationAxis;
this->rotationAngle = rotationAngle;
// Rotation effective immediately; removes beam:
// G4RunManager::GetRunManager()->DefineWorldVolume(Construct());
// Rotation takes effect upon: /run/beamOn
G4RunManager::GetRunManager()->ReinitializeGeometry();
}
| [
"mariuszjozefhoppe@yahoo.com.au"
] | mariuszjozefhoppe@yahoo.com.au |
a864ce1600476a37d3cd5fcb0057fde41f67338a | 9a3f8c3d4afe784a34ada757b8c6cd939cac701d | /leetSeparateDigitsInArray.cpp | b2a3868c886324e1729dde67ebfd8e1082685963 | [] | no_license | madhav-bits/Coding_Practice | 62035a6828f47221b14b1d2a906feae35d3d81a8 | f08d6403878ecafa83b3433dd7a917835b4f1e9e | refs/heads/master | 2023-08-17T04:58:05.113256 | 2023-08-17T02:00:53 | 2023-08-17T02:00:53 | 106,217,648 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,511 | cpp | /*
*
//******************************************************2553. Separate the Digits in an Array.***********************************************
https://leetcode.com/problems/separate-the-digits-in-an-array/
*******************************************************************TEST CASES:************************************************************
//These are the examples I had created, tweaked and worked on.
[13,25,83,77]
[7,1,3,9]
[3,13,20,3400]
// Time Complexity: O(n).
// Space Complexity: O(n).
//********************************************************THIS IS LEET ACCEPTED CODE.***************************************************
*/
//************************************************************Solution 1:************************************************************
//*****************************************************THIS IS LEET ACCEPTED CODE.***********************************************
// Time Complexity: O(n).
// Space Complexity: O(n).
// This algorithm is iteration based. We get the digits of each number in reverse order, we do it for all nums in the array. We reverse the whole res array to get digits original order and return it.
class Solution {
public:
vector<int> separateDigits(vector<int>& v) {
vector<int>res;
for(int i=v.size()-1;i>=0;i--) {
while(v[i]) {
res.push_back(v[i]%10);
v[i]/=10;
}
}
reverse(res.begin(), res.end());
return res;
}
};
| [
"kasamsaimadhavk@gmail.com"
] | kasamsaimadhavk@gmail.com |
c92cd0f8fdb50bce619d1e37ff78e17520dc8766 | b6d0b239e844d1ac0b0297850aee4b3990d2fd27 | /nulldc/plugins/ImgReader/ImgReader.cpp | 953fd5e7b5869d62ae9d222c8f207a648bc51ab8 | [] | no_license | segafan/nulldcsme | 8bffa0db02d61bb5b64b2685fa9e4d0720d544d1 | b50615b26dbe951e9f63c4c4e90bea3bba554f02 | refs/heads/master | 2020-06-01T03:59:16.173042 | 2014-04-19T14:59:42 | 2014-04-19T14:59:42 | 37,951,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,902 | cpp | // nullGDR.cpp : Defines the entry point for the DLL application.
//
#include "ImgReader.h"
//Get a copy of the operators for structs ... ugly , but works :)
#include "common.h"
HINSTANCE hInstance;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
hInstance=(HINSTANCE)hModule;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
_setts settings;
int cfgGetInt(wchar* key,int def)
{
return emu.ConfigLoadInt(L"ImageReader",key,def);
}
void cfgSetInt(wchar* key,int v)
{
emu.ConfigSaveInt(L"ImageReader",key,v);
}
void cfgGetStr(wchar* key,wchar* v,const wchar*def)
{
emu.ConfigLoadStr(L"ImageReader",key,v,def);
}
void cfgSetStr(wchar* key,const wchar* v)
{
emu.ConfigSaveStr(L"ImageReader",key,v);
}
void LoadSettings()
{
settings.PatchRegion=cfgGetInt(L"PatchRegion",0)!=0;
settings.LoadDefaultImage=cfgGetInt(L"LoadDefaultImage",0)!=0;
cfgGetStr(L"DefaultImage",settings.DefaultImage,L"defualt.gdi");
cfgGetStr(L"LastImage",settings.LastImage,L"c:\\game.gdi");
}
void SaveSettings()
{
cfgSetInt(L"PatchRegion",settings.PatchRegion);
cfgSetInt(L"LoadDefaultImage",settings.LoadDefaultImage);
cfgSetStr(L"DefaultImage",settings.DefaultImage);
cfgSetStr(L"LastImage",settings.LastImage);
}
#define PLUGIN_NAME "Image Reader plugin by drk||Raziel & GiGaHeRz [" __DATE__ "]"
#define PLUGIN_NAMEW L"Image Reader plugin by drk||Raziel & GiGaHeRz [" _T(__DATE__) L"]"
void FASTCALL GetSessionInfo(u8* out,u8 ses);
void FASTCALL DriveReadSubChannel(u8 * buff, u32 format, u32 len)
{
if (format==0)
{
memcpy(buff,q_subchannel,len);
}
}
void FASTCALL DriveReadSector(u8 * buff,u32 StartSector,u32 SectorCount,u32 secsz)
{
GetDriveSector(buff,StartSector,SectorCount,secsz);
//if (CurrDrive)
// CurrDrive->ReadSector(buff,StartSector,SectorCount,secsz);
}
void FASTCALL DriveGetTocInfo(u32* toc,u32 area)
{
GetDriveToc(toc,(DiskArea)area);
}
//TODO : fix up
u32 FASTCALL DriveGetDiscType()
{
if (disc)
return disc->type;
else
return NullDriveDiscType;
}
void FASTCALL GetSessionInfo(u8* out,u8 ses)
{
GetDriveSessionInfo(out,ses);
}
emu_info emu;
wchar emu_name[512];
void EXPORT_CALL handle_PatchRegion(u32 id,void* w,void* p)
{
if (settings.PatchRegion)
settings.PatchRegion=0;
else
settings.PatchRegion=1;
emu.SetMenuItemStyle(id,settings.PatchRegion?MIS_Checked:0,MIS_Checked);
SaveSettings();
}
void EXPORT_CALL handle_UseDefImg(u32 id,void* w,void* p)
{
if (settings.LoadDefaultImage)
settings.LoadDefaultImage=0;
else
settings.LoadDefaultImage=1;
emu.SetMenuItemStyle(id,settings.LoadDefaultImage?MIS_Checked:0,MIS_Checked);
SaveSettings();
}
void EXPORT_CALL handle_SelDefImg(u32 id,void* w,void* p)
{
if (GetFile(settings.DefaultImage,0,1)==1)//no "no disk"
{
SaveSettings();
}
}
void EXPORT_CALL handle_About(u32 id,void* w,void* p)
{
MessageBox((HWND)w,L"Made by drk||Raziel & GiGaHeRz",L"About ImageReader...",MB_ICONINFORMATION);
}
void EXPORT_CALL handle_SwitchDisc(u32 id,void* w,void* p)
{
//msgboxf("This feature is not yet implemented",MB_ICONWARNING);
//return;
TermDrive();
NullDriveDiscType=Busy;
DriveNotifyEvent(DiskChange,0);
Sleep(150); //busy for a bit
NullDriveDiscType=Open;
DriveNotifyEvent(DiskChange,0);
Sleep(150); //tray is open
while(!InitDrive(2))//no "cancel"
msgboxf(L"Init Drive failed, disc must be valid for swap",0x00000010L);
DriveNotifyEvent(DiskChange,0);
//new disc is in
}
//called when plugin is used by emu (you should do first time init here)
s32 FASTCALL Load(emu_info* emu_inf)
{
if (emu_inf==0)
return rv_ok;
memcpy(&emu,emu_inf,sizeof(emu));
emu.ConfigLoadStr(L"emu",L"shortname",emu_name,0);
LoadSettings();
emu.AddMenuItem(emu.RootMenu,-1,L"Swap Disc",handle_SwitchDisc,settings.LoadDefaultImage);
emu.AddMenuItem(emu.RootMenu,-1,0,0,0);
emu.AddMenuItem(emu.RootMenu,-1,L"Use Default Image",handle_UseDefImg,settings.LoadDefaultImage);
emu.AddMenuItem(emu.RootMenu,-1,L"Select Default Image",handle_SelDefImg,0);
emu.AddMenuItem(emu.RootMenu,-1,L"Patch GDROM region",handle_PatchRegion,settings.PatchRegion);
emu.AddMenuItem(emu.RootMenu,-1,0,0,0);
emu.AddMenuItem(emu.RootMenu,-1,L"About",handle_About,0);
return rv_ok;
}
//called when plugin is unloaded by emu , olny if dcInitGDR is called (eg , not called to enumerate plugins)
void FASTCALL Unload()
{
}
//It's suposed to reset everything (if not a manual reset)
void FASTCALL ResetGDR(bool Manual)
{
DriveNotifyEvent(DiskChange,0);
}
//called when entering sh4 thread , from the new thread context (for any thread speciacific init)
s32 FASTCALL InitGDR(gdr_init_params* prm)
{
DriveNotifyEvent=prm->DriveNotifyEvent;
if (!InitDrive())
return rv_serror;
DriveNotifyEvent(DiskChange,0);
LoadSettings();
return rv_ok;
}
//called when exiting from sh4 thread , from the new thread context (for any thread speciacific de init) :P
void FASTCALL TermGDR()
{
TermDrive();
}
//Give to the emu pointers for the gd rom interface
void EXPORT_CALL dcGetInterface(plugin_interface* info)
{
#define c info->common
#define g info->gdr
info->InterfaceVersion=PLUGIN_I_F_VERSION;
c.Type=Plugin_GDRom;
c.InterfaceVersion=GDR_PLUGIN_I_F_VERSION;
wcscpy(c.Name,PLUGIN_NAMEW);
c.Load=Load;
c.Unload=Unload;
g.Init=InitGDR;
g.Term=TermGDR;
g.Reset=ResetGDR;
g.GetDiscType=DriveGetDiscType;
g.GetToc=DriveGetTocInfo;
g.ReadSector=DriveReadSector;
g.GetSessionInfo=GetSessionInfo;
g.ReadSubChannel=DriveReadSubChannel;
g.ExeptionHanlder=0;
} | [
"masterchan777@gmail.com"
] | masterchan777@gmail.com |
36bf7a9aa5046526666ed2f060e57275a8e4f803 | 94dcc118f9492896d6781e5a3f59867eddfbc78a | /llvm/lib/Fuzzer/FuzzerIO.cpp | ac35d736bbfaa292630bf1f73086b6c898e717fb | [
"NCSA",
"Apache-2.0"
] | permissive | vusec/safeinit | 43fd500b5a832cce2bd87696988b64a718a5d764 | 8425bc49497684fe16e0063190dec8c3c58dc81a | refs/heads/master | 2021-07-07T11:46:25.138899 | 2021-05-05T10:40:52 | 2021-05-05T10:40:52 | 76,794,423 | 22 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 3,793 | cpp | //===- FuzzerIO.cpp - IO utils. -------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// IO functions.
//===----------------------------------------------------------------------===//
#include "FuzzerInternal.h"
#include <iterator>
#include <fstream>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstdarg>
#include <cstdio>
namespace fuzzer {
static FILE *OutputFile = stderr;
bool IsFile(const std::string &Path) {
struct stat St;
if (stat(Path.c_str(), &St))
return false;
return S_ISREG(St.st_mode);
}
static long GetEpoch(const std::string &Path) {
struct stat St;
if (stat(Path.c_str(), &St))
return 0; // Can't stat, be conservative.
return St.st_mtime;
}
static void ListFilesInDirRecursive(const std::string &Dir, long *Epoch,
std::vector<std::string> *V, bool TopDir) {
auto E = GetEpoch(Dir);
if (Epoch)
if (E && *Epoch >= E) return;
DIR *D = opendir(Dir.c_str());
if (!D) {
Printf("No such directory: %s; exiting\n", Dir.c_str());
exit(1);
}
while (auto E = readdir(D)) {
std::string Path = DirPlusFile(Dir, E->d_name);
if (E->d_type == DT_REG || E->d_type == DT_LNK)
V->push_back(Path);
else if (E->d_type == DT_DIR && *E->d_name != '.')
ListFilesInDirRecursive(Path, Epoch, V, false);
}
closedir(D);
if (Epoch && TopDir)
*Epoch = E;
}
Unit FileToVector(const std::string &Path, size_t MaxSize) {
std::ifstream T(Path);
if (!T) {
Printf("No such directory: %s; exiting\n", Path.c_str());
exit(1);
}
T.seekg(0, T.end);
size_t FileLen = T.tellg();
if (MaxSize)
FileLen = std::min(FileLen, MaxSize);
T.seekg(0, T.beg);
Unit Res(FileLen);
T.read(reinterpret_cast<char *>(Res.data()), FileLen);
return Res;
}
std::string FileToString(const std::string &Path) {
std::ifstream T(Path);
return std::string((std::istreambuf_iterator<char>(T)),
std::istreambuf_iterator<char>());
}
void CopyFileToErr(const std::string &Path) {
Printf("%s", FileToString(Path).c_str());
}
void WriteToFile(const Unit &U, const std::string &Path) {
// Use raw C interface because this function may be called from a sig handler.
FILE *Out = fopen(Path.c_str(), "w");
if (!Out) return;
fwrite(U.data(), sizeof(U[0]), U.size(), Out);
fclose(Out);
}
void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V,
long *Epoch, size_t MaxSize) {
long E = Epoch ? *Epoch : 0;
std::vector<std::string> Files;
ListFilesInDirRecursive(Path, Epoch, &Files, /*TopDir*/true);
size_t NumLoaded = 0;
for (size_t i = 0; i < Files.size(); i++) {
auto &X = Files[i];
if (Epoch && GetEpoch(X) < E) continue;
NumLoaded++;
if ((NumLoaded & (NumLoaded - 1)) == 0 && NumLoaded >= 1024)
Printf("Loaded %zd/%zd files from %s\n", NumLoaded, Files.size(), Path);
V->push_back(FileToVector(X, MaxSize));
}
}
std::string DirPlusFile(const std::string &DirPath,
const std::string &FileName) {
return DirPath + "/" + FileName;
}
void DupAndCloseStderr() {
int OutputFd = dup(2);
if (OutputFd > 0) {
FILE *NewOutputFile = fdopen(OutputFd, "w");
if (NewOutputFile) {
OutputFile = NewOutputFile;
close(2);
}
}
}
void CloseStdout() { close(1); }
void Printf(const char *Fmt, ...) {
va_list ap;
va_start(ap, Fmt);
vfprintf(OutputFile, Fmt, ap);
va_end(ap);
fflush(OutputFile);
}
} // namespace fuzzer
| [
"fuzzie@fuzzie.org"
] | fuzzie@fuzzie.org |
ff4ba326da8d88bc34ecde96f3643df7f7adb3d6 | 2f6e00bb938aaad85b23b4f06a929c7fbbd9e8a1 | /lab4/userprog/progtest.cc | 7fb25b00d364ec2ddd7702b83ff41add2a499ba8 | [] | no_license | baker221/Nachos-Lab | b95f793d3bc1ef920895847961accb05202b2545 | ca43e5d122badfd860521150ad1abd2c67cacee5 | refs/heads/main | 2023-07-17T12:57:08.524439 | 2021-08-27T02:28:40 | 2021-08-27T02:28:40 | 309,029,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,032 | cc | // progtest.cc
// Test routines for demonstrating that Nachos can load
// a user program and execute it.
//
// Also, routines for testing the Console hardware device.
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#include "addrspace.h"
#include "console.h"
#include "copyright.h"
#include "synch.h"
#include "system.h"
void RunUserProcess(int arg) {
Machine *m = (Machine *)arg;
currentThread->space->InitRegisters(); // set the initial register values
currentThread->space->RestoreState(); // load page table register
printf("fork thread ready to run\n");
m->Run();
}
//----------------------------------------------------------------------
// StartProcess
// Run a user program. Open the executable, load it into
// memory, and jump to it.
//----------------------------------------------------------------------
void StartProcess(char *filename) {
OpenFile *executable = fileSystem->Open(filename);
AddrSpace *space;
if (executable == NULL) {
printf("Unable to open file %s\n", filename);
return;
}
space = new AddrSpace(executable);
// char k = space->disk[0];
// printf("%c\n", k);
currentThread->space = space;
// k = currentThread->space->disk[0];
// printf("%c\n", k);
delete executable; // close file
space->InitRegisters(); // set the initial register values
space->RestoreState(); // load page table register
printf("main thread ready to run\n");
machine->Run(); // jump to the user progam
ASSERT(FALSE); // machine->Run never returns;
// the address space exits
// by doing the syscall "exit"
}
// Data structures needed for the console test. Threads making
// I/O requests wait on a Semaphore to delay until the I/O completes.
static Console *console;
static Semaphore *readAvail;
static Semaphore *writeDone;
//----------------------------------------------------------------------
// ConsoleInterruptHandlers
// Wake up the thread that requested the I/O.
//----------------------------------------------------------------------
static void ReadAvail(int arg) { readAvail->V(); }
static void WriteDone(int arg) { writeDone->V(); }
//----------------------------------------------------------------------
// ConsoleTest
// Test the console by echoing characters typed at the input onto
// the output. Stop when the user types a 'q'.
//----------------------------------------------------------------------
void ConsoleTest(char *in, char *out) {
char ch;
console = new Console(in, out, ReadAvail, WriteDone, 0);
readAvail = new Semaphore("read avail", 0);
writeDone = new Semaphore("write done", 0);
for (;;) {
readAvail->P(); // wait for character to arrive
ch = console->GetChar();
console->PutChar(ch); // echo it!
writeDone->P(); // wait for write to finish
if (ch == 'q')
return; // if q, quit
}
}
| [
"806871923@qq.com"
] | 806871923@qq.com |
f0b6c7c97ae4f8db1034811a9456fa36db3873da | 3209df75963925dc6cc7941b63119fb7f1c4e97f | /Headers/FGCameraModifierLimitLook.h | a2097362e7b05f87f85ae6e16221e16187475843 | [] | no_license | SatisGraphtory/SourceData | a06aff42b0da2156c0519e7c69093f3e1e7a83f5 | 7948e28a16ed600c4a9fae7873ef5ebbbbea6796 | refs/heads/master | 2023-08-18T09:27:14.186240 | 2021-04-20T18:38:54 | 2021-04-20T18:38:54 | 309,817,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,134 | h | // Copyright Coffee Stain Studios. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Camera/CameraModifier.h"
#include "FGCameraModifierLimitLook.generated.h"
/**
*
*/
UCLASS()
class FACTORYGAME_API UFGCameraModifierLimitLook : public UCameraModifier
{
GENERATED_BODY()
public:
virtual bool ProcessViewRotation( class AActor* ViewTarget, float DeltaTime, FRotator& OutViewRotation, FRotator& OutDeltaRot );
/** Sets the default rotation */
UFUNCTION( BlueprintCallable, Category = "Limited Look" )
void SetDefaultLookRotator( FRotator inRotator ) { mLookRotator = inRotator; }
/** Gets the default rotation */
UFUNCTION( BlueprintPure, Category = "Limited Look" )
FORCEINLINE FRotator GetDefaultLookRotator() { return mLookRotator; }
public:
/** The look rotation we use as base point */
FRotator mLookRotator;
/** The max rotation in pitch ( abs value ) */
UPROPERTY( EditDefaultsOnly, Category = "Limited Look" )
float mMaxPitch;
/** The max rotation in yaw ( abs value ) */
UPROPERTY( EditDefaultsOnly, Category = "Limited Look" )
float mMaxYaw;
};
| [
"aafu@ucdavis.edu"
] | aafu@ucdavis.edu |
985238a2650a1564984538fc4c010fde20920fbc | 56aa0e07739f12107358e7630d4baa67f565dbbc | /src/io/MultiThreadedFileCollector.cpp | 447d3b940026512a007ebb20967068757633b9c8 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | slide-lig/plcmpp | 19d8cbd3c2656495226fc4ea091adbb44cdcda8d | d2f5d8e2d0543023faf24b081b6085e42778b73a | refs/heads/master | 2021-01-16T18:31:51.430774 | 2014-06-18T15:16:53 | 2014-06-18T15:16:53 | 19,612,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,613 | cpp | /*******************************************************************************
* Copyright (c) 2014 Etienne Dublé, Martin Kirchgessner, Vincent Leroy, Alexandre Termier, CNRS and Université Joseph Fourier.
*
* 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
*
* or see the LICENSE.txt file joined with this program.
*
* 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 <sstream>
#include <io/MultiThreadedFileCollector.hpp>
#include <io/FileCollector.hpp>
namespace io {
MultiThreadedFileCollector::MultiThreadedFileCollector(string& prefix) {
collectors = new map<thread::id, FileCollector*>();
_prefix = prefix;
}
MultiThreadedFileCollector::~MultiThreadedFileCollector() {
for (pair<const std::thread::id, io::FileCollector*> pair : (*collectors)) {
delete pair.second;
}
delete collectors;
}
FileCollector *MultiThreadedFileCollector::getCollectorOfCurrentThread() {
thread::id this_thread_id = std::this_thread::get_id();
typename map<thread::id, FileCollector*>::iterator it =
collectors->find(this_thread_id);
FileCollector *result;
if (it == collectors->end())
{ // not found, create the collector
std::ostringstream spath(_prefix);
spath << this_thread_id << ".dat";
string path = spath.str();
result = new FileCollector(path);
(*collectors)[this_thread_id] = result;
}
else
{ // found
result = it->second;
}
return result;
}
void MultiThreadedFileCollector::collect(int32_t support,
vector<int32_t>* pattern) {
getCollectorOfCurrentThread()->collect(support, pattern);
}
int64_t MultiThreadedFileCollector::close() {
int64_t total = 0;
for (pair<const std::thread::id, io::FileCollector*> pair : (*collectors)) {
total += pair.second->close();
}
return total;
}
int32_t MultiThreadedFileCollector::getAveragePatternLength() {
int64_t totalLen = 0;
int64_t nbPatterns = 0;
for (pair<const std::thread::id, io::FileCollector*> pair : (*collectors)) {
totalLen += pair.second->getCollectedLength();
nbPatterns += pair.second->getCollected();
}
return (int) (totalLen / nbPatterns);
}
}
| [
"etienne.duble@imag.fr"
] | etienne.duble@imag.fr |
11adfc60f5282b4ee968af5c54739103e513033e | 0cab650e428599876511d0a4d7d1e215014bb3a5 | /DAY_5/P12/Ram_main.cpp | 214822a5a0821bd29f4857a59cdf60bfbadbf820 | [] | no_license | ksg0605/Practice_CPP | ed2dca85248f180611422f053ebffffd4186f53a | d9149c536d125b7ec3b390e9f03b2062b27b5c08 | refs/heads/main | 2023-02-04T21:20:45.105804 | 2020-12-23T14:55:07 | 2020-12-23T14:55:07 | 306,889,898 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 250 | cpp | #include<iostream>
#include"Ram.h"
using namespace std;
int main(){
Ram ram;
ram.write(100, 20);
ram.write(101, 30);
char res = ram.read(100) + ram.read(101);
ram.write(102, res);
cout<<"102 번지의 값 = "<<(int)ram.read(102)<<endl;
} | [
"yyh2337@naver.com"
] | yyh2337@naver.com |
d99ea04c8e693eebd537248f796c0373f3aebd20 | 134fdeae8c3dd047cf737dc34468a5a6d67a934c | /Behavioral/ChainOfResponsability/include/Monster.hpp | 83fd4b8ebf251473f6bd9f41cc68a96b98617c41 | [
"Unlicense"
] | permissive | craviee/design-patterns-modern-cpp | 5937873d6f3d7e974a44b8752d39e567b35bbef3 | 39896c8a2491c5599f79afa65a07deda2e4e7dd7 | refs/heads/master | 2020-09-08T21:35:55.806632 | 2020-02-05T14:52:34 | 2020-02-05T14:52:34 | 221,248,692 | 3 | 0 | Unlicense | 2020-02-05T14:52:36 | 2019-11-12T15:21:43 | C++ | UTF-8 | C++ | false | false | 267 | hpp | #pragma once
#include "Party.hpp"
class Monster {
private:
Monster* next{nullptr};
public:
Monster(Party& party) : party{party}{};
~Monster(){};
int power;
void add(Monster* monster);
virtual void handle();
protected:
Party& party;
}; | [
"danielcraviee@gmail.com"
] | danielcraviee@gmail.com |
45eefdf86be675809e994ec288d6b32c4758fffe | 8fdeb339d75b3aed20fd82fcf1b59e42411234e1 | /src/BootManager.h | ab3fd60cb5c6f7e264de2fe8f6d1b2bcffea88dc | [] | no_license | PMarinov1994/esp8266_MQTT_Transmiter | e6cc8bd471c1070a09fc7abddc5fb0931525479d | bb06ce9aaea6ac25d8bd9f491cedf5e18320e630 | refs/heads/main | 2023-04-03T01:26:26.627829 | 2021-04-12T11:25:19 | 2021-04-12T11:25:19 | 355,684,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 172 | h | #pragma once
#include <Arduino.h>
#define GPIO_RX 3
#define GPIO_TX 1
class CBootManager
{
public:
CBootManager();
virtual ~CBootManager() {};
bool IsConfigBoot();
}; | [
"44176168+PMarinov1994@users.noreply.github.com"
] | 44176168+PMarinov1994@users.noreply.github.com |
44162207134e56dfbc4fcf300dc0342cdfcf9c6c | 758d6e7aad76b8ab57d7725cb17db005e5033485 | /test/test_multidomain.cc | 4f7b85d353e178a93a5286d327d39fd97deb5ba0 | [
"BSD-3-Clause"
] | permissive | jurgispods/dune-ax1 | 4468b798a01928dd87b0a5eac1f8b5acf59ac157 | 152153824d95755a55bdd4fba80686863e928196 | refs/heads/master | 2023-04-15T05:45:58.440381 | 2021-11-09T22:42:16 | 2021-11-09T22:42:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,814 | cc | #ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <stdlib.h>
#include <typeinfo>
#include <dune/common/mpihelper.hh>
#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>
#include <dune/common/timer.hh>
#include <dune/common/parametertreeparser.hh>
#include <dune/grid/common/scsgmapper.hh>
#include <dune/grid/onedgrid.hh>
#if HAVE_ALBERTA
#include <dune/grid/albertagrid.hh>
#include <dune/grid/albertagrid/dgfparser.hh>
#endif
#if HAVE_UG
#include <dune/grid/uggrid.hh>
#endif
#if HAVE_ALUGRID
#include <dune/grid/alugrid.hh>
#include <dune/grid/io/file/dgfparser/dgfalu.hh>
#include <dune/grid/io/file/dgfparser/dgfparser.hh>
#endif
#if HAVE_DUNE_SUBGRID && USE_SUBGRID==2
#include <dune/subgrid/subgrid.hh>
#endif
#if HAVE_DUNE_MULTIDOMAINGRID
#include <dune/grid/multidomaingrid/multidomaingrid.hh>
#endif
#include <dune/pdelab/multidomain/multidomaingridfunctionspace.hh>
#include <dune/pdelab/multidomain/subproblemlocalfunctionspace.hh>
#include <dune/pdelab/multidomain/couplinggridfunctionspace.hh>
#include <dune/pdelab/multidomain/couplinglocalfunctionspace.hh>
#include <dune/pdelab/multidomain/gridoperator.hh>
#include <dune/pdelab/multidomain/subproblem.hh>
#include <dune/pdelab/multidomain/coupling.hh>
#include <dune/pdelab/multidomain/constraints.hh>
#include <dune/ax1/common/ax1_subgridview.hh>
#include <dune/ax1/common/ax1_subgrid_hostelement_mapper.hh>
#include <dune/ax1/common/tools.hh>
#include <dune/ax1/common/output.hh>
#include <dune/ax1/acme1MD/common/acme1MD_factory.hh>
#include <dune/ax1/acme1MD/common/acme1MD_physics.hh>
#include <dune/ax1/acme1MD/common/acme1MD_parametertree.hh>
#include <dune/ax1/acme1MD/common/acme1MD_setup.hh>
#include <dune/ax1/channels/channel_builder.hh>
template<typename Config, typename GV, typename SubGV>
void run(Acme1MDParameters& params, Config& config, GV& gv, std::vector<double>& coords, double dtstart, double tend,
ElementSubdomainMapper& elemSubdomainMapper, SubGV& elecGV, SubGV& membGV)
{
debug_verb << "Configuration '" << config.getConfigName() << "' loaded." << std::endl;
typedef typename Acme1MDFactory<GV,double,Config,SubGV>::PHYSICS PHYSICS;
PHYSICS physics = Acme1MDFactory<GV,double,Config,SubGV>::setup(config, gv, elecGV, membGV, params, coords, dtstart,
elemSubdomainMapper);
// Check parameters used
debug_verb << "==============================================" << std::endl;
debug_verb << "LENGTH_SCALE = " << physics.getLengthScale() << std::endl;
debug_verb << "TIME_SCALE = " << physics.getTimeScale() << std::endl;
for(int i=0; i<NUMBER_OF_SPECIES; ++i)
{
debug_verb << "con_diffWater" << ION_NAMES[i] << " = " << physics.getElectrolyte().getDiffConst(i) << std::endl;
}
debug_verb << "electrolyte temperature: " << physics.getElectrolyte().getTemperature() << std::endl;
debug_verb << "electrolyte stdCon: " << physics.getElectrolyte().getStdCon() << std::endl;
debug_verb << "poissonConstant: " << physics.getPoissonConstant() << std::endl;
debug_verb << "==============================================" << std::endl;
// Check multidomain grid
std::cout << "Checking multidomain grid" << std::endl;
for(typename PHYSICS::ElementIterator eit = gv.template begin<0>(); eit != gv.template end<0>(); ++eit)
{
std::cout << "Element #" << gv.indexSet().index(*eit) << "[" << physics.getElementIndex(*eit )<< "]"
<< " contains=" << gv.contains(*eit) << std::endl;
int iindex = 0;
for(typename PHYSICS::ElementIntersectionIterator iit = eit->ileafbegin(); iit != eit->ileafend(); ++iit)
{
std::cout << " - Intersection " << iindex++ << ": isMembraneInterface=" << physics.isMembraneInterface(*iit)
<< std::endl;
}
}
std::cout << "Checking subdomain #0" << std::endl;
for(typename PHYSICS::SubDomainElementIterator sdeit = elecGV.template begin<0>(); sdeit != elecGV.template end<0>(); ++sdeit)
{
std::cout << "Element #" << elecGV.indexSet().index(*sdeit) << std::endl;
std::cout << "[" << physics.getSubDomainElementIndex(*sdeit)<< "]"
<< " -- " << gv.indexSet().index(gv.grid().multiDomainEntity(*sdeit)) << "[" << physics.getElementIndex(*sdeit )<< "]"
<< " contains=" << elecGV.contains(*sdeit) << std::endl;
int iindex = 0;
for(typename PHYSICS::SubDomainElementIntersectionIterator iit = sdeit->ileafbegin(); iit != sdeit->ileafend(); ++iit)
{
std::cout << " - Intersection " << iindex++ << ": isMembraneInterface=" << physics.isMembraneInterface(*iit)
<< std::endl;
if(physics.isMembraneInterface(*iit))
{
std::cout << " + Associated membrane element (global/subdomain index): "
<< physics.getMembraneElementIndex(*iit) << " / "
<< physics.getSubDomainMembraneElementIndex(*iit)
<< std::endl;
}
}
}
std::cout << "Checking subdomain #1" << std::endl;
for(typename PHYSICS::SubDomainElementIterator sdeit = membGV.template begin<0>(); sdeit != membGV.template end<0>(); ++sdeit)
{
std::cout << "Element #" << membGV.indexSet().index(*sdeit) << "[" << physics.getSubDomainElementIndex(*sdeit )<< "]"
<< " -- " << gv.indexSet().index(gv.grid().multiDomainEntity(*sdeit)) << "[" << physics.getElementIndex(*sdeit )<< "]"
<< " contains=" << membGV.contains(*sdeit) << std::endl;
int iindex = 0;
for(typename PHYSICS::SubDomainElementIntersectionIterator iit = sdeit->ileafbegin(); iit != sdeit->ileafend(); ++iit)
{
std::cout << " - Intersection " << iindex++ << ": isMembraneInterface=" << physics.isMembraneInterface(*iit)
<< std::endl;
if(physics.isMembraneInterface(*iit))
{
std::cout << " + Associated membrane element (global/subdomain index): "
<< physics.getMembraneElementIndex(*iit) << " / "
<< physics.getSubDomainMembraneElementIndex(*iit)
<< std::endl;
}
}
}
}
//===============================================================
// Main program with grid setup
//===============================================================
int main(int argc, char** argv)
{
try{
//Maybe initialize Mpi
Dune::MPIHelper& helper = Dune::MPIHelper::instance(argc, argv);
if(Dune::MPIHelper::isFake)
std::cout<< "This is acme1MD. Extrem cremig." << std::endl;
else
{
if(helper.rank()==0)
std::cout << "parallel run on " << helper.size() << " process(es)" << std::endl;
}
if (argc<4)
{
if(helper.rank()==0)
std::cout << "usage: ./acme1MD <level> <dtstart> <tend> [config-file]" << std::endl;
return 1;
}
int level;
sscanf(argv[1],"%d",&level);
double dtstart;
sscanf(argv[2],"%lg",&dtstart);
double tend;
sscanf(argv[3],"%lg",&tend);
std::string configFileName;
if (argc>=5)
{
configFileName = argv[4];
} else {
configFileName = "acme1MD.config";
}
debug_verb << "Using config file " << configFileName << std::endl;
Dune::Timer timer;
// sequential version
if (1 && helper.size()==1)
{
// Read config file
Acme1MDParameters params;
Dune::ParameterTreeParser::readINITree(configFileName, params, true);
params.init();
assert(params.useMembrane() == true);
// ############## grid generation ##################
// Seed 1d grid coordinates
double d = params.dMemb();
std::vector<double> coords = { 0.5*d, params.xMax() };
Tools::globalRefineVector( coords, level, params.refineMembrane() );
//Tools::globalRefineVectorLogarithmic( coords, level );
//Output::printVector(coords);
// mirror grid
for (int i=coords.size()-1; i>=0; i--)
{
// Do not mirror coordinate x=0
if(not std::abs(coords[i] < 1e-12))
{
coords.push_back( -coords[i] );
}
}
sort(coords.begin(), coords.end());
//Output::printVector(coords);
typedef Dune::OneDGrid BaseGrid;
typedef BaseGrid GridType;
GridType baseGrid(coords);
// ############## END grid generation ###############
// ============== Multidomaingrid stuff ================================================================
typedef Dune::MultiDomainGrid<BaseGrid,Dune::mdgrid::FewSubDomainsTraits<BaseGrid::dimension,2> > Grid;
Grid grid(baseGrid,false);
typedef Grid::LeafGridView GV;
GV gv = grid.leafGridView();
typedef GV::Codim<0>::Iterator ElementIterator;
typedef GV::Codim<0>::EntityPointer ElementPointer;
typedef Dune::SingleCodimSingleGeomTypeMapper<GV, 0> ElementMapper;
// Custom mapper to map element indices to group indices
ElementSubdomainMapper elemSubdomainMapper;
ElementMapper elementMapper(gv);
// Tag elements by type
for(ElementIterator ep = gv.begin<0>(); ep != gv.end<0>(); ++ep)
{
int elemIndex = elementMapper.map(*ep);
int subdomainIndex = CYTOSOL;
double center = ep->geometry().center();
// We are on the membrane
if(params.useMembrane() and std::abs(center) < 0.5*d)
{
subdomainIndex = MEMBRANE;
}
// There is a membrane and we are on the outside of the cell
if(params.useMembrane() and center > 0.5*d)
{
subdomainIndex = ES;
}
// Store group of this element [M->G]
elemSubdomainMapper.setGroup(elemIndex, subdomainIndex);
}
typedef Grid::SubDomainGrid SubDomainGrid;
SubDomainGrid& elecGrid = grid.subDomain(0);
SubDomainGrid& membGrid = grid.subDomain(1);
typedef Grid::ctype ctype;
typedef SubDomainGrid::LeafGridView SDGV;
SDGV elecGV = elecGrid.leafGridView();
SDGV membGV = membGrid.leafGridView();
grid.startSubDomainMarking();
for (GV::Codim<0>::Iterator eit = gv.begin<0>(); eit != gv.end<0>(); ++eit)
{
int elemIndex = elementMapper.map(*eit);
int subdomainIndex = elemSubdomainMapper.map(elemIndex);
// Init subgrids
switch(subdomainIndex)
{
case CYTOSOL:
grid.addToSubDomain(0,*eit);
break;
case ES:
grid.addToSubDomain(0,*eit);
break;
case MEMBRANE:
grid.addToSubDomain(1,*eit);
break;
default:
DUNE_THROW(Dune::Exception, "Element could not be assigned to a pre-defined group!");
}
}
grid.preUpdateSubDomains();
grid.updateSubDomains();
grid.postUpdateSubDomains();
// ===============================================================================================
bool configFound = false;
std::string configName = params.getConfigName();
if(configName == "default")
{
DefaultConfiguration<double> config;
run(params,config,gv,coords,dtstart,tend,
elemSubdomainMapper,elecGV,membGV);
configFound = true;
}
if(configName == "hamburger")
{
HamburgerConfiguration<double> config;
run(params,config,gv,coords,dtstart,tend,
elemSubdomainMapper,elecGV,membGV);
configFound = true;
}
if(! configFound)
{
DUNE_THROW(Dune::Exception, "No configuration named '" << configName << "' could be found!");
}
double elapsed = timer.stop();
debug_info << "Time elapsed: " << elapsed << " s" << std::endl;
}
} catch (Dune::Exception &e){
std::cerr << "Dune reported error: " << e << std::endl;
return 0;
}
}
| [
"jpods@dune-project.org"
] | jpods@dune-project.org |
0574af8dda78faf488d29b4a10d8311ba1a71c1e | 370cb6baa54324bbe779a05fb11123e2787aed17 | /src/mpt/impl/prrt/prrt.hpp | 81cbaa62222792a70acdfd41fd239c359a93d332 | [
"BSD-3-Clause"
] | permissive | jeffi/mpt | 0125ccbc8305dacfdd67ec1caffc3079369cb0f1 | b867e91810b4b10970028301deb3ba9ab99812bf | refs/heads/master | 2020-03-30T04:59:43.887739 | 2018-09-28T16:34:40 | 2018-09-28T16:34:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,369 | hpp | // Software License Agreement (BSD-3-Clause)
//
// Copyright 2018 The University of North Carolina at Chapel Hill
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
//! @author Jeff Ichnowski
#pragma once
#ifndef MPT_IMPL_PRRT_PLANNER_HPP
#define MPT_IMPL_PRRT_PLANNER_HPP
#include "node.hpp"
#include "../atom.hpp"
#include "../goal_has_sampler.hpp"
#include "../object_pool.hpp"
#include "../planner_base.hpp"
#include "../scenario_goal.hpp"
#include "../scenario_rng.hpp"
#include "../scenario_sampler.hpp"
#include "../scenario_space.hpp"
#include "../timer_stat.hpp"
#include "../worker_pool.hpp"
#include "../../log.hpp"
#include "../../random_device_seed.hpp"
#include <forward_list>
#include <mutex>
namespace unc::robotics::mpt::impl::prrt {
template <bool enable>
struct WorkerStats;
template <>
struct WorkerStats<false> {
void countIteration() const {}
void countBiasedSample() const {}
auto& validMotion() { return TimerStat<void>::instance(); }
auto& nearest() { return TimerStat<void>::instance(); }
};
template <>
struct WorkerStats<true> {
mutable std::size_t iterations_{0};
mutable std::size_t biasedSamples_{0};
mutable TimerStat<> validMotion_;
mutable TimerStat<> nearest_;
void countIteration() const { ++iterations_; }
void countBiasedSample() const { ++biasedSamples_; }
TimerStat<>& validMotion() const { return validMotion_; }
TimerStat<>& nearest() const { return nearest_; }
WorkerStats& operator += (const WorkerStats& other) {
iterations_ += other.iterations_;
biasedSamples_ += other.biasedSamples_;
validMotion_ += other.validMotion_;
nearest_ += other.nearest_;
return *this;
}
void print() const {
MPT_LOG(INFO) << "iterations: " << iterations_;
MPT_LOG(INFO) << "biased samples: " << biasedSamples_;
MPT_LOG(INFO) << "valid motion: " << validMotion_;
MPT_LOG(INFO) << "nearest: " << nearest_;
}
};
template <typename Scenario, int maxThreads, bool reportStats, typename NNStrategy>
class PRRT : public PlannerBase<PRRT<Scenario, maxThreads, reportStats, NNStrategy>> {
using Planner = PRRT;
using Base = PlannerBase<Planner>;
using Space = scenario_space_t<Scenario>;
using State = typename Space::Type;
using Distance = typename Space::Distance;
using Node = prrt::Node<State>;
using RNG = scenario_rng_t<Scenario, Distance>;
using Sampler = scenario_sampler_t<Scenario, RNG>;
Distance maxDistance_{std::numeric_limits<Distance>::infinity()};
Distance goalBias_{0.01};
static constexpr bool concurrent = maxThreads != 1;
using NNConcurrency = std::conditional_t<concurrent, nigh::Concurrent, nigh::NoThreadSafety>;
nigh::Nigh<Node*, Space, NodeKey, NNConcurrency, NNStrategy> nn_;
std::mutex mutex_;
std::forward_list<Node*> goals_;
// we could use goals_.size(), but the performance of check if
// there is a solution can be critical, and goals_.size()
// requires a mutex lock. Thus we store the goal count in an
// atomic for fast access.
Atom<std::size_t, concurrent> goalCount_{0};
ObjectPool<Node, false> startNodes_;
struct Worker;
WorkerPool<Worker, maxThreads> workers_;
void foundGoal(Node* node) {
MPT_LOG(INFO) << "found solution";
{
std::lock_guard<std::mutex> lock(mutex_);
goals_.push_front(node);
}
++goalCount_;
}
public:
template <typename RNGSeed = RandomDeviceSeed<>>
explicit PRRT(const Scenario& scenario = Scenario(), const RNGSeed& seed = RNGSeed())
: nn_(scenario.space())
, workers_(scenario, seed)
{
MPT_LOG(TRACE) << "Using nearest: " << log::type_name<NNStrategy>();
MPT_LOG(TRACE) << "Using concurrency: " << log::type_name<NNConcurrency>();
MPT_LOG(TRACE) << "Using sampler: " << log::type_name<Sampler>();
}
void setGoalBias(Distance bias) {
assert(0 <= bias && bias <= 1);
goalBias_ = bias;
}
Distance getGoalBias() const {
return goalBias_;
}
void setRange(Distance range) {
assert(range > 0);
maxDistance_ = range;
}
Distance getRange() const {
return maxDistance_;
}
std::size_t size() const {
return nn_.size();
}
template <typename ... Args>
void addStart(Args&& ... args) {
std::lock_guard<std::mutex> lock(mutex_);
Node *node = startNodes_.allocate(nullptr, std::forward<Args>(args)...);
// TODO: workers_[0].connect(node);
nn_.insert(node);
}
// required to get convenience methods
using Base::solveFor;
using Base::solveUntil;
// required method
template <typename DoneFn>
std::enable_if_t<std::is_same_v<bool, std::result_of_t<DoneFn()>>>
solve(DoneFn doneFn) {
if (size() == 0)
throw std::runtime_error("there are no valid initial states");
workers_.solve(*this, doneFn);
}
bool solved() const {
return goalCount_.load(std::memory_order_relaxed);
}
private:
Distance buildSolution(std::vector<State>& path, const Node *n) const {
Distance cost = 0;
for (const Node *p ;; n = p) {
path.push_back(n->state());
if ((p = n->parent()) == nullptr)
return cost;
cost += workers_[0].space().distance(n->state(), p->state());
}
}
public:
std::vector<State> solution() const {
std::vector<State> best;
std::vector<State> curr;
Distance shortest = std::numeric_limits<Distance>::infinity();
for (const Node *n : goals_) {
curr.clear();
Distance cost = buildSolution(curr, n);
if (cost < shortest) {
std::swap(curr, best);
shortest = cost;
}
}
std::reverse(best.begin(), best.end());
return best;
}
void printStats() const {
MPT_LOG(INFO) << "nodes in graph: " << nn_.size();
if constexpr (reportStats) {
WorkerStats<true> stats;
for (unsigned i=0 ; i<workers_.size() ; ++i)
stats += workers_[i];
stats.print();
}
}
};
template <typename Scenario, int maxThreads, bool reportStats, typename NNStrategy>
class PRRT<Scenario, maxThreads, reportStats, NNStrategy>::Worker
: public WorkerStats<reportStats>
{
using Stats = WorkerStats<reportStats>;
unsigned no_;
Scenario scenario_;
RNG rng_;
ObjectPool<Node> nodePool_;
public:
Worker(Worker&& other)
: no_(other.no_)
, scenario_(other.scenario_)
, rng_(other.rng_)
, nodePool_(std::move(other.nodePool_))
{
}
template <typename RNGSeed>
Worker(unsigned no, const Scenario& scenario, const RNGSeed& seed)
: no_(no)
, scenario_(scenario)
, rng_(seed)
{
}
// decltype(auto) to allow both 'Space' and 'const Space&'
// return types.
decltype(auto) space() const{
return scenario_.space();
}
template <typename DoneFn>
void solve(Planner& planner, DoneFn done) {
MPT_LOG(TRACE) << "worker running";
Sampler sampler(scenario_);
using Goal = scenario_goal_t<Scenario>;
if constexpr (goal_has_sampler_v<Goal>) {
if (no_ == 0 && planner.goalBias_ > 0) {
GoalSampler<Goal> goalSampler(scenario_.goal());
std::uniform_real_distribution<Distance> uniform01;
// since we only have 1 thread performing goal
// biased sampling, we scale its percentage by the
// number of concurrent threads.
Distance scaledBias = planner.goalBias_ * planner.workers_.size();
MPT_LOG(TRACE) << "using scaled goal bias of " << scaledBias;
while (!done()) {
Stats::countIteration();
if (planner.goalCount_.load(std::memory_order_relaxed) >= 1)
goto unbiasedSamplingLoop;
if (uniform01(rng_) < planner.goalBias_) {
Stats::countBiasedSample();
addSample(planner, goalSampler(rng_));
} else {
addSample(planner, sampler(rng_));
}
}
return;
}
}
unbiasedSamplingLoop:
while (!done()) {
Stats::countIteration();
addSample(planner, sampler(rng_));
}
MPT_LOG(TRACE) << "worker done";
}
void addSample(Planner& planner, std::optional<State>&& sample) {
if (sample)
addSample(planner, *sample);
}
decltype(auto) nearest(Planner& planner, const State& state) {
Timer timer(Stats::nearest());
return planner.nn_.nearest(state);
}
void addSample(Planner& planner, State& randState) {
// nearest returns an optional, however it will
// only be empty if the nn structure is empty,
// which it will not be, because the planner's
// solve checks first. (but we assert anyways)
auto [nearNode, d] = nearest(planner, randState).value();
State newState = randState;
// avoid adding the same state multiple times. Unfortunately
// this check is not sufficient, and may need to be updated.
// numeric issues may cause distance() to return a non-zero
// value when given the same state as both arguments. It is
// also possible that non-equivalent states have a zero
// distance--but this would cause other issues with the
// planner and thus may not be worth handling.
if (d == 0)
return;
if (d > planner.maxDistance_)
newState = interpolate(
scenario_.space(),
nearNode->state(), randState,
planner.maxDistance_ / d);
// TODO: do not need to check when scenario returns
// std::optional<State> and the motion was not
// interpolated.
if (!scenario_.valid(newState))
return;
if (!validMotion(nearNode->state(), newState))
return;
auto [isGoal, goalDist] = scenario_.goal()(scenario_.space(), newState);
(void)goalDist; // mark unused (for now, may be used in approx solutions)
Node* newNode = nodePool_.allocate(nearNode, newState);
planner.nn_.insert(newNode);
if (isGoal)
planner.foundGoal(newNode);
}
bool validMotion(const State& a, const State& b) {
Timer timer(Stats::validMotion());
return scenario_.link(a, b);
}
};
}
#endif
| [
"jeff.ichnowski@gmail.com"
] | jeff.ichnowski@gmail.com |
c802b44f71deca44b9da592246404e5bd953b724 | caf491aed977a818d73e33e3b1abaa9c37c79d50 | /Module2leason3/Source.cpp | 0f254f96a16e8adcb82a0ae116c05a20737e6d1c | [] | no_license | MeushRoman/module2leasson3ht | e1314740188173fdf8de13fd3e9133754893ca91 | c915b20873d1fa342e94de50f3e8195a862d4685 | refs/heads/master | 2020-03-19T16:39:11.571296 | 2018-06-09T13:11:26 | 2018-06-09T13:11:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,099 | cpp | #include <stdlib.h>
#include <stdlib.h>
#include <locale.h>
#include <math.h>
#include <time.h>
#include <iostream>
void main()
{
setlocale(LC_ALL, "rus");
srand(time(NULL));
int n = 0;
do
{
printf("n = ");
scanf("%d", &n);
if (n == 1) {
printf("1. Определить, является ли данное целое число четным\n");
int x = 1 + rand() % 20;
printf("x = %d\n", x);
(x % 2 == 0) ? printf("true\n") : printf("false\n");
}
else if (n == 2) {
printf("2. Записать условие, которое является истинным, когда целое А кратно двум или трем.\n");
int A = 1 + rand() % 20;
printf("A = %d\n", A);
if ((A % 2 == 0) || (A % 3 == 0)) printf("true\n"); else printf("false\n");
}
else if (n == 3) {
printf("3. Записать условие, которое является истинным, когда каждое из чисел А и В нечетное\n");
int a = 1 + rand() % 20, b = 1 + rand() % 20;
printf("A = %d\tB = %d\n", a, b);
if (a % 2 != 0 && b % 2 != 0) printf("true\n"); else printf("false\n");
}
else if (n == 4) {
printf("4. Вычислить значение логических выражений при следующих значениях логических переменных X=0, Y=0, Z=1\na. X<Y>Z\nb. X>Y\nc. (X>Z)<Y\n\n");
int x = 0, y = 0, z = 1;
(x < y > z) ? printf("a. true\n") : printf("a. false\n");
(x > y) ? printf("b. true\n") : printf("b. false\n");
((x > z) < y) ? printf("c. true\n") : printf("c. false\n");
}
else if (n == 5) {
printf("5. Записать логическое выражение, описывающее область определения функции \na. y = 2tg x;\nb. у = 3 / (x - 1).\n\n");
int x = 1 + rand() % 2, y;
y = 2 * tan(x);
printf("a. y = %d\n", y);
if (x != 1) printf("b. y = %d\n", y = 3/(x-1));
}
else if (n == 6) {
printf("6. Вычислить значения логических выражений при следующих значениях логических переменных А=1, В=0, С=1\na. A<(A>B)<C\nb. A<C>(B<C)\nc. (A<B>C)<A\n\n");
int A = 1, B = 0, C = 1;
(A < (A > B) < C) ? printf("a. true\n") : printf("a. false\n");
(A < C > (B < C)) ? printf("b. true\n") : printf("b. false\n");
((A < B > C) < A) ? printf("c. true\n") : printf("c. false\n");
}
else if (n == 7) {
printf("7. Записать логическое выражение определяющее, что число А является трехзначным\n");
int a;
printf("A = ");
scanf("%d", &a);
if (a / 100 > 0 && a / 100 <= 9) printf("true\n"); else printf("false\n");
}
else if (n == 8) {
printf("8. Записать условие, которое является истинным, когда только одно из чисел А, В и С меньше 45.\n");
int a = 20 + rand() % 40, b = 20 + rand() % 40, c = 20 + rand() % 40;
printf("a = %d;\tb = %d;\tc = %d.\n\n", a, b, c);
if ((a < 45 && b >= 45 && c >= 45) || (b < 45 && a >= 45 && c >= 45) || (c < 45 && a >= 45 && b >= 45)) printf("true\n"); else printf("false\n");
}
else if (n == 9) {
printf("9. Записать условие, которое является истинным, когда целое А не кратно трем и оканчивается нулем\n");
int a = 1 + rand() % 99;
printf("A = %d\n", a);
if (a % 3 != 0 && a % 10 == 0) printf("true\n"); else printf("false\n");
}
else if (n == 10) {
printf("10. Записать логическое выражение, которое определяет, принадлежит ли число А интервалу от -137 до -51 или интервалу от 123 до 55.\n");
int a = -250 + rand() % 500;
printf("a = %d\n\n", a);
if ((a >= -137 && a <= -51) || (a >= 55 && a <= 123)) printf("true\n"); else printf("false\n");
}
} while (n > 0);
} | [
"amaii.sakura@gmail.com"
] | amaii.sakura@gmail.com |
eff2a04f05e659bf1d4b2ba4523ba19efc6d8d70 | 9c0e73e8909bc4b959918f573993804faba487d2 | /1128.cpp | e2a8d103e44d4be1e8ad47b66f4083950fd6ad0c | [] | no_license | MolinDeng/PAT | ab3d68ff747dfb1fc024fcbbfd3c2b787591efc3 | 8467fa07918f28aec3eff82c8e9bf81340e7f8ec | refs/heads/master | 2020-03-23T01:17:57.323874 | 2018-10-13T13:01:39 | 2018-10-13T13:01:39 | 140,909,837 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 889 | cpp | #include <cstdio>
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
#include <cmath>
using namespace std;
int main() {
int K, N;
scanf("%d", &K);
while(K--) {
scanf("%d", &N);
vector<int> config(N+1);
vector<vector<bool> > disabled(N+1, vector<bool>(N+1, false));
vector<bool> gap(2*N+1, false);
bool flag = false;
for(int i = 1; i <= N; i++) {
scanf("%d", &config[i]);
if(!flag) {
if(disabled[config[i]][i] || gap[config[i] - i + N]) flag = true;
else {
fill(disabled[config[i]].begin(), disabled[config[i]].end(), true);
gap[config[i] - i + N] = true;
}
}
}
printf("%s\n", flag ? "NO" : "YES");
}
return 0;
} | [
"zjumorning@gmail.com"
] | zjumorning@gmail.com |
4db349124c009df4e576106d97431dcc3bbc94c6 | 4352b5c9e6719d762e6a80e7a7799630d819bca3 | /tutorials/eulerVortex.twitch.test-test-test/eulerVortex.cyclic.twitch.moving/1.71/T | e895b25364b7ec5a63943358bf7ab2ef22ca165a | [] | no_license | dashqua/epicProject | d6214b57c545110d08ad053e68bc095f1d4dc725 | 54afca50a61c20c541ef43e3d96408ef72f0bcbc | refs/heads/master | 2022-02-28T17:20:20.291864 | 2019-10-28T13:33:16 | 2019-10-28T13:33:16 | 184,294,390 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,964 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "1.71";
object T;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 1 0 0 0];
internalField nonuniform List<scalar>
10000
(
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999999
0.999998
0.999998
0.999997
0.999997
0.999997
0.999998
0.999999
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999998
0.999997
0.999995
0.999993
0.999991
0.999989
0.999988
0.999989
0.99999
0.999993
0.999995
0.999997
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999999
0.999998
0.999996
0.999993
0.999988
0.999983
0.999976
0.99997
0.999965
0.999963
0.999964
0.999968
0.999974
0.999981
0.999988
0.999993
0.999997
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999998
0.999997
0.999994
0.999988
0.999979
0.999966
0.999951
0.999933
0.999916
0.999903
0.999896
0.999898
0.999908
0.999924
0.999943
0.999961
0.999976
0.999987
0.999994
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999998
0.999995
0.999991
0.999982
0.999967
0.999944
0.999912
0.999873
0.999829
0.999786
0.999753
0.999736
0.999741
0.999765
0.999804
0.99985
0.999895
0.999934
0.999962
0.999981
0.999991
0.999997
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999997
0.999994
0.999987
0.999975
0.999952
0.999916
0.999861
0.999787
0.999695
0.999594
0.999497
0.999421
0.999384
0.999393
0.999448
0.999537
0.999643
0.999747
0.999836
0.999903
0.999948
0.999975
0.999989
0.999996
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999997
0.999993
0.999985
0.999968
0.999938
0.999886
0.999803
0.999681
0.999517
0.999318
0.999101
0.998896
0.998739
0.998662
0.998683
0.9988
0.99899
0.999215
0.999438
0.99963
0.999777
0.999877
0.999938
0.999972
0.999989
0.999996
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999997
0.999993
0.999983
0.999963
0.999925
0.999857
0.999743
0.999565
0.99931
0.998973
0.99857
0.998138
0.997736
0.997433
0.99729
0.99734
0.997577
0.997956
0.998405
0.998851
0.999237
0.999533
0.999738
0.999865
0.999937
0.999973
0.99999
0.999996
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999997
0.999993
0.999982
0.99996
0.999915
0.999832
0.999688
0.999453
0.999095
0.998592
0.997943
0.997181
0.99638
0.995648
0.995109
0.994869
0.994984
0.99544
0.996152
0.996991
0.997823
0.998545
0.999102
0.999489
0.999732
0.999871
0.999943
0.999977
0.999992
0.999997
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999998
0.999993
0.999982
0.999958
0.999909
0.999815
0.999645
0.999356
0.998898
0.998219
0.997288
0.996114
0.994766
0.993377
0.992137
0.991251
0.990892
0.991147
0.991981
0.993245
0.994718
0.99617
0.997429
0.998403
0.999082
0.999513
0.999762
0.999893
0.999956
0.999983
0.999994
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999998
0.999994
0.999983
0.999958
0.999907
0.999804
0.999615
0.999284
0.998738
0.997893
0.996676
0.995052
0.993056
0.990818
0.988568
0.986611
0.985268
0.984803
0.985335
0.986791
0.988917
0.991351
0.993731
0.995783
0.99737
0.99848
0.999186
0.999597
0.999816
0.999922
0.99997
0.999989
0.999996
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999998
0.999994
0.999985
0.99996
0.999908
0.999803
0.999601
0.999239
0.998626
0.997642
0.996167
0.994105
0.991432
0.988237
0.984749
0.981334
0.978456
0.976592
0.976112
0.977159
0.979584
0.982974
0.986771
0.990434
0.993568
0.995981
0.997667
0.998743
0.999372
0.999709
0.999876
0.999951
0.999982
0.999994
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
0.999999
1
1
1
1
0.999999
0.999995
0.999986
0.999964
0.999913
0.999807
0.999601
0.999222
0.998563
0.997479
0.995796
0.993352
0.990044
0.985887
0.981065
0.975952
0.971097
0.967167
0.964824
0.964551
0.966484
0.970341
0.975475
0.981072
0.986376
0.990861
0.994291
0.996681
0.998206
0.999098
0.999579
0.999818
0.999927
0.999973
0.999991
0.999997
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
0.999999
1
1
1
1
1
0.999999
0.999996
0.999989
0.999967
0.99992
0.999817
0.999613
0.99923
0.998549
0.997402
0.995574
0.992833
0.988988
0.983958
0.977846
0.970978
0.963921
0.957457
0.952494
0.949895
0.950235
0.953585
0.959435
0.966822
0.974623
0.981858
0.987886
0.992451
0.995613
0.997625
0.998802
0.999438
0.999755
0.9999
0.999962
0.999987
0.999996
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
0.999998
0.99999
0.999973
0.999928
0.999833
0.999636
0.999259
0.998576
0.997405
0.995495
0.992554
0.988303
0.982554
0.975304
0.966794
0.957549
0.948377
0.940332
0.934589
0.932199
0.933774
0.939211
0.947656
0.957751
0.968044
0.977357
0.98498
0.990683
0.994601
0.99708
0.998527
0.999307
0.999696
0.999876
0.999953
0.999983
0.999994
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
0.999999
0.999993
0.999977
0.999939
0.999852
0.999666
0.999306
0.99864
0.997477
0.995545
0.992504
0.987988
0.981705
0.973534
0.963612
0.952383
0.940614
0.929392
0.920069
0.914085
0.912636
0.916255
0.924515
0.936096
0.949197
0.962071
0.973412
0.982516
0.989228
0.993791
0.996655
0.998317
0.999209
0.999653
0.999858
0.999945
0.99998
0.999993
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
0.999999
0.999996
0.999983
0.99995
0.999872
0.999704
0.999367
0.998733
0.997607
0.995706
0.992656
0.98802
0.981399
0.972553
0.961506
0.948606
0.934548
0.920372
0.907464
0.897478
0.892088
0.892533
0.899095
0.910849
0.925918
0.94208
0.957381
0.970494
0.980802
0.988279
0.993297
0.996414
0.998206
0.999161
0.999633
0.999849
0.999942
0.999979
0.999993
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
0.999999
1
1
1
1
1
1
0.999999
0.999997
0.999988
0.999961
0.999897
0.99975
0.999443
0.998855
0.997788
0.995961
0.992982
0.988363
0.981604
0.972337
0.960469
0.946252
0.930305
0.913591
0.897432
0.883514
0.873774
0.870049
0.873453
0.883796
0.899503
0.918123
0.937113
0.95445
0.968905
0.980022
0.987944
0.99318
0.996388
0.99821
0.999169
0.999639
0.999853
0.999944
0.99998
0.999993
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
0.999994
0.999974
0.999922
0.999799
0.999532
0.999001
0.998017
0.9963
0.993459
0.988981
0.982278
0.972851
0.96047
0.945292
0.927865
0.909093
0.890198
0.87277
0.858787
0.850434
0.849574
0.856956
0.871698
0.891489
0.913393
0.93471
0.953505
0.968752
0.980217
0.98823
0.993434
0.99657
0.998323
0.999232
0.99967
0.999867
0.999949
0.999982
0.999994
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999986
0.999948
0.999851
0.999631
0.999171
0.998291
0.996718
0.994071
0.989838
0.983375
0.974057
0.961486
0.945696
0.927177
0.906794
0.885705
0.86536
0.847611
0.834716
0.829025
0.832203
0.844362
0.863762
0.887397
0.912018
0.934962
0.954526
0.969968
0.981309
0.989067
0.994004
0.996921
0.99852
0.999334
0.999719
0.999888
0.999958
0.999985
0.999995
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
0.999999
1
1
1
1
1
1
0.999995
0.999972
0.999904
0.999734
0.99936
0.998606
0.997213
0.994809
0.9909
0.984843
0.975903
0.963496
0.947472
0.928234
0.906638
0.883825
0.861147
0.840268
0.823309
0.812779
0.811015
0.8192
0.83656
0.860456
0.887345
0.91389
0.937651
0.957267
0.972328
0.983116
0.990322
0.994801
0.997385
0.998769
0.999457
0.999775
0.999912
0.999968
0.999989
0.999996
0.999999
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
0.999991
0.999953
0.999838
0.999557
0.998952
0.997775
0.995669
0.992159
0.986628
0.978312
0.966447
0.950628
0.931088
0.908651
0.884498
0.859962
0.836557
0.81618
0.801229
0.794348
0.797594
0.811377
0.833903
0.861734
0.891022
0.918577
0.942326
0.961322
0.975502
0.98539
0.991823
0.995714
0.997898
0.999035
0.999584
0.999832
0.999936
0.999977
0.999992
0.999997
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1.00001
1
0.999988
0.999925
0.999742
0.999305
0.99838
0.996629
0.993596
0.988692
0.981186
0.970227
0.955122
0.935803
0.912954
0.887806
0.861764
0.8363
0.813107
0.79435
0.782642
0.780528
0.789505
0.809004
0.836221
0.867116
0.897804
0.925433
0.948407
0.966215
0.979123
0.987869
0.993393
0.996634
0.998397
0.999286
0.999702
0.999883
0.999957
0.999985
0.999995
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00001
1.00001
1.00001
0.999984
0.999891
0.999624
0.998979
0.997639
0.995166
0.990993
0.984433
0.974657
0.960786
0.942336
0.919669
0.893953
0.866714
0.839508
0.813952
0.79197
0.775968
0.768583
0.772013
0.786987
0.811872
0.842958
0.875861
0.906907
0.93374
0.955292
0.971477
0.982855
0.990325
0.99489
0.997478
0.998837
0.999499
0.999798
0.999924
0.999973
0.999991
0.999997
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00001
1.00001
1.00001
0.999982
0.99986
0.999492
0.998601
0.996767
0.993442
0.987959
0.979547
0.967313
0.950435
0.928751
0.903118
0.875099
0.846429
0.818802
0.794024
0.774262
0.762004
0.759699
0.769041
0.789859
0.819442
0.853341
0.887112
0.917522
0.942812
0.962443
0.976716
0.986426
0.992587
0.996217
0.998198
0.999198
0.999667
0.99987
0.999953
0.999984
0.999995
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00001
1.00001
1.00001
0.999984
0.999838
0.999374
0.998222
0.995849
0.991594
0.984702
0.974346
0.959612
0.939825
0.915227
0.887135
0.857419
0.827987
0.800698
0.777571
0.760894
0.753068
0.756237
0.771494
0.797668
0.830972
0.866474
0.899982
0.92888
0.952042
0.969416
0.981626
0.989644
0.994544
0.997319
0.998772
0.999475
0.999791
0.999922
0.999973
0.999991
0.999997
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00001
1.00001
1.00001
1.00002
0.999989
0.999834
0.9993
0.997918
0.995022
0.989834
0.981533
0.969263
0.952145
0.929729
0.902674
0.872691
0.841898
0.812378
0.786171
0.765434
0.752436
0.7494
0.758134
0.779033
0.80976
0.84557
0.88141
0.913623
0.940304
0.96093
0.975869
0.985995
0.992394
0.996146
0.99818
0.999199
0.999672
0.999875
0.999956
0.999985
0.999996
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1.00001
1.00001
1.00002
0.999994
0.999855
0.999305
0.997772
0.994444
0.988419
0.978816
0.964793
0.945558
0.920929
0.891956
0.860672
0.82942
0.800462
0.775971
0.758128
0.749114
0.750972
0.765152
0.791124
0.825289
0.862251
0.897228
0.927287
0.951241
0.969099
0.981568
0.989699
0.994626
0.997389
0.998818
0.999501
0.999804
0.999928
0.999975
0.999992
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
0.999999
1
1
1
1
1
1.00001
1.00001
1.00001
0.999996
0.99989
0.999397
0.997848
0.994268
0.987604
0.976923
0.961422
0.940449
0.914116
0.883803
0.851815
0.820695
0.79286
0.770533
0.75585
0.750896
0.757587
0.776869
0.807014
0.843275
0.880038
0.913111
0.940365
0.961275
0.976296
0.986385
0.992694
0.996347
0.998301
0.999263
0.999702
0.999888
0.99996
0.999987
0.999996
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00001
1.00001
1.00001
0.999989
0.999921
0.999552
0.998159
0.994587
0.987585
0.976157
0.959553
0.937307
0.909824
0.878765
0.846646
0.816192
0.789911
0.770006
0.758547
0.757585
0.7689
0.792654
0.825788
0.862718
0.898048
0.928382
0.952392
0.970128
0.982386
0.990284
0.995006
0.997611
0.998936
0.999559
0.999829
0.999939
0.99998
0.999994
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00001
1.00001
1.00001
0.99998
0.999926
0.999708
0.998636
0.995386
0.98845
0.976709
0.959461
0.936461
0.908404
0.877173
0.845458
0.816121
0.791692
0.774301
0.765996
0.768866
0.784407
0.811724
0.84647
0.882671
0.915514
0.942503
0.963042
0.977641
0.987329
0.993303
0.996707
0.998493
0.999357
0.999744
0.999905
0.999967
0.99999
0.999997
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00001
1.00001
0.999981
0.999907
0.999795
0.999136
0.996521
0.990129
0.978604
0.961253
0.938066
0.910006
0.879146
0.848312
0.820461
0.798066
0.783171
0.777871
0.784305
0.803459
0.833161
0.868051
0.902251
0.931796
0.95508
0.972123
0.983769
0.991176
0.995537
0.997901
0.999081
0.999625
0.999857
0.999949
0.999983
0.999995
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00002
1
0.9999
0.99979
0.999489
0.997718
0.992365
0.981669
0.964842
0.942076
0.914585
0.884595
0.855059
0.828972
0.808692
0.7962
0.793699
0.803307
0.825203
0.855917
0.889525
0.920683
0.946397
0.965865
0.979576
0.988572
0.994047
0.997118
0.998703
0.999456
0.999787
0.999923
0.999975
0.999993
0.999998
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00001
1.00003
0.999938
0.99976
0.999611
0.998665
0.994723
0.985499
0.969911
0.948238
0.921889
0.893235
0.865348
0.841205
0.823028
0.812789
0.812827
0.825043
0.848571
0.878863
0.909952
0.937341
0.959001
0.974776
0.985462
0.992189
0.996101
0.998194
0.999222
0.999688
0.999883
0.99996
0.999987
0.999997
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00003
1.00001
0.999801
0.99959
0.999172
0.9967
0.98947
0.975875
0.95604
0.931442
0.90458
0.878645
0.856541
0.840378
0.832187
0.834417
0.84849
0.872402
0.900944
0.92859
0.951833
0.969489
0.981871
0.989939
0.994809
0.997516
0.998896
0.999544
0.999825
0.999938
0.99998
0.999994
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00001
1.00005
0.999919
0.999615
0.99933
0.997971
0.992889
0.981905
0.964666
0.942478
0.917903
0.894193
0.874167
0.859881
0.853502
0.857482
0.872511
0.895577
0.921304
0.944951
0.96399
0.977913
0.987324
0.993224
0.99664
0.998456
0.999342
0.99974
0.999905
0.999968
0.99999
0.999998
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00004
1.00002
0.999761
0.999418
0.998614
0.995328
0.987149
0.973068
0.953927
0.932161
0.910964
0.893047
0.880502
0.875703
0.880929
0.895978
0.917137
0.939335
0.95878
0.973829
0.984443
0.991367
0.995549
0.997876
0.999063
0.999617
0.999855
0.99995
0.999984
0.999996
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00002
1.00005
0.999928
0.999596
0.99897
0.996859
0.99114
0.98032
0.964627
0.946115
0.927706
0.911962
0.901104
0.897715
0.903672
0.917879
0.93634
0.954661
0.970033
0.981502
0.989327
0.994264
0.997144
0.998686
0.999443
0.999782
0.999921
0.999974
0.999993
0.999998
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1.00001
1.00001
1.00003
1.00001
0.999803
0.999288
0.99785
0.993954
0.986023
0.973776
0.958704
0.943248
0.929761
0.920657
0.91858
0.924764
0.937413
0.952716
0.967169
0.97884
0.987274
0.992858
0.996276
0.998206
0.999205
0.999676
0.999879
0.999959
0.999987
0.999997
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1.00001
1.00002
1.00003
0.999937
0.999584
0.998586
0.995937
0.990302
0.981142
0.969371
0.956838
0.945693
0.938474
0.937572
0.943468
0.954048
0.96607
0.976959
0.985479
0.99147
0.995333
0.997636
0.998898
0.999528
0.999815
0.999934
0.999979
0.999994
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1.00001
1.00002
0.999992
0.999793
0.999142
0.997369
0.993479
0.986888
0.978031
0.96824
0.959483
0.954175
0.954143
0.959261
0.967529
0.97647
0.984316
0.990307
0.994426
0.997023
0.998531
0.999337
0.999726
0.999897
0.999965
0.99999
0.999998
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
0.999999
1
1.00001
1.00002
1.00001
0.999911
0.99952
0.99839
0.995816
0.991259
0.984851
0.977558
0.971102
0.967477
0.967869
0.971874
0.977903
0.984216
0.989641
0.993708
0.996451
0.998145
0.999109
0.99961
0.999844
0.999944
0.999982
0.999996
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00001
1.00001
0.999967
0.999752
0.999081
0.99747
0.994468
0.990064
0.984958
0.980493
0.978114
0.978537
0.981371
0.9855
0.989755
0.993363
0.996031
0.9978
0.998875
0.999472
0.999775
0.999914
0.999971
0.999991
0.999998
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1.00001
1.00001
0.999991
0.999883
0.999514
0.998568
0.996712
0.993879
0.990528
0.987588
0.986025
0.986298
0.988139
0.990818
0.993568
0.995882
0.997571
0.998678
0.999337
0.999696
0.999874
0.999954
0.999985
0.999996
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
0.999999
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1.00001
1
0.999952
0.999765
0.99925
0.998181
0.996479
0.994401
0.99253
0.991496
0.991612
0.992732
0.994393
0.996102
0.997531
0.998564
0.99923
0.99962
0.999831
0.999933
0.999976
0.999992
0.999998
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999986
0.9999
0.999641
0.999067
0.998102
0.996872
0.995721
0.995048
0.995071
0.995717
0.996706
0.997728
0.998576
0.999183
0.999569
0.999791
0.999909
0.999964
0.999988
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
0.999999
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999965
0.999844
0.999555
0.999034
0.998337
0.997657
0.997236
0.997222
0.997581
0.998147
0.998731
0.999214
0.999556
0.99977
0.999892
0.999954
0.999982
0.999994
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
0.999999
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
0.999993
0.999941
0.999802
0.999536
0.999158
0.998772
0.998524
0.998503
0.998697
0.999007
0.999327
0.999589
0.999772
0.999884
0.999947
0.999978
0.999992
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999983
0.99992
0.99979
0.999594
0.999388
0.999251
0.999235
0.999335
0.999497
0.999664
0.999798
0.999889
0.999945
0.999974
0.999989
0.999996
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
0.999999
0.999972
0.999912
0.999816
0.999712
0.99964
0.999631
0.999682
0.999763
0.999845
0.999908
0.99995
0.999976
0.999988
0.999995
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
0.999999
1
0.999999
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
0.999999
1
1
1
1
1
1
0.999993
0.999967
0.999923
0.999873
0.999839
0.999836
0.99986
0.999898
0.999934
0.999963
0.999982
0.999992
0.999998
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
0.99999
0.999971
0.999949
0.999934
0.999934
0.999945
0.999961
0.999977
0.999988
0.999995
0.999997
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
0.999999
0.999992
0.999983
0.999977
0.999977
0.999982
0.999988
0.999994
0.999997
0.999997
0.999998
0.999999
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
0.999999
1
1
1
1
1
1
1
1
0.999999
0.999996
0.999995
0.999994
0.999997
0.999998
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
0.999999
1
1
0.999999
1
1
0.999999
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
0.999999
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
0.999999
1
1
0.999999
1
1
0.999999
1
1
1
1
1
1
1
1
0.999999
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
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
0.999999
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
0.999999
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
0.999999
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
0.999999
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0.999999
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
)
;
boundaryField
{
emptyPatches_empt
{
type empty;
}
top_cyc
{
type cyclic;
}
bottom_cyc
{
type cyclic;
}
inlet_cyc
{
type cyclic;
}
outlet_cyc
{
type cyclic;
}
}
// ************************************************************************* //
| [
"tdg@debian"
] | tdg@debian | |
4dd16f0d7e8f52cea5bb59669b2f8655d7b0005f | 9299f63808d939586db6b27b86aaf68eebf472f2 | /scintilla/lexers/LexPython.cxx | aca076d9a66903016d39ceb69dba781c38a26cfc | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-scintilla",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | 1694776955/notepad2 | 80310678bc42bbbe292db527fb422b070f8ae2ea | 721d80935c0b2c010c9d9b10c49f6e65d64e3d6b | refs/heads/master | 2020-12-14T21:46:15.726617 | 2020-01-19T00:36:09 | 2020-01-19T00:36:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,769 | cxx | // This file is part of Notepad2.
// See License.txt for details about distribution and modification.
//! Lexer for Python.
#include <cassert>
#include <cstring>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
using namespace Scintilla;
#define LEX_PY 32 // Python
#define LEX_BOO 55 // Boo
#define PY_DEF_CLASS 1
#define PY_DEF_FUNC 2
#define PY_DEF_ENUM 3 // Boo
static constexpr bool IsPyStringPrefix(int ch) noexcept {
ch |= 32;
return ch == 'r' || ch == 'u' || ch == 'b' || ch == 'f';
}
static constexpr bool IsPyTripleStyle(int style) noexcept {
return style == SCE_PY_TRIPLE_STRING1 || style == SCE_PY_TRIPLE_STRING2
|| style == SCE_PY_TRIPLE_BYTES1 || style == SCE_PY_TRIPLE_BYTES2
|| style == SCE_PY_TRIPLE_FMT_STRING1 || style == SCE_PY_TRIPLE_FMT_STRING2;
}
static constexpr bool IsPyStringStyle(int style) noexcept {
return style == SCE_PY_STRING1 || style == SCE_PY_STRING2
|| style == SCE_PY_BYTES1 || style == SCE_PY_BYTES2
|| style == SCE_PY_RAW_STRING1 || style == SCE_PY_RAW_STRING2
|| style == SCE_PY_RAW_BYTES1 || style == SCE_PY_RAW_BYTES2
|| style == SCE_PY_FMT_STRING1 || style == SCE_PY_FMT_STRING2;
}
static constexpr bool IsSpaceEquiv(int state) noexcept {
// including SCE_PY_DEFAULT, SCE_PY_COMMENTLINE, SCE_PY_COMMENTBLOCK
return (state <= SCE_PY_COMMENTLINE) || (state == SCE_PY_COMMENTBLOCK);
}
#define PyStringPrefix_Empty 0
#define PyStringPrefix_Raw 1 // 'r'
#define PyStringPrefix_Unicode 2 // 'u'
#define PyStringPrefix_Bytes 4 // 'b'
#define PyStringPrefix_Formatted 8 // 'f'
// r, u, b, f
// ru, rb, rf
// ur, br, fr
static inline int GetPyStringPrefix(int ch) noexcept {
switch ((ch | 32)) {
case 'r':
return PyStringPrefix_Raw;
case 'u':
return PyStringPrefix_Unicode;
case 'b':
return PyStringPrefix_Bytes;
case 'f':
return PyStringPrefix_Formatted;
default:
return PyStringPrefix_Empty;
}
}
static inline int GetPyStringStyle(int quote, bool is_raw, bool is_bytes, bool is_fmt) noexcept {
switch (quote) {
case 1:
if (is_bytes)
return is_raw ? SCE_PY_RAW_BYTES1 : SCE_PY_BYTES1;
if (is_fmt)
return SCE_PY_FMT_STRING1;
return is_raw ? SCE_PY_RAW_STRING1 : SCE_PY_STRING1;
case 2:
if (is_bytes)
return is_raw ? SCE_PY_RAW_BYTES2 : SCE_PY_BYTES2;
if (is_fmt)
return SCE_PY_FMT_STRING2;
return is_raw ? SCE_PY_RAW_STRING2 : SCE_PY_STRING2;
case 3:
if (is_bytes)
return SCE_PY_TRIPLE_BYTES1;
if (is_fmt)
return SCE_PY_TRIPLE_FMT_STRING1;
return SCE_PY_TRIPLE_STRING1;
case 6:
if (is_bytes)
return SCE_PY_TRIPLE_BYTES2;
if (is_fmt)
return SCE_PY_TRIPLE_FMT_STRING2;
return SCE_PY_TRIPLE_STRING2;
default:
return SCE_PY_DEFAULT;
}
}
static void ColourisePyDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList keywordLists, Accessor &styler) {
const WordList &keywords = *keywordLists[0];
const WordList &keywords2 = *keywordLists[1];
const WordList &keywords_const = *keywordLists[2];
//const WordList &keywords4 = *keywordLists[3];
const WordList &keywords_func = *keywordLists[4];
const WordList &keywords_attr = *keywordLists[5];
const WordList &keywords_objm = *keywordLists[6];
const WordList &keywords_class = *keywordLists[7];
int defType = 0;
int visibleChars = 0;
bool continuationLine = false;
//const int lexType = styler.GetPropertyInt("lexer.lang.type", LEX_PY);
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart) {
if (IsPyTripleStyle(sc.state) || IsPyStringStyle(sc.state)) {
sc.SetState(sc.state);
}
defType = 0;
visibleChars = 0;
}
// Determine if the current state should terminate.
switch (sc.state) {
case SCE_PY_OPERATOR:
sc.SetState(SCE_PY_DEFAULT);
break;
case SCE_PY_NUMBER:
if (!IsDecimalNumber(sc.chPrev, sc.ch, sc.chNext)) {
sc.SetState(SCE_PY_DEFAULT);
}
break;
case SCE_PY_IDENTIFIER:
if (!iswordstart(sc.ch)) {
char s[128];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_PY_WORD);
if (strcmp(s, "def") == 0)
defType = PY_DEF_FUNC;
else if (strcmp(s, "class") == 0 || strcmp(s, "raise") == 0 || strcmp(s, "except") == 0)
defType = PY_DEF_CLASS;
//else if (strcmp(s, "enum") == 0)
// defType = PY_DEF_ENUM;
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_PY_WORD2);
} else if (keywords_const.InList(s)) {
sc.ChangeState(SCE_PY_BUILDIN_CONST);
} else if (keywords_func.InListPrefixed(s, '(')) {
sc.ChangeState(SCE_PY_BUILDIN_FUNC);
} else if (keywords_attr.InList(s)) {
sc.ChangeState(SCE_PY_ATTR);
} else if (keywords_objm.InList(s)) {
sc.ChangeState(SCE_PY_OBJ_FUNC);
} else if (defType == PY_DEF_CLASS) {
defType = 0;
sc.ChangeState(SCE_PY_CLASSNAME);
} else if (defType == PY_DEF_FUNC) {
defType = 0;
sc.ChangeState(SCE_PY_DEFNAME);
} else if (keywords_class.InList(s)) {
defType = 0;
sc.ChangeState(SCE_PY_CLASSNAME);
} else if (sc.GetNextNSChar() == '(') {
sc.ChangeState(SCE_PY_FUNCTION);
}
sc.SetState(SCE_PY_DEFAULT);
}
break;
case SCE_PY_DECORATOR:
if (!iswordchar(sc.ch))
sc.SetState(SCE_PY_DEFAULT);
break;
case SCE_PY_COMMENTLINE:
if (sc.atLineStart) {
sc.SetState(SCE_PY_DEFAULT);
}
break;
case SCE_PY_STRING1:
case SCE_PY_BYTES1:
case SCE_PY_RAW_STRING1:
case SCE_PY_RAW_BYTES1:
case SCE_PY_FMT_STRING1:
if (sc.atLineStart && !continuationLine) {
sc.SetState(SCE_PY_DEFAULT);
} else if (sc.ch == '\\' && (sc.chNext == '\\' || sc.chNext == '\"' || sc.chNext == '\'')) {
sc.Forward();
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_PY_DEFAULT);
}
break;
case SCE_PY_STRING2:
case SCE_PY_BYTES2:
case SCE_PY_RAW_STRING2:
case SCE_PY_RAW_BYTES2:
case SCE_PY_FMT_STRING2:
if (sc.atLineStart && !continuationLine) {
sc.SetState(SCE_PY_DEFAULT);
} else if (sc.ch == '\\' && (sc.chNext == '\\' || sc.chNext == '\"' || sc.chNext == '\'')) {
sc.Forward();
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_PY_DEFAULT);
}
break;
case SCE_PY_TRIPLE_STRING1:
case SCE_PY_TRIPLE_BYTES1:
case SCE_PY_TRIPLE_FMT_STRING1:
if (sc.ch == '\\') {
sc.Forward();
} else if (sc.Match(R"(''')")) {
sc.Forward(2);
sc.ForwardSetState(SCE_PY_DEFAULT);
}
break;
case SCE_PY_TRIPLE_STRING2:
case SCE_PY_TRIPLE_BYTES2:
case SCE_PY_TRIPLE_FMT_STRING2:
if (sc.ch == '\\') {
sc.Forward();
} else if (sc.Match(R"(""")")) {
sc.Forward(2);
sc.ForwardSetState(SCE_PY_DEFAULT);
}
break;
}
// Determine if a new state should be entered.
if (sc.state == SCE_PY_DEFAULT) {
if (sc.ch == '#') {
sc.SetState(SCE_PY_COMMENTLINE);
} else if (sc.Match(R"(''')")) {
sc.SetState(SCE_PY_TRIPLE_STRING1);
sc.Forward(2);
} else if (sc.Match(R"(""")")) {
sc.SetState(SCE_PY_TRIPLE_STRING2);
sc.Forward(2);
} else if (sc.ch == '\'') {
sc.SetState(SCE_PY_STRING1);
} else if (sc.ch == '\"') {
sc.SetState(SCE_PY_STRING2);
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_PY_NUMBER);
} else if (IsPyStringPrefix(sc.ch)) {
int offset = 0;
int prefix = GetPyStringPrefix(sc.ch);
bool is_bytes = prefix == PyStringPrefix_Bytes;
bool is_fmt = prefix == PyStringPrefix_Formatted;
bool is_raw = prefix == PyStringPrefix_Raw;
if (sc.chNext == '\"' || sc.chNext == '\'') {
offset = 1;
} else if (IsPyStringPrefix(sc.chNext) && (sc.GetRelative(2) == '\"' || sc.GetRelative(2) == '\'')) {
prefix = GetPyStringPrefix(sc.chNext);
offset = 2;
is_bytes = (is_bytes && prefix == PyStringPrefix_Raw) || (is_raw && prefix == PyStringPrefix_Bytes);
is_fmt = (is_fmt && prefix == PyStringPrefix_Raw) || (is_raw && prefix == PyStringPrefix_Formatted);
is_raw = (is_raw && prefix != PyStringPrefix_Raw) || (!is_raw && prefix == PyStringPrefix_Raw);
if (!(is_bytes || is_fmt || is_raw)) {
--offset;
sc.ForwardSetState(SCE_PY_IDENTIFIER);
}
}
if (!offset) {
sc.SetState(SCE_PY_IDENTIFIER);
} else {
sc.Forward(offset);
if (sc.Match(R"(''')")) {
sc.ChangeState(GetPyStringStyle(3, is_raw, is_bytes, is_fmt));
sc.Forward(2);
} else if (sc.Match(R"(""")")) {
sc.ChangeState(GetPyStringStyle(6, is_raw, is_bytes, is_fmt));
sc.Forward(2);
} else if (sc.ch == '\'') {
sc.ChangeState(GetPyStringStyle(1, is_raw, is_bytes, is_fmt));
} else if (sc.ch == '\"') {
sc.ChangeState(GetPyStringStyle(2, is_raw, is_bytes, is_fmt));
}
}
} else if (iswordstart(sc.ch)) {
sc.SetState(SCE_PY_IDENTIFIER);
} else if (sc.ch == '@') {
if (visibleChars == 1 && iswordstart(sc.chNext))
sc.SetState(SCE_PY_OPERATOR);
else
sc.SetState(SCE_PY_DECORATOR);
} else if (isoperator(sc.ch) || sc.ch == '`') {
sc.SetState(SCE_PY_OPERATOR);
if (defType > 0 && (sc.ch == '(' || sc.ch == ':'))
defType = 0;
}
}
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continuationLine = true;
continue;
}
}
if (!(isspacechar(sc.ch) || IsSpaceEquiv(sc.state))) {
visibleChars++;
}
continuationLine = false;
}
sc.Complete();
}
#define IsCommentLine(line) IsLexCommentLine(line, styler, MultiStyle(SCE_PY_COMMENTLINE, SCE_PY_COMMENTBLOCK))
static inline bool IsQuoteLine(Sci_Position line, const Accessor &styler) noexcept {
const int style = styler.StyleAt(styler.LineStart(line));
return IsPyTripleStyle(style);
}
// based on original folding code
static void FoldPyDoc(Sci_PositionU startPos, Sci_Position length, int, LexerWordList, Accessor &styler) {
const Sci_Position maxPos = startPos + length;
const Sci_Position docLines = styler.GetLine(styler.Length()); // Available last line
const Sci_Position maxLines = (maxPos == styler.Length()) ? docLines : styler.GetLine(maxPos - 1); // Requested last line
// property fold.quotes.python
// This option enables folding multi-line quoted strings when using the Python lexer.
const bool foldQuotes = styler.GetPropertyInt("fold.quotes.python", 1) != 0;
// Backtrack to previous non-blank line so we can determine indent level
// for any white space lines (needed esp. within triple quoted strings)
// and so we can fix any preceding fold level (which is why we go back
// at least one line in all cases)
int spaceFlags = 0;
Sci_Position lineCurrent = styler.GetLine(startPos);
int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, nullptr);
while (lineCurrent > 0) {
lineCurrent--;
indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, nullptr);
if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG) && (!IsCommentLine(lineCurrent)) &&
(!IsQuoteLine(lineCurrent, styler))) {
break;
}
}
int indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK;
// Set up initial loop state
startPos = styler.LineStart(lineCurrent);
int prev_state = SCE_PY_DEFAULT;
if (lineCurrent >= 1) {
prev_state = styler.StyleAt(startPos - 1);
}
int prevQuote = foldQuotes && IsPyTripleStyle(prev_state);
// Process all characters to end of requested range or end of any triple quote
//that hangs over the end of the range. Cap processing in all cases
// to end of document (in case of unclosed quote at end).
while ((lineCurrent <= maxLines) || prevQuote) {
// Gather info
int lev = indentCurrent;
Sci_Position lineNext = lineCurrent + 1;
int indentNext = indentCurrent;
int quote = false;
if (lineNext <= docLines) {
// Information about next line is only available if not at end of document
indentNext = styler.IndentAmount(lineNext, &spaceFlags, nullptr);
const Sci_Position lookAtPos = (styler.LineStart(lineNext) == styler.Length()) ? styler.Length() - 1 : styler.LineStart(lineNext);
const int style = styler.StyleAt(lookAtPos);
quote = foldQuotes && IsPyTripleStyle(style);
}
const int quote_start = (quote && !prevQuote);
const int quote_continue = (quote && prevQuote);
if (!quote || !prevQuote) {
indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK;
}
if (quote) {
indentNext = indentCurrentLevel;
}
if (indentNext & SC_FOLDLEVELWHITEFLAG) {
indentNext = SC_FOLDLEVELWHITEFLAG | indentCurrentLevel;
}
if (quote_start) {
// Place fold point at start of triple quoted string
lev |= SC_FOLDLEVELHEADERFLAG;
} else if (quote_continue || prevQuote) {
// Add level to rest of lines in the string
lev = lev + 1;
}
// Skip past any blank lines for next indent level info; we skip also
// comments (all comments, not just those starting in column 0)
// which effectively folds them into surrounding code rather
// than screwing up folding. If comments end file, use the min
// comment indent as the level after
int minCommentLevel = indentCurrentLevel;
while (!quote
&& (lineNext < docLines)
&& ((indentNext & SC_FOLDLEVELWHITEFLAG) || (lineNext <= docLines && IsCommentLine(lineNext)))) {
if (IsCommentLine(lineNext) && indentNext < minCommentLevel) {
minCommentLevel = indentNext;
}
lineNext++;
indentNext = styler.IndentAmount(lineNext, &spaceFlags, nullptr);
}
const int levelAfterComments = ((lineNext < docLines) ? indentNext & SC_FOLDLEVELNUMBERMASK : minCommentLevel);
const int levelBeforeComments = (indentCurrentLevel > levelAfterComments) ? indentCurrentLevel : levelAfterComments;
// Now set all the indent levels on the lines we skipped
// Do this from end to start. Once we encounter one line
// which is indented more than the line after the end of
// the comment-block, use the level of the block before
Sci_Position skipLine = lineNext;
int skipLevel = levelAfterComments;
while (--skipLine > lineCurrent) {
const int skipLineIndent = styler.IndentAmount(skipLine, &spaceFlags, nullptr);
if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments &&
!(skipLineIndent & SC_FOLDLEVELWHITEFLAG) &&
!IsCommentLine(skipLine)) {
skipLevel = levelBeforeComments;
}
styler.SetLevel(skipLine, skipLevel);
}
// Set fold header on non-quote line
if (!quote && !(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
}
// Keep track of triple quote state of previous line
prevQuote = quote;
// Set fold level for this line and move to next line
styler.SetLevel(lineCurrent, lev & ~SC_FOLDLEVELWHITEFLAG);
indentCurrent = indentNext;
lineCurrent = lineNext;
}
// NOTE: Cannot set level of last line here because indentCurrent doesn't have
// header flag set; the loop above is crafted to take care of this case!
//styler.SetLevel(lineCurrent, indentCurrent);
}
LexerModule lmPython(SCLEX_PYTHON, ColourisePyDoc, "python", FoldPyDoc);
| [
"zufuliu@gmail.com"
] | zufuliu@gmail.com |
f27c5277e45070541c545713656a13cd493abf42 | aa69f4680f318295547d1ce76e471a2d53251a02 | /Users/Giles/Downloads/Traffic Simulator 2017/gameengine/GUI/Button.cpp | b489342f7de987550c0b38813086e84a8635862e | [] | no_license | GilesPenfold/Traffic-Simulator-2017 | 66c9048eaa1c5abd015f34856552a361670f0d67 | 4baf0cbe666066ed0d81e8b22c54111446a9bbc9 | refs/heads/master | 2021-01-02T09:45:09.691614 | 2017-10-07T09:13:30 | 2017-10-07T09:13:30 | 99,288,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,332 | cpp | #include "Button.h"
Button::Button(glm::vec3 cen, glm::vec2 dim, Texture* tex, Shader* guiShader){
this->pos[0] = glm::vec3(cen.x - dim.x/2, cen.y - dim.y/2, 0);
this->pos[1] = glm::vec3(cen.x + dim.x/2, cen.y - dim.y/2, 0);
this->pos[2] = glm::vec3(cen.x + dim.x/2, cen.y + dim.y/2, 0);
this->pos[3] = glm::vec3(cen.x - dim.x/2, cen.y + dim.y/2, 0);
this->tex[0] = glm::vec2(0, 1);
this->tex[1] = glm::vec2(1, 1);
this->tex[2] = glm::vec2(1, 0);
this->tex[3] = glm::vec2(0, 0);
this->normal[0] = glm::vec3(0.0, 0.0, -1.0);
this->normal[1] = glm::vec3(0.0, 0.0, -1.0);
this->normal[2] = glm::vec3(0.0, 0.0, -1.0);
this->normal[3] = glm::vec3(0.0, 0.0, -1.0);
unsigned int buttonIndices[] = { 0,1,2,0,2,3 };
this->buttonVerts = new Vert [4]
{
Vert(this->pos[0], this->tex[0], this->normal[0]),
Vert(this->pos[1], this->tex[1], this->normal[1]),
Vert(this->pos[2], this->tex[2], this->normal[2]),
Vert(this->pos[3], this->tex[3], this->normal[3])
};
this->button = new Mesh(buttonVerts, sizeof(buttonVerts), buttonIndices, sizeof(buttonIndices));
this->texture = tex;
this->isSelected = 0;
this->GUIShader = guiShader;
}
void Button::Draw(){
this->GUIShader->Bind();
this->GUIShader->UpdateGUI(this->isSelected);
this->texture->Bind(0);
this->button->Draw();
}
void Button::Update(){
}
| [
"gtpenfold@hotmail.co.uk"
] | gtpenfold@hotmail.co.uk |
8aaf5cef261471db862c68af0c2ca9ce8c723b65 | 1c24264c0884b709a7943f30dd157d92168581d0 | /learncpp.com/09_Operator_Overloading/Question02/src/Main.cpp | aa49eee1f05708db8d214902f7686b464318e922 | [
"MIT"
] | permissive | KoaLaYT/Learn-Cpp | 56dbece554503ca2e0d1bea35ae4ddda3c03f236 | 0bfc98c3eca9c2fde5bff609c67d7e273fde5196 | refs/heads/master | 2020-12-22T13:08:02.582113 | 2020-10-26T02:33:24 | 2020-10-26T02:33:24 | 236,792,487 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 610 | cpp | /**
* Chapter 9 :: Question 2
*
* a simple operator overload practice
*
* KoaLaYT 17:48 02/02/2020
*
*/
#include "Average.h"
int main() {
Average avg{};
avg += 4;
std::cout << avg << '\n'; // 4 / 1 = 4
avg += 8;
std::cout << avg << '\n'; // (4 + 8) / 2 = 6
avg += 24;
std::cout << avg << '\n'; // (4 + 8 + 24) / 3 = 12
avg += -10;
std::cout << avg << '\n'; // (4 + 8 + 24 - 10) / 4 = 6.5
(avg += 6) += 10; // 2 calls chained together
std::cout << avg << '\n'; // (4 + 8 + 24 - 10 + 6 + 10) / 6 = 7
Average copy{avg};
std::cout << copy << '\n';
return 0;
}
| [
"hytohyeah@outlook.com"
] | hytohyeah@outlook.com |
95216b4ecb2775d81abb45b593a88921ad7b6587 | fe91ffa11707887e4cdddde8f386a8c8e724aa58 | /third_party/blink/renderer/core/frame/scheduling.h | b2f35f168d71719ff5bee185f94bcaccfdaf36cf | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | akshaymarch7/chromium | 78baac2b45526031846ccbaeca96c639d1d60ace | d273c844a313b1e527dec0d59ce70c95fd2bd458 | refs/heads/master | 2023-02-26T23:48:03.686055 | 2020-04-15T01:20:07 | 2020-04-15T01:20:07 | 255,778,651 | 2 | 1 | BSD-3-Clause | 2020-04-15T02:04:56 | 2020-04-15T02:04:55 | null | UTF-8 | C++ | false | false | 965 | h | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_SCHEDULING_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_SCHEDULING_H_
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
class IsInputPendingOptions;
// Low-level scheduling primitives for JS scheduler implementations.
class Scheduling : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
bool isInputPending(ScriptState*, const IsInputPendingOptions* options) const;
bool isFramePending() const;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_SCHEDULING_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
9fb278aad126cd69b377ee73bde177442c357b94 | 4d33c090428407d599a4c0a586e0341353bcf8d7 | /trunk/net/ListenSock.h | b516f5943064571ecc49572e6a666baa4acf9d3f | [] | no_license | yty/bud | f2c46d689be5dfca74e239f90570617b3471ea81 | a37348b77fb2722c73d972a77827056b0b2344f6 | refs/heads/master | 2020-12-11T06:07:55.915476 | 2012-07-22T21:48:05 | 2012-07-22T21:48:05 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 975 | h | /********************************************************************
author : cpzhang
created: 2012Äê-2ÔÂ-7ÈÕ 11:37
*********************************************************************/
#ifndef __ListenSock_h__
#define __ListenSock_h__
#include "TCPSock.h"
namespace Shannon
{
class _NET_EXPORT_ ListenSock: public TCPSocket
{
public:
ListenSock();
/// Prepares to receive connections on a specified port (bind+listen)
void init( u16 port );
/// Prepares to receive connections on a specified address/port (useful when the host has several addresses)
void init( const Address& addr );
/// Sets the number of the pending connections queue, or -1 for the maximum possible value.
void setBacklog( s32 backlog );
/// Blocks until an incoming connection is requested, accepts it, and creates a new socket (you have to delete it after use)
TCPSocket *accept();
private:
bool _Bound;
s32 _BackLog;
};
}
#endif //__ListenSock_h__
| [
"297191409@qq.com"
] | 297191409@qq.com |
8c46453a0ef73b1c89873a11f1b070336ed36f60 | 4ea408c28d642c970e4a26b24961300c650620ae | /Homework/Review/main.cpp | d656b5ad233ab2dba30844b4b899934fff8185cc | [] | no_license | joseroman1/CSC_17A_48983 | fd047bc53dff225fa6e01070ddf7f26ccfc2812a | 7cff1ae5265f95832a333f1b8528b634d1036905 | refs/heads/master | 2021-01-22T05:01:04.665119 | 2015-12-08T20:35:11 | 2015-12-08T20:35:11 | 42,428,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,029 | cpp | /*
* File: main.cpp
* Author: Jose Roman
* Purpose: Review Assignment
* Modified on September 13th, 2015
*/
//System Libraries
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
//User Libraries
//Global Constants
//Function Prototypes
void problem1 ();
void problem2 ();
void problem3 ();
void problem4 ();
void problem5 ();
void problem6 ();
void problem7 ();
void sBoard(char []);
//Problem 6
int cNumber(int [], int);
void printArray(int [],int);
//Problem 7
void delete_repeats(char [],int);
void printAray(char [],int);
//Execution Begins Here
int main(int argc, char** argv) {
//Declare menu variable choice
char choice;
//Repeat the menu
do{
//General Menu Format
//Display the selection
cout<<"Review Assignment Menu."<<endl;
cout<<"Type 1 to solve Savitch 8th Ed. Chapter 4 Problem 1"<<endl;
cout<<"Type 2 to solve Gaddis 7th Ed. Chapter 5 Problem 6"<<endl;
cout<<"Type 3 to solve Gaddis 8th Ed. Chapter 8 Problem 3"<<endl;
cout<<"Type 4 to solve Gaddis 8th Ed. Chapter 7 Problem 1"<<endl;
cout<<"Type 5 to solve Savitch 8th Ed. Chapter 7 Problem 10"<<endl;
cout<<"Type 6 to solve Savitch 9th Ed. Chapter 7 Problem 2"<<endl;
cout<<"Type 7 to solve Savitch 9th Ed. Chapter 7 Problem 3"<<endl;
cout<<"Type anything else to quit with no solutions."<<endl;
//Read the choice
cin>>choice;
//Solve a problem that has been chosen.
switch(choice){
case '1':problem1();break;
case '2':problem2();break;
case '3':problem3();break;
case '4':problem4();break;
case '5':problem4();break;
case '6':problem4();break;
case '7':problem4();break;
default: cout<<"Exit?"<<endl;
};
}while(choice>='1'&&choice<='7');
//Exit right stage
return 0;
}
//*********** problem 1 **********/
void problem1(){
//Declare variables
float L1, W1, L2, W2, A1, A2;
//Prompt for Input
cout<<"This program will determine which rectangle has the greater Area."<<endl;
cout<<"Enter length of First rectangle."<<endl;
cin>>L1;//Length of first rectangle
cout<<"Enter width of First rectangle."<<endl;
cin>>W1;//Width of first rectangle
cout<<"Enter length of Second rectangle."<<endl;
cin>>L2;//Length of Second rectangle
cout<<"Enter width of Second rectangle."<<endl;
cin>>W2;//Width of Second rectangle
//Calculate Area
A1=L1*W1;//Area of first rectangle
A2=L2*W2;//Area of Second rectangle
//Output results with IF
if(A1>A2)
cout<<"First rectangle has greater area."<<endl;
else if(A1==A2)
cout<<"Both rectangles have equal area."<<endl;
else
cout<<"Second rectangle has greater area."<<endl;
}
//*********** problem 2 **********/
void problem2(){
//Declare Variable
float Speed,hours,dist;
cout<<"I will calculate the distance you have traveled. "<<endl;
cout<<"Enter the speed of your vehicle (in Miles per Hours)"<<endl;
cin>>Speed;
cout<<"Then input how many hours you have traveled.(Greater than 1 hour)"<<endl;
cin>>hours;
dist=Speed*hours;
if(Speed<0 || hours<=1)
cout<<"Error. Please enter positive speeds and greater than or equal to 1."<<endl;
else{
cout<<" Hour Distance Traveled\n ----------------------------"<<endl;
for(int x=1;x<=hours;x++){
dist=Speed*x;
cout<<" "<<x<<"\t "<<setw(10)<<right<<dist<<" miles"<<endl;
}
}
}
//*********** problem 3 **********\
void problem3(){
string name[5];
int sale[5];
int i,hSel=0,hName,lSel=0,lName;
name[0] = "Mild";
name[1] = "Medium";
name[2] = "Sweet";
name[3] = "Hot";
name[4] = "Zesty";
int total=0;
for(i=0;i<=4;i++){
cout<<"Enter number of sold "<<name[i]<<" jars: ";
cin>>sale[i];
total = total + sale[i];
if(i==0){
hSel=sale[i];
hName=i;lSel=sale[i];
lName = i;
}if(hSel<sale[i]){
hSel=sale[i];
hName=i;
}if(lSel>sale[i]){
lSel=sale[i];
lName=i; }
}
cout<<"There were sold: "<<endl;
for(i=0;i<=4;i++){
cout<<sale[i]<<" "<<name[i]<<" jars"<<""<<endl;
}
cout<<"Total sales: "<<total<<" jars"<<endl;
cout<<"Highest sales: "<<hSel<<" ("<<name[hName]<<" salsa)"<<endl;
cout<<"Lowest sales: "<<lSel<<" ("<<name[lName]<<" salsa)"<<endl;
}
//************** Problem 4 ***********/
void problem4(){
//Declare variables
const int SIZE=10;
int a[SIZE];
int min,max;
//Prompt user
cout<<"Input 10 random numbers. Press return after entering each number."<<endl;
for(int i=0;i<10;i++){
cin>>a[i];//User input
}
min=a[0];
max=a[0];
//Finding the max and minimum of the input
for(int i=1;i<10;i++){
if(min>a[i]){
min=a[i];
}else if(max<a[i]){
max=a[i];
}
}
//Output the results
cout<<"Min "<<min<<endl;
cout<<"Max "<<max<<endl;
}
//************** Problem 5 ***********/
void problem5(){
const char SIZE=9;
char board[SIZE];
int nMoves = 0;
char wTurn = 'X';
int move;
for (int i=0;i<9;i++){
board[i]= '1' + i;
}
while (nMoves < 9){
sBoard(board);
cout<<"Enter move: "<<endl;
cin>>move;
if((move < 1) || (move > 9))
cout<<"Invalid move, try again"<<endl;
else{
move--;
if ((board[move]=='X') || (board[move]=='O'))
cout<<"That space is taken. "<<endl;
else{
board[move]= wTurn;
//Switch turn
if(wTurn == 'X')
wTurn = 'O';
else
wTurn = 'X';
nMoves++;
}
}
}
//Display Board
sBoard(board);
cout<<endl<<"Game over.."<<endl;
}
void sBoard(char board[]){
cout<<endl;
for (int i=0;i<9;i++){
cout<<board[i]<<" ";
if (((i+1) % 3) == 0)cout<<endl;
}
cout<<endl;
}
//************** Problem 6 ***********/
void problem6(){
//Declare Variables
int SIZE = 5;
int array[SIZE];
int nof2 = 0;//Number of two
cout<<"Give me "<<SIZE<<" Numbers. Press Return after entering each number"<<endl;
cin>>array[0]>>array[1]>>array[2]>>array[3]>>array[4];
//Print array
printArray (array, SIZE);
//Count the number of two
nof2 = cNumber(array, SIZE);
cout<<"The number of 2's in the array is : "<<nof2<<endl;
}
void printArray(int a[],int SIZE){
for(int i=0;i<SIZE;i++)
cout<<a[i]<<" ";
cout<<endl;
}
int cNumber(int a[],int SIZE){
int counter =0;
for (int i=0;i<SIZE;i++){
if(a[i] == 2)
counter++;
}
return counter;
}
//************** Problem 7 ***********/
void problem7(){
char SIZE=10;
char array[SIZE];
array[0] = 'a';
array[1] = 'b';
array[2] = 'a';
array[3] = 'c';
int sizes = 4;
cout<<"Before removing: ";
printAray(array,sizes);
delete_repeats(array,sizes);
cout<<"After removing: ";
printAray(array,sizes);
}
void printAray(char a[],int sizes){
for(int i=0;i<sizes;i++)
cout<<a[i]<<" ";
cout<<endl;
}
void delete_repeats(char a[],int sizes){
//Go through and find the repeated characters
for(int i=0;i<sizes;i++){
for(int j=i+1;j<sizes;j++){
//.if the character is repeated
if(a[i] == a[j])
a[j]= 0;
else
continue;
}
}
//Go throught and find the deleted character
for(int i = 0;i<sizes;i++){
//empty space move it forward
if(a[i] == 0){
a[i] = a[i+1];
a[i+1] = 0;
}
else
continue;
}
}
| [
"joseroman@outlook.com"
] | joseroman@outlook.com |
7558c17efb110d07f5b33babc128e6d861761533 | 7d1bbcfc89bcc60614a2a2338e74d8b0fa48669f | /nowcoder/baidu_2017spring_dudu_go_home_2.cpp | c803a14d54d7643ac2068d5a91b54d6212d01b40 | [] | no_license | Nana0606/basic-algorithms | 3dcfb6554fe28fb8ea007c76e2e0b1aac9012035 | f78317a934d945c1f468c28a7fc65d1560fc880f | refs/heads/master | 2020-03-23T20:09:21.548501 | 2019-05-27T01:47:29 | 2019-05-27T01:47:29 | 142,024,882 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 691 | cpp | # include <iostream>
# include <vector>
# include <algorithm>
using namespace std;
//题目:度度熊回家
//网址:https://www.nowcoder.com/question/next?pid=4998655&qid=95824&tid=206443599
int main(){
int N;
cin >> N;
int value;
vector<int> vec;
int len_N = N;
while (N-- > 0){
cin >> value;
vec.push_back(value);
}
int sum = 0; //表示全部距离
for (int i = 0; i < len_N-1; i++){
sum += abs(vec[i + 1] - vec[i]);
}
int max_diff = 0;
for (int i = 1; i < len_N - 1; i++){
max_diff = max(max_diff, abs(vec[i + 1] - vec[i]) + abs(vec[i] - vec[i - 1]) - abs(vec[i + 1] - vec[i - 1]));
}
cout << sum - max_diff << endl;
return 0;
} | [
"“paopaotanglee@126.com”"
] | “paopaotanglee@126.com” |
a4f55acf8e5cf2aedffbe646b9238eba7d6ed982 | 9a255e0549bd3d5ae227156db37f4a0b4ee652da | /supervisor/src/network/bsdsocket/wrapper/events/IncomingMessage.cpp | 649629a618c9498dba658c07b182d0ed37a58413 | [
"MIT"
] | permissive | mdziekon/eiti-tin-ftp-stattr | 3a01de21010760debd6a878d04374ba5305e57e2 | c8b8c119f6731045f90281d607b98d7a5ffb3bd2 | refs/heads/master | 2021-01-17T20:59:57.805343 | 2015-06-09T19:24:59 | 2015-06-09T19:24:59 | 34,629,736 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | cpp | #include "IncomingMessage.hpp"
#include "../ClientVisitor.hpp"
using tin::network::bsdsocket::wrapper::events::IncomingMessage;
IncomingMessage::IncomingMessage(
const std::string& ip,
const unsigned int& port,
const std::string& message
):
ip(ip),
port(port),
message(message)
{}
void IncomingMessage::accept(tin::network::bsdsocket::wrapper::ClientVisitor& i)
{
i.visit(*this);
}
| [
"dani@notebookcheck.pl"
] | dani@notebookcheck.pl |
4fb457dae2743daed6748cfaf57aa78c6ea866d5 | 2dd86497f804773a5de778c6efc342d86ad81cb8 | /40-protocol/gb28181client/include/recinfo.h | 727628d7b405ce9029e48d085459100d65f8a347 | [] | no_license | px41833/wangjin | 071e2efe94c233c0317caf6daee77debde6e791d | 5c400d7605ae6060f2367bfa14bbc02d007c5802 | refs/heads/master | 2020-06-16T01:05:03.522914 | 2018-02-06T08:43:28 | 2018-02-06T08:43:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,533 | h | #ifndef __REC_INFO_H__
#define __REC_INFO_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "xmlparser.h"
#include "gb.h"
class CRecordInfoList
{
public:
/// recorder response item node
class CNode
{
public:
int id;
void * ctx;
int sn;
int sum_num;
int current_sum_num;
GB::CGbRecordItem *item;
CNode * next;
GB::CGbRecordItem * last_item;
/// construction & deconstruction
CNode();
~CNode();
void set_ctx_sn(void * ctx, int sn);
void set_sum_num(int sum_num);
int add_record_info_item(CRecordInfoItem *item);
/// src的值复制给dst
void value_copy_to(GB::CGbRecordItem *dst, GB::CGbRecordItem *src);
void sort_by_start_time();
void set_id(int in_id);
};
CRecordInfoList();
~CRecordInfoList();
int insert_ctx_sn(void * ctx, int sn);
/// delete specified query by ctx and sn
void delete_ctx(int sn);
int add_record_info(int sn, CRecordInfoItem *item, CNode **out_node = NULL);
void printf_all();
CNode *find_node_by_sn(int sn);
/*
* find specified node by ctx and sn
*/
CNode *find_node(void *ctx, int sn);
void sort_by_start_time( int sn );
void set_id_sn( int id, int sn);
void shedule(uint64_t time);
private:
CNode *head;
CNode *current;
CNode *tail;
int list_len;
const static int MAX_NODE_COUNT;
};
#endif /// __REC_INFO_H__
| [
"yrj2009yrj@qq.com"
] | yrj2009yrj@qq.com |
625d09bf9dc4a11d345ff934371441b5520b0499 | 356d45e683ddf4834f85619e574125675539b9de | /HelloTriangle/HelloTriangle/Camera.cpp | 4d2c4dfe0423b17bca81778d04b9a7dd1117bc56 | [] | no_license | Iteevo/HelloCG | 3f954c8e977f4e31084de0d1911d9b8d4c866004 | d9420ca00b07b648e50b5273c199536913ac75ec | refs/heads/master | 2020-12-07T11:13:05.160144 | 2020-01-09T03:15:03 | 2020-01-09T03:15:03 | 232,710,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 146 | cpp | //
// Camera.cpp
// HelloTriangle
//
// Created by dn on 6/10/19.
// Copyright © 2019 Iteevo. All rights reserved.
//
#include "Camera.hpp"
| [
""
] | |
f0be028af30e7235eabdc6a83c479396bc15ea44 | 8556aae0afcee3323801cf4de2008f1dcdadbbfa | /src/27/ciagi.cpp | d2b35648f0898f2753785292f0bafb918af4961d | [
"WTFPL"
] | permissive | AdamSiekierski/cpp | 4ce080c71882e328286629fa188634802d654776 | 09b9a46b44ecce5cc1d6e0cb9d1c689b350563d5 | refs/heads/main | 2023-02-26T10:10:23.715457 | 2021-02-02T18:11:29 | 2021-02-02T18:11:29 | 307,671,598 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 673 | cpp | #include <iostream>
int main()
{
std::cout << "ciag 1: ";
int i = 12;
while (i >= -12)
{
std::cout << i << " ";
i -= 4;
}
std::cout << "\nciag 2: ";
i = 12;
while (i >= -12)
{
if (i != 0)
std::cout << i << " ";
i -= 4;
}
std::cout << "\nciag 3:\n"
<< "Podaj długość ciągu: ";
int n;
std::cin >> n;
i = -3;
while (n > 0)
{
std::cout << i << " ";
i *= -2;
n -= 1;
}
std::cout << "\nciag 4:\n"
<< "Podaj dlugość ciągu: ";
std::cin >> n;
i = -10;
int sum = 0;
while (n > 0)
{
sum += i;
i += 6;
n -= 1;
}
std::cout << sum;
return 0;
} | [
"a@siekierski.ml"
] | a@siekierski.ml |
3dace18713df1a8c0537d143d8558b0bb30d3f27 | 038fd9e7f469c4e7f7343a10c0183d60050f4b4e | /couchbase-sys/libcouchbase/src/jsparse/parser.h | d19dce07bcc46cc31ff8e4234e40daffeb3a1782 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | tinh-phan/couchbase-rs | 32abc0119e11da7c8c06e7d610e364a42c493a6d | a6160df405302ea40848efe4751ab7b46dd692ca | refs/heads/master | 2020-10-01T00:51:43.324887 | 2019-12-11T16:54:31 | 2019-12-11T16:54:31 | 227,413,790 | 0 | 0 | Apache-2.0 | 2019-12-11T16:41:48 | 2019-12-11T16:41:47 | null | UTF-8 | C++ | false | false | 4,908 | h | /**
* Copyright 2013-2019 Couchbase, 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 LCB_VIEWROW_H_
#define LCB_VIEWROW_H_
#include <libcouchbase/couchbase.h>
#include "contrib/jsonsl/jsonsl.h"
#include "contrib/lcb-jsoncpp/lcb-jsoncpp.h"
#include <string>
namespace lcb
{
namespace jsparse
{
struct Parser;
struct Row {
lcb_IOV docid;
lcb_IOV key;
lcb_IOV value;
lcb_IOV row;
lcb_IOV geo;
};
struct Parser {
enum Mode { MODE_VIEWS, MODE_N1QL, MODE_FTS, MODE_ANALYTICS, MODE_ANALYTICS_DEFERRED };
struct Actions {
/**
* Called when a row is received.
* This is a row of view data. You can parse this as JSON from your
* favorite decoder/converter
*/
virtual void JSPARSE_on_row(const Row &) = 0;
/**
* A JSON parse error occured. The payload will contain string data. This
* may be JSON (but this is not likely).
* The callback will be delivered twice. First when the error is noticed,
* and second at the end (instead of a COMPLETE callback)
*/
virtual void JSPARSE_on_error(const std::string &buf) = 0;
/**
* All the rows have been returned. In this case, the data is the 'meta'.
* This is a valid JSON payload which was returned from the server.
* The "rows" : [] array will be empty.
*/
virtual void JSPARSE_on_complete(const std::string &meta) = 0;
virtual ~Actions() {}
};
/**
* Creates a new vrow context object.
* You must set callbacks on this object if you wish it to be useful.
* You must feed it data (calling vrow_feed) as well. The data may be fed
* in chunks and callbacks will be invoked as each row is read.
*/
Parser(Mode mode, Actions *actions_);
~Parser();
/**
* Feeds data into the vrow. The callback may be invoked multiple times
* in this function. In the context of normal lcb usage, this will typically
* be invoked from within an http_data_callback.
*/
void feed(const char *s, size_t n);
void feed(const std::string &s)
{
feed(s.c_str(), s.size());
}
/**
* Parse the row buffer into its constituent parts. This should be called
* if you want to split the row into its basic 'docid', 'key' and 'value'
* fields
* @param vp The parser to use
* @param vr The row to parse. This assumes the row's "row" field is properly
* set.
*/
void parse_viewrow(Row &vr);
/**
* Get the raw contents of the current buffer. This can be used to debug errors.
*
* Note that the buffer may be partial or malformed or otherwise unsuitable
* for structured inspection, but may help human observers debug problems.
*
* @param out The iov structure to contain the buffer/offset
*/
void get_postmortem(lcb_IOV &out) const;
inline const char *get_buffer_region(size_t pos, size_t desired, size_t *actual);
inline void combine_meta();
inline static const char *jprstr_for_mode(Mode);
jsonsl_t jsn; /**< Parser for the row itself */
jsonsl_t jsn_rdetails; /**< Parser for the row details */
jsonsl_jpr_t jpr; /**< jsonpointer match object */
std::string meta_buf; /**< String containing the skeleton (outer layer) */
std::string current_buf; /**< Scratch/read buffer */
std::string last_hk; /**< Last hashkey */
lcb_U8 mode;
/* flags. This should be an int with a bunch of constant flags */
lcb_U8 have_error;
lcb_U8 initialized;
lcb_U8 meta_complete;
unsigned rowcount;
/* absolute position offset corresponding to the first byte in current_buf */
size_t min_pos;
/* minimum (absolute) position to keep */
size_t keep_pos;
/**
* size of the metadata header chunk (i.e. everything until the opening
* bracket of "rows" [
*/
size_t header_len;
/**
* Position of last row returned. If there are no subsequent rows, this
* signals the beginning of the metadata trailer
*/
size_t last_row_endpos;
/**
* std::string to contain parsed document ID.
*/
Json::Value cxx_data;
/* callback to invoke */
Actions *actions;
};
} // namespace jsparse
} // namespace lcb
#endif /* LCB_VIEWROW_H_ */
| [
"michael@nitschinger.at"
] | michael@nitschinger.at |
207f8f235e1bd26d903ef8b9e9023db4105e0f44 | 31589435071cbff4c5e95b357d8f3fa258f43269 | /PPTVForWin8/ppbox_1.2.0/src/p2p/server_mod/index_server_data_migration/statistic/DownloadDriverStatistic.h | 32d0176f6953f47f42b888d5837be83db6c3c7ac | [] | no_license | huangyt/MyProjects | 8d94656f41f6fac9ae30f089230f7c4bfb5448ac | cd17f4b0092d19bc752d949737c6ed3a3ef00a86 | refs/heads/master | 2021-01-17T20:19:35.691882 | 2013-05-03T07:19:31 | 2013-05-03T07:19:31 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,111 | h | #pragma once
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <map>
#include <string>
#include "framework/mswin/ShareMemory.h"
#include "SpeedInfoStatistic.h"
#include "StatisticStructs.h"
#include "HttpDownloaderStatistic.h"
using namespace std;
using namespace framework::mswin;
namespace statistic
{
class DownloadDriverStatistic
: public boost::noncopyable
, public boost::enable_shared_from_this<DownloadDriverStatistic>
{
public:
typedef boost::shared_ptr<DownloadDriverStatistic> p;
static p Create(int id);
public:
void Start(u_int max_http_downloader_count);
void Stop();
void Clear();
bool IsRunning() const;
void OnShareMemoryTimer(u_int times);
public:
//////////////////////////////////////////////////////////////////////////
// Operations
HttpDownloaderStatistic::p AttachHttpDownloaderStatistic(const string& url);
bool DetachHttpDownloaderStatistic(const string& url);
bool DetachHttpDownloaderStatistic(const HttpDownloaderStatistic::p http_downloader_statistic);
bool DetachAllHttpDownloaderStatistic();
//////////////////////////////////////////////////////////////////////////
// Download Driver Statistic Info
DOWNLOADDRIVER_STATISTIC_INFO GetDownloadDriverStatisticInfo();
//////////////////////////////////////////////////////////////////////////
// Speed Info
void SubmitDownloadedBytes(u_int downloaded_bytes);
void SubmitUploadedBytes(u_int uploaded_bytes);
SPEED_INFO GetSpeedInfo();
//////////////////////////////////////////////////////////////////////////
// Url Info
void SetOriginalUrl(const string& original_url);
void SetOriginalReferUrl(const string& original_refer_url);
//////////////////////////////////////////////////////////////////////////
// Shared Memory
string GetSharedMemoryName();
u_int GetSharedMemorySize();
//////////////////////////////////////////////////////////////////////////
// Misc
u_int GetDownloadDriverID() const;
u_int GetMaxHttpDownloaderCount() const;
//////////////////////////////////////////////////////////////////////////
// Resource Info
void SetResourceID(const RID& rid);
RID GetResourceID();
void SetFileLength(u_int file_length);
u_int GetFileLength();
void SetBlockSize(u_int block_size);
u_int GetBlockSize();
void SetBlockCount(u_short block_count);
u_short GetBlockCount();
//////////////////////////////////////////////////////////////////////////
// HTTP Data Bytes
void SubmitHttpDataBytes(u_int http_data_bytes);
void SetLocalDataBytes(u_int local_data_bytes);
u_int GetTotalHttpDataBytes() { return DownloadDriverStatisticInfo().TotalHttpDataBytes; }
//////////////////////////////////////////////////////////////////////////
// HTTP Max Download Speed (历史最大瞬时速度)
u_int GetHttpDownloadMaxSpeed();
// HTTP 历史平均速度
u_int GetHttpDownloadAvgSpeed();
private:
//////////////////////////////////////////////////////////////////////////
// Speed Info & HTTP Downloader Info
void UpdateSpeedInfo();
void UpdateHttpDownloaderInfo();
DOWNLOADDRIVER_STATISTIC_INFO& DownloadDriverStatisticInfo();
//////////////////////////////////////////////////////////////////////////
// Shared Memory
bool CreateSharedMemory();
private:
typedef map<string, HttpDownloaderStatistic::p> HttpDownloaderStatisticMap;
private:
bool is_running_;
string original_url_;
string original_refer_url_;
SpeedInfoStatistic::p speed_info_;
DOWNLOADDRIVER_STATISTIC_INFO_EX download_driver_statistic_info_;
u_int download_driver_id_;
HttpDownloaderStatisticMap http_downloader_statistic_map_;
ShareMemory shared_memory_;
u_int http_download_max_speed_;
private:
DownloadDriverStatistic() : http_download_max_speed_(0) {}
DownloadDriverStatistic(u_int id);
};
}
| [
"penneryu@outlook.com"
] | penneryu@outlook.com |
bbb3456e2609ca469a3b30c10eb995dc91dd44ff | 25aa9cb1cb724a1e543211fa852a070f33df79de | /kaldi-ali.cc | 131b8a050d64bdb2c614bbd3f7e1986172e7afac | [] | no_license | pikaliov/kaldi-readers-for-tensorflow | b42c7527ecda3126d90a47e286193770a9008580 | c3f83feb68476de1624ae1e7931803bfb2d7c7cb | refs/heads/master | 2021-08-28T21:38:37.793936 | 2017-12-13T06:42:39 | 2017-12-13T06:42:39 | 119,988,621 | 1 | 0 | null | 2018-02-02T14:00:53 | 2018-02-02T14:00:53 | null | UTF-8 | C++ | false | false | 7,765 | cc | #include <memory>
#include <regex>
#include "tensorflow/core/framework/reader_base.h"
#include "tensorflow/core/framework/reader_op_kernel.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/io/buffered_inputstream.h"
#include "tensorflow/core/lib/io/random_inputstream.h"
#include "tensorflow/core/lib/io/zlib_compression_options.h"
#include "tensorflow/core/lib/io/zlib_inputstream.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "shape-funcs.hh"
namespace tensorflow {
using shape_util::ScalarInputsAndOutputs;
using shape_util::TwoElementOutput;
static Status ReadKaldiPostAndAli(Env* env, const string& ark_path, uint64 ark_offset, bool is_reading_post, string* contents) {
enum { kBufferSize = 256 << 10 /* 256 kB */ };
std::unique_ptr<RandomAccessFile> file_;
std::unique_ptr<io::InputStreamInterface> buffered_inputstream_;
TF_RETURN_IF_ERROR(env->NewRandomAccessFile(ark_path, &file_));
buffered_inputstream_.reset(
new io::BufferedInputStream(file_.get(), kBufferSize));
TF_RETURN_IF_ERROR(buffered_inputstream_->SkipNBytes(ark_offset));
// Actural reading start from here
string binary;
TF_RETURN_IF_ERROR(buffered_inputstream_->ReadNBytes(2, &binary));
CHECK_EQ(binary[0], '\0');
CHECK_EQ(binary[1], 'B');
string header_buffer;
TF_RETURN_IF_ERROR(buffered_inputstream_->ReadNBytes(1, &header_buffer));
if (header_buffer[0] == '\4') {
// This is a vector of int
string size_str;
buffered_inputstream_->ReadNBytes(4, &size_str);
int32 size = *reinterpret_cast<const int32*>(size_str.data());
string data;
if (is_reading_post) {
for (int32 outer_vec_idx = 0; outer_vec_idx < size; outer_vec_idx++) {
// <1> <4> [<1> <4> <1> <4>] [<1> <4> <1> <4>]
string inner_size_str;
buffered_inputstream_->ReadNBytes(5, &inner_size_str);
int32 inner_size = *reinterpret_cast<const int32 *>(inner_size_str.data() + 1);
string inner_vec_data;
buffered_inputstream_->ReadNBytes(inner_size * 10, &inner_vec_data);
data += inner_size_str + inner_vec_data;
}
} else {
TF_RETURN_IF_ERROR(buffered_inputstream_->ReadNBytes(size * 5, &data));
}
*contents = header_buffer + size_str + data;
} else {
return Status(error::UNAVAILABLE, "Unknown Kaldi Post or Ali: " + header_buffer);
}
return Status::OK();
}
class ReadKaldiPostAndAliOp : public OpKernel {
public:
using OpKernel::OpKernel;
explicit ReadKaldiPostAndAliOp(OpKernelConstruction *context)
:OpKernel(context),
id_pat_("^(\\S+):(\\d+)")
{
OP_REQUIRES_OK(context, context->GetAttr("is_reading_post", &is_reading_post_));
}
void Compute(OpKernelContext* context) override {
const Tensor* input;
OP_REQUIRES_OK(context, context->input("scpline", &input));
OP_REQUIRES(context, TensorShapeUtils::IsScalar(input->shape()),
errors::InvalidArgument(
"Input filename tensor must be scalar, but had shape: ",
input->shape().DebugString()));
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output("contents",
TensorShape({}), &output));
const std::regex id_pat("^(\\S+):(\\d+)");
std::smatch m;
string half_scp_line = input->scalar<string>()();
bool matched = std::regex_search(half_scp_line, m, id_pat);
OP_REQUIRES(context, matched, Status(error::INVALID_ARGUMENT, "Script line is " + half_scp_line));
string ark_path = m[1];
string ark_offset_str = m[2];
uint64 ark_offset = std::stoull(ark_offset_str);
OP_REQUIRES_OK(context,
ReadKaldiPostAndAli(context->env(), ark_path, ark_offset, is_reading_post_,
&output->scalar<string>()()));
}
private:
bool is_reading_post_;
const std::regex id_pat_;
};
REGISTER_KERNEL_BUILDER(Name("ReadKaldiPostAndAli").Device(DEVICE_CPU), ReadKaldiPostAndAliOp);
REGISTER_OP("ReadKaldiPostAndAli")
.Attr("is_reading_post: bool")
.Input("scpline: string")
.Output("contents: string")
.SetShapeFn(ScalarInputsAndOutputs)
.Doc(R"doc(
Reads and outputs the entire contents of the input kaldi post or ali ark filename.
scpline: scalar. /path/to/ark.file:12345
)doc");
class DecodeKaldiAliOp : public OpKernel {
public:
explicit DecodeKaldiAliOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("out_type", &out_type_));
OP_REQUIRES_OK(context, context->GetAttr("is_reading_post", &is_reading_post_));
}
void Compute(OpKernelContext* context) override {
const auto& input = context->input(0);
int64 str_size = -1;
auto flat_in = input.flat<string>();
OP_REQUIRES(context, flat_in.size() == 1,
errors::InvalidArgument(
"DecodeKaldiAliOp requires input string size = 1"
)
)
const string& in_str = flat_in(0);
str_size = in_str.size();
const char* in_data = reinterpret_cast<const char*>(flat_in(0).data());
TensorShape out_shape;
int32 num_elem = *reinterpret_cast<const int32*>(in_data + 1);
out_shape.AddDim(num_elem);
if (str_size == -1 || str_size == 0) { // Empty input
Tensor* output_tensor = nullptr;
OP_REQUIRES_OK(context, context->allocate_output("output", out_shape,
&output_tensor));
return;
}
Tensor* output_tensor = nullptr;
OP_REQUIRES_OK(
context, context->allocate_output("output", out_shape, &output_tensor));
auto out = output_tensor->flat<int32>();
int32* out_data = out.data();
const char* in_bytes = in_data + 5;
if (is_reading_post_) {
for (int32 frame_idx = 0; frame_idx < num_elem; frame_idx++) {
out_data[frame_idx] = *reinterpret_cast<const int32*>(in_bytes + 5 + 1);
in_bytes += 15;
}
} else {
for (int32 frame_idx = 0; frame_idx < num_elem; frame_idx++) {
out_data[frame_idx] = *reinterpret_cast<const int32*>(in_bytes + 1);
in_bytes += 5;
}
}
}
private:
bool is_reading_post_;
DataType out_type_;
};
REGISTER_KERNEL_BUILDER(Name("DecodeKaldiAli").Device(DEVICE_CPU), DecodeKaldiAliOp);
REGISTER_OP("DecodeKaldiAli")
.Input("bytes: string")
.Output("output: out_type")
.Attr("out_type: {int32}")
.Attr("is_reading_post: bool")
.SetShapeFn(shape_inference::UnknownShape)
.Doc(R"doc(
Reinterpret the bytes of a string as a kaldi ali
)doc");
} // namespace tensorflow
| [
"zyfan@ling-ban.com"
] | zyfan@ling-ban.com |
fba2d0a288c7f58d74ad3b1fc0558f6a82769798 | 86b6c8faf14d9e4156a183b3aaf8cb5a2e931c9e | /findMin.cpp | 8de2ed433c2f286115aff9a116b0808045a7f03a | [] | no_license | hengshuangliu/lintcode | 6293ac5ff006ab6957fce8bace82091fd62088dd | aa091ff712fd5fb430d654cc4ca13b4444ceba36 | refs/heads/master | 2021-01-22T12:37:39.841658 | 2017-09-08T07:51:08 | 2017-09-08T07:51:08 | 102,352,229 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 869 | cpp | #include<iostream>
#include<vector>
#include <cstdlib>
using namespace std;
class Solution {
public:
/**
* @param nums: a rotated sorted array
* @return: the minimum number in the array
*/
int findMin(vector<int> &nums) {
// write your code here
int left = 0, right = nums.size() - 1;
int mid = (left + right) / 2;
while(left <= right){
if(left == right){
return nums[left];
}
else if(right - 1 == left){
return (nums[left] > nums[right]) ? nums[right] : nums[left];
}
if(nums[mid] > nums[right]){
left = mid;
mid = (left + right) / 2;
}
else{
right = mid;
mid = (left + right) / 2;
}
}
return nums[mid];
}
};
int main(){
int a[7] = {4, 5, 6, 10, 1, 2, 3 };
vector<int> array(a,a + 7);
Solution solu;
cout << solu.findMin(array) << endl;
return EXIT_SUCCESS;
}
| [
"767924520@qq.com"
] | 767924520@qq.com |
41204a2f1ee4be02585a88da2339a5bbe288a094 | b072ae78bbddb0c1e63cfeae2196fd13a476c440 | /3D_Warfare_Client/3D_Warfare_Client/struct_package.h | 4911846d7040ed25faeb2a64e8a81e08466ed60f | [] | no_license | sounghyun/NetGameProgramming | f1548254df3c6e8159e0bf1d02c011735cf3e2fa | aabfbe970a29390c1e0f9d53614519c8caae8a7a | refs/heads/master | 2021-05-02T09:32:08.776388 | 2016-12-07T12:47:19 | 2016-12-07T12:47:35 | 72,851,222 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 330 | h | #ifndef STRUCK_PACKAGE_H
#define STRUCK_PACKAGE_H
#include <winsock2.h>
#include <GL/glut.h> // includes gl.h glu.h
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <sys/timeb.h>
#include <list>
#include <vector>
using namespace std;
struct Point
{
GLfloat x, y, z;
GLint state;
};
#endif | [
"unfade2@gmail.com"
] | unfade2@gmail.com |
4a1c6d5030ead7dcd96bac87fb73551883eba033 | 1586fd5da36e6616996410470984fced9afc17a1 | /chrome/browser/vr/ui_scene.h | 699af2db805f9999ad8c583b8ae9d259e5808b1c | [
"BSD-3-Clause"
] | permissive | thefreakingmind/chromium | 01cf65599c5e1385250083827e6c61c8b5e58005 | 99c093c25c78d5268beae7ccd3d34bb23b17d30b | refs/heads/master | 2023-02-25T10:27:43.277471 | 2018-05-02T14:12:25 | 2018-05-02T14:12:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,176 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_VR_UI_SCENE_H_
#define CHROME_BROWSER_VR_UI_SCENE_H_
#include <memory>
#include <vector>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "chrome/browser/vr/elements/ui_element.h"
#include "chrome/browser/vr/elements/ui_element_name.h"
#include "chrome/browser/vr/keyboard_delegate.h"
#include "third_party/skia/include/core/SkColor.h"
namespace base {
class TimeTicks;
} // namespace base
namespace gfx {
class Transform;
} // namespace gfx
namespace vr {
class UiElement;
class UiScene {
public:
typedef base::RepeatingCallback<void()> PerFrameCallback;
UiScene();
~UiScene();
void AddUiElement(UiElementName parent, std::unique_ptr<UiElement> element);
void AddParentUiElement(UiElementName child,
std::unique_ptr<UiElement> element);
std::unique_ptr<UiElement> RemoveUiElement(int element_id);
// Handles per-frame updates, giving each element the opportunity to update,
// if necessary (eg, for animations). NB: |current_time| is the shared,
// absolute begin frame time.
// Returns true if *anything* was updated.
bool OnBeginFrame(const base::TimeTicks& current_time,
const gfx::Transform& head_pose);
// Returns true if any textures were redrawn.
bool UpdateTextures();
UiElement& root_element();
UiElement* GetUiElementById(int element_id) const;
UiElement* GetUiElementByName(UiElementName name) const;
typedef std::vector<const UiElement*> Elements;
typedef std::vector<UiElement*> MutableElements;
std::vector<UiElement*>& GetAllElements();
Elements GetElementsToHitTest();
Elements GetElementsToDraw();
Elements GetWebVrOverlayElementsToDraw();
float background_distance() const { return background_distance_; }
void set_background_distance(float d) { background_distance_ = d; }
void set_dirty() { is_dirty_ = true; }
void OnGlInitialized(SkiaSurfaceProvider* provider);
// The callback to call on every new frame. This is used for things we want to
// do every frame regardless of element or subtree visibility.
void AddPerFrameCallback(PerFrameCallback callback);
SkiaSurfaceProvider* SurfaceProviderForTesting() { return provider_; }
private:
void InitializeElement(UiElement* element);
MutableElements GetVisibleElementsMutable();
std::unique_ptr<UiElement> root_element_;
float background_distance_ = 10.0f;
bool gl_initialized_ = false;
bool initialized_scene_ = false;
// TODO(mthiesse): Convert everything that manipulates UI elements to
// bindings. Don't allow any code to go in and manipulate UI elements outside
// of bindings so that we can do a single pass and update everything and
// easily compute dirtiness.
bool is_dirty_ = false;
std::vector<UiElement*> all_elements_;
std::vector<PerFrameCallback> per_frame_callback_;
SkiaSurfaceProvider* provider_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(UiScene);
};
} // namespace vr
#endif // CHROME_BROWSER_VR_UI_SCENE_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
4a71e51c82e17e58fbbf82fe5380928f1975eaff | 6d5a257bf72afdd85660ad3e938e2aa3025c680b | /include/Core/Utilities/QProgInfo/QuantumVolume.h | 053cc77ee060cae3ac82754e1ab56fb0b12b107e | [
"Apache-2.0"
] | permissive | OriginQ/QPanda-2 | 682b0e3bcdec7c66a651e8001d639f6146595fdf | a182212503a97981844140b165cb3cee8e293edd | refs/heads/master | 2023-08-19T03:01:27.385297 | 2023-08-04T08:43:03 | 2023-08-04T08:43:03 | 136,144,680 | 1,207 | 96 | Apache-2.0 | 2023-08-04T08:42:52 | 2018-06-05T08:23:20 | C++ | UTF-8 | C++ | false | false | 3,090 | h | #ifndef _QUANTUM_VOLUME_H_
#define _QUANTUM_VOLUME_H_
#include "Core/QuantumMachine/QuantumMachineInterface.h"
#include "Core/QuantumMachine/OriginQuantumMachine.h"
#include "Core/Utilities/QProgInfo/CrossEntropyBenchmarking.h"
QPANDA_BEGIN
#if defined(USE_OPENSSL) && defined(USE_CURL)
/**
* @class QuantumVolume
* @ingroup Utilities
* @brief Calculate the quantum volume of the chip
*/
class QuantumVolume
{
struct QvCircuit
{
QProg cir;
int depth;
int trial;
QVec qv;
std::vector < ClassicalCondition > cv;
prob_vec result;
float heavy_output;
int shots;
int qvm_type;
};
public:
QuantumVolume(MeasureQVMType type, QuantumMachine* qvm);
~QuantumVolume();
size_t calcQuantumVolume(const std::vector<std::vector<int>> &qubit_lists, int ntrials, int shots);
private:
void createQvCircuits(std::vector<std::vector<int> > qubit_lists, int ntrials,
std::vector<std::vector <QvCircuit> >& circuits, std::vector<std::vector <QvCircuit> >& circuits_nomeas);
void calcIdealResult(std::vector<std::vector <QvCircuit> >& circuits_nomeas);
void calcINoiseResult(std::vector<std::vector <QvCircuit> >& circuits, int shots);
void calcStatistics();
void calcHeavyOutput(int trial, int depth, prob_vec probs);
size_t volumeResult();
std::vector<int> randomPerm(int depth);
private:
int m_shots;
CPUQVM *m_qvm;
NoiseQVM *m_noise_qvm;
QCloudMachine * m_qcm;
std::vector<std::vector<int> > m_qubit_lists;
std::vector<int> m_depth_list;
int m_ntrials;
std::map<int, std::string> m_gate_type_map;
std::vector<std::vector <QvCircuit> > m_circuits;
std::vector<std::vector <QvCircuit> >m_circuits_nomeas;
std::map<std::pair<int, int >, std::vector<std::string>> m_heavy_outputs; /**< eg: <depth, trial> , <"001", "010", ...> */
std::map<std::pair<int, int >, double> m_heavy_output_prob_ideal; /**< eg: <depth, trial> , 0.88888888... */
std::map<std::pair<int, int >, size_t> m_heavy_output_counts; /**< eg: <depth, trial> , 1000... */
std::vector<std::pair <bool, float>> m_success_list;
std::vector<std::vector <float>> m_ydata;
MeasureQVMType m_qvm_type;
};
/**
* @brief calculate quantum volume
* @param[in] NoiseQVM* noise quantum machine
* @param[in] std::vector <std::vector<int>> qubit_lists, eg: {{1,2}, {1,2,3,4,5}}
* @param[in] const std::vector<int>& number of layer
* @param[in] int number of random iterations
* @param[in] int shots
* @return size_t quantum volume
*/
size_t calculate_quantum_volume(NoiseQVM * qvm, std::vector <std::vector<int> >qubit_lists, int ntrials, int shots = 1000);
/**
* @brief calculate quantum volume
* @param[in] QCloudMachine* real chip
* @param[in] std::vector <std::vector<int>> qubit_lists, eg: {{1,2}, {1,2,3,4,5}}
* @param[in] const std::vector<int>& number of layer
* @param[in] int number of random iterations
* @param[in] int shots
* @return size_t quantum volume
*/
size_t calculate_quantum_volume(QCloudMachine* qvm, std::vector <std::vector<int> >qubit_lists, int ntrials, int shots = 1000);
#endif
QPANDA_END
#endif // !_QUANTUM_VOLUME_H_
| [
"wj@originqc.cn"
] | wj@originqc.cn |
203ac9b8ef01a33c1fa50f782d98ae73d67e5e8c | 5399d919f33bca564bd309c448f1151e7fb6aa27 | /server/configuration/ListenGuideline.hpp | 910238d8e6551996150c15258d6a83ef780c9ade | [] | no_license | hotgloupi/zhttpd | bcbc37283ebf0fb401417fa1799f7f7bb286f0d5 | 0437ac2e34dde89abab26665df9cbee1777f1d44 | refs/heads/master | 2021-01-25T05:57:49.958146 | 2011-01-03T14:22:05 | 2011-01-03T14:22:05 | 963,056 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | hpp |
#ifndef __LISTENGUIDELINE_HPP__
# define __LISTENGUIDELINE_HPP__
# include "IVHostGuideline.hpp"
namespace zhttpd
{
class ListenGuideline : public IVHostGuideline
{
private:
api::uint16_t _port;
bool _deny;
public:
ListenGuideline(api::uint16_t port, bool deny = false);
virtual ~ListenGuideline();
bool match(api::IRequest& request) const;
};
}
#endif // __LISTENGUIDELINE_HPP__
| [
"github@hotgloupi.chapeaunoir.info"
] | github@hotgloupi.chapeaunoir.info |
28c3a54f1f3a1d79d5c501f136c40d9efbec4c1c | cbf1069a489cd6b5c4ac61bcafb49e05eec98c99 | /Programowanie Obiektowe/Lesson_7/C07/01_ID03P04/C07_Proj_ID03P04_0001/program.cpp | 8fe762455baf05c00e4e24e87e308466c0776e0c | [] | no_license | RuslanLytvynov/University_WIT | 35eb3a0622d76907fead57e63e625edfa6ac1b33 | b75ee4bc0e16ccaa9abf8b50075ff64ea6e87a52 | refs/heads/master | 2021-03-12T10:56:17.579139 | 2020-12-06T11:49:18 | 2020-12-06T11:49:18 | 246,613,927 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #include "Application.h"
int main(){
Application myApplication;
myApplication.Run();
return 0;
}
| [
"lytvynovrus@gmail.com"
] | lytvynovrus@gmail.com |
4b07fbd005fc32928efe4052c5ed4bafb02beb3b | d93fe00111f8072d803f7d13a576ce77267b9fd0 | /src/test/assets/cache_tests.cpp | 219a72ad7b87950f88760189c7985b9e69d4837e | [
"MIT"
] | permissive | yiya-core/yiya-core | 279dcb00f6eb94bdd7eadee4e197565a9f5ecf5f | 54bdc5c72f6d760cb3ec840f202c289bccd03ccd | refs/heads/master | 2020-08-07T15:06:30.855194 | 2019-10-14T20:25:18 | 2019-10-14T20:25:18 | 213,237,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | cpp |
#include "assets/assets.h"
#include <boost/test/unit_test.hpp>
#include <test/test_yiya.h>
BOOST_FIXTURE_TEST_SUITE(cache_tests, BasicTestingSetup)
const int NUM_OF_ASSETS1 = 100000;
BOOST_AUTO_TEST_CASE(cache_test)
{
BOOST_TEST_MESSAGE("Running Cache Test");
CLRUCache<std::string, CNewAsset> cache(NUM_OF_ASSETS1);
std::string assetName = "TEST";
int counter = 0;
while(cache.Size() != NUM_OF_ASSETS1)
{
CNewAsset asset(std::string(assetName + std::to_string(counter)), CAmount(1), 0, 0, 1, "43f81c6f2c0593bde5a85e09ae662816eca80797");
cache.Put(asset.strName, asset);
counter++;
}
BOOST_CHECK_MESSAGE(cache.Exists("TEST0"), "Didn't have TEST0");
CNewAsset asset("THISWILLOVERWRITE", CAmount(1), 0, 0, 1, "43f81c6f2c0593bde5a85e09ae662816eca80797");
cache.Put(asset.strName, asset);
BOOST_CHECK_MESSAGE(cache.Exists("THISWILLOVERWRITE"), "New asset wasn't added to cache");
BOOST_CHECK_MESSAGE(!cache.Exists("TEST0"), "Cache didn't remove the least recently used");
BOOST_CHECK_MESSAGE(cache.Exists("TEST1"), "Cache didn't have TEST1");
}
BOOST_AUTO_TEST_SUITE_END()
| [
"yiya-core@protonmail.com"
] | yiya-core@protonmail.com |
28b1ae39d01e3fca2ea54d2cde29707f901adca2 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_2652486_1/C++/hex539/C.cc | bae10d62801471afd43b581880ffc704c179417a | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,489 | cc | #include <functional>/*{{{*/
#include <unordered_set>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <numeric>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <cstdio>
#include <vector>
#include <math.h>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <set>
using namespace std;typedef long long ll;typedef long double real;void run();int main(){ios::sync_with_stdio(0);run();}/*}}}*/
ll val[15];
ll res[15];
ll prod[15];
real chance=-1;
ll r,n,m,k;
int useful[20];
unordered_set<ll> important;
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
int bad=0;
void dfs(int left,int last=2,ll tot=1){
if (80<=bad or chance>1e-10L) return;
if (left--){
bool did=false;
int consider[9];
for (int i=0; i<=m-last; i++) consider[i]=i+last;
random_shuffle(consider,consider+m-last);
// for (int i=last; i<=m; i++){
for (int z=0; z<=m-last; ++z){
int i=consider[z];
if (useful[i] or i==m and not did){
dfs(left,val[left]=i,tot*i);
did=true;
}
}
return;
}
if (chance>=-0.5L){
ll tot=1; for (int i=k; i--;) tot=tot/gcd(tot,prod[i])*prod[i];
for (int i=n; i--;) if (tot%val[i]) return;
tot=1; for (int i=n; i--;) tot*=val[i];
for (int i=k; i--;) if (tot%prod[i]) return;
}
map<int,real> prob[13];
prob[0][1]=8;
for (int i=0; i<n; i++){
for (auto j: prob[i]){
prob[i+1][j.first * 1] += 0.5L*j.second;
if (important.count(j.first*val[i]))
prob[i+1][j.first * val[i]] += 0.5L*j.second;
}
}
real final=1e20L;
for (int i=0; i<k and final>=chance; i++) final*=prob[n][prod[i]];
if (final>=chance){
for (int i=0; i<n; i++) res[i]=val[i];
chance=final;
}
++bad;
}
void run(){
{int u; cin>>u; cout<<"Case #1:"<<endl;}
cin>>r>>n>>m>>k;
for (int i=0; i<r; i++){
memset(useful,0,sizeof useful);
important.clear();
for (int j=0; j<k; j++){
cin>>prod[j];
for (int q=1; q*q<=prod[j]; q++)
if (prod[j]%q==0)
important.insert(q),
important.insert(prod[j]/q);
for (int q=2,z=prod[j]; q<=m; q++){
if (z%q==0){
int t=0; do ++t,z/=q; while (z%q==0);
useful[q]=max(useful[q],t);
}
}
}
for (int i=2; i<=m; i++) useful[i]=true;
chance=-1; bad=0;
dfs(n);
for (int i=0; i<n; i++) cout<<res[i]; cout<<endl;
// cout<<"("<<chance<<")"<<endl;
}
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
f859fd114ffadd83ea7589ba013633b127ce3d3b | 36579e820f5c07cd1fe796abc777f23f32efeb10 | /src/content/app/content_main_runner.cc | 00864253f7c97b98d1e66eb67e717588523559a1 | [
"BSD-3-Clause"
] | permissive | sokolovp/BraveMining | 089ea9940ee6e6cb8108b106198e66c62049d27b | 7040cdee80f6f7176bea0e92f8f3435abce3e0ae | refs/heads/master | 2020-03-20T00:52:22.001918 | 2018-06-12T11:33:31 | 2018-06-12T11:33:31 | 137,058,944 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 27,733 | cc | // 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.
#include "content/public/app/content_main_runner.h"
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/allocator/allocator_check.h"
#include "base/allocator/allocator_extension.h"
#include "base/allocator/buildflags.h"
#include "base/at_exit.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/debug/debugger.h"
#include "base/debug/stack_trace.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/i18n/icu_util.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_base.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/process/memory.h"
#include "base/process/process.h"
#include "base/process/process_handle.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "components/tracing/common/trace_startup.h"
#include "content/app/mojo/mojo_init.h"
#include "content/common/url_schemes.h"
#include "content/public/app/content_main.h"
#include "content/public/app/content_main_delegate.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_descriptor_keys.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/sandbox_init.h"
#include "content/public/common/zygote_features.h"
#include "gin/v8_initializer.h"
#include "media/base/media.h"
#include "media/media_features.h"
#include "ppapi/features/features.h"
#include "services/service_manager/embedder/switches.h"
#include "services/service_manager/sandbox/sandbox_type.h"
#include "ui/base/ui_base_paths.h"
#include "ui/base/ui_base_switches.h"
#if defined(OS_WIN)
#include <malloc.h>
#include <cstring>
#include "base/trace_event/trace_event_etw_export_win.h"
#include "sandbox/win/src/sandbox_types.h"
#include "ui/display/win/dpi.h"
#elif defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#include "base/power_monitor/power_monitor_device_source.h"
#include "content/browser/mach_broker_mac.h"
#endif // OS_WIN
#if defined(OS_POSIX)
#include <signal.h>
#include "base/file_descriptor_store.h"
#include "base/posix/global_descriptors.h"
#include "content/public/common/content_descriptors.h"
#if !defined(OS_MACOSX)
#include "content/public/common/zygote_fork_delegate_linux.h"
#endif
#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
#include "content/zygote/zygote_main.h"
#include "sandbox/linux/services/libc_interceptor.h"
#endif
#endif // OS_POSIX
#if !defined(CHROME_MULTIPLE_DLL_BROWSER)
#include "content/public/gpu/content_gpu_client.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/public/utility/content_utility_client.h"
#endif
#if !defined(CHROME_MULTIPLE_DLL_CHILD)
#include "content/browser/browser_main.h"
#include "content/public/browser/content_browser_client.h"
#endif
#if !defined(CHROME_MULTIPLE_DLL_BROWSER) && !defined(CHROME_MULTIPLE_DLL_CHILD)
#include "content/browser/gpu/gpu_main_thread_factory.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/utility_process_host_impl.h"
#include "content/gpu/in_process_gpu_thread.h"
#include "content/renderer/in_process_renderer_thread.h"
#include "content/utility/in_process_utility_thread.h"
#endif
namespace content {
extern int GpuMain(const content::MainFunctionParams&);
#if BUILDFLAG(ENABLE_PLUGINS)
#if !defined(OS_LINUX)
extern int PluginMain(const content::MainFunctionParams&);
#endif
extern int PpapiPluginMain(const MainFunctionParams&);
extern int PpapiBrokerMain(const MainFunctionParams&);
#endif
extern int RendererMain(const content::MainFunctionParams&);
extern int UtilityMain(const MainFunctionParams&);
} // namespace content
namespace content {
namespace {
#if defined(V8_USE_EXTERNAL_STARTUP_DATA) && defined(OS_ANDROID)
#if defined __LP64__
#define kV8SnapshotDataDescriptor kV8Snapshot64DataDescriptor
#else
#define kV8SnapshotDataDescriptor kV8Snapshot32DataDescriptor
#endif
#endif
// This sets up two singletons responsible for managing field trials. The
// |field_trial_list| singleton lives on the stack and must outlive the Run()
// method of the process.
void InitializeFieldTrialAndFeatureList(
std::unique_ptr<base::FieldTrialList>* field_trial_list) {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
// Initialize statistical testing infrastructure. We set the entropy
// provider to nullptr to disallow non-browser processes from creating
// their own one-time randomized trials; they should be created in the
// browser process.
field_trial_list->reset(new base::FieldTrialList(nullptr));
// Ensure any field trials in browser are reflected into the child
// process.
#if defined(OS_POSIX)
// On POSIX systems that use the zygote, we get the trials from a shared
// memory segment backed by an fd instead of the command line.
base::FieldTrialList::CreateTrialsFromCommandLine(
command_line, switches::kFieldTrialHandle, kFieldTrialDescriptor);
#else
base::FieldTrialList::CreateTrialsFromCommandLine(
command_line, switches::kFieldTrialHandle, -1);
#endif
std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
base::FieldTrialList::CreateFeaturesFromCommandLine(
command_line, switches::kEnableFeatures, switches::kDisableFeatures,
feature_list.get());
base::FeatureList::SetInstance(std::move(feature_list));
}
#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
void LoadV8SnapshotFile() {
#if defined(USE_V8_CONTEXT_SNAPSHOT)
static constexpr gin::V8Initializer::V8SnapshotFileType kSnapshotType =
gin::V8Initializer::V8SnapshotFileType::kWithAdditionalContext;
static const char* snapshot_data_descriptor =
kV8ContextSnapshotDataDescriptor;
#else
static constexpr gin::V8Initializer::V8SnapshotFileType kSnapshotType =
gin::V8Initializer::V8SnapshotFileType::kDefault;
static const char* snapshot_data_descriptor = kV8SnapshotDataDescriptor;
#endif // USE_V8_CONTEXT_SNAPSHOT
ALLOW_UNUSED_LOCAL(kSnapshotType);
ALLOW_UNUSED_LOCAL(snapshot_data_descriptor);
#if defined(OS_POSIX) && !defined(OS_MACOSX)
base::FileDescriptorStore& file_descriptor_store =
base::FileDescriptorStore::GetInstance();
base::MemoryMappedFile::Region region;
base::ScopedFD fd =
file_descriptor_store.MaybeTakeFD(snapshot_data_descriptor, ®ion);
if (fd.is_valid()) {
gin::V8Initializer::LoadV8SnapshotFromFD(fd.get(), region.offset,
region.size, kSnapshotType);
return;
}
#endif // OS_POSIX && !OS_MACOSX
#if !defined(CHROME_MULTIPLE_DLL_BROWSER)
gin::V8Initializer::LoadV8Snapshot(kSnapshotType);
#endif // !CHROME_MULTIPLE_DLL_BROWSER
}
void LoadV8NativesFile() {
#if defined(OS_POSIX) && !defined(OS_MACOSX)
base::FileDescriptorStore& file_descriptor_store =
base::FileDescriptorStore::GetInstance();
base::MemoryMappedFile::Region region;
base::ScopedFD fd =
file_descriptor_store.MaybeTakeFD(kV8NativesDataDescriptor, ®ion);
if (fd.is_valid()) {
gin::V8Initializer::LoadV8NativesFromFD(fd.get(), region.offset,
region.size);
return;
}
#endif // OS_POSIX && !OS_MACOSX
#if !defined(CHROME_MULTIPLE_DLL_BROWSER)
gin::V8Initializer::LoadV8Natives();
#endif // !CHROME_MULTIPLE_DLL_BROWSER
}
#endif // V8_USE_EXTERNAL_STARTUP_DATA
void InitializeV8IfNeeded(const base::CommandLine& command_line,
const std::string& process_type) {
if (process_type == switches::kGpuProcess)
return;
#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
LoadV8SnapshotFile();
LoadV8NativesFile();
#endif // V8_USE_EXTERNAL_STARTUP_DATA
}
} // namespace
#if !defined(CHROME_MULTIPLE_DLL_CHILD)
base::LazyInstance<ContentBrowserClient>::DestructorAtExit
g_empty_content_browser_client = LAZY_INSTANCE_INITIALIZER;
#endif // !CHROME_MULTIPLE_DLL_CHILD
#if !defined(CHROME_MULTIPLE_DLL_BROWSER)
base::LazyInstance<ContentGpuClient>::DestructorAtExit
g_empty_content_gpu_client = LAZY_INSTANCE_INITIALIZER;
base::LazyInstance<ContentRendererClient>::DestructorAtExit
g_empty_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
base::LazyInstance<ContentUtilityClient>::DestructorAtExit
g_empty_content_utility_client = LAZY_INSTANCE_INITIALIZER;
#endif // !CHROME_MULTIPLE_DLL_BROWSER
class ContentClientInitializer {
public:
static void Set(const std::string& process_type,
ContentMainDelegate* delegate) {
ContentClient* content_client = GetContentClient();
#if !defined(CHROME_MULTIPLE_DLL_CHILD)
if (process_type.empty()) {
if (delegate)
content_client->browser_ = delegate->CreateContentBrowserClient();
if (!content_client->browser_)
content_client->browser_ = &g_empty_content_browser_client.Get();
}
#endif // !CHROME_MULTIPLE_DLL_CHILD
#if !defined(CHROME_MULTIPLE_DLL_BROWSER)
base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
if (process_type == switches::kGpuProcess ||
cmd->HasSwitch(switches::kSingleProcess) ||
(process_type.empty() && cmd->HasSwitch(switches::kInProcessGPU))) {
if (delegate)
content_client->gpu_ = delegate->CreateContentGpuClient();
if (!content_client->gpu_)
content_client->gpu_ = &g_empty_content_gpu_client.Get();
}
if (process_type == switches::kRendererProcess ||
cmd->HasSwitch(switches::kSingleProcess)) {
if (delegate)
content_client->renderer_ = delegate->CreateContentRendererClient();
if (!content_client->renderer_)
content_client->renderer_ = &g_empty_content_renderer_client.Get();
}
if (process_type == switches::kUtilityProcess ||
cmd->HasSwitch(switches::kSingleProcess)) {
if (delegate)
content_client->utility_ = delegate->CreateContentUtilityClient();
// TODO(scottmg): http://crbug.com/237249 Should be in _child.
if (!content_client->utility_)
content_client->utility_ = &g_empty_content_utility_client.Get();
}
#endif // !CHROME_MULTIPLE_DLL_BROWSER
}
};
// We dispatch to a process-type-specific FooMain() based on a command-line
// flag. This struct is used to build a table of (flag, main function) pairs.
struct MainFunction {
const char* name;
int (*function)(const MainFunctionParams&);
};
#if BUILDFLAG(USE_ZYGOTE_HANDLE)
// On platforms that use the zygote, we have a special subset of
// subprocesses that are launched via the zygote. This function
// fills in some process-launching bits around ZygoteMain().
// Returns the exit code of the subprocess.
int RunZygote(ContentMainDelegate* delegate) {
static const MainFunction kMainFunctions[] = {
{switches::kRendererProcess, RendererMain},
{switches::kUtilityProcess, UtilityMain},
#if BUILDFLAG(ENABLE_PLUGINS)
{switches::kPpapiPluginProcess, PpapiPluginMain},
#endif
};
std::vector<std::unique_ptr<ZygoteForkDelegate>> zygote_fork_delegates;
if (delegate) {
delegate->ZygoteStarting(&zygote_fork_delegates);
media::InitializeMediaLibrary();
}
// This function call can return multiple times, once per fork().
if (!ZygoteMain(std::move(zygote_fork_delegates)))
return 1;
if (delegate)
delegate->ZygoteForked();
// Zygote::HandleForkRequest may have reallocated the command
// line so update it here with the new version.
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
ContentClientInitializer::Set(process_type, delegate);
MainFunctionParams main_params(command_line);
main_params.zygote_child = true;
std::unique_ptr<base::FieldTrialList> field_trial_list;
InitializeFieldTrialAndFeatureList(&field_trial_list);
service_manager::SandboxType sandbox_type =
service_manager::SandboxTypeFromCommandLine(command_line);
if (sandbox_type == service_manager::SANDBOX_TYPE_PROFILING)
sandbox::SetUseLocaltimeOverride(false);
for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
if (process_type == kMainFunctions[i].name)
return kMainFunctions[i].function(main_params);
}
if (delegate)
return delegate->RunProcess(process_type, main_params);
NOTREACHED() << "Unknown zygote process type: " << process_type;
return 1;
}
#endif // BUILDFLAG(USE_ZYGOTE_HANDLE)
static void RegisterMainThreadFactories() {
#if !defined(CHROME_MULTIPLE_DLL_BROWSER) && !defined(CHROME_MULTIPLE_DLL_CHILD)
UtilityProcessHostImpl::RegisterUtilityMainThreadFactory(
CreateInProcessUtilityThread);
RenderProcessHostImpl::RegisterRendererMainThreadFactory(
CreateInProcessRendererThread);
content::RegisterGpuMainThreadFactory(CreateInProcessGpuThread);
#else
base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kSingleProcess)) {
LOG(FATAL) <<
"--single-process is not supported in chrome multiple dll browser.";
}
if (command_line.HasSwitch(switches::kInProcessGPU)) {
LOG(FATAL) <<
"--in-process-gpu is not supported in chrome multiple dll browser.";
}
#endif // !CHROME_MULTIPLE_DLL_BROWSER && !CHROME_MULTIPLE_DLL_CHILD
}
// Run the FooMain() for a given process type.
// If |process_type| is empty, runs BrowserMain().
// Returns the exit code for this process.
int RunNamedProcessTypeMain(
const std::string& process_type,
const MainFunctionParams& main_function_params,
ContentMainDelegate* delegate) {
static const MainFunction kMainFunctions[] = {
#if !defined(CHROME_MULTIPLE_DLL_CHILD)
{ "", BrowserMain },
#endif
#if !defined(CHROME_MULTIPLE_DLL_BROWSER)
#if BUILDFLAG(ENABLE_PLUGINS)
{ switches::kPpapiPluginProcess, PpapiPluginMain },
{ switches::kPpapiBrokerProcess, PpapiBrokerMain },
#endif // ENABLE_PLUGINS
{ switches::kUtilityProcess, UtilityMain },
{ switches::kRendererProcess, RendererMain },
{ switches::kGpuProcess, GpuMain },
#endif // !CHROME_MULTIPLE_DLL_BROWSER
};
RegisterMainThreadFactories();
for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
if (process_type == kMainFunctions[i].name) {
if (delegate) {
int exit_code = delegate->RunProcess(process_type,
main_function_params);
#if defined(OS_ANDROID)
// In Android's browser process, the negative exit code doesn't mean the
// default behavior should be used as the UI message loop is managed by
// the Java and the browser process's default behavior is always
// overridden.
if (process_type.empty())
return exit_code;
#endif
if (exit_code >= 0)
return exit_code;
}
return kMainFunctions[i].function(main_function_params);
}
}
#if BUILDFLAG(USE_ZYGOTE_HANDLE)
// Zygote startup is special -- see RunZygote comments above
// for why we don't use ZygoteMain directly.
if (process_type == switches::kZygoteProcess)
return RunZygote(delegate);
#endif // BUILDFLAG(USE_ZYGOTE_HANDLE)
// If it's a process we don't know about, the embedder should know.
if (delegate)
return delegate->RunProcess(process_type, main_function_params);
NOTREACHED() << "Unknown process type: " << process_type;
return 1;
}
class ContentMainRunnerImpl : public ContentMainRunner {
public:
ContentMainRunnerImpl() {
#if defined(OS_WIN)
memset(&sandbox_info_, 0, sizeof(sandbox_info_));
#endif
}
~ContentMainRunnerImpl() override {
if (is_initialized_ && !is_shutdown_)
Shutdown();
}
int TerminateForFatalInitializationError() {
if (delegate_)
return delegate_->TerminateForFatalInitializationError();
CHECK(false);
return 0;
}
int Initialize(const ContentMainParams& params) override {
ui_task_ = params.ui_task;
created_main_parts_closure_ = params.created_main_parts_closure;
#if defined(OS_WIN)
sandbox_info_ = *params.sandbox_info;
#else // !OS_WIN
#if defined(OS_MACOSX)
autorelease_pool_ = params.autorelease_pool;
#endif // defined(OS_MACOSX)
#if defined(OS_ANDROID)
// See note at the initialization of ExitManager, below; basically,
// only Android builds have the ctor/dtor handlers set up to use
// TRACE_EVENT right away.
TRACE_EVENT0("startup,benchmark,rail", "ContentMainRunnerImpl::Initialize");
#endif // OS_ANDROID
base::GlobalDescriptors* g_fds = base::GlobalDescriptors::GetInstance();
ALLOW_UNUSED_LOCAL(g_fds);
// On Android, the ipc_fd is passed through the Java service.
#if !defined(OS_ANDROID)
g_fds->Set(kMojoIPCChannel,
kMojoIPCChannel + base::GlobalDescriptors::kBaseDescriptor);
g_fds->Set(
kFieldTrialDescriptor,
kFieldTrialDescriptor + base::GlobalDescriptors::kBaseDescriptor);
#endif // !OS_ANDROID
#if defined(OS_LINUX) || defined(OS_OPENBSD)
g_fds->Set(kCrashDumpSignal,
kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor);
#endif // OS_LINUX || OS_OPENBSD
#endif // !OS_WIN
is_initialized_ = true;
delegate_ = params.delegate;
// The exit manager is in charge of calling the dtors of singleton objects.
// On Android, AtExitManager is set up when library is loaded.
// A consequence of this is that you can't use the ctor/dtor-based
// TRACE_EVENT methods on Linux or iOS builds till after we set this up.
#if !defined(OS_ANDROID)
if (!ui_task_) {
// When running browser tests, don't create a second AtExitManager as that
// interfers with shutdown when objects created before ContentMain is
// called are destructed when it returns.
exit_manager_.reset(new base::AtExitManager);
}
#endif // !OS_ANDROID
int exit_code = 0;
if (delegate_ && delegate_->BasicStartupComplete(&exit_code))
return exit_code;
completed_basic_startup_ = true;
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
#if defined(OS_WIN)
if (command_line.HasSwitch(switches::kDeviceScaleFactor)) {
std::string scale_factor_string = command_line.GetSwitchValueASCII(
switches::kDeviceScaleFactor);
double scale_factor = 0;
if (base::StringToDouble(scale_factor_string, &scale_factor))
display::win::SetDefaultDeviceScaleFactor(scale_factor);
}
#endif
if (!GetContentClient())
SetContentClient(&empty_content_client_);
ContentClientInitializer::Set(process_type, delegate_);
#if !defined(OS_ANDROID)
// Enable startup tracing asap to avoid early TRACE_EVENT calls being
// ignored. For Android, startup tracing is enabled in an even earlier place
// content/app/android/library_loader_hooks.cc.
// Zygote process does not have file thread and renderer process on Win10
// cannot access the file system.
// TODO(ssid): Check if other processes can enable startup tracing here.
bool can_access_file_system = (process_type != switches::kZygoteProcess &&
process_type != switches::kRendererProcess);
tracing::EnableStartupTracingIfNeeded(can_access_file_system);
#endif // !OS_ANDROID
#if defined(OS_WIN)
// Enable exporting of events to ETW if requested on the command line.
if (command_line.HasSwitch(switches::kTraceExportEventsToETW))
base::trace_event::TraceEventETWExport::EnableETWExport();
#endif // OS_WIN
#if !defined(OS_ANDROID)
// Android tracing started at the beginning of the method.
// Other OSes have to wait till we get here in order for all the memory
// management setup to be completed.
TRACE_EVENT0("startup,benchmark,rail", "ContentMainRunnerImpl::Initialize");
#endif // !OS_ANDROID
#if defined(OS_MACOSX)
// We need to allocate the IO Ports before the Sandbox is initialized or
// the first instance of PowerMonitor is created.
// It's important not to allocate the ports for processes which don't
// register with the power monitor - see crbug.com/88867.
if (process_type.empty() ||
(delegate_ &&
delegate_->ProcessRegistersWithSystemProcess(process_type))) {
base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
}
if (!process_type.empty() &&
(!delegate_ || delegate_->ShouldSendMachPort(process_type))) {
MachBroker::ChildSendTaskPortToParent();
}
#endif
// If we are on a platform where the default allocator is overridden (shim
// layer on windows, tcmalloc on Linux Desktop) smoke-tests that the
// overriding logic is working correctly. If not causes a hard crash, as its
// unexpected absence has security implications.
CHECK(base::allocator::IsAllocatorInitialized());
#if defined(OS_POSIX)
if (!process_type.empty()) {
// When you hit Ctrl-C in a terminal running the browser
// process, a SIGINT is delivered to the entire process group.
// When debugging the browser process via gdb, gdb catches the
// SIGINT for the browser process (and dumps you back to the gdb
// console) but doesn't for the child processes, killing them.
// The fix is to have child processes ignore SIGINT; they'll die
// on their own when the browser process goes away.
//
// Note that we *can't* rely on BeingDebugged to catch this case because
// we are the child process, which is not being debugged.
// TODO(evanm): move this to some shared subprocess-init function.
if (!base::debug::BeingDebugged())
signal(SIGINT, SIG_IGN);
}
#endif
RegisterPathProvider();
RegisterContentSchemes(true);
#if defined(OS_ANDROID) && (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE)
int icudata_fd = g_fds->MaybeGet(kAndroidICUDataDescriptor);
if (icudata_fd != -1) {
auto icudata_region = g_fds->GetRegion(kAndroidICUDataDescriptor);
if (!base::i18n::InitializeICUWithFileDescriptor(icudata_fd,
icudata_region))
return TerminateForFatalInitializationError();
} else {
if (!base::i18n::InitializeICU())
return TerminateForFatalInitializationError();
}
#else
if (!base::i18n::InitializeICU())
return TerminateForFatalInitializationError();
#endif // OS_ANDROID && (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE)
InitializeV8IfNeeded(command_line, process_type);
#if !defined(OFFICIAL_BUILD)
#if defined(OS_WIN)
bool should_enable_stack_dump = !process_type.empty();
#else
bool should_enable_stack_dump = true;
#endif
// Print stack traces to stderr when crashes occur. This opens up security
// holes so it should never be enabled for official builds. This needs to
// happen before crash reporting is initialized (which for chrome happens in
// the call to PreSandboxStartup() on the delegate below), because otherwise
// this would interfere with signal handlers used by crash reporting.
if (should_enable_stack_dump &&
!command_line.HasSwitch(
service_manager::switches::kDisableInProcessStackTraces)) {
base::debug::EnableInProcessStackDumping();
}
#endif // !defined(OFFICIAL_BUILD)
if (delegate_)
delegate_->PreSandboxStartup();
#if defined(OS_WIN)
if (!InitializeSandbox(
service_manager::SandboxTypeFromCommandLine(command_line),
params.sandbox_info))
return TerminateForFatalInitializationError();
#elif defined(OS_MACOSX)
// Do not initialize the sandbox at this point if the V2
// sandbox is enabled for the process type.
bool v2_enabled = base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableV2Sandbox);
if (process_type == switches::kRendererProcess ||
process_type == switches::kPpapiPluginProcess || v2_enabled ||
(delegate_ && delegate_->DelaySandboxInitialization(process_type))) {
// On OS X the renderer sandbox needs to be initialized later in the
// startup sequence in RendererMainPlatformDelegate::EnableSandbox().
} else {
if (!InitializeSandbox())
return TerminateForFatalInitializationError();
}
#endif
if (delegate_)
delegate_->SandboxInitialized(process_type);
// Return -1 to indicate no early termination.
return -1;
}
int Run() override {
DCHECK(is_initialized_);
DCHECK(!is_shutdown_);
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
// Run this logic on all child processes. Zygotes will run this at a later
// point in time when the command line has been updated.
std::unique_ptr<base::FieldTrialList> field_trial_list;
if (!process_type.empty() && process_type != switches::kZygoteProcess)
InitializeFieldTrialAndFeatureList(&field_trial_list);
MainFunctionParams main_params(command_line);
main_params.ui_task = ui_task_;
main_params.created_main_parts_closure = created_main_parts_closure_;
#if defined(OS_WIN)
main_params.sandbox_info = &sandbox_info_;
#elif defined(OS_MACOSX)
main_params.autorelease_pool = autorelease_pool_;
#endif
return RunNamedProcessTypeMain(process_type, main_params, delegate_);
}
void Shutdown() override {
DCHECK(is_initialized_);
DCHECK(!is_shutdown_);
if (completed_basic_startup_ && delegate_) {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
delegate_->ProcessExiting(process_type);
}
#if defined(OS_WIN)
#ifdef _CRTDBG_MAP_ALLOC
_CrtDumpMemoryLeaks();
#endif // _CRTDBG_MAP_ALLOC
#endif // OS_WIN
exit_manager_.reset(nullptr);
delegate_ = nullptr;
is_shutdown_ = true;
}
private:
// True if the runner has been initialized.
bool is_initialized_ = false;
// True if the runner has been shut down.
bool is_shutdown_ = false;
// True if basic startup was completed.
bool completed_basic_startup_ = false;
// Used if the embedder doesn't set one.
ContentClient empty_content_client_;
// The delegate will outlive this object.
ContentMainDelegate* delegate_ = nullptr;
std::unique_ptr<base::AtExitManager> exit_manager_;
#if defined(OS_WIN)
sandbox::SandboxInterfaceInfo sandbox_info_;
#elif defined(OS_MACOSX)
base::mac::ScopedNSAutoreleasePool* autorelease_pool_ = nullptr;
#endif
base::Closure* ui_task_ = nullptr;
CreatedMainPartsClosure* created_main_parts_closure_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl);
};
// static
ContentMainRunner* ContentMainRunner::Create() {
return new ContentMainRunnerImpl();
}
} // namespace content
| [
"sokolov.p@gmail.com"
] | sokolov.p@gmail.com |
b9611ca62c9c60bb395f85e34c932f8b1f125b3b | c7693de80148bc9e6fa38e7bcf59717e6bcf1d93 | /src/cyberlink/control/ControlResponse.cpp | 173405368575faf3516d830e91b2f0b33e36bd6f | [] | no_license | muidea/magicMirror | bea6d0fe2696573641042528670a961756895828 | 8d301c26b8055cec7f48913f4497a52c6d5c91f7 | refs/heads/master | 2021-01-20T06:51:04.723500 | 2017-05-13T16:19:08 | 2017-05-13T16:19:08 | 89,934,711 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,984 | cpp | /******************************************************************
*
* CyberLink for C++
*
* Copyright (C) Satoshi Konno 2002
*
* File: ControlResponse.cpp
*
* Revision;
*
* 08/13/03
* - first revision
*
******************************************************************/
#include <control/ControlResponse.h>
#include <Device.h>
#include <string>
using namespace std;
using namespace CyberLink;
using namespace CyberLink;
////////////////////////////////////////////////
// Constants
////////////////////////////////////////////////
const char *ControlResponse::FAULT_CODE = "Client";
const char *ControlResponse::FAULT_STRING = "UPnPError";
////////////////////////////////////////////////
// FaultResponse
////////////////////////////////////////////////
void ControlResponse::setFaultResponse(int errCode, const std::string &errDescr) {
setStatusCode(HTTP::INTERNAL_SERVER_ERROR);
cyber_shared_ptr<uXML::Node> bodyNode = getBodyNode();
uXML::Node *faultNode = createFaultResponseNode(errCode, errDescr);
cyber_shared_ptr<uXML::Node> newNode(faultNode);
bodyNode->addNode(newNode);
cyber_shared_ptr<uXML::Node> envNode = getEnvelopeNode();
setContent(envNode.get());
}
uXML::Node *ControlResponse::createFaultResponseNode(int errCode, const std::string &errDescr) {
// <s:Fault>
string faultNodeName;
faultNodeName = uSOAP::SOAP::XMLNS;
faultNodeName += uSOAP::SOAP::DELIM;
faultNodeName += uSOAP::SOAP::FAULT;
uXML::Node *faultNode = new uXML::Node(faultNodeName.c_str());
// <faultcode>s:Client</faultcode>
uXML::Node *faultCodeNode = new uXML::Node(uSOAP::SOAP::FAULT_CODE);
string faultCodeNodeValue;
faultCodeNodeValue = uSOAP::SOAP::XMLNS;
faultCodeNodeValue += uSOAP::SOAP::DELIM;
faultCodeNodeValue += FAULT_CODE;
faultCodeNode->setValue(faultCodeNodeValue.c_str());
cyber_shared_ptr<uXML::Node> newNode(faultCodeNode);
faultNode->addNode(newNode);
// <faultstring>UPnPError</faultstring>
cyber_shared_ptr<uXML::Node> faultStringNode(new uXML::Node(uSOAP::SOAP::FAULT_STRING));
faultStringNode->setValue(FAULT_STRING);
faultNode->addNode(faultStringNode);
// <detail>
cyber_shared_ptr<uXML::Node> detailNode(new uXML::Node(uSOAP::SOAP::DETAIL));
faultNode->addNode(detailNode);
// <UPnPError xmlns="urn:schemas-upnp-org:control-1-0">
cyber_shared_ptr<uXML::Node> upnpErrorNode(new uXML::Node(FAULT_STRING));
upnpErrorNode->setAttribute("xmlns", Control::XMLNS);
detailNode->addNode(upnpErrorNode);
// <errorCode>error code</errorCode>
cyber_shared_ptr<uXML::Node> errorCodeNode(new uXML::Node(uSOAP::SOAP::ERROR_CODE));
errorCodeNode->setValue(errCode);
upnpErrorNode->addNode(errorCodeNode);
// <errorDescription>error string</errorDescription>
cyber_shared_ptr<uXML::Node> errorDesctiprionNode(new uXML::Node(uSOAP::SOAP::ERROR_DESCRIPTION));
errorDesctiprionNode->setValue(errDescr);
upnpErrorNode->addNode(errorDesctiprionNode);
return faultNode;
}
| [
"muidea@gmail.com"
] | muidea@gmail.com |
da984e6a7ddd43e4daa52a88ae2a67cbdd1e6fc3 | 6ab6a8ea4493eea105734bd0fece9a61e59afa79 | /public/codes/kruskals/kruskals.cpp | 8c442bbd0ecd5bd929f4679bc670a52850e13f31 | [
"MIT"
] | permissive | myNameArnav/dsa-visualizer | 7e397c486be29ff611357dc27563bf3aa41c3558 | 4076297ba24462e7361cb621176f370b3cd60043 | refs/heads/main | 2023-08-22T16:07:42.605293 | 2021-09-27T11:10:29 | 2021-09-27T11:10:29 | 411,303,897 | 1 | 0 | MIT | 2021-09-28T13:57:09 | 2021-09-28T13:57:08 | null | UTF-8 | C++ | false | false | 3,015 | cpp | // C++ program for Kruskal's algorithm to find Minimum
// Spanning Tree of a given connected, undirected and
// weighted graph
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Creating shortcut for an integer pair
typedef pair<int, int> iPair;
// Structure to represent a graph
struct Graph
{
int V, E;
vector< pair<int, iPair> > edges;
// Constructor
Graph(int V, int E)
{
this->V = V;
this->E = E;
}
// Utility function to add an edge
void addEdge(int u, int v, int w)
{
edges.push_back({w, {u, v}});
}
// Function to find MST using Kruskal's
// MST algorithm
int kruskalMST();
};
// To represent Disjoint Sets
struct DisjointSets
{
int *parent, *rnk;
int n;
// Constructor.
DisjointSets(int n)
{
// Allocate memory
this->n = n;
parent = new int[n+1];
rnk = new int[n+1];
// Initially, all vertices are in
// different sets and have rank 0.
for (int i = 0; i <= n; i++)
{
rnk[i] = 0;
//every element is parent of itself
parent[i] = i;
}
}
// Find the parent of a node 'u'
// Path Compression
int find(int u)
{
/* Make the parent of the nodes in the path
from u--> parent[u] point to parent[u] */
if (u != parent[u])
parent[u] = find(parent[u]);
return parent[u];
}
// Union by rank
void merge(int x, int y)
{
x = find(x), y = find(y);
/* Make tree with smaller height
a subtree of the other tree */
if (rnk[x] > rnk[y])
parent[y] = x;
else
parent[x] = y;
if (rnk[x] == rnk[y])
rnk[y]++;
}
};
/* Functions returns weight of the MST*/
int Graph::kruskalMST()
{
int mst_wt = 0; // Initialize result
// Sort edges in increasing order on basis of cost
sort(edges.begin(), edges.end());
// Create disjoint sets
DisjointSets ds(V);
// Iterate through all sorted edges
vector< pair<int, iPair> >::iterator it;
for (it=edges.begin(); it!=edges.end(); it++)
{
int u = it->second.first;
int v = it->second.second;
int set_u = ds.find(u);
int set_v = ds.find(v);
// Check if the selected edge is creating
// a cycle or not (Cycle is created if u
// and v belong to same set)
if (set_u != set_v)
{
// Current edge will be in the MST
// so print it
cout << u << " - " << v << endl;
// Update MST weight
mst_wt += it->first;
// Merge two sets
ds.merge(set_u, set_v);
}
}
return mst_wt;
}
// Driver program to test above functions
int main()
{
int V = 9, E = 14;
Graph g(V, E);
g.addEdge(0, 1, 4);
g.addEdge(0, 7, 8);
g.addEdge(1, 2, 8);
g.addEdge(1, 7, 11);
g.addEdge(2, 3, 7);
g.addEdge(2, 8, 2);
g.addEdge(2, 5, 4);
g.addEdge(3, 4, 9);
g.addEdge(3, 5, 14);
g.addEdge(4, 5, 10);
g.addEdge(5, 6, 2);
g.addEdge(6, 7, 1);
g.addEdge(6, 8, 6);
g.addEdge(7, 8, 7);
cout << "Edges of MST are \n";
int mst_wt = g.kruskalMST();
cout << "\nWeight of MST is " << mst_wt;
return 0;
}
// Output:
// Edges of MST are
// 6 - 7
// 2 - 8
// 5 - 6
// 0 - 1
// 2 - 5
// 2 - 3
// 0 - 7
// 3 - 4
// Weight of MST is 37
| [
"sahilahmed0707@gmail.com"
] | sahilahmed0707@gmail.com |
626b423ace85c9792575f2819c1afd90be490d4d | bd1bad37425d942964d8630bca2263e13d303515 | /vendor/bela/include/bela/details/charconv_fwd.hpp | 820a8ba277707961c5aa18312ecdbe3cbcc36264 | [
"Apache-2.0",
"MIT"
] | permissive | fcharlie/Planck | 78855cdd4c659cd053bfbf6ac7913f5d12ad9b8c | 56861b3d3a62ea16becea965bc3bc0198f28e26a | refs/heads/master | 2021-06-06T09:35:44.525162 | 2021-05-17T13:48:44 | 2021-05-17T13:48:44 | 161,035,393 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,207 | hpp | // Porting from MSVC STL
// xcharconv.h internal header
// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef BELA_DETAILS_CHARCONV_FWD_HPP
#define BELA_DETAILS_CHARCONV_FWD_HPP
#include <type_traits>
#include <system_error>
#include <cstring>
#include <cstdint>
#ifdef __has_attribute
#define BELA_HAVE_ATTRIBUTE(x) __has_attribute(x)
#else
#define BELA_HAVE_ATTRIBUTE(x) 0
#endif
#if BELA_HAVE_ATTRIBUTE(always_inline) || \
(defined(__GNUC__) && !defined(__clang__))
#define BELA_ATTRIBUTE_ALWAYS_INLINE __attribute__((always_inline))
#else
#define BELA_ATTRIBUTE_ALWAYS_INLINE
#endif
#if defined(_MSC_VER)
// We can achieve something similar to attribute((always_inline)) with MSVC by
// using the __forceinline keyword, however this is not perfect. MSVC is
// much less aggressive about inlining, and even with the __forceinline keyword.
#define BELA_BASE_INTERNAL_FORCEINLINE __forceinline
#else
// Use default attribute inline.
#define BELA_BASE_INTERNAL_FORCEINLINE inline BELA_ATTRIBUTE_ALWAYS_INLINE
#endif
namespace bela {
enum class chars_format {
scientific = 0b001,
fixed = 0b010,
hex = 0b100,
general = fixed | scientific,
};
[[nodiscard]] constexpr chars_format operator&(chars_format L,
chars_format R) noexcept {
using I = std::underlying_type_t<chars_format>;
return static_cast<chars_format>(static_cast<I>(L) & static_cast<I>(R));
}
[[nodiscard]] constexpr chars_format operator|(chars_format L,
chars_format R) noexcept {
using I = std::underlying_type_t<chars_format>;
return static_cast<chars_format>(static_cast<I>(L) | static_cast<I>(R));
}
struct to_chars_result {
wchar_t *ptr;
std::errc ec;
};
template <typename T> T _Min_value(T a, T b) { return a < b ? a : b; }
template <typename T> T _Max_value(T a, T b) { return a > b ? a : b; }
template <typename T> void ArrayCopy(void *dst, const T *src, size_t n) {
memcpy(dst, src, n * sizeof(T));
}
template <typename T> void Memset(T *buf, T ch, size_t n) {
std::fill_n(buf, n, ch);
}
} // namespace bela
#endif
| [
"charlieio@outlook.com"
] | charlieio@outlook.com |
d7913e3ab420cd64606e244c4e8ff76c5e67665f | 01e21d29af961df02e516e729c26c381ce1d485d | /modules/squarepine_core/maths/Trigonometry.h | 59fc8b3b2d1d5ca0adef533612e603e9c3d03e10 | [
"ISC"
] | permissive | thinium/squarepine_core | 1f92848d668b9af48124e24891c2e1b85fe74532 | 9d73b0820b8b44129b62a643785e8a7d4a7035b0 | refs/heads/main | 2023-07-16T04:30:09.089866 | 2021-08-06T14:25:10 | 2021-08-06T14:25:10 | 383,528,340 | 0 | 0 | NOASSERTION | 2021-07-06T16:10:59 | 2021-07-06T16:10:58 | null | UTF-8 | C++ | false | false | 3,747 | h | //==============================================================================
/** Cas function */
inline double cas (double x) noexcept { return std::sin (x) + std::cos (x); }
/** Cas function */
inline float cas (float x) noexcept { return std::sin (x) + std::cos (x); }
/** Cas function */
template<typename Type>
inline Type cas (Type x) noexcept { return (Type) cas ((double) x); }
//==============================================================================
/** Cotangent function */
inline double cot (double x) noexcept { return std::cos (x) / std::sin (x); }
/** Cotangent function */
inline float cot (float x) noexcept { return std::cos (x) / std::sin (x); }
/** Cotangent function */
template<typename Type>
inline Type cot (Type x) noexcept { return (Type) cot ((double) x); }
//==============================================================================
/** Cosecant function */
inline double csc (double x) noexcept { return 1.0 / std::sin (x); }
/** Cosecant function */
inline float csc (float x) noexcept { return 1.0f / std::sin (x); }
/** Cosecant function */
template<typename Type>
inline Type csc (Type x) noexcept { return (Type) csc ((double) x); }
//==============================================================================
/** Secant function */
inline double sec (double x) noexcept { return 1.0 / std::cos (x); }
/** Secant function */
inline float sec (float x) noexcept { return 1.0f / std::cos (x); }
/** Secant function */
template<typename Type>
inline Type sec (Type x) noexcept { return (Type) sec ((double) x); }
//==============================================================================
/** Versine function */
inline double versin (double x) noexcept { return 1.0 - std::cos (x); }
/** Versine function */
inline float versin (float x) noexcept { return 1.0f - std::cos (x); }
/** Versine function */
template<typename Type>
inline Type versin (Type x) noexcept { return (Type) versin ((double) x); }
//==============================================================================
/** Vercosine function */
inline double vercosin (double x) noexcept { return 1.0 + std::cos (x); }
/** Vercosine function */
inline float vercosin (float x) noexcept { return 1.0f + std::cos (x); }
/** Vercosine function */
template<typename Type>
inline Type vercosin (Type x) noexcept { return (Type) vercosin ((double) x); }
//==============================================================================
/** Coversine function */
inline double coversin (double x) noexcept { return 1.0 + std::cos (x); }
/** Coversine function */
inline float coversin (float x) noexcept { return 1.0f + std::cos (x); }
/** Coversine function */
template<typename Type>
inline Type coversin (Type x) noexcept { return (Type) vercosin ((double) x); }
//==============================================================================
/** Exsecant function */
inline double exsec (double x) noexcept { return sec (x) - 1.0; }
/** Exsecant function */
inline float exsec (float x) noexcept { return sec (x) - 1.0f; }
/** Exsecant function */
template<typename Type>
inline Type exsec (Type x) noexcept { return (Type) exsec ((double) x); }
//==============================================================================
/** Excosecant function */
inline double excsc (double x) noexcept { return csc (x) - 1.0; }
/** Excosecant function */
inline float excsc (float x) noexcept { return csc (x) - 1.0f; }
/** Excosecant function */
template<typename Type>
inline Type excsc (Type x) noexcept { return (Type) excsc ((double) x); }
| [
"joel.r.langlois@gmail.com"
] | joel.r.langlois@gmail.com |
12200bc5ad97374c11a03ca15ea98555cab1dc42 | 65b9a9ffa4333c01daa58e25d6b486607aec95f2 | /Code/SkinMesh.h | 03dc1c4f73a8e2d681580ccd8a7242398e37fbd7 | [] | no_license | followDreamLgx/Snake | 871d273f5bdd8682c2a7d214cf26f6b0c68a018d | 20701610205026fef6e2a12768b9e8502fea3c80 | refs/heads/master | 2021-01-10T11:45:35.544133 | 2016-03-03T14:34:21 | 2016-03-03T14:34:21 | 53,056,341 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,457 | h | //=============================================================================
// SkinMesh.h: 蒙皮网格模型类的定义
//=============================================================================
# ifndef _SKINMESH_H
# define _SKINMESH_H
#include "AllocateHierarchy.h"
class CSkinMesh
{
private:
CAllocateHierarchy* m_pAlloc;
LPDIRECT3DDEVICE9 m_pd3dDevice;
LPD3DXFRAME m_pFrameRoot;
D3DXMATRIXA16* m_pBoneMatrices;
UINT m_NumBoneMatricesMax;
BOUNDINGSPHERE sphere;
public:
D3DXVECTOR3 m_vObjectCenter;
float m_fObjectRadius;
BOOL m_bPlayAnim;
LPD3DXANIMATIONCONTROLLER m_pAnimController; //动画控制相关变量
LPD3DXANIMATIONSET m_pAnimationset; //
private:
HRESULT SetupBoneMatrixPointers( LPD3DXFRAME pFrame );
HRESULT SetupBoneMatrixPointersOnMesh( LPD3DXMESHCONTAINER pMeshContainerBase );
HRESULT LoadFromXFile(WCHAR* strFileName);
VOID UpdateFrameMatrices( LPD3DXFRAME pFrameBase, LPD3DXMATRIX pParentMatrix );
VOID DrawFrame(LPD3DXFRAME pFrame);
VOID DrawMeshContainer(LPD3DXMESHCONTAINER pMeshContainerBase, LPD3DXFRAME pFrameBase);
public:
HRESULT OnCreate(LPDIRECT3DDEVICE9 pD3DDevice, WCHAR* strFileName);
HRESULT Render(D3DXMATRIXA16* matWorld, double fElapsedAppTime);
HRESULT OnDestory();
void set_animation(char *); //自定义函数,用于设置骨骼动画
public:
CSkinMesh();
virtual ~CSkinMesh();
};
# endif
| [
"254784121@qq.c"
] | 254784121@qq.c |
b1a2f4dc223163dd733aa5f773282679ee731bc0 | bd18edfafeec1470d9776f5a696780cbd8c2e978 | /SlimDX/source/direct2d/Geometry.cpp | 120a559d5c732b4576854c0fa3e70b807b437a29 | [
"MIT"
] | permissive | MogreBindings/EngineDeps | 1e37db6cd2aad791dfbdfec452111c860f635349 | 7d1b8ecaa2cbd8e8e21ec47b3ce3a5ab979bdde7 | refs/heads/master | 2023-03-30T00:45:53.489795 | 2020-06-30T10:48:12 | 2020-06-30T10:48:12 | 276,069,149 | 0 | 1 | null | 2021-04-05T16:05:53 | 2020-06-30T10:33:46 | C++ | UTF-8 | C++ | false | false | 18,462 | cpp | /*
* Copyright (c) 2007-2010 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "stdafx.h"
#include <d2d1.h>
#include <d2d1helper.h>
#include "Direct2DException.h"
#include "ConversionMethods.h"
#include "Geometry.h"
const IID IID_ID2D1Geometry = __uuidof(ID2D1Geometry);
using namespace System;
namespace SlimDX
{
namespace Direct2D
{
Result Geometry::Combine( Geometry^ geometry1, Geometry^ geometry2, CombineMode combineMode, SimplifiedGeometrySink^ geometrySink )
{
HRESULT hr = geometry1->InternalPointer->CombineWithGeometry( geometry2->InternalPointer, static_cast<D2D1_COMBINE_MODE>( combineMode ),
NULL, geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Combine( Geometry^ geometry1, Geometry^ geometry2, CombineMode combineMode, Matrix3x2 transform, SimplifiedGeometrySink^ geometrySink )
{
HRESULT hr = geometry1->InternalPointer->CombineWithGeometry( geometry2->InternalPointer, static_cast<D2D1_COMBINE_MODE>( combineMode ),
reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Combine( Geometry^ geometry1, Geometry^ geometry2, CombineMode combineMode, Matrix3x2 transform, float flatteningTolerance, SimplifiedGeometrySink^ geometrySink )
{
HRESULT hr = geometry1->InternalPointer->CombineWithGeometry( geometry2->InternalPointer, static_cast<D2D1_COMBINE_MODE>( combineMode ),
reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
GeometryRelation Geometry::Compare( Geometry^ geometry1, Geometry^ geometry2 )
{
D2D1_GEOMETRY_RELATION result;
HRESULT hr = geometry1->InternalPointer->CompareWithGeometry( geometry2->InternalPointer, NULL, &result );
RECORD_D2D( hr );
return static_cast<GeometryRelation>( result );
}
GeometryRelation Geometry::Compare( Geometry^ geometry1, Geometry^ geometry2, Matrix3x2 transform )
{
D2D1_GEOMETRY_RELATION result;
HRESULT hr = geometry1->InternalPointer->CompareWithGeometry( geometry2->InternalPointer, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), &result );
RECORD_D2D( hr );
return static_cast<GeometryRelation>( result );
}
GeometryRelation Geometry::Compare( Geometry^ geometry1, Geometry^ geometry2, Matrix3x2 transform, float flatteningTolerance )
{
D2D1_GEOMETRY_RELATION result;
HRESULT hr = geometry1->InternalPointer->CompareWithGeometry( geometry2->InternalPointer, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, &result );
RECORD_D2D( hr );
return static_cast<GeometryRelation>( result );
}
float Geometry::ComputeArea( Geometry^ geometry )
{
float area = 0.0f;
HRESULT hr = geometry->InternalPointer->ComputeArea( NULL, &area );
RECORD_D2D( hr );
return area;
}
float Geometry::ComputeArea( Geometry^ geometry, Matrix3x2 transform )
{
float area = 0.0f;
HRESULT hr = geometry->InternalPointer->ComputeArea( reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), &area );
RECORD_D2D( hr );
return area;
}
float Geometry::ComputeArea( Geometry^ geometry, Matrix3x2 transform, float flatteningTolerance )
{
float area = 0.0f;
HRESULT hr = geometry->InternalPointer->ComputeArea( reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, &area );
RECORD_D2D( hr );
return area;
}
float Geometry::ComputeLength( Geometry^ geometry )
{
float length = 0.0f;
HRESULT hr = geometry->InternalPointer->ComputeLength( NULL, &length );
RECORD_D2D( hr );
return length;
}
float Geometry::ComputeLength( Geometry^ geometry, Matrix3x2 transform )
{
float length = 0.0f;
HRESULT hr = geometry->InternalPointer->ComputeLength( reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), &length );
RECORD_D2D( hr );
return length;
}
float Geometry::ComputeLength( Geometry^ geometry, Matrix3x2 transform, float flatteningTolerance )
{
float length = 0.0f;
HRESULT hr = geometry->InternalPointer->ComputeLength( reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, &length );
RECORD_D2D( hr );
return length;
}
System::Drawing::PointF Geometry::ComputePointAtLength( Geometry^ geometry, float length )
{
D2D1_POINT_2F point;
HRESULT hr = geometry->InternalPointer->ComputePointAtLength( length, NULL, &point, NULL );
RECORD_D2D( hr );
return System::Drawing::PointF( point.x, point.y );
}
System::Drawing::PointF Geometry::ComputePointAtLength( Geometry^ geometry, float length, Matrix3x2 transform )
{
D2D1_POINT_2F point;
HRESULT hr = geometry->InternalPointer->ComputePointAtLength( length, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), &point, NULL );
RECORD_D2D( hr );
return System::Drawing::PointF( point.x, point.y );
}
System::Drawing::PointF Geometry::ComputePointAtLength( Geometry^ geometry, float length, Matrix3x2 transform, float flatteningTolerance )
{
D2D1_POINT_2F point;
HRESULT hr = geometry->InternalPointer->ComputePointAtLength( length, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, &point, NULL );
RECORD_D2D( hr );
return System::Drawing::PointF( point.x, point.y );
}
System::Drawing::PointF Geometry::ComputePointAtLength( Geometry^ geometry, float length, Matrix3x2 transform, float flatteningTolerance, [Out] Vector2% unitTangentVector )
{
D2D1_POINT_2F point;
D2D1_POINT_2F tangent;
HRESULT hr = geometry->InternalPointer->ComputePointAtLength( length, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, &point, &tangent );
RECORD_D2D( hr );
unitTangentVector = Vector2( tangent.x, tangent.y );
return System::Drawing::PointF( point.x, point.y );
}
bool Geometry::FillContainsPoint( Geometry^ geometry, System::Drawing::Point point )
{
return FillContainsPoint( geometry, CastPoint( point ) );
}
bool Geometry::FillContainsPoint( Geometry^ geometry, System::Drawing::Point point, Matrix3x2 transform )
{
return FillContainsPoint( geometry, CastPoint( point ), transform );
}
bool Geometry::FillContainsPoint( Geometry^ geometry, System::Drawing::Point point, Matrix3x2 transform, float flatteningTolerance )
{
return FillContainsPoint( geometry, CastPoint( point ), transform, flatteningTolerance );
}
bool Geometry::FillContainsPoint( Geometry^ geometry, System::Drawing::PointF point )
{
BOOL result;
D2D1_POINT_2F p = D2D1::Point2F( point.X, point.Y );
HRESULT hr = geometry->InternalPointer->FillContainsPoint( p, NULL, &result );
RECORD_D2D( hr );
return result > 0;
}
bool Geometry::FillContainsPoint( Geometry^ geometry, System::Drawing::PointF point, Matrix3x2 transform )
{
BOOL result;
D2D1_POINT_2F p = D2D1::Point2F( point.X, point.Y );
HRESULT hr = geometry->InternalPointer->FillContainsPoint( p, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), &result );
RECORD_D2D( hr );
return result > 0;
}
bool Geometry::FillContainsPoint( Geometry^ geometry, System::Drawing::PointF point, Matrix3x2 transform, float flatteningTolerance )
{
BOOL result;
D2D1_POINT_2F p = D2D1::Point2F( point.X, point.Y );
HRESULT hr = geometry->InternalPointer->FillContainsPoint( p, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, &result );
RECORD_D2D( hr );
return result > 0;
}
System::Drawing::RectangleF Geometry::GetBounds( Geometry^ geometry )
{
D2D1_RECT_F bounds;
HRESULT hr = geometry->InternalPointer->GetBounds( NULL, &bounds );
RECORD_D2D( hr );
return System::Drawing::RectangleF::FromLTRB( bounds.left, bounds.top, bounds.right, bounds.bottom );
}
System::Drawing::RectangleF Geometry::GetBounds( Geometry^ geometry, Matrix3x2 transform )
{
D2D1_RECT_F bounds;
HRESULT hr = geometry->InternalPointer->GetBounds( reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), &bounds );
RECORD_D2D( hr );
return System::Drawing::RectangleF::FromLTRB( bounds.left, bounds.top, bounds.right, bounds.bottom );
}
System::Drawing::RectangleF Geometry::GetWidenedBounds( Geometry^ geometry, float strokeWidth )
{
D2D1_RECT_F bounds;
HRESULT hr = geometry->InternalPointer->GetWidenedBounds( strokeWidth, NULL, NULL, &bounds );
RECORD_D2D( hr );
return System::Drawing::RectangleF::FromLTRB( bounds.left, bounds.top, bounds.right, bounds.bottom );
}
System::Drawing::RectangleF Geometry::GetWidenedBounds( Geometry^ geometry, float strokeWidth, StrokeStyle^ strokeStyle )
{
ID2D1StrokeStyle *ss = strokeStyle == nullptr ? NULL : strokeStyle->InternalPointer;
D2D1_RECT_F bounds;
HRESULT hr = geometry->InternalPointer->GetWidenedBounds( strokeWidth, ss, NULL, &bounds );
RECORD_D2D( hr );
return System::Drawing::RectangleF::FromLTRB( bounds.left, bounds.top, bounds.right, bounds.bottom );
}
System::Drawing::RectangleF Geometry::GetWidenedBounds( Geometry^ geometry, float strokeWidth, StrokeStyle^ strokeStyle, Matrix3x2 transform )
{
ID2D1StrokeStyle *ss = strokeStyle == nullptr ? NULL : strokeStyle->InternalPointer;
D2D1_RECT_F bounds;
HRESULT hr = geometry->InternalPointer->GetWidenedBounds( strokeWidth, ss, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), &bounds );
RECORD_D2D( hr );
return System::Drawing::RectangleF::FromLTRB( bounds.left, bounds.top, bounds.right, bounds.bottom );
}
System::Drawing::RectangleF Geometry::GetWidenedBounds( Geometry^ geometry, float strokeWidth, StrokeStyle^ strokeStyle, Matrix3x2 transform, float flatteningTolerance )
{
ID2D1StrokeStyle *ss = strokeStyle == nullptr ? NULL : strokeStyle->InternalPointer;
D2D1_RECT_F bounds;
HRESULT hr = geometry->InternalPointer->GetWidenedBounds( strokeWidth, ss, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, &bounds );
RECORD_D2D( hr );
return System::Drawing::RectangleF::FromLTRB( bounds.left, bounds.top, bounds.right, bounds.bottom );
}
Result Geometry::Outline( Geometry^ geometry, SimplifiedGeometrySink^ geometrySink )
{
HRESULT hr = geometry->InternalPointer->Outline( NULL, geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Outline( Geometry^ geometry, Matrix3x2 transform, SimplifiedGeometrySink^ geometrySink )
{
HRESULT hr = geometry->InternalPointer->Outline( reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Outline( Geometry^ geometry, Matrix3x2 transform, float flatteningTolerance, SimplifiedGeometrySink^ geometrySink )
{
HRESULT hr = geometry->InternalPointer->Outline( reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
bool Geometry::StrokeContainsPoint( Geometry^ geometry, System::Drawing::Point point, float strokeWidth )
{
return StrokeContainsPoint( geometry, CastPoint( point ), strokeWidth );
}
bool Geometry::StrokeContainsPoint( Geometry^ geometry, System::Drawing::Point point, float strokeWidth, StrokeStyle^ strokeStyle )
{
return StrokeContainsPoint( geometry, CastPoint( point ), strokeWidth, strokeStyle );
}
bool Geometry::StrokeContainsPoint( Geometry^ geometry, System::Drawing::Point point, float strokeWidth, StrokeStyle^ strokeStyle, Matrix3x2 transform )
{
return StrokeContainsPoint( geometry, CastPoint( point ), strokeWidth, strokeStyle, transform );
}
bool Geometry::StrokeContainsPoint( Geometry^ geometry, System::Drawing::Point point, float strokeWidth, StrokeStyle^ strokeStyle, Matrix3x2 transform, float flatteningTolerance )
{
return StrokeContainsPoint( geometry, CastPoint( point ), strokeWidth, strokeStyle, transform, flatteningTolerance );
}
bool Geometry::StrokeContainsPoint( Geometry^ geometry, System::Drawing::PointF point, float strokeWidth )
{
BOOL result;
D2D1_POINT_2F p = D2D1::Point2F( point.X, point.Y );
HRESULT hr = geometry->InternalPointer->StrokeContainsPoint( p, strokeWidth, NULL, NULL, &result );
RECORD_D2D( hr );
return result > 0;
}
bool Geometry::StrokeContainsPoint( Geometry^ geometry, System::Drawing::PointF point, float strokeWidth, StrokeStyle^ strokeStyle )
{
BOOL result;
ID2D1StrokeStyle *ss = strokeStyle == nullptr ? NULL : strokeStyle->InternalPointer;
D2D1_POINT_2F p = D2D1::Point2F( point.X, point.Y );
HRESULT hr = geometry->InternalPointer->StrokeContainsPoint( p, strokeWidth, ss, NULL, &result );
RECORD_D2D( hr );
return result > 0;
}
bool Geometry::StrokeContainsPoint( Geometry^ geometry, System::Drawing::PointF point, float strokeWidth, StrokeStyle^ strokeStyle, Matrix3x2 transform )
{
BOOL result;
ID2D1StrokeStyle *ss = strokeStyle == nullptr ? NULL : strokeStyle->InternalPointer;
D2D1_POINT_2F p = D2D1::Point2F( point.X, point.Y );
HRESULT hr = geometry->InternalPointer->StrokeContainsPoint( p, strokeWidth, ss, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), &result );
RECORD_D2D( hr );
return result > 0;
}
bool Geometry::StrokeContainsPoint( Geometry^ geometry, System::Drawing::PointF point, float strokeWidth, StrokeStyle^ strokeStyle, Matrix3x2 transform, float flatteningTolerance )
{
BOOL result;
ID2D1StrokeStyle *ss = strokeStyle == nullptr ? NULL : strokeStyle->InternalPointer;
D2D1_POINT_2F p = D2D1::Point2F( point.X, point.Y );
HRESULT hr = geometry->InternalPointer->StrokeContainsPoint( p, strokeWidth, ss, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, &result );
RECORD_D2D( hr );
return result > 0;
}
Result Geometry::Simplify( Geometry^ geometry, SimplificationType type, SimplifiedGeometrySink^ geometrySink )
{
HRESULT hr = geometry->InternalPointer->Simplify( static_cast<D2D1_GEOMETRY_SIMPLIFICATION_OPTION>( type ), NULL, geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Simplify( Geometry^ geometry, SimplificationType type, Matrix3x2 transform, SimplifiedGeometrySink^ geometrySink )
{
HRESULT hr = geometry->InternalPointer->Simplify( static_cast<D2D1_GEOMETRY_SIMPLIFICATION_OPTION>( type ),
reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Simplify( Geometry^ geometry, SimplificationType type, Matrix3x2 transform, float flatteningTolerance, SimplifiedGeometrySink^ geometrySink )
{
HRESULT hr = geometry->InternalPointer->Simplify( static_cast<D2D1_GEOMETRY_SIMPLIFICATION_OPTION>( type ),
reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Tessellate( Geometry^ geometry, TessellationSink^ tessellationSink )
{
HRESULT hr = geometry->InternalPointer->Tessellate( NULL, tessellationSink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Tessellate( Geometry^ geometry, Matrix3x2 transform, TessellationSink^ tessellationSink )
{
HRESULT hr = geometry->InternalPointer->Tessellate( reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), tessellationSink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Tessellate( Geometry^ geometry, Matrix3x2 transform, float flatteningTolerance, TessellationSink^ tessellationSink )
{
HRESULT hr = geometry->InternalPointer->Tessellate( reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, tessellationSink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Widen( Geometry^ geometry, float strokeWidth, SimplifiedGeometrySink^ geometrySink )
{
HRESULT hr = geometry->InternalPointer->Widen( strokeWidth, NULL, NULL, geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Widen( Geometry^ geometry, float strokeWidth, StrokeStyle^ strokeStyle, SimplifiedGeometrySink^ geometrySink )
{
ID2D1StrokeStyle *ss = strokeStyle == nullptr ? NULL : strokeStyle->InternalPointer;
HRESULT hr = geometry->InternalPointer->Widen( strokeWidth, ss, NULL, geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Widen( Geometry^ geometry, float strokeWidth, StrokeStyle^ strokeStyle, Matrix3x2 transform, SimplifiedGeometrySink^ geometrySink )
{
ID2D1StrokeStyle *ss = strokeStyle == nullptr ? NULL : strokeStyle->InternalPointer;
HRESULT hr = geometry->InternalPointer->Widen( strokeWidth, ss, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
Result Geometry::Widen( Geometry^ geometry, float strokeWidth, StrokeStyle^ strokeStyle, Matrix3x2 transform, float flatteningTolerance, SimplifiedGeometrySink^ geometrySink )
{
ID2D1StrokeStyle *ss = strokeStyle == nullptr ? NULL : strokeStyle->InternalPointer;
HRESULT hr = geometry->InternalPointer->Widen( strokeWidth, ss, reinterpret_cast<D2D1_MATRIX_3X2_F*>( &transform ), flatteningTolerance, geometrySink->InternalPointer );
return RECORD_D2D( hr );
}
}
} | [
"Michael@localhost"
] | Michael@localhost |
ac63c4f7902523458b622edfd1345a8d11a38681 | 51b16e2d745c2fdcc35e5e2f14ffe9136407689b | /C++/Dynamic Programming/LongestSubstrPalindrome.cpp | 00168feb054a11242d77c1475237ee743fc90c73 | [] | no_license | anishashruti/Computer-programming | b54ab79c281b2068b340fc3f54bc8af37fdf7599 | 244b44916ff8087b1ce54f96e2c2d97fddd40816 | refs/heads/main | 2023-07-04T11:03:00.199696 | 2021-08-08T15:27:01 | 2021-08-08T15:27:01 | 379,686,669 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,186 | cpp | #include <bits/stdc++.h>
using namespace std;
void fastIO(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
void printSubStr(string s, int low, int high)
{
for (int i = low; i <= high; ++i)
cout << s[i];
}
int longestsubstr(string s){
int n = s.size();
int adj[n][n];
int start = 0;
memset(adj, 0, sizeof(adj));
int maxLength = 1;
for (int i = 0; i < n;i++){
adj[i][i] = 1;
if(s[i]==s[i+1]){
adj[i][i + 1] = 1;
int maxLength = 1;
}
}
//For substring having length greater than 3
for (int k = 0; k <= n;k++){
for (int i = 0; i < n - k + 1;i++){
int j = i + k - 1;
if (adj[i + 1][j - 1] && s[i] == s[j]) {
adj[i][j] = true;
if (k > maxLength) {
start = i;
maxLength = k;
}
}
}
}
printSubStr(s, start, start + maxLength - 1);
return maxLength;
}
int main()
{
fastIO();
string s;
int l;
cout << "Enter a string: ";
getline(cin, s);
l = longestsubstr(s);
cout << " ";
cout << l;
return 0;
} | [
"anishashruti.at@gmail.com"
] | anishashruti.at@gmail.com |
795d5360752822a125dc90016815bd3fb3fd259c | 4cec58c6e54319d71dcbb24e7862d31733073b5c | /plugs/ImgReader/ImgReader.cpp | 0b4abfdcfd8d601362ebefd797142ead763e7317 | [] | no_license | libretro-mirrors/nulldce | dc56b5c6911d6bc22772d02384c1fa801aca1989 | 39c05500629116f0eb6bcb89a94027e1b987170c | refs/heads/master | 2021-05-13T12:14:44.472836 | 2017-11-20T14:23:30 | 2017-11-20T14:28:48 | 116,666,088 | 1 | 0 | null | 2018-01-08T11:04:09 | 2018-01-08T11:04:09 | null | UTF-8 | C++ | false | false | 3,484 | cpp | // nullGDR.cpp : Defines the entry point for the DLL application.
//
#include "ImgReader.h"
#include <stdio.h>
#include <string.h>
#include "common.h"
void FASTCALL libGDR_ReadSubChannel(u8 * buff, u32 format, u32 len)
{
//printf("libGDR_ReadSubChannel\n");
}/*
FILE* fiso;
u32 fiso_fad;
u32 fiso_ssz;
u32 fiso_offs;
bool ConvertSector(u8* in_buff , u8* out_buff , int from , int to)
{
//if no convertion
if (to==from)
{
memcpy(out_buff,in_buff,to);
return true;
}
switch (to)
{
case 2048:
{
//verify(from>=2048);
//verify((from==2448) || (from==2352) || (from==2336));
if ((from == 2352) || (from == 2448))
{
if (in_buff[15]==1)
{
memcpy(out_buff,&in_buff[0x10],2048); //0x10 -> mode1
}
else
memcpy(out_buff,&in_buff[0x18],2048); //0x18 -> mode2 (all forms ?)
}
else
memcpy(out_buff,&in_buff[0x8],2048); //hmm only possible on mode2.Skip the mode2 header
}
break;
case 2352:
//if (from >= 2352)
{
memcpy(out_buff,&in_buff[0],2352);
}
break;
default :
printf("Sector convertion from %d to %d not supported \n", from , to);
break;
}
return true;
}
void FASTCALL libGDR_ReadSector(u8 * buff,u32 StartSector,u32 SectorCount,u32 secsz)
{
printf("libGDR_ReadSector\n");
if (!fiso)
{
FILE* p=fopen("gdrom/disc.txt","rb");
fscanf(p,"%d %d %d",&fiso_fad,&fiso_ssz,&fiso_offs);
fclose(p);
fiso=fopen("gdrom/disc.gdrom","rb");
}
while(SectorCount)
{
u8 temp[5200];
fseek(fiso,fiso_offs+(StartSector-fiso_fad)*fiso_ssz,SEEK_SET);
fread(temp,1,fiso_ssz,fiso);
ConvertSector(temp,buff,fiso_ssz,secsz);
buff+=secsz;
StartSector++;
SectorCount--;
}
}
void FASTCALL libGDR_GetToc(u32* toc,u32 area)
{
printf("libGDR_GetToc\n");
FILE* f=fopen("gdrom/toc.bin","rb");
fread(toc,1,102,f);
fclose(f);
}
//TODO : fix up
u32 FASTCALL libGDR_GetDiscType()
{
return CdRom_XA;
}
void FASTCALL libGDR_GetSessionInfo(u8* out,u8 ses)
{
printf("libGDR_GetSessionInfo\n");
FILE* f=fopen(ses==0?"gdrom/ses0.bin":"gdrom/ses2.bin","rb");
fread(out,1,6,f);
fclose(f);
}
*/
void FASTCALL libGDR_ReadSector(u8 * buff,u32 StartSector,u32 SectorCount,u32 secsz)
{
if (CurrDrive)
CurrDrive->ReadSector(buff,StartSector,SectorCount,secsz);
}
void FASTCALL libGDR_GetToc(u32* toc,u32 area)
{
if (CurrDrive)
GetDriveToc(toc,(DiskArea)area);
}
//TODO : fix up
u32 FASTCALL libGDR_GetDiscType()
{
if (CurrDrive)
return CurrDrive->GetDiscType();
else
return NoDisk;
}
void FASTCALL libGDR_GetSessionInfo(u8* out,u8 ses)
{
GetDriveSessionInfo(out,ses);
}
//called when plugin is used by emu (you should do first time init here)
s32 FASTCALL libGDR_Load()
{
return rv_ok;
}
//called when plugin is unloaded by emu , olny if dcInitGDR is called (eg , not called to enumerate plugins)
void FASTCALL libGDR_Unload()
{
}
//It's suposed to reset everything (if not a manual reset)
void FASTCALL libGDR_Reset(bool Manual)
{
}
//called when entering sh4 thread , from the new thread context (for any thread speciacific init)
s32 FASTCALL libGDR_Init(gdr_init_params* prm)
{
if (!InitDrive())
return rv_serror;
NotifyEvent_gdrom(DiskChange,0);
return rv_ok;
}
//called when exiting from sh4 thread , from the new thread context (for any thread speciacific de init) :P
void FASTCALL libGDR_Term()
{
TermDrive();
}
| [
"skmp@nillware.com"
] | skmp@nillware.com |
e32d5042f232dbd7d0ca53629be823f8a2f3e0a1 | 57e55822ab1d54a3d7cf0eecb13f130f9bec8983 | /cppsrc/encoder/fdkaac.cpp | dc44d6deb0d5a212a25992427444981a7c9130de | [] | no_license | taktod/ttLibGo | a358534fb6796265178a9b318de6121f6f496257 | ca2590d41630c0ba97790f22f5a484ec1e156c01 | refs/heads/master | 2021-01-01T05:53:07.366436 | 2019-10-03T03:25:18 | 2019-10-03T03:25:18 | 97,297,745 | 20 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,068 | cpp | #include "fdkaac.hpp"
#include "../util.hpp"
#include <iostream>
#include "ttLibC/ttLibC/container/container.h"
using namespace std;
extern "C" {
typedef void *(* ttLibC_FdkaacEncoder_make_func)(const char *,uint32_t,uint32_t,uint32_t);
typedef bool (* ttLibC_FdkaacEncoder_setBitrate_func)(void *,uint32_t);
typedef void (* ttLibC_close_func)(void **);
typedef void *(* ttLibC_codec_func)(void *, void *, ttLibC_getFrameFunc, void *);
extern ttLibC_FdkaacEncoder_make_func ttLibGo_FdkaacEncoder_make;
extern ttLibC_codec_func ttLibGo_FdkaacEncoder_encode;
extern ttLibC_close_func ttLibGo_FdkaacEncoder_close;
extern ttLibC_FdkaacEncoder_setBitrate_func ttLibGo_FdkaacEncoder_setBitrate;
extern bool ttLibGoFrameCallback(void *ptr, ttLibC_Frame *frame);
}
FdkaacEncoder::FdkaacEncoder(maps *mp) {
if(ttLibGo_FdkaacEncoder_make != nullptr) {
string type = mp->getString("aacType");
uint32_t sampleRate = mp->getUint32("sampleRate");
uint32_t channelNum = mp->getUint32("channelNum");
uint32_t bitrate = mp->getUint32("bitrate");
_encoder = (*ttLibGo_FdkaacEncoder_make)(type.c_str(), sampleRate, channelNum, bitrate);
}
}
FdkaacEncoder::~FdkaacEncoder() {
if(ttLibGo_FdkaacEncoder_close != nullptr) {
(*ttLibGo_FdkaacEncoder_close)(&_encoder);
}
}
bool FdkaacEncoder::encodeFrame(ttLibC_Frame *cFrame, ttLibGoFrame *goFrame, void *ptr) {
bool result = false;
if(ttLibGo_FdkaacEncoder_encode != nullptr) {
if(cFrame->type != frameType_pcmS16) {
return result;
}
update(cFrame, goFrame);
result = (*ttLibGo_FdkaacEncoder_encode)(_encoder, cFrame, ttLibGoFrameCallback, ptr);
reset(cFrame, goFrame);
}
return result;
}
bool FdkaacEncoder::setBitrate(uint32_t value) {
if(ttLibGo_FdkaacEncoder_setBitrate != nullptr) {
return (* ttLibGo_FdkaacEncoder_setBitrate)(_encoder, value);
}
return false;
}
extern "C" {
bool FdkaacEncoder_setBitrate(void *encoder, uint32_t value) {
FdkaacEncoder *fdk = reinterpret_cast<FdkaacEncoder *>(encoder);
return fdk->setBitrate(value);
}
}
| [
"poepoemix@hotmail.com"
] | poepoemix@hotmail.com |
4ecd50354915f0a31bdeea48f0b410ada4f362ad | ae0b041a5fb2170a3d1095868a7535cc82d6661f | /MFCHash/stdafx.cpp | 8953c3b2f3560b9237e39e1bb2d6ee832c5c49dc | [] | no_license | hexonxons/6thSemester | 59c479a1bb3cd715744543f4c2e0f8fdbf336f4a | c3c8fdea6eef49de629a7f454b91ceabd58d15d8 | refs/heads/master | 2016-09-15T17:45:13.433434 | 2011-06-08T20:57:25 | 2011-06-08T20:57:25 | 1,467,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 207 | cpp | // stdafx.cpp : source file that includes just the standard includes
// MFCHash.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"killgamesh666@gmail.com"
] | killgamesh666@gmail.com |
23637dd080dffbd66b80bb3e0b5490e51a0014cd | a9e308c81c27a80c53c899ce806d6d7b4a9bbbf3 | /engine/xray/editor/world/sources/command_set_object_transform.cpp | 61bf7e1efac8ed7a36ff508f59411ccd3acf08b4 | [] | no_license | NikitaNikson/xray-2_0 | 00d8e78112d7b3d5ec1cb790c90f614dc732f633 | 82b049d2d177aac15e1317cbe281e8c167b8f8d1 | refs/heads/master | 2023-06-25T16:51:26.243019 | 2020-09-29T15:49:23 | 2020-09-29T15:49:23 | 390,966,305 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,795 | cpp | ////////////////////////////////////////////////////////////////////////////
// Created : 30.03.2009
// Author : Armen Abroyan
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "command_set_object_transform.h"
#include "object_base.h"
#include "project.h"
namespace xray {
namespace editor {
command_set_object_transform::command_set_object_transform(level_editor^ le, u32 id, math::float4x4 transform)
:m_level_editor (le)
{
id_matrix idm;
idm.id = id;
idm.matrix = NEW(float4x4)(transform);
m_id_matrices.Add(idm);
}
command_set_object_transform::~command_set_object_transform( )
{
for each(id_matrix^ itm in m_id_matrices)
DELETE ( itm->matrix );
m_id_matrices.Clear( );
}
bool command_set_object_transform::commit ()
{
math::float4x4 tmp_mat;
for each (id_matrix^ idm in m_id_matrices)
{
object_base^ curr_obj = object_base::object_by_id(idm->id);
tmp_mat = curr_obj->get_transform();
curr_obj->set_transform( *idm->matrix );
*idm->matrix = tmp_mat;
}
return true;
}
void command_set_object_transform::rollback ()
{
commit();
}
command_set_object_name::command_set_object_name( level_editor^ le, u32 id, System::String^ name ):
m_level_editor (le),
m_object_id (id)
{
m_name = name;
}
bool command_set_object_name::commit ()
{
object_base^ curr_obj = object_base::object_by_id(m_object_id);
R_ASSERT (curr_obj, "object %d not found", m_object_id);
m_rollback_name = curr_obj->get_name();
curr_obj->set_name (m_name, true);
return true;
}
void command_set_object_name::rollback ()
{
object_base^ curr_obj = object_base::object_by_id(m_object_id);
curr_obj->set_name (m_rollback_name, true);
}
} // namespace editor
} // namespace xray
| [
"loxotron@bk.ru"
] | loxotron@bk.ru |
b69bd972ac3bcd3078d45a12cdc330df10383dbe | c67cbd22f9bc3c465fd763fdf87172f2c8ec77d4 | /Desktop/Please Work/build/Android/Preview/app/src/main/include/Fuse.Input.FocusPredi-2161b71d.h | 3a788c720472060ffdd458f850206cc04df2bfda | [] | no_license | AzazelMoreno/Soteria-project | 7c58896d6bf5a9ad919bde6ddc2a30f4a07fa0d4 | 04fdb71065941176867fb9007ecf38bbf851ad47 | refs/heads/master | 2020-03-11T16:33:22.153713 | 2018-04-19T19:47:55 | 2018-04-19T19:47:55 | 130,120,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 755 | h | // This file was generated based on C:/Users/rudy0/AppData/Local/Fusetools/Packages/Fuse.Nodes/1.8.1/Input/Focus.Prediction.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.h>
namespace g{namespace Fuse{namespace Input{struct FocusPredictStrategy;}}}
namespace g{namespace Fuse{struct Visual;}}
namespace g{
namespace Fuse{
namespace Input{
// internal static class FocusPredictStrategy :7
// {
uClassType* FocusPredictStrategy_typeof();
void FocusPredictStrategy__Predict_fn(::g::Fuse::Visual* n, int32_t* direction, ::g::Fuse::Visual** __retval);
struct FocusPredictStrategy : uObject
{
static ::g::Fuse::Visual* Predict(::g::Fuse::Visual* n, int32_t direction);
};
// }
}}} // ::g::Fuse::Input
| [
"rudy0604594@gmail.com"
] | rudy0604594@gmail.com |
b67658139305c6c88418f21cdad2f71b7cb3f987 | 864496807499c9cb8588d60c49356697b1370470 | /Source/Game.cpp | 688c7d7484a009f54cba356d8ac8b26d07f8c8f8 | [] | no_license | Hopson97/Minesweeper | 7357c1b50fafce289fa0edcb34fff67904a0e755 | 204d9bc798aa00355d771e09a480dcbefbfcf6ca | refs/heads/master | 2022-07-06T09:56:22.955779 | 2017-02-11T17:53:28 | 2017-02-11T17:53:28 | 81,117,341 | 2 | 1 | null | 2022-06-18T17:47:06 | 2017-02-06T18:20:38 | C++ | UTF-8 | C++ | false | false | 626 | cpp | #include "Game.h"
#include "States/Playing.h"
#include "Util/Random.h"
Game::Game()
{
Random::init();
pushState(std::make_unique<State::Playing>(*this));
}
void Game::runLoop()
{
while (m_isRunning)
{
//system("cls");//I know "system" is bad, but I cba type out the "windows" way of clearing.
m_states.top()->logic();
}
}
void Game::pushState(std::unique_ptr<State::S_Base> state)
{
m_states.push(std::move(state));
}
void Game::popState()
{
m_states.pop();
}
void Game::changeState(std::unique_ptr<State::S_Base> state)
{
popState();
pushState(std::move(state));
}
| [
"mhopson@hotmail.co.uk"
] | mhopson@hotmail.co.uk |
7f4f7cf5e8fab116e6a47a50912f9b53e346090f | a6a9d5259574756bdbe903a4d66bcd82b4b40b29 | /multiplos.cpp | b5efc534a59cc9dfbf77e2705f90422b5460e284 | [
"MIT"
] | permissive | DariaMachado/Algoritmos_em_C-- | 24299e8f931de63f4c1afd65a6edda1ce421611e | a61dae7445f8274e1c43ca7030ee69c1474395d1 | refs/heads/main | 2023-03-14T14:28:28.641084 | 2021-03-06T23:03:52 | 2021-03-06T23:03:52 | 341,552,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 319 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int n1, n2;
cout << "Digite dois numeros inteiros: " << endl;
cin >> n1 >> n2;
if(n1 % n2 == 0 || n2 % n1 == 0) {
cout << "Sao multiplos" << endl;
}
else {
cout << "Nao sao multiplos" << endl;
}
return 0;
}
| [
"78050749+DariaMachado@users.noreply.github.com"
] | 78050749+DariaMachado@users.noreply.github.com |
56d5131fdb1142322b95df5a103f73122ec89df0 | 8aebaaac7e08ccad863ed013d3de7ea025356e06 | /main.cpp | 1ade0bff2ea5099bbe16b0ebe3c7a098fc5bfa73 | [] | no_license | fotsing365/IFCModule | 0ae664f660138cff71f04e606cad1d8934c47c2a | 56c1f8ec0f66543c47ee5665468ef7d095c02c2b | refs/heads/master | 2021-01-21T10:25:23.523805 | 2017-05-18T12:30:06 | 2017-05-18T12:30:06 | 91,687,687 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,704 | cpp | // IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
#include <ifc2x3/SPFReader.h>
#include <ifc2x3/SPFWriter.h>
#include <ifc2x3/ExpressDataSet.h>
#include <ifc2x3/IfcProject.h>
#include <ifc2x3/IfcLocalPlacement.h>
#include <ifc2x3/IfcAxis2Placement.h>
#include <ifc2x3/IfcAxis2Placement2D.h>
#include <ifc2x3/IfcAxis2Placement3D.h>
#include <ifc2x3/IfcUnit.h>
#include "UUIDGenerator.h"
#include "geometric.h"
#include <iostream>
#include <stdio.h>
#include <vector>
#ifdef WIN32
#include <time.h>
#endif
void initOwnerHistory(ifc2x3::IfcOwnerHistory* theOwnerHistory,
std::string userID, std::string userFN, std::string userLN,
std::string orgID, std::string orgName,
std::string appVersion, std::string appID, std::string appName)
{
theOwnerHistory->getOwningUser()->getThePerson()->setId(userID);
theOwnerHistory->getOwningUser()->getThePerson()->setGivenName(userFN);
theOwnerHistory->getOwningUser()->getThePerson()->setFamilyName(userLN);
theOwnerHistory->getOwningUser()->getTheOrganization()->setId(orgID);
theOwnerHistory->getOwningUser()->getTheOrganization()->setName(orgName);
theOwnerHistory->getOwningApplication()->setVersion(appVersion);
theOwnerHistory->getOwningApplication()->setApplicationIdentifier(appID);
theOwnerHistory->getOwningApplication()->setApplicationFullName(appName);
#ifdef WIN32
time_t ltime;
time( <ime );
theOwnerHistory->setCreationDate((ifc2x3::IfcTimeStamp)ltime);
#endif
}
void initRootProperties(ifc2x3::IfcRoot* entity, std::string name)
{
entity->setGlobalId(UUIDGenerator::generateIfcGloballyUniqueId());
entity->setName(name);
}
ifc2x3::IfcRelAggregates* linkByAggregate(
ifc2x3::IfcObjectDefinition* relating,
ifc2x3::IfcObjectDefinition* related)
{
static unsigned int count = 0;
char buffer[128];
#ifdef WIN32
sprintf_s(buffer,"%d",count);
#else
sprintf(buffer,"%d", count);
#endif
Step::RefPtr< ifc2x3::ExpressDataSet > mDataSet = (ifc2x3::ExpressDataSet*)relating->getExpressDataSet();
ifc2x3::IfcRelAggregates* agg = mDataSet->createIfcRelAggregates().get();
initRootProperties(agg,std::string("Aggregate") + buffer);
agg->setRelatingObject(relating);
agg->getRelatedObjects().insert(related);
return agg;
}
ifc2x3::IfcRelContainedInSpatialStructure* linkByContainedInSpatial(
ifc2x3::IfcSpatialStructureElement* relating,
ifc2x3::IfcProduct* related)
{
static unsigned int count = 0;
char buffer[128];
Step::RefPtr< ifc2x3::ExpressDataSet > mDataSet = (ifc2x3::ExpressDataSet*)relating->getExpressDataSet();
ifc2x3::IfcRelContainedInSpatialStructure* contained =
mDataSet->createIfcRelContainedInSpatialStructure().get();
#ifdef WIN32
sprintf_s(buffer,"%d",count);
#else
sprintf(buffer,"%d", count);
#endif
initRootProperties(contained,std::string("ContainedInSpatial") + buffer);
contained->setRelatingStructure(relating);
contained->getRelatedElements().insert(related);
return contained;
}
ifc2x3::IfcRelConnectsPathElements* linkByConnectsPathElements(
ifc2x3::IfcElement* relating, ifc2x3::IfcConnectionTypeEnum relatingConnectionType,
ifc2x3::IfcElement* related, ifc2x3::IfcConnectionTypeEnum relatedConnectionType)
{
static unsigned int count = 0;
char buffer[128];
Step::RefPtr< ifc2x3::ExpressDataSet > mDataSet = (ifc2x3::ExpressDataSet*)relating->getExpressDataSet();
ifc2x3::IfcRelConnectsPathElements* connects =
mDataSet->createIfcRelConnectsPathElements().get();
#ifdef WIN32
sprintf_s(buffer,"%d",count);
#else
sprintf(buffer,"%d", count);
#endif
initRootProperties(connects,std::string("ConnectsPathElements") + buffer);
connects->setRelatingElement(relating);
connects->setRelatingConnectionType(relatingConnectionType);
connects->setRelatedElement(related);
connects->setRelatedConnectionType(relatedConnectionType);
return connects;
}
ifc2x3::IfcRelSpaceBoundary* linkBySpaceBoundary(
ifc2x3::IfcSpace* relating,
ifc2x3::IfcElement* related)
{
static unsigned int count = 0;
char buffer[128];
Step::RefPtr< ifc2x3::ExpressDataSet > mDataSet = (ifc2x3::ExpressDataSet*)relating->getExpressDataSet();
ifc2x3::IfcRelSpaceBoundary* connects =
mDataSet->createIfcRelSpaceBoundary().get();
#ifdef WIN32
sprintf_s(buffer,"%d",count);
#else
sprintf(buffer,"%d", count);
#endif
initRootProperties(connects,std::string("SpaceBoundary") + buffer);
connects->setRelatingSpace(relating);
connects->setRelatedBuildingElement(related);
connects->setPhysicalOrVirtualBoundary(ifc2x3::IfcPhysicalOrVirtualEnum_PHYSICAL);
connects->setInternalOrExternalBoundary(ifc2x3::IfcInternalOrExternalEnum_INTERNAL);
return connects;
}
ifc2x3::IfcRelVoidsElement* linkByVoidsElement(
ifc2x3::IfcElement* relatingBuildingElement,
ifc2x3::IfcFeatureElementSubtraction* relatedOpeningElement)
{
static unsigned int count = 0;
char buffer[128];
Step::RefPtr< ifc2x3::ExpressDataSet > mDataSet =
(ifc2x3::ExpressDataSet*)relatingBuildingElement->getExpressDataSet();
ifc2x3::IfcRelVoidsElement* relVoidsElement =
mDataSet->createIfcRelVoidsElement().get();
#ifdef WIN32
sprintf_s(buffer,"%d",count);
#else
sprintf(buffer,"%d", count);
#endif
initRootProperties(relVoidsElement,std::string("VoidsElement") + buffer);
ifc2x3::IfcLocalPlacement * localPlacement = (ifc2x3::IfcLocalPlacement*)relatedOpeningElement->getObjectPlacement();
localPlacement->setPlacementRelTo(relatingBuildingElement->getObjectPlacement());
relVoidsElement->setRelatingBuildingElement(relatingBuildingElement);
relVoidsElement->setRelatedOpeningElement(relatedOpeningElement);
return relVoidsElement;
}
ifc2x3::IfcRelFillsElement* linkByFillsElement(
ifc2x3::IfcOpeningElement* relatingOpeningElement,
ifc2x3::IfcElement* relatedBuildingElement)
{
static unsigned int count = 0;
char buffer[128];
Step::RefPtr< ifc2x3::ExpressDataSet > mDataSet =
(ifc2x3::ExpressDataSet*)relatingOpeningElement->getExpressDataSet();
ifc2x3::IfcRelFillsElement* relFillsElement =
mDataSet->createIfcRelFillsElement().get();
#ifdef WIN32
sprintf_s(buffer,"%d",count);
#else
sprintf(buffer,"%d", count);
#endif
initRootProperties(relFillsElement,std::string("FillsElement") + buffer);
ifc2x3::IfcLocalPlacement * localPlacement = (ifc2x3::IfcLocalPlacement*)relatedBuildingElement->getObjectPlacement();
localPlacement->setPlacementRelTo(relatingOpeningElement->getObjectPlacement());
relFillsElement->setRelatingOpeningElement(relatingOpeningElement);
relFillsElement->setRelatedBuildingElement(relatedBuildingElement);
return relFillsElement;
}
//##################################################################### my area###############################################
// this founction create an Ifcsite and links it to a project
Step::RefPtr<ifc2x3::IfcSite> createIfcSite(std::vector<double> points, Step::RefPtr< ifc2x3::ExpressDataSet > &mDataSet,
CreateGeometricRepresentationVisitor &cwrv, Step::RefPtr<ifc2x3::IfcProject> &theProject)
{
// Build an Ifc site
Step::RefPtr<ifc2x3::IfcSite> theSite = mDataSet->createIfcSite();
initRootProperties(theSite.get(), "The site");
theSite->setCompositionType(ifc2x3::IfcElementCompositionEnum_ELEMENT);
// Create representation
points.clear();
//position.clear();
//placement.clear();
cwrv.init();
cwrv.set2DPolyline(points);
//cwrv.setColor(255, 255, 255);
if (!theSite->acceptVisitor(&cwrv)) {
std::cerr << "ERROR while creating site representation" << std::endl;
}
// Link (Project <--> Site)
linkByAggregate(theProject.get(), theSite.get());
return theSite;
}
//########################################## MY AREA END ###########################################################################
int main(int argc, char **argv)
{
std::cout << "Ifc2x3 SDK simple example: how to build an Ifc model?" << std::endl;
// ** First build an ExpressDataSet
Step::RefPtr< ifc2x3::ExpressDataSet > mDataSet = new ifc2x3::ExpressDataSet();
// ** Geometric representation stuff
std::vector<double> points, points2;
std::vector<double> position, placement;
CreateGeometricRepresentationVisitor cwrv(mDataSet.get());
// ** Then, build the header
Step::SPFHeader theHeader;
theHeader.getFileDescription().description.push_back("The very first model built from CSTB Ifc2x3 C++ SDK");
#ifdef WIN32
char buf[128];
struct tm t;
time_t ltime;
time(<ime);
localtime_s(&t,<ime);
sprintf_s(buf,"%.4i-%.2i-%.2iT%.2i:%.2i:%.2i",
t.tm_year+1900,t.tm_mon+1,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec);
theHeader.getFileName().timeStamp = buf;
#else // WIN32
theHeader.getFileName().timeStamp = "2008-07-24T18:57:00";
#endif // WIN32
theHeader.getFileSchema().schemaIdentifiers.push_back("IFC2X3");
mDataSet->setHeader(theHeader);
// Build the project
Step::RefPtr<ifc2x3::IfcProject> theProject = mDataSet->createIfcProject();
// Init root properties
initRootProperties(theProject.get(),"Simple building");
theProject->setLongName("Simple building model for testing");
// Build the project owner history
Step::RefPtr< ifc2x3::IfcOwnerHistory > theOwnerHistory = mDataSet->createIfcOwnerHistory();
// - Build the owning user
Step::RefPtr<ifc2x3::IfcPersonAndOrganization> thePersonOrg = mDataSet->createIfcPersonAndOrganization();
Step::RefPtr<ifc2x3::IfcPerson> thePerson = mDataSet->createIfcPerson();
thePersonOrg->setThePerson(thePerson);
Step::RefPtr<ifc2x3::IfcOrganization> theOrganization = mDataSet->createIfcOrganization();
thePersonOrg->setTheOrganization(theOrganization);
theOwnerHistory->setOwningUser(thePersonOrg);
// - Build the owning application
Step::RefPtr<ifc2x3::IfcApplication> theApplication = mDataSet->createIfcApplication();
theApplication->setApplicationDeveloper(theOrganization);
theOwnerHistory->setOwningApplication(theApplication);
// Init the owner history
initOwnerHistory(theOwnerHistory.get(),"GP","Guillaume","PICINBONO","CSTB_MOD-EVE",
"CSTB MOD-EVE Team","1.0.0","IFC2X3_C++_SDK","IFC 2x3 C++ SDK");
theProject->setOwnerHistory(theOwnerHistory);
// set the units
Step::RefPtr<ifc2x3::IfcUnitAssignment> theProjectUnits = mDataSet->createIfcUnitAssignment();
Step::RefPtr< ifc2x3::IfcUnit > unitSelect = new ifc2x3::IfcUnit();
Step::RefPtr< ifc2x3::IfcSIUnit > unit = mDataSet->createIfcSIUnit();
unit->setUnitType(ifc2x3::IfcUnitEnum_LENGTHUNIT);
unit->setName(ifc2x3::IfcSIUnitName_METRE);
unitSelect->setIfcNamedUnit(unit.get());
theProjectUnits->getUnits().insert(unitSelect);
theProject->setUnitsInContext(theProjectUnits);
// Build an Ifc site
Step::RefPtr<ifc2x3::IfcSite> theSite = mDataSet->createIfcSite();
initRootProperties(theSite.get(), "The site");
theSite->setCompositionType(ifc2x3::IfcElementCompositionEnum_ELEMENT);
//Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(-100.0); points.push_back(-100.0);
points.push_back(100.0); points.push_back(-100.0);
points.push_back(100.0); points.push_back(100.0);
points.push_back(-100.0); points.push_back(100.0);
//theSite=(points, mDataSet, cwrv, theProject);
cwrv.set2DPolyline(points);
if ( !theSite->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating site representation" << std::endl;
}
// Link (Project <--> Site)
linkByAggregate(theProject.get(), theSite.get());
// Build an Ifc Building
Step::RefPtr<ifc2x3::IfcBuilding> theBuilding = mDataSet->createIfcBuilding();
initRootProperties(theBuilding.get(),"The building");
theBuilding->setCompositionType(ifc2x3::IfcElementCompositionEnum_ELEMENT);
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(-10.0); points.push_back(-10.0);
points.push_back(30.0); points.push_back(-10.0);
points.push_back(30.0); points.push_back(30.0);
points.push_back(-10.0); points.push_back(30.0);
cwrv.set2DPolyline(points);
if ( !theBuilding->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating building representation" << std::endl;
}
// Link (Site <--> Building)
linkByAggregate(theSite.get(), theBuilding.get());
// Build an Ifc Building Storey
Step::RefPtr<ifc2x3::IfcBuildingStorey> theGroundFloor = mDataSet->createIfcBuildingStorey();
initRootProperties(theGroundFloor.get(),"The ground floor");
theGroundFloor->setCompositionType(ifc2x3::IfcElementCompositionEnum_ELEMENT);
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.0); points.push_back(0.0);
points.push_back(20.0); points.push_back(0.0);
points.push_back(20.0); points.push_back(20.0);
points.push_back(0.0); points.push_back(20.0);
cwrv.set2DPolyline(points);
if ( !theGroundFloor->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating building storey representation" << std::endl;
}
// Link (Building <--> Storey)
linkByAggregate(theBuilding.get(), theGroundFloor.get());
// Build an Ifc Slab
Step::RefPtr<ifc2x3::IfcSlab> theGroundFloorSlab = mDataSet->createIfcSlab();
initRootProperties(theGroundFloorSlab.get(),"Ground floor slab");
theGroundFloorSlab->setPredefinedType(ifc2x3::IfcSlabTypeEnum_FLOOR);
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.0); points.push_back(0.0);
points.push_back(20.0); points.push_back(0.0);
points.push_back(20.0); points.push_back(15.0);
points.push_back(15.0); points.push_back(15.0);
points.push_back(15.0); points.push_back(20.0);
points.push_back(0.0); points.push_back(20.0);
cwrv.set2DPolyline(points);
position.push_back(0.0);
position.push_back(0.0);
position.push_back(-0.3);
cwrv.setPosition(position);
cwrv.setExtrusionDepth(0.3);
//cwrv.setColor(255, 255, 255);
if ( !theGroundFloorSlab->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating slab representation" << std::endl;
}
// Link (Storey <--> Wall)
linkByContainedInSpatial(theGroundFloor.get(), theGroundFloorSlab.get());
//################################
//build personal wall
//Step::RefPtr<ifc2x3::IfcWall> theMyWall = mDataSet->createIfcWallStandardCase();
Step::RefPtr<ifc2x3::IfcWallStandardCase> theMyWall = mDataSet->createIfcWallStandardCase();
// Step::RefPtr<ifc2x3::IfcRoof> theMyWall = mDataSet->createIfcRoof();
initRootProperties(theMyWall.get(), "mywall");
//theMyWall->setPredefinedType(ifc2x3::IfcS);
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.0); points.push_back(0.0);
points.push_back(17.0); points.push_back(0.0);
points.push_back(17.0); points.push_back(15.0);
points.push_back(15.0); points.push_back(15.0);
points.push_back(15.0); points.push_back(20.0);
points.push_back(0.0); points.push_back(20.0);
cwrv.set2DPolyline(points);
position.push_back(0.0);
position.push_back(0.0);
position.push_back(3.5);
cwrv.setPosition(position);
cwrv.setExtrusionDepth(0.3);
cwrv.setColor(255, 255, 255);
if (!theMyWall->acceptVisitor(&cwrv)) {
std::cerr << "ERROR while creating Mywall representation" << std::endl;
}
// Link (Storey <--> Wall)
linkByContainedInSpatial(theBuilding.get(), theMyWall.get());
// Build an Ifc Wall
Step::RefPtr<ifc2x3::IfcWallStandardCase> theWall1 = mDataSet->createIfcWallStandardCase();
// Step::RefPtr<ifc2x3::IfcWall>theWall1 = mDataSet->createIfcWall();
//Step::RefPtr<ifc2x3::IfcWallType>theWall1 = mDataSet->createIfcWallType();
// Init root properties
initRootProperties(theWall1.get(),"Wall #1");
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.0); points.push_back(0.0);
points.push_back(14.4); points.push_back(0.0);
points.push_back(14.4); points.push_back(0.2);
points.push_back(0.0); points.push_back(0.2);
cwrv.set2DPolyline(points);
position.push_back(0.3);
position.push_back(0.0);
position.push_back(0.0);
cwrv.setPosition(position);
cwrv.setExtrusionDepth(3.5);
//cwrv.setColor(16,255,0);
if ( !theWall1->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Add a second layer to the wall
points2.clear();
position.clear();
placement.clear();
points2.push_back(0.0); points2.push_back(0.0);
points2.push_back(14.4); points2.push_back(0.0);
points2.push_back(14.4); points2.push_back(0.1);
points2.push_back(0.0); points2.push_back(0.1);
cwrv.set2DPolyline(points2);
position.push_back(0.3);
position.push_back(0.2);
position.push_back(0.0);
cwrv.setPosition(position);
cwrv.setExtrusionDepth(3.0);
// cwrv.setColor(255, 255, 255);
if ( !theWall1->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Link (Storey <--> Wall)
linkByContainedInSpatial(theGroundFloor.get(), theWall1.get());
// Build an Ifc Wall
Step::RefPtr<ifc2x3::IfcWallStandardCase> theWall4 = mDataSet->createIfcWallStandardCase();
// Init root properties
initRootProperties(theWall4.get(),"Wall #4");
// Create representation
position.clear();
placement.clear();
cwrv.set2DPolyline(points);
position.push_back(0.3);
position.push_back(14.8);
position.push_back(0.0);
cwrv.setPosition(position);
cwrv.setExtrusionDepth(3.5);
// cwrv.setColor(255, 255, 255);
if ( !theWall4->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Add a second layer to the wall
position.clear();
placement.clear();
cwrv.set2DPolyline(points2);
position.push_back(0.3);
position.push_back(14.7);
position.push_back(0.0);
cwrv.setPosition(position);
cwrv.setExtrusionDepth(3.0);
//cwrv.setColor(255, 255, 255);
if ( !theWall4->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Add a second layer to the wall
position.clear();
placement.clear();
position.push_back(0.3);
position.push_back(15.0);
position.push_back(0.0);
cwrv.setPosition(position);
cwrv.setExtrusionDepth(3.0);
// cwrv.setColor(255, 255, 255);
if ( !theWall4->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Link (Storey <--> Wall)
linkByContainedInSpatial(theGroundFloor.get(), theWall4.get());
// Build an Ifc Wall
Step::RefPtr<ifc2x3::IfcWallStandardCase> theWall5 = mDataSet->createIfcWallStandardCase();
// Init root properties
initRootProperties(theWall5.get(),"Wall #5");
// Create representation
position.clear();
placement.clear();
cwrv.set2DPolyline(points);
position.push_back(0.3);
position.push_back(19.8);
position.push_back(0.0);
cwrv.setPosition(position);
cwrv.setExtrusionDepth(3.5);
//cwrv.setColor(255, 255, 255);
if ( !theWall5->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Add a second layer to the wall
position.clear();
placement.clear();
cwrv.set2DPolyline(points2);
position.push_back(0.3);
position.push_back(19.7);
position.push_back(0.0);
cwrv.setPosition(position);
cwrv.setExtrusionDepth(3.0);
//cwrv.setColor(255, 255, 255);
if ( !theWall5->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Link (Storey <--> Wall)
linkByContainedInSpatial(theGroundFloor.get(), theWall5.get());
// Build another Ifc Wall
Step::RefPtr<ifc2x3::IfcWallStandardCase> theWall2 = mDataSet->createIfcWallStandardCase();
// Init root properties
initRootProperties(theWall2.get(),"Wall #2");
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.0); points.push_back(0.0);
points.push_back(0.0); points.push_back(20.0);
points.push_back(0.3); points.push_back(20.0);
points.push_back(0.3); points.push_back(0.0);
cwrv.set2DPolyline(points);
cwrv.setExtrusionDepth(3.5);
//cwrv.setColor(255, 255, 255);
if ( !theWall2->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Link (Storey <--> Wall)
linkByContainedInSpatial(theGroundFloor.get(), theWall2.get());
// Link (Wall <--> Wall)
linkByConnectsPathElements(theWall2.get(),ifc2x3::IfcConnectionTypeEnum_ATSTART,
theWall1.get(),ifc2x3::IfcConnectionTypeEnum_ATSTART);
linkByConnectsPathElements(theWall2.get(),ifc2x3::IfcConnectionTypeEnum_ATPATH,
theWall4.get(),ifc2x3::IfcConnectionTypeEnum_ATSTART);
linkByConnectsPathElements(theWall2.get(),ifc2x3::IfcConnectionTypeEnum_ATEND,
theWall5.get(),ifc2x3::IfcConnectionTypeEnum_ATSTART);
#if 1
// Build another Ifc Wall
Step::RefPtr<ifc2x3::IfcWallStandardCase> theWall3 = mDataSet->createIfcWallStandardCase();
// Init root properties
initRootProperties(theWall3.get(),"Wall #3");
// Create representation
position.clear();
placement.clear();
placement.push_back(14.7);
placement.push_back(0.0);
placement.push_back(0.0);
cwrv.setLocalPlacement(placement);
cwrv.setExtrusionDepth(3.5);
//cwrv.setColor(255, 255, 255);
if ( !theWall3->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
#else
// Build another Ifc Wall
Step::RefPtr<ifc2x3::IfcWall> theWall3 = mDataSet->createIfcWall();
// Init root properties
initRootProperties(theWall3.get(),"Wall #3");
// Create representation
points.clear();
position.clear();
placement.clear();
placement.push_back(14.7);
placement.push_back(0.0);
placement.push_back(0.0);
cwrv.setLocalPlacement(placement);
if ( !theWall3->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Make this wall composed of several Layers
// Layer one
Step::RefPtr<ifc2x3::IfcBuildingElementPart> theWall3_1 = mDataSet->createIfcBuildingElementPart();
initRootProperties(theWall3_1.get(),"Wall #3 - Layer 1");
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.0); points.push_back(0.0);
points.push_back(0.0); points.push_back(20.0);
points.push_back(0.3); points.push_back(20.0);
points.push_back(0.3); points.push_back(0.0);
cwrv.set2DPolyline(points);
placement.push_back(14.7);
placement.push_back(0.0);
placement.push_back(0.0);
cwrv.setLocalPlacement(placement);
cwrv.setExtrusionDepth(3.5);
if ( !theWall3_1->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Link (Wall <--> Wall part)
linkByAggregate(theWall3.get(), theWall3_1.get());
// Layer two
Step::RefPtr<ifc2x3::IfcBuildingElementPart> theWall3_2 = mDataSet->createIfcBuildingElementPart();
initRootProperties(theWall3_2.get(),"Wall #3 - Layer 2");
// Insulation parameters
double element_width = 1.5;
double inter_element_width = 0.02;
double wall_width = 14.4;
double assembled_element_width = inter_element_width;
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.0); points.push_back(0.3);
points.push_back(0.0); points.push_back(0.3+element_width);
points.push_back(0.1); points.push_back(0.3+element_width);
points.push_back(0.1); points.push_back(0.3);
cwrv.set2DPolyline(points);
position.push_back(0.0);
position.push_back(assembled_element_width);
position.push_back(0.0);
cwrv.setPosition(position);
placement.push_back(14.58);
placement.push_back(0.0);
placement.push_back(0.0);
cwrv.setExtrusionDepth(3.2);
cwrv.setLocalPlacement(placement);
if ( !theWall3_2->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Add several geometric parts
placement.clear();
assembled_element_width += element_width + inter_element_width;
while ( assembled_element_width < (wall_width - element_width - inter_element_width) ) {
position.clear();
position.push_back(0.0);
position.push_back(assembled_element_width);
position.push_back(0.0);
cwrv.setPosition(position);
cwrv.setExtrusionDepth(3.2);
if ( !theWall3_2->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
assembled_element_width += element_width + inter_element_width;
}
// Compute width of last element
double lasting_width = wall_width - assembled_element_width - inter_element_width;
points.clear();
position.clear();
points.push_back(0.0); points.push_back(0.3);
points.push_back(0.0); points.push_back(0.3+lasting_width);
points.push_back(0.1); points.push_back(0.3+lasting_width);
points.push_back(0.1); points.push_back(0.3);
cwrv.set2DPolyline(points);
position.push_back(0.0);
position.push_back(assembled_element_width);
position.push_back(0.0);
cwrv.setPosition(position);
cwrv.setExtrusionDepth(3.2);
if ( !theWall3_2->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Link (Wall <--> Wall part)
linkByAggregate(theWall3.get(), theWall3_2.get());
// Layer three
Step::RefPtr<ifc2x3::IfcBuildingElementPart> theWall3_3 = mDataSet->createIfcBuildingElementPart();
initRootProperties(theWall3_3.get(),"Wall #3 - Layer 3");
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.0); points.push_back(0.3);
points.push_back(0.0); points.push_back(14.7);
points.push_back(0.03); points.push_back(14.7);
points.push_back(0.03); points.push_back(0.3);
cwrv.set2DPolyline(points);
placement.push_back(14.53);
placement.push_back(0.0);
placement.push_back(0.0);
cwrv.setExtrusionDepth(3.0);
cwrv.setLocalPlacement(placement);
if ( !theWall3_3->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating wall representation" << std::endl;
}
// Link (Wall <--> Wall part)
linkByAggregate(theWall3.get(), theWall3_3.get());
#endif
// Link (Storey <--> Wall)
linkByContainedInSpatial(theGroundFloor.get(), theWall3.get());
// Define an Opening
Step::RefPtr<ifc2x3::IfcOpeningElement> opening1 = mDataSet->createIfcOpeningElement();
// Init root properties
initRootProperties(opening1.get(),"Opening #1");
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.0); points.push_back(0.0);
points.push_back(0.0); points.push_back(0.9);
points.push_back(0.3); points.push_back(0.9);
points.push_back(0.3); points.push_back(0.0);
cwrv.set2DPolyline(points);
cwrv.setExtrusionDepth(2.0);
placement.push_back(0.0);
placement.push_back(2.0);
placement.push_back(0.0);
cwrv.setLocalPlacement(placement);
if ( !opening1->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating opening representation" << std::endl;
}
// Assign it to a wall
//linkByVoidsElement(theWall3_1.get(),opening1.get());
//linkByVoidsElement(theWall3_2.get(),opening1.get());
linkByVoidsElement(theWall3.get(),opening1.get());
// Define an Opening
Step::RefPtr<ifc2x3::IfcOpeningElement> opening2 = mDataSet->createIfcOpeningElement();
// Init root properties
initRootProperties(opening2.get(),"Opening #2");
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.0); points.push_back(0.0);
points.push_back(0.0); points.push_back(2.0);
points.push_back(0.3); points.push_back(2.0);
points.push_back(0.3); points.push_back(0.0);
cwrv.set2DPolyline(points);
cwrv.setExtrusionDepth(1.5);
placement.push_back(0.0);
placement.push_back(6.0);
placement.push_back(1.0);
cwrv.setLocalPlacement(placement);
if ( !opening2->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating opening representation" << std::endl;
}
// Assign it to a wall
linkByVoidsElement(theWall3.get(),opening2.get());
// Define an Opening
Step::RefPtr<ifc2x3::IfcOpeningElement> opening3 = mDataSet->createIfcOpeningElement();
// Init root properties
initRootProperties(opening3.get(),"Opening #3");
// Create representation
placement.clear();
placement.push_back(0.0);
placement.push_back(10.0);
placement.push_back(1.0);
cwrv.setLocalPlacement(placement);
if ( !opening3->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating opening representation" << std::endl;
}
// Assign it to a wall
linkByVoidsElement(theWall3.get(),opening3.get());
// Define a window
Step::RefPtr<ifc2x3::IfcWindow> window1 = mDataSet->createIfcWindow();
// Init root properties
initRootProperties(window1.get(),"Window #1");
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.0); points.push_back(0.0);
points.push_back(0.0); points.push_back(2.0);
points.push_back(0.05); points.push_back(2.0);
points.push_back(0.05); points.push_back(0.0);
cwrv.set2DPolyline(points);
cwrv.setExtrusionDepth(1.5);
position.push_back(0.1);
position.push_back(0.0);
position.push_back(0.0);
cwrv.setPosition(position);
if ( !window1->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating window representation" << std::endl;
}
// Assign it to a wall
linkByContainedInSpatial(theGroundFloor.get(),window1.get());
linkByFillsElement(opening3.get(),window1.get());
// Build in Ifc Space
Step::RefPtr<ifc2x3::IfcSpace> theSpace1 = mDataSet->createIfcSpace();
// Init root properties
initRootProperties(theSpace1.get(),"Space #1");
theSpace1->setInteriorOrExteriorSpace(ifc2x3::IfcInternalOrExternalEnum_INTERNAL);
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.3); points.push_back(0.3);
points.push_back(0.3); points.push_back(14.7);
points.push_back(14.57); points.push_back(14.7);
points.push_back(14.57); points.push_back(0.3);
cwrv.set2DPolyline(points);
cwrv.setExtrusionDepth(2.5);
if ( !theSpace1->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating space representation" << std::endl;
}
// Link (Storey <--> Space)
linkByAggregate(theGroundFloor.get(), theSpace1.get());
// Link (Space <--> Building element)
linkBySpaceBoundary(theSpace1.get(),theWall1.get());
linkBySpaceBoundary(theSpace1.get(),theWall2.get());
linkBySpaceBoundary(theSpace1.get(),theWall3.get());
linkBySpaceBoundary(theSpace1.get(),theWall4.get());
linkBySpaceBoundary(theSpace1.get(),opening1.get());
linkBySpaceBoundary(theSpace1.get(),opening2.get());
linkBySpaceBoundary(theSpace1.get(),opening3.get());
// Build another Ifc Space
Step::RefPtr<ifc2x3::IfcSpace> theSpace2 = mDataSet->createIfcSpace();
// Init root properties
initRootProperties(theSpace2.get(),"Space #2");
theSpace1->setInteriorOrExteriorSpace(ifc2x3::IfcInternalOrExternalEnum_INTERNAL);
// Create representation
points.clear();
position.clear();
placement.clear();
cwrv.init();
points.push_back(0.3); points.push_back(15.1);
points.push_back(0.3); points.push_back(19.7);
points.push_back(14.7); points.push_back(19.7);
points.push_back(14.7); points.push_back(15.1);
cwrv.set2DPolyline(points);
cwrv.setExtrusionDepth(2.5);
if ( !theSpace2->acceptVisitor(&cwrv) ) {
std::cerr << "ERROR while creating space representation" << std::endl;
}
// Link (Storey <--> Space)
linkByAggregate(theGroundFloor.get(), theSpace2.get());
// Link (Space <--> Building element)
linkBySpaceBoundary(theSpace2.get(),theWall5.get());
linkBySpaceBoundary(theSpace2.get(),theWall2.get());
linkBySpaceBoundary(theSpace2.get(),theWall3.get());
linkBySpaceBoundary(theSpace2.get(),theWall4.get());
// ** Write to model to a file
ifc2x3::SPFWriter writer(mDataSet.get());
std::ofstream filestream;
filestream.open("builtModel.ifc");
bool status = writer.write(filestream);
filestream.close();
return status;
}
| [
"fotsing365@gmail.com"
] | fotsing365@gmail.com |
62c087bd16cef36d06abed3eafd8d78175d3a57a | bfb5d48e57876c7863d9a7d1ab03299e608ddc8b | /classes/MsgDelayResp.h | bd66e10792e85a870739f096d739c9504e7e47d2 | [] | no_license | li7/PTP_Click | 12c54bb7de77dc491de26ab2fe8759de04217fa3 | fcf441b90d0e51d130d092bc7f6f62269c7e312b | refs/heads/master | 2020-04-15T13:33:56.043581 | 2014-07-08T01:29:24 | 2014-07-08T01:29:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,454 | h | #ifndef MSGDELAYRESP_H
#define MSGDELAYRESP_H
#include "TimeRepresentation.h"
#include "constants.h"
#include <iostream>
using namespace std;
class MsgDelayResp{
public:
/*************Constructor************/
MsgDelayResp();
/****************accessors***********/
TimeRepresentation& get_delayReceiptTimestamp();
UInteger32 get_delayReceiptTimestamp_seconds() const;
Integer32 get_delayReceiptTimestamp_nanoseconds() const;
UInteger8 get_requestingSourceCommunicationTechnology() const;
Octet* get_requestingSourceUuid();
UInteger16 get_requestingSourcePortId() const;
UInteger16 get_requestingSourceSequenceId() const;
/****************mutators***********/
void set_delayReceiptTimestamp(TimeRepresentation drt);
void set_delayReceiptTimestamp_seconds(UInteger32 sec);
void set_delayReceiptTimestamp_nanoseconds(Integer32 nsec);
void set_requestingSourceCommunicationTechnology(UInteger8 rsct);
void set_requestingSourceUuid(const void *rsu, int length);
void set_requestingSourcePortId(UInteger16 rspi);
void set_requestingSourceSequenceId(UInteger16 rssi);
friend ostream& operator<<(ostream& s, const MsgDelayResp& it);
private:
TimeRepresentation delayReceiptTimestamp;
UInteger8 requestingSourceCommunicationTechnology;
Octet requestingSourceUuid[PTP_UUID_LENGTH];
UInteger16 requestingSourcePortId;
UInteger16 requestingSourceSequenceId;
};
ostream& operator<<(ostream& s, const MsgDelayResp& it);
#endif
| [
"li7@hawaii.edu"
] | li7@hawaii.edu |
3a1957dc4cb75bd1873a838b2f238fd60cc626bb | 31287dccda1fa0be67d87c61175fc7e9206134e8 | /Schedule/MagicWindow/NinePatchPainter.h | fd2f4f07f5f9364d7f94e0744c55d4ccba8c5c3c | [] | no_license | xtuer/Qt | 83c9407f92cef8f0d1b702083bb51ea29d69f18a | 01d3862353f88a64e3c4ea76d4ecdd1d98ab1806 | refs/heads/master | 2022-06-02T02:32:56.694458 | 2022-05-29T13:06:48 | 2022-05-29T13:06:48 | 55,279,709 | 15 | 13 | null | null | null | null | UTF-8 | C++ | false | false | 475 | h | #ifndef NINEPATCHPAINTER_H
#define NINEPATCHPAINTER_H
class QRect;
class QString;
class QPainter;
class NinePatchPainterPrivate;
/**
* @brief 使用九宫格的方式绘图
*/
class NinePatchPainter {
public:
NinePatchPainter(int left, int top, int right, int bottom, const QString &imagePath, bool tiled);
~NinePatchPainter();
void draw(QPainter *painter, const QRect &rect) const;
private:
NinePatchPainterPrivate *d;
};
#endif // NINEPATCHPAINTER_H
| [
"biao.mac@icloud.com"
] | biao.mac@icloud.com |
2e2d1ed20b6d20251378c4af4ece5d3df3aaa883 | 220529721e151c6cc088ebecf4d3c19fd4716df3 | /LeetCode/Minimum Length of String After Deleting Similar Ends/main.cpp | 1cad3442245ce79db3e317461c97abe8df3801ba | [
"MIT"
] | permissive | jahid-coder/competitive-programming | baa2311796e3ffad3ded4789e43f4f37b95673ef | e7878de2445019c916404238180959dc9308ed4a | refs/heads/master | 2023-08-26T10:13:57.816451 | 2021-10-18T04:26:32 | 2021-10-18T04:26:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | cpp | class Solution {
public:
int minimumLength(string s) {
int i = 0, j = s.size() - 1;
while (i < j && s[i] == s[j]) {
char ch = s[i];
while (i <= j && s[i] == ch) {
i++;
}
while (i <= j && s[j] == ch) {
j--;
}
}
return max(0, j - i + 1);
}
}; | [
"thedevelopersanjeev@gmail.com"
] | thedevelopersanjeev@gmail.com |
8fa44a3fa71db53c2221ad3356a33044849dc6fe | b5f6d2410a794a9acba9a0f010f941a1d35e46ce | /utils/RCBot2_meta/bot_ga_ind.cpp | 90004afb47f66e3f50a30065273ad3f7be791a96 | [] | no_license | chrizonix/RCBot2 | 0a58591101e4537b166a672821ea28bc3aa486c6 | ef0572f45c9542268923d500e64bb4cd037077eb | refs/heads/master | 2021-01-19T12:55:49.003814 | 2018-08-27T08:48:55 | 2018-08-27T08:48:55 | 44,916,746 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,419 | cpp | /*
* This file is part of RCBot.
*
* RCBot by Paul Murphy adapted from Botman's HPB Bot 2 template.
*
* RCBot 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.
*
* RCBot 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 RCBot; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game Engine ("HL
* Engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL Engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "bot.h"
#include "bot_mtrand.h"
#include "bot_ga.h"
#include "bot_ga_ind.h"
#include "bot_mtrand.h"
CBotGAValues :: CBotGAValues()
{
init();
}
void CBotGAValues :: init (void)
{
clear();
setFitness(0);
}
CBotGAValues :: CBotGAValues( vector<float> values )
{
clear();
setFitness(0);
setVector(values);
}
void CBotGAValues :: clear ()
{
m_theValues.clear();
}
// crossover with other individual
void CBotGAValues :: crossOver ( IIndividual *other )
{
unsigned int iPoint = randomInt(0,m_theValues.size());
float fTemp;
CBotGAValues *vother = (CBotGAValues*)other;
unsigned int i;
for ( i = 0; i < iPoint; i ++ )
{
fTemp = get(i);
set(i,vother->get(i));
vother->set(i,fTemp);
}
for ( i = iPoint; i < m_theValues.size(); i ++ )
{
fTemp = vother->get(i);
vother->set(i,get(i));
set(i,fTemp);
}
}
// mutate some values
void CBotGAValues :: mutate ()
{
for ( unsigned int i = 0; i < m_theValues.size(); i ++ )
{
if ( randomFloat(0,1) < CGA::g_fMutateRate )
{
float fCurrentVal = get(i);
set(i,fCurrentVal + ((fCurrentVal * (-1+randomFloat(0,2))) * CGA::g_fMaxPerturbation));
}
}
}
float CBotGAValues :: get ( int iIndex )
{
return m_theValues[iIndex];
}
void CBotGAValues :: set ( int iIndex, float fVal )
{
m_theValues[iIndex] = fVal;
}
void CBotGAValues :: addRnd()
{
m_theValues.push_back(randomFloat(0,1));
}
// get new copy of this
// sub classes return their class with own values
IIndividual *CBotGAValues :: copy ()
{
IIndividual *individual = new CBotGAValues (m_theValues);
individual->setFitness(getFitness());
return individual;
}
void CBotGAValues :: setVector ( vector<float> values )
{
for ( unsigned int i = 0; i < values.size(); i ++ )
m_theValues.push_back(values[i]);
}
void CBotGAValues :: freeMemory ()
{
m_theValues.clear();
}
| [
"christian.pichler.msc@gmail.com"
] | christian.pichler.msc@gmail.com |
71c97f2b1453bc4ac4999bd50b395a29c09115e3 | 02fec111191ecede92d844422125ac8482171bde | /NepsAcademy/frete_silva.cpp | 891599ab4bec0250b25084d6a9da8978c02dab2f | [] | no_license | Lucas3H/Maratona | 475825b249659e376a1f63a6b3b6a1e15c0d4287 | 97a2e2a91fb60243124fc2ffb4193e1b72924c3c | refs/heads/master | 2020-11-24T18:35:24.456960 | 2020-11-06T14:00:56 | 2020-11-06T14:00:56 | 228,292,025 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,360 | cpp | #include<bits/stdc++.h>
using namespace std;
#define fr(i, n) for(int i = 0; i < n; i++)
#define frj(j, n) for(int j = 0; j < n; j++)
#define frr(i, n) for(int i = 1; i <= n; i++)
#define frm(i, n) for(int i = n-1; i >= 0; i--)
#define pb push_back
#define erase(i) erase(v.begin() + i, v.begin() + i + 1)
typedef pair<int,int> pii;
#define mem(v, k) memset(v, k, sizeof(v));
#define mp make_pair
#define pq priority_queue
#define ll long long
#define MAXN 100010
int n, m;
int processado[1010], aresta[1010];
vector<pii> v[1010];
int Prim(int S){
pq<pii, vector<pii>, greater<pii>> fila;
fila.push(mp(0, S));
aresta[S] = 0;
while(true){
int davez = -1;
while(!fila.empty()){
if(!processado[fila.top().second]){
davez = fila.top().second;
fila.pop();
processado[davez] = 1;
break;
}
else fila.pop();
}
if(davez == -1) break;
for(int i = 0; i < v[davez].size(); i++){
int e = v[davez][i].first, vt = v[davez][i].second;
if(!processado[vt] && aresta[vt] > e){
aresta[vt] = e;
fila.push(mp(aresta[vt], vt));
}
}
}
int sum = 0;
fr(i, n) sum += aresta[i];
return sum;
}
int main(){
cin >> n >> m;
mem(processado, 0);
fr(i, n) aresta[i] = 1010;
int v1, v2, c;
fr(i, m){
cin >> v1 >> v2 >> c;
v[v1].pb(mp(c, v2));
v[v2].pb(mp(c, v1));
}
cout << Prim(0) << endl;;
}
| [
"lucashhh@usp.br"
] | lucashhh@usp.br |
d825139b26a1389dd3417170486c453347969fc6 | 3309f74c7120899929139d80530f8a5b85e6b7f3 | /JuceLibraryCode/modules/juce_gui_basics/layout/juce_TabbedComponent.cpp | d8570afc7b6b370d255712cb767e33fd76d9e209 | [] | no_license | AndyBrown91/MusicPlayer | d8910e6b5963c9abfa6e26fbe0c1e6b82be92e44 | d5867a1448439b49b5140bc3eabc327230e1b4db | refs/heads/master | 2020-04-12T21:02:20.544198 | 2013-07-25T11:18:48 | 2013-07-25T11:18:48 | 10,436,549 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,453 | cpp | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
namespace TabbedComponentHelpers
{
const Identifier deleteComponentId ("deleteByTabComp_");
static void deleteIfNecessary (Component* const comp)
{
if (comp != nullptr && (bool) comp->getProperties() [deleteComponentId])
delete comp;
}
static Rectangle<int> getTabArea (Rectangle<int>& content, BorderSize<int>& outline,
const TabbedButtonBar::Orientation orientation, const int tabDepth)
{
switch (orientation)
{
case TabbedButtonBar::TabsAtTop: outline.setTop (0); return content.removeFromTop (tabDepth);
case TabbedButtonBar::TabsAtBottom: outline.setBottom (0); return content.removeFromBottom (tabDepth);
case TabbedButtonBar::TabsAtLeft: outline.setLeft (0); return content.removeFromLeft (tabDepth);
case TabbedButtonBar::TabsAtRight: outline.setRight (0); return content.removeFromRight (tabDepth);
default: jassertfalse; break;
}
return Rectangle<int>();
}
}
//==============================================================================
class TabbedComponent::ButtonBar : public TabbedButtonBar
{
public:
ButtonBar (TabbedComponent& owner_, const TabbedButtonBar::Orientation orientation_)
: TabbedButtonBar (orientation_),
owner (owner_)
{
}
void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
{
owner.changeCallback (newCurrentTabIndex, newTabName);
}
void popupMenuClickOnTab (int tabIndex, const String& tabName)
{
owner.popupMenuClickOnTab (tabIndex, tabName);
}
Colour getTabBackgroundColour (const int tabIndex)
{
return owner.tabs->getTabBackgroundColour (tabIndex);
}
TabBarButton* createTabButton (const String& tabName, int tabIndex)
{
return owner.createTabButton (tabName, tabIndex);
}
private:
TabbedComponent& owner;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonBar)
};
//==============================================================================
TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
: tabDepth (30),
outlineThickness (1),
edgeIndent (0)
{
addAndMakeVisible (tabs = new ButtonBar (*this, orientation));
}
TabbedComponent::~TabbedComponent()
{
clearTabs();
tabs = nullptr;
}
//==============================================================================
void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
{
tabs->setOrientation (orientation);
resized();
}
TabbedButtonBar::Orientation TabbedComponent::getOrientation() const noexcept
{
return tabs->getOrientation();
}
void TabbedComponent::setTabBarDepth (const int newDepth)
{
if (tabDepth != newDepth)
{
tabDepth = newDepth;
resized();
}
}
TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
{
return new TabBarButton (tabName, *tabs);
}
//==============================================================================
void TabbedComponent::clearTabs()
{
if (panelComponent != nullptr)
{
panelComponent->setVisible (false);
removeChildComponent (panelComponent);
panelComponent = nullptr;
}
tabs->clearTabs();
for (int i = contentComponents.size(); --i >= 0;)
TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (i));
contentComponents.clear();
}
void TabbedComponent::addTab (const String& tabName,
Colour tabBackgroundColour,
Component* const contentComponent,
const bool deleteComponentWhenNotNeeded,
const int insertIndex)
{
contentComponents.insert (insertIndex, WeakReference<Component> (contentComponent));
if (deleteComponentWhenNotNeeded && contentComponent != nullptr)
contentComponent->getProperties().set (TabbedComponentHelpers::deleteComponentId, true);
tabs->addTab (tabName, tabBackgroundColour, insertIndex);
resized();
}
void TabbedComponent::setTabName (const int tabIndex, const String& newName)
{
tabs->setTabName (tabIndex, newName);
}
void TabbedComponent::removeTab (const int tabIndex)
{
if (isPositiveAndBelow (tabIndex, contentComponents.size()))
{
TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (tabIndex));
contentComponents.remove (tabIndex);
tabs->removeTab (tabIndex);
}
}
int TabbedComponent::getNumTabs() const
{
return tabs->getNumTabs();
}
StringArray TabbedComponent::getTabNames() const
{
return tabs->getTabNames();
}
Component* TabbedComponent::getTabContentComponent (const int tabIndex) const noexcept
{
return contentComponents [tabIndex];
}
Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const noexcept
{
return tabs->getTabBackgroundColour (tabIndex);
}
void TabbedComponent::setTabBackgroundColour (const int tabIndex, Colour newColour)
{
tabs->setTabBackgroundColour (tabIndex, newColour);
if (getCurrentTabIndex() == tabIndex)
repaint();
}
void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
{
tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
}
int TabbedComponent::getCurrentTabIndex() const
{
return tabs->getCurrentTabIndex();
}
String TabbedComponent::getCurrentTabName() const
{
return tabs->getCurrentTabName();
}
void TabbedComponent::setOutline (const int thickness)
{
outlineThickness = thickness;
resized();
repaint();
}
void TabbedComponent::setIndent (const int indentThickness)
{
edgeIndent = indentThickness;
resized();
repaint();
}
void TabbedComponent::paint (Graphics& g)
{
g.fillAll (findColour (backgroundColourId));
Rectangle<int> content (getLocalBounds());
BorderSize<int> outline (outlineThickness);
TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth);
g.reduceClipRegion (content);
g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
if (outlineThickness > 0)
{
RectangleList rl (content);
rl.subtract (outline.subtractedFrom (content));
g.reduceClipRegion (rl);
g.fillAll (findColour (outlineColourId));
}
}
void TabbedComponent::resized()
{
Rectangle<int> content (getLocalBounds());
BorderSize<int> outline (outlineThickness);
tabs->setBounds (TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth));
content = BorderSize<int> (edgeIndent).subtractedFrom (outline.subtractedFrom (content));
for (int i = contentComponents.size(); --i >= 0;)
if (Component* c = contentComponents.getReference(i))
c->setBounds (content);
}
void TabbedComponent::lookAndFeelChanged()
{
for (int i = contentComponents.size(); --i >= 0;)
if (Component* c = contentComponents.getReference(i))
c->lookAndFeelChanged();
}
void TabbedComponent::changeCallback (const int newCurrentTabIndex, const String& newTabName)
{
Component* const newPanelComp = getTabContentComponent (getCurrentTabIndex());
if (newPanelComp != panelComponent)
{
if (panelComponent != nullptr)
{
panelComponent->setVisible (false);
removeChildComponent (panelComponent);
}
panelComponent = newPanelComp;
if (panelComponent != nullptr)
{
// do these ops as two stages instead of addAndMakeVisible() so that the
// component has always got a parent when it gets the visibilityChanged() callback
addChildComponent (panelComponent);
panelComponent->setVisible (true);
panelComponent->toFront (true);
}
repaint();
}
resized();
currentTabChanged (newCurrentTabIndex, newTabName);
}
void TabbedComponent::currentTabChanged (const int, const String&) {}
void TabbedComponent::popupMenuClickOnTab (const int, const String&) {}
| [
"andyjtbrown@gmail.com"
] | andyjtbrown@gmail.com |
8cdf5696d41c35584e3f1a4183d082e93f3c31d8 | 43a2fbc77f5cea2487c05c7679a30e15db9a3a50 | /Cpp/External (Offsets Only)/SDK/BP_SmallShip_Capstan_functions.cpp | fad306a28d4a9cdb580875f6e5fd17909b11dd22 | [] | no_license | zH4x/SoT-Insider-SDK | 57e2e05ede34ca1fd90fc5904cf7a79f0259085c | 6bff738a1b701c34656546e333b7e59c98c63ad7 | refs/heads/main | 2023-06-09T23:10:32.929216 | 2021-07-07T01:34:27 | 2021-07-07T01:34:27 | 383,638,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,195 | cpp | // Name: SoT-Insider, Version: 1.102.2382.0
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_SmallShip_Capstan.BP_SmallShip_Capstan_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_SmallShip_Capstan_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_SmallShip_Capstan.BP_SmallShip_Capstan_C.UserConstructionScript");
ABP_SmallShip_Capstan_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void ABP_SmallShip_Capstan_C::AfterRead()
{
ABP_Base_Capstan_C::AfterRead();
READ_PTR_FULL(Arm1, UChildActorComponent);
READ_PTR_FULL(Arm2, UChildActorComponent);
}
void ABP_SmallShip_Capstan_C::BeforeDelete()
{
ABP_Base_Capstan_C::BeforeDelete();
DELE_PTR_FULL(Arm1);
DELE_PTR_FULL(Arm2);
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"Massimo.linker@gmail.com"
] | Massimo.linker@gmail.com |
137ed3ebe3264c5a94ffbade562d9fc034e0057a | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /Implementation/658.cpp | ba5f35ba85ce35a479fad572f4cf73643d52bd4f | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 503 | cpp | #include<stdio.h>
int main(){
int n,k,i;
scanf("%d %d",&n,&k);
int score[n],mark=0;
for(i=0;i<n;i++){
scanf("%d",&score[i]);
}
for(i=0;i<k;i++){
if(score[i]==0){
mark=1;
printf("%d",i);
break;}
}
if(mark==0) {
i=k;
while(score[k-1]==score[i])
{
i++;
}
printf("%d",i);
}
}
| [
"mukeshchugani10@gmail.com"
] | mukeshchugani10@gmail.com |
f0b02990e3ea20783ffe862b10d512890ef2dda2 | a65c77b44164b2c69dfe4bfa2772d18ae8e0cce2 | /atcoder/Walk_on_Multiplication_Table.cpp | 0d83c0b1b6a725309d0a473a4bbfff68dce2637d | [] | no_license | dl8sd11/online-judge | 553422b55080e49e6bd9b38834ccf1076fb95395 | 5ef8e3c5390e54381683f62f88d03629e1355d1d | refs/heads/master | 2021-12-22T15:13:34.279988 | 2021-12-13T06:45:49 | 2021-12-13T06:45:49 | 111,268,306 | 1 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 884 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define REP(i,n) for(int i=0;i<n;i++)
#define REP1(i,n) for(int i=1;i<=n;i++)
#define SZ(i) int(i.size())
#ifdef tmd
#define IOS()
#define debug(...) fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);_do(__VA_ARGS__);
template<typename T> void _do(T &&x){cerr<<x<<endl;}
template<typename T, typename ...S> void _do(T &&x, S &&...y){cerr<<x<<", ";_do(y...);}
#else
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0);
#define endl '\n'
#define debug(...)
#endif
const int MAXN = 500005;
const ll MOD = 1000000007;
ll n;
/*********************GoodLuck***********************/
int main () {
IOS();
cin >> n;
ll ans = 0x3f3f3f3f3f3f3f3f;
for (ll i=1; i*i<=n; i++) {
if (n%i == 0) {
ans = min(ans, n/i+i-2);
}
}
cout << ans << endl;
}
| [
"tmd910607@gmail.com"
] | tmd910607@gmail.com |
652c9d52a131e33a05a8120c6bd79b6f57dca806 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /chrome/browser/web_applications/components/web_app_helpers_unittest.cc | 1b4194f878f84f7b396958833d1e8a93e2cf8eb2 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 3,043 | cc | // Copyright 2018 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.
#include "chrome/browser/web_applications/components/web_app_helpers.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace web_app {
TEST(WebAppHelpers, GenerateApplicationNameFromURL) {
EXPECT_EQ("_", GenerateApplicationNameFromURL(GURL()));
EXPECT_EQ("example.com_/",
GenerateApplicationNameFromURL(GURL("http://example.com")));
EXPECT_EQ("example.com_/path",
GenerateApplicationNameFromURL(GURL("https://example.com/path")));
}
TEST(WebAppHelpers, GenerateAppIdFromURL) {
EXPECT_EQ(
"fedbieoalmbobgfjapopkghdmhgncnaa",
GenerateAppIdFromURL(GURL("https://www.chromestatus.com/features")));
// The io2016 example is also walked through at
// https://play.golang.org/p/VrIq_QKFjiV
EXPECT_EQ(
"mjgafbdfajpigcjmkgmeokfbodbcfijl",
GenerateAppIdFromURL(GURL(
"https://events.google.com/io2016/?utm_source=web_app_manifest")));
}
TEST(WebAppHelpers, IsValidWebAppUrl) {
EXPECT_TRUE(IsValidWebAppUrl(GURL("https://chromium.org")));
EXPECT_TRUE(IsValidWebAppUrl(GURL("https://www.chromium.org")));
EXPECT_TRUE(
IsValidWebAppUrl(GURL("https://www.chromium.org/path/to/page.html")));
EXPECT_TRUE(IsValidWebAppUrl(GURL("http://chromium.org")));
EXPECT_TRUE(IsValidWebAppUrl(GURL("http://www.chromium.org")));
EXPECT_TRUE(
IsValidWebAppUrl(GURL("http://www.chromium.org/path/to/page.html")));
EXPECT_TRUE(IsValidWebAppUrl(GURL("https://examle.com/foo?bar")));
EXPECT_TRUE(IsValidWebAppUrl(GURL("https://examle.com/foo#bar")));
EXPECT_FALSE(IsValidWebAppUrl(GURL()));
EXPECT_TRUE(IsValidWebAppUrl(
GURL("chrome-extension://oafaagfgbdpldilgjjfjocjglfbolmac")));
EXPECT_FALSE(IsValidWebAppUrl(GURL("ftp://www.chromium.org")));
EXPECT_FALSE(IsValidWebAppUrl(GURL("chrome://flags")));
EXPECT_FALSE(IsValidWebAppUrl(GURL("about:blank")));
EXPECT_FALSE(
IsValidWebAppUrl(GURL("file://mhjfbmdgcfjbbpaeojofohoefgiehjai")));
EXPECT_FALSE(IsValidWebAppUrl(GURL("chrome://extensions")));
EXPECT_FALSE(
IsValidWebAppUrl(GURL("filesystem:http://example.com/path/file.html")));
}
TEST(WebAppHelpers, IsValidExtensionUrl) {
EXPECT_FALSE(IsValidExtensionUrl(GURL("https://chromium.org")));
EXPECT_FALSE(IsValidExtensionUrl(GURL("http://example.org")));
EXPECT_TRUE(IsValidExtensionUrl(
GURL("chrome-extension://oafaagfgbdpldilgjjfjocjglfbolmac")));
EXPECT_FALSE(IsValidExtensionUrl(GURL("ftp://www.chromium.org")));
EXPECT_FALSE(IsValidExtensionUrl(GURL("chrome://flags")));
EXPECT_FALSE(IsValidExtensionUrl(GURL("about:blank")));
EXPECT_FALSE(
IsValidExtensionUrl(GURL("file://mhjfbmdgcfjbbpaeojofohoefgiehjai")));
EXPECT_FALSE(IsValidExtensionUrl(GURL("chrome://extensions")));
EXPECT_FALSE(IsValidExtensionUrl(
GURL("filesystem:http://example.com/path/file.html")));
}
} // namespace web_app
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
48366f1ce15a52de6793c8f2e3663ff0aafe4e19 | a23f895a3982037ea114200ef2f31e9c15e1c69e | /Marsh/Marsh/SpikeLauncher.h | 13fc52c837e775b4c2f12562972c8e0c531427d9 | [] | no_license | Casket/marsh-game-files | 588fd930c804ca91fc9b227291d520e5e2c7e297 | 176fa31bf469e2ffd827b7601eb3f4334f2164ce | refs/heads/master | 2020-12-24T15:23:15.703437 | 2013-05-15T15:46:21 | 2013-05-15T15:46:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | h | #pragma once
#include "Main.h"
using namespace std;
class SpikeLauncher: public Attack{
int spawn_delay;
int spawn_counter;
int spawn_num;
Attack* attack_spawn;
public:
SpikeLauncher(int x, int y, Sprite* img, Attack* to_launch, AttackStatistics stats, int delay, int spawn_num);
~SpikeLauncher(void);
virtual Attack* clone(int, int, Direction);
virtual void update(void);
virtual void start_death_sequence(void);
}; | [
"sturgedl@rose-hulman.edu"
] | sturgedl@rose-hulman.edu |
6ef718843cb03dce7e473ef6a4760302d812ddfe | 891bfc38e6e85b643afe683ac69942634ec2dde7 | /services/tracing/public/mojom/data_source_config_struct_traits.cc | bd1ca60cec9ecc0586765df0e7268b228fdb8d40 | [
"BSD-3-Clause"
] | permissive | siliu1/chromium | 6635bef82e896f2fee63dcd5f1182c289b35edb4 | b9310a104d7cf73c7807963089a77e287ef4b19b | refs/heads/master | 2023-03-18T14:13:43.241848 | 2019-02-13T19:56:46 | 2019-02-13T19:56:46 | 170,571,164 | 0 | 0 | NOASSERTION | 2019-02-14T04:28:44 | 2019-02-13T20:01:41 | null | UTF-8 | C++ | false | false | 1,081 | cc | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/tracing/public/mojom/data_source_config_struct_traits.h"
#include <utility>
#include "services/tracing/public/mojom/chrome_config_struct_traits.h"
namespace mojo {
bool StructTraits<tracing::mojom::DataSourceConfigDataView,
perfetto::DataSourceConfig>::
Read(tracing::mojom::DataSourceConfigDataView data,
perfetto::DataSourceConfig* out) {
std::string name, legacy_config;
perfetto::ChromeConfig config;
if (!data.ReadName(&name) || !data.ReadChromeConfig(&config) ||
!data.ReadLegacyConfig(&legacy_config)) {
return false;
}
out->set_name(name);
out->set_target_buffer(data.target_buffer());
out->set_trace_duration_ms(data.trace_duration_ms());
out->set_tracing_session_id(data.tracing_session_id());
*out->mutable_chrome_config() = std::move(config);
out->set_legacy_config(legacy_config);
return true;
}
} // namespace mojo
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
ec5f4939be6ef85a7fec35618aee70b2f7208da8 | c1863ac87c30f271f43e6ed834c949637f70dea3 | /src/test/versionbits_tests.cpp | 804d43db9884f090aeebfe67338e4181c0d3fb37 | [
"MIT"
] | permissive | quantix-team/quantix | 05bc3cdb97d83b617c1b53afdaa5fa6aa40628d0 | 6275c62e8ba36e53eefb46793a9444e2bec72da7 | refs/heads/master | 2020-03-19T16:20:15.662965 | 2018-06-22T06:44:44 | 2018-06-22T06:44:44 | 136,711,625 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,211 | cpp | // Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
#include "random.h"
#include "versionbits.h"
#include "test/test_quantix.h"
#include "chainparams.h"
#include "main.h"
#include "consensus/params.h"
#include <boost/test/unit_test.hpp>
/* Define a virtual block time, one block per 10 minutes after Nov 14 2014, 0:55:36am */
int32_t TestTime(int nHeight) { return 1415926536 + 600 * nHeight; }
static const Consensus::Params paramsDummy = Consensus::Params();
class TestConditionChecker : public AbstractThresholdConditionChecker
{
private:
mutable ThresholdConditionCache cache;
public:
int64_t BeginTime(const Consensus::Params& params) const { return TestTime(10000); }
int64_t EndTime(const Consensus::Params& params) const { return TestTime(20000); }
int Period(const Consensus::Params& params) const { return 1000; }
int Threshold(const Consensus::Params& params) const { return 900; }
bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const { return (pindex->nVersion & 0x100); }
ThresholdState GetStateFor(const CBlockIndex* pindexPrev) const { return AbstractThresholdConditionChecker::GetStateFor(pindexPrev, paramsDummy, cache); }
};
#define CHECKERS 6
class VersionBitsTester
{
// A fake blockchain
std::vector<CBlockIndex*> vpblock;
// 6 independent checkers for the same bit.
// The first one performs all checks, the second only 50%, the third only 25%, etc...
// This is to test whether lack of cached information leads to the same results.
TestConditionChecker checker[CHECKERS];
// Test counter (to identify failures)
int num;
public:
VersionBitsTester() : num(0) {}
VersionBitsTester& Reset() {
for (unsigned int i = 0; i < vpblock.size(); i++) {
delete vpblock[i];
}
for (unsigned int i = 0; i < CHECKERS; i++) {
checker[i] = TestConditionChecker();
}
vpblock.clear();
return *this;
}
~VersionBitsTester() {
Reset();
}
VersionBitsTester& Mine(unsigned int height, int32_t nTime, int32_t nVersion) {
while (vpblock.size() < height) {
CBlockIndex* pindex = new CBlockIndex();
pindex->nHeight = vpblock.size();
pindex->pprev = vpblock.size() > 0 ? vpblock.back() : NULL;
pindex->nTime = nTime;
pindex->nVersion = nVersion;
pindex->BuildSkip();
vpblock.push_back(pindex);
}
return *this;
}
VersionBitsTester& TestDefined() {
for (int i = 0; i < CHECKERS; i++) {
if ((insecure_rand() & ((1 << i) - 1)) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_DEFINED, strprintf("Test %i for DEFINED", num));
}
}
num++;
return *this;
}
VersionBitsTester& TestStarted() {
for (int i = 0; i < CHECKERS; i++) {
if ((insecure_rand() & ((1 << i) - 1)) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_STARTED, strprintf("Test %i for STARTED", num));
}
}
num++;
return *this;
}
VersionBitsTester& TestLockedIn() {
for (int i = 0; i < CHECKERS; i++) {
if ((insecure_rand() & ((1 << i) - 1)) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_LOCKED_IN, strprintf("Test %i for LOCKED_IN", num));
}
}
num++;
return *this;
}
VersionBitsTester& TestActive() {
for (int i = 0; i < CHECKERS; i++) {
if ((insecure_rand() & ((1 << i) - 1)) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_ACTIVE, strprintf("Test %i for ACTIVE", num));
}
}
num++;
return *this;
}
VersionBitsTester& TestFailed() {
for (int i = 0; i < CHECKERS; i++) {
if ((insecure_rand() & ((1 << i) - 1)) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_FAILED, strprintf("Test %i for FAILED", num));
}
}
num++;
return *this;
}
CBlockIndex * Tip() { return vpblock.size() ? vpblock.back() : NULL; }
};
BOOST_FIXTURE_TEST_SUITE(versionbits_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(versionbits_test)
{
for (int i = 0; i < 64; i++) {
// DEFINED -> FAILED
VersionBitsTester().TestDefined()
.Mine(1, TestTime(1), 0x100).TestDefined()
.Mine(11, TestTime(11), 0x100).TestDefined()
.Mine(989, TestTime(989), 0x100).TestDefined()
.Mine(999, TestTime(20000), 0x100).TestDefined()
.Mine(1000, TestTime(20000), 0x100).TestFailed()
.Mine(1999, TestTime(30001), 0x100).TestFailed()
.Mine(2000, TestTime(30002), 0x100).TestFailed()
.Mine(2001, TestTime(30003), 0x100).TestFailed()
.Mine(2999, TestTime(30004), 0x100).TestFailed()
.Mine(3000, TestTime(30005), 0x100).TestFailed()
// DEFINED -> STARTED -> FAILED
.Reset().TestDefined()
.Mine(1, TestTime(1), 0).TestDefined()
.Mine(1000, TestTime(10000) - 1, 0x100).TestDefined() // One second more and it would be defined
.Mine(2000, TestTime(10000), 0x100).TestStarted() // So that's what happens the next period
.Mine(2051, TestTime(10010), 0).TestStarted() // 51 old blocks
.Mine(2950, TestTime(10020), 0x100).TestStarted() // 899 new blocks
.Mine(3000, TestTime(20000), 0).TestFailed() // 50 old blocks (so 899 out of the past 1000)
.Mine(4000, TestTime(20010), 0x100).TestFailed()
// DEFINED -> STARTED -> FAILED while threshold reached
.Reset().TestDefined()
.Mine(1, TestTime(1), 0).TestDefined()
.Mine(1000, TestTime(10000) - 1, 0x101).TestDefined() // One second more and it would be defined
.Mine(2000, TestTime(10000), 0x101).TestStarted() // So that's what happens the next period
.Mine(2999, TestTime(30000), 0x100).TestStarted() // 999 new blocks
.Mine(3000, TestTime(30000), 0x100).TestFailed() // 1 new block (so 1000 out of the past 1000 are new)
.Mine(3999, TestTime(30001), 0).TestFailed()
.Mine(4000, TestTime(30002), 0).TestFailed()
.Mine(14333, TestTime(30003), 0).TestFailed()
.Mine(24000, TestTime(40000), 0).TestFailed()
// DEFINED -> STARTED -> LOCKEDIN at the last minute -> ACTIVE
.Reset().TestDefined()
.Mine(1, TestTime(1), 0).TestDefined()
.Mine(1000, TestTime(10000) - 1, 0x101).TestDefined() // One second more and it would be defined
.Mine(2000, TestTime(10000), 0x101).TestStarted() // So that's what happens the next period
.Mine(2050, TestTime(10010), 0x200).TestStarted() // 50 old blocks
.Mine(2950, TestTime(10020), 0x100).TestStarted() // 900 new blocks
.Mine(2999, TestTime(19999), 0x200).TestStarted() // 49 old blocks
.Mine(3000, TestTime(29999), 0x200).TestLockedIn() // 1 old block (so 900 out of the past 1000)
.Mine(3999, TestTime(30001), 0).TestLockedIn()
.Mine(4000, TestTime(30002), 0).TestActive()
.Mine(14333, TestTime(30003), 0).TestActive()
.Mine(24000, TestTime(40000), 0).TestActive();
}
// Sanity checks of version bit deployments
const Consensus::Params &mainnetParams = Params(CBaseChainParams::MAIN).GetConsensus();
for (int i=0; i<(int) Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
uint32_t bitmask = VersionBitsMask(mainnetParams, (Consensus::DeploymentPos)i);
// Make sure that no deployment tries to set an invalid bit.
BOOST_CHECK_EQUAL(bitmask & ~(uint32_t)VERSIONBITS_TOP_MASK, bitmask);
// Verify that the deployment windows of different deployment using the
// same bit are disjoint.
// This test may need modification at such time as a new deployment
// is proposed that reuses the bit of an activated soft fork, before the
// end time of that soft fork. (Alternatively, the end time of that
// activated soft fork could be later changed to be earlier to avoid
// overlap.)
for (int j=i+1; j<(int) Consensus::MAX_VERSION_BITS_DEPLOYMENTS; j++) {
if (VersionBitsMask(mainnetParams, (Consensus::DeploymentPos)j) == bitmask) {
BOOST_CHECK(mainnetParams.vDeployments[j].nStartTime > mainnetParams.vDeployments[i].nTimeout ||
mainnetParams.vDeployments[i].nStartTime > mainnetParams.vDeployments[j].nTimeout);
}
}
}
}
BOOST_AUTO_TEST_CASE(versionbits_computeblockversion)
{
// Check that ComputeBlockVersion will set the appropriate bit correctly
// on mainnet.
const Consensus::Params &mainnetParams = Params(CBaseChainParams::MAIN).GetConsensus();
// Use the TESTDUMMY deployment for testing purposes.
int64_t bit = mainnetParams.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit;
int64_t nStartTime = mainnetParams.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime;
int64_t nTimeout = mainnetParams.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout;
assert(nStartTime < nTimeout);
// In the first chain, test that the bit is set by CBV until it has failed.
// In the second chain, test the bit is set by CBV while STARTED and
// LOCKED-IN, and then no longer set while ACTIVE.
VersionBitsTester firstChain, secondChain;
// Start generating blocks before nStartTime
int64_t nTime = nStartTime - 1;
// Before MedianTimePast of the chain has crossed nStartTime, the bit
// should not be set.
CBlockIndex *lastBlock = NULL;
lastBlock = firstChain.Mine(2016, nTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
BOOST_CHECK_EQUAL(ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit), 0);
// Mine 2011 more blocks at the old time, and check that CBV isn't setting the bit yet.
for (int i=1; i<2012; i++) {
lastBlock = firstChain.Mine(2016+i, nTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
// This works because VERSIONBITS_LAST_OLD_BLOCK_VERSION happens
// to be 4, and the bit we're testing happens to be bit 28.
BOOST_CHECK_EQUAL(ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit), 0);
}
// Now mine 5 more blocks at the start time -- MTP should not have passed yet, so
// CBV should still not yet set the bit.
nTime = nStartTime;
for (int i=2012; i<=2016; i++) {
lastBlock = firstChain.Mine(2016+i, nTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
BOOST_CHECK_EQUAL(ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit), 0);
}
// Advance to the next period and transition to STARTED,
lastBlock = firstChain.Mine(6048, nTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
// so ComputeBlockVersion should now set the bit,
BOOST_CHECK((ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit)) != 0);
// and should also be using the VERSIONBITS_TOP_BITS.
BOOST_CHECK_EQUAL(ComputeBlockVersion(lastBlock, mainnetParams) & VERSIONBITS_TOP_MASK, VERSIONBITS_TOP_BITS);
// Check that ComputeBlockVersion will set the bit until nTimeout
nTime += 600;
int blocksToMine = 4032; // test blocks for up to 2 time periods
int nHeight = 6048;
// These blocks are all before nTimeout is reached.
while (nTime < nTimeout && blocksToMine > 0) {
lastBlock = firstChain.Mine(nHeight+1, nTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
BOOST_CHECK((ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit)) != 0);
BOOST_CHECK_EQUAL(ComputeBlockVersion(lastBlock, mainnetParams) & VERSIONBITS_TOP_MASK, VERSIONBITS_TOP_BITS);
blocksToMine--;
nTime += 600;
nHeight += 1;
};
nTime = nTimeout;
// FAILED is only triggered at the end of a period, so CBV should be setting
// the bit until the period transition.
for (int i=0; i<2015; i++) {
lastBlock = firstChain.Mine(nHeight+1, nTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
BOOST_CHECK((ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit)) != 0);
nHeight += 1;
}
// The next block should trigger no longer setting the bit.
lastBlock = firstChain.Mine(nHeight+1, nTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
BOOST_CHECK_EQUAL(ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit), 0);
// On a new chain:
// verify that the bit will be set after lock-in, and then stop being set
// after activation.
nTime = nStartTime;
// Mine one period worth of blocks, and check that the bit will be on for the
// next period.
lastBlock = secondChain.Mine(2016, nStartTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
BOOST_CHECK((ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit)) != 0);
// Mine another period worth of blocks, signaling the new bit.
lastBlock = secondChain.Mine(4032, nStartTime, VERSIONBITS_TOP_BITS | (1<<bit)).Tip();
// After one period of setting the bit on each block, it should have locked in.
// We keep setting the bit for one more period though, until activation.
BOOST_CHECK((ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit)) != 0);
// Now check that we keep mining the block until the end of this period, and
// then stop at the beginning of the next period.
lastBlock = secondChain.Mine(6047, nStartTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
BOOST_CHECK((ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit)) != 0);
lastBlock = secondChain.Mine(6048, nStartTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
BOOST_CHECK_EQUAL(ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit), 0);
// Finally, verify that after a soft fork has activated, CBV no longer uses
// VERSIONBITS_LAST_OLD_BLOCK_VERSION.
//BOOST_CHECK_EQUAL(ComputeBlockVersion(lastBlock, mainnetParams) & VERSIONBITS_TOP_MASK, VERSIONBITS_TOP_BITS);
}
BOOST_AUTO_TEST_SUITE_END()
| [
"quantixteam@quantix-coin.online"
] | quantixteam@quantix-coin.online |
3e0c383d202402a3e5107a43084807c6b3dfc1ea | 55d78aa8c8510cb7bbb8547d44249a9fe4e63f16 | /tests/src/parser/KeywordEntries.test.cpp | 0727d712fe100ab953a6742444db926a74500f42 | [] | no_license | goforbroke1006/adelantado | 8e72826974fe57efc17a2fda663ea34c1a0a9054 | 3eaf71ed129d69cf4e5907481edd5e11649b78dd | refs/heads/master | 2023-01-20T02:24:50.928279 | 2020-11-30T00:23:06 | 2020-11-30T00:23:06 | 311,798,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,001 | cpp | //
// Created by goforbroke on 15.11.2020.
//
#include <gtest/gtest.h>
#include "../../../src/parser/KeywordEntries.h"
TEST(atLeastOneLetter, positive_simplest) {
ASSERT_TRUE( atLeastOneLetter("h"));
ASSERT_TRUE( atLeastOneLetter("h..."));
ASSERT_TRUE( atLeastOneLetter("2020hello"));
ASSERT_TRUE( atLeastOneLetter("world"));
}
TEST(atLeastOneLetter, negative) {
ASSERT_FALSE( atLeastOneLetter(""));
ASSERT_FALSE( atLeastOneLetter("..."));
ASSERT_FALSE( atLeastOneLetter("!@#$%^&*()"));
ASSERT_FALSE( atLeastOneLetter("_+{}:\"<>?"));
}
TEST(atLeastOneLetter, positive_cyrillic) {
ASSERT_TRUE( atLeastOneLetter("п"));
ASSERT_TRUE( atLeastOneLetter("р..."));
ASSERT_TRUE( atLeastOneLetter("и2020"));
ASSERT_TRUE( atLeastOneLetter(",,в.."));
ASSERT_TRUE( atLeastOneLetter("_е"));
ASSERT_TRUE( atLeastOneLetter(" т "));
ASSERT_TRUE( atLeastOneLetter("ё"));
ASSERT_TRUE( atLeastOneLetter(" ё "));
// ASSERT_TRUE( atLeastOneLetter("Ё")); // FIXME: problem with this rune
// ASSERT_TRUE( atLeastOneLetter(" Ё ")); // FIXME: problem with this rune
}
TEST(KeywordEntries_all, positive_simplest) {
KeywordEntries entries;
entries.appendPhrase("hello world");
ASSERT_EQ(1, entries.getTop().at("hello"));
ASSERT_EQ(1, entries.getTop().at("world"));
}
TEST(KeywordEntries_all, positive_duplicates) {
KeywordEntries entries(3);
entries.appendPhrase("hello world.");
entries.appendPhrase("world cup.");
ASSERT_EQ(1, entries.getTop().at("hello"));
ASSERT_EQ(2, entries.getTop().at("world"));
ASSERT_EQ(1, entries.getTop().at("cup"));
}
TEST(KeywordEntries_all, positive_skip_non_letter) {
KeywordEntries entries(4);
entries.appendPhrase("hello, world");
entries.appendPhrase("world cup!");
ASSERT_EQ(1, entries.getTop().at("hello"));
ASSERT_EQ(2, entries.getTop().at("world"));
ASSERT_EQ(0, entries.getTop().count("cup"));
}
TEST(KeywordEntries_all, positive_skip_non_letter_2) {
KeywordEntries entries(3);
entries.appendPhrase("hello,,,,#%^&*(world");
entries.appendPhrase("/\\world<><>,.,.,.,[cup]!%^&:;");
ASSERT_EQ(1, entries.getTop().at("hello"));
ASSERT_EQ(2, entries.getTop().at("world"));
ASSERT_EQ(1, entries.getTop().at("cup"));
}
TEST(KeywordEntries_all, positive_skip_quotes) {
KeywordEntries entries(3);
entries.appendPhrase("\"hello\" world");
entries.appendPhrase("world cup!");
ASSERT_EQ(1, entries.getTop().at("hello"));
ASSERT_EQ(2, entries.getTop().at("world"));
ASSERT_EQ(1, entries.getTop().at("cup"));
}
TEST(KeywordEntries_all, negative_empty_lines) {
KeywordEntries entries;
entries.appendPhrase("");
entries.appendPhrase("");
ASSERT_TRUE(entries.getTop().empty());
}
TEST(KeywordEntries_all, negative_lines_without_text) {
KeywordEntries entries;
entries.appendPhrase("#$#$#$#$");
entries.appendPhrase("_-_-_=+");
ASSERT_TRUE(entries.getTop().empty());
}
| [
"go.for.broke1006@gmail.com"
] | go.for.broke1006@gmail.com |
78222bc340b020566d90e922a0499ef44adc2533 | 40b9c9ba225c7c93456cd2173483c28c4b485557 | /src/s2/s2cell_range_iterator.h | c1188c75fb7aee275c86bb1f602119909360f54d | [
"Apache-2.0"
] | permissive | google/s2geometry | 04d89ed376da4943cbdf2f46a235e159df34e3f9 | 7773d518b1f29caa1c2045eb66ec519e025be108 | refs/heads/master | 2023-08-25T21:12:52.183730 | 2023-04-28T15:28:39 | 2023-04-28T15:28:39 | 46,291,330 | 2,042 | 326 | Apache-2.0 | 2023-04-28T15:28:40 | 2015-11-16T17:41:03 | C++ | UTF-8 | C++ | false | false | 9,232 | h | // Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef S2_S2CELL_RANGE_ITERATOR_H_
#define S2_S2CELL_RANGE_ITERATOR_H_
#include "absl/meta/type_traits.h"
#include "s2/s2cell_id.h"
#include "s2/s2cell_iterator.h"
#include "s2/s2shape_index.h"
// S2CellRangeIterator is a wrapper around an S2CellIterator that caches the
// range_min() and range_max() that each cell covers as it iterates. This lets
// us define range based methods such as SeekTo() and Locate() efficiently.
//
// Computing the range_max() and range_min() of a cell isn't expensive but it's
// not free either, so we extend the S2CellIterator interface instead of
// integrating this functionality there, allowing the user to pay only for what
// they use.
//
// An S2CellRangeIterator wraps an S2CellIterator, but is also itself an
// S2CellIterator and thus can be used anywhere one is required.
template <typename Iterator>
class S2CellRangeIterator final : public S2CellIterator {
public:
static_assert(S2CellIterator::ImplementedBy<Iterator>{},
"S2CellRangeIterator requires an S2CellIterator");
// Construct a new S2CellRangeIterator positioned at the beginning.
explicit S2CellRangeIterator(Iterator iter) : it_(std::move(iter)) {
Begin();
}
// Returns a const reference to the underlying iterator.
const Iterator& iterator() const { return it_; }
// The current S2CellId and cell contents.
S2CellId id() const override { return it_.id(); }
// The min and max leaf cell ids covered by the current cell. If done() is
// true, these methods return a value larger than any valid cell id.
S2CellId range_min() const { return range_min_; }
S2CellId range_max() const { return range_max_; }
// Queries the relationship between two range iterators. Returns -1 if this
// iterator's current position entirely precedes the other iterator's current
// position, +1 if it entirely follows, and 0 if they overlap.
template <typename T>
int Relation(const S2CellRangeIterator<T>& b) {
if (range_max() < b.range_min()) return -1;
if (range_min() > b.range_max()) return +1;
return 0;
}
// S2CellIterator API.
void Begin() override;
void Next() override;
bool Prev() override;
void Seek(S2CellId target) override;
void Finish() override;
bool done() const override { return it_.done(); }
bool Locate(const S2Point& target) override;
S2CellRelation Locate(S2CellId target) override;
// The same as above, but uses another S2CellRangeIterator as the target.
template <typename T>
S2CellRelation Locate(const S2CellRangeIterator<T>& target);
// Position the iterator at the first cell that overlaps or follows
// "target", i.e. such that range_max() >= target.range_min().
template <typename T>
void SeekTo(const S2CellRangeIterator<T>& target);
// Position the iterator at the first cell that follows "target", i.e. the
// first cell such that range_min() > target.range_max().
template <typename T>
void SeekBeyond(const S2CellRangeIterator<T>& target);
private:
// Updates internal state after the iterator has been repositioned.
void Refresh();
Iterator it_;
S2CellId range_min_, range_max_;
};
// Builds a new S2CellRangeIterator from an index, supporting type inference.
//
// We may wish to provide overloads for other types in the future, so we
// disqualify this function from overload resolution using std::enable_if when
// the type isn't an S2ShapeIndex.
//
// The index must live for the duration of the iterator, so we take it by const
// pointer instead of reference to avoid binding to temporaries.
template <typename IndexType,
typename std::enable_if<S2ShapeIndex::ImplementedBy<IndexType>{},
bool>::type = true>
S2CellRangeIterator<typename IndexType::Iterator> MakeS2CellRangeIterator(
const IndexType* index) {
using Iterator = typename IndexType::Iterator;
return S2CellRangeIterator<Iterator>(Iterator(index, S2ShapeIndex::BEGIN));
}
// Builds a new S2CellRangeIterator from an S2CellIterator, explicitly supports
// type inference for the Iterator parameter.
template <typename Iterator,
typename std::enable_if<S2CellIterator::ImplementedBy<Iterator>{},
bool>::type = true>
auto MakeS2CellRangeIterator(Iterator&& iter) {
return S2CellRangeIterator<absl::decay_t<Iterator>>(
std::forward<Iterator>(iter));
}
////////////////// Implementation details follow ////////////////////
template <typename Iterator>
void S2CellRangeIterator<Iterator>::S2CellRangeIterator::Begin() {
it_.Begin();
Refresh();
}
template <typename Iterator>
void S2CellRangeIterator<Iterator>::S2CellRangeIterator::Next() {
it_.Next();
Refresh();
}
template <typename Iterator>
bool S2CellRangeIterator<Iterator>::S2CellRangeIterator::Prev() {
bool status = it_.Prev();
Refresh();
return status;
}
template <typename Iterator>
void S2CellRangeIterator<Iterator>::S2CellRangeIterator::Seek(S2CellId target) {
it_.Seek(target);
Refresh();
}
template <typename Iterator>
void S2CellRangeIterator<Iterator>::S2CellRangeIterator::Finish() {
it_.Finish();
Refresh();
}
template <typename Iterator>
bool S2CellRangeIterator<Iterator>::S2CellRangeIterator::Locate(
const S2Point& target) {
bool status = it_.Locate(target);
Refresh();
return status;
}
template <typename Iterator>
S2CellRelation S2CellRangeIterator<Iterator>::Locate(S2CellId target) {
// Let T be the target cell id, let I = Seek(T.range_min()) and let Prev(I) be
// the predecessor of I. If T contains any index cells, then T contains I.
// Similarly, if T is contained by an index cell, then the containing cell is
// either I or Prev(I). We test for containment by comparing the ranges of
// leaf cells spanned by T, I, and Prev(I).
Seek(target.range_min());
if (!done()) {
// The target is contained by the cell we landed on, so it's indexed.
if (id() >= target && range_min() <= target) {
return S2CellRelation::INDEXED;
}
// The cell we landed on is contained by the target, so it's subdivided.
if (id() <= target.range_max()) {
return S2CellRelation::SUBDIVIDED;
}
}
// Otherwise check the previous cell (if it exists). If it contains the
// target then it's indexed, otherwise the target cell is disjoint.
if (Prev() && range_max() >= target) {
return S2CellRelation::INDEXED;
}
return S2CellRelation::DISJOINT;
}
// Convenience re-implementation of the above function, see it for details.
template <typename Iterator>
template <typename T>
S2CellRelation S2CellRangeIterator<Iterator>::S2CellRangeIterator::Locate(
const S2CellRangeIterator<T>& target) {
Seek(target.range_min());
if (!done()) {
// The target is contained by the cell we landed on, so it's indexed.
if (id() >= target.id() && range_min() <= target.id()) {
return S2CellRelation::INDEXED;
}
// The cell we landed on is contained by the target, so it's subdivided.
if (id() <= target.range_max()) {
return S2CellRelation::SUBDIVIDED;
}
}
// Otherwise check the previous cell (if it exists). If it contains the
// target then it's indexed, otherwise the target cell is disjoint.
if (Prev() && range_max() >= target.id()) {
return S2CellRelation::INDEXED;
}
return S2CellRelation::DISJOINT;
}
template <typename Iterator>
template <typename T>
void S2CellRangeIterator<Iterator>::SeekTo(
const S2CellRangeIterator<T>& target) {
Seek(target.range_min());
// If the current cell does not overlap "target", it is possible that the
// previous cell is the one we are looking for. This can only happen when
// the previous cell contains "target" but has a smaller S2CellId.
if (done() || range_min() > target.range_max()) {
if (Prev() && range_max() < target.id()) {
Next();
}
}
Refresh();
}
template <typename Iterator>
template <typename T>
void S2CellRangeIterator<Iterator>::SeekBeyond(
const S2CellRangeIterator<T>& target) {
Seek(target.range_max().next());
if (!done() && range_min() <= target.range_max()) {
Next();
}
Refresh();
}
// This method is inline, but is only called by non-inline methods defined in
// this file. Putting the definition here enforces this requirement.
template <typename Iterator>
inline void S2CellRangeIterator<Iterator>::Refresh() {
if (done()) {
range_min_ = S2CellId::Sentinel().range_min();
range_max_ = S2CellId::Sentinel().range_max();
} else {
range_min_ = id().range_min();
range_max_ = id().range_max();
}
}
#endif // S2_S2CELL_RANGE_ITERATOR_H_
| [
"jmr@google.com"
] | jmr@google.com |
1ed0dfcb6c230016811923ad6e7c32f9c357cee5 | 2c562fdff8ac5c2d19a0589d630b960a3374db07 | /src/notification.cpp | 2e5d85567e2f5a52c7d3ea0f57719b2a6b77cb51 | [] | no_license | lhardt/Minerva | 219c39bfe2ccd185456dcc1052fd1ca6f89a6fcf | 46003638d917c5f11a29535f45f3f9fc1a2815fa | refs/heads/master | 2021-07-15T21:33:03.556572 | 2021-03-27T01:54:28 | 2021-03-27T01:54:28 | 243,601,556 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,123 | cpp | #include "gui.hpp"
#include <wx/timer.h>
#include <wx/hyperlink.h>
Notification::Notification(Application * owner, wxWindow * parent, wxWindowID id, wxString text, wxPoint position , wxSize size) : wxPanel(parent, id, position, size){
SetBackgroundColour(wxColour(0x32,0x32,0x32));
wxSizer * sz = new wxBoxSizer(wxHORIZONTAL);
m_text = new wxStaticText(this, wxID_ANY, text, wxDefaultPosition, wxDefaultSize);
m_text->SetForegroundColour(wxColour(255,255,255));
sz->Add(m_text, 1, wxALL, 8);
SetSizer(sz);
}
Notification::Notification(Application * owner, wxWindow * parent, wxWindowID id, Action * action, wxPoint position , wxSize size) : wxPanel(parent, id, position, size){
SetBackgroundColour(wxColour(0x32,0x32,0x32));
wxSizer * sz = new wxBoxSizer(wxHORIZONTAL);
m_text = new wxStaticText(this, wxID_ANY, action->Describe(), wxDefaultPosition, wxDefaultSize);
// m_button = new wxHyperlinkCtrl(this, wxID_ANY, owner->m_lang->str_undo, wxT(""), wxDefaultPosition, wxDefaultSize);
m_text->SetForegroundColour(wxColour(255,255,255));
// m_button->SetFont(*owner->m_bold_text_font);
// m_button->SetNormalColour(wxColour(0x89,0x03,0x03));
// m_button->SetHoverColour(wxColour(255,255,255));
m_associated_action = action;
/* The action is taller, therefore we don't need vertical margin here. */
sz->Add(m_text, 0, wxALL, 10);
sz->AddStretchSpacer();
// sz->Add(m_button, 0, wxALL |wxALIGN_CENTER_VERTICAL, 5);
SetSizer(sz);
// m_button->Bind(wxEVT_HYPERLINK, &Notification::OnHyperlinkAction, this);
m_timer = new wxTimer();
m_timer->Bind(wxEVT_TIMER, &Notification::OnCloseTimer, this);
}
Notification::Notification(Application * owner, wxWindow * parent, wxWindowID id, wxString text, wxString action_text, wxPoint position , wxSize size) : wxPanel(parent, id, position, size){
SetBackgroundColour(wxColour(0x32,0x32,0x32));
wxSizer * sz = new wxBoxSizer(wxHORIZONTAL);
m_text = new wxStaticText(this, wxID_ANY, text, wxDefaultPosition, wxDefaultSize);
m_button = new wxHyperlinkCtrl(this, wxID_ANY, action_text, wxT(""), wxDefaultPosition, wxDefaultSize);
m_text->SetForegroundColour(wxColour(255,255,255));
m_button->SetFont(*owner->m_bold_text_font);
m_button->SetNormalColour(wxColour(0x89,0x03,0x03));
m_button->SetHoverColour(wxColour(255,255,255));
/* The action is taller, therefore we don't need vertical margin here. */
sz->Add(m_text, 0, wxLEFT |wxALIGN_CENTER_VERTICAL, 20);
sz->AddStretchSpacer();
sz->Add(m_button, 0, wxALL |wxALIGN_CENTER_VERTICAL, 5);
SetSizer(sz);
m_button->Bind(wxEVT_HYPERLINK, &Notification::OnHyperlinkAction, this);
m_timer = new wxTimer();
m_timer->Bind(wxEVT_TIMER, &Notification::OnCloseTimer, this);
}
void Notification::Start(int ms){
m_timer->Start(ms);
}
wxHyperlinkCtrl* Notification::GetButton(){
return m_button;
}
wxTimer* Notification::GetTimer(){
return m_timer;
}
void Notification::OnCloseTimer(wxTimerEvent &){
Close();
}
void Notification::Close(){
Destroy();
}
void Notification::OnHyperlinkAction(wxHyperlinkEvent &){
if(m_associated_action != NULL){
m_associated_action->Undo();
}
Close();
}
| [
"leom.hardt@gmail.com"
] | leom.hardt@gmail.com |
804646b1d47dcdb83ec105ff7f924aacf4ddf720 | f4ee1e9b95abc8498e3e0094d873c471037589cc | /02_Transparency/02_Transparency/MyApp.h | d69be664f23499c6d300cacb1e214242c1d28142 | [] | no_license | ZsemberiDaniel/2020OszGrafikaGyak | f6ac9ce35706d977f7d7c3dceee53a5b9fc57d52 | cd00be4049582513c04521eef8f066d7a0a7a5cf | refs/heads/master | 2023-01-23T03:51:26.042136 | 2020-12-08T12:54:22 | 2020-12-08T12:54:22 | 293,063,261 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 1,295 | h | #pragma once
// C++ includes
#include <memory>
// GLEW
#include <GL/glew.h>
// SDL
#include <SDL.h>
#include <SDL_opengl.h>
// GLM
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform2.hpp>
#include "ProgramObject.h"
#include "BufferObject.h"
#include "VertexArrayObject.h"
#include "TextureObject.h"
#include "Mesh_OGL3.h"
#include "gCamera.h"
class CMyApp
{
public:
CMyApp(void);
~CMyApp(void);
bool Init();
void Clean();
void Update();
void Render();
void KeyboardDown(SDL_KeyboardEvent&);
void KeyboardUp(SDL_KeyboardEvent&);
void MouseMove(SDL_MouseMotionEvent&);
void MouseDown(SDL_MouseButtonEvent&);
void MouseUp(SDL_MouseButtonEvent&);
void MouseWheel(SDL_MouseWheelEvent&);
void Resize(int, int);
protected:
std::vector<glm::vec3> wallPositions;
// shaderekhez szükséges változók
ProgramObject m_program; // shaderek programja
Texture2D m_textureMetal;
VertexArrayObject m_vao; // VAO objektum
IndexBuffer m_gpuBufferIndices; // indexek
ArrayBuffer m_gpuBufferPos; // pozíciók tömbje
ArrayBuffer m_gpuBufferNormal; // normálisok tömbje
ArrayBuffer m_gpuBufferTex; // textúrakoordináták tömbje
std::unique_ptr<Mesh> m_mesh;
gCamera m_camera;
glm::vec4 m_wallColor{ 1 };
};
| [
"zsemberi.daniel@gmail.com"
] | zsemberi.daniel@gmail.com |
4b02b7b8dca9a77b1ce922fda9bc491827ca683e | 76f0efb245ff0013e0428ee7636e72dc288832ab | /out/Default/gen/blink/bindings/core/v8/V8GeneratedCoreBindings72.cpp | dd22252b62d814e4f9128b3a4306966e04517d39 | [] | no_license | dckristiono/chromium | e8845d2a8754f39e0ca1d3d3d44d01231957367c | 8ad7c1bd5778bfda3347cf6b30ef60d3e4d7c0b9 | refs/heads/master | 2020-04-22T02:34:41.775069 | 2016-08-24T14:05:09 | 2016-08-24T14:05:09 | 66,465,243 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,744 | cpp | /*
* THIS FILE WAS AUTOMATICALLY GENERATED, DO NOT EDIT.
*
* This file was generated by the action_derivedsourcesallinone.py script.
*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define NO_IMPLICIT_ATOMICSTRING
#include "bindings/core/v8/V8ApplicationCacheErrorEvent.cpp"
#include "bindings/core/v8/V8CompositionEventInit.cpp"
#include "bindings/core/v8/V8ResizeObserver.cpp"
#include "bindings/core/v8/V8SVGFEMergeNodeElement.cpp"
| [
"dckristiono@gmail.com"
] | dckristiono@gmail.com |
5fc304fcc6520bea3f642e78a9e829090a82fc68 | 1463abcfbe949dcf409613518ea8fc0815499b7b | /sprout/math/hypot.hpp | 4334d580830b75253693ddc2f307a15f478eb295 | [
"BSL-1.0"
] | permissive | osyo-manga/Sprout | d445c0d2e59a2e32f91c03fceb35958dcfb2c0ce | 8885b115f739ef255530f772067475d3bc0dcef7 | refs/heads/master | 2021-01-18T11:58:21.604326 | 2013-04-09T10:27:06 | 2013-04-09T10:27:06 | 4,191,046 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,840 | hpp | #ifndef SPROUT_MATH_HYPOT_HPP
#define SPROUT_MATH_HYPOT_HPP
#include <limits>
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/type_traits/float_promote.hpp>
#include <sprout/type_traits/enabler_if.hpp>
#include <sprout/math/detail/config.hpp>
#include <sprout/math/fabs.hpp>
#include <sprout/math/sqrt.hpp>
namespace sprout {
namespace math {
namespace detail {
template<
typename FloatType,
typename sprout::enabler_if<std::is_floating_point<FloatType>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR FloatType
hypot(FloatType x, FloatType y) {
return y == 0 ? sprout::math::fabs(x)
: x == 0 ? sprout::math::fabs(y)
: y == std::numeric_limits<FloatType>::infinity() || y == -std::numeric_limits<FloatType>::infinity()
? std::numeric_limits<FloatType>::infinity()
: x == std::numeric_limits<FloatType>::infinity() || x == -std::numeric_limits<FloatType>::infinity()
? std::numeric_limits<FloatType>::infinity()
: sprout::math::sqrt(x * x + y * y)
;
}
template<
typename ArithmeticType1,
typename ArithmeticType2,
typename sprout::enabler_if<
std::is_arithmetic<ArithmeticType1>::value && std::is_arithmetic<ArithmeticType2>::value
>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR typename sprout::float_promote<ArithmeticType1, ArithmeticType2>::type
hypot(ArithmeticType1 x, ArithmeticType2 y) {
typedef typename sprout::float_promote<ArithmeticType1, ArithmeticType2>::type type;
return sprout::math::detail::hypot(static_cast<type>(x), static_cast<type>(y));
}
} // namespace detail
using NS_SPROUT_MATH_DETAIL::hypot;
} // namespace math
using sprout::math::hypot;
} // namespace sprout
#endif // #ifndef SPROUT_MATH_HYPOT_HPP
| [
"bolero.murakami@gmail.com"
] | bolero.murakami@gmail.com |
3ad7d714c3e79f0ca23a810e9c610d349908af33 | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_1/MP+dmb.sy+[fr-rf]-ctrl-addr.c.cbmc_out.cpp | 2f8aded2f0e3be04ca487f8ca75fc9cbd5696f8b | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 49,195 | cpp | // 0:vars:3
// 3:atom_1_X0_1:1
// 4:atom_1_X2_2:1
// 5:atom_1_X6_0:1
// 6:thr0:1
// 7:thr1:1
// 8:thr2:1
#define ADDRSIZE 9
#define NPROC 4
#define NCONTEXT 1
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NPROC*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NPROC*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NPROC*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NPROC*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NPROC*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NPROC*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NPROC*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NPROC*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NPROC*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NPROC];
int cdy[NPROC];
int cds[NPROC];
int cdl[NPROC];
int cisb[NPROC];
int caddr[NPROC];
int cctrl[NPROC];
int cstart[NPROC];
int creturn[NPROC];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
int r0= 0;
char creg_r0;
int r1= 0;
char creg_r1;
int r2= 0;
char creg_r2;
int r3= 0;
char creg_r3;
int r4= 0;
char creg_r4;
int r5= 0;
char creg_r5;
int r6= 0;
char creg_r6;
int r7= 0;
char creg_r7;
int r8= 0;
char creg_r8;
int r9= 0;
char creg_r9;
int r10= 0;
char creg_r10;
int r11= 0;
char creg_r11;
int r12= 0;
char creg_r12;
int r13= 0;
char creg_r13;
int r14= 0;
char creg_r14;
int r15= 0;
char creg_r15;
int r16= 0;
char creg_r16;
int r17= 0;
char creg_r17;
int r18= 0;
char creg_r18;
int r19= 0;
char creg_r19;
int r20= 0;
char creg_r20;
char old_cctrl= 0;
char old_cr= 0;
char old_cdy= 0;
char old_cw= 0;
char new_creg= 0;
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
buff(0,5) = 0;
pw(0,5) = 0;
cr(0,5) = 0;
iw(0,5) = 0;
cw(0,5) = 0;
cx(0,5) = 0;
is(0,5) = 0;
cs(0,5) = 0;
crmax(0,5) = 0;
buff(0,6) = 0;
pw(0,6) = 0;
cr(0,6) = 0;
iw(0,6) = 0;
cw(0,6) = 0;
cx(0,6) = 0;
is(0,6) = 0;
cs(0,6) = 0;
crmax(0,6) = 0;
buff(0,7) = 0;
pw(0,7) = 0;
cr(0,7) = 0;
iw(0,7) = 0;
cw(0,7) = 0;
cx(0,7) = 0;
is(0,7) = 0;
cs(0,7) = 0;
crmax(0,7) = 0;
buff(0,8) = 0;
pw(0,8) = 0;
cr(0,8) = 0;
iw(0,8) = 0;
cw(0,8) = 0;
cx(0,8) = 0;
is(0,8) = 0;
cs(0,8) = 0;
crmax(0,8) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
buff(1,5) = 0;
pw(1,5) = 0;
cr(1,5) = 0;
iw(1,5) = 0;
cw(1,5) = 0;
cx(1,5) = 0;
is(1,5) = 0;
cs(1,5) = 0;
crmax(1,5) = 0;
buff(1,6) = 0;
pw(1,6) = 0;
cr(1,6) = 0;
iw(1,6) = 0;
cw(1,6) = 0;
cx(1,6) = 0;
is(1,6) = 0;
cs(1,6) = 0;
crmax(1,6) = 0;
buff(1,7) = 0;
pw(1,7) = 0;
cr(1,7) = 0;
iw(1,7) = 0;
cw(1,7) = 0;
cx(1,7) = 0;
is(1,7) = 0;
cs(1,7) = 0;
crmax(1,7) = 0;
buff(1,8) = 0;
pw(1,8) = 0;
cr(1,8) = 0;
iw(1,8) = 0;
cw(1,8) = 0;
cx(1,8) = 0;
is(1,8) = 0;
cs(1,8) = 0;
crmax(1,8) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
buff(2,5) = 0;
pw(2,5) = 0;
cr(2,5) = 0;
iw(2,5) = 0;
cw(2,5) = 0;
cx(2,5) = 0;
is(2,5) = 0;
cs(2,5) = 0;
crmax(2,5) = 0;
buff(2,6) = 0;
pw(2,6) = 0;
cr(2,6) = 0;
iw(2,6) = 0;
cw(2,6) = 0;
cx(2,6) = 0;
is(2,6) = 0;
cs(2,6) = 0;
crmax(2,6) = 0;
buff(2,7) = 0;
pw(2,7) = 0;
cr(2,7) = 0;
iw(2,7) = 0;
cw(2,7) = 0;
cx(2,7) = 0;
is(2,7) = 0;
cs(2,7) = 0;
crmax(2,7) = 0;
buff(2,8) = 0;
pw(2,8) = 0;
cr(2,8) = 0;
iw(2,8) = 0;
cw(2,8) = 0;
cx(2,8) = 0;
is(2,8) = 0;
cs(2,8) = 0;
crmax(2,8) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
buff(3,0) = 0;
pw(3,0) = 0;
cr(3,0) = 0;
iw(3,0) = 0;
cw(3,0) = 0;
cx(3,0) = 0;
is(3,0) = 0;
cs(3,0) = 0;
crmax(3,0) = 0;
buff(3,1) = 0;
pw(3,1) = 0;
cr(3,1) = 0;
iw(3,1) = 0;
cw(3,1) = 0;
cx(3,1) = 0;
is(3,1) = 0;
cs(3,1) = 0;
crmax(3,1) = 0;
buff(3,2) = 0;
pw(3,2) = 0;
cr(3,2) = 0;
iw(3,2) = 0;
cw(3,2) = 0;
cx(3,2) = 0;
is(3,2) = 0;
cs(3,2) = 0;
crmax(3,2) = 0;
buff(3,3) = 0;
pw(3,3) = 0;
cr(3,3) = 0;
iw(3,3) = 0;
cw(3,3) = 0;
cx(3,3) = 0;
is(3,3) = 0;
cs(3,3) = 0;
crmax(3,3) = 0;
buff(3,4) = 0;
pw(3,4) = 0;
cr(3,4) = 0;
iw(3,4) = 0;
cw(3,4) = 0;
cx(3,4) = 0;
is(3,4) = 0;
cs(3,4) = 0;
crmax(3,4) = 0;
buff(3,5) = 0;
pw(3,5) = 0;
cr(3,5) = 0;
iw(3,5) = 0;
cw(3,5) = 0;
cx(3,5) = 0;
is(3,5) = 0;
cs(3,5) = 0;
crmax(3,5) = 0;
buff(3,6) = 0;
pw(3,6) = 0;
cr(3,6) = 0;
iw(3,6) = 0;
cw(3,6) = 0;
cx(3,6) = 0;
is(3,6) = 0;
cs(3,6) = 0;
crmax(3,6) = 0;
buff(3,7) = 0;
pw(3,7) = 0;
cr(3,7) = 0;
iw(3,7) = 0;
cw(3,7) = 0;
cx(3,7) = 0;
is(3,7) = 0;
cs(3,7) = 0;
crmax(3,7) = 0;
buff(3,8) = 0;
pw(3,8) = 0;
cr(3,8) = 0;
iw(3,8) = 0;
cw(3,8) = 0;
cx(3,8) = 0;
is(3,8) = 0;
cs(3,8) = 0;
crmax(3,8) = 0;
cl[3] = 0;
cdy[3] = 0;
cds[3] = 0;
cdl[3] = 0;
cisb[3] = 0;
caddr[3] = 0;
cctrl[3] = 0;
cstart[3] = get_rng(0,NCONTEXT-1);
creturn[3] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(0+2,0) = 0;
mem(3+0,0) = 0;
mem(4+0,0) = 0;
mem(5+0,0) = 0;
mem(6+0,0) = 0;
mem(7+0,0) = 0;
mem(8+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
co(1,0) = 0;
delta(1,0) = -1;
co(2,0) = 0;
delta(2,0) = -1;
co(3,0) = 0;
delta(3,0) = -1;
co(4,0) = 0;
delta(4,0) = -1;
co(5,0) = 0;
delta(5,0) = -1;
co(6,0) = 0;
delta(6,0) = -1;
co(7,0) = 0;
delta(7,0) = -1;
co(8,0) = 0;
delta(8,0) = -1;
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !37, metadata !DIExpression()), !dbg !46
// br label %label_1, !dbg !47
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !45), !dbg !48
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !38, metadata !DIExpression()), !dbg !49
// call void @llvm.dbg.value(metadata i64 1, metadata !41, metadata !DIExpression()), !dbg !49
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !50
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 1;
mem(0,cw(1,0)) = 1;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// call void (...) @dmbsy(), !dbg !51
// dumbsy: Guess
old_cdy = cdy[1];
cdy[1] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[1] >= old_cdy);
ASSUME(cdy[1] >= cisb[1]);
ASSUME(cdy[1] >= cdl[1]);
ASSUME(cdy[1] >= cds[1]);
ASSUME(cdy[1] >= cctrl[1]);
ASSUME(cdy[1] >= cw(1,0+0));
ASSUME(cdy[1] >= cw(1,0+1));
ASSUME(cdy[1] >= cw(1,0+2));
ASSUME(cdy[1] >= cw(1,3+0));
ASSUME(cdy[1] >= cw(1,4+0));
ASSUME(cdy[1] >= cw(1,5+0));
ASSUME(cdy[1] >= cw(1,6+0));
ASSUME(cdy[1] >= cw(1,7+0));
ASSUME(cdy[1] >= cw(1,8+0));
ASSUME(cdy[1] >= cr(1,0+0));
ASSUME(cdy[1] >= cr(1,0+1));
ASSUME(cdy[1] >= cr(1,0+2));
ASSUME(cdy[1] >= cr(1,3+0));
ASSUME(cdy[1] >= cr(1,4+0));
ASSUME(cdy[1] >= cr(1,5+0));
ASSUME(cdy[1] >= cr(1,6+0));
ASSUME(cdy[1] >= cr(1,7+0));
ASSUME(cdy[1] >= cr(1,8+0));
ASSUME(creturn[1] >= cdy[1]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !42, metadata !DIExpression()), !dbg !52
// call void @llvm.dbg.value(metadata i64 1, metadata !44, metadata !DIExpression()), !dbg !52
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !53
// ST: Guess
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
ASSUME(creturn[1] >= cw(1,0+1*1));
// ret i8* null, !dbg !54
ret_thread_1 = (- 1);
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !57, metadata !DIExpression()), !dbg !90
// br label %label_2, !dbg !72
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !88), !dbg !92
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !60, metadata !DIExpression()), !dbg !93
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !75
// LD: Guess
old_cr = cr(2,0+1*1);
cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+1*1)] == 2);
ASSUME(cr(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cr(2,0+1*1) >= 0);
ASSUME(cr(2,0+1*1) >= cdy[2]);
ASSUME(cr(2,0+1*1) >= cisb[2]);
ASSUME(cr(2,0+1*1) >= cdl[2]);
ASSUME(cr(2,0+1*1) >= cl[2]);
// Update
creg_r0 = cr(2,0+1*1);
crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+1*1) < cw(2,0+1*1)) {
r0 = buff(2,0+1*1);
} else {
if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) {
ASSUME(cr(2,0+1*1) >= old_cr);
}
pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1));
r0 = mem(0+1*1,cr(2,0+1*1));
}
ASSUME(creturn[2] >= cr(2,0+1*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !62, metadata !DIExpression()), !dbg !93
// %conv = trunc i64 %0 to i32, !dbg !76
// call void @llvm.dbg.value(metadata i32 %conv, metadata !58, metadata !DIExpression()), !dbg !90
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !64, metadata !DIExpression()), !dbg !96
// %1 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !78
// LD: Guess
old_cr = cr(2,0+1*1);
cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+1*1)] == 2);
ASSUME(cr(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cr(2,0+1*1) >= 0);
ASSUME(cr(2,0+1*1) >= cdy[2]);
ASSUME(cr(2,0+1*1) >= cisb[2]);
ASSUME(cr(2,0+1*1) >= cdl[2]);
ASSUME(cr(2,0+1*1) >= cl[2]);
// Update
creg_r1 = cr(2,0+1*1);
crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+1*1) < cw(2,0+1*1)) {
r1 = buff(2,0+1*1);
} else {
if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) {
ASSUME(cr(2,0+1*1) >= old_cr);
}
pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1));
r1 = mem(0+1*1,cr(2,0+1*1));
}
ASSUME(creturn[2] >= cr(2,0+1*1));
// call void @llvm.dbg.value(metadata i64 %1, metadata !66, metadata !DIExpression()), !dbg !96
// %conv4 = trunc i64 %1 to i32, !dbg !79
// call void @llvm.dbg.value(metadata i32 %conv4, metadata !63, metadata !DIExpression()), !dbg !90
// %tobool = icmp ne i32 %conv4, 0, !dbg !80
// br i1 %tobool, label %if.then, label %if.else, !dbg !82
old_cctrl = cctrl[2];
cctrl[2] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[2] >= old_cctrl);
ASSUME(cctrl[2] >= creg_r1);
ASSUME(cctrl[2] >= 0);
if((r1!=0)) {
goto T2BLOCK2;
} else {
goto T2BLOCK3;
}
T2BLOCK2:
// br label %lbl_LC00, !dbg !83
goto T2BLOCK4;
T2BLOCK3:
// br label %lbl_LC00, !dbg !84
goto T2BLOCK4;
T2BLOCK4:
// call void @llvm.dbg.label(metadata !89), !dbg !104
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !68, metadata !DIExpression()), !dbg !105
// %2 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !87
// LD: Guess
old_cr = cr(2,0+2*1);
cr(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+2*1)] == 2);
ASSUME(cr(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cr(2,0+2*1) >= 0);
ASSUME(cr(2,0+2*1) >= cdy[2]);
ASSUME(cr(2,0+2*1) >= cisb[2]);
ASSUME(cr(2,0+2*1) >= cdl[2]);
ASSUME(cr(2,0+2*1) >= cl[2]);
// Update
creg_r2 = cr(2,0+2*1);
crmax(2,0+2*1) = max(crmax(2,0+2*1),cr(2,0+2*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+2*1) < cw(2,0+2*1)) {
r2 = buff(2,0+2*1);
} else {
if(pw(2,0+2*1) != co(0+2*1,cr(2,0+2*1))) {
ASSUME(cr(2,0+2*1) >= old_cr);
}
pw(2,0+2*1) = co(0+2*1,cr(2,0+2*1));
r2 = mem(0+2*1,cr(2,0+2*1));
}
ASSUME(creturn[2] >= cr(2,0+2*1));
// call void @llvm.dbg.value(metadata i64 %2, metadata !70, metadata !DIExpression()), !dbg !105
// %conv8 = trunc i64 %2 to i32, !dbg !88
// call void @llvm.dbg.value(metadata i32 %conv8, metadata !67, metadata !DIExpression()), !dbg !90
// %xor = xor i32 %conv8, %conv8, !dbg !89
creg_r3 = max(creg_r2,creg_r2);
ASSUME(active[creg_r3] == 2);
r3 = r2 ^ r2;
// call void @llvm.dbg.value(metadata i32 %xor, metadata !71, metadata !DIExpression()), !dbg !90
// %add = add nsw i32 0, %xor, !dbg !90
creg_r4 = max(0,creg_r3);
ASSUME(active[creg_r4] == 2);
r4 = 0 + r3;
// %idxprom = sext i32 %add to i64, !dbg !90
// %arrayidx = getelementptr inbounds [3 x i64], [3 x i64]* @vars, i64 0, i64 %idxprom, !dbg !90
r5 = 0+r4*1;
ASSUME(creg_r5 >= 0);
ASSUME(creg_r5 >= creg_r4);
ASSUME(active[creg_r5] == 2);
// call void @llvm.dbg.value(metadata i64* %arrayidx, metadata !73, metadata !DIExpression()), !dbg !110
// %3 = load atomic i64, i64* %arrayidx monotonic, align 8, !dbg !90
// LD: Guess
old_cr = cr(2,r5);
cr(2,r5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,r5)] == 2);
ASSUME(cr(2,r5) >= iw(2,r5));
ASSUME(cr(2,r5) >= creg_r5);
ASSUME(cr(2,r5) >= cdy[2]);
ASSUME(cr(2,r5) >= cisb[2]);
ASSUME(cr(2,r5) >= cdl[2]);
ASSUME(cr(2,r5) >= cl[2]);
// Update
creg_r6 = cr(2,r5);
crmax(2,r5) = max(crmax(2,r5),cr(2,r5));
caddr[2] = max(caddr[2],creg_r5);
if(cr(2,r5) < cw(2,r5)) {
r6 = buff(2,r5);
} else {
if(pw(2,r5) != co(r5,cr(2,r5))) {
ASSUME(cr(2,r5) >= old_cr);
}
pw(2,r5) = co(r5,cr(2,r5));
r6 = mem(r5,cr(2,r5));
}
ASSUME(creturn[2] >= cr(2,r5));
// call void @llvm.dbg.value(metadata i64 %3, metadata !75, metadata !DIExpression()), !dbg !110
// %conv12 = trunc i64 %3 to i32, !dbg !92
// call void @llvm.dbg.value(metadata i32 %conv12, metadata !72, metadata !DIExpression()), !dbg !90
// %cmp = icmp eq i32 %conv, 1, !dbg !93
// %conv13 = zext i1 %cmp to i32, !dbg !93
// call void @llvm.dbg.value(metadata i32 %conv13, metadata !76, metadata !DIExpression()), !dbg !90
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !77, metadata !DIExpression()), !dbg !113
// %4 = zext i32 %conv13 to i64
// call void @llvm.dbg.value(metadata i64 %4, metadata !79, metadata !DIExpression()), !dbg !113
// store atomic i64 %4, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !95
// ST: Guess
iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,3);
cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,3)] == 2);
ASSUME(active[cw(2,3)] == 2);
ASSUME(sforbid(3,cw(2,3))== 0);
ASSUME(iw(2,3) >= max(creg_r0,0));
ASSUME(iw(2,3) >= 0);
ASSUME(cw(2,3) >= iw(2,3));
ASSUME(cw(2,3) >= old_cw);
ASSUME(cw(2,3) >= cr(2,3));
ASSUME(cw(2,3) >= cl[2]);
ASSUME(cw(2,3) >= cisb[2]);
ASSUME(cw(2,3) >= cdy[2]);
ASSUME(cw(2,3) >= cdl[2]);
ASSUME(cw(2,3) >= cds[2]);
ASSUME(cw(2,3) >= cctrl[2]);
ASSUME(cw(2,3) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,3) = (r0==1);
mem(3,cw(2,3)) = (r0==1);
co(3,cw(2,3))+=1;
delta(3,cw(2,3)) = -1;
ASSUME(creturn[2] >= cw(2,3));
// %cmp15 = icmp eq i32 %conv4, 2, !dbg !96
// %conv16 = zext i1 %cmp15 to i32, !dbg !96
// call void @llvm.dbg.value(metadata i32 %conv16, metadata !80, metadata !DIExpression()), !dbg !90
// call void @llvm.dbg.value(metadata i64* @atom_1_X2_2, metadata !81, metadata !DIExpression()), !dbg !116
// %5 = zext i32 %conv16 to i64
// call void @llvm.dbg.value(metadata i64 %5, metadata !83, metadata !DIExpression()), !dbg !116
// store atomic i64 %5, i64* @atom_1_X2_2 seq_cst, align 8, !dbg !98
// ST: Guess
iw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,4);
cw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,4)] == 2);
ASSUME(active[cw(2,4)] == 2);
ASSUME(sforbid(4,cw(2,4))== 0);
ASSUME(iw(2,4) >= max(creg_r1,0));
ASSUME(iw(2,4) >= 0);
ASSUME(cw(2,4) >= iw(2,4));
ASSUME(cw(2,4) >= old_cw);
ASSUME(cw(2,4) >= cr(2,4));
ASSUME(cw(2,4) >= cl[2]);
ASSUME(cw(2,4) >= cisb[2]);
ASSUME(cw(2,4) >= cdy[2]);
ASSUME(cw(2,4) >= cdl[2]);
ASSUME(cw(2,4) >= cds[2]);
ASSUME(cw(2,4) >= cctrl[2]);
ASSUME(cw(2,4) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,4) = (r1==2);
mem(4,cw(2,4)) = (r1==2);
co(4,cw(2,4))+=1;
delta(4,cw(2,4)) = -1;
ASSUME(creturn[2] >= cw(2,4));
// %cmp20 = icmp eq i32 %conv12, 0, !dbg !99
// %conv21 = zext i1 %cmp20 to i32, !dbg !99
// call void @llvm.dbg.value(metadata i32 %conv21, metadata !84, metadata !DIExpression()), !dbg !90
// call void @llvm.dbg.value(metadata i64* @atom_1_X6_0, metadata !85, metadata !DIExpression()), !dbg !119
// %6 = zext i32 %conv21 to i64
// call void @llvm.dbg.value(metadata i64 %6, metadata !87, metadata !DIExpression()), !dbg !119
// store atomic i64 %6, i64* @atom_1_X6_0 seq_cst, align 8, !dbg !101
// ST: Guess
iw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,5);
cw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,5)] == 2);
ASSUME(active[cw(2,5)] == 2);
ASSUME(sforbid(5,cw(2,5))== 0);
ASSUME(iw(2,5) >= max(creg_r6,0));
ASSUME(iw(2,5) >= 0);
ASSUME(cw(2,5) >= iw(2,5));
ASSUME(cw(2,5) >= old_cw);
ASSUME(cw(2,5) >= cr(2,5));
ASSUME(cw(2,5) >= cl[2]);
ASSUME(cw(2,5) >= cisb[2]);
ASSUME(cw(2,5) >= cdy[2]);
ASSUME(cw(2,5) >= cdl[2]);
ASSUME(cw(2,5) >= cds[2]);
ASSUME(cw(2,5) >= cctrl[2]);
ASSUME(cw(2,5) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,5) = (r6==0);
mem(5,cw(2,5)) = (r6==0);
co(5,cw(2,5))+=1;
delta(5,cw(2,5)) = -1;
ASSUME(creturn[2] >= cw(2,5));
// ret i8* null, !dbg !102
ret_thread_2 = (- 1);
// Dumping thread 3
int ret_thread_3 = 0;
cdy[3] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[3] >= cstart[3]);
T3BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !124, metadata !DIExpression()), !dbg !129
// br label %label_3, !dbg !44
goto T3BLOCK1;
T3BLOCK1:
// call void @llvm.dbg.label(metadata !128), !dbg !131
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !125, metadata !DIExpression()), !dbg !132
// call void @llvm.dbg.value(metadata i64 2, metadata !127, metadata !DIExpression()), !dbg !132
// store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !47
// ST: Guess
iw(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,0+1*1);
cw(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,0+1*1)] == 3);
ASSUME(active[cw(3,0+1*1)] == 3);
ASSUME(sforbid(0+1*1,cw(3,0+1*1))== 0);
ASSUME(iw(3,0+1*1) >= 0);
ASSUME(iw(3,0+1*1) >= 0);
ASSUME(cw(3,0+1*1) >= iw(3,0+1*1));
ASSUME(cw(3,0+1*1) >= old_cw);
ASSUME(cw(3,0+1*1) >= cr(3,0+1*1));
ASSUME(cw(3,0+1*1) >= cl[3]);
ASSUME(cw(3,0+1*1) >= cisb[3]);
ASSUME(cw(3,0+1*1) >= cdy[3]);
ASSUME(cw(3,0+1*1) >= cdl[3]);
ASSUME(cw(3,0+1*1) >= cds[3]);
ASSUME(cw(3,0+1*1) >= cctrl[3]);
ASSUME(cw(3,0+1*1) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,0+1*1) = 2;
mem(0+1*1,cw(3,0+1*1)) = 2;
co(0+1*1,cw(3,0+1*1))+=1;
delta(0+1*1,cw(3,0+1*1)) = -1;
ASSUME(creturn[3] >= cw(3,0+1*1));
// ret i8* null, !dbg !48
ret_thread_3 = (- 1);
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// %thr2 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !142, metadata !DIExpression()), !dbg !194
// call void @llvm.dbg.value(metadata i8** %argv, metadata !143, metadata !DIExpression()), !dbg !194
// %0 = bitcast i64* %thr0 to i8*, !dbg !95
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !95
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !144, metadata !DIExpression()), !dbg !196
// %1 = bitcast i64* %thr1 to i8*, !dbg !97
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !97
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !148, metadata !DIExpression()), !dbg !198
// %2 = bitcast i64* %thr2 to i8*, !dbg !99
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !99
// call void @llvm.dbg.declare(metadata i64* %thr2, metadata !149, metadata !DIExpression()), !dbg !200
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !150, metadata !DIExpression()), !dbg !201
// call void @llvm.dbg.value(metadata i64 0, metadata !152, metadata !DIExpression()), !dbg !201
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !102
// ST: Guess
iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+2*1);
cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+2*1)] == 0);
ASSUME(active[cw(0,0+2*1)] == 0);
ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(cw(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cw(0,0+2*1) >= old_cw);
ASSUME(cw(0,0+2*1) >= cr(0,0+2*1));
ASSUME(cw(0,0+2*1) >= cl[0]);
ASSUME(cw(0,0+2*1) >= cisb[0]);
ASSUME(cw(0,0+2*1) >= cdy[0]);
ASSUME(cw(0,0+2*1) >= cdl[0]);
ASSUME(cw(0,0+2*1) >= cds[0]);
ASSUME(cw(0,0+2*1) >= cctrl[0]);
ASSUME(cw(0,0+2*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+2*1) = 0;
mem(0+2*1,cw(0,0+2*1)) = 0;
co(0+2*1,cw(0,0+2*1))+=1;
delta(0+2*1,cw(0,0+2*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !153, metadata !DIExpression()), !dbg !203
// call void @llvm.dbg.value(metadata i64 0, metadata !155, metadata !DIExpression()), !dbg !203
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !104
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !156, metadata !DIExpression()), !dbg !205
// call void @llvm.dbg.value(metadata i64 0, metadata !158, metadata !DIExpression()), !dbg !205
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !106
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !159, metadata !DIExpression()), !dbg !207
// call void @llvm.dbg.value(metadata i64 0, metadata !161, metadata !DIExpression()), !dbg !207
// store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !108
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// call void @llvm.dbg.value(metadata i64* @atom_1_X2_2, metadata !162, metadata !DIExpression()), !dbg !209
// call void @llvm.dbg.value(metadata i64 0, metadata !164, metadata !DIExpression()), !dbg !209
// store atomic i64 0, i64* @atom_1_X2_2 monotonic, align 8, !dbg !110
// ST: Guess
iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,4);
cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,4)] == 0);
ASSUME(active[cw(0,4)] == 0);
ASSUME(sforbid(4,cw(0,4))== 0);
ASSUME(iw(0,4) >= 0);
ASSUME(iw(0,4) >= 0);
ASSUME(cw(0,4) >= iw(0,4));
ASSUME(cw(0,4) >= old_cw);
ASSUME(cw(0,4) >= cr(0,4));
ASSUME(cw(0,4) >= cl[0]);
ASSUME(cw(0,4) >= cisb[0]);
ASSUME(cw(0,4) >= cdy[0]);
ASSUME(cw(0,4) >= cdl[0]);
ASSUME(cw(0,4) >= cds[0]);
ASSUME(cw(0,4) >= cctrl[0]);
ASSUME(cw(0,4) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,4) = 0;
mem(4,cw(0,4)) = 0;
co(4,cw(0,4))+=1;
delta(4,cw(0,4)) = -1;
ASSUME(creturn[0] >= cw(0,4));
// call void @llvm.dbg.value(metadata i64* @atom_1_X6_0, metadata !165, metadata !DIExpression()), !dbg !211
// call void @llvm.dbg.value(metadata i64 0, metadata !167, metadata !DIExpression()), !dbg !211
// store atomic i64 0, i64* @atom_1_X6_0 monotonic, align 8, !dbg !112
// ST: Guess
iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,5);
cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,5)] == 0);
ASSUME(active[cw(0,5)] == 0);
ASSUME(sforbid(5,cw(0,5))== 0);
ASSUME(iw(0,5) >= 0);
ASSUME(iw(0,5) >= 0);
ASSUME(cw(0,5) >= iw(0,5));
ASSUME(cw(0,5) >= old_cw);
ASSUME(cw(0,5) >= cr(0,5));
ASSUME(cw(0,5) >= cl[0]);
ASSUME(cw(0,5) >= cisb[0]);
ASSUME(cw(0,5) >= cdy[0]);
ASSUME(cw(0,5) >= cdl[0]);
ASSUME(cw(0,5) >= cds[0]);
ASSUME(cw(0,5) >= cctrl[0]);
ASSUME(cw(0,5) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,5) = 0;
mem(5,cw(0,5)) = 0;
co(5,cw(0,5))+=1;
delta(5,cw(0,5)) = -1;
ASSUME(creturn[0] >= cw(0,5));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !113
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call11 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !114
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %call12 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !115
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[3] >= cdy[0]);
// %3 = load i64, i64* %thr0, align 8, !dbg !116, !tbaa !117
// LD: Guess
old_cr = cr(0,6);
cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,6)] == 0);
ASSUME(cr(0,6) >= iw(0,6));
ASSUME(cr(0,6) >= 0);
ASSUME(cr(0,6) >= cdy[0]);
ASSUME(cr(0,6) >= cisb[0]);
ASSUME(cr(0,6) >= cdl[0]);
ASSUME(cr(0,6) >= cl[0]);
// Update
creg_r8 = cr(0,6);
crmax(0,6) = max(crmax(0,6),cr(0,6));
caddr[0] = max(caddr[0],0);
if(cr(0,6) < cw(0,6)) {
r8 = buff(0,6);
} else {
if(pw(0,6) != co(6,cr(0,6))) {
ASSUME(cr(0,6) >= old_cr);
}
pw(0,6) = co(6,cr(0,6));
r8 = mem(6,cr(0,6));
}
ASSUME(creturn[0] >= cr(0,6));
// %call13 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !121
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %4 = load i64, i64* %thr1, align 8, !dbg !122, !tbaa !117
// LD: Guess
old_cr = cr(0,7);
cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,7)] == 0);
ASSUME(cr(0,7) >= iw(0,7));
ASSUME(cr(0,7) >= 0);
ASSUME(cr(0,7) >= cdy[0]);
ASSUME(cr(0,7) >= cisb[0]);
ASSUME(cr(0,7) >= cdl[0]);
ASSUME(cr(0,7) >= cl[0]);
// Update
creg_r9 = cr(0,7);
crmax(0,7) = max(crmax(0,7),cr(0,7));
caddr[0] = max(caddr[0],0);
if(cr(0,7) < cw(0,7)) {
r9 = buff(0,7);
} else {
if(pw(0,7) != co(7,cr(0,7))) {
ASSUME(cr(0,7) >= old_cr);
}
pw(0,7) = co(7,cr(0,7));
r9 = mem(7,cr(0,7));
}
ASSUME(creturn[0] >= cr(0,7));
// %call14 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !123
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %5 = load i64, i64* %thr2, align 8, !dbg !124, !tbaa !117
// LD: Guess
old_cr = cr(0,8);
cr(0,8) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,8)] == 0);
ASSUME(cr(0,8) >= iw(0,8));
ASSUME(cr(0,8) >= 0);
ASSUME(cr(0,8) >= cdy[0]);
ASSUME(cr(0,8) >= cisb[0]);
ASSUME(cr(0,8) >= cdl[0]);
ASSUME(cr(0,8) >= cl[0]);
// Update
creg_r10 = cr(0,8);
crmax(0,8) = max(crmax(0,8),cr(0,8));
caddr[0] = max(caddr[0],0);
if(cr(0,8) < cw(0,8)) {
r10 = buff(0,8);
} else {
if(pw(0,8) != co(8,cr(0,8))) {
ASSUME(cr(0,8) >= old_cr);
}
pw(0,8) = co(8,cr(0,8));
r10 = mem(8,cr(0,8));
}
ASSUME(creturn[0] >= cr(0,8));
// %call15 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !125
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[3]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !169, metadata !DIExpression()), !dbg !226
// %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) seq_cst, align 8, !dbg !127
// LD: Guess
old_cr = cr(0,0);
cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0)] == 0);
ASSUME(cr(0,0) >= iw(0,0));
ASSUME(cr(0,0) >= 0);
ASSUME(cr(0,0) >= cdy[0]);
ASSUME(cr(0,0) >= cisb[0]);
ASSUME(cr(0,0) >= cdl[0]);
ASSUME(cr(0,0) >= cl[0]);
// Update
creg_r11 = cr(0,0);
crmax(0,0) = max(crmax(0,0),cr(0,0));
caddr[0] = max(caddr[0],0);
if(cr(0,0) < cw(0,0)) {
r11 = buff(0,0);
} else {
if(pw(0,0) != co(0,cr(0,0))) {
ASSUME(cr(0,0) >= old_cr);
}
pw(0,0) = co(0,cr(0,0));
r11 = mem(0,cr(0,0));
}
ASSUME(creturn[0] >= cr(0,0));
// call void @llvm.dbg.value(metadata i64 %6, metadata !171, metadata !DIExpression()), !dbg !226
// %conv = trunc i64 %6 to i32, !dbg !128
// call void @llvm.dbg.value(metadata i32 %conv, metadata !168, metadata !DIExpression()), !dbg !194
// %cmp = icmp eq i32 %conv, 1, !dbg !129
// %conv16 = zext i1 %cmp to i32, !dbg !129
// call void @llvm.dbg.value(metadata i32 %conv16, metadata !172, metadata !DIExpression()), !dbg !194
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !174, metadata !DIExpression()), !dbg !230
// %7 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) seq_cst, align 8, !dbg !131
// LD: Guess
old_cr = cr(0,0+1*1);
cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0+1*1)] == 0);
ASSUME(cr(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cr(0,0+1*1) >= 0);
ASSUME(cr(0,0+1*1) >= cdy[0]);
ASSUME(cr(0,0+1*1) >= cisb[0]);
ASSUME(cr(0,0+1*1) >= cdl[0]);
ASSUME(cr(0,0+1*1) >= cl[0]);
// Update
creg_r12 = cr(0,0+1*1);
crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1));
caddr[0] = max(caddr[0],0);
if(cr(0,0+1*1) < cw(0,0+1*1)) {
r12 = buff(0,0+1*1);
} else {
if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) {
ASSUME(cr(0,0+1*1) >= old_cr);
}
pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1));
r12 = mem(0+1*1,cr(0,0+1*1));
}
ASSUME(creturn[0] >= cr(0,0+1*1));
// call void @llvm.dbg.value(metadata i64 %7, metadata !176, metadata !DIExpression()), !dbg !230
// %conv20 = trunc i64 %7 to i32, !dbg !132
// call void @llvm.dbg.value(metadata i32 %conv20, metadata !173, metadata !DIExpression()), !dbg !194
// %cmp21 = icmp eq i32 %conv20, 2, !dbg !133
// %conv22 = zext i1 %cmp21 to i32, !dbg !133
// call void @llvm.dbg.value(metadata i32 %conv22, metadata !177, metadata !DIExpression()), !dbg !194
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !179, metadata !DIExpression()), !dbg !234
// %8 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !135
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r13 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r13 = buff(0,3);
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r13 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i64 %8, metadata !181, metadata !DIExpression()), !dbg !234
// %conv26 = trunc i64 %8 to i32, !dbg !136
// call void @llvm.dbg.value(metadata i32 %conv26, metadata !178, metadata !DIExpression()), !dbg !194
// call void @llvm.dbg.value(metadata i64* @atom_1_X2_2, metadata !183, metadata !DIExpression()), !dbg !237
// %9 = load atomic i64, i64* @atom_1_X2_2 seq_cst, align 8, !dbg !138
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r14 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r14 = buff(0,4);
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r14 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// call void @llvm.dbg.value(metadata i64 %9, metadata !185, metadata !DIExpression()), !dbg !237
// %conv30 = trunc i64 %9 to i32, !dbg !139
// call void @llvm.dbg.value(metadata i32 %conv30, metadata !182, metadata !DIExpression()), !dbg !194
// call void @llvm.dbg.value(metadata i64* @atom_1_X6_0, metadata !187, metadata !DIExpression()), !dbg !240
// %10 = load atomic i64, i64* @atom_1_X6_0 seq_cst, align 8, !dbg !141
// LD: Guess
old_cr = cr(0,5);
cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,5)] == 0);
ASSUME(cr(0,5) >= iw(0,5));
ASSUME(cr(0,5) >= 0);
ASSUME(cr(0,5) >= cdy[0]);
ASSUME(cr(0,5) >= cisb[0]);
ASSUME(cr(0,5) >= cdl[0]);
ASSUME(cr(0,5) >= cl[0]);
// Update
creg_r15 = cr(0,5);
crmax(0,5) = max(crmax(0,5),cr(0,5));
caddr[0] = max(caddr[0],0);
if(cr(0,5) < cw(0,5)) {
r15 = buff(0,5);
} else {
if(pw(0,5) != co(5,cr(0,5))) {
ASSUME(cr(0,5) >= old_cr);
}
pw(0,5) = co(5,cr(0,5));
r15 = mem(5,cr(0,5));
}
ASSUME(creturn[0] >= cr(0,5));
// call void @llvm.dbg.value(metadata i64 %10, metadata !189, metadata !DIExpression()), !dbg !240
// %conv34 = trunc i64 %10 to i32, !dbg !142
// call void @llvm.dbg.value(metadata i32 %conv34, metadata !186, metadata !DIExpression()), !dbg !194
// %and = and i32 %conv30, %conv34, !dbg !143
creg_r16 = max(creg_r14,creg_r15);
ASSUME(active[creg_r16] == 0);
r16 = r14 & r15;
// call void @llvm.dbg.value(metadata i32 %and, metadata !190, metadata !DIExpression()), !dbg !194
// %and35 = and i32 %conv26, %and, !dbg !144
creg_r17 = max(creg_r13,creg_r16);
ASSUME(active[creg_r17] == 0);
r17 = r13 & r16;
// call void @llvm.dbg.value(metadata i32 %and35, metadata !191, metadata !DIExpression()), !dbg !194
// %and36 = and i32 %conv22, %and35, !dbg !145
creg_r18 = max(max(creg_r12,0),creg_r17);
ASSUME(active[creg_r18] == 0);
r18 = (r12==2) & r17;
// call void @llvm.dbg.value(metadata i32 %and36, metadata !192, metadata !DIExpression()), !dbg !194
// %and37 = and i32 %conv16, %and36, !dbg !146
creg_r19 = max(max(creg_r11,0),creg_r18);
ASSUME(active[creg_r19] == 0);
r19 = (r11==1) & r18;
// call void @llvm.dbg.value(metadata i32 %and37, metadata !193, metadata !DIExpression()), !dbg !194
// %cmp38 = icmp eq i32 %and37, 1, !dbg !147
// br i1 %cmp38, label %if.then, label %if.end, !dbg !149
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg_r19);
ASSUME(cctrl[0] >= 0);
if((r19==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([112 x i8], [112 x i8]* @.str.1, i64 0, i64 0), i32 noundef 82, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !150
// unreachable, !dbg !150
r20 = 1;
T0BLOCK2:
// %11 = bitcast i64* %thr2 to i8*, !dbg !153
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !153
// %12 = bitcast i64* %thr1 to i8*, !dbg !153
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %12) #7, !dbg !153
// %13 = bitcast i64* %thr0 to i8*, !dbg !153
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %13) #7, !dbg !153
// ret i32 0, !dbg !154
ret_thread_0 = 0;
ASSERT(r20== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
7057d762a069c4c683b1f6fad432533577568a9b | a5a85f7b11fe781042c1e4e3fabdf46308c026b1 | /Module 2/main.c/coeur.c/coeur.c.ino | d55b238d7c8710e164544c2a9cbe506d688b2380 | [] | no_license | FlorianCa/Projet-Hexart-Care | 6191cda8a7357953c14dfd95ab5195cf3981c8b8 | c123c9e371a43e47b84f64d0ae5f7aa11df6fb03 | refs/heads/master | 2021-09-28T18:09:55.365803 | 2018-11-16T13:54:50 | 2018-11-16T13:54:50 | 157,174,888 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,921 | ino | #include "coeur.h"
#include "param.h"
int TabPinLed[10]={2,3,4,5,6,7,8,9,10,11};
int TabPinLed_1[10]={11,10,9,8,7,6,5,4,3,2};
int TabPinLed_2[5]={2,4,6,8,10};
int TabPinLed_3[5]={3,5,7,9,11};
int TabPinLed_4[4]={2,5,8,11};
int TabPinLed_5[4]={3,5,9,2};
int TabPinLed_6[4]={4,7,10,3};
int TabPinLed_7[5]={2,3,4,5,6};
int TabPinLed_8[5]={7,8,9,10,11};
int i;
// Initialization of the DELLs'numbers all the "#define" lines associate a DELL to a number.
#define LED_1 2
#define LED_2 3
#define LED_3 4
#define LED_4 5
#define LED_5 6
#define LED_6 7
#define LED_7 8
#define LED_8 9
#define LED_9 10
#define LED_10 11
/*
Initialization of the blinking mode
LED_MODE 1 = bCoeur
LED_MODE 2 = unSurDeux
LED_MODE 3 = unSurTrois
LED_MODE 4 = auchoix
LED_MODE 5 = Chenille
*/
#define LED_auChoix 5
//Those lines define pinmodes of the Arduino as outputs so each pinmode is associate with a DELL
void setup() {
Serial.begin(9600);
pinMode(LED_1, OUTPUT);
pinMode(LED_2, OUTPUT);
pinMode(LED_3, OUTPUT);
pinMode(LED_4, OUTPUT);
pinMode(LED_5, OUTPUT);
pinMode(LED_6, OUTPUT);
pinMode(LED_7, OUTPUT);
pinMode(LED_8, OUTPUT);
pinMode(LED_9, OUTPUT);
pinMode(LED_10, OUTPUT);
}
//Main loop, the switch is connected with LED_MODE's value so we have cases for all the value we can put into LED_MODE as it was said before.
void loop() {
switch(LED_MODE){
case 1 :
Mode_bCoeur();
break;
case 2 :
Mode_unSurDeux();
break;
case 3 :
Mode_unSurTrois();
break;
case 4 :
Mode_auChoix();
break;
case 5 :
Mode_chenille();
break;
case 6 :
Mode_fade();
break;
case 7:
Mode_moitie();
break;
case 8:
Mode_chenillard();
break;
case 9:
Mode_allerRetour();
break;
default:
while(1);
}
}
| [
"44927341+FlorianCa@users.noreply.github.com"
] | 44927341+FlorianCa@users.noreply.github.com |
47021d97e7695899d135f6ab1e979a8d88a9ef26 | 7ff45f1195fa4bebb46237649b76fa97912ed587 | /src/runtime/src/coreclr/vm/codeman.cpp | 0dc1e17680681b54803a0adc537b8948bd32e66a | [
"MIT"
] | permissive | directhex/dotnet | 5665ed71a1c4e9289ab7d86162954431967bc015 | 02cc69a55e6a44eb1e783e22fa8d9c4f64c7ac90 | refs/heads/main | 2023-08-09T08:35:32.866522 | 2022-12-08T00:01:47 | 2022-12-08T00:01:47 | 575,902,243 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 226,113 | cpp | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// codeman.cpp - a managment class for handling multiple code managers
//
#include "common.h"
#include "jitinterface.h"
#include "corjit.h"
#include "jithost.h"
#include "eetwain.h"
#include "eeconfig.h"
#include "excep.h"
#include "appdomain.hpp"
#include "codeman.h"
#include "nibblemapmacros.h"
#include "generics.h"
#include "dynamicmethod.h"
#include "eventtrace.h"
#include "threadsuspend.h"
#include "exceptionhandling.h"
#include "rtlfunctions.h"
#include "shimload.h"
#include "debuginfostore.h"
#include "strsafe.h"
#include "configuration.h"
#ifdef HOST_64BIT
#define CHECK_DUPLICATED_STRUCT_LAYOUTS
#include "../debug/daccess/fntableaccess.h"
#endif // HOST_64BIT
#ifdef FEATURE_PERFMAP
#include "perfmap.h"
#endif
// Default number of jump stubs in a jump stub block
#define DEFAULT_JUMPSTUBS_PER_BLOCK 32
SPTR_IMPL(EECodeManager, ExecutionManager, m_pDefaultCodeMan);
SPTR_IMPL(EEJitManager, ExecutionManager, m_pEEJitManager);
#ifdef FEATURE_READYTORUN
SPTR_IMPL(ReadyToRunJitManager, ExecutionManager, m_pReadyToRunJitManager);
#endif
VOLATILE_SPTR_IMPL_INIT(RangeSection, ExecutionManager, m_CodeRangeList, NULL);
VOLATILE_SVAL_IMPL_INIT(LONG, ExecutionManager, m_dwReaderCount, 0);
VOLATILE_SVAL_IMPL_INIT(LONG, ExecutionManager, m_dwWriterLock, 0);
#ifndef DACCESS_COMPILE
CrstStatic ExecutionManager::m_JumpStubCrst;
CrstStatic ExecutionManager::m_RangeCrst;
unsigned ExecutionManager::m_normal_JumpStubLookup;
unsigned ExecutionManager::m_normal_JumpStubUnique;
unsigned ExecutionManager::m_normal_JumpStubBlockAllocCount;
unsigned ExecutionManager::m_normal_JumpStubBlockFullCount;
unsigned ExecutionManager::m_LCG_JumpStubLookup;
unsigned ExecutionManager::m_LCG_JumpStubUnique;
unsigned ExecutionManager::m_LCG_JumpStubBlockAllocCount;
unsigned ExecutionManager::m_LCG_JumpStubBlockFullCount;
#endif // DACCESS_COMPILE
#if defined(TARGET_AMD64) && !defined(DACCESS_COMPILE) // We don't do this on ARM just amd64
// Support for new style unwind information (to allow OS to stack crawl JIT compiled code).
typedef NTSTATUS (WINAPI* RtlAddGrowableFunctionTableFnPtr) (
PVOID *DynamicTable, PRUNTIME_FUNCTION FunctionTable, ULONG EntryCount,
ULONG MaximumEntryCount, ULONG_PTR rangeStart, ULONG_PTR rangeEnd);
typedef VOID (WINAPI* RtlGrowFunctionTableFnPtr) (PVOID DynamicTable, ULONG NewEntryCount);
typedef VOID (WINAPI* RtlDeleteGrowableFunctionTableFnPtr) (PVOID DynamicTable);
// OS entry points (only exist on Win8 and above)
static RtlAddGrowableFunctionTableFnPtr pRtlAddGrowableFunctionTable;
static RtlGrowFunctionTableFnPtr pRtlGrowFunctionTable;
static RtlDeleteGrowableFunctionTableFnPtr pRtlDeleteGrowableFunctionTable;
static Volatile<bool> RtlUnwindFtnsInited;
// statics for UnwindInfoTable
Crst* UnwindInfoTable::s_pUnwindInfoTableLock = NULL;
Volatile<bool> UnwindInfoTable::s_publishingActive = false;
#if _DEBUG
// Fake functions on Win7 checked build to excercize the code paths, they are no-ops
NTSTATUS WINAPI FakeRtlAddGrowableFunctionTable (
PVOID *DynamicTable, PT_RUNTIME_FUNCTION FunctionTable, ULONG EntryCount,
ULONG MaximumEntryCount, ULONG_PTR rangeStart, ULONG_PTR rangeEnd) { *DynamicTable = (PVOID) 1; return 0; }
VOID WINAPI FakeRtlGrowFunctionTable (PVOID DynamicTable, ULONG NewEntryCount) { }
VOID WINAPI FakeRtlDeleteGrowableFunctionTable (PVOID DynamicTable) {}
#endif
/****************************************************************************/
// initialize the entry points for new win8 unwind info publishing functions.
// return true if the initialize is successful (the functions exist)
bool InitUnwindFtns()
{
CONTRACTL {
NOTHROW;
} CONTRACTL_END;
#ifndef TARGET_UNIX
if (!RtlUnwindFtnsInited)
{
HINSTANCE hNtdll = WszGetModuleHandle(W("ntdll.dll"));
if (hNtdll != NULL)
{
void* growFunctionTable = GetProcAddress(hNtdll, "RtlGrowFunctionTable");
void* deleteGrowableFunctionTable = GetProcAddress(hNtdll, "RtlDeleteGrowableFunctionTable");
void* addGrowableFunctionTable = GetProcAddress(hNtdll, "RtlAddGrowableFunctionTable");
// All or nothing AddGroableFunctionTable is last (marker)
if (growFunctionTable != NULL &&
deleteGrowableFunctionTable != NULL &&
addGrowableFunctionTable != NULL)
{
pRtlGrowFunctionTable = (RtlGrowFunctionTableFnPtr) growFunctionTable;
pRtlDeleteGrowableFunctionTable = (RtlDeleteGrowableFunctionTableFnPtr) deleteGrowableFunctionTable;
pRtlAddGrowableFunctionTable = (RtlAddGrowableFunctionTableFnPtr) addGrowableFunctionTable;
}
// Don't call FreeLibrary(hNtdll) because GetModuleHandle did *NOT* increment the reference count!
}
else
{
#if _DEBUG
pRtlGrowFunctionTable = FakeRtlGrowFunctionTable;
pRtlDeleteGrowableFunctionTable = FakeRtlDeleteGrowableFunctionTable;
pRtlAddGrowableFunctionTable = FakeRtlAddGrowableFunctionTable;
#endif
}
RtlUnwindFtnsInited = true;
}
return (pRtlAddGrowableFunctionTable != NULL);
#else // !TARGET_UNIX
return false;
#endif // !TARGET_UNIX
}
/****************************************************************************/
UnwindInfoTable::UnwindInfoTable(ULONG_PTR rangeStart, ULONG_PTR rangeEnd, ULONG size)
{
STANDARD_VM_CONTRACT;
_ASSERTE(s_pUnwindInfoTableLock->OwnedByCurrentThread());
_ASSERTE((rangeEnd - rangeStart) <= 0x7FFFFFFF);
cTableCurCount = 0;
cTableMaxCount = size;
cDeletedEntries = 0;
iRangeStart = rangeStart;
iRangeEnd = rangeEnd;
hHandle = NULL;
pTable = new T_RUNTIME_FUNCTION[cTableMaxCount];
}
/****************************************************************************/
UnwindInfoTable::~UnwindInfoTable()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
_ASSERTE(s_publishingActive);
// We do this lock free to because too many places still want no-trigger. It should be OK
// It would be cleaner if we could take the lock (we did not have to be GC_NOTRIGGER)
UnRegister();
delete[] pTable;
}
/*****************************************************************************/
void UnwindInfoTable::Register()
{
_ASSERTE(s_pUnwindInfoTableLock->OwnedByCurrentThread());
EX_TRY
{
hHandle = NULL;
NTSTATUS ret = pRtlAddGrowableFunctionTable(&hHandle, pTable, cTableCurCount, cTableMaxCount, iRangeStart, iRangeEnd);
if (ret != STATUS_SUCCESS)
{
_ASSERTE(!"Failed to publish UnwindInfo (ignorable)");
hHandle = NULL;
STRESS_LOG3(LF_JIT, LL_ERROR, "UnwindInfoTable::Register ERROR %x creating table [%p, %p]\n", ret, iRangeStart, iRangeEnd);
}
else
{
STRESS_LOG3(LF_JIT, LL_INFO100, "UnwindInfoTable::Register Handle: %p [%p, %p]\n", hHandle, iRangeStart, iRangeEnd);
}
}
EX_CATCH
{
hHandle = NULL;
STRESS_LOG2(LF_JIT, LL_ERROR, "UnwindInfoTable::Register Exception while creating table [%p, %p]\n",
iRangeStart, iRangeEnd);
_ASSERTE(!"Failed to publish UnwindInfo (ignorable)");
}
EX_END_CATCH(SwallowAllExceptions)
}
/*****************************************************************************/
void UnwindInfoTable::UnRegister()
{
PVOID handle = hHandle;
hHandle = 0;
if (handle != 0)
{
STRESS_LOG3(LF_JIT, LL_INFO100, "UnwindInfoTable::UnRegister Handle: %p [%p, %p]\n", handle, iRangeStart, iRangeEnd);
pRtlDeleteGrowableFunctionTable(handle);
}
}
/*****************************************************************************/
// Add 'data' to the linked list whose head is pointed at by 'unwindInfoPtr'
//
/* static */
void UnwindInfoTable::AddToUnwindInfoTable(UnwindInfoTable** unwindInfoPtr, PT_RUNTIME_FUNCTION data,
TADDR rangeStart, TADDR rangeEnd)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
}
CONTRACTL_END;
_ASSERTE(data->BeginAddress <= RUNTIME_FUNCTION__EndAddress(data, rangeStart));
_ASSERTE(RUNTIME_FUNCTION__EndAddress(data, rangeStart) <= (rangeEnd-rangeStart));
_ASSERTE(unwindInfoPtr != NULL);
if (!s_publishingActive)
return;
CrstHolder ch(s_pUnwindInfoTableLock);
UnwindInfoTable* unwindInfo = *unwindInfoPtr;
// was the original list null, If so lazy initialize.
if (unwindInfo == NULL)
{
// We can choose the average method size estimate dynamically based on past experience
// 128 is the estimated size of an average method, so we can accurately predict
// how many RUNTIME_FUNCTION entries are in each chunk we allocate.
ULONG size = (ULONG) ((rangeEnd - rangeStart) / 128) + 1;
// To insure the test the growing logic in debug code make the size much smaller.
INDEBUG(size = size / 4 + 1);
unwindInfo = (PTR_UnwindInfoTable)new UnwindInfoTable(rangeStart, rangeEnd, size);
unwindInfo->Register();
*unwindInfoPtr = unwindInfo;
}
_ASSERTE(unwindInfo != NULL); // If new had failed, we would have thrown OOM
_ASSERTE(unwindInfo->cTableCurCount <= unwindInfo->cTableMaxCount);
_ASSERTE(unwindInfo->iRangeStart == rangeStart);
_ASSERTE(unwindInfo->iRangeEnd == rangeEnd);
// Means we had a failure publishing to the OS, in this case we give up
if (unwindInfo->hHandle == NULL)
return;
// Check for the fast path: we are adding the end of an UnwindInfoTable with space
if (unwindInfo->cTableCurCount < unwindInfo->cTableMaxCount)
{
if (unwindInfo->cTableCurCount == 0 ||
unwindInfo->pTable[unwindInfo->cTableCurCount-1].BeginAddress < data->BeginAddress)
{
// Yeah, we can simply add to the end of table and we are done!
unwindInfo->pTable[unwindInfo->cTableCurCount] = *data;
unwindInfo->cTableCurCount++;
// Add to the function table
pRtlGrowFunctionTable(unwindInfo->hHandle, unwindInfo->cTableCurCount);
STRESS_LOG5(LF_JIT, LL_INFO1000, "AddToUnwindTable Handle: %p [%p, %p] ADDING 0x%p TO END, now 0x%x entries\n",
unwindInfo->hHandle, unwindInfo->iRangeStart, unwindInfo->iRangeEnd,
data->BeginAddress, unwindInfo->cTableCurCount);
return;
}
}
// OK we need to rellocate the table and reregister. First figure out our 'desiredSpace'
// We could imagine being much more efficient for 'bulk' updates, but we don't try
// because we assume that this is rare and we want to keep the code simple
ULONG usedSpace = unwindInfo->cTableCurCount - unwindInfo->cDeletedEntries;
ULONG desiredSpace = usedSpace * 5 / 4 + 1; // Increase by 20%
// Be more aggressive if we used all of our space;
if (usedSpace == unwindInfo->cTableMaxCount)
desiredSpace = usedSpace * 3 / 2 + 1; // Increase by 50%
STRESS_LOG7(LF_JIT, LL_INFO100, "AddToUnwindTable Handle: %p [%p, %p] SLOW Realloc Cnt 0x%x Max 0x%x NewMax 0x%x, Adding %x\n",
unwindInfo->hHandle, unwindInfo->iRangeStart, unwindInfo->iRangeEnd,
unwindInfo->cTableCurCount, unwindInfo->cTableMaxCount, desiredSpace, data->BeginAddress);
UnwindInfoTable* newTab = new UnwindInfoTable(unwindInfo->iRangeStart, unwindInfo->iRangeEnd, desiredSpace);
// Copy in the entries, removing deleted entries and adding the new entry wherever it belongs
int toIdx = 0;
bool inserted = false; // Have we inserted 'data' into the table
for(ULONG fromIdx = 0; fromIdx < unwindInfo->cTableCurCount; fromIdx++)
{
if (!inserted && data->BeginAddress < unwindInfo->pTable[fromIdx].BeginAddress)
{
STRESS_LOG1(LF_JIT, LL_INFO100, "AddToUnwindTable Inserted at MID position 0x%x\n", toIdx);
newTab->pTable[toIdx++] = *data;
inserted = true;
}
if (unwindInfo->pTable[fromIdx].UnwindData != 0) // A 'non-deleted' entry
newTab->pTable[toIdx++] = unwindInfo->pTable[fromIdx];
}
if (!inserted)
{
STRESS_LOG1(LF_JIT, LL_INFO100, "AddToUnwindTable Inserted at END position 0x%x\n", toIdx);
newTab->pTable[toIdx++] = *data;
}
newTab->cTableCurCount = toIdx;
STRESS_LOG2(LF_JIT, LL_INFO100, "AddToUnwindTable New size 0x%x max 0x%x\n",
newTab->cTableCurCount, newTab->cTableMaxCount);
_ASSERTE(newTab->cTableCurCount <= newTab->cTableMaxCount);
// Unregister the old table
*unwindInfoPtr = 0;
unwindInfo->UnRegister();
// Note that there is a short time when we are not publishing...
// Register the new table
newTab->Register();
*unwindInfoPtr = newTab;
delete unwindInfo;
}
/*****************************************************************************/
/* static */ void UnwindInfoTable::RemoveFromUnwindInfoTable(UnwindInfoTable** unwindInfoPtr, TADDR baseAddress, TADDR entryPoint)
{
CONTRACTL {
NOTHROW;
GC_TRIGGERS;
} CONTRACTL_END;
_ASSERTE(unwindInfoPtr != NULL);
if (!s_publishingActive)
return;
CrstHolder ch(s_pUnwindInfoTableLock);
UnwindInfoTable* unwindInfo = *unwindInfoPtr;
if (unwindInfo != NULL)
{
DWORD relativeEntryPoint = (DWORD)(entryPoint - baseAddress);
STRESS_LOG3(LF_JIT, LL_INFO100, "RemoveFromUnwindInfoTable Removing %p BaseAddress %p rel %x\n",
entryPoint, baseAddress, relativeEntryPoint);
for(ULONG i = 0; i < unwindInfo->cTableCurCount; i++)
{
if (unwindInfo->pTable[i].BeginAddress <= relativeEntryPoint &&
relativeEntryPoint < RUNTIME_FUNCTION__EndAddress(&unwindInfo->pTable[i], unwindInfo->iRangeStart))
{
if (unwindInfo->pTable[i].UnwindData != 0)
unwindInfo->cDeletedEntries++;
unwindInfo->pTable[i].UnwindData = 0; // Mark the entry for deletion
STRESS_LOG1(LF_JIT, LL_INFO100, "RemoveFromUnwindInfoTable Removed entry 0x%x\n", i);
return;
}
}
}
STRESS_LOG2(LF_JIT, LL_WARNING, "RemoveFromUnwindInfoTable COULD NOT FIND %p BaseAddress %p\n",
entryPoint, baseAddress);
}
/****************************************************************************/
// Publish the stack unwind data 'data' which is relative 'baseAddress'
// to the operating system in a way ETW stack tracing can use.
/* static */ void UnwindInfoTable::PublishUnwindInfoForMethod(TADDR baseAddress, PT_RUNTIME_FUNCTION unwindInfo, int unwindInfoCount)
{
STANDARD_VM_CONTRACT;
if (!s_publishingActive)
return;
TADDR entry = baseAddress + unwindInfo->BeginAddress;
RangeSection * pRS = ExecutionManager::FindCodeRange(entry, ExecutionManager::GetScanFlags());
_ASSERTE(pRS != NULL);
if (pRS != NULL)
{
for(int i = 0; i < unwindInfoCount; i++)
AddToUnwindInfoTable(&pRS->pUnwindInfoTable, &unwindInfo[i], pRS->LowAddress, pRS->HighAddress);
}
}
/*****************************************************************************/
/* static */ void UnwindInfoTable::UnpublishUnwindInfoForMethod(TADDR entryPoint)
{
CONTRACTL {
NOTHROW;
GC_TRIGGERS;
} CONTRACTL_END;
if (!s_publishingActive)
return;
RangeSection * pRS = ExecutionManager::FindCodeRange(entryPoint, ExecutionManager::GetScanFlags());
_ASSERTE(pRS != NULL);
if (pRS != NULL)
{
_ASSERTE(pRS->pjit->GetCodeType() == (miManaged | miIL));
if (pRS->pjit->GetCodeType() == (miManaged | miIL))
{
// This cast is justified because only EEJitManager's have the code type above.
EEJitManager* pJitMgr = (EEJitManager*)(pRS->pjit);
CodeHeader * pHeader = pJitMgr->GetCodeHeaderFromStartAddress(entryPoint);
for(ULONG i = 0; i < pHeader->GetNumberOfUnwindInfos(); i++)
RemoveFromUnwindInfoTable(&pRS->pUnwindInfoTable, pRS->LowAddress, pRS->LowAddress + pHeader->GetUnwindInfo(i)->BeginAddress);
}
}
}
#ifdef STUBLINKER_GENERATES_UNWIND_INFO
extern StubUnwindInfoHeapSegment *g_StubHeapSegments;
#endif // STUBLINKER_GENERATES_UNWIND_INFO
extern CrstStatic g_StubUnwindInfoHeapSegmentsCrst;
/*****************************************************************************/
// Publish all existing JIT compiled methods by iterating through the code heap
// Note that because we need to keep the entries in order we have to hold
// s_pUnwindInfoTableLock so that all entries get inserted in the correct order.
// (we rely on heapIterator walking the methods in a heap section in order).
/* static */ void UnwindInfoTable::PublishUnwindInfoForExistingMethods()
{
STANDARD_VM_CONTRACT;
{
// CodeHeapIterator holds the m_CodeHeapCritSec, which insures code heaps don't get deallocated while being walked
EEJitManager::CodeHeapIterator heapIterator(NULL);
// Currently m_CodeHeapCritSec is given the CRST_UNSAFE_ANYMODE flag which allows it to be taken in a GC_NOTRIGGER
// region but also disallows GC_TRIGGERS. We need GC_TRIGGERS because we take another lock. Ideally we would
// fix m_CodeHeapCritSec to not have the CRST_UNSAFE_ANYMODE flag, but I currently reached my threshold for fixing
// contracts.
CONTRACT_VIOLATION(GCViolation);
while(heapIterator.Next())
{
MethodDesc *pMD = heapIterator.GetMethod();
if(pMD)
{
PCODE methodEntry =(PCODE) heapIterator.GetMethodCode();
RangeSection * pRS = ExecutionManager::FindCodeRange(methodEntry, ExecutionManager::GetScanFlags());
_ASSERTE(pRS != NULL);
_ASSERTE(pRS->pjit->GetCodeType() == (miManaged | miIL));
if (pRS != NULL && pRS->pjit->GetCodeType() == (miManaged | miIL))
{
// This cast is justified because only EEJitManager's have the code type above.
EEJitManager* pJitMgr = (EEJitManager*)(pRS->pjit);
CodeHeader * pHeader = pJitMgr->GetCodeHeaderFromStartAddress(methodEntry);
int unwindInfoCount = pHeader->GetNumberOfUnwindInfos();
for(int i = 0; i < unwindInfoCount; i++)
AddToUnwindInfoTable(&pRS->pUnwindInfoTable, pHeader->GetUnwindInfo(i), pRS->LowAddress, pRS->HighAddress);
}
}
}
}
#ifdef STUBLINKER_GENERATES_UNWIND_INFO
// Enumerate all existing stubs
CrstHolder crst(&g_StubUnwindInfoHeapSegmentsCrst);
for (StubUnwindInfoHeapSegment* pStubHeapSegment = g_StubHeapSegments; pStubHeapSegment; pStubHeapSegment = pStubHeapSegment->pNext)
{
// The stubs are in reverse order, so we reverse them so they are in memory order
CQuickArrayList<StubUnwindInfoHeader*> list;
for (StubUnwindInfoHeader *pHeader = pStubHeapSegment->pUnwindHeaderList; pHeader; pHeader = pHeader->pNext)
list.Push(pHeader);
for(int i = (int) list.Size()-1; i >= 0; --i)
{
StubUnwindInfoHeader *pHeader = list[i];
AddToUnwindInfoTable(&pStubHeapSegment->pUnwindInfoTable, &pHeader->FunctionEntry,
(TADDR) pStubHeapSegment->pbBaseAddress, (TADDR) pStubHeapSegment->pbBaseAddress + pStubHeapSegment->cbSegment);
}
}
#endif // STUBLINKER_GENERATES_UNWIND_INFO
}
/*****************************************************************************/
// turn on the publishing of unwind info. Called when the ETW rundown provider
// is turned on.
/* static */ void UnwindInfoTable::PublishUnwindInfo(bool publishExisting)
{
CONTRACTL {
NOTHROW;
GC_TRIGGERS;
} CONTRACTL_END;
if (s_publishingActive)
return;
// If we don't have the APIs we need, give up
if (!InitUnwindFtns())
return;
EX_TRY
{
// Create the lock
Crst* newCrst = new Crst(CrstUnwindInfoTableLock);
if (InterlockedCompareExchangeT(&s_pUnwindInfoTableLock, newCrst, NULL) == NULL)
{
s_publishingActive = true;
if (publishExisting)
PublishUnwindInfoForExistingMethods();
}
else
delete newCrst; // we were in a race and failed, throw away the Crst we made.
} EX_CATCH {
STRESS_LOG1(LF_JIT, LL_ERROR, "Exception happened when doing unwind Info rundown. EIP of last AV = %p\n", g_LastAccessViolationEIP);
_ASSERTE(!"Exception thrown while publishing 'catchup' ETW unwind information");
s_publishingActive = false; // Try to minimize damage.
} EX_END_CATCH(SwallowAllExceptions);
}
#endif // defined(TARGET_AMD64) && !defined(DACCESS_COMPILE)
/*-----------------------------------------------------------------------------
This is a listing of which methods uses which synchronization mechanism
in the EEJitManager.
//-----------------------------------------------------------------------------
Setters of EEJitManager::m_CodeHeapCritSec
-----------------------------------------------
allocCode
allocGCInfo
allocEHInfo
allocJumpStubBlock
ResolveEHClause
RemoveJitData
Unload
ReleaseReferenceToHeap
JitCodeToMethodInfo
Need EEJitManager::m_CodeHeapCritSec to be set
-----------------------------------------------
NewCodeHeap
allocCodeRaw
GetCodeHeapList
RemoveCodeHeapFromDomainList
DeleteCodeHeap
AddRangeToJitHeapCache
DeleteJitHeapCache
*/
#if !defined(DACCESS_COMPILE)
EEJitManager::CodeHeapIterator::CodeHeapIterator(LoaderAllocator *pLoaderAllocatorFilter)
: m_lockHolder(&(ExecutionManager::GetEEJitManager()->m_CodeHeapCritSec)), m_Iterator(NULL, 0, NULL, 0)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
m_pHeapList = NULL;
m_pLoaderAllocator = pLoaderAllocatorFilter;
m_pHeapList = ExecutionManager::GetEEJitManager()->GetCodeHeapList();
if(m_pHeapList)
new (&m_Iterator) MethodSectionIterator((const void *)m_pHeapList->mapBase, (COUNT_T)m_pHeapList->maxCodeHeapSize, m_pHeapList->pHdrMap, (COUNT_T)HEAP2MAPSIZE(ROUND_UP_TO_PAGE(m_pHeapList->maxCodeHeapSize)));
};
EEJitManager::CodeHeapIterator::~CodeHeapIterator()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
}
BOOL EEJitManager::CodeHeapIterator::Next()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
if(!m_pHeapList)
return FALSE;
while(1)
{
if(!m_Iterator.Next())
{
m_pHeapList = m_pHeapList->GetNext();
if(!m_pHeapList)
return FALSE;
new (&m_Iterator) MethodSectionIterator((const void *)m_pHeapList->mapBase, (COUNT_T)m_pHeapList->maxCodeHeapSize, m_pHeapList->pHdrMap, (COUNT_T)HEAP2MAPSIZE(ROUND_UP_TO_PAGE(m_pHeapList->maxCodeHeapSize)));
}
else
{
BYTE * code = m_Iterator.GetMethodCode();
CodeHeader * pHdr = (CodeHeader *)(code - sizeof(CodeHeader));
m_pCurrent = !pHdr->IsStubCodeBlock() ? pHdr->GetMethodDesc() : NULL;
// LoaderAllocator filter
if (m_pLoaderAllocator && m_pCurrent)
{
LoaderAllocator *pCurrentLoaderAllocator = m_pCurrent->GetLoaderAllocator();
if(pCurrentLoaderAllocator != m_pLoaderAllocator)
continue;
}
return TRUE;
}
}
}
#endif // !DACCESS_COMPILE
#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
//
// ReaderLockHolder::ReaderLockHolder takes the reader lock, checks for the writer lock
// and either aborts if the writer lock is held, or yields until the writer lock is released,
// keeping the reader lock. This is normally called in the constructor for the
// ReaderLockHolder.
//
// The writer cannot be taken if there are any readers. The WriterLockHolder functions take the
// writer lock and check for any readers. If there are any, the WriterLockHolder functions
// release the writer and yield to wait for the readers to be done.
ExecutionManager::ReaderLockHolder::ReaderLockHolder(HostCallPreference hostCallPreference /*=AllowHostCalls*/)
{
CONTRACTL {
NOTHROW;
if (hostCallPreference == AllowHostCalls) { HOST_CALLS; } else { HOST_NOCALLS; }
GC_NOTRIGGER;
CAN_TAKE_LOCK;
} CONTRACTL_END;
IncCantAllocCount();
InterlockedIncrement(&m_dwReaderCount);
EE_LOCK_TAKEN(GetPtrForLockContract());
if (VolatileLoad(&m_dwWriterLock) != 0)
{
if (hostCallPreference != AllowHostCalls)
{
// Rats, writer lock is held. Gotta bail. Since the reader count was already
// incremented, we're technically still blocking writers at the moment. But
// the holder who called us is about to call DecrementReader in its
// destructor and unblock writers.
return;
}
YIELD_WHILE ((VolatileLoad(&m_dwWriterLock) != 0));
}
}
//---------------------------------------------------------------------------------------
//
// See code:ExecutionManager::ReaderLockHolder::ReaderLockHolder. This just decrements the reader count.
ExecutionManager::ReaderLockHolder::~ReaderLockHolder()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
InterlockedDecrement(&m_dwReaderCount);
DecCantAllocCount();
EE_LOCK_RELEASED(GetPtrForLockContract());
}
//---------------------------------------------------------------------------------------
//
// Returns whether the reader lock is acquired
BOOL ExecutionManager::ReaderLockHolder::Acquired()
{
LIMITED_METHOD_CONTRACT;
return VolatileLoad(&m_dwWriterLock) == 0;
}
ExecutionManager::WriterLockHolder::WriterLockHolder()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
CAN_TAKE_LOCK;
} CONTRACTL_END;
_ASSERTE(m_dwWriterLock == 0);
// Signal to a debugger that this thread cannot stop now
IncCantStopCount();
IncCantAllocCount();
DWORD dwSwitchCount = 0;
while (TRUE)
{
// While this thread holds the writer lock, we must not try to suspend it
// or allow a profiler to walk its stack
Thread::IncForbidSuspendThread();
InterlockedIncrement(&m_dwWriterLock);
if (m_dwReaderCount == 0)
break;
InterlockedDecrement(&m_dwWriterLock);
// Before we loop and retry, it's safe to suspend or hijack and inspect
// this thread
Thread::DecForbidSuspendThread();
__SwitchToThread(0, ++dwSwitchCount);
}
EE_LOCK_TAKEN(GetPtrForLockContract());
}
ExecutionManager::WriterLockHolder::~WriterLockHolder()
{
LIMITED_METHOD_CONTRACT;
InterlockedDecrement(&m_dwWriterLock);
// Writer lock released, so it's safe again for this thread to be
// suspended or have its stack walked by a profiler
Thread::DecForbidSuspendThread();
DecCantAllocCount();
// Signal to a debugger that it's again safe to stop this thread
DecCantStopCount();
EE_LOCK_RELEASED(GetPtrForLockContract());
}
#else
// For DAC builds, we only care whether the writer lock is held.
// If it is, we will assume the locked data is in an inconsistent
// state and throw. We never actually take the lock.
// Note: Throws
ExecutionManager::ReaderLockHolder::ReaderLockHolder(HostCallPreference hostCallPreference /*=AllowHostCalls*/)
{
SUPPORTS_DAC;
if (m_dwWriterLock != 0)
{
ThrowHR(CORDBG_E_PROCESS_NOT_SYNCHRONIZED);
}
}
ExecutionManager::ReaderLockHolder::~ReaderLockHolder()
{
}
#endif // DACCESS_COMPILE
/*-----------------------------------------------------------------------------
This is a listing of which methods uses which synchronization mechanism
in the ExecutionManager
//-----------------------------------------------------------------------------
==============================================================================
ExecutionManger::ReaderLockHolder and ExecutionManger::WriterLockHolder
Protects the callers of ExecutionManager::GetRangeSection from heap deletions
while walking RangeSections. You need to take a reader lock before reading the
values: m_CodeRangeList and hold it while walking the lists
Uses ReaderLockHolder (allows multiple reeaders with no writers)
-----------------------------------------
ExecutionManager::FindCodeRange
ExecutionManager::FindZapModule
ExecutionManager::EnumMemoryRegions
Uses WriterLockHolder (allows single writer and no readers)
-----------------------------------------
ExecutionManager::AddRangeHelper
ExecutionManager::DeleteRangeHelper
*/
//-----------------------------------------------------------------------------
#if defined(TARGET_ARM) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64)
#define EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS
#endif
#if defined(EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS)
// The function fragments can be used in Hot/Cold splitting, expressing Large Functions or in 'ShrinkWrapping', which is
// delaying saving and restoring some callee-saved registers later inside the body of the method.
// (It's assumed that JIT will not emit any ShrinkWrapping-style methods)
// For these cases multiple RUNTIME_FUNCTION entries (a.k.a function fragments) are used to define
// all the regions of the function or funclet. And one of these function fragments cover the beginning of the function/funclet,
// including the prolog section and is referred as the 'Host Record'.
// This function returns TRUE if the inspected RUNTIME_FUNCTION entry is NOT a host record
BOOL IsFunctionFragment(TADDR baseAddress, PTR_RUNTIME_FUNCTION pFunctionEntry)
{
LIMITED_METHOD_DAC_CONTRACT;
_ASSERTE((pFunctionEntry->UnwindData & 3) == 0); // The unwind data must be an RVA; we don't support packed unwind format
DWORD unwindHeader = *(PTR_DWORD)(baseAddress + pFunctionEntry->UnwindData);
_ASSERTE((0 == ((unwindHeader >> 18) & 3)) || !"unknown unwind data format, version != 0");
#if defined(TARGET_ARM)
// On ARM, It's assumed that the prolog is always at the beginning of the function and cannot be split.
// Given that, there are 4 possible ways to fragment a function:
// 1. Prolog only:
// 2. Prolog and some epilogs:
// 3. Epilogs only:
// 4. No Prolog or epilog
//
// Function fragments describing 1 & 2 are host records, 3 & 4 are not.
// for 3 & 4, the .xdata record's F bit is set to 1, marking clearly what is NOT a host record
_ASSERTE((pFunctionEntry->BeginAddress & THUMB_CODE) == THUMB_CODE); // Sanity check: it's a thumb address
DWORD Fbit = (unwindHeader >> 22) & 0x1; // F "fragment" bit
return (Fbit == 1);
#elif defined(TARGET_ARM64)
// ARM64 is a little bit more flexible, in the sense that it supports partial prologs. However only one of the
// prolog regions are allowed to alter SP and that's the Host Record. Partial prologs are used in ShrinkWrapping
// scenarios which is not supported, hence we don't need to worry about them. discarding partial prologs
// simplifies identifying a host record a lot.
//
// 1. Prolog only: The host record. Epilog Count and E bit are all 0.
// 2. Prolog and some epilogs: The host record with accompanying epilog-only records
// 3. Epilogs only: First unwind code is Phantom prolog (Starting with an end_c, indicating an empty prolog)
// 4. No prologs or epilogs: First unwind code is Phantom prolog (Starting with an end_c, indicating an empty prolog)
//
int EpilogCount = (int)(unwindHeader >> 22) & 0x1F;
int CodeWords = unwindHeader >> 27;
PTR_DWORD pUnwindCodes = (PTR_DWORD)(baseAddress + pFunctionEntry->UnwindData);
// Skip header.
pUnwindCodes++;
// Skip extended header.
if ((CodeWords == 0) && (EpilogCount == 0))
{
EpilogCount = (*pUnwindCodes) & 0xFFFF;
pUnwindCodes++;
}
// Skip epilog scopes.
BOOL Ebit = (unwindHeader >> 21) & 0x1;
if (!Ebit && (EpilogCount != 0))
{
// EpilogCount is the number of exception scopes defined right after the unwindHeader
pUnwindCodes += EpilogCount;
}
return ((*pUnwindCodes & 0xFF) == 0xE5);
#elif defined(TARGET_LOONGARCH64)
// LOONGARCH64 is a little bit more flexible, in the sense that it supports partial prologs. However only one of the
// prolog regions are allowed to alter SP and that's the Host Record. Partial prologs are used in ShrinkWrapping
// scenarios which is not supported, hence we don't need to worry about them. discarding partial prologs
// simplifies identifying a host record a lot.
//
// 1. Prolog only: The host record. Epilog Count and E bit are all 0.
// 2. Prolog and some epilogs: The host record with accompanying epilog-only records
// 3. Epilogs only: First unwind code is Phantom prolog (Starting with an end_c, indicating an empty prolog)
// 4. No prologs or epilogs: First unwind code is Phantom prolog (Starting with an end_c, indicating an empty prolog)
//
int EpilogCount = (int)(unwindHeader >> 22) & 0x1F;
int CodeWords = unwindHeader >> 27;
PTR_DWORD pUnwindCodes = (PTR_DWORD)(baseAddress + pFunctionEntry->UnwindData);
// Skip header.
pUnwindCodes++;
// Skip extended header.
if ((CodeWords == 0) && (EpilogCount == 0))
{
EpilogCount = (*pUnwindCodes) & 0xFFFF;
pUnwindCodes++;
}
// Skip epilog scopes.
BOOL Ebit = (unwindHeader >> 21) & 0x1;
if (!Ebit && (EpilogCount != 0))
{
// EpilogCount is the number of exception scopes defined right after the unwindHeader
pUnwindCodes += EpilogCount;
}
return ((*pUnwindCodes & 0xFF) == 0xE5);
#else
PORTABILITY_ASSERT("IsFunctionFragnent - NYI on this platform");
#endif
}
// When we have fragmented unwind we usually want to refer to the
// unwind record that includes the prolog. We can find it by searching
// back in the sequence of unwind records.
PTR_RUNTIME_FUNCTION FindRootEntry(PTR_RUNTIME_FUNCTION pFunctionEntry, TADDR baseAddress)
{
LIMITED_METHOD_DAC_CONTRACT;
PTR_RUNTIME_FUNCTION pRootEntry = pFunctionEntry;
if (pRootEntry != NULL)
{
// Walk backwards in the RUNTIME_FUNCTION array until we find a non-fragment.
// We're guaranteed to find one, because we require that a fragment live in a function or funclet
// that has a prolog, which will have non-fragment .xdata.
while (true)
{
if (!IsFunctionFragment(baseAddress, pRootEntry))
{
// This is not a fragment; we're done
break;
}
--pRootEntry;
}
}
return pRootEntry;
}
#endif // EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS
#ifndef DACCESS_COMPILE
//**********************************************************************************
// IJitManager
//**********************************************************************************
IJitManager::IJitManager()
{
LIMITED_METHOD_CONTRACT;
m_runtimeSupport = ExecutionManager::GetDefaultCodeManager();
}
#endif // #ifndef DACCESS_COMPILE
// When we unload an appdomain, we need to make sure that any threads that are crawling through
// our heap or rangelist are out. For cooperative-mode threads, we know that they will have
// been stopped when we suspend the EE so they won't be touching an element that is about to be deleted.
// However for pre-emptive mode threads, they could be stalled right on top of the element we want
// to delete, so we need to apply the reader lock to them and wait for them to drain.
ExecutionManager::ScanFlag ExecutionManager::GetScanFlags()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
HOST_NOCALLS;
SUPPORTS_DAC;
} CONTRACTL_END;
#if !defined(DACCESS_COMPILE)
Thread *pThread = GetThreadNULLOk();
if (!pThread)
return ScanNoReaderLock;
// If this thread is hijacked by a profiler and crawling its own stack,
// we do need to take the lock
if (pThread->GetProfilerFilterContext() != NULL)
return ScanReaderLock;
if (pThread->PreemptiveGCDisabled() || (pThread == ThreadSuspend::GetSuspensionThread()))
return ScanNoReaderLock;
return ScanReaderLock;
#else
return ScanNoReaderLock;
#endif
}
#ifdef DACCESS_COMPILE
void IJitManager::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
DAC_ENUM_VTHIS();
if (m_runtimeSupport.IsValid())
{
m_runtimeSupport->EnumMemoryRegions(flags);
}
}
#endif // #ifdef DACCESS_COMPILE
#if defined(FEATURE_EH_FUNCLETS)
PTR_VOID GetUnwindDataBlob(TADDR moduleBase, PTR_RUNTIME_FUNCTION pRuntimeFunction, /* out */ SIZE_T * pSize)
{
LIMITED_METHOD_CONTRACT;
#if defined(TARGET_AMD64)
PTR_UNWIND_INFO pUnwindInfo(dac_cast<PTR_UNWIND_INFO>(moduleBase + RUNTIME_FUNCTION__GetUnwindInfoAddress(pRuntimeFunction)));
*pSize = ALIGN_UP(offsetof(UNWIND_INFO, UnwindCode) +
sizeof(UNWIND_CODE) * pUnwindInfo->CountOfUnwindCodes +
sizeof(ULONG) /* personality routine is always present */,
sizeof(DWORD));
return pUnwindInfo;
#elif defined(TARGET_X86)
PTR_UNWIND_INFO pUnwindInfo(dac_cast<PTR_UNWIND_INFO>(moduleBase + RUNTIME_FUNCTION__GetUnwindInfoAddress(pRuntimeFunction)));
*pSize = sizeof(UNWIND_INFO);
return pUnwindInfo;
#elif defined(TARGET_ARM) || defined(TARGET_ARM64)
// if this function uses packed unwind data then at least one of the two least significant bits
// will be non-zero. if this is the case then there will be no xdata record to enumerate.
_ASSERTE((pRuntimeFunction->UnwindData & 0x3) == 0);
// compute the size of the unwind info
PTR_DWORD xdata = dac_cast<PTR_DWORD>(pRuntimeFunction->UnwindData + moduleBase);
int size = 4;
#if defined(TARGET_ARM)
// See https://docs.microsoft.com/en-us/cpp/build/arm-exception-handling
int unwindWords = xdata[0] >> 28;
int epilogScopes = (xdata[0] >> 23) & 0x1f;
#else
// See https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
int unwindWords = xdata[0] >> 27;
int epilogScopes = (xdata[0] >> 22) & 0x1f;
#endif
if (unwindWords == 0 && epilogScopes == 0)
{
size += 4;
unwindWords = (xdata[1] >> 16) & 0xff;
epilogScopes = xdata[1] & 0xffff;
}
if (!(xdata[0] & (1 << 21)))
size += 4 * epilogScopes;
size += 4 * unwindWords;
_ASSERTE(xdata[0] & (1 << 20)); // personality routine should be always present
size += 4;
*pSize = size;
return xdata;
#elif defined(TARGET_LOONGARCH64)
// TODO: maybe optimize further.
// if this function uses packed unwind data then at least one of the two least significant bits
// will be non-zero. if this is the case then there will be no xdata record to enumerate.
_ASSERTE((pRuntimeFunction->UnwindData & 0x3) == 0);
// compute the size of the unwind info
PTR_ULONG xdata = dac_cast<PTR_ULONG>(pRuntimeFunction->UnwindData + moduleBase);
ULONG epilogScopes = 0;
ULONG unwindWords = 0;
ULONG size = 0;
//If both Epilog Count and Code Word is not zero
//Info of Epilog and Unwind scopes are given by 1 word header
//Otherwise this info is given by a 2 word header
if ((xdata[0] >> 27) != 0)
{
size = 4;
epilogScopes = (xdata[0] >> 22) & 0x1f;
unwindWords = (xdata[0] >> 27) & 0x1f;
}
else
{
size = 8;
epilogScopes = xdata[1] & 0xffff;
unwindWords = (xdata[1] >> 16) & 0xff;
}
if (!(xdata[0] & (1 << 21)))
size += 4 * epilogScopes;
size += 4 * unwindWords;
_ASSERTE(xdata[0] & (1 << 20)); // personality routine should be always present
size += 4; // exception handler RVA
*pSize = size;
return xdata;
#else
PORTABILITY_ASSERT("GetUnwindDataBlob");
return NULL;
#endif
}
// GetFuncletStartAddress returns the starting address of the function or funclet indicated by the EECodeInfo address.
TADDR IJitManager::GetFuncletStartAddress(EECodeInfo * pCodeInfo)
{
PTR_RUNTIME_FUNCTION pFunctionEntry = pCodeInfo->GetFunctionEntry();
#ifdef TARGET_AMD64
_ASSERTE((pFunctionEntry->UnwindData & RUNTIME_FUNCTION_INDIRECT) == 0);
#endif
TADDR baseAddress = pCodeInfo->GetModuleBase();
#if defined(EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS)
pFunctionEntry = FindRootEntry(pFunctionEntry, baseAddress);
#endif // EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS
TADDR funcletStartAddress = baseAddress + RUNTIME_FUNCTION__BeginAddress(pFunctionEntry);
return funcletStartAddress;
}
BOOL IJitManager::IsFunclet(EECodeInfo * pCodeInfo)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
TADDR funcletStartAddress = GetFuncletStartAddress(pCodeInfo);
TADDR methodStartAddress = pCodeInfo->GetStartAddress();
return (funcletStartAddress != methodStartAddress);
}
BOOL IJitManager::IsFilterFunclet(EECodeInfo * pCodeInfo)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
if (!pCodeInfo->IsFunclet())
return FALSE;
TADDR funcletStartAddress = GetFuncletStartAddress(pCodeInfo);
// This assumes no hot/cold splitting for funclets
_ASSERTE(FitsInU4(pCodeInfo->GetCodeAddress() - funcletStartAddress));
DWORD relOffsetWithinFunclet = static_cast<DWORD>(pCodeInfo->GetCodeAddress() - funcletStartAddress);
_ASSERTE(pCodeInfo->GetRelOffset() >= relOffsetWithinFunclet);
DWORD funcletStartOffset = pCodeInfo->GetRelOffset() - relOffsetWithinFunclet;
EH_CLAUSE_ENUMERATOR pEnumState;
unsigned EHCount = InitializeEHEnumeration(pCodeInfo->GetMethodToken(), &pEnumState);
_ASSERTE(EHCount > 0);
EE_ILEXCEPTION_CLAUSE EHClause;
for (ULONG i = 0; i < EHCount; i++)
{
GetNextEHClause(&pEnumState, &EHClause);
// Duplicate clauses are always listed at the end, so when we hit a duplicate clause,
// we have already visited all of the normal clauses.
if (IsDuplicateClause(&EHClause))
{
break;
}
if (IsFilterHandler(&EHClause))
{
if (EHClause.FilterOffset == funcletStartOffset)
{
return true;
}
}
}
return false;
}
#else // FEATURE_EH_FUNCLETS
PTR_VOID GetUnwindDataBlob(TADDR moduleBase, PTR_RUNTIME_FUNCTION pRuntimeFunction, /* out */ SIZE_T * pSize)
{
*pSize = 0;
return dac_cast<PTR_VOID>(pRuntimeFunction->UnwindData + moduleBase);
}
#endif // FEATURE_EH_FUNCLETS
#ifndef DACCESS_COMPILE
//**********************************************************************************
// EEJitManager
//**********************************************************************************
EEJitManager::EEJitManager()
:
// CRST_DEBUGGER_THREAD - We take this lock on debugger thread during EnC add method, among other things
// CRST_TAKEN_DURING_SHUTDOWN - We take this lock during shutdown if ETW is on (to do rundown)
m_CodeHeapCritSec( CrstSingleUseLock,
CrstFlags(CRST_UNSAFE_ANYMODE|CRST_DEBUGGER_THREAD|CRST_TAKEN_DURING_SHUTDOWN)),
m_CPUCompileFlags(),
m_JitLoadCritSec( CrstSingleUseLock )
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
m_pCodeHeap = NULL;
m_jit = NULL;
m_JITCompiler = NULL;
#ifdef TARGET_AMD64
m_pEmergencyJumpStubReserveList = NULL;
#endif
#if defined(TARGET_X86) || defined(TARGET_AMD64)
m_JITCompilerOther = NULL;
#endif
#ifdef ALLOW_SXS_JIT
m_alternateJit = NULL;
m_AltJITCompiler = NULL;
m_AltJITRequired = false;
#endif
m_storeRichDebugInfo = false;
m_cleanupList = NULL;
}
#if defined(TARGET_X86) || defined(TARGET_AMD64)
bool DoesOSSupportAVX()
{
LIMITED_METHOD_CONTRACT;
#ifndef TARGET_UNIX
// On Windows we have an api(GetEnabledXStateFeatures) to check if AVX is supported
typedef DWORD64 (WINAPI *PGETENABLEDXSTATEFEATURES)();
PGETENABLEDXSTATEFEATURES pfnGetEnabledXStateFeatures = NULL;
HMODULE hMod = WszLoadLibraryEx(WINDOWS_KERNEL32_DLLNAME_W, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
if(hMod == NULL)
return FALSE;
pfnGetEnabledXStateFeatures = (PGETENABLEDXSTATEFEATURES)GetProcAddress(hMod, "GetEnabledXStateFeatures");
if (pfnGetEnabledXStateFeatures == NULL)
{
return FALSE;
}
DWORD64 FeatureMask = pfnGetEnabledXStateFeatures();
if ((FeatureMask & XSTATE_MASK_AVX) == 0)
{
return FALSE;
}
#endif // !TARGET_UNIX
return TRUE;
}
bool DoesOSSupportAVX512()
{
LIMITED_METHOD_CONTRACT;
#ifndef TARGET_UNIX
// On Windows we have an api(GetEnabledXStateFeatures) to check if AVX512 is supported
typedef DWORD64 (WINAPI *PGETENABLEDXSTATEFEATURES)();
PGETENABLEDXSTATEFEATURES pfnGetEnabledXStateFeatures = NULL;
HMODULE hMod = WszLoadLibraryEx(WINDOWS_KERNEL32_DLLNAME_W, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
if(hMod == NULL)
return FALSE;
pfnGetEnabledXStateFeatures = (PGETENABLEDXSTATEFEATURES)GetProcAddress(hMod, "GetEnabledXStateFeatures");
if (pfnGetEnabledXStateFeatures == NULL)
{
return FALSE;
}
DWORD64 FeatureMask = pfnGetEnabledXStateFeatures();
if ((FeatureMask & XSTATE_MASK_AVX512) == 0)
{
return FALSE;
}
#endif // !TARGET_UNIX
return TRUE;
}
#endif // defined(TARGET_X86) || defined(TARGET_AMD64)
#ifdef TARGET_ARM64
extern "C" DWORD64 __stdcall GetDataCacheZeroIDReg();
#endif
void EEJitManager::SetCpuInfo()
{
LIMITED_METHOD_CONTRACT;
//
// NOTE: This function needs to be kept in sync with compSetProcessor() in jit\compiler.cpp
//
CORJIT_FLAGS CPUCompileFlags;
#if defined(TARGET_X86)
CORINFO_CPU cpuInfo;
GetSpecificCpuInfo(&cpuInfo);
switch (CPU_X86_FAMILY(cpuInfo.dwCPUType))
{
case CPU_X86_PENTIUM_4:
CPUCompileFlags.Set(CORJIT_FLAGS::CORJIT_FLAG_TARGET_P4);
break;
default:
break;
}
if (CPU_X86_USE_CMOV(cpuInfo.dwFeatures))
{
CPUCompileFlags.Set(CORJIT_FLAGS::CORJIT_FLAG_USE_CMOV);
CPUCompileFlags.Set(CORJIT_FLAGS::CORJIT_FLAG_USE_FCOMI);
}
#endif // TARGET_X86
#if defined(TARGET_X86) || defined(TARGET_AMD64)
CPUCompileFlags.Set(InstructionSet_X86Base);
// NOTE: The below checks are based on the information reported by
// Intel® 64 and IA-32 Architectures Software Developer’s Manual. Volume 2
// and
// AMD64 Architecture Programmer’s Manual. Volume 3
// For more information, please refer to the CPUID instruction in the respective manuals
// We will set the following flags:
// CORJIT_FLAG_USE_SSE2 is required
// SSE - EDX bit 25
// SSE2 - EDX bit 26
// CORJIT_FLAG_USE_AES
// CORJIT_FLAG_USE_SSE2
// AES - ECX bit 25
// CORJIT_FLAG_USE_PCLMULQDQ
// CORJIT_FLAG_USE_SSE2
// PCLMULQDQ - ECX bit 1
// CORJIT_FLAG_USE_SSE3 if the following feature bits are set (input EAX of 1)
// CORJIT_FLAG_USE_SSE2
// SSE3 - ECX bit 0
// CORJIT_FLAG_USE_SSSE3 if the following feature bits are set (input EAX of 1)
// CORJIT_FLAG_USE_SSE3
// SSSE3 - ECX bit 9
// CORJIT_FLAG_USE_SSE41 if the following feature bits are set (input EAX of 1)
// CORJIT_FLAG_USE_SSSE3
// SSE4.1 - ECX bit 19
// CORJIT_FLAG_USE_SSE42 if the following feature bits are set (input EAX of 1)
// CORJIT_FLAG_USE_SSE41
// SSE4.2 - ECX bit 20
// CORJIT_FLAG_USE_MOVBE if the following feature bits are set (input EAX of 1)
// CORJIT_FLAG_USE_SSE42
// MOVBE - ECX bit 22
// CORJIT_FLAG_USE_POPCNT if the following feature bits are set (input EAX of 1)
// CORJIT_FLAG_USE_SSE42
// POPCNT - ECX bit 23
// CORJIT_FLAG_USE_AVX if the following feature bits are set (input EAX of 1), and xmmYmmStateSupport returns 1:
// CORJIT_FLAG_USE_SSE42
// OSXSAVE - ECX bit 27
// AVX - ECX bit 28
// XGETBV - XCR0[2:1] 11b
// CORJIT_FLAG_USE_FMA if the following feature bits are set (input EAX of 1), and xmmYmmStateSupport returns 1:
// CORJIT_FLAG_USE_AVX
// FMA - ECX bit 12
// CORJIT_FLAG_USE_AVX2 if the following feature bit is set (input EAX of 0x07 and input ECX of 0):
// CORJIT_FLAG_USE_AVX
// AVX2 - EBX bit 5
// CORJIT_FLAG_USE_AVXVNNI if the following feature bit is set (input EAX of 0x07 and input ECX of 1):
// CORJIT_FLAG_USE_AVX2
// AVXVNNI - EAX bit 4
// CORJIT_FLAG_USE_AVX_512F if the following feature bit is set (input EAX of 0x07 and input ECX of 0), and avx512StateSupport returns 1:
// CORJIT_FLAG_USE_AVX2
// AVX512F - EBX bit 16
// XGETBV - XRC0[7:5] 111b
// CORJIT_FLAG_USE_AVX_512F_VL if the following feature bit is set (input EAX of 0x07 and input ECX of 0):
// CORJIT_FLAG_USE_AVX512F
// AVX512VL - EBX bit 31
// CORJIT_FLAG_USE_AVX_512BW if the following feature bit is set (input EAX of 0x07 and input ECX of 0):
// CORJIT_FLAG_USE_AVX512F
// AVX512BW - EBX bit 30
// CORJIT_FLAG_USE_AVX_512BW_VL if the following feature bit is set (input EAX of 0x07 and input ECX of 0):
// CORJIT_FLAG_USE_AVX512F_VL
// CORJIT_FLAG_USE_AVX_512BW
// CORJIT_FLAG_USE_AVX_512CD if the following feature bit is set (input EAX of 0x07 and input ECX of 0):
// CORJIT_FLAG_USE_AVX512F
// AVX512CD - EBX bit 28
// CORJIT_FLAG_USE_AVX_512CD_VL if the following feature bit is set (input EAX of 0x07 and input ECX of 0):
// CORJIT_FLAG_USE_AVX512F_VL
// CORJIT_FLAG_USE_AVX_512CD
// CORJIT_FLAG_USE_AVX_512DQ if the following feature bit is set (input EAX of 0x07 and input ECX of 0):
// CORJIT_FLAG_USE_AVX512F
// AVX512DQ - EBX bit 7
// CORJIT_FLAG_USE_AVX_512DQ_VL if the following feature bit is set (input EAX of 0x07 and input ECX of 0):
// CORJIT_FLAG_USE_AVX512F_VL
// CORJIT_FLAG_USE_AVX_512DQ
// CORJIT_FLAG_USE_BMI1 if the following feature bit is set (input EAX of 0x07 and input ECX of 0):
// BMI1 - EBX bit 3
// CORJIT_FLAG_USE_BMI2 if the following feature bit is set (input EAX of 0x07 and input ECX of 0):
// BMI2 - EBX bit 8
// CORJIT_FLAG_USE_LZCNT if the following feature bits are set (input EAX of 80000001H)
// LZCNT - ECX bit 5
// synchronously updating VM and JIT.
int cpuidInfo[4];
const int EAX = CPUID_EAX;
const int EBX = CPUID_EBX;
const int ECX = CPUID_ECX;
const int EDX = CPUID_EDX;
__cpuid(cpuidInfo, 0x00000000);
uint32_t maxCpuId = static_cast<uint32_t>(cpuidInfo[EAX]);
if (maxCpuId >= 1)
{
__cpuid(cpuidInfo, 0x00000001);
if (((cpuidInfo[EDX] & (1 << 25)) != 0) && ((cpuidInfo[EDX] & (1 << 26)) != 0)) // SSE & SSE2
{
CPUCompileFlags.Set(InstructionSet_SSE);
CPUCompileFlags.Set(InstructionSet_SSE2);
if ((cpuidInfo[ECX] & (1 << 25)) != 0) // AESNI
{
CPUCompileFlags.Set(InstructionSet_AES);
}
if ((cpuidInfo[ECX] & (1 << 1)) != 0) // PCLMULQDQ
{
CPUCompileFlags.Set(InstructionSet_PCLMULQDQ);
}
if ((cpuidInfo[ECX] & (1 << 0)) != 0) // SSE3
{
CPUCompileFlags.Set(InstructionSet_SSE3);
if ((cpuidInfo[ECX] & (1 << 9)) != 0) // SSSE3
{
CPUCompileFlags.Set(InstructionSet_SSSE3);
if ((cpuidInfo[ECX] & (1 << 19)) != 0) // SSE4.1
{
CPUCompileFlags.Set(InstructionSet_SSE41);
if ((cpuidInfo[ECX] & (1 << 20)) != 0) // SSE4.2
{
CPUCompileFlags.Set(InstructionSet_SSE42);
if ((cpuidInfo[ECX] & (1 << 22)) != 0) // MOVBE
{
CPUCompileFlags.Set(InstructionSet_MOVBE);
}
if ((cpuidInfo[ECX] & (1 << 23)) != 0) // POPCNT
{
CPUCompileFlags.Set(InstructionSet_POPCNT);
}
if (((cpuidInfo[ECX] & (1 << 27)) != 0) && ((cpuidInfo[ECX] & (1 << 28)) != 0)) // OSXSAVE & AVX
{
if(DoesOSSupportAVX() && (xmmYmmStateSupport() == 1)) // XGETBV == 11
{
CPUCompileFlags.Set(InstructionSet_AVX);
if ((cpuidInfo[ECX] & (1 << 12)) != 0) // FMA
{
CPUCompileFlags.Set(InstructionSet_FMA);
}
if (maxCpuId >= 0x07)
{
__cpuidex(cpuidInfo, 0x00000007, 0x00000000);
if ((cpuidInfo[EBX] & (1 << 5)) != 0) // AVX2
{
CPUCompileFlags.Set(InstructionSet_AVX2);
if (DoesOSSupportAVX512() && (avx512StateSupport() == 1)) // XGETBV XRC0[7:5] == 111
{
if ((cpuidInfo[EBX] & (1 << 16)) != 0) // AVX512F
{
CPUCompileFlags.Set(InstructionSet_AVX512F);
bool isAVX512_VLSupported = false;
if ((cpuidInfo[EBX] & (1 << 31)) != 0) // AVX512VL
{
CPUCompileFlags.Set(InstructionSet_AVX512F_VL);
isAVX512_VLSupported = true;
}
if ((cpuidInfo[EBX] & (1 << 30)) != 0) // AVX512BW
{
CPUCompileFlags.Set(InstructionSet_AVX512BW);
if (isAVX512_VLSupported) // AVX512BW_VL
{
CPUCompileFlags.Set(InstructionSet_AVX512BW_VL);
}
}
if ((cpuidInfo[EBX] & (1 << 28)) != 0) // AVX512CD
{
CPUCompileFlags.Set(InstructionSet_AVX512CD);
if (isAVX512_VLSupported) // AVX512CD_VL
{
CPUCompileFlags.Set(InstructionSet_AVX512CD_VL);
}
}
if ((cpuidInfo[EBX] & (1 << 17)) != 0) // AVX512DQ
{
CPUCompileFlags.Set(InstructionSet_AVX512DQ);
if (isAVX512_VLSupported) // AVX512DQ_VL
{
CPUCompileFlags.Set(InstructionSet_AVX512DQ_VL);
}
}
}
}
__cpuidex(cpuidInfo, 0x00000007, 0x00000001);
if ((cpuidInfo[EAX] & (1 << 4)) != 0) // AVX-VNNI
{
CPUCompileFlags.Set(InstructionSet_AVXVNNI);
}
}
}
}
}
}
}
}
}
if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_SIMD16ByteOnly) != 0)
{
CPUCompileFlags.Clear(InstructionSet_AVX2);
}
}
if (maxCpuId >= 0x07)
{
__cpuidex(cpuidInfo, 0x00000007, 0x00000000);
if ((cpuidInfo[EBX] & (1 << 3)) != 0) // BMI1
{
CPUCompileFlags.Set(InstructionSet_BMI1);
}
if ((cpuidInfo[EBX] & (1 << 8)) != 0) // BMI2
{
CPUCompileFlags.Set(InstructionSet_BMI2);
}
if ((cpuidInfo[EDX] & (1 << 14)) != 0)
{
CPUCompileFlags.Set(InstructionSet_X86Serialize); // SERIALIZE
}
}
}
__cpuid(cpuidInfo, 0x80000000);
uint32_t maxCpuIdEx = static_cast<uint32_t>(cpuidInfo[EAX]);
if (maxCpuIdEx >= 0x80000001)
{
__cpuid(cpuidInfo, 0x80000001);
if ((cpuidInfo[ECX] & (1 << 5)) != 0) // LZCNT
{
CPUCompileFlags.Set(InstructionSet_LZCNT);
}
}
if (!CPUCompileFlags.IsSet(InstructionSet_SSE))
{
EEPOLICY_HANDLE_FATAL_ERROR_WITH_MESSAGE(COR_E_EXECUTIONENGINE, W("SSE is not supported on the processor."));
}
if (!CPUCompileFlags.IsSet(InstructionSet_SSE2))
{
EEPOLICY_HANDLE_FATAL_ERROR_WITH_MESSAGE(COR_E_EXECUTIONENGINE, W("SSE2 is not supported on the processor."));
}
#endif // defined(TARGET_X86) || defined(TARGET_AMD64)
#if defined(TARGET_ARM64)
#if defined(TARGET_UNIX)
PAL_GetJitCpuCapabilityFlags(&CPUCompileFlags);
// For HOST_ARM64, if OS has exposed mechanism to detect CPU capabilities, make sure it has AdvSimd capability.
// For other cases i.e. if !HOST_ARM64 but TARGET_ARM64 or HOST_ARM64 but OS doesn't expose way to detect
// CPU capabilities, we always enable AdvSimd flags by default.
//
if (!CPUCompileFlags.IsSet(InstructionSet_AdvSimd))
{
EEPOLICY_HANDLE_FATAL_ERROR_WITH_MESSAGE(COR_E_EXECUTIONENGINE, W("AdvSimd is not supported on the processor."));
}
#elif defined(HOST_64BIT)
// FP and SIMD support are enabled by default
CPUCompileFlags.Set(InstructionSet_ArmBase);
CPUCompileFlags.Set(InstructionSet_AdvSimd);
// PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE (30)
if (IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE))
{
CPUCompileFlags.Set(InstructionSet_Aes);
CPUCompileFlags.Set(InstructionSet_Sha1);
CPUCompileFlags.Set(InstructionSet_Sha256);
}
// PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE (31)
if (IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE))
{
CPUCompileFlags.Set(InstructionSet_Crc32);
}
// Older version of SDK would return false for these intrinsics
// but make sure we pass the right values to the APIs
#ifndef PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE
#define PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE 34
#endif
#ifndef PF_ARM_V82_DP_INSTRUCTIONS_AVAILABLE
# define PF_ARM_V82_DP_INSTRUCTIONS_AVAILABLE 43
#endif
// PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE (34)
if (IsProcessorFeaturePresent(PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE))
{
CPUCompileFlags.Set(InstructionSet_Atomics);
}
// PF_ARM_V82_DP_INSTRUCTIONS_AVAILABLE (43)
if (IsProcessorFeaturePresent(PF_ARM_V82_DP_INSTRUCTIONS_AVAILABLE))
{
CPUCompileFlags.Set(InstructionSet_Dp);
}
#endif // HOST_64BIT
if (GetDataCacheZeroIDReg() == 4)
{
// DCZID_EL0<4> (DZP) indicates whether use of DC ZVA instructions is permitted (0) or prohibited (1).
// DCZID_EL0<3:0> (BS) specifies Log2 of the block size in words.
//
// We set the flag when the instruction is permitted and the block size is 64 bytes.
CPUCompileFlags.Set(InstructionSet_Dczva);
}
if (CPUCompileFlags.IsSet(InstructionSet_Atomics))
{
g_arm64_atomics_present = true;
}
#endif // TARGET_ARM64
// Now that we've queried the actual hardware support, we need to adjust what is actually supported based
// on some externally available config switches that exist so users can test code for downlevel hardware.
#if defined(TARGET_AMD64) || defined(TARGET_X86)
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableHWIntrinsic))
{
CPUCompileFlags.Clear(InstructionSet_X86Base);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAES))
{
CPUCompileFlags.Clear(InstructionSet_AES);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVX))
{
CPUCompileFlags.Clear(InstructionSet_AVX);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVX2))
{
CPUCompileFlags.Clear(InstructionSet_AVX2);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVX512F))
{
CPUCompileFlags.Clear(InstructionSet_AVX512F);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVX512F_VL))
{
CPUCompileFlags.Clear(InstructionSet_AVX512F_VL);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVX512BW))
{
CPUCompileFlags.Clear(InstructionSet_AVX512BW);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVX512BW_VL))
{
CPUCompileFlags.Clear(InstructionSet_AVX512BW_VL);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVX512CD))
{
CPUCompileFlags.Clear(InstructionSet_AVX512CD);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVX512CD_VL))
{
CPUCompileFlags.Clear(InstructionSet_AVX512CD_VL);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVX512DQ))
{
CPUCompileFlags.Clear(InstructionSet_AVX512DQ);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVX512DQ_VL))
{
CPUCompileFlags.Clear(InstructionSet_AVX512DQ_VL);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVXVNNI))
{
CPUCompileFlags.Clear(InstructionSet_AVXVNNI);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableBMI1))
{
CPUCompileFlags.Clear(InstructionSet_BMI1);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableBMI2))
{
CPUCompileFlags.Clear(InstructionSet_BMI2);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableFMA))
{
CPUCompileFlags.Clear(InstructionSet_FMA);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableLZCNT))
{
CPUCompileFlags.Clear(InstructionSet_LZCNT);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnablePCLMULQDQ))
{
CPUCompileFlags.Clear(InstructionSet_PCLMULQDQ);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableMOVBE))
{
CPUCompileFlags.Clear(InstructionSet_MOVBE);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnablePOPCNT))
{
CPUCompileFlags.Clear(InstructionSet_POPCNT);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSE))
{
CPUCompileFlags.Clear(InstructionSet_SSE);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSE2))
{
CPUCompileFlags.Clear(InstructionSet_SSE2);
}
// We need to additionally check that EXTERNAL_EnableSSE3_4 is set, as that
// is a prexisting config flag that controls the SSE3+ ISAs
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSE3) || !CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSE3_4))
{
CPUCompileFlags.Clear(InstructionSet_SSE3);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSE41))
{
CPUCompileFlags.Clear(InstructionSet_SSE41);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSE42))
{
CPUCompileFlags.Clear(InstructionSet_SSE42);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSSE3))
{
CPUCompileFlags.Clear(InstructionSet_SSSE3);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableX86Serialize))
{
CPUCompileFlags.Clear(InstructionSet_X86Serialize);
}
#elif defined(TARGET_ARM64)
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableHWIntrinsic))
{
CPUCompileFlags.Clear(InstructionSet_ArmBase);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64AdvSimd))
{
CPUCompileFlags.Clear(InstructionSet_AdvSimd);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Aes))
{
CPUCompileFlags.Clear(InstructionSet_Aes);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Atomics))
{
CPUCompileFlags.Clear(InstructionSet_Atomics);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Rcpc))
{
CPUCompileFlags.Clear(InstructionSet_Rcpc);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Crc32))
{
CPUCompileFlags.Clear(InstructionSet_Crc32);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Dczva))
{
CPUCompileFlags.Clear(InstructionSet_Dczva);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Dp))
{
CPUCompileFlags.Clear(InstructionSet_Dp);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Rdm))
{
CPUCompileFlags.Clear(InstructionSet_Rdm);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Sha1))
{
CPUCompileFlags.Clear(InstructionSet_Sha1);
}
if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Sha256))
{
CPUCompileFlags.Clear(InstructionSet_Sha256);
}
#endif
#if defined(TARGET_LOONGARCH64)
// TODO-LoongArch64: set LoongArch64's InstructionSet features !
#endif // TARGET_LOONGARCH64
// These calls are very important as it ensures the flags are consistent with any
// removals specified above. This includes removing corresponding 64-bit ISAs
// and any other implications such as SSE2 depending on SSE or AdvSimd on ArmBase
CPUCompileFlags.Set64BitInstructionSetVariants();
CPUCompileFlags.EnsureValidInstructionSetSupport();
m_CPUCompileFlags = CPUCompileFlags;
}
// Define some data that we can use to get a better idea of what happened when we get a Watson dump that indicates the JIT failed to load.
// This will be used and updated by the JIT loading and initialization functions, and the data written will get written into a Watson dump.
enum JIT_LOAD_JIT_ID
{
JIT_LOAD_MAIN = 500, // The "main" JIT. Normally, this is named "clrjit.dll". Start at a number that is somewhat uncommon (i.e., not zero or 1) to help distinguish from garbage, in process dumps.
// 501 is JIT_LOAD_LEGACY on some platforms; please do not reuse this value.
JIT_LOAD_ALTJIT = 502 // An "altjit". By default, named something like "clrjit_<targetos>_<target_arch>_<host_arch>.dll". Used both internally, as well as externally for JIT CTP builds.
};
enum JIT_LOAD_STATUS
{
JIT_LOAD_STATUS_STARTING = 1001, // The JIT load process is starting. Start at a number that is somewhat uncommon (i.e., not zero or 1) to help distinguish from garbage, in process dumps.
JIT_LOAD_STATUS_DONE_LOAD, // LoadLibrary of the JIT dll succeeded.
JIT_LOAD_STATUS_DONE_GET_JITSTARTUP, // GetProcAddress for "jitStartup" succeeded.
JIT_LOAD_STATUS_DONE_CALL_JITSTARTUP, // Calling jitStartup() succeeded.
JIT_LOAD_STATUS_DONE_GET_GETJIT, // GetProcAddress for "getJit" succeeded.
JIT_LOAD_STATUS_DONE_CALL_GETJIT, // Calling getJit() succeeded.
JIT_LOAD_STATUS_DONE_CALL_GETVERSIONIDENTIFIER, // Calling ICorJitCompiler::getVersionIdentifier() succeeded.
JIT_LOAD_STATUS_DONE_VERSION_CHECK, // The JIT-EE version identifier check succeeded.
JIT_LOAD_STATUS_DONE, // The JIT load is complete, and successful.
};
struct JIT_LOAD_DATA
{
JIT_LOAD_JIT_ID jld_id; // Which JIT are we currently loading?
JIT_LOAD_STATUS jld_status; // The current load status of a JIT load attempt.
HRESULT jld_hr; // If the JIT load fails, the last jld_status will be JIT_LOAD_STATUS_STARTING.
// In that case, this will contain the HRESULT returned by LoadLibrary.
// Otherwise, this will be S_OK (which is zero).
};
// Here's the global data for JIT load and initialization state.
JIT_LOAD_DATA g_JitLoadData;
// Validate that the name used to load the JIT is just a simple file name
// and does not contain something that could be used in a non-qualified path.
// For example, using the string "..\..\..\myjit.dll" we might attempt to
// load a JIT from the root of the drive.
//
// The minimal set of characters that we must check for and exclude are:
// On all platforms:
// '/' - (forward slash)
// On Windows:
// '\\' - (backslash)
// ':' - (colon)
//
// Returns false if we find any of these characters in 'pwzJitName'
// Returns true if we reach the null terminator without encountering
// any of these characters.
//
static bool ValidateJitName(LPCWSTR pwzJitName)
{
LPCWSTR pCurChar = pwzJitName;
wchar_t curChar;
do {
curChar = *pCurChar;
if (curChar == '/'
#ifdef TARGET_WINDOWS
|| (curChar == '\\') || (curChar == ':')
#endif
)
{
// Return false if we find any of these character in 'pwzJitName'
return false;
}
pCurChar++;
} while (curChar != 0);
// Return true; we have reached the null terminator
//
return true;
}
CORINFO_OS getClrVmOs();
// LoadAndInitializeJIT: load the JIT dll into the process, and initialize it (call the UtilCode initialization function,
// check the JIT-EE interface GUID, etc.)
//
// Parameters:
//
// pwzJitName - The filename of the JIT .dll file to load. E.g., "altjit.dll".
// pwzJitPath - (Debug only) The full path of the JIT .dll file to load
// phJit - On return, *phJit is the Windows module handle of the loaded JIT dll. It will be NULL if the load failed.
// ppICorJitCompiler - On return, *ppICorJitCompiler is the ICorJitCompiler* returned by the JIT's getJit() entrypoint.
// It is NULL if the JIT returns a NULL interface pointer, or if the JIT-EE interface GUID is mismatched.
// Note that if the given JIT is loaded, but the interface is mismatched, then *phJit will be legal and non-NULL
// even though *ppICorJitCompiler is NULL. This allows the caller to unload the JIT dll, if necessary
// (nobody does this today).
// pJitLoadData - Pointer to a structure that we update as we load and initialize the JIT to indicate how far we've gotten. This
// is used to help understand problems we see with JIT loading that come in via Watson dumps. Since we don't throw
// an exception immediately upon failure, we can lose information about what the failure was if we don't store this
// information in a way that persists into a process dump.
// targetOs - Target OS for JIT
//
static void LoadAndInitializeJIT(LPCWSTR pwzJitName DEBUGARG(LPCWSTR pwzJitPath), OUT HINSTANCE* phJit, OUT ICorJitCompiler** ppICorJitCompiler, IN OUT JIT_LOAD_DATA* pJitLoadData, CORINFO_OS targetOs)
{
STANDARD_VM_CONTRACT;
_ASSERTE(phJit != NULL);
_ASSERTE(ppICorJitCompiler != NULL);
_ASSERTE(pJitLoadData != NULL);
pJitLoadData->jld_status = JIT_LOAD_STATUS_STARTING;
pJitLoadData->jld_hr = S_OK;
*phJit = NULL;
*ppICorJitCompiler = NULL;
HRESULT hr = E_FAIL;
#ifdef _DEBUG
if (pwzJitPath != NULL)
{
*phJit = CLRLoadLibrary(pwzJitPath);
if (*phJit != NULL)
{
hr = S_OK;
}
}
#endif
if (hr == E_FAIL)
{
if (pwzJitName == nullptr)
{
pJitLoadData->jld_hr = E_FAIL;
LOG((LF_JIT, LL_FATALERROR, "LoadAndInitializeJIT: pwzJitName is null"));
return;
}
if (ValidateJitName(pwzJitName))
{
// Load JIT from next to CoreCLR binary
PathString CoreClrFolderHolder;
if (GetClrModulePathName(CoreClrFolderHolder) && !CoreClrFolderHolder.IsEmpty())
{
SString::Iterator iter = CoreClrFolderHolder.End();
BOOL findSep = CoreClrFolderHolder.FindBack(iter, DIRECTORY_SEPARATOR_CHAR_W);
if (findSep)
{
SString sJitName(pwzJitName);
CoreClrFolderHolder.Replace(iter + 1, CoreClrFolderHolder.End() - (iter + 1), sJitName);
*phJit = CLRLoadLibrary(CoreClrFolderHolder.GetUnicode());
if (*phJit != NULL)
{
hr = S_OK;
}
}
}
}
else
{
LOG((LF_JIT, LL_FATALERROR, "LoadAndInitializeJIT: invalid characters in %S\n", pwzJitName));
}
}
if (SUCCEEDED(hr))
{
pJitLoadData->jld_status = JIT_LOAD_STATUS_DONE_LOAD;
EX_TRY
{
typedef void (* pjitStartup)(ICorJitHost*);
pjitStartup jitStartupFn = (pjitStartup) GetProcAddress(*phJit, "jitStartup");
if (jitStartupFn)
{
pJitLoadData->jld_status = JIT_LOAD_STATUS_DONE_GET_JITSTARTUP;
(*jitStartupFn)(JitHost::getJitHost());
pJitLoadData->jld_status = JIT_LOAD_STATUS_DONE_CALL_JITSTARTUP;
}
typedef ICorJitCompiler* (__stdcall* pGetJitFn)();
pGetJitFn getJitFn = (pGetJitFn) GetProcAddress(*phJit, "getJit");
if (getJitFn)
{
pJitLoadData->jld_status = JIT_LOAD_STATUS_DONE_GET_GETJIT;
ICorJitCompiler* pICorJitCompiler = (*getJitFn)();
if (pICorJitCompiler != NULL)
{
pJitLoadData->jld_status = JIT_LOAD_STATUS_DONE_CALL_GETJIT;
GUID versionId;
memset(&versionId, 0, sizeof(GUID));
pICorJitCompiler->getVersionIdentifier(&versionId);
pJitLoadData->jld_status = JIT_LOAD_STATUS_DONE_CALL_GETVERSIONIDENTIFIER;
if (memcmp(&versionId, &JITEEVersionIdentifier, sizeof(GUID)) == 0)
{
pJitLoadData->jld_status = JIT_LOAD_STATUS_DONE_VERSION_CHECK;
// Specify to the JIT that it is working with the OS that we are compiled against
pICorJitCompiler->setTargetOS(targetOs);
// The JIT has loaded and passed the version identifier test, so publish the JIT interface to the caller.
*ppICorJitCompiler = pICorJitCompiler;
// The JIT is completely loaded and initialized now.
pJitLoadData->jld_status = JIT_LOAD_STATUS_DONE;
}
else
{
// Mismatched version ID. Fail the load.
LOG((LF_JIT, LL_FATALERROR, "LoadAndInitializeJIT: mismatched JIT version identifier in %S\n", pwzJitName));
}
}
else
{
LOG((LF_JIT, LL_FATALERROR, "LoadAndInitializeJIT: failed to get ICorJitCompiler in %S\n", pwzJitName));
}
}
else
{
LOG((LF_JIT, LL_FATALERROR, "LoadAndInitializeJIT: failed to find 'getJit' entrypoint in %S\n", pwzJitName));
}
}
EX_CATCH
{
LOG((LF_JIT, LL_FATALERROR, "LoadAndInitializeJIT: caught an exception trying to initialize %S\n", pwzJitName));
}
EX_END_CATCH(SwallowAllExceptions)
}
else
{
pJitLoadData->jld_hr = hr;
LOG((LF_JIT, LL_FATALERROR, "LoadAndInitializeJIT: failed to load %S, hr=0x%08x\n", pwzJitName, hr));
}
}
#ifdef FEATURE_MERGE_JIT_AND_ENGINE
EXTERN_C void jitStartup(ICorJitHost* host);
EXTERN_C ICorJitCompiler* getJit();
#endif // FEATURE_MERGE_JIT_AND_ENGINE
BOOL EEJitManager::LoadJIT()
{
STANDARD_VM_CONTRACT;
// If the JIT is already loaded, don't take the lock.
if (IsJitLoaded())
return TRUE;
// Use m_JitLoadCritSec to ensure that the JIT is loaded on one thread only
CrstHolder chRead(&m_JitLoadCritSec);
// Did someone load the JIT before we got the lock?
if (IsJitLoaded())
return TRUE;
SetCpuInfo();
m_storeRichDebugInfo = CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_RichDebugInfo) != 0;
ICorJitCompiler* newJitCompiler = NULL;
#ifdef FEATURE_MERGE_JIT_AND_ENGINE
EX_TRY
{
jitStartup(JitHost::getJitHost());
newJitCompiler = getJit();
// We don't need to call getVersionIdentifier(), since the JIT is linked together with the VM.
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions)
#else // !FEATURE_MERGE_JIT_AND_ENGINE
m_JITCompiler = NULL;
#if defined(TARGET_X86) || defined(TARGET_AMD64)
m_JITCompilerOther = NULL;
#endif
g_JitLoadData.jld_id = JIT_LOAD_MAIN;
LPWSTR mainJitPath = NULL;
#ifdef _DEBUG
IfFailThrow(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPath, &mainJitPath));
#endif
LoadAndInitializeJIT(ExecutionManager::GetJitName() DEBUGARG(mainJitPath), &m_JITCompiler, &newJitCompiler, &g_JitLoadData, getClrVmOs());
#endif // !FEATURE_MERGE_JIT_AND_ENGINE
#ifdef ALLOW_SXS_JIT
// Do not load altjit.dll unless COMPlus_AltJit is set.
// Even if the main JIT fails to load, if the user asks for an altjit we try to load it.
// This allows us to display load error messages for loading altjit.
ICorJitCompiler* newAltJitCompiler = NULL;
LPWSTR altJitConfig;
IfFailThrow(CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_AltJit, &altJitConfig));
m_AltJITCompiler = NULL;
if (altJitConfig != NULL)
{
// Load the altjit into the system.
// Note: altJitName must be declared as a const otherwise assigning the string
// constructed by MAKEDLLNAME_W() to altJitName will cause a build break on Unix.
LPCWSTR altJitName;
IfFailThrow(CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_AltJitName, (LPWSTR*)&altJitName));
if (altJitName == NULL)
{
#ifdef TARGET_WINDOWS
#ifdef TARGET_X86
altJitName = MAKEDLLNAME_W(W("clrjit_win_x86_x86"));
#elif defined(TARGET_AMD64)
altJitName = MAKEDLLNAME_W(W("clrjit_win_x64_x64"));
#endif
#else // TARGET_WINDOWS
#ifdef TARGET_X86
altJitName = MAKEDLLNAME_W(W("clrjit_unix_x86_x86"));
#elif defined(TARGET_AMD64)
altJitName = MAKEDLLNAME_W(W("clrjit_unix_x64_x64"));
#elif defined(TARGET_LOONGARCH64)
altJitName = MAKEDLLNAME_W(W("clrjit_unix_loongarch64_loongarch64"));
#endif
#endif // TARGET_WINDOWS
#if defined(TARGET_ARM)
altJitName = MAKEDLLNAME_W(W("clrjit_universal_arm_arm"));
#elif defined(TARGET_ARM64)
altJitName = MAKEDLLNAME_W(W("clrjit_universal_arm64_arm64"));
#endif // TARGET_ARM
}
#ifdef _DEBUG
LPWSTR altJitPath;
IfFailThrow(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_AltJitPath, &altJitPath));
#endif
CORINFO_OS targetOs = getClrVmOs();
LPWSTR altJitOsConfig;
IfFailThrow(CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_AltJitOs, &altJitOsConfig));
if (altJitOsConfig != NULL)
{
// We have some inconsistency all over the place with osx vs macos, let's handle both here
if ((_wcsicmp(altJitOsConfig, W("macos")) == 0) || (_wcsicmp(altJitOsConfig, W("osx")) == 0))
{
targetOs = CORINFO_MACOS;
}
else if ((_wcsicmp(altJitOsConfig, W("linux")) == 0) || (_wcsicmp(altJitOsConfig, W("unix")) == 0))
{
targetOs = CORINFO_UNIX;
}
else if (_wcsicmp(altJitOsConfig, W("windows")) == 0)
{
targetOs = CORINFO_WINNT;
}
else
{
_ASSERTE(!"Unknown AltJitOS, it has to be either Windows, Linux or macOS");
}
}
g_JitLoadData.jld_id = JIT_LOAD_ALTJIT;
LoadAndInitializeJIT(altJitName DEBUGARG(altJitPath), &m_AltJITCompiler, &newAltJitCompiler, &g_JitLoadData, targetOs);
}
#endif // ALLOW_SXS_JIT
// Publish the compilers.
#ifdef ALLOW_SXS_JIT
m_AltJITRequired = (altJitConfig != NULL);
m_alternateJit = newAltJitCompiler;
#endif // ALLOW_SXS_JIT
m_jit = newJitCompiler;
// Failing to load the main JIT is a failure.
// If the user requested an altjit and we failed to load an altjit, that is also a failure.
// In either failure case, we'll rip down the VM (so no need to clean up (unload) either JIT that did load successfully.
return IsJitLoaded();
}
//**************************************************************************
CodeFragmentHeap::CodeFragmentHeap(LoaderAllocator * pAllocator, StubCodeBlockKind kind)
: m_pAllocator(pAllocator), m_pFreeBlocks(NULL), m_kind(kind),
// CRST_DEBUGGER_THREAD - We take this lock on debugger thread during EnC add meth
m_CritSec(CrstCodeFragmentHeap, CrstFlags(CRST_UNSAFE_ANYMODE | CRST_DEBUGGER_THREAD))
{
WRAPPER_NO_CONTRACT;
}
void CodeFragmentHeap::AddBlock(VOID * pMem, size_t dwSize)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// The new "nothrow" below failure is handled in a non-fault way, so
// make sure that callers with FORBID_FAULT can call this method without
// firing the contract violation assert.
PERMANENT_CONTRACT_VIOLATION(FaultViolation, ReasonContractInfrastructure);
FreeBlock * pBlock = new (nothrow) FreeBlock;
// In the OOM case we don't add the block to the list of free blocks
// as we are in a FORBID_FAULT code path.
if (pBlock != NULL)
{
pBlock->m_pNext = m_pFreeBlocks;
pBlock->m_pBlock = pMem;
pBlock->m_dwSize = dwSize;
m_pFreeBlocks = pBlock;
}
}
void CodeFragmentHeap::RemoveBlock(FreeBlock ** ppBlock)
{
LIMITED_METHOD_CONTRACT;
FreeBlock * pBlock = *ppBlock;
*ppBlock = pBlock->m_pNext;
delete pBlock;
}
CodeFragmentHeap::~CodeFragmentHeap()
{
FreeBlock* pBlock = m_pFreeBlocks;
while (pBlock != NULL)
{
FreeBlock *pNextBlock = pBlock->m_pNext;
delete pBlock;
pBlock = pNextBlock;
}
}
TaggedMemAllocPtr CodeFragmentHeap::RealAllocAlignedMem(size_t dwRequestedSize
,unsigned dwAlignment
#ifdef _DEBUG
,_In_ _In_z_ const char *szFile
,int lineNum
#endif
)
{
CrstHolder ch(&m_CritSec);
dwRequestedSize = ALIGN_UP(dwRequestedSize, sizeof(TADDR));
// We will try to batch up allocation of small blocks into one large allocation
#define SMALL_BLOCK_THRESHOLD 0x100
SIZE_T nFreeSmallBlocks = 0;
FreeBlock ** ppBestFit = NULL;
FreeBlock ** ppFreeBlock = &m_pFreeBlocks;
while (*ppFreeBlock != NULL)
{
FreeBlock * pFreeBlock = *ppFreeBlock;
if (((BYTE *)pFreeBlock->m_pBlock + pFreeBlock->m_dwSize) - (BYTE *)ALIGN_UP(pFreeBlock->m_pBlock, dwAlignment) >= (SSIZE_T)dwRequestedSize)
{
if (ppBestFit == NULL || pFreeBlock->m_dwSize < (*ppBestFit)->m_dwSize)
ppBestFit = ppFreeBlock;
}
else
{
if (pFreeBlock->m_dwSize < SMALL_BLOCK_THRESHOLD)
nFreeSmallBlocks++;
}
ppFreeBlock = &(*ppFreeBlock)->m_pNext;
}
VOID * pMem;
SIZE_T dwSize;
if (ppBestFit != NULL)
{
pMem = (*ppBestFit)->m_pBlock;
dwSize = (*ppBestFit)->m_dwSize;
RemoveBlock(ppBestFit);
}
else
{
dwSize = dwRequestedSize;
if (dwSize < SMALL_BLOCK_THRESHOLD)
dwSize = 4 * SMALL_BLOCK_THRESHOLD;
pMem = ExecutionManager::GetEEJitManager()->allocCodeFragmentBlock(dwSize, dwAlignment, m_pAllocator, m_kind);
}
SIZE_T dwExtra = (BYTE *)ALIGN_UP(pMem, dwAlignment) - (BYTE *)pMem;
_ASSERTE(dwSize >= dwExtra + dwRequestedSize);
SIZE_T dwRemaining = dwSize - (dwExtra + dwRequestedSize);
// Avoid accumulation of too many small blocks. The more small free blocks we have, the more picky we are going to be about adding new ones.
if ((dwRemaining >= max(sizeof(FreeBlock), sizeof(StubPrecode)) + (SMALL_BLOCK_THRESHOLD / 0x10) * nFreeSmallBlocks) || (dwRemaining >= SMALL_BLOCK_THRESHOLD))
{
AddBlock((BYTE *)pMem + dwExtra + dwRequestedSize, dwRemaining);
dwSize -= dwRemaining;
}
TaggedMemAllocPtr tmap;
tmap.m_pMem = pMem;
tmap.m_dwRequestedSize = dwSize;
tmap.m_pHeap = this;
tmap.m_dwExtra = dwExtra;
#ifdef _DEBUG
tmap.m_szFile = szFile;
tmap.m_lineNum = lineNum;
#endif
return tmap;
}
void CodeFragmentHeap::RealBackoutMem(void *pMem
, size_t dwSize
#ifdef _DEBUG
, _In_ _In_z_ const char *szFile
, int lineNum
, _In_ _In_z_ const char *szAllocFile
, int allocLineNum
#endif
)
{
CrstHolder ch(&m_CritSec);
{
ExecutableWriterHolder<BYTE> memWriterHolder((BYTE*)pMem, dwSize);
ZeroMemory(memWriterHolder.GetRW(), dwSize);
}
//
// Try to coalesce blocks if possible
//
FreeBlock ** ppFreeBlock = &m_pFreeBlocks;
while (*ppFreeBlock != NULL)
{
FreeBlock * pFreeBlock = *ppFreeBlock;
if ((BYTE *)pFreeBlock == (BYTE *)pMem + dwSize)
{
// pMem = pMem;
dwSize += pFreeBlock->m_dwSize;
RemoveBlock(ppFreeBlock);
continue;
}
else
if ((BYTE *)pFreeBlock + pFreeBlock->m_dwSize == (BYTE *)pMem)
{
pMem = pFreeBlock;
dwSize += pFreeBlock->m_dwSize;
RemoveBlock(ppFreeBlock);
continue;
}
ppFreeBlock = &(*ppFreeBlock)->m_pNext;
}
AddBlock(pMem, dwSize);
}
//**************************************************************************
LoaderCodeHeap::LoaderCodeHeap()
: m_LoaderHeap(NULL, // RangeList *pRangeList
TRUE), // BOOL fMakeExecutable
m_cbMinNextPad(0)
{
WRAPPER_NO_CONTRACT;
}
void ThrowOutOfMemoryWithinRange()
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
// Allow breaking into debugger or terminating the process when this exception occurs
switch (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_BreakOnOutOfMemoryWithinRange))
{
case 1:
DebugBreak();
break;
case 2:
EEPOLICY_HANDLE_FATAL_ERROR(COR_E_OUTOFMEMORY);
break;
default:
break;
}
EX_THROW(EEMessageException, (kOutOfMemoryException, IDS_EE_OUT_OF_MEMORY_WITHIN_RANGE));
}
#ifdef TARGET_AMD64
BYTE * EEJitManager::AllocateFromEmergencyJumpStubReserve(const BYTE * loAddr, const BYTE * hiAddr, SIZE_T * pReserveSize)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
} CONTRACTL_END;
for (EmergencyJumpStubReserve ** ppPrev = &m_pEmergencyJumpStubReserveList; *ppPrev != NULL; ppPrev = &(*ppPrev)->m_pNext)
{
EmergencyJumpStubReserve * pList = *ppPrev;
if (loAddr <= pList->m_ptr &&
pList->m_ptr + pList->m_size < hiAddr)
{
*ppPrev = pList->m_pNext;
BYTE * pBlock = pList->m_ptr;
*pReserveSize = pList->m_size;
delete pList;
return pBlock;
}
}
return NULL;
}
VOID EEJitManager::EnsureJumpStubReserve(BYTE * pImageBase, SIZE_T imageSize, SIZE_T reserveSize)
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
CrstHolder ch(&m_CodeHeapCritSec);
BYTE * loAddr = pImageBase + imageSize + INT32_MIN;
if (loAddr > pImageBase) loAddr = NULL; // overflow
BYTE * hiAddr = pImageBase + INT32_MAX;
if (hiAddr < pImageBase) hiAddr = (BYTE *)UINT64_MAX; // overflow
for (EmergencyJumpStubReserve * pList = m_pEmergencyJumpStubReserveList; pList != NULL; pList = pList->m_pNext)
{
if (loAddr <= pList->m_ptr &&
pList->m_ptr + pList->m_size < hiAddr)
{
SIZE_T used = min(reserveSize, pList->m_free);
pList->m_free -= used;
reserveSize -= used;
if (reserveSize == 0)
return;
}
}
// Try several different strategies - the most efficient one first
int allocMode = 0;
// Try to reserve at least 16MB at a time
SIZE_T allocChunk = max(ALIGN_UP(reserveSize, VIRTUAL_ALLOC_RESERVE_GRANULARITY), 16*1024*1024);
while (reserveSize > 0)
{
NewHolder<EmergencyJumpStubReserve> pNewReserve(new EmergencyJumpStubReserve());
while (true)
{
BYTE * loAddrCurrent = loAddr;
BYTE * hiAddrCurrent = hiAddr;
switch (allocMode)
{
case 0:
// First, try to allocate towards the center of the allowed range. It is more likely to
// satisfy subsequent reservations.
loAddrCurrent = loAddr + (hiAddr - loAddr) / 8;
hiAddrCurrent = hiAddr - (hiAddr - loAddr) / 8;
break;
case 1:
// Try the whole allowed range
break;
case 2:
// If the large allocation failed, retry with small chunk size
allocChunk = VIRTUAL_ALLOC_RESERVE_GRANULARITY;
break;
default:
return; // Unable to allocate the reserve - give up
}
pNewReserve->m_ptr = (BYTE*)ExecutableAllocator::Instance()->ReserveWithinRange(allocChunk, loAddrCurrent, hiAddrCurrent);
if (pNewReserve->m_ptr != NULL)
break;
// Retry with the next allocation strategy
allocMode++;
}
SIZE_T used = min(allocChunk, reserveSize);
reserveSize -= used;
pNewReserve->m_size = allocChunk;
pNewReserve->m_free = allocChunk - used;
// Add it to the list
pNewReserve->m_pNext = m_pEmergencyJumpStubReserveList;
m_pEmergencyJumpStubReserveList = pNewReserve.Extract();
}
}
#endif // TARGET_AMD64
static size_t GetDefaultReserveForJumpStubs(size_t codeHeapSize)
{
LIMITED_METHOD_CONTRACT;
#if defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64)
//
// Keep a small default reserve at the end of the codeheap for jump stubs. It should reduce
// chance that we won't be able allocate jump stub because of lack of suitable address space.
//
static ConfigDWORD configCodeHeapReserveForJumpStubs;
int percentReserveForJumpStubs = configCodeHeapReserveForJumpStubs.val(CLRConfig::INTERNAL_CodeHeapReserveForJumpStubs);
size_t reserveForJumpStubs = percentReserveForJumpStubs * (codeHeapSize / 100);
size_t minReserveForJumpStubs = sizeof(CodeHeader) +
sizeof(JumpStubBlockHeader) + (size_t) DEFAULT_JUMPSTUBS_PER_BLOCK * BACK_TO_BACK_JUMP_ALLOCATE_SIZE +
CODE_SIZE_ALIGN + BYTES_PER_BUCKET;
return max(reserveForJumpStubs, minReserveForJumpStubs);
#else
return 0;
#endif
}
HeapList* LoaderCodeHeap::CreateCodeHeap(CodeHeapRequestInfo *pInfo, LoaderHeap *pJitMetaHeap)
{
CONTRACT(HeapList *) {
THROWS;
GC_NOTRIGGER;
POSTCONDITION((RETVAL != NULL) || !pInfo->getThrowOnOutOfMemoryWithinRange());
} CONTRACT_END;
size_t reserveSize = pInfo->getReserveSize();
size_t initialRequestSize = pInfo->getRequestSize();
const BYTE * loAddr = pInfo->m_loAddr;
const BYTE * hiAddr = pInfo->m_hiAddr;
// Make sure that what we are reserving will fix inside a DWORD
if (reserveSize != (DWORD) reserveSize)
{
_ASSERTE(!"reserveSize does not fit in a DWORD");
EEPOLICY_HANDLE_FATAL_ERROR(COR_E_EXECUTIONENGINE);
}
LOG((LF_JIT, LL_INFO100,
"Request new LoaderCodeHeap::CreateCodeHeap(%08x, %08x, for loader allocator" FMT_ADDR "in" FMT_ADDR ".." FMT_ADDR ")\n",
(DWORD) reserveSize, (DWORD) initialRequestSize, DBG_ADDR(pInfo->m_pAllocator), DBG_ADDR(loAddr), DBG_ADDR(hiAddr)
));
NewHolder<LoaderCodeHeap> pCodeHeap(new LoaderCodeHeap());
BYTE * pBaseAddr = NULL;
DWORD dwSizeAcquiredFromInitialBlock = 0;
bool fAllocatedFromEmergencyJumpStubReserve = false;
size_t allocationSize = pCodeHeap->m_LoaderHeap.AllocMem_TotalSize(initialRequestSize);
#if defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64)
allocationSize += pCodeHeap->m_LoaderHeap.AllocMem_TotalSize(JUMP_ALLOCATE_SIZE);
#endif
pBaseAddr = (BYTE *)pInfo->m_pAllocator->GetCodeHeapInitialBlock(loAddr, hiAddr, (DWORD)allocationSize, &dwSizeAcquiredFromInitialBlock);
if (pBaseAddr != NULL)
{
pCodeHeap->m_LoaderHeap.SetReservedRegion(pBaseAddr, dwSizeAcquiredFromInitialBlock, FALSE);
}
else
{
if (loAddr != NULL || hiAddr != NULL)
{
#ifdef _DEBUG
// Always exercise the fallback path in the caller when forced relocs are turned on
if (!pInfo->getThrowOnOutOfMemoryWithinRange() && PEDecoder::GetForceRelocs())
RETURN NULL;
#endif
pBaseAddr = (BYTE*)ExecutableAllocator::Instance()->ReserveWithinRange(reserveSize, loAddr, hiAddr);
if (!pBaseAddr)
{
// Conserve emergency jump stub reserve until when it is really needed
if (!pInfo->getThrowOnOutOfMemoryWithinRange())
RETURN NULL;
#ifdef TARGET_AMD64
pBaseAddr = ExecutionManager::GetEEJitManager()->AllocateFromEmergencyJumpStubReserve(loAddr, hiAddr, &reserveSize);
if (!pBaseAddr)
ThrowOutOfMemoryWithinRange();
fAllocatedFromEmergencyJumpStubReserve = true;
#else
ThrowOutOfMemoryWithinRange();
#endif // TARGET_AMD64
}
}
else
{
pBaseAddr = (BYTE*)ExecutableAllocator::Instance()->Reserve(reserveSize);
if (!pBaseAddr)
ThrowOutOfMemory();
}
pCodeHeap->m_LoaderHeap.SetReservedRegion(pBaseAddr, reserveSize, TRUE);
}
// this first allocation is critical as it sets up correctly the loader heap info
HeapList *pHp = new HeapList;
#if defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64)
pHp->CLRPersonalityRoutine = (BYTE *)pCodeHeap->m_LoaderHeap.AllocMem(JUMP_ALLOCATE_SIZE);
#else
// Ensure that the heap has a reserved block of memory and so the GetReservedBytesFree()
// and GetAllocPtr() calls below return nonzero values.
pCodeHeap->m_LoaderHeap.ReservePages(1);
#endif
pHp->pHeap = pCodeHeap;
size_t heapSize = pCodeHeap->m_LoaderHeap.GetReservedBytesFree();
size_t nibbleMapSize = HEAP2MAPSIZE(ROUND_UP_TO_PAGE(heapSize));
pHp->startAddress = (TADDR)pCodeHeap->m_LoaderHeap.GetAllocPtr();
pHp->endAddress = pHp->startAddress;
pHp->maxCodeHeapSize = heapSize;
pHp->reserveForJumpStubs = fAllocatedFromEmergencyJumpStubReserve ? pHp->maxCodeHeapSize : GetDefaultReserveForJumpStubs(pHp->maxCodeHeapSize);
_ASSERTE(heapSize >= initialRequestSize);
// We do not need to memset this memory, since ClrVirtualAlloc() guarantees that the memory is zero.
// Furthermore, if we avoid writing to it, these pages don't come into our working set
pHp->mapBase = ROUND_DOWN_TO_PAGE(pHp->startAddress); // round down to next lower page align
pHp->pHdrMap = (DWORD*)(void*)pJitMetaHeap->AllocMem(S_SIZE_T(nibbleMapSize));
LOG((LF_JIT, LL_INFO100,
"Created new CodeHeap(" FMT_ADDR ".." FMT_ADDR ")\n",
DBG_ADDR(pHp->startAddress), DBG_ADDR(pHp->startAddress+pHp->maxCodeHeapSize)
));
#ifdef TARGET_64BIT
ExecutableWriterHolder<BYTE> personalityRoutineWriterHolder(pHp->CLRPersonalityRoutine, 12);
emitJump(pHp->CLRPersonalityRoutine, personalityRoutineWriterHolder.GetRW(), (void *)ProcessCLRException);
#endif // TARGET_64BIT
pCodeHeap.SuppressRelease();
RETURN pHp;
}
void * LoaderCodeHeap::AllocMemForCode_NoThrow(size_t header, size_t size, DWORD alignment, size_t reserveForJumpStubs)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
if (m_cbMinNextPad > (SSIZE_T)header) header = m_cbMinNextPad;
void * p = m_LoaderHeap.AllocMemForCode_NoThrow(header, size, alignment, reserveForJumpStubs);
if (p == NULL)
return NULL;
// If the next allocation would have started in the same nibble map entry, allocate extra space to prevent it from happening
// Note that m_cbMinNextPad can be negative
m_cbMinNextPad = ALIGN_UP((SIZE_T)p + 1, BYTES_PER_BUCKET) - ((SIZE_T)p + size);
return p;
}
void CodeHeapRequestInfo::Init()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
PRECONDITION((m_hiAddr == 0) ||
((m_loAddr < m_hiAddr) &&
((m_loAddr + m_requestSize) < m_hiAddr)));
} CONTRACTL_END;
if (m_pAllocator == NULL)
m_pAllocator = m_pMD->GetLoaderAllocator();
m_isDynamicDomain = (m_pMD != NULL) && m_pMD->IsLCGMethod();
m_isCollectible = m_pAllocator->IsCollectible();
m_throwOnOutOfMemoryWithinRange = true;
}
#ifdef FEATURE_EH_FUNCLETS
#ifdef HOST_64BIT
extern "C" PT_RUNTIME_FUNCTION GetRuntimeFunctionCallback(IN ULONG64 ControlPc,
IN PVOID Context)
#else
extern "C" PT_RUNTIME_FUNCTION GetRuntimeFunctionCallback(IN ULONG ControlPc,
IN PVOID Context)
#endif
{
WRAPPER_NO_CONTRACT;
PT_RUNTIME_FUNCTION prf = NULL;
// We must preserve this so that GCStress=4 eh processing doesnt kill last error.
BEGIN_PRESERVE_LAST_ERROR;
#ifdef ENABLE_CONTRACTS
// Some 64-bit OOM tests use the hosting interface to re-enter the CLR via
// RtlVirtualUnwind to track unique stacks at each failure point. RtlVirtualUnwind can
// result in the EEJitManager taking a reader lock. This, in turn, results in a
// CANNOT_TAKE_LOCK contract violation if a CANNOT_TAKE_LOCK function were on the stack
// at the time. While it's theoretically possible for "real" hosts also to re-enter the
// CLR via RtlVirtualUnwind, generally they don't, and we'd actually like to catch a real
// host causing such a contract violation. Therefore, we'd like to suppress such contract
// asserts when these OOM tests are running, but continue to enforce the contracts by
// default. This function returns whether to suppress locking violations.
CONDITIONAL_CONTRACT_VIOLATION(
TakesLockViolation,
g_pConfig->SuppressLockViolationsOnReentryFromOS());
#endif // ENABLE_CONTRACTS
EECodeInfo codeInfo((PCODE)ControlPc);
if (codeInfo.IsValid())
prf = codeInfo.GetFunctionEntry();
LOG((LF_EH, LL_INFO1000000, "GetRuntimeFunctionCallback(%p) returned %p\n", ControlPc, prf));
END_PRESERVE_LAST_ERROR;
return prf;
}
#endif // FEATURE_EH_FUNCLETS
HeapList* EEJitManager::NewCodeHeap(CodeHeapRequestInfo *pInfo, DomainCodeHeapList *pADHeapList)
{
CONTRACT(HeapList *) {
THROWS;
GC_NOTRIGGER;
PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
POSTCONDITION((RETVAL != NULL) || !pInfo->getThrowOnOutOfMemoryWithinRange());
} CONTRACT_END;
size_t initialRequestSize = pInfo->getRequestSize();
size_t minReserveSize = VIRTUAL_ALLOC_RESERVE_GRANULARITY; // ( 64 KB)
#ifdef HOST_64BIT
if (pInfo->m_hiAddr == 0)
{
if (pADHeapList->m_CodeHeapList.Count() > CODE_HEAP_SIZE_INCREASE_THRESHOLD)
{
minReserveSize *= 4; // Increase the code heap size to 256 KB for workloads with a lot of code.
}
// For non-DynamicDomains that don't have a loAddr/hiAddr range
// we bump up the reserve size for the 64-bit platforms
if (!pInfo->IsDynamicDomain())
{
minReserveSize *= 8; // CodeHeaps are larger on AMD64 (256 KB to 2048 KB)
}
}
#endif
size_t reserveSize = initialRequestSize;
#if defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64)
reserveSize += JUMP_ALLOCATE_SIZE;
#endif
if (reserveSize < minReserveSize)
reserveSize = minReserveSize;
reserveSize = ALIGN_UP(reserveSize, VIRTUAL_ALLOC_RESERVE_GRANULARITY);
pInfo->setReserveSize(reserveSize);
HeapList *pHp = NULL;
DWORD flags = RangeSection::RANGE_SECTION_CODEHEAP;
if (pInfo->IsDynamicDomain())
{
flags |= RangeSection::RANGE_SECTION_COLLECTIBLE;
pHp = HostCodeHeap::CreateCodeHeap(pInfo, this);
}
else
{
LoaderHeap *pJitMetaHeap = pADHeapList->m_pAllocator->GetLowFrequencyHeap();
if (pInfo->IsCollectible())
flags |= RangeSection::RANGE_SECTION_COLLECTIBLE;
pHp = LoaderCodeHeap::CreateCodeHeap(pInfo, pJitMetaHeap);
}
if (pHp == NULL)
{
_ASSERTE(!pInfo->getThrowOnOutOfMemoryWithinRange());
RETURN(NULL);
}
_ASSERTE (pHp != NULL);
_ASSERTE (pHp->maxCodeHeapSize >= initialRequestSize);
pHp->SetNext(GetCodeHeapList());
EX_TRY
{
TADDR pStartRange = pHp->GetModuleBase();
TADDR pEndRange = (TADDR) &((BYTE*)pHp->startAddress)[pHp->maxCodeHeapSize];
ExecutionManager::AddCodeRange(pStartRange,
pEndRange,
this,
(RangeSection::RangeSectionFlags)flags,
pHp);
//
// add a table to cover each range in the range list
//
InstallEEFunctionTable(
(PVOID)pStartRange, // this is just an ID that gets passed to RtlDeleteFunctionTable;
(PVOID)pStartRange,
(ULONG)((ULONG64)pEndRange - (ULONG64)pStartRange),
GetRuntimeFunctionCallback,
this,
DYNFNTABLE_JIT);
}
EX_CATCH
{
// If we failed to alloc memory in ExecutionManager::AddCodeRange()
// then we will delete the LoaderHeap that we allocated
delete pHp->pHeap;
delete pHp;
pHp = NULL;
}
EX_END_CATCH(SwallowAllExceptions)
if (pHp == NULL)
{
ThrowOutOfMemory();
}
m_pCodeHeap = pHp;
HeapList **ppHeapList = pADHeapList->m_CodeHeapList.AppendThrowing();
*ppHeapList = pHp;
RETURN(pHp);
}
void* EEJitManager::allocCodeRaw(CodeHeapRequestInfo *pInfo,
size_t header, size_t blockSize, unsigned align,
HeapList ** ppCodeHeap)
{
CONTRACT(void *) {
THROWS;
GC_NOTRIGGER;
PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
POSTCONDITION((RETVAL != NULL) || !pInfo->getThrowOnOutOfMemoryWithinRange());
} CONTRACT_END;
pInfo->setRequestSize(header+blockSize+(align-1)+pInfo->getReserveForJumpStubs());
void * mem = NULL;
HeapList * pCodeHeap = NULL;
DomainCodeHeapList *pList = NULL;
// Avoid going through the full list in the common case - try to use the most recently used codeheap
if (pInfo->IsDynamicDomain())
{
pCodeHeap = (HeapList *)pInfo->m_pAllocator->m_pLastUsedDynamicCodeHeap;
pInfo->m_pAllocator->m_pLastUsedDynamicCodeHeap = NULL;
}
else
{
pCodeHeap = (HeapList *)pInfo->m_pAllocator->m_pLastUsedCodeHeap;
pInfo->m_pAllocator->m_pLastUsedCodeHeap = NULL;
}
// If we will use a cached code heap, ensure that the code heap meets the constraints
if (pCodeHeap && CanUseCodeHeap(pInfo, pCodeHeap))
{
mem = (pCodeHeap->pHeap)->AllocMemForCode_NoThrow(header, blockSize, align, pInfo->getReserveForJumpStubs());
}
if (mem == NULL)
{
pList = GetCodeHeapList(pInfo, pInfo->m_pAllocator);
if (pList != NULL)
{
for (int i = 0; i < pList->m_CodeHeapList.Count(); i++)
{
pCodeHeap = pList->m_CodeHeapList[i];
// Validate that the code heap can be used for the current request
if (CanUseCodeHeap(pInfo, pCodeHeap))
{
mem = (pCodeHeap->pHeap)->AllocMemForCode_NoThrow(header, blockSize, align, pInfo->getReserveForJumpStubs());
if (mem != NULL)
break;
}
}
}
if (mem == NULL)
{
// Let us create a new heap.
if (pList == NULL)
{
// not found so need to create the first one
pList = CreateCodeHeapList(pInfo);
_ASSERTE(pList == GetCodeHeapList(pInfo, pInfo->m_pAllocator));
}
_ASSERTE(pList);
pCodeHeap = NewCodeHeap(pInfo, pList);
if (pCodeHeap == NULL)
{
_ASSERTE(!pInfo->getThrowOnOutOfMemoryWithinRange());
RETURN(NULL);
}
mem = (pCodeHeap->pHeap)->AllocMemForCode_NoThrow(header, blockSize, align, pInfo->getReserveForJumpStubs());
if (mem == NULL)
ThrowOutOfMemory();
_ASSERTE(mem);
}
}
if (pInfo->IsDynamicDomain())
{
pInfo->m_pAllocator->m_pLastUsedDynamicCodeHeap = pCodeHeap;
}
else
{
pInfo->m_pAllocator->m_pLastUsedCodeHeap = pCodeHeap;
}
// Record the pCodeHeap value into ppCodeHeap
*ppCodeHeap = pCodeHeap;
_ASSERTE((TADDR)mem >= pCodeHeap->startAddress);
if (((TADDR) mem)+blockSize > (TADDR)pCodeHeap->endAddress)
{
// Update the CodeHeap endAddress
pCodeHeap->endAddress = (TADDR)mem+blockSize;
}
RETURN(mem);
}
void EEJitManager::allocCode(MethodDesc* pMD, size_t blockSize, size_t reserveForJumpStubs, CorJitAllocMemFlag flag, CodeHeader** ppCodeHeader, CodeHeader** ppCodeHeaderRW,
size_t* pAllocatedSize, HeapList** ppCodeHeap
#ifdef USE_INDIRECT_CODEHEADER
, BYTE** ppRealHeader
#endif
#ifdef FEATURE_EH_FUNCLETS
, UINT nUnwindInfos
#endif
)
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
//
// Alignment
//
unsigned alignment = CODE_SIZE_ALIGN;
if ((flag & CORJIT_ALLOCMEM_FLG_32BYTE_ALIGN) != 0)
{
alignment = max(alignment, 32);
}
else if ((flag & CORJIT_ALLOCMEM_FLG_16BYTE_ALIGN) != 0)
{
alignment = max(alignment, 16);
}
#if defined(TARGET_X86)
// when not optimizing for code size, 8-byte align the method entry point, so that
// the JIT can in turn 8-byte align the loop entry headers.
else if ((g_pConfig->GenOptimizeType() != OPT_SIZE))
{
alignment = max(alignment, 8);
}
#endif
//
// Compute header layout
//
SIZE_T totalSize = blockSize;
CodeHeader * pCodeHdr = NULL;
CodeHeader * pCodeHdrRW = NULL;
CodeHeapRequestInfo requestInfo(pMD);
#if defined(FEATURE_JIT_PITCHING)
if (pMD && pMD->IsPitchable() && CLRConfig::GetConfigValue(CLRConfig::INTERNAL_JitPitchMethodSizeThreshold) < blockSize)
{
requestInfo.SetDynamicDomain();
}
#endif
requestInfo.setReserveForJumpStubs(reserveForJumpStubs);
#if defined(USE_INDIRECT_CODEHEADER)
SIZE_T realHeaderSize = offsetof(RealCodeHeader, unwindInfos[0]) + (sizeof(T_RUNTIME_FUNCTION) * nUnwindInfos);
// if this is a LCG method then we will be allocating the RealCodeHeader
// following the code so that the code block can be removed easily by
// the LCG code heap.
if (requestInfo.IsDynamicDomain())
{
totalSize = ALIGN_UP(totalSize, sizeof(void*)) + realHeaderSize;
static_assert_no_msg(CODE_SIZE_ALIGN >= sizeof(void*));
}
#endif // USE_INDIRECT_CODEHEADER
// Scope the lock
{
CrstHolder ch(&m_CodeHeapCritSec);
*ppCodeHeap = NULL;
TADDR pCode = (TADDR) allocCodeRaw(&requestInfo, sizeof(CodeHeader), totalSize, alignment, ppCodeHeap);
_ASSERTE(*ppCodeHeap);
if (pMD->IsLCGMethod())
{
pMD->AsDynamicMethodDesc()->GetLCGMethodResolver()->m_recordCodePointer = (void*) pCode;
}
_ASSERTE(IS_ALIGNED(pCode, alignment));
pCodeHdr = ((CodeHeader *)pCode) - 1;
*pAllocatedSize = sizeof(CodeHeader) + totalSize;
if (ExecutableAllocator::IsWXORXEnabled())
{
pCodeHdrRW = (CodeHeader *)new BYTE[*pAllocatedSize];
}
else
{
pCodeHdrRW = pCodeHdr;
}
#ifdef USE_INDIRECT_CODEHEADER
if (requestInfo.IsDynamicDomain())
{
// Set the real code header to the writeable mapping so that we can set its members via the CodeHeader methods below
pCodeHdrRW->SetRealCodeHeader((BYTE *)(pCodeHdrRW + 1) + ALIGN_UP(blockSize, sizeof(void*)));
}
else
{
// TODO: think about the CodeHeap carrying around a RealCodeHeader chunking mechanism
//
// allocate the real header in the low frequency heap
BYTE* pRealHeader = (BYTE*)(void*)pMD->GetLoaderAllocator()->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(realHeaderSize));
pCodeHdrRW->SetRealCodeHeader(pRealHeader);
}
#endif
pCodeHdrRW->SetDebugInfo(NULL);
pCodeHdrRW->SetEHInfo(NULL);
pCodeHdrRW->SetGCInfo(NULL);
pCodeHdrRW->SetMethodDesc(pMD);
#ifdef FEATURE_EH_FUNCLETS
pCodeHdrRW->SetNumberOfUnwindInfos(nUnwindInfos);
#endif
#ifdef USE_INDIRECT_CODEHEADER
if (requestInfo.IsDynamicDomain())
{
*ppRealHeader = (BYTE*)pCode + ALIGN_UP(blockSize, sizeof(void*));
}
else
{
*ppRealHeader = NULL;
}
#endif // USE_INDIRECT_CODEHEADER
}
*ppCodeHeader = pCodeHdr;
*ppCodeHeaderRW = pCodeHdrRW;
}
EEJitManager::DomainCodeHeapList *EEJitManager::GetCodeHeapList(CodeHeapRequestInfo *pInfo, LoaderAllocator *pAllocator, BOOL fDynamicOnly)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
} CONTRACTL_END;
DomainCodeHeapList *pList = NULL;
DomainCodeHeapList **ppList = NULL;
int count = 0;
// get the appropriate list of heaps
// pMD is NULL for NGen modules during Module::LoadTokenTables
if (fDynamicOnly || (pInfo != NULL && pInfo->IsDynamicDomain()))
{
ppList = m_DynamicDomainCodeHeaps.Table();
count = m_DynamicDomainCodeHeaps.Count();
}
else
{
ppList = m_DomainCodeHeaps.Table();
count = m_DomainCodeHeaps.Count();
}
// this is a virtual call - pull it out of the loop
BOOL fCanUnload = pAllocator->CanUnload();
// look for a DomainCodeHeapList
for (int i=0; i < count; i++)
{
if (ppList[i]->m_pAllocator == pAllocator ||
(!fCanUnload && !ppList[i]->m_pAllocator->CanUnload()))
{
pList = ppList[i];
break;
}
}
return pList;
}
bool EEJitManager::CanUseCodeHeap(CodeHeapRequestInfo *pInfo, HeapList *pCodeHeap)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
} CONTRACTL_END;
bool retVal = false;
if ((pInfo->m_loAddr == 0) && (pInfo->m_hiAddr == 0))
{
// We have no constraint so this non empty heap will be able to satisfy our request
if (pInfo->IsDynamicDomain())
{
_ASSERTE(pCodeHeap->reserveForJumpStubs == 0);
retVal = true;
}
else
{
BYTE * lastAddr = (BYTE *) pCodeHeap->startAddress + pCodeHeap->maxCodeHeapSize;
BYTE * loRequestAddr = (BYTE *) pCodeHeap->endAddress;
BYTE * hiRequestAddr = loRequestAddr + pInfo->getRequestSize() + BYTES_PER_BUCKET;
if (hiRequestAddr <= lastAddr - pCodeHeap->reserveForJumpStubs)
{
retVal = true;
}
}
}
else
{
// We also check to see if an allocation in this heap would satisfy
// the [loAddr..hiAddr] requirement
// Calculate the byte range that can ever be returned by
// an allocation in this HeapList element
//
BYTE * firstAddr = (BYTE *) pCodeHeap->startAddress;
BYTE * lastAddr = (BYTE *) pCodeHeap->startAddress + pCodeHeap->maxCodeHeapSize;
_ASSERTE(pCodeHeap->startAddress <= pCodeHeap->endAddress);
_ASSERTE(firstAddr <= lastAddr);
if (pInfo->IsDynamicDomain())
{
_ASSERTE(pCodeHeap->reserveForJumpStubs == 0);
// We check to see if every allocation in this heap
// will satisfy the [loAddr..hiAddr] requirement.
//
// Dynamic domains use a free list allocator,
// thus we can receive any address in the range
// when calling AllocMemory with a DynamicDomain
// [firstaddr .. lastAddr] must be entirely within
// [pInfo->m_loAddr .. pInfo->m_hiAddr]
//
if ((pInfo->m_loAddr <= firstAddr) &&
(lastAddr <= pInfo->m_hiAddr))
{
// This heap will always satisfy our constraint
retVal = true;
}
}
else // non-DynamicDomain
{
// Calculate the byte range that would be allocated for the
// next allocation request into [loRequestAddr..hiRequestAddr]
//
BYTE * loRequestAddr = (BYTE *) pCodeHeap->endAddress;
BYTE * hiRequestAddr = loRequestAddr + pInfo->getRequestSize() + BYTES_PER_BUCKET;
_ASSERTE(loRequestAddr <= hiRequestAddr);
// loRequestAddr and hiRequestAddr must be entirely within
// [pInfo->m_loAddr .. pInfo->m_hiAddr]
//
if ((pInfo->m_loAddr <= loRequestAddr) &&
(hiRequestAddr <= pInfo->m_hiAddr))
{
// Additionally hiRequestAddr must also be less than or equal to lastAddr.
// If throwOnOutOfMemoryWithinRange is not set, conserve reserveForJumpStubs until when it is really needed.
if (hiRequestAddr <= lastAddr - (pInfo->getThrowOnOutOfMemoryWithinRange() ? 0 : pCodeHeap->reserveForJumpStubs))
{
// This heap will be able to satisfy our constraint
retVal = true;
}
}
}
}
return retVal;
}
EEJitManager::DomainCodeHeapList * EEJitManager::CreateCodeHeapList(CodeHeapRequestInfo *pInfo)
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
} CONTRACTL_END;
NewHolder<DomainCodeHeapList> pNewList(new DomainCodeHeapList());
pNewList->m_pAllocator = pInfo->m_pAllocator;
DomainCodeHeapList **ppList = NULL;
if (pInfo->IsDynamicDomain())
ppList = m_DynamicDomainCodeHeaps.AppendThrowing();
else
ppList = m_DomainCodeHeaps.AppendThrowing();
*ppList = pNewList;
return pNewList.Extract();
}
LoaderHeap *EEJitManager::GetJitMetaHeap(MethodDesc *pMD)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
LoaderAllocator *pAllocator = pMD->GetLoaderAllocator();
_ASSERTE(pAllocator);
return pAllocator->GetLowFrequencyHeap();
}
BYTE* EEJitManager::allocGCInfo(CodeHeader* pCodeHeader, DWORD blockSize, size_t * pAllocationSize)
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
MethodDesc* pMD = pCodeHeader->GetMethodDesc();
// sadly for light code gen I need the check in here. We should change GetJitMetaHeap
if (pMD->IsLCGMethod())
{
CrstHolder ch(&m_CodeHeapCritSec);
pCodeHeader->SetGCInfo((BYTE*)(void*)pMD->AsDynamicMethodDesc()->GetResolver()->GetJitMetaHeap()->New(blockSize));
}
else
{
pCodeHeader->SetGCInfo((BYTE*) (void*)GetJitMetaHeap(pMD)->AllocMem(S_SIZE_T(blockSize)));
}
_ASSERTE(pCodeHeader->GetGCInfo()); // AllocMem throws if there's not enough memory
* pAllocationSize = blockSize; // Store the allocation size so we can backout later.
return(pCodeHeader->GetGCInfo());
}
void* EEJitManager::allocEHInfoRaw(CodeHeader* pCodeHeader, DWORD blockSize, size_t * pAllocationSize)
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
MethodDesc* pMD = pCodeHeader->GetMethodDesc();
void * mem = NULL;
// sadly for light code gen I need the check in here. We should change GetJitMetaHeap
if (pMD->IsLCGMethod())
{
CrstHolder ch(&m_CodeHeapCritSec);
mem = (void*)pMD->AsDynamicMethodDesc()->GetResolver()->GetJitMetaHeap()->New(blockSize);
}
else
{
mem = (void*)GetJitMetaHeap(pMD)->AllocMem(S_SIZE_T(blockSize));
}
_ASSERTE(mem); // AllocMem throws if there's not enough memory
* pAllocationSize = blockSize; // Store the allocation size so we can backout later.
return(mem);
}
EE_ILEXCEPTION* EEJitManager::allocEHInfo(CodeHeader* pCodeHeader, unsigned numClauses, size_t * pAllocationSize)
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
// Note - pCodeHeader->phdrJitEHInfo - sizeof(size_t) contains the number of EH clauses
DWORD temp = EE_ILEXCEPTION::Size(numClauses);
DWORD blockSize = 0;
if (!ClrSafeInt<DWORD>::addition(temp, sizeof(size_t), blockSize))
COMPlusThrowOM();
BYTE *EHInfo = (BYTE*)allocEHInfoRaw(pCodeHeader, blockSize, pAllocationSize);
pCodeHeader->SetEHInfo((EE_ILEXCEPTION*) (EHInfo + sizeof(size_t)));
pCodeHeader->GetEHInfo()->Init(numClauses);
*((size_t *)EHInfo) = numClauses;
return(pCodeHeader->GetEHInfo());
}
JumpStubBlockHeader * EEJitManager::allocJumpStubBlock(MethodDesc* pMD, DWORD numJumps,
BYTE * loAddr, BYTE * hiAddr,
LoaderAllocator *pLoaderAllocator,
bool throwOnOutOfMemoryWithinRange)
{
CONTRACT(JumpStubBlockHeader *) {
THROWS;
GC_NOTRIGGER;
PRECONDITION(loAddr < hiAddr);
PRECONDITION(pLoaderAllocator != NULL);
POSTCONDITION((RETVAL != NULL) || !throwOnOutOfMemoryWithinRange);
} CONTRACT_END;
_ASSERTE((sizeof(JumpStubBlockHeader) % CODE_SIZE_ALIGN) == 0);
size_t blockSize = sizeof(JumpStubBlockHeader) + (size_t) numJumps * BACK_TO_BACK_JUMP_ALLOCATE_SIZE;
HeapList *pCodeHeap = NULL;
CodeHeapRequestInfo requestInfo(pMD, pLoaderAllocator, loAddr, hiAddr);
requestInfo.setThrowOnOutOfMemoryWithinRange(throwOnOutOfMemoryWithinRange);
TADDR mem;
ExecutableWriterHolderNoLog<JumpStubBlockHeader> blockWriterHolder;
// Scope the lock
{
CrstHolder ch(&m_CodeHeapCritSec);
mem = (TADDR) allocCodeRaw(&requestInfo, sizeof(CodeHeader), blockSize, CODE_SIZE_ALIGN, &pCodeHeap);
if (mem == NULL)
{
_ASSERTE(!throwOnOutOfMemoryWithinRange);
RETURN(NULL);
}
// CodeHeader comes immediately before the block
CodeHeader * pCodeHdr = (CodeHeader *) (mem - sizeof(CodeHeader));
ExecutableWriterHolder<CodeHeader> codeHdrWriterHolder(pCodeHdr, sizeof(CodeHeader));
codeHdrWriterHolder.GetRW()->SetStubCodeBlockKind(STUB_CODE_BLOCK_JUMPSTUB);
NibbleMapSetUnlocked(pCodeHeap, mem, TRUE);
blockWriterHolder.AssignExecutableWriterHolder((JumpStubBlockHeader *)mem, sizeof(JumpStubBlockHeader));
_ASSERTE(IS_ALIGNED(blockWriterHolder.GetRW(), CODE_SIZE_ALIGN));
}
blockWriterHolder.GetRW()->m_next = NULL;
blockWriterHolder.GetRW()->m_used = 0;
blockWriterHolder.GetRW()->m_allocated = numJumps;
if (pMD && pMD->IsLCGMethod())
blockWriterHolder.GetRW()->SetHostCodeHeap(static_cast<HostCodeHeap*>(pCodeHeap->pHeap));
else
blockWriterHolder.GetRW()->SetLoaderAllocator(pLoaderAllocator);
LOG((LF_JIT, LL_INFO1000, "Allocated new JumpStubBlockHeader for %d stubs at" FMT_ADDR " in loader allocator " FMT_ADDR "\n",
numJumps, DBG_ADDR(mem) , DBG_ADDR(pLoaderAllocator) ));
RETURN((JumpStubBlockHeader*)mem);
}
void * EEJitManager::allocCodeFragmentBlock(size_t blockSize, unsigned alignment, LoaderAllocator *pLoaderAllocator, StubCodeBlockKind kind)
{
CONTRACT(void *) {
THROWS;
GC_NOTRIGGER;
PRECONDITION(pLoaderAllocator != NULL);
POSTCONDITION(CheckPointer(RETVAL));
} CONTRACT_END;
HeapList *pCodeHeap = NULL;
CodeHeapRequestInfo requestInfo(NULL, pLoaderAllocator, NULL, NULL);
#ifdef TARGET_AMD64
// CodeFragments are pretty much always Precodes that may need to be patched with jump stubs at some point in future
// We will assume the worst case that every FixupPrecode will need to be patched and reserve the jump stubs accordingly
requestInfo.setReserveForJumpStubs((blockSize / 8) * JUMP_ALLOCATE_SIZE);
#endif
TADDR mem;
// Scope the lock
{
CrstHolder ch(&m_CodeHeapCritSec);
mem = (TADDR) allocCodeRaw(&requestInfo, sizeof(CodeHeader), blockSize, alignment, &pCodeHeap);
// CodeHeader comes immediately before the block
CodeHeader * pCodeHdr = (CodeHeader *) (mem - sizeof(CodeHeader));
ExecutableWriterHolder<CodeHeader> codeHdrWriterHolder(pCodeHdr, sizeof(CodeHeader));
codeHdrWriterHolder.GetRW()->SetStubCodeBlockKind(kind);
NibbleMapSetUnlocked(pCodeHeap, mem, TRUE);
// Record the jump stub reservation
pCodeHeap->reserveForJumpStubs += requestInfo.getReserveForJumpStubs();
}
RETURN((void *)mem);
}
#endif // !DACCESS_COMPILE
GCInfoToken EEJitManager::GetGCInfoToken(const METHODTOKEN& MethodToken)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
HOST_NOCALLS;
SUPPORTS_DAC;
} CONTRACTL_END;
// The JIT-ed code always has the current version of GCInfo
return{ GetCodeHeader(MethodToken)->GetGCInfo(), GCINFO_VERSION };
}
// creates an enumeration and returns the number of EH clauses
unsigned EEJitManager::InitializeEHEnumeration(const METHODTOKEN& MethodToken, EH_CLAUSE_ENUMERATOR* pEnumState)
{
LIMITED_METHOD_CONTRACT;
EE_ILEXCEPTION * EHInfo = GetCodeHeader(MethodToken)->GetEHInfo();
pEnumState->iCurrentPos = 0; // since the EH info is not compressed, the clause number is used to do the enumeration
pEnumState->pExceptionClauseArray = NULL;
if (!EHInfo)
return 0;
pEnumState->pExceptionClauseArray = dac_cast<TADDR>(EHInfo->EHClause(0));
return *(dac_cast<PTR_unsigned>(dac_cast<TADDR>(EHInfo) - sizeof(size_t)));
}
PTR_EXCEPTION_CLAUSE_TOKEN EEJitManager::GetNextEHClause(EH_CLAUSE_ENUMERATOR* pEnumState,
EE_ILEXCEPTION_CLAUSE* pEHClauseOut)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
unsigned iCurrentPos = pEnumState->iCurrentPos;
pEnumState->iCurrentPos++;
EE_ILEXCEPTION_CLAUSE* pClause = &(dac_cast<PTR_EE_ILEXCEPTION_CLAUSE>(pEnumState->pExceptionClauseArray)[iCurrentPos]);
*pEHClauseOut = *pClause;
return dac_cast<PTR_EXCEPTION_CLAUSE_TOKEN>(pClause);
}
#ifndef DACCESS_COMPILE
TypeHandle EEJitManager::ResolveEHClause(EE_ILEXCEPTION_CLAUSE* pEHClause,
CrawlFrame *pCf)
{
// We don't want to use a runtime contract here since this codepath is used during
// the processing of a hard SO. Contracts use a significant amount of stack
// which we can't afford for those cases.
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
_ASSERTE(NULL != pCf);
_ASSERTE(NULL != pEHClause);
_ASSERTE(IsTypedHandler(pEHClause));
TypeHandle typeHnd = TypeHandle();
mdToken typeTok = mdTokenNil;
// CachedTypeHandle's are filled in at JIT time, and not cached when accessed multiple times
if (HasCachedTypeHandle(pEHClause))
{
return TypeHandle::FromPtr(pEHClause->TypeHandle);
}
else
{
typeTok = pEHClause->ClassToken;
}
MethodDesc* pMD = pCf->GetFunction();
Module* pModule = pMD->GetModule();
PREFIX_ASSUME(pModule != NULL);
SigTypeContext typeContext(pMD);
return ClassLoader::LoadTypeDefOrRefOrSpecThrowing(pModule, typeTok, &typeContext,
ClassLoader::ReturnNullIfNotFound);
}
void EEJitManager::RemoveJitData (CodeHeader * pCHdr, size_t GCinfo_len, size_t EHinfo_len)
{
CONTRACTL {
NOTHROW;
GC_TRIGGERS;
} CONTRACTL_END;
MethodDesc* pMD = pCHdr->GetMethodDesc();
if (pMD->IsLCGMethod()) {
void * codeStart = (pCHdr + 1);
{
CrstHolder ch(&m_CodeHeapCritSec);
LCGMethodResolver * pResolver = pMD->AsDynamicMethodDesc()->GetLCGMethodResolver();
// Clear the pointer only if it matches what we are about to free.
// There can be cases where the JIT is reentered and we JITed the method multiple times.
if (pResolver->m_recordCodePointer == codeStart)
pResolver->m_recordCodePointer = NULL;
}
#if defined(TARGET_AMD64)
// Remove the unwind information (if applicable)
UnwindInfoTable::UnpublishUnwindInfoForMethod((TADDR)codeStart);
#endif // defined(TARGET_AMD64)
HostCodeHeap* pHeap = HostCodeHeap::GetCodeHeap((TADDR)codeStart);
FreeCodeMemory(pHeap, codeStart);
// We are leaking GCInfo and EHInfo. They will be freed once the dynamic method is destroyed.
return;
}
{
CrstHolder ch(&m_CodeHeapCritSec);
HeapList *pHp = GetCodeHeapList();
while (pHp && ((pHp->startAddress > (TADDR)pCHdr) ||
(pHp->endAddress < (TADDR)pCHdr + sizeof(CodeHeader))))
{
pHp = pHp->GetNext();
}
_ASSERTE(pHp && pHp->pHdrMap);
// Better to just return than AV?
if (pHp == NULL)
return;
NibbleMapSetUnlocked(pHp, (TADDR)(pCHdr + 1), FALSE);
}
// Backout the GCInfo
if (GCinfo_len > 0) {
GetJitMetaHeap(pMD)->BackoutMem(pCHdr->GetGCInfo(), GCinfo_len);
}
// Backout the EHInfo
BYTE *EHInfo = (BYTE *)pCHdr->GetEHInfo();
if (EHInfo) {
EHInfo -= sizeof(size_t);
_ASSERTE(EHinfo_len>0);
GetJitMetaHeap(pMD)->BackoutMem(EHInfo, EHinfo_len);
}
// <TODO>
// TODO: Although we have backout the GCInfo and EHInfo, we haven't actually backout the
// code buffer itself. As a result, we might leak the CodeHeap if jitting fails after
// the code buffer is allocated.
//
// However, it appears non-trivial to fix this.
// Here are some of the reasons:
// (1) AllocCode calls in AllocCodeRaw to alloc code buffer in the CodeHeap. The exact size
// of the code buffer is not known until the alignment is calculated deep on the stack.
// (2) AllocCodeRaw is called in 3 different places. We might need to remember the
// information for these places.
// (3) AllocCodeRaw might create a new CodeHeap. We should remember exactly which
// CodeHeap is used to allocate the code buffer.
//
// Fortunately, this is not a severe leak since the CodeHeap will be reclaimed on appdomain unload.
//
// </TODO>
return;
}
// appdomain is being unloaded, so delete any data associated with it. We have to do this in two stages.
// On the first stage, we remove the elements from the list. On the second stage, which occurs after a GC
// we know that only threads who were in preemptive mode prior to the GC could possibly still be looking
// at an element that is about to be deleted. All such threads are guarded with a reader count, so if the
// count is 0, we can safely delete, otherwise we must add to the cleanup list to be deleted later. We know
// there can only be one unload at a time, so we can use a single var to hold the unlinked, but not deleted,
// elements.
void EEJitManager::Unload(LoaderAllocator *pAllocator)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
CrstHolder ch(&m_CodeHeapCritSec);
DomainCodeHeapList **ppList = m_DomainCodeHeaps.Table();
int count = m_DomainCodeHeaps.Count();
for (int i=0; i < count; i++) {
if (ppList[i]->m_pAllocator== pAllocator) {
DomainCodeHeapList *pList = ppList[i];
m_DomainCodeHeaps.DeleteByIndex(i);
// pHeapList is allocated in pHeap, so only need to delete the LoaderHeap itself
count = pList->m_CodeHeapList.Count();
for (i=0; i < count; i++) {
HeapList *pHeapList = pList->m_CodeHeapList[i];
DeleteCodeHeap(pHeapList);
}
// this is ok to do delete as anyone accessing the DomainCodeHeapList structure holds the critical section.
delete pList;
break;
}
}
ppList = m_DynamicDomainCodeHeaps.Table();
count = m_DynamicDomainCodeHeaps.Count();
for (int i=0; i < count; i++) {
if (ppList[i]->m_pAllocator== pAllocator) {
DomainCodeHeapList *pList = ppList[i];
m_DynamicDomainCodeHeaps.DeleteByIndex(i);
// pHeapList is allocated in pHeap, so only need to delete the CodeHeap itself
count = pList->m_CodeHeapList.Count();
for (i=0; i < count; i++) {
HeapList *pHeapList = pList->m_CodeHeapList[i];
// m_DynamicDomainCodeHeaps should only contain HostCodeHeap.
RemoveFromCleanupList(static_cast<HostCodeHeap*>(pHeapList->pHeap));
DeleteCodeHeap(pHeapList);
}
// this is ok to do delete as anyone accessing the DomainCodeHeapList structure holds the critical section.
delete pList;
break;
}
}
ExecutableAllocator::ResetLazyPreferredRangeHint();
}
EEJitManager::DomainCodeHeapList::DomainCodeHeapList()
{
LIMITED_METHOD_CONTRACT;
m_pAllocator = NULL;
}
EEJitManager::DomainCodeHeapList::~DomainCodeHeapList()
{
LIMITED_METHOD_CONTRACT;
}
void EEJitManager::RemoveCodeHeapFromDomainList(CodeHeap *pHeap, LoaderAllocator *pAllocator)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
} CONTRACTL_END;
// get the AppDomain heap list for pAllocator in m_DynamicDomainCodeHeaps
DomainCodeHeapList *pList = GetCodeHeapList(NULL, pAllocator, TRUE);
// go through the heaps and find and remove pHeap
int count = pList->m_CodeHeapList.Count();
for (int i = 0; i < count; i++) {
HeapList *pHeapList = pList->m_CodeHeapList[i];
if (pHeapList->pHeap == pHeap) {
// found the heap to remove. If this is the only heap we remove the whole DomainCodeHeapList
// otherwise we just remove this heap
if (count == 1) {
m_DynamicDomainCodeHeaps.Delete(pList);
delete pList;
}
else
pList->m_CodeHeapList.Delete(i);
// if this heaplist is cached in the loader allocator, we must clear it
if (pAllocator->m_pLastUsedDynamicCodeHeap == ((void *) pHeapList))
{
pAllocator->m_pLastUsedDynamicCodeHeap = NULL;
}
break;
}
}
}
void EEJitManager::FreeCodeMemory(HostCodeHeap *pCodeHeap, void * codeStart)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
CrstHolder ch(&m_CodeHeapCritSec);
// FreeCodeMemory is only supported on LCG methods,
// so pCodeHeap can only be a HostCodeHeap.
// clean up the NibbleMap
NibbleMapSetUnlocked(pCodeHeap->m_pHeapList, (TADDR)codeStart, FALSE);
// The caller of this method doesn't call HostCodeHeap->FreeMemForCode
// directly because the operation should be protected by m_CodeHeapCritSec.
pCodeHeap->FreeMemForCode(codeStart);
}
void ExecutionManager::CleanupCodeHeaps()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE (g_fProcessDetach || (GCHeapUtilities::IsGCInProgress() && ::IsGCThread()));
GetEEJitManager()->CleanupCodeHeaps();
}
void EEJitManager::CleanupCodeHeaps()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE (g_fProcessDetach || (GCHeapUtilities::IsGCInProgress() && ::IsGCThread()));
// Quick out, don't even take the lock if we have not cleanup to do.
// This is important because ETW takes the CodeHeapLock when it is doing
// rundown, and if there are many JIT compiled methods, this can take a while.
// Because cleanup is called synchronously before a GC, this means GCs get
// blocked while ETW is doing rundown. By not taking the lock we avoid
// this stall most of the time since cleanup is rare, and ETW rundown is rare
// the likelihood of both is very very rare.
if (m_cleanupList == NULL)
return;
CrstHolder ch(&m_CodeHeapCritSec);
if (m_cleanupList == NULL)
return;
HostCodeHeap *pHeap = m_cleanupList;
m_cleanupList = NULL;
while (pHeap)
{
HostCodeHeap *pNextHeap = pHeap->m_pNextHeapToRelease;
DWORD allocCount = pHeap->m_AllocationCount;
if (allocCount == 0)
{
LOG((LF_BCL, LL_INFO100, "Level2 - Destryoing CodeHeap [0x%p, vt(0x%x)] - ref count 0\n", pHeap, *(size_t*)pHeap));
RemoveCodeHeapFromDomainList(pHeap, pHeap->m_pAllocator);
DeleteCodeHeap(pHeap->m_pHeapList);
}
else
{
LOG((LF_BCL, LL_INFO100, "Level2 - Restoring CodeHeap [0x%p, vt(0x%x)] - ref count %d\n", pHeap, *(size_t*)pHeap, allocCount));
}
pHeap = pNextHeap;
}
}
void EEJitManager::RemoveFromCleanupList(HostCodeHeap *pCodeHeap)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
} CONTRACTL_END;
HostCodeHeap *pHeap = m_cleanupList;
HostCodeHeap *pPrevHeap = NULL;
while (pHeap)
{
if (pHeap == pCodeHeap)
{
if (pPrevHeap)
{
// remove current heap from list
pPrevHeap->m_pNextHeapToRelease = pHeap->m_pNextHeapToRelease;
}
else
{
m_cleanupList = pHeap->m_pNextHeapToRelease;
}
break;
}
pPrevHeap = pHeap;
pHeap = pHeap->m_pNextHeapToRelease;
}
}
void EEJitManager::AddToCleanupList(HostCodeHeap *pCodeHeap)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
} CONTRACTL_END;
// it may happen that the current heap count goes to 0 and later on, before it is destroyed, it gets reused
// for another dynamic method.
// It's then possible that the ref count reaches 0 multiple times. If so we simply don't add it again
// Also on cleanup we check the ref count is actually 0.
HostCodeHeap *pHeap = m_cleanupList;
while (pHeap)
{
if (pHeap == pCodeHeap)
{
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p, vt(0x%x)] - Already in list\n", pCodeHeap, *(size_t*)pCodeHeap));
break;
}
pHeap = pHeap->m_pNextHeapToRelease;
}
if (pHeap == NULL)
{
pCodeHeap->m_pNextHeapToRelease = m_cleanupList;
m_cleanupList = pCodeHeap;
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p, vt(0x%x)] - ref count %d - Adding to cleanup list\n", pCodeHeap, *(size_t*)pCodeHeap, pCodeHeap->m_AllocationCount));
}
}
void EEJitManager::DeleteCodeHeap(HeapList *pHeapList)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
} CONTRACTL_END;
HeapList *pHp = GetCodeHeapList();
if (pHp == pHeapList)
m_pCodeHeap = pHp->GetNext();
else
{
HeapList *pHpNext = pHp->GetNext();
while (pHpNext != pHeapList)
{
pHp = pHpNext;
_ASSERTE(pHp != NULL); // should always find the HeapList
pHpNext = pHp->GetNext();
}
pHp->SetNext(pHeapList->GetNext());
}
DeleteEEFunctionTable((PVOID)pHeapList->GetModuleBase());
ExecutionManager::DeleteRange((TADDR)pHeapList->GetModuleBase());
LOG((LF_JIT, LL_INFO100, "DeleteCodeHeap start" FMT_ADDR "end" FMT_ADDR "\n",
(const BYTE*)pHeapList->startAddress,
(const BYTE*)pHeapList->endAddress ));
CodeHeap* pHeap = pHeapList->pHeap;
delete pHeap;
delete pHeapList;
}
#endif // #ifndef DACCESS_COMPILE
static CodeHeader * GetCodeHeaderFromDebugInfoRequest(const DebugInfoRequest & request)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
TADDR address = (TADDR) request.GetStartAddress();
_ASSERTE(address != NULL);
CodeHeader * pHeader = dac_cast<PTR_CodeHeader>(address & ~3) - 1;
_ASSERTE(pHeader != NULL);
return pHeader;
}
//-----------------------------------------------------------------------------
// Get vars from Jit Store
//-----------------------------------------------------------------------------
BOOL EEJitManager::GetBoundariesAndVars(
const DebugInfoRequest & request,
IN FP_IDS_NEW fpNew, IN void * pNewData,
OUT ULONG32 * pcMap,
OUT ICorDebugInfo::OffsetMapping **ppMap,
OUT ULONG32 * pcVars,
OUT ICorDebugInfo::NativeVarInfo **ppVars)
{
CONTRACTL {
THROWS; // on OOM.
GC_NOTRIGGER; // getting vars shouldn't trigger
SUPPORTS_DAC;
} CONTRACTL_END;
CodeHeader * pHdr = GetCodeHeaderFromDebugInfoRequest(request);
_ASSERTE(pHdr != NULL);
PTR_BYTE pDebugInfo = pHdr->GetDebugInfo();
// No header created, which means no jit information is available.
if (pDebugInfo == NULL)
return FALSE;
#ifdef FEATURE_ON_STACK_REPLACEMENT
BOOL hasFlagByte = TRUE;
#else
BOOL hasFlagByte = FALSE;
#endif
if (m_storeRichDebugInfo)
{
hasFlagByte = TRUE;
}
// Uncompress. This allocates memory and may throw.
CompressDebugInfo::RestoreBoundariesAndVars(
fpNew, pNewData, // allocators
pDebugInfo, // input
pcMap, ppMap, // output
pcVars, ppVars, // output
hasFlagByte
);
return TRUE;
}
BOOL EEJitManager::GetRichDebugInfo(
const DebugInfoRequest& request,
IN FP_IDS_NEW fpNew, IN void* pNewData,
OUT ICorDebugInfo::InlineTreeNode** ppInlineTree,
OUT ULONG32* pNumInlineTree,
OUT ICorDebugInfo::RichOffsetMapping** ppRichMappings,
OUT ULONG32* pNumRichMappings)
{
CONTRACTL {
THROWS; // on OOM.
GC_NOTRIGGER; // getting debug info shouldn't trigger
SUPPORTS_DAC;
} CONTRACTL_END;
if (!m_storeRichDebugInfo)
{
return FALSE;
}
CodeHeader * pHdr = GetCodeHeaderFromDebugInfoRequest(request);
_ASSERTE(pHdr != NULL);
PTR_BYTE pDebugInfo = pHdr->GetDebugInfo();
// No header created, which means no debug information is available.
if (pDebugInfo == NULL)
return FALSE;
CompressDebugInfo::RestoreRichDebugInfo(
fpNew, pNewData,
pDebugInfo,
ppInlineTree, pNumInlineTree,
ppRichMappings, pNumRichMappings);
return TRUE;
}
#ifdef DACCESS_COMPILE
void CodeHeader::EnumMemoryRegions(CLRDataEnumMemoryFlags flags, IJitManager* pJitMan)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
}
CONTRACTL_END;
DAC_ENUM_DTHIS();
#ifdef USE_INDIRECT_CODEHEADER
this->pRealCodeHeader.EnumMem();
#endif // USE_INDIRECT_CODEHEADER
#ifdef FEATURE_ON_STACK_REPLACEMENT
BOOL hasFlagByte = TRUE;
#else
BOOL hasFlagByte = FALSE;
#endif
if (this->GetDebugInfo() != NULL)
{
CompressDebugInfo::EnumMemoryRegions(flags, this->GetDebugInfo(), hasFlagByte);
}
}
//-----------------------------------------------------------------------------
// Enumerate for minidumps.
//-----------------------------------------------------------------------------
void EEJitManager::EnumMemoryRegionsForMethodDebugInfo(CLRDataEnumMemoryFlags flags, MethodDesc * pMD)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
}
CONTRACTL_END;
DebugInfoRequest request;
PCODE addrCode = pMD->GetNativeCode();
request.InitFromStartingAddr(pMD, addrCode);
CodeHeader * pHeader = GetCodeHeaderFromDebugInfoRequest(request);
pHeader->EnumMemoryRegions(flags, NULL);
}
#endif // DACCESS_COMPILE
PCODE EEJitManager::GetCodeAddressForRelOffset(const METHODTOKEN& MethodToken, DWORD relOffset)
{
WRAPPER_NO_CONTRACT;
CodeHeader * pHeader = GetCodeHeader(MethodToken);
return pHeader->GetCodeStartAddress() + relOffset;
}
BOOL EEJitManager::JitCodeToMethodInfo(
RangeSection * pRangeSection,
PCODE currentPC,
MethodDesc ** ppMethodDesc,
EECodeInfo * pCodeInfo)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
_ASSERTE(pRangeSection != NULL);
TADDR start = dac_cast<PTR_EEJitManager>(pRangeSection->pjit)->FindMethodCode(pRangeSection, currentPC);
if (start == NULL)
return FALSE;
CodeHeader * pCHdr = PTR_CodeHeader(start - sizeof(CodeHeader));
if (pCHdr->IsStubCodeBlock())
return FALSE;
_ASSERTE(pCHdr->GetMethodDesc()->SanityCheck());
if (pCodeInfo)
{
pCodeInfo->m_methodToken = METHODTOKEN(pRangeSection, dac_cast<TADDR>(pCHdr));
// This can be counted on for Jitted code. For NGEN code in the case
// where we have hot/cold splitting this isn't valid and we need to
// take into account cold code.
pCodeInfo->m_relOffset = (DWORD)(PCODEToPINSTR(currentPC) - pCHdr->GetCodeStartAddress());
#ifdef FEATURE_EH_FUNCLETS
// Computed lazily by code:EEJitManager::LazyGetFunctionEntry
pCodeInfo->m_pFunctionEntry = NULL;
#endif
}
if (ppMethodDesc)
{
*ppMethodDesc = pCHdr->GetMethodDesc();
}
return TRUE;
}
StubCodeBlockKind EEJitManager::GetStubCodeBlockKind(RangeSection * pRangeSection, PCODE currentPC)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
TADDR start = dac_cast<PTR_EEJitManager>(pRangeSection->pjit)->FindMethodCode(pRangeSection, currentPC);
if (start == NULL)
return STUB_CODE_BLOCK_NOCODE;
CodeHeader * pCHdr = PTR_CodeHeader(start - sizeof(CodeHeader));
return pCHdr->IsStubCodeBlock() ? pCHdr->GetStubCodeBlockKind() : STUB_CODE_BLOCK_MANAGED;
}
TADDR EEJitManager::FindMethodCode(PCODE currentPC)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
RangeSection * pRS = ExecutionManager::FindCodeRange(currentPC, ExecutionManager::GetScanFlags());
if (pRS == NULL || (pRS->flags & RangeSection::RANGE_SECTION_CODEHEAP) == 0)
return STUB_CODE_BLOCK_NOCODE;
return dac_cast<PTR_EEJitManager>(pRS->pjit)->FindMethodCode(pRS, currentPC);
}
// Finds the header corresponding to the code at offset "delta".
// Returns NULL if there is no header for the given "delta"
TADDR EEJitManager::FindMethodCode(RangeSection * pRangeSection, PCODE currentPC)
{
LIMITED_METHOD_DAC_CONTRACT;
_ASSERTE(pRangeSection != NULL);
HeapList *pHp = dac_cast<PTR_HeapList>(pRangeSection->pHeapListOrZapModule);
if ((currentPC < pHp->startAddress) ||
(currentPC > pHp->endAddress))
{
return NULL;
}
TADDR base = pHp->mapBase;
TADDR delta = currentPC - base;
PTR_DWORD pMap = pHp->pHdrMap;
PTR_DWORD pMapStart = pMap;
DWORD tmp;
size_t startPos = ADDR2POS(delta); // align to 32byte buckets
// ( == index into the array of nibbles)
DWORD offset = ADDR2OFFS(delta); // this is the offset inside the bucket + 1
_ASSERTE(offset == (offset & NIBBLE_MASK));
pMap += (startPos >> LOG2_NIBBLES_PER_DWORD); // points to the proper DWORD of the map
// get DWORD and shift down our nibble
PREFIX_ASSUME(pMap != NULL);
tmp = VolatileLoadWithoutBarrier<DWORD>(pMap) >> POS2SHIFTCOUNT(startPos);
if ((tmp & NIBBLE_MASK) && ((tmp & NIBBLE_MASK) <= offset) )
{
return base + POSOFF2ADDR(startPos, tmp & NIBBLE_MASK);
}
// Is there a header in the remainder of the DWORD ?
tmp = tmp >> NIBBLE_SIZE;
if (tmp)
{
startPos--;
while (!(tmp & NIBBLE_MASK))
{
tmp = tmp >> NIBBLE_SIZE;
startPos--;
}
return base + POSOFF2ADDR(startPos, tmp & NIBBLE_MASK);
}
// We skipped the remainder of the DWORD,
// so we must set startPos to the highest position of
// previous DWORD, unless we are already on the first DWORD
if (startPos < NIBBLES_PER_DWORD)
return NULL;
startPos = ((startPos >> LOG2_NIBBLES_PER_DWORD) << LOG2_NIBBLES_PER_DWORD) - 1;
// Skip "headerless" DWORDS
while (pMapStart < pMap && 0 == (tmp = VolatileLoadWithoutBarrier<DWORD>(--pMap)))
{
startPos -= NIBBLES_PER_DWORD;
}
// This helps to catch degenerate error cases. This relies on the fact that
// startPos cannot ever be bigger than MAX_UINT
if (((INT_PTR)startPos) < 0)
return NULL;
// Find the nibble with the header in the DWORD
while (startPos && !(tmp & NIBBLE_MASK))
{
tmp = tmp >> NIBBLE_SIZE;
startPos--;
}
if (startPos == 0 && tmp == 0)
return NULL;
return base + POSOFF2ADDR(startPos, tmp & NIBBLE_MASK);
}
#if !defined(DACCESS_COMPILE)
void EEJitManager::NibbleMapSet(HeapList * pHp, TADDR pCode, BOOL bSet)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
CrstHolder ch(&m_CodeHeapCritSec);
NibbleMapSetUnlocked(pHp, pCode, bSet);
}
void EEJitManager::NibbleMapSetUnlocked(HeapList * pHp, TADDR pCode, BOOL bSet)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
// Currently all callers to this method ensure EEJitManager::m_CodeHeapCritSec
// is held.
_ASSERTE(m_CodeHeapCritSec.OwnedByCurrentThread());
_ASSERTE(pCode >= pHp->mapBase);
size_t delta = pCode - pHp->mapBase;
size_t pos = ADDR2POS(delta);
DWORD value = bSet?ADDR2OFFS(delta):0;
DWORD index = (DWORD) (pos >> LOG2_NIBBLES_PER_DWORD);
DWORD mask = ~((DWORD) HIGHEST_NIBBLE_MASK >> ((pos & NIBBLES_PER_DWORD_MASK) << LOG2_NIBBLE_SIZE));
value = value << POS2SHIFTCOUNT(pos);
PTR_DWORD pMap = pHp->pHdrMap;
// assert that we don't overwrite an existing offset
// (it's a reset or it is empty)
_ASSERTE(!value || !((*(pMap+index))& ~mask));
// It is important for this update to be atomic. Synchronization would be required with FindMethodCode otherwise.
*(pMap+index) = ((*(pMap+index))&mask)|value;
}
#endif // !DACCESS_COMPILE
#if defined(FEATURE_EH_FUNCLETS)
// Note: This returns the root unwind record (the one that describes the prolog)
// in cases where there is fragmented unwind.
PTR_RUNTIME_FUNCTION EEJitManager::LazyGetFunctionEntry(EECodeInfo * pCodeInfo)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
if (!pCodeInfo->IsValid())
{
return NULL;
}
CodeHeader * pHeader = GetCodeHeader(pCodeInfo->GetMethodToken());
DWORD address = RUNTIME_FUNCTION__BeginAddress(pHeader->GetUnwindInfo(0)) + pCodeInfo->GetRelOffset();
// We need the module base address to calculate the end address of a function from the functionEntry.
// Thus, save it off right now.
TADDR baseAddress = pCodeInfo->GetModuleBase();
// NOTE: We could binary search here, if it would be helpful (e.g., large number of funclets)
for (UINT iUnwindInfo = 0; iUnwindInfo < pHeader->GetNumberOfUnwindInfos(); iUnwindInfo++)
{
PTR_RUNTIME_FUNCTION pFunctionEntry = pHeader->GetUnwindInfo(iUnwindInfo);
if (RUNTIME_FUNCTION__BeginAddress(pFunctionEntry) <= address && address < RUNTIME_FUNCTION__EndAddress(pFunctionEntry, baseAddress))
{
#if defined(EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS) && (defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64))
// If we might have fragmented unwind, and we're on ARM64/LoongArch64,
// make sure to returning the root record,
// as the trailing records don't have prolog unwind codes.
pFunctionEntry = FindRootEntry(pFunctionEntry, baseAddress);
#endif
return pFunctionEntry;
}
}
return NULL;
}
DWORD EEJitManager::GetFuncletStartOffsets(const METHODTOKEN& MethodToken, DWORD* pStartFuncletOffsets, DWORD dwLength)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
CodeHeader * pCH = GetCodeHeader(MethodToken);
TADDR moduleBase = JitTokenToModuleBase(MethodToken);
_ASSERTE(pCH->GetNumberOfUnwindInfos() >= 1);
DWORD parentBeginRva = RUNTIME_FUNCTION__BeginAddress(pCH->GetUnwindInfo(0));
DWORD nFunclets = 0;
for (COUNT_T iUnwindInfo = 1; iUnwindInfo < pCH->GetNumberOfUnwindInfos(); iUnwindInfo++)
{
PTR_RUNTIME_FUNCTION pFunctionEntry = pCH->GetUnwindInfo(iUnwindInfo);
#if defined(EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS)
if (IsFunctionFragment(moduleBase, pFunctionEntry))
{
// This is a fragment (not the funclet beginning); skip it
continue;
}
#endif // EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS
DWORD funcletBeginRva = RUNTIME_FUNCTION__BeginAddress(pFunctionEntry);
DWORD relParentOffsetToFunclet = funcletBeginRva - parentBeginRva;
if (nFunclets < dwLength)
pStartFuncletOffsets[nFunclets] = relParentOffsetToFunclet;
nFunclets++;
}
return nFunclets;
}
#if defined(DACCESS_COMPILE)
// This function is basically like RtlLookupFunctionEntry(), except that it works with DAC
// to read the function entries out of process. Also, it can only look up function entries
// inside mscorwks.dll, since DAC doesn't know anything about other unmanaged dll's.
void GetUnmanagedStackWalkInfo(IN ULONG64 ControlPc,
OUT UINT_PTR* pModuleBase,
OUT UINT_PTR* pFuncEntry)
{
WRAPPER_NO_CONTRACT;
if (pModuleBase)
{
*pModuleBase = NULL;
}
if (pFuncEntry)
{
*pFuncEntry = NULL;
}
PEDecoder peDecoder(DacGlobalBase());
SIZE_T baseAddr = dac_cast<TADDR>(peDecoder.GetBase());
SIZE_T cbSize = (SIZE_T)peDecoder.GetVirtualSize();
// Check if the control PC is inside mscorwks.
if ( (baseAddr <= ControlPc) &&
(ControlPc < (baseAddr + cbSize))
)
{
if (pModuleBase)
{
*pModuleBase = baseAddr;
}
if (pFuncEntry)
{
// Check if there is a static function table.
COUNT_T cbSize = 0;
TADDR pExceptionDir = peDecoder.GetDirectoryEntryData(IMAGE_DIRECTORY_ENTRY_EXCEPTION, &cbSize);
if (pExceptionDir != NULL)
{
// Do a binary search on the static function table of mscorwks.dll.
HRESULT hr = E_FAIL;
TADDR taFuncEntry;
T_RUNTIME_FUNCTION functionEntry;
DWORD dwLow = 0;
DWORD dwHigh = cbSize / sizeof(T_RUNTIME_FUNCTION);
DWORD dwMid = 0;
while (dwLow <= dwHigh)
{
dwMid = (dwLow + dwHigh) >> 1;
taFuncEntry = pExceptionDir + dwMid * sizeof(T_RUNTIME_FUNCTION);
hr = DacReadAll(taFuncEntry, &functionEntry, sizeof(functionEntry), false);
if (FAILED(hr))
{
return;
}
if (ControlPc < baseAddr + functionEntry.BeginAddress)
{
dwHigh = dwMid - 1;
}
else if (ControlPc >= baseAddr + RUNTIME_FUNCTION__EndAddress(&functionEntry, baseAddr))
{
dwLow = dwMid + 1;
}
else
{
_ASSERTE(pFuncEntry);
#ifdef _TARGET_AMD64_
// On amd64, match RtlLookupFunctionEntry behavior by resolving indirect function entries
// back to the associated owning function entry.
if ((functionEntry.UnwindData & RUNTIME_FUNCTION_INDIRECT) != 0)
{
DWORD dwRvaOfOwningFunctionEntry = (functionEntry.UnwindData & ~RUNTIME_FUNCTION_INDIRECT);
taFuncEntry = peDecoder.GetRvaData(dwRvaOfOwningFunctionEntry);
hr = DacReadAll(taFuncEntry, &functionEntry, sizeof(functionEntry), false);
if (FAILED(hr))
{
return;
}
_ASSERTE((functionEntry.UnwindData & RUNTIME_FUNCTION_INDIRECT) == 0);
}
#endif // _TARGET_AMD64_
*pFuncEntry = (UINT_PTR)(T_RUNTIME_FUNCTION*)PTR_RUNTIME_FUNCTION(taFuncEntry);
break;
}
}
if (dwLow > dwHigh)
{
_ASSERTE(*pFuncEntry == NULL);
}
}
}
}
}
#endif // DACCESS_COMPILE
extern "C" void GetRuntimeStackWalkInfo(IN ULONG64 ControlPc,
OUT UINT_PTR* pModuleBase,
OUT UINT_PTR* pFuncEntry)
{
WRAPPER_NO_CONTRACT;
BEGIN_PRESERVE_LAST_ERROR;
if (pModuleBase)
*pModuleBase = NULL;
if (pFuncEntry)
*pFuncEntry = NULL;
EECodeInfo codeInfo((PCODE)ControlPc);
if (!codeInfo.IsValid())
{
#if defined(DACCESS_COMPILE)
GetUnmanagedStackWalkInfo(ControlPc, pModuleBase, pFuncEntry);
#endif // DACCESS_COMPILE
goto Exit;
}
if (pModuleBase)
{
*pModuleBase = (UINT_PTR)codeInfo.GetModuleBase();
}
if (pFuncEntry)
{
*pFuncEntry = (UINT_PTR)(PT_RUNTIME_FUNCTION)codeInfo.GetFunctionEntry();
}
Exit:
;
END_PRESERVE_LAST_ERROR;
}
#endif // FEATURE_EH_FUNCLETS
#ifdef DACCESS_COMPILE
void EEJitManager::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
IJitManager::EnumMemoryRegions(flags);
//
// Save all of the code heaps.
//
HeapList* heap;
for (heap = m_pCodeHeap; heap; heap = heap->GetNext())
{
DacEnumHostDPtrMem(heap);
if (heap->pHeap.IsValid())
{
heap->pHeap->EnumMemoryRegions(flags);
}
DacEnumMemoryRegion(heap->startAddress, (ULONG32)
(heap->endAddress - heap->startAddress));
if (heap->pHdrMap.IsValid())
{
ULONG32 nibbleMapSize = (ULONG32)
HEAP2MAPSIZE(ROUND_UP_TO_PAGE(heap->maxCodeHeapSize));
DacEnumMemoryRegion(dac_cast<TADDR>(heap->pHdrMap), nibbleMapSize);
}
}
}
#endif // #ifdef DACCESS_COMPILE
#ifndef DACCESS_COMPILE
//*******************************************************
// Execution Manager
//*******************************************************
// Init statics
void ExecutionManager::Init()
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
m_JumpStubCrst.Init(CrstJumpStubCache, CrstFlags(CRST_UNSAFE_ANYMODE|CRST_DEBUGGER_THREAD));
m_RangeCrst.Init(CrstExecuteManRangeLock, CRST_UNSAFE_ANYMODE);
m_pDefaultCodeMan = new EECodeManager();
m_pEEJitManager = new EEJitManager();
#ifdef FEATURE_READYTORUN
m_pReadyToRunJitManager = new ReadyToRunJitManager();
#endif
}
#endif // #ifndef DACCESS_COMPILE
//**************************************************************************
RangeSection *
ExecutionManager::FindCodeRange(PCODE currentPC, ScanFlag scanFlag)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
if (currentPC == NULL)
return NULL;
if (scanFlag == ScanReaderLock)
return FindCodeRangeWithLock(currentPC);
return GetRangeSection(currentPC);
}
//**************************************************************************
NOINLINE // Make sure that the slow path with lock won't affect the fast path
RangeSection *
ExecutionManager::FindCodeRangeWithLock(PCODE currentPC)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
ReaderLockHolder rlh;
return GetRangeSection(currentPC);
}
//**************************************************************************
PCODE ExecutionManager::GetCodeStartAddress(PCODE currentPC)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(currentPC != NULL);
EECodeInfo codeInfo(currentPC);
if (!codeInfo.IsValid())
return NULL;
return PINSTRToPCODE(codeInfo.GetStartAddress());
}
//**************************************************************************
NativeCodeVersion ExecutionManager::GetNativeCodeVersion(PCODE currentPC)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END;
EECodeInfo codeInfo(currentPC);
return codeInfo.IsValid() ? codeInfo.GetNativeCodeVersion() : NativeCodeVersion();
}
//**************************************************************************
MethodDesc * ExecutionManager::GetCodeMethodDesc(PCODE currentPC)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
EECodeInfo codeInfo(currentPC);
if (!codeInfo.IsValid())
return NULL;
return codeInfo.GetMethodDesc();
}
//**************************************************************************
BOOL ExecutionManager::IsManagedCode(PCODE currentPC)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
if (currentPC == NULL)
return FALSE;
if (GetScanFlags() == ScanReaderLock)
return IsManagedCodeWithLock(currentPC);
return IsManagedCodeWorker(currentPC);
}
//**************************************************************************
NOINLINE // Make sure that the slow path with lock won't affect the fast path
BOOL ExecutionManager::IsManagedCodeWithLock(PCODE currentPC)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
ReaderLockHolder rlh;
return IsManagedCodeWorker(currentPC);
}
//**************************************************************************
BOOL ExecutionManager::IsManagedCode(PCODE currentPC, HostCallPreference hostCallPreference /*=AllowHostCalls*/, BOOL *pfFailedReaderLock /*=NULL*/)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
#ifdef DACCESS_COMPILE
return IsManagedCode(currentPC);
#else
if (hostCallPreference == AllowHostCalls)
{
return IsManagedCode(currentPC);
}
ReaderLockHolder rlh(hostCallPreference);
if (!rlh.Acquired())
{
_ASSERTE(pfFailedReaderLock != NULL);
*pfFailedReaderLock = TRUE;
return FALSE;
}
return IsManagedCodeWorker(currentPC);
#endif
}
//**************************************************************************
// Assumes that the ExecutionManager reader/writer lock is taken or that
// it is safe not to take it.
BOOL ExecutionManager::IsManagedCodeWorker(PCODE currentPC)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
// This may get called for arbitrary code addresses. Note that the lock is
// taken over the call to JitCodeToMethodInfo too so that nobody pulls out
// the range section from underneath us.
RangeSection * pRS = GetRangeSection(currentPC);
if (pRS == NULL)
return FALSE;
if (pRS->flags & RangeSection::RANGE_SECTION_CODEHEAP)
{
// Typically if we find a Jit Manager we are inside a managed method
// but on we could also be in a stub, so we check for that
// as well and we don't consider stub to be real managed code.
TADDR start = dac_cast<PTR_EEJitManager>(pRS->pjit)->FindMethodCode(pRS, currentPC);
if (start == NULL)
return FALSE;
CodeHeader * pCHdr = PTR_CodeHeader(start - sizeof(CodeHeader));
if (!pCHdr->IsStubCodeBlock())
return TRUE;
}
#ifdef FEATURE_READYTORUN
else
if (pRS->flags & RangeSection::RANGE_SECTION_READYTORUN)
{
if (dac_cast<PTR_ReadyToRunJitManager>(pRS->pjit)->JitCodeToMethodInfo(pRS, currentPC, NULL, NULL))
return TRUE;
}
#endif
return FALSE;
}
//**************************************************************************
// Assumes that it is safe not to take it the ExecutionManager reader/writer lock
BOOL ExecutionManager::IsReadyToRunCode(PCODE currentPC)
{
CONTRACTL{
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
// This may get called for arbitrary code addresses. Note that the lock is
// taken over the call to JitCodeToMethodInfo too so that nobody pulls out
// the range section from underneath us.
#ifdef FEATURE_READYTORUN
RangeSection * pRS = GetRangeSection(currentPC);
if (pRS != NULL && (pRS->flags & RangeSection::RANGE_SECTION_READYTORUN))
{
if (dac_cast<PTR_ReadyToRunJitManager>(pRS->pjit)->JitCodeToMethodInfo(pRS, currentPC, NULL, NULL))
return TRUE;
}
#endif
return FALSE;
}
#ifndef FEATURE_MERGE_JIT_AND_ENGINE
/*********************************************************************/
// This static method returns the name of the jit dll
//
LPCWSTR ExecutionManager::GetJitName()
{
STANDARD_VM_CONTRACT;
LPCWSTR pwzJitName = NULL;
// Try to obtain a name for the jit library from the env. variable
IfFailThrow(CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_JitName, const_cast<LPWSTR *>(&pwzJitName)));
if (NULL == pwzJitName)
{
pwzJitName = MAKEDLLNAME_W(W("clrjit"));
}
return pwzJitName;
}
#endif // !FEATURE_MERGE_JIT_AND_ENGINE
RangeSection* ExecutionManager::GetRangeSection(TADDR addr)
{
CONTRACTL {
NOTHROW;
HOST_NOCALLS;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
RangeSection * pHead = m_CodeRangeList;
if (pHead == NULL)
{
return NULL;
}
RangeSection *pCurr = pHead;
RangeSection *pLast = NULL;
#ifndef DACCESS_COMPILE
RangeSection *pLastUsedRS = (pCurr != NULL) ? pCurr->pLastUsed : NULL;
if (pLastUsedRS != NULL)
{
// positive case
if ((addr >= pLastUsedRS->LowAddress) &&
(addr < pLastUsedRS->HighAddress) )
{
return pLastUsedRS;
}
RangeSection * pNextAfterLastUsedRS = pLastUsedRS->pnext;
// negative case
if ((addr < pLastUsedRS->LowAddress) &&
(pNextAfterLastUsedRS == NULL || addr >= pNextAfterLastUsedRS->HighAddress))
{
return NULL;
}
}
#endif
while (pCurr != NULL)
{
// See if addr is in [pCurr->LowAddress .. pCurr->HighAddress)
if (pCurr->LowAddress <= addr)
{
// Since we are sorted, once pCurr->HighAddress is less than addr
// then all subsequence ones will also be lower, so we are done.
if (addr >= pCurr->HighAddress)
{
// we'll return NULL and put pLast into pLastUsed
pCurr = NULL;
}
else
{
// addr must be in [pCurr->LowAddress .. pCurr->HighAddress)
_ASSERTE((pCurr->LowAddress <= addr) && (addr < pCurr->HighAddress));
// Found the matching RangeSection
// we'll return pCurr and put it into pLastUsed
pLast = pCurr;
}
break;
}
pLast = pCurr;
pCurr = pCurr->pnext;
}
#ifndef DACCESS_COMPILE
// Cache pCurr as pLastUsed in the head node
// Unless we are on an MP system with many cpus
// where this sort of caching actually diminishes scaling during server GC
// due to many processors writing to a common location
if (g_SystemInfo.dwNumberOfProcessors < 4 || !GCHeapUtilities::IsServerHeap() || !GCHeapUtilities::IsGCInProgress())
pHead->pLastUsed = pLast;
#endif
return pCurr;
}
RangeSection* ExecutionManager::GetRangeSectionAndPrev(RangeSection *pHead, TADDR addr, RangeSection** ppPrev)
{
WRAPPER_NO_CONTRACT;
RangeSection *pCurr;
RangeSection *pPrev;
RangeSection *result = NULL;
for (pPrev = NULL, pCurr = pHead;
pCurr != NULL;
pPrev = pCurr, pCurr = pCurr->pnext)
{
// See if addr is in [pCurr->LowAddress .. pCurr->HighAddress)
if (pCurr->LowAddress > addr)
continue;
if (addr >= pCurr->HighAddress)
break;
// addr must be in [pCurr->LowAddress .. pCurr->HighAddress)
_ASSERTE((pCurr->LowAddress <= addr) && (addr < pCurr->HighAddress));
// Found the matching RangeSection
result = pCurr;
// Write back pPrev to ppPrev if it is non-null
if (ppPrev != NULL)
*ppPrev = pPrev;
break;
}
// If we failed to find a match write NULL to ppPrev if it is non-null
if ((ppPrev != NULL) && (result == NULL))
{
*ppPrev = NULL;
}
return result;
}
/* static */
PTR_Module ExecutionManager::FindZapModule(TADDR currentData)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
STATIC_CONTRACT_HOST_CALLS;
SUPPORTS_DAC;
}
CONTRACTL_END;
ReaderLockHolder rlh;
RangeSection * pRS = GetRangeSection(currentData);
if (pRS == NULL)
return NULL;
if (pRS->flags & RangeSection::RANGE_SECTION_CODEHEAP)
return NULL;
#ifdef FEATURE_READYTORUN
if (pRS->flags & RangeSection::RANGE_SECTION_READYTORUN)
return NULL;
#endif
return dac_cast<PTR_Module>(pRS->pHeapListOrZapModule);
}
/* static */
PTR_Module ExecutionManager::FindReadyToRunModule(TADDR currentData)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
STATIC_CONTRACT_HOST_CALLS;
SUPPORTS_DAC;
}
CONTRACTL_END;
#ifdef FEATURE_READYTORUN
ReaderLockHolder rlh;
RangeSection * pRS = GetRangeSection(currentData);
if (pRS == NULL)
return NULL;
if (pRS->flags & RangeSection::RANGE_SECTION_CODEHEAP)
return NULL;
if (pRS->flags & RangeSection::RANGE_SECTION_READYTORUN)
return dac_cast<PTR_Module>(pRS->pHeapListOrZapModule);;
return NULL;
#else
return NULL;
#endif
}
/* static */
PTR_Module ExecutionManager::FindModuleForGCRefMap(TADDR currentData)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
}
CONTRACTL_END;
RangeSection * pRS = FindCodeRange(currentData, ExecutionManager::GetScanFlags());
if (pRS == NULL)
return NULL;
if (pRS->flags & RangeSection::RANGE_SECTION_CODEHEAP)
return NULL;
#ifdef FEATURE_READYTORUN
// RANGE_SECTION_READYTORUN is intentionally not filtered out here
#endif
return dac_cast<PTR_Module>(pRS->pHeapListOrZapModule);
}
#ifndef DACCESS_COMPILE
/* NGenMem depends on this entrypoint */
NOINLINE
void ExecutionManager::AddCodeRange(TADDR pStartRange,
TADDR pEndRange,
IJitManager * pJit,
RangeSection::RangeSectionFlags flags,
void * pHp)
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
PRECONDITION(CheckPointer(pJit));
PRECONDITION(CheckPointer(pHp));
} CONTRACTL_END;
AddRangeHelper(pStartRange,
pEndRange,
pJit,
flags,
dac_cast<TADDR>(pHp));
}
void ExecutionManager::AddRangeHelper(TADDR pStartRange,
TADDR pEndRange,
IJitManager * pJit,
RangeSection::RangeSectionFlags flags,
TADDR pHeapListOrZapModule)
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
HOST_CALLS;
PRECONDITION(pStartRange < pEndRange);
PRECONDITION(pHeapListOrZapModule != NULL);
} CONTRACTL_END;
RangeSection *pnewrange = new RangeSection;
_ASSERTE(pEndRange > pStartRange);
pnewrange->LowAddress = pStartRange;
pnewrange->HighAddress = pEndRange;
pnewrange->pjit = pJit;
pnewrange->pnext = NULL;
pnewrange->flags = flags;
pnewrange->pLastUsed = NULL;
pnewrange->pHeapListOrZapModule = pHeapListOrZapModule;
#if defined(TARGET_AMD64)
pnewrange->pUnwindInfoTable = NULL;
#endif // defined(TARGET_AMD64)
{
CrstHolder ch(&m_RangeCrst); // Acquire the Crst before linking in a new RangeList
RangeSection * current = m_CodeRangeList;
RangeSection * previous = NULL;
if (current != NULL)
{
while (true)
{
// Sort addresses top down so that more recently created ranges
// will populate the top of the list
if (pnewrange->LowAddress > current->LowAddress)
{
// Asserts if ranges are overlapping
_ASSERTE(pnewrange->LowAddress >= current->HighAddress);
pnewrange->pnext = current;
if (previous == NULL) // insert new head
{
m_CodeRangeList = pnewrange;
}
else
{ // insert in the middle
previous->pnext = pnewrange;
}
break;
}
RangeSection * next = current->pnext;
if (next == NULL) // insert at end of list
{
current->pnext = pnewrange;
break;
}
// Continue walking the RangeSection list
previous = current;
current = next;
}
}
else
{
m_CodeRangeList = pnewrange;
}
}
}
// Deletes a single range starting at pStartRange
void ExecutionManager::DeleteRange(TADDR pStartRange)
{
CONTRACTL {
NOTHROW; // If this becomes throwing, then revisit the queuing of deletes below.
GC_NOTRIGGER;
} CONTRACTL_END;
RangeSection *pCurr = NULL;
{
// Acquire the Crst before unlinking a RangeList.
// NOTE: The Crst must be acquired BEFORE we grab the writer lock, as the
// writer lock forces us into a forbid suspend thread region, and it's illegal
// to enter a Crst after the forbid suspend thread region is entered
CrstHolder ch(&m_RangeCrst);
// Acquire the WriterLock and prevent any readers from walking the RangeList.
// This also forces us to enter a forbid suspend thread region, to prevent
// hijacking profilers from grabbing this thread and walking it (the walk may
// require the reader lock, which would cause a deadlock).
WriterLockHolder wlh;
RangeSection *pPrev = NULL;
pCurr = GetRangeSectionAndPrev(m_CodeRangeList, pStartRange, &pPrev);
// pCurr points at the Range that needs to be unlinked from the RangeList
if (pCurr != NULL)
{
// If pPrev is NULL the head of this list is to be deleted
if (pPrev == NULL)
{
m_CodeRangeList = pCurr->pnext;
}
else
{
_ASSERT(pPrev->pnext == pCurr);
pPrev->pnext = pCurr->pnext;
}
// Clear the cache pLastUsed in the head node (if any)
RangeSection * head = m_CodeRangeList;
if (head != NULL)
{
head->pLastUsed = NULL;
}
//
// Cannot delete pCurr here because we own the WriterLock and if this is
// a hosted scenario then the hosting api callback cannot occur in a forbid
// suspend region, which the writer lock is.
//
}
}
//
// Now delete the node
//
if (pCurr != NULL)
{
#if defined(TARGET_AMD64)
if (pCurr->pUnwindInfoTable != 0)
delete pCurr->pUnwindInfoTable;
#endif // defined(TARGET_AMD64)
delete pCurr;
}
}
#endif // #ifndef DACCESS_COMPILE
#ifdef DACCESS_COMPILE
void ExecutionManager::EnumRangeList(RangeSection* list,
CLRDataEnumMemoryFlags flags)
{
while (list != NULL)
{
// If we can't read the target memory, stop immediately so we don't work
// with broken data.
if (!DacEnumMemoryRegion(dac_cast<TADDR>(list), sizeof(*list)))
break;
if (list->pjit.IsValid())
{
list->pjit->EnumMemoryRegions(flags);
}
if (!(list->flags & RangeSection::RANGE_SECTION_CODEHEAP))
{
PTR_Module pModule = dac_cast<PTR_Module>(list->pHeapListOrZapModule);
if (pModule.IsValid())
{
pModule->EnumMemoryRegions(flags, true);
}
}
list = list->pnext;
#if defined (_DEBUG)
// Test hook: when testing on debug builds, we want an easy way to test that the while
// correctly terminates in the face of ridiculous stuff from the target.
if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DumpGeneration_IntentionallyCorruptDataFromTarget) == 1)
{
// Force us to struggle on with something bad.
if (list == NULL)
{
list = (RangeSection *)&flags;
}
}
#endif // (_DEBUG)
}
}
void ExecutionManager::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
STATIC_CONTRACT_HOST_CALLS;
ReaderLockHolder rlh;
//
// Report the global data portions.
//
m_CodeRangeList.EnumMem();
m_pDefaultCodeMan.EnumMem();
//
// Walk structures and report.
//
if (m_CodeRangeList.IsValid())
{
EnumRangeList(m_CodeRangeList, flags);
}
}
#endif // #ifdef DACCESS_COMPILE
#if !defined(DACCESS_COMPILE)
void ExecutionManager::Unload(LoaderAllocator *pLoaderAllocator)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
// a size of 0 is a signal to Nirvana to flush the entire cache
FlushInstructionCache(GetCurrentProcess(),0,0);
/* StackwalkCacheEntry::EIP is an address into code. Since we are
unloading the code, we need to invalidate the cache. Otherwise,
its possible that another appdomain might generate code at the very
same address, and we might incorrectly think that the old
StackwalkCacheEntry corresponds to it. So flush the cache.
*/
StackwalkCache::Invalidate(pLoaderAllocator);
JumpStubCache * pJumpStubCache = (JumpStubCache *) pLoaderAllocator->m_pJumpStubCache;
if (pJumpStubCache != NULL)
{
delete pJumpStubCache;
pLoaderAllocator->m_pJumpStubCache = NULL;
}
GetEEJitManager()->Unload(pLoaderAllocator);
}
// This method is used by the JIT and the runtime for PreStubs. It will return
// the address of a short jump thunk that will jump to the 'target' address.
// It is only needed when the target architecture has a perferred call instruction
// that doesn't actually span the full address space. This is true for x64 where
// the preferred call instruction is a 32-bit pc-rel call instruction.
// (This is also true on ARM64, but it not true for x86)
//
// For these architectures, in JITed code and in the prestub, we encode direct calls
// using the preferred call instruction and we also try to insure that the Jitted
// code is within the 32-bit pc-rel range of clr.dll to allow direct JIT helper calls.
//
// When the call target is too far away to encode using the preferred call instruction.
// We will create a short code thunk that uncoditionally jumps to the target address.
// We call this jump thunk a "jumpStub" in the CLR code.
// We have the requirement that the "jumpStub" that we create on demand be usable by
// the preferred call instruction, this requires that on x64 the location in memory
// where we create the "jumpStub" be within the 32-bit pc-rel range of the call that
// needs it.
//
// The arguments to this method:
// pMD - the MethodDesc for the currenty managed method in Jitted code
// or for the target method for a PreStub
// It is required if calling from or to a dynamic method (LCG method)
// target - The call target address (this is the address that was too far to encode)
// loAddr
// hiAddr - The range of the address that we must place the jumpStub in, so that it
// can be used to encode the preferred call instruction.
// pLoaderAllocator
// - The Loader allocator to use for allocations, this can be null.
// When it is null, then the pMD must be valid and is used to obtain
// the allocator.
//
// This method will either locate and return an existing jumpStub thunk that can be
// reused for this request, because it meets all of the requirements necessary.
// Or it will allocate memory in the required region and create a new jumpStub that
// meets all of the requirements necessary.
//
// Note that for dynamic methods (LCG methods) we cannot share the jumpStubs between
// different methods. This is because we allow for the unloading (reclaiming) of
// individual dynamic methods. And we associate the jumpStub memory allocated with
// the dynamic method that requested the jumpStub.
//
PCODE ExecutionManager::jumpStub(MethodDesc* pMD, PCODE target,
BYTE * loAddr, BYTE * hiAddr,
LoaderAllocator *pLoaderAllocator,
bool throwOnOutOfMemoryWithinRange)
{
CONTRACT(PCODE) {
THROWS;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(pLoaderAllocator != NULL || pMD != NULL);
PRECONDITION(loAddr < hiAddr);
POSTCONDITION((RETVAL != NULL) || !throwOnOutOfMemoryWithinRange);
} CONTRACT_END;
PCODE jumpStub = NULL;
if (pLoaderAllocator == NULL)
{
pLoaderAllocator = pMD->GetLoaderAllocator();
}
_ASSERTE(pLoaderAllocator != NULL);
bool isLCG = pMD && pMD->IsLCGMethod();
LCGMethodResolver * pResolver = nullptr;
JumpStubCache * pJumpStubCache = (JumpStubCache *) pLoaderAllocator->m_pJumpStubCache;
if (isLCG)
{
pResolver = pMD->AsDynamicMethodDesc()->GetLCGMethodResolver();
pJumpStubCache = pResolver->m_pJumpStubCache;
}
CrstHolder ch(&m_JumpStubCrst);
if (pJumpStubCache == NULL)
{
pJumpStubCache = new JumpStubCache();
if (isLCG)
{
pResolver->m_pJumpStubCache = pJumpStubCache;
}
else
{
pLoaderAllocator->m_pJumpStubCache = pJumpStubCache;
}
}
if (isLCG)
{
// Increment counter of LCG jump stub lookup attempts
m_LCG_JumpStubLookup++;
}
else
{
// Increment counter of normal jump stub lookup attempts
m_normal_JumpStubLookup++;
}
// search for a matching jumpstub in the jumpStubCache
//
for (JumpStubTable::KeyIterator i = pJumpStubCache->m_Table.Begin(target),
end = pJumpStubCache->m_Table.End(target); i != end; i++)
{
jumpStub = i->m_jumpStub;
_ASSERTE(jumpStub != NULL);
// Is the matching entry with the requested range?
if (((TADDR)loAddr <= jumpStub) && (jumpStub <= (TADDR)hiAddr))
{
RETURN(jumpStub);
}
}
// If we get here we need to create a new jump stub
// add or change the jump stub table to point at the new one
jumpStub = getNextJumpStub(pMD, target, loAddr, hiAddr, pLoaderAllocator, throwOnOutOfMemoryWithinRange); // this statement can throw
if (jumpStub == NULL)
{
_ASSERTE(!throwOnOutOfMemoryWithinRange);
RETURN(NULL);
}
_ASSERTE(((TADDR)loAddr <= jumpStub) && (jumpStub <= (TADDR)hiAddr));
LOG((LF_JIT, LL_INFO10000, "Add JumpStub to" FMT_ADDR "at" FMT_ADDR "\n",
DBG_ADDR(target), DBG_ADDR(jumpStub) ));
RETURN(jumpStub);
}
PCODE ExecutionManager::getNextJumpStub(MethodDesc* pMD, PCODE target,
BYTE * loAddr, BYTE * hiAddr,
LoaderAllocator *pLoaderAllocator,
bool throwOnOutOfMemoryWithinRange)
{
CONTRACT(PCODE) {
THROWS;
GC_NOTRIGGER;
PRECONDITION(pLoaderAllocator != NULL);
PRECONDITION(m_JumpStubCrst.OwnedByCurrentThread());
POSTCONDITION((RETVAL != NULL) || !throwOnOutOfMemoryWithinRange);
} CONTRACT_END;
BYTE * jumpStub = NULL;
BYTE * jumpStubRW = NULL;
bool isLCG = pMD && pMD->IsLCGMethod();
// For LCG we request a small block of 4 jumpstubs, because we can not share them
// with any other methods and very frequently our method only needs one jump stub.
// Using 4 gives a request size of (32 + 4*12) or 80 bytes.
// Also note that request sizes are rounded up to a multiples of 16.
// The request size is calculated into 'blockSize' in allocJumpStubBlock.
// For x64 the value of BACK_TO_BACK_JUMP_ALLOCATE_SIZE is 12 bytes
// and the sizeof(JumpStubBlockHeader) is 32.
//
DWORD numJumpStubs = isLCG ? 4 : DEFAULT_JUMPSTUBS_PER_BLOCK;
JumpStubCache * pJumpStubCache = (JumpStubCache *) pLoaderAllocator->m_pJumpStubCache;
if (isLCG)
{
LCGMethodResolver * pResolver;
pResolver = pMD->AsDynamicMethodDesc()->GetLCGMethodResolver();
pJumpStubCache = pResolver->m_pJumpStubCache;
}
JumpStubBlockHeader ** ppHead = &(pJumpStubCache->m_pBlocks);
JumpStubBlockHeader * curBlock = *ppHead;
ExecutableWriterHolderNoLog<JumpStubBlockHeader> curBlockWriterHolder;
// allocate a new jumpstub from 'curBlock' if it is not fully allocated
//
while (curBlock)
{
_ASSERTE(pLoaderAllocator == (isLCG ? curBlock->GetHostCodeHeap()->GetAllocator() : curBlock->GetLoaderAllocator()));
if (curBlock->m_used < curBlock->m_allocated)
{
jumpStub = (BYTE *) curBlock + sizeof(JumpStubBlockHeader) + ((size_t) curBlock->m_used * BACK_TO_BACK_JUMP_ALLOCATE_SIZE);
if ((loAddr <= jumpStub) && (jumpStub <= hiAddr))
{
// We will update curBlock->m_used at "DONE"
size_t blockSize = sizeof(JumpStubBlockHeader) + (size_t) numJumpStubs * BACK_TO_BACK_JUMP_ALLOCATE_SIZE;
curBlockWriterHolder.AssignExecutableWriterHolder(curBlock, blockSize);
jumpStubRW = (BYTE *)((TADDR)jumpStub + (TADDR)curBlockWriterHolder.GetRW() - (TADDR)curBlock);
goto DONE;
}
}
curBlock = curBlock->m_next;
}
// If we get here then we need to allocate a new JumpStubBlock
if (isLCG)
{
#ifdef TARGET_AMD64
// Note this these values are not requirements, instead we are
// just confirming the values that are mentioned in the comments.
_ASSERTE(BACK_TO_BACK_JUMP_ALLOCATE_SIZE == 12);
_ASSERTE(sizeof(JumpStubBlockHeader) == 32);
#endif
// Increment counter of LCG jump stub block allocations
m_LCG_JumpStubBlockAllocCount++;
}
else
{
// Increment counter of normal jump stub block allocations
m_normal_JumpStubBlockAllocCount++;
}
// allocJumpStubBlock will allocate from the LoaderCodeHeap for normal methods
// and will allocate from a HostCodeHeap for LCG methods.
//
// note that this can throw an OOM exception
curBlock = ExecutionManager::GetEEJitManager()->allocJumpStubBlock(pMD, numJumpStubs, loAddr, hiAddr, pLoaderAllocator, throwOnOutOfMemoryWithinRange);
if (curBlock == NULL)
{
_ASSERTE(!throwOnOutOfMemoryWithinRange);
RETURN(NULL);
}
curBlockWriterHolder.AssignExecutableWriterHolder(curBlock, sizeof(JumpStubBlockHeader) + ((size_t) (curBlock->m_used + 1) * BACK_TO_BACK_JUMP_ALLOCATE_SIZE));
jumpStubRW = (BYTE *) curBlockWriterHolder.GetRW() + sizeof(JumpStubBlockHeader) + ((size_t) curBlock->m_used * BACK_TO_BACK_JUMP_ALLOCATE_SIZE);
jumpStub = (BYTE *) curBlock + sizeof(JumpStubBlockHeader) + ((size_t) curBlock->m_used * BACK_TO_BACK_JUMP_ALLOCATE_SIZE);
_ASSERTE((loAddr <= jumpStub) && (jumpStub <= hiAddr));
curBlockWriterHolder.GetRW()->m_next = *ppHead;
*ppHead = curBlock;
DONE:
_ASSERTE((curBlock->m_used < curBlock->m_allocated));
#ifdef TARGET_ARM64
// 8-byte alignment is required on ARM64
_ASSERTE(((UINT_PTR)jumpStub & 7) == 0);
#endif
emitBackToBackJump(jumpStub, jumpStubRW, (void*) target);
#ifdef FEATURE_PERFMAP
PerfMap::LogStubs(__FUNCTION__, "emitBackToBackJump", (PCODE)jumpStub, BACK_TO_BACK_JUMP_ALLOCATE_SIZE);
#endif
// We always add the new jumpstub to the jumpStubCache
//
_ASSERTE(pJumpStubCache != NULL);
JumpStubEntry entry;
entry.m_target = target;
entry.m_jumpStub = (PCODE)jumpStub;
pJumpStubCache->m_Table.Add(entry);
curBlockWriterHolder.GetRW()->m_used++; // record that we have used up one more jumpStub in the block
// Every time we create a new jumpStub thunk one of these counters is incremented
if (isLCG)
{
// Increment counter of LCG unique jump stubs
m_LCG_JumpStubUnique++;
}
else
{
// Increment counter of normal unique jump stubs
m_normal_JumpStubUnique++;
}
// Is the 'curBlock' now completely full?
if (curBlock->m_used == curBlock->m_allocated)
{
if (isLCG)
{
// Increment counter of LCG jump stub blocks that are full
m_LCG_JumpStubBlockFullCount++;
// Log this "LCG JumpStubBlock filled" along with the four counter values
STRESS_LOG4(LF_JIT, LL_INFO1000, "LCG JumpStubBlock filled - (%u, %u, %u, %u)\n",
m_LCG_JumpStubLookup, m_LCG_JumpStubUnique,
m_LCG_JumpStubBlockAllocCount, m_LCG_JumpStubBlockFullCount);
}
else
{
// Increment counter of normal jump stub blocks that are full
m_normal_JumpStubBlockFullCount++;
// Log this "normal JumpStubBlock filled" along with the four counter values
STRESS_LOG4(LF_JIT, LL_INFO1000, "Normal JumpStubBlock filled - (%u, %u, %u, %u)\n",
m_normal_JumpStubLookup, m_normal_JumpStubUnique,
m_normal_JumpStubBlockAllocCount, m_normal_JumpStubBlockFullCount);
if ((m_LCG_JumpStubLookup > 0) && ((m_normal_JumpStubBlockFullCount % 5) == 1))
{
// Every 5 occurrence of the above we also
// Log "LCG JumpStubBlock status" along with the four counter values
STRESS_LOG4(LF_JIT, LL_INFO1000, "LCG JumpStubBlock status - (%u, %u, %u, %u)\n",
m_LCG_JumpStubLookup, m_LCG_JumpStubUnique,
m_LCG_JumpStubBlockAllocCount, m_LCG_JumpStubBlockFullCount);
}
}
}
RETURN((PCODE)jumpStub);
}
#endif // !DACCESS_COMPILE
static void GetFuncletStartOffsetsHelper(PCODE pCodeStart, SIZE_T size, SIZE_T ofsAdj,
PTR_RUNTIME_FUNCTION pFunctionEntry, TADDR moduleBase,
DWORD * pnFunclets, DWORD* pStartFuncletOffsets, DWORD dwLength)
{
_ASSERTE(FitsInU4((pCodeStart + size) - moduleBase));
DWORD endAddress = (DWORD)((pCodeStart + size) - moduleBase);
// Entries are sorted and terminated by sentinel value (DWORD)-1
for (; RUNTIME_FUNCTION__BeginAddress(pFunctionEntry) < endAddress; pFunctionEntry++)
{
#ifdef TARGET_AMD64
_ASSERTE((pFunctionEntry->UnwindData & RUNTIME_FUNCTION_INDIRECT) == 0);
#endif
#if defined(EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS)
if (IsFunctionFragment(moduleBase, pFunctionEntry))
{
// This is a fragment (not the funclet beginning); skip it
continue;
}
#endif // EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS
if (*pnFunclets < dwLength)
{
TADDR funcletStartAddress = (moduleBase + RUNTIME_FUNCTION__BeginAddress(pFunctionEntry)) + ofsAdj;
_ASSERTE(FitsInU4(funcletStartAddress - pCodeStart));
pStartFuncletOffsets[*pnFunclets] = (DWORD)(funcletStartAddress - pCodeStart);
}
(*pnFunclets)++;
}
}
#if defined(FEATURE_EH_FUNCLETS) && defined(DACCESS_COMPILE)
//
// To locate an entry in the function entry table (the program exceptions data directory), the debugger
// performs a binary search over the table. This function reports the entries that are encountered in the
// binary search.
//
// Parameters:
// pRtf: The target function table entry to be located
// pNativeLayout: A pointer to the loaded native layout for the module containing pRtf
//
static void EnumRuntimeFunctionEntriesToFindEntry(PTR_RUNTIME_FUNCTION pRtf, PTR_PEImageLayout pNativeLayout)
{
pRtf.EnumMem();
if (pNativeLayout == NULL)
{
return;
}
IMAGE_DATA_DIRECTORY * pProgramExceptionsDirectory = pNativeLayout->GetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_EXCEPTION);
if (!pProgramExceptionsDirectory ||
(pProgramExceptionsDirectory->Size == 0) ||
(pProgramExceptionsDirectory->Size % sizeof(T_RUNTIME_FUNCTION) != 0))
{
// Program exceptions directory malformatted
return;
}
PTR_BYTE moduleBase(pNativeLayout->GetBase());
PTR_RUNTIME_FUNCTION firstFunctionEntry(moduleBase + pProgramExceptionsDirectory->VirtualAddress);
if (pRtf < firstFunctionEntry ||
((dac_cast<TADDR>(pRtf) - dac_cast<TADDR>(firstFunctionEntry)) % sizeof(T_RUNTIME_FUNCTION) != 0))
{
// Program exceptions directory malformatted
return;
}
UINT_PTR indexToLocate = pRtf - firstFunctionEntry;
UINT_PTR low = 0; // index in the function entry table of low end of search range
UINT_PTR high = (pProgramExceptionsDirectory->Size) / sizeof(T_RUNTIME_FUNCTION) - 1; // index of high end of search range
UINT_PTR mid = (low + high) / 2; // index of entry to be compared
if (indexToLocate > high)
{
return;
}
while (indexToLocate != mid)
{
PTR_RUNTIME_FUNCTION functionEntry = firstFunctionEntry + mid;
functionEntry.EnumMem();
if (indexToLocate > mid)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
mid = (low + high) / 2;
_ASSERTE(low <= mid && mid <= high);
}
}
#endif // FEATURE_EH_FUNCLETS
#if defined(FEATURE_READYTORUN)
// Return start of exception info for a method, or 0 if the method has no EH info
DWORD NativeExceptionInfoLookupTable::LookupExceptionInfoRVAForMethod(PTR_CORCOMPILE_EXCEPTION_LOOKUP_TABLE pExceptionLookupTable,
COUNT_T numLookupEntries,
DWORD methodStartRVA,
COUNT_T* pSize)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
_ASSERTE(pExceptionLookupTable != NULL);
COUNT_T start = 0;
COUNT_T end = numLookupEntries - 2;
// The last entry in the lookup table (end-1) points to a sentinel entry.
// The sentinel entry helps to determine the number of EH clauses for the last table entry.
_ASSERTE(pExceptionLookupTable->ExceptionLookupEntry(numLookupEntries-1)->MethodStartRVA == (DWORD)-1);
// Binary search the lookup table
// Using linear search is faster once we get down to small number of entries.
while (end - start > 10)
{
COUNT_T middle = start + (end - start) / 2;
_ASSERTE(start < middle && middle < end);
DWORD rva = pExceptionLookupTable->ExceptionLookupEntry(middle)->MethodStartRVA;
if (methodStartRVA < rva)
{
end = middle - 1;
}
else
{
start = middle;
}
}
for (COUNT_T i = start; i <= end; ++i)
{
DWORD rva = pExceptionLookupTable->ExceptionLookupEntry(i)->MethodStartRVA;
if (methodStartRVA == rva)
{
CORCOMPILE_EXCEPTION_LOOKUP_TABLE_ENTRY *pEntry = pExceptionLookupTable->ExceptionLookupEntry(i);
//Get the count of EH Clause entries
CORCOMPILE_EXCEPTION_LOOKUP_TABLE_ENTRY * pNextEntry = pExceptionLookupTable->ExceptionLookupEntry(i + 1);
*pSize = pNextEntry->ExceptionInfoRVA - pEntry->ExceptionInfoRVA;
return pEntry->ExceptionInfoRVA;
}
}
// Not found
return 0;
}
int NativeUnwindInfoLookupTable::LookupUnwindInfoForMethod(DWORD RelativePc,
PTR_RUNTIME_FUNCTION pRuntimeFunctionTable,
int Low,
int High)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
#ifdef TARGET_ARM
RelativePc |= THUMB_CODE;
#endif
// Entries are sorted and terminated by sentinel value (DWORD)-1
// Binary search the RUNTIME_FUNCTION table
// Use linear search once we get down to a small number of elements
// to avoid Binary search overhead.
while (High - Low > 10)
{
int Middle = Low + (High - Low) / 2;
PTR_RUNTIME_FUNCTION pFunctionEntry = pRuntimeFunctionTable + Middle;
if (RelativePc < pFunctionEntry->BeginAddress)
{
High = Middle - 1;
}
else
{
Low = Middle;
}
}
for (int i = Low; i <= High; ++i)
{
// This is safe because of entries are terminated by sentinel value (DWORD)-1
PTR_RUNTIME_FUNCTION pNextFunctionEntry = pRuntimeFunctionTable + (i + 1);
if (RelativePc < pNextFunctionEntry->BeginAddress)
{
PTR_RUNTIME_FUNCTION pFunctionEntry = pRuntimeFunctionTable + i;
if (RelativePc >= pFunctionEntry->BeginAddress)
{
return i;
}
break;
}
}
return -1;
}
int HotColdMappingLookupTable::LookupMappingForMethod(ReadyToRunInfo* pInfo, ULONG MethodIndex)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
if (pInfo->m_nHotColdMap == 0)
{
return -1;
}
// Casting the lookup table size to an int is safe:
// We index the RUNTIME_FUNCTION table with ints, and the lookup table
// contains a subset of the indices in the RUNTIME_FUNCTION table.
// Thus, |lookup table| <= |RUNTIME_FUNCTION table|.
_ASSERTE(pInfo->m_nHotColdMap <= pInfo->m_nRuntimeFunctions);
const int nLookupTable = (int)(pInfo->m_nHotColdMap);
// The lookup table contains pairs of hot/cold indices, and thus should have an even size.
_ASSERTE((nLookupTable % 2) == 0);
int high = ((nLookupTable - 1) / 2);
int low = 0;
const int indexCorrection = (int)(MethodIndex < pInfo->m_pHotColdMap[0]);
// Binary search the lookup table.
// Use linear search once we get down to a small number of elements
// to avoid binary search overhead.
while (high - low > 10)
{
const int middle = low + (high - low) / 2;
const int index = (middle * 2) + indexCorrection;
if (MethodIndex < pInfo->m_pHotColdMap[index])
{
high = middle - 1;
}
else
{
low = middle;
}
}
// In each pair of indices in lookup table, the first index is of the cold fragment.
const bool isColdCode = (indexCorrection == 0);
for (int i = low; i <= high; ++i)
{
const int index = (i * 2);
if (pInfo->m_pHotColdMap[index + indexCorrection] == MethodIndex)
{
if (isColdCode)
{
return index + 1;
}
return index;
}
else if (isColdCode && (MethodIndex > pInfo->m_pHotColdMap[index]))
{
// If MethodIndex is a cold funclet from a cold block, the above search will fail.
// To get its corresponding hot block, find the cold block containing the funclet,
// then use the lookup table.
// The cold funclet's MethodIndex will be greater than its cold block's MethodIndex,
// but less than the next cold block's MethodIndex in the lookup table.
const bool isFuncletIndex = ((index + 2) == nLookupTable) || (MethodIndex < pInfo->m_pHotColdMap[index + 2]);
if (isFuncletIndex)
{
return index + 1;
}
}
}
return -1;
}
//***************************************************************************************
//***************************************************************************************
#ifndef DACCESS_COMPILE
ReadyToRunJitManager::ReadyToRunJitManager()
{
WRAPPER_NO_CONTRACT;
}
#endif // #ifndef DACCESS_COMPILE
ReadyToRunInfo * ReadyToRunJitManager::JitTokenToReadyToRunInfo(const METHODTOKEN& MethodToken)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
HOST_NOCALLS;
SUPPORTS_DAC;
} CONTRACTL_END;
return dac_cast<PTR_Module>(MethodToken.m_pRangeSection->pHeapListOrZapModule)->GetReadyToRunInfo();
}
UINT32 ReadyToRunJitManager::JitTokenToGCInfoVersion(const METHODTOKEN& MethodToken)
{
CONTRACTL{
NOTHROW;
GC_NOTRIGGER;
HOST_NOCALLS;
SUPPORTS_DAC;
} CONTRACTL_END;
READYTORUN_HEADER * header = JitTokenToReadyToRunInfo(MethodToken)->GetReadyToRunHeader();
return GCInfoToken::ReadyToRunVersionToGcInfoVersion(header->MajorVersion);
}
PTR_RUNTIME_FUNCTION ReadyToRunJitManager::JitTokenToRuntimeFunction(const METHODTOKEN& MethodToken)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
HOST_NOCALLS;
SUPPORTS_DAC;
} CONTRACTL_END;
return dac_cast<PTR_RUNTIME_FUNCTION>(MethodToken.m_pCodeHeader);
}
TADDR ReadyToRunJitManager::JitTokenToStartAddress(const METHODTOKEN& MethodToken)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
HOST_NOCALLS;
SUPPORTS_DAC;
} CONTRACTL_END;
return JitTokenToModuleBase(MethodToken) +
RUNTIME_FUNCTION__BeginAddress(dac_cast<PTR_RUNTIME_FUNCTION>(MethodToken.m_pCodeHeader));
}
GCInfoToken ReadyToRunJitManager::GetGCInfoToken(const METHODTOKEN& MethodToken)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
HOST_NOCALLS;
SUPPORTS_DAC;
} CONTRACTL_END;
PTR_RUNTIME_FUNCTION pRuntimeFunction = JitTokenToRuntimeFunction(MethodToken);
TADDR baseAddress = JitTokenToModuleBase(MethodToken);
SIZE_T nUnwindDataSize;
PTR_VOID pUnwindData = GetUnwindDataBlob(baseAddress, pRuntimeFunction, &nUnwindDataSize);
// GCInfo immediately follows unwind data
PTR_BYTE gcInfo = dac_cast<PTR_BYTE>(pUnwindData) + nUnwindDataSize;
UINT32 gcInfoVersion = JitTokenToGCInfoVersion(MethodToken);
return{ gcInfo, gcInfoVersion };
}
unsigned ReadyToRunJitManager::InitializeEHEnumeration(const METHODTOKEN& MethodToken, EH_CLAUSE_ENUMERATOR* pEnumState)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
ReadyToRunInfo * pReadyToRunInfo = JitTokenToReadyToRunInfo(MethodToken);
IMAGE_DATA_DIRECTORY * pExceptionInfoDir = pReadyToRunInfo->FindSection(ReadyToRunSectionType::ExceptionInfo);
if (pExceptionInfoDir == NULL)
return 0;
PEImageLayout * pLayout = pReadyToRunInfo->GetImage();
PTR_CORCOMPILE_EXCEPTION_LOOKUP_TABLE pExceptionLookupTable = dac_cast<PTR_CORCOMPILE_EXCEPTION_LOOKUP_TABLE>(pLayout->GetRvaData(pExceptionInfoDir->VirtualAddress));
COUNT_T numLookupTableEntries = (COUNT_T)(pExceptionInfoDir->Size / sizeof(CORCOMPILE_EXCEPTION_LOOKUP_TABLE_ENTRY));
// at least 2 entries (1 valid entry + 1 sentinel entry)
_ASSERTE(numLookupTableEntries >= 2);
DWORD methodStartRVA = (DWORD)(JitTokenToStartAddress(MethodToken) - JitTokenToModuleBase(MethodToken));
COUNT_T ehInfoSize = 0;
DWORD exceptionInfoRVA = NativeExceptionInfoLookupTable::LookupExceptionInfoRVAForMethod(pExceptionLookupTable,
numLookupTableEntries,
methodStartRVA,
&ehInfoSize);
if (exceptionInfoRVA == 0)
return 0;
pEnumState->iCurrentPos = 0;
pEnumState->pExceptionClauseArray = JitTokenToModuleBase(MethodToken) + exceptionInfoRVA;
return ehInfoSize / sizeof(CORCOMPILE_EXCEPTION_CLAUSE);
}
PTR_EXCEPTION_CLAUSE_TOKEN ReadyToRunJitManager::GetNextEHClause(EH_CLAUSE_ENUMERATOR* pEnumState,
EE_ILEXCEPTION_CLAUSE* pEHClauseOut)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
unsigned iCurrentPos = pEnumState->iCurrentPos;
pEnumState->iCurrentPos++;
CORCOMPILE_EXCEPTION_CLAUSE* pClause = &(dac_cast<PTR_CORCOMPILE_EXCEPTION_CLAUSE>(pEnumState->pExceptionClauseArray)[iCurrentPos]);
// copy to the input parameter, this is a nice abstraction for the future
// if we want to compress the Clause encoding, we can do without affecting the call sites
pEHClauseOut->TryStartPC = pClause->TryStartPC;
pEHClauseOut->TryEndPC = pClause->TryEndPC;
pEHClauseOut->HandlerStartPC = pClause->HandlerStartPC;
pEHClauseOut->HandlerEndPC = pClause->HandlerEndPC;
pEHClauseOut->Flags = pClause->Flags;
pEHClauseOut->FilterOffset = pClause->FilterOffset;
return dac_cast<PTR_EXCEPTION_CLAUSE_TOKEN>(pClause);
}
StubCodeBlockKind ReadyToRunJitManager::GetStubCodeBlockKind(RangeSection * pRangeSection, PCODE currentPC)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
DWORD rva = (DWORD)(currentPC - pRangeSection->LowAddress);
PTR_ReadyToRunInfo pReadyToRunInfo = dac_cast<PTR_Module>(pRangeSection->pHeapListOrZapModule)->GetReadyToRunInfo();
PTR_IMAGE_DATA_DIRECTORY pDelayLoadMethodCallThunksDir = pReadyToRunInfo->GetDelayMethodCallThunksSection();
if (pDelayLoadMethodCallThunksDir != NULL)
{
if (pDelayLoadMethodCallThunksDir->VirtualAddress <= rva
&& rva < pDelayLoadMethodCallThunksDir->VirtualAddress + pDelayLoadMethodCallThunksDir->Size)
return STUB_CODE_BLOCK_METHOD_CALL_THUNK;
}
return STUB_CODE_BLOCK_UNKNOWN;
}
#ifndef DACCESS_COMPILE
TypeHandle ReadyToRunJitManager::ResolveEHClause(EE_ILEXCEPTION_CLAUSE* pEHClause,
CrawlFrame* pCf)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
_ASSERTE(NULL != pCf);
_ASSERTE(NULL != pEHClause);
_ASSERTE(IsTypedHandler(pEHClause));
MethodDesc *pMD = PTR_MethodDesc(pCf->GetFunction());
_ASSERTE(pMD != NULL);
Module* pModule = pMD->GetModule();
PREFIX_ASSUME(pModule != NULL);
SigTypeContext typeContext(pMD);
mdToken typeTok = pEHClause->ClassToken;
return ClassLoader::LoadTypeDefOrRefOrSpecThrowing(pModule, typeTok, &typeContext,
ClassLoader::ReturnNullIfNotFound);
}
#endif // #ifndef DACCESS_COMPILE
//-----------------------------------------------------------------------------
// Ngen info manager
//-----------------------------------------------------------------------------
BOOL ReadyToRunJitManager::GetBoundariesAndVars(
const DebugInfoRequest & request,
IN FP_IDS_NEW fpNew, IN void * pNewData,
OUT ULONG32 * pcMap,
OUT ICorDebugInfo::OffsetMapping **ppMap,
OUT ULONG32 * pcVars,
OUT ICorDebugInfo::NativeVarInfo **ppVars)
{
CONTRACTL {
THROWS; // on OOM.
GC_NOTRIGGER; // getting vars shouldn't trigger
SUPPORTS_DAC;
} CONTRACTL_END;
EECodeInfo codeInfo(request.GetStartAddress());
if (!codeInfo.IsValid())
return FALSE;
ReadyToRunInfo * pReadyToRunInfo = JitTokenToReadyToRunInfo(codeInfo.GetMethodToken());
PTR_RUNTIME_FUNCTION pRuntimeFunction = JitTokenToRuntimeFunction(codeInfo.GetMethodToken());
PTR_BYTE pDebugInfo = pReadyToRunInfo->GetDebugInfo(pRuntimeFunction);
if (pDebugInfo == NULL)
return FALSE;
// Uncompress. This allocates memory and may throw.
CompressDebugInfo::RestoreBoundariesAndVars(
fpNew, pNewData, // allocators
pDebugInfo, // input
pcMap, ppMap, // output
pcVars, ppVars, // output
FALSE); // no patchpoint info
return TRUE;
}
BOOL ReadyToRunJitManager::GetRichDebugInfo(
const DebugInfoRequest& request,
IN FP_IDS_NEW fpNew, IN void* pNewData,
OUT ICorDebugInfo::InlineTreeNode** ppInlineTree,
OUT ULONG32* pNumInlineTree,
OUT ICorDebugInfo::RichOffsetMapping** ppRichMappings,
OUT ULONG32* pNumRichMappings)
{
return FALSE;
}
#ifdef DACCESS_COMPILE
//
// Need to write out debug info
//
void ReadyToRunJitManager::EnumMemoryRegionsForMethodDebugInfo(CLRDataEnumMemoryFlags flags, MethodDesc * pMD)
{
SUPPORTS_DAC;
EECodeInfo codeInfo(pMD->GetNativeCode());
if (!codeInfo.IsValid())
return;
ReadyToRunInfo * pReadyToRunInfo = JitTokenToReadyToRunInfo(codeInfo.GetMethodToken());
PTR_RUNTIME_FUNCTION pRuntimeFunction = JitTokenToRuntimeFunction(codeInfo.GetMethodToken());
PTR_BYTE pDebugInfo = pReadyToRunInfo->GetDebugInfo(pRuntimeFunction);
if (pDebugInfo == NULL)
return;
CompressDebugInfo::EnumMemoryRegions(flags, pDebugInfo, FALSE);
}
#endif
PCODE ReadyToRunJitManager::GetCodeAddressForRelOffset(const METHODTOKEN& MethodToken, DWORD relOffset)
{
WRAPPER_NO_CONTRACT;
MethodRegionInfo methodRegionInfo;
JitTokenToMethodRegionInfo(MethodToken, &methodRegionInfo);
if (relOffset < methodRegionInfo.hotSize)
return methodRegionInfo.hotStartAddress + relOffset;
SIZE_T coldOffset = relOffset - methodRegionInfo.hotSize;
_ASSERTE(coldOffset < methodRegionInfo.coldSize);
return methodRegionInfo.coldStartAddress + coldOffset;
}
BOOL ReadyToRunJitManager::JitCodeToMethodInfo(RangeSection * pRangeSection,
PCODE currentPC,
MethodDesc** ppMethodDesc,
OUT EECodeInfo * pCodeInfo)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
// If the address is in a thunk, return NULL.
if (GetStubCodeBlockKind(pRangeSection, currentPC) != STUB_CODE_BLOCK_UNKNOWN)
{
return FALSE;
}
TADDR currentInstr = PCODEToPINSTR(currentPC);
TADDR ImageBase = pRangeSection->LowAddress;
DWORD RelativePc = (DWORD)(currentInstr - ImageBase);
Module * pModule = dac_cast<PTR_Module>(pRangeSection->pHeapListOrZapModule);
ReadyToRunInfo * pInfo = pModule->GetReadyToRunInfo();
COUNT_T nRuntimeFunctions = pInfo->m_nRuntimeFunctions;
PTR_RUNTIME_FUNCTION pRuntimeFunctions = pInfo->m_pRuntimeFunctions;
int MethodIndex = NativeUnwindInfoLookupTable::LookupUnwindInfoForMethod(RelativePc,
pRuntimeFunctions,
0,
nRuntimeFunctions - 1);
if (MethodIndex < 0)
return FALSE;
if (ppMethodDesc == NULL && pCodeInfo == NULL)
{
// Bail early if caller doesn't care about the MethodDesc or EECodeInfo.
// Avoiding the method desc lookups below also prevents deadlocks when this
// is called from IsManagedCode.
return TRUE;
}
#ifdef FEATURE_EH_FUNCLETS
// Save the raw entry
PTR_RUNTIME_FUNCTION RawFunctionEntry = pRuntimeFunctions + MethodIndex;
ULONG UMethodIndex = (ULONG)MethodIndex;
const int lookupIndex = HotColdMappingLookupTable::LookupMappingForMethod(pInfo, (ULONG)MethodIndex);
if ((lookupIndex != -1) && ((lookupIndex & 1) == 1))
{
// If the MethodIndex happens to be the cold code block, turn it into the associated hot code block
MethodIndex = pInfo->m_pHotColdMap[lookupIndex];
}
MethodDesc *pMethodDesc;
while ((pMethodDesc = pInfo->GetMethodDescForEntryPoint(ImageBase + RUNTIME_FUNCTION__BeginAddress(pRuntimeFunctions + MethodIndex))) == NULL)
MethodIndex--;
#endif
PTR_RUNTIME_FUNCTION FunctionEntry = pRuntimeFunctions + MethodIndex;
if (ppMethodDesc)
{
#ifdef FEATURE_EH_FUNCLETS
*ppMethodDesc = pMethodDesc;
#else
*ppMethodDesc = pInfo->GetMethodDescForEntryPoint(ImageBase + RUNTIME_FUNCTION__BeginAddress(FunctionEntry));
#endif
_ASSERTE(*ppMethodDesc != NULL);
}
if (pCodeInfo)
{
// We are using RUNTIME_FUNCTION as METHODTOKEN
pCodeInfo->m_methodToken = METHODTOKEN(pRangeSection, dac_cast<TADDR>(FunctionEntry));
#ifdef FEATURE_EH_FUNCLETS
AMD64_ONLY(_ASSERTE((RawFunctionEntry->UnwindData & RUNTIME_FUNCTION_INDIRECT) == 0));
pCodeInfo->m_pFunctionEntry = RawFunctionEntry;
#endif
MethodRegionInfo methodRegionInfo;
JitTokenToMethodRegionInfo(pCodeInfo->m_methodToken, &methodRegionInfo);
if ((methodRegionInfo.coldSize > 0) && (currentInstr >= methodRegionInfo.coldStartAddress))
{
pCodeInfo->m_relOffset = (DWORD)
(methodRegionInfo.hotSize + (currentInstr - methodRegionInfo.coldStartAddress));
}
else
{
pCodeInfo->m_relOffset = (DWORD)(currentInstr - methodRegionInfo.hotStartAddress);
}
}
return TRUE;
}
#if defined(FEATURE_EH_FUNCLETS)
PTR_RUNTIME_FUNCTION ReadyToRunJitManager::LazyGetFunctionEntry(EECodeInfo * pCodeInfo)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
if (!pCodeInfo->IsValid())
{
return NULL;
}
// code:ReadyToRunJitManager::JitCodeToMethodInfo computes PTR_RUNTIME_FUNCTION eagerly. This path is only
// reachable via EECodeInfo::GetMainFunctionInfo, and so we can just return the main entry.
_ASSERTE(pCodeInfo->GetRelOffset() == 0);
return dac_cast<PTR_RUNTIME_FUNCTION>(pCodeInfo->GetMethodToken().m_pCodeHeader);
}
TADDR ReadyToRunJitManager::GetFuncletStartAddress(EECodeInfo * pCodeInfo)
{
LIMITED_METHOD_DAC_CONTRACT;
return IJitManager::GetFuncletStartAddress(pCodeInfo);
}
DWORD ReadyToRunJitManager::GetFuncletStartOffsets(const METHODTOKEN& MethodToken, DWORD* pStartFuncletOffsets, DWORD dwLength)
{
PTR_RUNTIME_FUNCTION pFirstFuncletFunctionEntry = dac_cast<PTR_RUNTIME_FUNCTION>(MethodToken.m_pCodeHeader) + 1;
TADDR moduleBase = JitTokenToModuleBase(MethodToken);
DWORD nFunclets = 0;
MethodRegionInfo regionInfo;
JitTokenToMethodRegionInfo(MethodToken, ®ionInfo);
// pFirstFuncletFunctionEntry will work for ARM when passed to GetFuncletStartOffsetsHelper()
// even if it is a fragment of the main body and not a RUNTIME_FUNCTION for the beginning
// of the first hot funclet, because GetFuncletStartOffsetsHelper() will skip all the function
// fragments until the first funclet, if any, is found.
GetFuncletStartOffsetsHelper(regionInfo.hotStartAddress, regionInfo.hotSize, 0,
pFirstFuncletFunctionEntry, moduleBase,
&nFunclets, pStartFuncletOffsets, dwLength);
// Technically, the cold code is not a funclet, but it looks like the debugger wants it
if (regionInfo.coldSize > 0)
{
ReadyToRunInfo * pInfo = JitTokenToReadyToRunInfo(MethodToken);
PTR_RUNTIME_FUNCTION pRuntimeFunctions = pInfo->m_pRuntimeFunctions;
int i = 0;
while (true)
{
pFirstFuncletFunctionEntry = pRuntimeFunctions + i;
if (regionInfo.coldStartAddress == moduleBase + RUNTIME_FUNCTION__BeginAddress(pFirstFuncletFunctionEntry))
{
break;
}
i++;
}
GetFuncletStartOffsetsHelper(regionInfo.coldStartAddress, regionInfo.coldSize, 0,
pFirstFuncletFunctionEntry, moduleBase,
&nFunclets, pStartFuncletOffsets, dwLength);
}
return nFunclets;
}
BOOL ReadyToRunJitManager::IsFunclet(EECodeInfo* pCodeInfo)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
HOST_NOCALLS;
SUPPORTS_DAC;
} CONTRACTL_END;
ReadyToRunInfo * pInfo = JitTokenToReadyToRunInfo(pCodeInfo->GetMethodToken());
COUNT_T nRuntimeFunctions = pInfo->m_nRuntimeFunctions;
PTR_RUNTIME_FUNCTION pRuntimeFunctions = pInfo->m_pRuntimeFunctions;
ULONG methodIndex = (ULONG)(pCodeInfo->GetFunctionEntry() - pRuntimeFunctions);
const int lookupIndex = HotColdMappingLookupTable::LookupMappingForMethod(pInfo, methodIndex);
if ((lookupIndex != -1) && ((lookupIndex & 1) == 1))
{
// This maps to a hot entry in the lookup table, so check its unwind info
SIZE_T unwindSize;
PTR_VOID pUnwindData = GetUnwindDataBlob(pCodeInfo->GetModuleBase(), pCodeInfo->GetFunctionEntry(), &unwindSize);
_ASSERTE(pUnwindData != NULL);
#ifdef TARGET_AMD64
// Chained unwind info is used only for cold part of the main code
const UCHAR chainedUnwindFlag = (((PTR_UNWIND_INFO)pUnwindData)->Flags & UNW_FLAG_CHAININFO);
return (chainedUnwindFlag == 0);
#else
// TODO: We need a solution for arm64 here
return false;
#endif
}
// Fall back to existing logic if it is not cold
TADDR funcletStartAddress = GetFuncletStartAddress(pCodeInfo);
TADDR methodStartAddress = pCodeInfo->GetStartAddress();
return (funcletStartAddress != methodStartAddress);
}
BOOL ReadyToRunJitManager::IsFilterFunclet(EECodeInfo * pCodeInfo)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
if (!pCodeInfo->IsFunclet())
return FALSE;
// Get address of the personality routine for the function being queried.
SIZE_T size;
PTR_VOID pUnwindData = GetUnwindDataBlob(pCodeInfo->GetModuleBase(), pCodeInfo->GetFunctionEntry(), &size);
_ASSERTE(pUnwindData != NULL);
// Personality routine is always the last element of the unwind data
DWORD rvaPersonalityRoutine = *(dac_cast<PTR_DWORD>(dac_cast<TADDR>(pUnwindData) + size) - 1);
// Get the personality routine for the first function in the module, which is guaranteed to be not a funclet.
ReadyToRunInfo * pInfo = JitTokenToReadyToRunInfo(pCodeInfo->GetMethodToken());
if (pInfo->m_nRuntimeFunctions == 0)
return FALSE;
PTR_VOID pFirstUnwindData = GetUnwindDataBlob(pCodeInfo->GetModuleBase(), pInfo->m_pRuntimeFunctions, &size);
_ASSERTE(pFirstUnwindData != NULL);
DWORD rvaFirstPersonalityRoutine = *(dac_cast<PTR_DWORD>(dac_cast<TADDR>(pFirstUnwindData) + size) - 1);
// Compare the two personality routines. If they are different, then the current function is a filter funclet.
BOOL fRet = (rvaPersonalityRoutine != rvaFirstPersonalityRoutine);
// Verify that the optimized implementation is in sync with the slow implementation
_ASSERTE(fRet == IJitManager::IsFilterFunclet(pCodeInfo));
return fRet;
}
#endif // FEATURE_EH_FUNCLETS
void ReadyToRunJitManager::JitTokenToMethodRegionInfo(const METHODTOKEN& MethodToken,
MethodRegionInfo * methodRegionInfo)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
HOST_NOCALLS;
SUPPORTS_DAC;
PRECONDITION(methodRegionInfo != NULL);
} CONTRACTL_END;
methodRegionInfo->hotStartAddress = JitTokenToStartAddress(MethodToken);
methodRegionInfo->hotSize = GetCodeManager()->GetFunctionSize(GetGCInfoToken(MethodToken));
methodRegionInfo->coldStartAddress = 0;
methodRegionInfo->coldSize = 0;
ReadyToRunInfo * pInfo = JitTokenToReadyToRunInfo(MethodToken);
COUNT_T nRuntimeFunctions = pInfo->m_nRuntimeFunctions;
PTR_RUNTIME_FUNCTION pRuntimeFunctions = pInfo->m_pRuntimeFunctions;
PTR_RUNTIME_FUNCTION pRuntimeFunction = dac_cast<PTR_RUNTIME_FUNCTION>(MethodToken.m_pCodeHeader);
ULONG methodIndex = (ULONG)(pRuntimeFunction - pRuntimeFunctions);
const int lookupIndex = HotColdMappingLookupTable::LookupMappingForMethod(pInfo, methodIndex);
// If true, this method has no cold code
if (lookupIndex == -1)
{
return;
}
#ifdef TARGET_X86
_ASSERTE(!"hot cold splitting is not supported for x86");
#else
_ASSERTE((lookupIndex & 1) == 0);
ULONG coldMethodIndex = pInfo->m_pHotColdMap[lookupIndex];
PTR_RUNTIME_FUNCTION pColdRuntimeFunction = pRuntimeFunctions + coldMethodIndex;
methodRegionInfo->coldStartAddress = JitTokenToModuleBase(MethodToken)
+ RUNTIME_FUNCTION__BeginAddress(pColdRuntimeFunction);
ULONG coldMethodIndexNext;
if ((ULONG)(lookupIndex) == (pInfo->m_nHotColdMap - 2))
{
coldMethodIndexNext = nRuntimeFunctions - 1;
}
else
{
coldMethodIndexNext = pInfo->m_pHotColdMap[lookupIndex + 2] - 1;
}
PTR_RUNTIME_FUNCTION pLastRuntimeFunction = pRuntimeFunctions + coldMethodIndexNext;
methodRegionInfo->coldSize = RUNTIME_FUNCTION__EndAddress(pLastRuntimeFunction, 0)
- RUNTIME_FUNCTION__BeginAddress(pColdRuntimeFunction);
methodRegionInfo->hotSize -= methodRegionInfo->coldSize;
#endif //TARGET_X86
}
#ifdef DACCESS_COMPILE
void ReadyToRunJitManager::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
IJitManager::EnumMemoryRegions(flags);
}
#if defined(FEATURE_EH_FUNCLETS)
//
// EnumMemoryRegionsForMethodUnwindInfo - enumerate the memory necessary to read the unwind info for the
// specified method.
//
// Note that in theory, a dump generation library could save the unwind information itself without help
// from us, since it's stored in the image in the standard function table layout for Win64. However,
// dump-generation libraries assume that the image will be available at debug time, and if the image
// isn't available then it is acceptable for stackwalking to break. For ngen images (which are created
// on the client), it usually isn't possible to have the image available at debug time, and so for minidumps
// we must explicitly ensure the unwind information is saved into the dump.
//
// Arguments:
// flags - EnumMem flags
// pMD - MethodDesc for the method in question
//
void ReadyToRunJitManager::EnumMemoryRegionsForMethodUnwindInfo(CLRDataEnumMemoryFlags flags, EECodeInfo * pCodeInfo)
{
// Get the RUNTIME_FUNCTION entry for this method
PTR_RUNTIME_FUNCTION pRtf = pCodeInfo->GetFunctionEntry();
if (pRtf==NULL)
{
return;
}
// Enumerate the function entry and other entries needed to locate it in the program exceptions directory
ReadyToRunInfo * pReadyToRunInfo = JitTokenToReadyToRunInfo(pCodeInfo->GetMethodToken());
EnumRuntimeFunctionEntriesToFindEntry(pRtf, pReadyToRunInfo->GetImage());
SIZE_T size;
PTR_VOID pUnwindData = GetUnwindDataBlob(pCodeInfo->GetModuleBase(), pRtf, &size);
if (pUnwindData != NULL)
DacEnumMemoryRegion(PTR_TO_TADDR(pUnwindData), size);
}
#endif //FEATURE_EH_FUNCLETS
#endif // #ifdef DACCESS_COMPILE
#endif
| [
"dotnet-maestro[bot]@users.noreply.github.com"
] | dotnet-maestro[bot]@users.noreply.github.com |
86388bedcac37aae0a77e35edbcf62757565b400 | a1b4d9a091dfd3720167e07aed0930fe0d3f4dbc | /secindexs/src/common/message_event.h | bbfcb417d1167674d4f1094da18805652df61f31 | [
"MIT"
] | permissive | pravblockc/secondary-indexes | 306aee834bc32603cc1ab1bf834119883ca4b552 | b7aeef8319c9fa9e6b8b335ed7fedf8a7a76de01 | refs/heads/master | 2023-07-28T22:18:46.284511 | 2021-09-21T17:35:08 | 2021-09-21T17:35:08 | 408,839,483 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,371 | h | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#pragma once
#include <cstdint>
#include "common/string_data.h"
#include "common/log_component.h"
#include "common/log_severity.h"
#include "common/time_support.h"
namespace mongo {
namespace logger {
/**
* Free form text log message object that does not own the storage behind its message and
* contextName.
*
* Used and owned by one thread. This is the message type used by MessageLogDomain.
*/
class MessageEventEphemeral {
public:
MessageEventEphemeral(Date_t date,
LogSeverity severity,
StringData contextName,
StringData message)
: MessageEventEphemeral(date, severity, LogComponent::kDefault, contextName, message) {}
MessageEventEphemeral(Date_t date,
LogSeverity severity,
LogComponent component,
StringData contextName,
StringData message)
: _date(date),
_severity(severity),
_component(component),
_contextName(contextName),
_message(message) {}
MessageEventEphemeral& setIsTruncatable(bool value) {
_isTruncatable = value;
return *this;
}
Date_t getDate() const {
return _date;
}
LogSeverity getSeverity() const {
return _severity;
}
LogComponent getComponent() const {
return _component;
}
StringData getContextName() const {
return _contextName;
}
StringData getMessage() const {
return _message;
}
bool isTruncatable() const {
return _isTruncatable;
}
private:
Date_t _date;
LogSeverity _severity;
LogComponent _component;
StringData _contextName;
StringData _message;
bool _isTruncatable = true;
};
} // namespace logger
} // namespace mongo
| [
"pravin.blockc@gmail.com"
] | pravin.blockc@gmail.com |
53e698b082ca68a0eac26468ce2071048a2d73fe | d2a258b02cb941d012273558f4b6c2281ca56eeb | /ds/002_Stack/StackSTL.h | ad08f5f3159405cc4eb0fbf42c4c650164ea7c42 | [] | no_license | jitendrakr54/Learning | 7b379e4c015d47063d797042f4e83ffbdebef483 | 58e1443e91a644381e63bf9847c281043b23c5f8 | refs/heads/master | 2023-07-26T16:09:51.352594 | 2021-09-06T09:54:20 | 2021-09-06T09:54:20 | 391,670,709 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 811 | h | /*
* StackSTL.h
*
* Created on: 04-Nov-2020
* Author: Jitendra
*/
#pragma once
#include <iostream>
#include <cassert>
namespace ds {
namespace stack {
template<class T>
class StackSTL {
private:
int size{};
int top;
T *arr{};
public:
StackSTL(int length) : size{length}, top{-1}{
assert( size > 0 );
arr = new T[size];
}
~StackSTL() { delete[] arr; }
void push(T data) {
if(isFull()) {
std::cout<<"Stack is overflow! \n";
return;
}
arr[++top] = data;
}
T pop() {
if(isEmpty()) {
std::cout<<"Stack is empty! \n";
exit(0);
}
return arr[top--];
}
bool isEmpty() {
return top == -1;
}
bool isFull() {
return top == size-1;
}
T peek() {
return arr[top];
}
};
}
}
| [
"jitendrakr54@gmail.com"
] | jitendrakr54@gmail.com |
4ee16d325b805fcb11c3dfaba0517f188b475986 | b4f42eed62aa7ef0e28f04c1f455f030115ec58e | /messagingfw/msgtestproduct/media/inc/t_mediatestserver.h | ead1c0337bed359196e3355de513d782429564ed | [] | no_license | SymbianSource/oss.FCL.sf.mw.messagingmw | 6addffd79d854f7a670cbb5d89341b0aa6e8c849 | 7af85768c2d2bc370cbb3b95e01103f7b7577455 | refs/heads/master | 2021-01-17T16:45:41.697969 | 2010-11-03T17:11:46 | 2010-11-03T17:11:46 | 71,851,820 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,964 | h | // Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
// @file
// This contains CT_MediaTestServer
//
//
/**
@test
@internalComponent
*/
#ifndef __C_TEF_INTEGRATION_TEST_SERVER__
#define __C_TEF_INTEGRATION_TEST_SERVER__
#include <test\testblockcontroller.h>
#include <test\testserver2.h>
#include "t_mediatestwrapper.h"
#include "t_oomtestwrapper.h"
#include "t_cenreptestwrapper.h"
#include "t_setsubsttestwrapper.h"
_LIT(KMediaTestWrapper, "MediaTestWrapper");
_LIT(KOomTestWrapper, "OomTestWrapper");
_LIT(KCenRepTestWrapper, "CenRepTestWrapper");
_LIT(KSetSubstTestWrapper, "SetSubstTestWrapper");
class CT_MediaTestBlock : public CTestBlockController
{
public:
CT_MediaTestBlock() : CTestBlockController() {}
~CT_MediaTestBlock() {}
CDataWrapper* CreateDataL(const TDesC& aData)
{
CDataWrapper* wrapper = NULL;
if (KMediaTestWrapper() == aData)
{
wrapper = CT_MediaTestWrapper::NewL();
}
else if (KOomTestWrapper() == aData)
{
wrapper = CT_OomTestWrapper::NewL();
}
else if (KCenRepTestWrapper() == aData)
{
wrapper = CT_CenRepTestWrapper::NewL();
}
else if (KSetSubstTestWrapper() == aData)
{
wrapper = CT_SetSubstTestWrapper::NewL();
}
return wrapper;
}
};
class CT_MediaTestServer : public CTestServer2
{
public:
CT_MediaTestServer() {}
~CT_MediaTestServer() {}
static CT_MediaTestServer* NewL();
CTestBlockController* CreateTestBlock()
{
CTestBlockController* controller = new (ELeave) CT_MediaTestBlock();
return controller;
}
};
#endif // __C_TEF_INTEGRATION_TEST_SERVER__
| [
"none@none"
] | none@none |
759aa0e43c43e86d34bd3e11ddfe4f7d680e7dc9 | af0ecafb5428bd556d49575da2a72f6f80d3d14b | /CodeJamCrawler/dataset/09_11405_99.cpp | 26ff8e1799f9cb6d79f7082d782c9a714d453b37 | [] | no_license | gbrlas/AVSP | 0a2a08be5661c1b4a2238e875b6cdc88b4ee0997 | e259090bf282694676b2568023745f9ffb6d73fd | refs/heads/master | 2021-06-16T22:25:41.585830 | 2017-06-09T06:32:01 | 2017-06-09T06:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 724 | cpp | #include <iostream>
#include <cstdio>
using namespace std;
bool is[20][500];
char a[5005][20];
char p[100000000];
int main()
{
freopen("in.txt","rt",stdin);
freopen("Aout.txt","wt",stdout);
int l,n,d,i,j,k,m;
scanf("%d %d %d ",&l,&d,&n);
for(i=0;i<d;i++)
gets(a[i]);
p[0] = ')';
for(k=0;k<n;++k)
{
gets(p+1);
m = (int)strlen(p);
memset(is,0,sizeof(is) );
j = 0;
for(i=1;i<m;i++)
{
if(p[i]=='(' )
while(p[i]!=')')
is[j][p[i++]] = 1;
else is[j][p[i]] = 1;
j++;
}
int ans = 0;
for(i=0;i<d;i++)
{
for(j=0;j<l;j++)
if(!is[j][a[i][j]])
break;
if(j<l) continue;
ans++;
}
printf("Case #%d: %d\n",k+1,ans);
}
return 0;
} | [
"nikola.mrzljak@fer.hr"
] | nikola.mrzljak@fer.hr |
ce4b873d127813ebc4a50110ac639100c6167bd3 | 60e58a41cabf059812a7bba5267f175689bbc48f | /WickedEngine/wiFont.cpp | abe918d562acbd2a93111b359105568f64e86ac3 | [
"MIT",
"Zlib",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | all500234765/WickedEngine | e6b7d74276a1bb9266f30496786c9c4df478f4dd | b4aac25021454da93b90e213ee2f8a274a6bd76c | refs/heads/master | 2020-05-21T01:17:52.927015 | 2019-05-08T18:00:12 | 2019-05-08T18:00:12 | 185,854,045 | 1 | 0 | null | 2019-05-09T18:45:41 | 2019-05-09T18:45:40 | null | UTF-8 | C++ | false | false | 17,122 | cpp | #include "wiFont.h"
#include "wiRenderer.h"
#include "wiResourceManager.h"
#include "wiHelper.h"
#include "ResourceMapping.h"
#include "ShaderInterop_Font.h"
#include "wiBackLog.h"
#include "wiTextureHelper.h"
#include "wiRectPacker.h"
#include "wiSpinLock.h"
#include "Utility/stb_truetype.h"
#include <fstream>
#include <sstream>
#include <atomic>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
using namespace wiGraphics;
using namespace wiRectPacker;
#define MAX_TEXT 10000
#define WHITESPACE_SIZE (int((params.size + params.spacingX) * params.scaling * 0.3f))
#define TAB_SIZE (WHITESPACE_SIZE * 4)
#define LINEBREAK_SIZE (int((params.size + params.spacingY) * params.scaling))
namespace wiFont_Internal
{
std::string FONTPATH = "fonts/";
GPUBuffer indexBuffer;
GPUBuffer constantBuffer;
BlendState blendState;
RasterizerState rasterizerState;
DepthStencilState depthStencilState;
Sampler sampler;
VertexLayout vertexLayout;
const VertexShader *vertexShader = nullptr;
const PixelShader *pixelShader = nullptr;
GraphicsPSO PSO;
atomic_bool initialized = false;
Texture2D texture;
struct Glyph
{
int16_t x;
int16_t y;
int16_t width;
int16_t height;
uint16_t tc_left;
uint16_t tc_right;
uint16_t tc_top;
uint16_t tc_bottom;
};
unordered_map<int32_t, Glyph> glyph_lookup;
unordered_map<int32_t, rect_xywh> rect_lookup;
// pack glyph identifiers to a 32-bit hash:
// height: 10 bits (height supported: 0 - 1023)
// style: 6 bits (number of font styles supported: 0 - 63)
// code: 16 bits (character code range supported: 0 - 65535)
constexpr int32_t glyphhash(int code, int style, int height) { return ((code & 0xFFFF) << 16) | ((style & 0x3F) << 10) | (height & 0x3FF); }
constexpr int codefromhash(int64_t hash) { return int((hash >> 16) & 0xFFFF); }
constexpr int stylefromhash(int64_t hash) { return int((hash >> 10) & 0x3F); }
constexpr int heightfromhash(int64_t hash) { return int((hash >> 0) & 0x3FF); }
unordered_set<int32_t> pendingGlyphs;
wiSpinLock glyphLock;
struct wiFontStyle
{
string name;
vector<uint8_t> fontBuffer;
stbtt_fontinfo fontInfo;
int ascent, descent, lineGap;
wiFontStyle(const string& newName) : name(newName)
{
wiHelper::readByteData(newName, fontBuffer);
int offset = stbtt_GetFontOffsetForIndex(fontBuffer.data(), 0);
if (!stbtt_InitFont(&fontInfo, fontBuffer.data(), offset))
{
stringstream ss("");
ss << "Failed to load font: " << name;
wiHelper::messageBox(ss.str());
}
stbtt_GetFontVMetrics(&fontInfo, &ascent, &descent, &lineGap);
}
};
std::vector<wiFontStyle*> fontStyles;
struct FontVertex
{
XMSHORT2 Pos;
XMHALF2 Tex;
};
int WriteVertices(volatile FontVertex* vertexList, const std::wstring& text, wiFontParams params, int style)
{
int quadCount = 0;
int16_t line = 0;
int16_t pos = 0;
for (auto& code : text)
{
const int32_t hash = glyphhash(code, style, params.size);
if (glyph_lookup.count(hash) == 0)
{
// glyph not packed yet, so add to pending list:
glyphLock.lock();
pendingGlyphs.insert(hash);
glyphLock.unlock();
continue;
}
if (code == '\n')
{
line += LINEBREAK_SIZE;
pos = 0;
}
else if (code == ' ')
{
pos += WHITESPACE_SIZE;
}
else if (code == '\t')
{
pos += TAB_SIZE;
}
else
{
const Glyph& glyph = glyph_lookup.at(hash);
const int16_t glyphWidth = int16_t(glyph.width * params.scaling);
const int16_t glyphHeight = int16_t(glyph.height * params.scaling);
const int16_t glyphOffsetX = int16_t(glyph.x * params.scaling);
const int16_t glyphOffsetY = int16_t(glyph.y * params.scaling);
const size_t vertexID = quadCount * 4;
const int16_t left = pos + glyphOffsetX;
const int16_t right = left + glyphWidth;
const int16_t top = line + glyphOffsetY;
const int16_t bottom = top + glyphHeight;
vertexList[vertexID + 0].Pos.x = left;
vertexList[vertexID + 0].Pos.y = top;
vertexList[vertexID + 1].Pos.x = right;
vertexList[vertexID + 1].Pos.y = top;
vertexList[vertexID + 2].Pos.x = left;
vertexList[vertexID + 2].Pos.y = bottom;
vertexList[vertexID + 3].Pos.x = right;
vertexList[vertexID + 3].Pos.y = bottom;
vertexList[vertexID + 0].Tex.x = glyph.tc_left;
vertexList[vertexID + 0].Tex.y = glyph.tc_top;
vertexList[vertexID + 1].Tex.x = glyph.tc_right;
vertexList[vertexID + 1].Tex.y = glyph.tc_top;
vertexList[vertexID + 2].Tex.x = glyph.tc_left;
vertexList[vertexID + 2].Tex.y = glyph.tc_bottom;
vertexList[vertexID + 3].Tex.x = glyph.tc_right;
vertexList[vertexID + 3].Tex.y = glyph.tc_bottom;
pos += int16_t((glyph.width + params.spacingX) * params.scaling);
quadCount++;
}
}
return quadCount;
}
}
using namespace wiFont_Internal;
wiFont::wiFont(const std::string& text, wiFontParams params, int style) : params(params), style(style)
{
SetText(text);
}
wiFont::wiFont(const std::wstring& text, wiFontParams params, int style) : params(params), style(style)
{
SetText(text);
}
void wiFont::Initialize()
{
if (initialized)
{
return;
}
// add default font if there is none yet:
if (fontStyles.empty())
{
AddFontStyle(FONTPATH + "arial.ttf");
}
GraphicsDevice* device = wiRenderer::GetDevice();
{
uint16_t indices[MAX_TEXT * 6];
for (uint16_t i = 0; i < MAX_TEXT * 4; i += 4)
{
indices[i / 4 * 6 + 0] = i + 0;
indices[i / 4 * 6 + 1] = i + 2;
indices[i / 4 * 6 + 2] = i + 1;
indices[i / 4 * 6 + 3] = i + 1;
indices[i / 4 * 6 + 4] = i + 2;
indices[i / 4 * 6 + 5] = i + 3;
}
GPUBufferDesc bd;
bd.Usage = USAGE_IMMUTABLE;
bd.ByteWidth = sizeof(indices);
bd.BindFlags = BIND_INDEX_BUFFER;
bd.CPUAccessFlags = 0;
SubresourceData InitData;
InitData.pSysMem = indices;
HRESULT hr = device->CreateBuffer(&bd, &InitData, &indexBuffer);
assert(SUCCEEDED(hr));
}
{
GPUBufferDesc bd;
bd.Usage = USAGE_DYNAMIC;
bd.ByteWidth = sizeof(FontCB);
bd.BindFlags = BIND_CONSTANT_BUFFER;
bd.CPUAccessFlags = CPU_ACCESS_WRITE;
HRESULT hr = device->CreateBuffer(&bd, nullptr, &constantBuffer);
assert(SUCCEEDED(hr));
}
RasterizerStateDesc rs;
rs.FillMode = FILL_SOLID;
rs.CullMode = CULL_BACK;
rs.FrontCounterClockwise = true;
rs.DepthBias = 0;
rs.DepthBiasClamp = 0;
rs.SlopeScaledDepthBias = 0;
rs.DepthClipEnable = false;
rs.MultisampleEnable = false;
rs.AntialiasedLineEnable = false;
device->CreateRasterizerState(&rs, &rasterizerState);
DepthStencilStateDesc dsd;
dsd.DepthEnable = false;
dsd.StencilEnable = false;
device->CreateDepthStencilState(&dsd, &depthStencilState);
BlendStateDesc bd;
bd.RenderTarget[0].BlendEnable = true;
bd.RenderTarget[0].SrcBlend = BLEND_ONE;
bd.RenderTarget[0].DestBlend = BLEND_INV_SRC_ALPHA;
bd.RenderTarget[0].BlendOp = BLEND_OP_ADD;
bd.RenderTarget[0].SrcBlendAlpha = BLEND_ONE;
bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE;
bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD;
bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL;
bd.IndependentBlendEnable = false;
device->CreateBlendState(&bd, &blendState);
SamplerDesc samplerDesc;
samplerDesc.Filter = FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = TEXTURE_ADDRESS_BORDER;
samplerDesc.AddressV = TEXTURE_ADDRESS_BORDER;
samplerDesc.AddressW = TEXTURE_ADDRESS_BORDER;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 0;
samplerDesc.ComparisonFunc = COMPARISON_NEVER;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = FLT_MAX;
device->CreateSamplerState(&samplerDesc, &sampler);
LoadShaders();
wiBackLog::post("wiFont Initialized");
initialized.store(true);
}
void wiFont::CleanUp()
{
fontStyles.clear();
}
void wiFont::LoadShaders()
{
std::string path = wiRenderer::GetShaderPath();
VertexLayoutDesc layout[] =
{
{ "POSITION", 0, FORMAT_R16G16_SINT, 0, VertexLayoutDesc::APPEND_ALIGNED_ELEMENT, INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, FORMAT_R16G16_FLOAT, 0, VertexLayoutDesc::APPEND_ALIGNED_ELEMENT, INPUT_PER_VERTEX_DATA, 0 },
};
vertexShader = static_cast<const VertexShader*>(wiResourceManager::GetShaderManager().add(path + "fontVS.cso", wiResourceManager::VERTEXSHADER));
wiRenderer::GetDevice()->CreateInputLayout(layout, ARRAYSIZE(layout), &vertexShader->code, &vertexLayout);
pixelShader = static_cast<const PixelShader*>(wiResourceManager::GetShaderManager().add(path + "fontPS.cso", wiResourceManager::PIXELSHADER));
GraphicsPSODesc desc;
desc.vs = vertexShader;
desc.ps = pixelShader;
desc.il = &vertexLayout;
desc.bs = &blendState;
desc.rs = &rasterizerState;
desc.dss = &depthStencilState;
desc.numRTs = 1;
desc.RTFormats[0] = wiRenderer::GetDevice()->GetBackBufferFormat();
wiRenderer::GetDevice()->CreateGraphicsPSO(&desc, &PSO);
}
void UpdatePendingGlyphs()
{
// If there are pending glyphs, render them and repack the atlas:
if (!pendingGlyphs.empty())
{
// Pad the glyph rects in the atlas to avoid bleeding from nearby texels:
const int borderPadding = 1;
for (int32_t hash : pendingGlyphs)
{
const int code = codefromhash(hash);
const int style = stylefromhash(hash);
const int height = heightfromhash(hash);
wiFontStyle& fontStyle = *fontStyles[style];
float fontScaling = stbtt_ScaleForPixelHeight(&fontStyle.fontInfo, float(height));
// get bounding box for character (may be offset to account for chars that dip above or below the line
int left, top, right, bottom;
stbtt_GetCodepointBitmapBox(&fontStyle.fontInfo, code, fontScaling, fontScaling, &left, &top, &right, &bottom);
// Glyph dimensions are calculated without padding:
Glyph& glyph = glyph_lookup[hash];
glyph.x = left;
glyph.y = top + int(fontStyle.ascent * fontScaling);
glyph.width = right - left;
glyph.height = bottom - top;
// Add padding to the rectangle that will be packed in the atlas:
right += borderPadding * 2;
bottom += borderPadding * 2;
rect_lookup[hash] = rect_ltrb(left, top, right, bottom);
}
pendingGlyphs.clear();
// This reference array will be used for packing:
vector<rect_xywh*> out_rects;
out_rects.reserve(rect_lookup.size());
for (auto& it : rect_lookup)
{
out_rects.push_back(&it.second);
}
// Perform packing and process the result if successful:
std::vector<bin> bins;
if (pack(out_rects.data(), (int)out_rects.size(), 4096, bins))
{
assert(bins.size() == 1 && "The regions won't fit into one texture!");
// Retrieve texture atlas dimensions:
const int bitmapWidth = bins[0].size.w;
const int bitmapHeight = bins[0].size.h;
const float inv_width = 1.0f / bitmapWidth;
const float inv_height = 1.0f / bitmapHeight;
// Create the CPU-side texture atlas and fill with transparency (0):
vector<uint8_t> bitmap(bitmapWidth * bitmapHeight);
std::fill(bitmap.begin(), bitmap.end(), 0);
// Iterate all packed glyph rectangles:
for (auto it : rect_lookup)
{
const int32_t hash = it.first;
const wchar_t code = codefromhash(hash);
const int style = stylefromhash(hash);
const int height = heightfromhash(hash);
wiFontStyle& fontStyle = *fontStyles[style];
rect_xywh& rect = it.second;
Glyph& glyph = glyph_lookup[hash];
// Remove border padding from the packed rectangle (we don't want to touch the border, it should stay transparent):
rect.x += borderPadding;
rect.y += borderPadding;
rect.w -= borderPadding * 2;
rect.h -= borderPadding * 2;
float fontScaling = stbtt_ScaleForPixelHeight(&fontStyle.fontInfo, float(height));
// Render the glyph inside the CPU-side atlas:
int byteOffset = rect.x + (rect.y * bitmapWidth);
stbtt_MakeCodepointBitmap(&fontStyle.fontInfo, bitmap.data() + byteOffset, rect.w, rect.h, bitmapWidth, fontScaling, fontScaling, code);
// Compute texture coordinates for the glyph:
float tc_left = float(rect.x);
float tc_right = tc_left + float(rect.w);
float tc_top = float(rect.y);
float tc_bottom = tc_top + float(rect.h);
tc_left *= inv_width;
tc_right *= inv_width;
tc_top *= inv_height;
tc_bottom *= inv_height;
glyph.tc_left = XMConvertFloatToHalf(tc_left);
glyph.tc_right = XMConvertFloatToHalf(tc_right);
glyph.tc_top = XMConvertFloatToHalf(tc_top);
glyph.tc_bottom = XMConvertFloatToHalf(tc_bottom);
}
// Upload the CPU-side texture atlas bitmap to the GPU:
HRESULT hr = wiTextureHelper::CreateTexture(texture, bitmap.data(), bitmapWidth, bitmapHeight, FORMAT_R8_UNORM);
assert(SUCCEEDED(hr));
}
}
}
const Texture2D* wiFont::GetAtlas()
{
return &texture;
}
std::string& wiFont::GetFontPath()
{
return FONTPATH;
}
int wiFont::AddFontStyle(const string& fontName)
{
for (size_t i = 0; i < fontStyles.size(); i++)
{
const wiFontStyle& fontStyle = *fontStyles[i];
if (!fontStyle.name.compare(fontName))
{
return int(i);
}
}
fontStyles.push_back(new wiFontStyle(fontName));
return int(fontStyles.size() - 1);
}
void wiFont::Draw(GRAPHICSTHREAD threadID) const
{
if (!initialized.load() || text.length() <= 0)
{
return;
}
wiFontParams newProps = params;
if (params.h_align == WIFALIGN_CENTER)
newProps.posX -= textWidth() / 2;
else if (params.h_align == WIFALIGN_RIGHT)
newProps.posX -= textWidth();
if (params.v_align == WIFALIGN_CENTER)
newProps.posY -= textHeight() / 2;
else if (params.v_align == WIFALIGN_BOTTOM)
newProps.posY -= textHeight();
GraphicsDevice* device = wiRenderer::GetDevice();
GraphicsDevice::GPUAllocation mem = device->AllocateGPU(sizeof(FontVertex) * text.length() * 4, threadID);
if (!mem.IsValid())
{
return;
}
volatile FontVertex* textBuffer = (volatile FontVertex*)mem.data;
const int quadCount = WriteVertices(textBuffer, text, newProps, style);
device->EventBegin("Font", threadID);
device->BindGraphicsPSO(&PSO, threadID);
device->BindConstantBuffer(VS, &constantBuffer, CB_GETBINDSLOT(FontCB), threadID);
device->BindConstantBuffer(PS, &constantBuffer, CB_GETBINDSLOT(FontCB), threadID);
device->BindResource(PS, &texture, TEXSLOT_FONTATLAS, threadID);
device->BindSampler(PS, &sampler, SSLOT_ONDEMAND1, threadID);
const GPUBuffer* vbs[] = {
mem.buffer,
};
const UINT strides[] = {
sizeof(FontVertex),
};
const UINT offsets[] = {
mem.offset,
};
device->BindVertexBuffers(vbs, 0, ARRAYSIZE(vbs), strides, offsets, threadID);
assert(text.length() * 4 < 65536 && "The index buffer currently only supports so many characters!");
device->BindIndexBuffer(&indexBuffer, INDEXFORMAT_16BIT, 0, threadID);
FontCB cb;
if (newProps.shadowColor.getA() > 0)
{
// font shadow render:
XMStoreFloat4x4(&cb.g_xFont_Transform, XMMatrixTranspose(
XMMatrixTranslation((float)newProps.posX + 1, (float)newProps.posY + 1, 0)
* device->GetScreenProjection()
));
cb.g_xFont_Color = newProps.shadowColor.toFloat4();
device->UpdateBuffer(&constantBuffer, &cb, threadID);
device->DrawIndexed(quadCount * 6, 0, 0, threadID);
}
// font base render:
XMStoreFloat4x4(&cb.g_xFont_Transform, XMMatrixTranspose(
XMMatrixTranslation((float)newProps.posX, (float)newProps.posY, 0)
* device->GetScreenProjection()
));
cb.g_xFont_Color = newProps.color.toFloat4();
device->UpdateBuffer(&constantBuffer, &cb, threadID);
device->DrawIndexed(quadCount * 6, 0, 0, threadID);
device->EventEnd(threadID);
UpdatePendingGlyphs();
}
int wiFont::textWidth() const
{
if (style >= fontStyles.size())
{
return 0;
}
int maxWidth = 0;
int currentLineWidth = 0;
for (auto& code : text)
{
const int32_t hash = glyphhash(code, style, params.size);
if (glyph_lookup.count(hash) == 0)
{
// glyph not packed yet, we just continue (it will be added if it is actually rendered)
continue;
}
if (code == '\n')
{
currentLineWidth = 0;
}
else if (code == ' ')
{
currentLineWidth += WHITESPACE_SIZE;
}
else if (code == '\t')
{
currentLineWidth += TAB_SIZE;
}
else
{
const Glyph& glyph = glyph_lookup.at(hash);
currentLineWidth += int((glyph.width + params.spacingX) * params.scaling);
}
maxWidth = max(maxWidth, currentLineWidth);
}
return maxWidth;
}
int wiFont::textHeight() const
{
if (style >= fontStyles.size())
{
return 0;
}
int height = LINEBREAK_SIZE;
for(auto& code : text)
{
if (code == '\n')
{
height += LINEBREAK_SIZE;
}
}
return height;
}
void wiFont::SetText(const string& text)
{
#ifdef WIN32
int wchars_num = MultiByteToWideChar(CP_UTF8, 0, text.c_str(), -1, NULL, 0);
wchar_t* wstr = new wchar_t[wchars_num];
MultiByteToWideChar(CP_UTF8, 0, text.c_str(), -1, wstr, wchars_num);
this->text = wstr;
delete[] wstr;
#else
this->text = wstring(text.begin(), text.end());
#endif
}
void wiFont::SetText(const wstring& text)
{
this->text = text;
}
wstring wiFont::GetText() const
{
return text;
}
string wiFont::GetTextA() const
{
return string(text.begin(),text.end());
}
| [
"turanszkij@gmail.com"
] | turanszkij@gmail.com |
52b010721ee908370b92e0b4ccfc713d063c15f3 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/HostedIPInterface/UNIX_HostedIPInterfaceMain.cpp | ddb620d19fae8ae279b99e8edcf0d95417af0952 | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,278 | cpp | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#include <Pegasus/Common/Config.h>
#include <Pegasus/Common/String.h>
#include <Pegasus/Common/PegasusVersion.h>
#include <UNIX_Common.h>
PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;
using PROVIDER_LIB_NS::CIMHelper;
#include <HostedIPInterface/UNIX_HostedIPInterfaceProvider.h>
extern "C"
PEGASUS_EXPORT CIMProvider* PegasusCreateProvider(const String& providerName)
{
if (String::equalNoCase(providerName, CIMHelper::EmptyString)) return NULL;
else if (String::equalNoCase(providerName, "UNIX_HostedIPInterfaceProvider")) return new UNIX_HostedIPInterfaceProvider();
return NULL;
}
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
bfa244ceb50b961120b6cea2da8a262ab1a69268 | 0fff2b8b5faa7e551f2f95bf4709ac146c42bbbf | /sort_demo.cpp | 1f77d66b2af63b6c1cf41d8071c0758575265aba | [] | no_license | joiln/Bilibili_lanqiao_codes_1 | 45707922b8ad3197695005803aeb618c27d20826 | a471c2950326428134c1be3fb2d907757ac0f109 | refs/heads/master | 2021-06-18T00:18:20.363737 | 2019-08-18T09:07:18 | 2019-08-18T09:07:18 | 202,847,888 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | cpp | //
// Created by chen on 2019/7/30.
//
#include <iostream>
#include <algorithm>
using namespace std;
//从大到小排
bool cmp(int x,int y)
{
return x > y;
}
int num[10];
int main()
{
int n;
for (int i = 0; i < 10; ++i) {
cin >> num[i];
}
sort(num,num+10,cmp);
for (int j = 0; j < 10; ++j) {
cout << num[j] << " ";
}
cout << endl;
return 0;
}
| [
"38676358+joiln@users.noreply.github.com"
] | 38676358+joiln@users.noreply.github.com |
82334354923a6cc3f5912ccb55b657cb659efa77 | ee0cfbb03280a2549f88b0d2f6e7e5d905438c4d | /src/Wrappers/PosType2Block.cpp | 08baa40f529ba38780c58e190312b54e4c309875 | [] | no_license | liminglives/c-store | 6d8f71e33fc130b3c779087c752910ddd9bf84a3 | 8516db5caa32620e24fab308a6659b369ff3bce6 | refs/heads/master | 2020-04-16T23:12:18.944454 | 2019-01-16T08:26:47 | 2019-01-16T08:26:47 | 166,002,609 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,598 | cpp | /* Copyright (c) 2005, Regents of Massachusetts Institute of Technology,
* Brandeis University, Brown University, and University of Massachusetts
* Boston. 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 Massachusetts Institute of Technology,
* Brandeis University, Brown University, or University of
* Massachusetts Boston 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.
*/
// Single value block
#include "PosType2Block.h"
PosType2Block::PosType2Block() : PosBlock()
{
vp=NULL;
numOccCounter=0;
block=NULL;
//block=new Type2Block(false);
posContig=false;
posSorted=true;
}
PosType2Block::PosType2Block(const PosType2Block& block_) : PosBlock(block_)
{
numOccCounter=0;
block=new Type2Block(*block_.block);
posContig=block_.posContig;
posSorted=block_.posSorted;
vp=NULL;
}
PosBlock* PosType2Block::clone(PosBlock& block_)
{
PosBlock* newBlock = new PosType2Block((PosType2Block&)block_);
return newBlock;
}
PosType2Block::~PosType2Block()
{
/*if (pair)
delete pair;
if (utilityPair)
delete utilityPair;
if (buffer)
delete[] buffer;*/
//delete block;
}
void PosType2Block::resetBlock() {
block->resetBlock();
numOccCounter=0;
vp=NULL;
}
void PosType2Block::setBlock(Type2Block* block_) {
block=block_;
}
Type2Block* PosType2Block::getBlock() {
return block;
}
// Iterator access to block
bool PosType2Block::hasNext() {
if (numOccCounter==0)
return block->hasNext();
else
return true;
}
/*bool PosType2Block::hasNext(int value_) {
if (startVal == value_)
return hasNext();
else
return false;
}*/
unsigned int PosType2Block::getNext() {
if (numOccCounter==0) {
vp=block->getNext();
}
if (vp==NULL) throw new CodingException("PosType2Block: error no next position");
numOccCounter=(numOccCounter+1)%numOccurences;
return vp->position;
}
unsigned int PosType2Block::peekNext() {
if (numOccCounter==0) {
return block->peekNext()->position;
}
if (vp==NULL) throw new CodingException("PosType2Block: error no next position");
return vp->position;
}
// Zero indexed, gets the pair at this pos_
unsigned int PosType2Block::getPosAtLoc(unsigned int loc_) {
//pair=block->getPairAtLoc(loc_%(block->getSize()));
//numOccCounter=loc_%numOccurences;
vp=block->getPairAtLoc(loc_/numOccurences);
if (vp==NULL) throw new CodingException("PosType2Block: error no next position");
return vp->position;
}
unsigned int PosType2Block::getCurrLoc() {
return block->getCurrLoc()*numOccurences+numOccCounter;
}
// return size of block
int PosType2Block::getSize() {
return block->getSize()*numOccurences;
}
int PosType2Block::getSizeInBits() {
throw new UnexpectedException("Don't think this is used anymore");
//doubt this is right but who cares since we don't actually use I don't think
//return (2+numValues)*sizeof(int);
}
unsigned int PosType2Block::getStartPos() {
return block->getStartPair()->position;
}
unsigned int PosType2Block::getEndPos() {
return block->getEndPosition();
}
PosBlock* PosType2Block::copySubset(int fromPos, int untilPos) {
int startPos = getStartPos();
int endPos = getEndPos();
assert(startPos <= fromPos);
assert(startPos <= untilPos);
assert(fromPos <= endPos);
assert(untilPos <= endPos);
assert(fromPos <= untilPos);
Type2Block* temp = new Type2Block(block->isValueSorted());
//assume for now that value is an integer ... fix later ...
temp->setBufferWithHeader(block->makeNewBuffer(-1,fromPos,untilPos));
PosType2Block* temp2 = new PosType2Block();
temp2->setBlock(temp);
return temp2;
}
/*void PosType2Block::printBits(int bits) {
for (int i = 0; i < 32; i++)
cout << (bool)(bits & (((unsigned int)1) << (31-i)));
cout << endl;
}*/
// Stream properties
bool PosType2Block::isPosSorted() {
return posSorted;
}
bool PosType2Block::isSparse() {
return false;
}
// Block properties
bool PosType2Block::isPosContiguous() {
return false;
}
bool PosType2Block::isBlockPosSorted() {
return true;
}
byte* PosType2Block::makeNewBuffer(int value_, int startPos_, int endPos_) {
//ick ... assumes that value is an integer ... fix later
return block->makeNewBuffer(value_, startPos_, endPos_);
}
unsigned int PosType2Block::initBitStringIterator(unsigned int pos) {
return block->initBitStringIterator(pos);
}
int PosType2Block::getNextBitString() {
return block->getNextBitString();
}
/*************************
for now ignore numOccCounter in all methods
*************************/
bool PosType2Block::PosType2BlockIter::hasNext() {
return /*numOccCounter == 0 ? */blockIter->hasNext()/* : true*/;
}
unsigned int PosType2Block::PosType2BlockIter::getNext() {
/* if (numOccCounter == 0) {
currPair = blockIter->getNext();
}
assert(currPair != NULL);
numOccCounter=(numOccCounter+1)%pType2Block->numOccurences;
return currPair->position;*/
return blockIter->getNext()->position;
}
unsigned int PosType2Block::PosType2BlockIter::peekNext() {
/*if (numOccCounter==0) {
return blockIter->peekNext()->position;
}
assert(currPair != NULL);
return currPair->position;*/
return blockIter->peekNext()->position;
}
unsigned int PosType2Block::PosType2BlockIter::getCurrLoc() {
//return blockIter->getCurrLoc()*pType2Block->numOccurences+numOccCounter;
return blockIter->getCurrLoc();
}
void PosType2Block::PosType2BlockIter::resetIterator() {
/*numOccCounter = 0;
currPair = NULL;*/
blockIter->resetIterator();
FLAPlastPos=0;
FLAPlastCount=0;
}
bool PosType2Block::PosType2BlockIter::skipToPos(unsigned int pos) {
return ((Type2Block::Type2BlockIter*)blockIter)->skipToPos(pos);
//throw new UnimplementedException("This will be really expensive to calculate ... do I really need to ever do this?");
}
int PosType2Block::PosType2BlockIter::findLocAtPosAndSkip(unsigned int pos) {
skipToPos(pos);
int numvalues;
int adjStartPos, adjEndPos;
int sp;
if ((FLAPlastPos) && (pos > FLAPlastPos)) {
sp = FLAPlastPos; //start at the last position since we never actually counted it
}
else {
sp = startpos;
}
if (sp % 32)
adjStartPos = sp - ((sp % 32) - 1);
else
adjStartPos = sp - 31;
//posIndex=new int[8*sizeof(int)+1];
byte* bufferwithheader = ((Type2Block*)blockIter->getBlock())->getBuffer();
int diff = (adjStartPos - *((int*)bufferwithheader));
//assumes buffer header size ... fix later
byte* newBufferStart = bufferwithheader + (4*sizeof(int)) + (diff/8);
//temporarily set numvalues
numvalues=((pos-adjStartPos+1)/8/sizeof(int));
if (((pos-adjStartPos+1)%(8*sizeof(int))))
numvalues++;
if (pos % 32)
adjEndPos = pos - ((pos % 32) - 1);
else
adjEndPos = pos - 31;
int numToAdd = 0;
if ((FLAPlastPos) && (pos > FLAPlastPos)) {
numToAdd = FLAPlastCount;
}
int count;
if (peekNext() == pos) {
count = ((Type2Block*)(blockIter->getBlock()))->howManyOnBits(newBufferStart, numvalues, sp-adjStartPos, pos-adjEndPos)-1+numToAdd;
if (pos > FLAPlastPos) {
FLAPlastPos = pos;
FLAPlastCount = count;
}
return count;
}
else {
count = ((Type2Block*)(blockIter->getBlock()))->howManyOnBits(newBufferStart, numvalues, sp-adjStartPos, pos-adjEndPos)+numToAdd;
if (pos > FLAPlastPos) {
FLAPlastPos = pos;
FLAPlastCount = count;
}
return count;
}
}
int PosType2Block::PosType2BlockIter::getSize() {
//return (endpos-startpos)+1;
return blockIter->getSize();
}
unsigned int PosType2Block::PosType2BlockIter::getStartPos() {
return blockIter->getStartPair()->position;
}
unsigned int PosType2Block::PosType2BlockIter::getEndPos() {
return blockIter->getEndPosition();
}
unsigned int PosType2Block::PosType2BlockIter::initBitStringIterator(unsigned int pos) {
return ((Type2Block::Type2BlockIter*)blockIter)->initBitStringIterator(pos);
}
int PosType2Block::PosType2BlockIter::getNextBitString() {
return ((Type2Block::Type2BlockIter*)blockIter)->getNextBitString();
}
// DSM NB: or operator changes start/end pos calculations! And may extend past the ends of a block,
// so if does, need to grab parts of longer block directly
void PosType2Block::PosType2BlockIter::posAnd(PosBlockIter* other, PosBlock* toWrite) {
assert (other->isPosSorted());
if (other->isSparse())
throw new UnexpectedException("It isn't supposed to work this way. PosType2Block can only and with something if it can produce a PosType2Block as a result.");
PosType2Block* tw = (PosType2Block*) toWrite;
Type2Block* outBlock = tw->getBlock();
int sp1 = blockIter->getStartPair()->position;
int sp2 = other->getStartPos();
int ep1 = blockIter->getEndPosition();
int ep2 = other->getEndPos();
int sp3;
int ep3;
if (sp1 < sp2)
sp3 = sp2;
else
sp3 = sp1;
if (ep1 < ep2)
ep3 = ep1;
else
ep3 = ep2;
Type2Block* t2b = (Type2Block*)blockIter->getBlock();
if (other->isPosContiguous()) { // all 1s-> no need to do the anding--it'll just be (a subset of) our poslist.
//assumes value is an integer ... fix later ...
outBlock->setBufferWithHeader(t2b->makeNewBuffer(-1,sp3,ep3));
}
else {
unsigned int pos1 = initBitStringIterator(sp3);
unsigned int pos2 = other->initBitStringIterator(sp3);
assert(pos1==pos2);
byte* playBuffer=new byte[PAGE_SIZE];
memset(playBuffer, 0, PAGE_SIZE);
Type2Header* header=((Type2Header*) playBuffer);
header->value = ((Type2Header*)t2b->getBuffer())->value;
header->startPos = pos1;
header->endPos = ep3;
int newNumValues=((ep3-pos1+1)/8/sizeof(int));
if (((ep3-pos1+1)%(8*sizeof(int))))
newNumValues++;
header->numValues = newNumValues;
byte* y = playBuffer + sizeof(Type2Header);
//fix later
assert(sizeof(Type2Header)==16);
int* z = (int*)y;
z[0] = (getNextBitString() & other->getNextBitString());
int tempAdjStartPos = sp3;
if (tempAdjStartPos % 32)
tempAdjStartPos -= ((tempAdjStartPos % 32) - 1);
else {
tempAdjStartPos-=31;
}
unsigned int mask=0;
for (unsigned int i =0; i < (sp3-tempAdjStartPos)%(sizeof(int)*8); i++)
mask = mask | (1 << (31 - i));
z[0] = z[0] & (~mask);
for (int i = 1; i < newNumValues; i++)
z[i] = (getNextBitString() & other->getNextBitString()); // AND operator
mask = 0;
for (unsigned int i =0; i <= (ep3-tempAdjStartPos)%(sizeof(int)*8); i++)
mask = mask | (1 << (31 - i));
z[newNumValues-1] = z[newNumValues-1] & mask;
outBlock->setBufferWithHeader(playBuffer);
delete[] playBuffer;
cerr << "PosAND outblock from " << outBlock->getStartPair()->position << " to " << outBlock->getEndPosition() << endl;
}
}
void PosType2Block::PosType2BlockIter::posOr(PosBlockIter* other, PosBlock* toWrite) {
assert (other->isPosSorted());
assert(other->getPosBlock() != this);
if (other->isSparse())
throw new UnexpectedException("It isn't supposed to work this way. PosType2Block can only and with something if it can produce a PosType2Block as a result.");
// FIXME proper start positions
PosType2Block* tw = (PosType2Block*) toWrite;
Type2Block* outBlock = tw->getBlock();
int sp1 = blockIter->getStartPair()->position;
int sp2 = other->getStartPos();
int ep1 = blockIter->getEndPosition();
int ep2 = other->getEndPos();
assert(ep1 >= sp2);
assert(ep2 >= sp1);
unsigned int sp3;
unsigned int ep3;
unsigned int minsp, maxsp;
unsigned int minep, maxep;
PosBlockIter* minIter = NULL;
PosBlockIter* maxIter = NULL;
PosBlockIter* minepIter = NULL;
PosBlockIter* maxepIter = NULL;
if (sp1 < sp2) { // For OR we use the EARLIER startpos
sp3 = sp1;
minsp = sp1;
maxsp = sp2;
minIter = this;
maxIter = other;
} else {
sp3 = sp2;
minsp = sp2;
maxsp = sp1;
minIter = other;
maxIter = this;
}
if (ep1 < ep2) { // For OR we use the LATER endPos.
ep3 = ep2;
minep = ep1;
maxep = ep2;
minepIter = this;
maxepIter = other;
} else {
ep3 = ep1;
minep = ep2;
maxep = ep1;
minepIter = other;
maxepIter = this;
}
Type2Block* t2b = (Type2Block*)blockIter->getBlock();
// cerr << "will por from " << sp3 << " to " << ep3 << endl;
// If the other block is pos contiguous, then its bitstring is all 1's. The oring of all 1's
// with anything is all 1's, so there's no need to actually do the or.
// t2b is our block. FIXME FIXME FIXME.
// outBlock is the Type2Block in the PosType2Block we're writing
if (other->isPosContiguous()) {
throw UnexpectedException("not implemented correctly");
outBlock->setBufferWithHeader(t2b->makeNewBuffer(-1,sp3,ep3));
}
else {
unsigned int pos1 = minIter->initBitStringIterator(minsp);
unsigned int pos2 = maxIter->initBitStringIterator(maxsp);
// cerr << "pos1 = " << pos1 << " pos2 = " << pos2 << endl;
byte* playBuffer=new byte[PAGE_SIZE];
memset(playBuffer, 0, PAGE_SIZE);
Type2Header* header=((Type2Header*) playBuffer);
//assumes integer ... fix later ...
header->value = ((Type2Header*)t2b->getBuffer())->value;
header->startPos = pos1;
header->endPos = ep3;
unsigned int newNumValues=((ep3-pos1+1)/8/sizeof(int));
if (((ep3-pos1+1)%(8*sizeof(int))))
newNumValues++;
header->numValues = newNumValues;
// cerr << "using " << newNumValues << " new num values (assume this means ints)" << endl;
byte* y = playBuffer + sizeof(Type2Header);
assert(sizeof(Type2Header)==16);
int* z = (int*)y;
unsigned int minAdjEndPos = minep;
if (minAdjEndPos % 32)
minAdjEndPos -= ((minAdjEndPos % 32) - 1);
else {
minAdjEndPos-=31;
}
unsigned int maxAdjEndPos = maxep;
if (maxAdjEndPos % 32)
maxAdjEndPos -= ((maxAdjEndPos % 32) - 1);
else {
maxAdjEndPos-=31;
}
// Copy until consensus start
unsigned int i = pos1;
for (; i < pos2; i+=sizeof(int)*8) {
z[(i-pos1)/(sizeof(int)*8)] = minIter->getNextBitString();
}
// Mask out first block of consensus read from maxiter
unsigned int mask=0;
for (unsigned int j = 0; j < (maxsp - pos2)%(sizeof(int)*8); j++) {
mask |= (1 << (31 - j)); // zero out until consensus (inter-block) start pos
}
if (i < minAdjEndPos) {
z[(i-pos1)/(sizeof(int)*8)] = maxIter->getNextBitString() & (~mask);
z[(i-pos1)/(sizeof(int)*8)] |= minIter->getNextBitString();
i+=sizeof(int)*8;
for (; i < minAdjEndPos; i+=sizeof(int)*8)
z[(i-pos1)/(sizeof(int)*8)] = (minIter->getNextBitString() | maxIter->getNextBitString()); // OR operator
mask=0;
for (unsigned int j =0; j <= (minep-pos2)%(sizeof(int)*8); j++)
mask = mask | (1 << (31 - j));
z[(i-pos1)/(sizeof(int)*8)] = minepIter->getNextBitString() & mask;
z[(i-pos1)/(sizeof(int)*8)] |= maxepIter->getNextBitString();
i+=sizeof(int)*8;
}
else {
assert(i==pos2);
assert(minAdjEndPos==pos2);
unsigned int temp = maxIter->getNextBitString() & (~mask);
mask=0;
for (unsigned int j =0; j <= (minep-pos2)%(sizeof(int)*8); j++)
mask = mask | (1 << (31 - j));
//z[(i-pos1)/(sizeof(int)*8)] = minepIter->getNextBitString() & mask;
//z[(i-pos1)/(sizeof(int)*8)] |= maxepIter->getNextBitString();
//i+=sizeof(int)*8;
if (maxIter == minepIter) {
z[(i-pos1)/(sizeof(int)*8)] = temp & mask;
z[(i-pos1)/(sizeof(int)*8)] |= maxepIter->getNextBitString();
}
else {
z[(i-pos1)/(sizeof(int)*8)] = temp;
temp = minepIter->getNextBitString() & mask;
z[(i-pos1)/(sizeof(int)*8)] |= temp;
}
i+=sizeof(int)*8;
}
maxAdjEndPos+=sizeof(int)*8;
for (; i < maxAdjEndPos; i+=sizeof(int)*8)
z[(i-pos1)/(sizeof(int)*8)] = (maxepIter->getNextBitString());
// Fixup z[0]
mask=0;
for (unsigned int j = 0; j < (minsp - pos1)%(sizeof(int)*8); j++) {
mask |= (1 << (31 - j)); // zero out until consensus (inter-block) start pos
}
z[0] = z[0] & (~mask); // Masking AND
// Fixup z[(i-pos1)/(sizeof(int)*8)]
mask = 0;
for (unsigned int j = 0; j <= (maxep - pos1)%(sizeof(int)*8); j++) {
mask |= (1 << (31 - j)); // zero out until consensus (inter-block) start pos
}
z[(i-pos1)/(sizeof(int)*8)] = z[(i-pos1)/(sizeof(int)*8)] & (mask); // Masking AND
assert((newNumValues) == ((i-pos1)/(sizeof(int)*8)));
outBlock->setBufferWithHeader(playBuffer);
// cerr << "PosOR outblock from " << outBlock->getStartPair()->position << " to " << outBlock->getEndPosition() << endl;
delete[] playBuffer;
}
}
bool PosType2Block::PosType2BlockIter::isPosSorted() {
return pType2Block->isPosSorted();
}
bool PosType2Block::PosType2BlockIter::isPosContiguous() {
return pType2Block->isPosContiguous();
}
bool PosType2Block::PosType2BlockIter::isBlockPosSorted() {
return pType2Block->isBlockPosSorted();
}
bool PosType2Block::PosType2BlockIter::isSparse() {
return pType2Block->isSparse();
}
PosBlock* PosType2Block::PosType2BlockIter::clone(PosBlock& pb) {
return new PosType2BlockIter((PosType2BlockIter&)pb);
}
| [
"zhengliming"
] | zhengliming |
95e4854bf18d13ebc9834b09bc3e4ce3b949019f | 509fdd2068df00dfb47a3fddd1d5bb0e7d9009aa | /Win32Project2/Win32Project2/Win32Project2Doc.cpp | 4856ed9f07bb2abdffaea8d43b8dc9ad825d7c70 | [] | no_license | joker-nshsh/exam1 | 8695b32b731487bf1c7b1ccc12a87474fdd254c0 | ac46dc4664c2e387038e80dc0e844321224060da | refs/heads/master | 2021-03-26T07:30:11.425572 | 2020-07-02T15:34:22 | 2020-07-02T15:34:22 | 247,682,370 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,687 | cpp |
// Win32Project2Doc.cpp : CWin32Project2Doc 类的实现
//
#include "stdafx.h"
// SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的
// ATL 项目中进行定义,并允许与该项目共享文档代码。
#ifndef SHARED_HANDLERS
#include "Win32Project2.h"
#endif
#include "Win32Project2Doc.h"
#include <propkey.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CWin32Project2Doc
IMPLEMENT_DYNCREATE(CWin32Project2Doc, CDocument)
BEGIN_MESSAGE_MAP(CWin32Project2Doc, CDocument)
END_MESSAGE_MAP()
// CWin32Project2Doc 构造/析构
CWin32Project2Doc::CWin32Project2Doc()
{
// TODO: 在此添加一次性构造代码
}
CWin32Project2Doc::~CWin32Project2Doc()
{
}
BOOL CWin32Project2Doc::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;
// TODO: 在此添加重新初始化代码
// (SDI 文档将重用该文档)
return TRUE;
}
// CWin32Project2Doc 序列化
void CWin32Project2Doc::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
// TODO: 在此添加存储代码
}
else
{
// TODO: 在此添加加载代码
}
}
#ifdef SHARED_HANDLERS
// 缩略图的支持
void CWin32Project2Doc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds)
{
// 修改此代码以绘制文档数据
dc.FillSolidRect(lprcBounds, RGB(255, 255, 255));
CString strText = _T("TODO: implement thumbnail drawing here");
LOGFONT lf;
CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT));
pDefaultGUIFont->GetLogFont(&lf);
lf.lfHeight = 36;
CFont fontDraw;
fontDraw.CreateFontIndirect(&lf);
CFont* pOldFont = dc.SelectObject(&fontDraw);
dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK);
dc.SelectObject(pOldFont);
}
// 搜索处理程序的支持
void CWin32Project2Doc::InitializeSearchContent()
{
CString strSearchContent;
// 从文档数据设置搜索内容。
// 内容部分应由“;”分隔
// 例如: strSearchContent = _T("point;rectangle;circle;ole object;");
SetSearchContent(strSearchContent);
}
void CWin32Project2Doc::SetSearchContent(const CString& value)
{
if (value.IsEmpty())
{
RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid);
}
else
{
CMFCFilterChunkValueImpl *pChunk = NULL;
ATLTRY(pChunk = new CMFCFilterChunkValueImpl);
if (pChunk != NULL)
{
pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT);
SetChunkValue(pChunk);
}
}
}
#endif // SHARED_HANDLERS
// CWin32Project2Doc 诊断
#ifdef _DEBUG
void CWin32Project2Doc::AssertValid() const
{
CDocument::AssertValid();
}
void CWin32Project2Doc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
// CWin32Project2Doc 命令
| [
"1569849722@qq.com"
] | 1569849722@qq.com |
1fc1420765f49e9b1a0aa29e46fe418719deab67 | 152f13462437d042efab568e514d4ab6c1e182ee | /DirectUI/Core/UIDxAnimation.h | 735eb9df182a453dbf0b8076e31a23dc279dc413 | [] | no_license | ZhouchaoAlbert/MiniQQ | fc900290482e700dd2908529b37cd44f2e28ed1d | 387540f24ec7467c3908cadd6445acf91365e97b | refs/heads/master | 2020-09-16T22:03:40.879243 | 2018-02-25T09:46:43 | 2018-02-25T09:46:43 | 66,358,640 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,263 | h | #ifndef UIDxAnimation_h__
#define UIDxAnimation_h__
#include <d3d9.h>
#include <math.h>
#pragma once
namespace DuiLib
{
typedef enum
{
UIANIMTYPE_FLAT,
UIANIMTYPE_SWIPE,
} UITYPE_ANIM;
class CDxAnimationUI;
class UILIB_API CAnimationSpooler
{
public:
CAnimationSpooler();
~CAnimationSpooler();
enum { MAX_BUFFERS = 80 };
bool Init(HWND hWnd);
bool PrepareAnimation(HWND hWnd);
void CancelJobs();
bool Render();
bool IsAnimating() const;
bool IsJobScheduled() const;
bool AddJob(CDxAnimationUI* pJob);
protected:
void Term();
COLORREF TranslateColor(LPDIRECT3DSURFACE9 pSurface, COLORREF clr) const;
bool SetColorKey(LPDIRECT3DTEXTURE9 pTexture, LPDIRECT3DSURFACE9 pSurface, int iTexSize, COLORREF clrColorKey);
bool PrepareJob_Flat(CDxAnimationUI* pJob);
bool RenderJob_Flat(const CDxAnimationUI* pJob, LPDIRECT3DSURFACE9 pSurface, DWORD dwTick);
protected:
struct CUSTOMVERTEX
{
FLOAT x, y, z;
FLOAT rhw;
DWORD color;
FLOAT tu, tv;
};
typedef CUSTOMVERTEX CUSTOMFAN[4];
HWND m_hWnd;
bool m_bIsAnimating;
bool m_bIsInitialized;
CStdPtrArray m_aJobs;
D3DFORMAT m_ColorFormat;
LPDIRECT3D9 m_pD3D;
LPDIRECT3DDEVICE9 m_p3DDevice;
LPDIRECT3DSURFACE9 m_p3DBackSurface;
//
LPDIRECT3DVERTEXBUFFER9 m_p3DVertices[MAX_BUFFERS];
LPDIRECT3DTEXTURE9 m_p3DTextures[MAX_BUFFERS];
CUSTOMFAN m_fans[MAX_BUFFERS];
int m_nBuffers;
};
class UILIB_API CDxAnimationUI
{
public:
CDxAnimationUI(const CDxAnimationUI& src);
CDxAnimationUI(UITYPE_ANIM AnimType, DWORD dwStartTick, DWORD dwDuration, COLORREF clrBack, COLORREF clrKey, RECT rcFrom, int xtrans, int ytrans, int ztrans, int alpha, float zrot);
~CDxAnimationUI(void);
typedef enum
{
INTERPOLATE_LINEAR,
INTERPOLATE_COS,
} INTERPOLATETYPE;
typedef struct PLOTMATRIX
{
int xtrans;
int ytrans;
int ztrans;
int alpha;
float zrot;
} PLOTMATRIX;
UITYPE_ANIM AnimType;
DWORD dwStartTick;
DWORD dwDuration;
int iBufferStart;
int iBufferEnd;
union
{
struct
{
COLORREF clrBack;
COLORREF clrKey;
RECT rcFrom;
PLOTMATRIX mFrom;
INTERPOLATETYPE iInterpolate;
} plot;
} data;
};
}
#endif // UIDxAnimation_h__
| [
"838944042@qq.com"
] | 838944042@qq.com |
be60eb652b3bc23e22caff780d515788f65cff1f | fe8eda5ef62e7f43eb93bdb1906b4667ac76c3ab | /inazuma/cpp/ABC/Cprob/under_99/095.cpp | 13ab6c58ab2655fab6a472407fab9a65d20e556f | [] | no_license | DeeeU/Everyday-problem-C | 0b1011f2162aa4a3c4488cfeee432968309b2e9c | e7dba35fd7aee3b0e17ae5867576a1a11ae49b2b | refs/heads/master | 2023-03-15T04:37:29.270017 | 2021-03-08T06:19:01 | 2021-03-08T06:19:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> p;
int main()
{
int a, b, c, x, y;
cin >> a >> b >> c >> x >> y;
ll tmp1 = a * x + b * y;
ll tmp2 = max(x, y) * 2 * c;
ll tmp3 = min(x, y) * 2 * c;
if (x > y) {
tmp3 += ((max(x, y)-min(x, y)) * a);
}else{
tmp3 += ((max(x, y)-min(x, y)) * b);
}
tmp1 = min(tmp1, tmp2);
cout << min(tmp1, tmp3) << endl;
return 0;
}
| [
"c011703534@edu.teu.ac.jp"
] | c011703534@edu.teu.ac.jp |
e623ee69b780b03137dfb0b343c71987abfce868 | 0348bad09f104fc0338b6a5e051c5156952a9daf | /include/boost/callable_traits/detail/parameter_index_helper.hpp | 452901aff7124520819e16708dfcd682f7256e3d | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | sbosnick/callable_traits | 588fff9f417a9d721f359206cd67577dba716950 | 26f62e21e7b95ec07da242195ebf5ce600503c7e | refs/heads/master | 2021-01-22T22:13:30.468705 | 2017-03-12T01:01:29 | 2017-03-12T01:01:29 | 85,521,398 | 0 | 0 | null | 2017-03-20T01:07:54 | 2017-03-20T01:07:54 | null | UTF-8 | C++ | false | false | 1,989 | hpp | #ifndef CALLABLE_TRAITS_PARAMETER_INDEX_HELPER_HPP
#define CALLABLE_TRAITS_PARAMETER_INDEX_HELPER_HPP
#include <tuple>
CALLABLE_TRAITS_DETAIL_NAMESPACE_BEGIN
template<std::size_t I, typename T, bool IgnoreThisPointer = false,
bool AllowPlusOne = false, std::size_t Count = 0>
struct parameter_index_helper {
using error_t = error_type<T>;
using args_tuple = typename std::conditional<IgnoreThisPointer,
typename detail::traits<T>::non_invoke_arg_types,
typename detail::traits<T>::arg_types>::type;
static constexpr bool has_parameter_list =
!std::is_same<args_tuple, invalid_type>::value
&& !std::is_same<args_tuple, reference_error>::value;
using temp_tuple = typename std::conditional<has_parameter_list,
args_tuple, std::tuple<error_t>>::type;
static constexpr std::size_t parameter_list_size =
std::tuple_size<temp_tuple>::value;
static constexpr bool is_out_of_range = has_parameter_list &&
I >= parameter_list_size + static_cast<std::size_t>(AllowPlusOne);
static constexpr bool is_count_out_of_range = has_parameter_list &&
I + Count > parameter_list_size + static_cast<std::size_t>(AllowPlusOne);
static constexpr std::size_t index =
has_parameter_list && !is_out_of_range ? I : 0;
static constexpr std::size_t count =
has_parameter_list && !is_count_out_of_range ? Count : 0;
using permissive_tuple = typename std::conditional<
has_parameter_list && !is_out_of_range,
args_tuple, std::tuple<error_t>>::type;
using permissive_function = typename std::conditional<
has_parameter_list && !is_out_of_range,
T, error_t(error_t)>::type;
};
CALLABLE_TRAITS_DETAIL_NAMESPACE_END
#endif // #ifndef CALLABLE_TRAITS_PARAMETER_INDEX_HELPER_HPP
| [
"badair@github.com"
] | badair@github.com |
a64f4985579156d4a030d486509f5d123582a440 | 975aaead37462f90ca5af6edc378b7ab7c7dfa02 | /BrofilerCore/CallstackCollector.h | 76dcaf7e6cef83ab6b7ace70a23302fd85f018e6 | [
"MIT"
] | permissive | galek/brofiler | 98dd5228daf806cfd8b73be378dc0cdd3258fd46 | b2cafd7d1473739ef3913ba8da6408d31c434158 | refs/heads/master | 2021-01-19T17:39:32.455180 | 2018-06-11T20:39:59 | 2018-06-11T20:39:59 | 40,742,968 | 0 | 0 | null | 2015-10-10T23:18:24 | 2015-08-15T01:48:17 | C# | UTF-8 | C++ | false | false | 950 | h | #pragma once
#include <MTTypes.h>
#include "Brofiler.h"
#include "MemoryPool.h"
#include "Serialization.h"
namespace Brofiler
{
//////////////////////////////////////////////////////////////////////////
class SymEngine;
//////////////////////////////////////////////////////////////////////////
struct CallstackDesc
{
uint64 threadID;
uint64 timestamp;
uint64* callstack;
uint8 count;
};
//////////////////////////////////////////////////////////////////////////
class CallstackCollector
{
// Packed callstack list: {ThreadID, Timestamp, Count, Callstack[Count]}
typedef MemoryPool<uint64, 1024 * 32> CallstacksPool;
CallstacksPool callstacksPool;
public:
void Add(const CallstackDesc& desc);
void Clear();
bool SerializeSymbols(OutputDataStream& stream);
bool SerializeCallstacks(OutputDataStream& stream);
bool IsEmpty() const;
};
//////////////////////////////////////////////////////////////////////////
} | [
"nb_grif@mail.ru"
] | nb_grif@mail.ru |
59c01c3d4c0db3a74f4e78fcb8a6e3582e377ccf | a04e0c3fcba8b85befa414d726ef2863b98cb013 | /esercizi/2/esercizio8.3/Random.cc | 9119191025427934e5ffcbbcd6d0565bebd258f3 | [] | no_license | gfugante/Numerical-Treatment-of-Experimental-Data-TNDS-2018 | df6e85c9d88ec804ee3af4f4dbc463becd193588 | e11a488b53990ae5c14e110fecdefef3de186cf3 | refs/heads/master | 2023-07-13T16:02:16.433019 | 2021-08-25T14:21:01 | 2021-08-25T14:21:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | cc | #include <cmath>
#include "Random.h"
using namespace std;
Random::Random(int seme){
_seme=seme;
_a=1664525;
_c=1013904223;
_m=pow(2, 31);
}
void Random::setA(int a){
_a=a;
}
void Random::setC(int c){
_c=c;
}
void Random::setM(int m){
_m=m;
}
double Random::Rand(){
double n= (_a*_seme+_c)%_m;
double d=n/(double)(_m-1);
_seme=n;
return d;
}
double Random::Accept_Reject(double sigma, double media, double A, double B){
double x, y, g;
do{
double s=Rand();
double t=Rand();
x=A+(B-A)*s;
y=(1/(pow((2*M_PI), 0.5)*sigma))*t;
g=1/(pow((2*M_PI), 0.5)*sigma)*exp(-pow(x-media,2)/(2*sigma*sigma));
}while(y>g);
return x;
}
double Random::Box_Mull_Gauss(double sigma, double media){
double s=this->Rand();
double t=this->Rand();
double x=sqrt(-2.*log(s))*cos(2*M_PI*t);
return media+sigma*x;
}
double Random::Box_Mull_Exp(double rate){
double z=this->Rand();
double x=log(1-z);
double p=-1./rate;
return p*x;
}
Random::~Random(){}
| [
"gianlucafugante@MBP-di-Gianluca.fritz.box"
] | gianlucafugante@MBP-di-Gianluca.fritz.box |
c3ae9c51d39ad227a0882b1a3a1d7dd723a5ae3f | 8b34e827181766263ee0a825c3339bd44deee2ba | /SettlersOfCatanGame_CENG430/GameBoardTestCases.cpp | e502e082c2e65d199554632bdb0027c2611c062b | [] | no_license | ZacharyDownum/SettlersOfCatanAI | ba58bf930626d6279679f74e7f78d080e15c20de | 2dca31ad615824721801fc150bc2f99f17d091de | refs/heads/master | 2020-06-11T12:45:11.971765 | 2016-12-05T20:32:04 | 2016-12-05T20:32:04 | 75,663,757 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,279 | cpp | #include <map>
#include <iostream>
#include "GameBoardTestCases.h"
#include "ResourceTile.h"
#include "Node.h"
#include "Edge.h"
#include "Player.h"
using std::map;
using std::cout;
using std::endl;
//main function that returns zero if all test cases passed
//will return the number of the test that failed (based on the order of the functions below) if one actually failed
//the int returned will be based off base 2 return codes (first one is 1, second is 2, third is 4, etc...)
//ex.: if runTestCases() returns 15, that means that the first 4 functions failed
int GameBoardTestCases::runTestCases()
{
return gameBoard_checkResourceTileInitialConditions() + gameBoard_checkNodeInitialConditions() + gameBoard_checkEdgeInitialConditions() + gameBoard_checkDevelopmentCardInitialConditions() + gameBoard_checkPlayerInitialConditions() + gameBoard_checkRobberLocationInitialConditions()
+ resourceTile_checkNodeAssociations()
+ node_checkEdgeAssociations()
+ edge_checkNodeAssociations();
}
//this will ensure that the proper number of each element is contained within the resource tile list in the game board
int GameBoardTestCases::gameBoard_checkResourceTileInitialConditions()
{
//should either return 1 or 0
int returnValue = 0;
//there should be 4 Grain, 4 Lumber, 4 Wool, 3 Ore, 3 Brick, and 1 Desert
//this map will count the Elements that are contained within the resource tiles
//if these do not match up at the end, the test should fail
map<GameBoard::Elements, int> elementsCounter;
elementsCounter.insert(std::make_pair(GameBoard::Elements::Grain, 4));
elementsCounter.insert(std::make_pair(GameBoard::Elements::Lumber, 4));
elementsCounter.insert(std::make_pair(GameBoard::Elements::Wool, 4));
elementsCounter.insert(std::make_pair(GameBoard::Elements::Ore, 3));
elementsCounter.insert(std::make_pair(GameBoard::Elements::Brick, 3));
elementsCounter.insert(std::make_pair(GameBoard::Elements::Desert, 1));
//this map holds the numbers for the rollValues and how many times they should occur
map<int, int> rollValueCounter;
for (int i = 2; i < 13; ++i)
{
//2, 7, and 12 are only represented once, all others are represented 2 times
if (i == 2 || i == 7 || i == 12)
{
rollValueCounter.insert(std::make_pair(i, 1));
}
else
{
rollValueCounter.insert(std::make_pair(i, 2));
}
}
for (ResourceTile tile : board.tiles)
{
--elementsCounter[tile.element];
--rollValueCounter[tile.rollValue];
if (tile.borderingNodes.empty())
{
returnValue = 1;
}
}
if (returnValue <= 0)
{
for (auto p : elementsCounter)
{
if (p.second != 0)
{
if (p.first == GameBoard::Elements::Grain)
{
cout << "Grain is off by " << p.second << endl;
}
else if (p.first == GameBoard::Elements::Brick)
{
cout << "Brick is off by " << p.second << endl;
}
else if (p.first == GameBoard::Elements::Desert)
{
cout << "Desert is off by " << p.second << endl;
}
else if (p.first == GameBoard::Elements::Lumber)
{
cout << "Lumber is off by " << p.second << endl;
}
else if (p.first == GameBoard::Elements::Ore)
{
cout << "Ore is off by " << p.second << endl;
}
else if (p.first == GameBoard::Elements::Wool)
{
cout << "Wool is off by " << p.second << endl;
}
returnValue = 1;
}
}
}
if (returnValue <= 0)
{
for (auto p : rollValueCounter)
{
if (p.second != 0)
{
cout << "Roll Number " << p.first << " is off by " << p.second << endl;
returnValue = 1;
}
}
}
return returnValue;
}
//this will ensure that the initial node conditions are what they are expected to be
//for each node in the game board
int GameBoardTestCases::gameBoard_checkNodeInitialConditions()
{
//should either return 2 or 0
int returnValue = 0;
for (Node node : board.nodes)
{
if (node.occupiedBy != GameBoard::PlayerColors::None
|| node.typeOfBuilding != GameBoard::BuildingType::None
|| node.borderingEdges.empty())
{
returnValue = 2;
}
}
//those nodes should have a trade "any" port
if (board.nodes[0].port != GameBoard::Elements::Any
|| board.nodes[3].port != GameBoard::Elements::Any
|| board.nodes[10].port != GameBoard::Elements::Any
|| board.nodes[15].port != GameBoard::Elements::Any
|| board.nodes[26].port != GameBoard::Elements::Any
|| board.nodes[32].port != GameBoard::Elements::Any
|| board.nodes[47].port != GameBoard::Elements::Any
|| board.nodes[51].port != GameBoard::Elements::Any
|| board.nodes[0].port != GameBoard::Elements::Any)
{
returnValue = 2;
}
else if (board.nodes[1].port != GameBoard::Elements::Wool
|| board.nodes[5].port != GameBoard::Elements::Wool)
{
returnValue = 2;
}
else if (board.nodes[42].port != GameBoard::Elements::Brick
|| board.nodes[46].port != GameBoard::Elements::Brick)
{
returnValue = 2;
}
else if (board.nodes[49].port != GameBoard::Elements::Lumber
|| board.nodes[52].port != GameBoard::Elements::Lumber)
{
returnValue = 2;
}
else if (board.nodes[33].port != GameBoard::Elements::Grain
|| board.nodes[38].port != GameBoard::Elements::Grain)
{
returnValue = 2;
}
else if (board.nodes[11].port != GameBoard::Elements::Ore
|| board.nodes[16].port != GameBoard::Elements::Ore)
{
returnValue = 2;
}
return returnValue;
}
//this will ensure that the intial edge conditions are what they are expected to be
//for each edge in the game board
int GameBoardTestCases::gameBoard_checkEdgeInitialConditions()
{
//should either return 4 or 0
int returnValue = 0;
for (Edge edge : board.edges)
{
if (edge.occupiedBy != GameBoard::PlayerColors::None
|| edge.borderingNodes.empty())
{
returnValue = 4;
}
}
return returnValue;
}
//this will ensure that the initial development card conditions are what they are expected to be
//for each development card in the game board
int GameBoardTestCases::gameBoard_checkDevelopmentCardInitialConditions()
{
//should either return 8 or 0
int returnValue = 0;
map<GameBoard::DevelopmentCardTypes, int> developmentCardCounter;
developmentCardCounter.insert(std::make_pair(GameBoard::DevelopmentCardTypes::Knight, 14));
developmentCardCounter.insert(std::make_pair(GameBoard::DevelopmentCardTypes::Monopoly, 2));
developmentCardCounter.insert(std::make_pair(GameBoard::DevelopmentCardTypes::RoadBuilding, 2));
developmentCardCounter.insert(std::make_pair(GameBoard::DevelopmentCardTypes::VictoryPoint, 5));
developmentCardCounter.insert(std::make_pair(GameBoard::DevelopmentCardTypes::YearOfPlenty, 2));
for (GameBoard::DevelopmentCardTypes card : board.developmentCards)
{
--developmentCardCounter[card];
}
for (auto iter : developmentCardCounter)
{
if (iter.second != 0)
{
if (iter.first == GameBoard::DevelopmentCardTypes::Knight)
{
cout << "Knight cards are off by " << iter.second << endl;
}
else if (iter.first == GameBoard::DevelopmentCardTypes::Monopoly)
{
cout << "Monopoly cards are off by " << iter.second << endl;
}
else if (iter.first == GameBoard::DevelopmentCardTypes::RoadBuilding)
{
cout << "Road Building cards are off by " << iter.second << endl;
}
else if (iter.first == GameBoard::DevelopmentCardTypes::VictoryPoint)
{
cout << "Victory Point cards are off by " << iter.second << endl;
}
else if (iter.first == GameBoard::DevelopmentCardTypes::YearOfPlenty)
{
cout << "Year Of Plenty cards are off by " << iter.second << endl;
}
returnValue = 8;
}
}
return returnValue;
}
//Cannot fill this out until we finish the player class
//this will ensure that the initial player conditions are what they are expected to be
//for each development card in the game board
int GameBoardTestCases::gameBoard_checkPlayerInitialConditions()
{
//should either return 16 or 0
int returnValue = 0;
return returnValue;
}
//this will ensure that the initial robber location conditions are what they are expected to be
//for each development card in the game board
int GameBoardTestCases::gameBoard_checkRobberLocationInitialConditions()
{
//should either return 32 or 0
int returnValue = 0;
for (auto tilePointer = board.tiles.begin(); tilePointer != board.tiles.end(); ++tilePointer)
{
if (tilePointer->element == GameBoard::Elements::Desert)
{
if (&board.tiles[board.robberTileNumber] != tilePointer._Ptr)
{
returnValue = 32;
}
}
}
return returnValue;
}
//this will ensure that each resource tile has the correct node associations
//based on the numbering scheme for the nodes and resource tiles established previously
int GameBoardTestCases::resourceTile_checkNodeAssociations()
{
//should either return 64 or 0
int returnValue = 0;
return returnValue;
}
//this will ensure that each node has the correct edge associations based on the numbering scheme
//of nodes and edges established previous
int GameBoardTestCases::node_checkEdgeAssociations()
{
//should either return 128 or 0
int returnValue = 0;
return returnValue;
}
//this will ensure that each edge has the correct node associations based on the numbering scheme
//of edges and nodes established previous
int GameBoardTestCases::edge_checkNodeAssociations()
{
//should either return 256 or 0
int returnValue = 0;
return returnValue;
}
| [
"zdownum@gmail.com"
] | zdownum@gmail.com |
8b2e4f8d1dd32dec79aa17eb15f61c6ac586bb50 | 7dc042a3f9068bc911c16f9173393660df704dab | /VC2010Samples/Attributes/General/AutoThread/AutoServer/AutoServer.cpp | ddcc0ca996df028605b4f7fcb748f25e6d4eb10d | [
"MIT"
] | permissive | pluciro/VCSamples | 5639f953bfbe0ef598af601cc78d5a18012e1792 | 8453972390580ef1bbc8c09ec7a14d3c9111518e | refs/heads/master | 2022-05-10T04:45:11.889276 | 2022-05-06T15:11:50 | 2022-05-06T15:11:50 | 280,199,366 | 0 | 0 | NOASSERTION | 2020-07-16T16:10:32 | 2020-07-16T16:10:32 | null | UTF-8 | C++ | false | false | 2,882 | cpp | // This is a part of the Active Template Library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Active Template Library Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Active Template Library product.
// AutoServer.cpp : Implementation of WinMain
// Note: Proxy/Stub Information
// To build a separate proxy/stub DLL,
// run nmake -f AutoServerps.mk in the project directory.
#include "stdafx.h"
#include "resource.h"
#include <initguid.h>
#include "AutoServ.h"
const DWORD dwTimeOut = 5000; // time for EXE to be idle before shutting down
const DWORD dwPause = 1000; // time to wait for threads to finish up
[emitidl];
[module(exe, name="AutoServerLib", uuid="{A6D89F0F-35F4-11D2-9375-00C04FD9757C}", helpstring="AutoServer 1.0 Type Library")];
CAtlAutoThreadModule _AtlAutoThreadModule;
class CAppExeModule : public CAtlAutoThreadModule
{
public:
LONG Unlock();
DWORD dwThreadID;
HANDLE hEventShutdown;
void MonitorShutdown();
bool StartMonitor();
bool bActivity;
};
// Passed to CreateThread to monitor the shutdown event
static DWORD WINAPI MonitorProc(void* pv)
{
CAppExeModule* p = (CAppExeModule*)pv;
p->MonitorShutdown();
return 0;
}
LONG CAppExeModule::Unlock()
{
LONG l = _pAtlModule->Unlock();
if (l == 0)
{
bActivity = true;
SetEvent(hEventShutdown); // tell monitor that we transitioned to zero
}
return l;
}
//Monitors the shutdown event
void CAppExeModule::MonitorShutdown()
{
while (1)
{
WaitForSingleObject(hEventShutdown, INFINITE);
DWORD dwWait=0;
do
{
bActivity = false;
dwWait = WaitForSingleObject(hEventShutdown, dwTimeOut);
} while (dwWait == WAIT_OBJECT_0);
// timed out
if (!bActivity && _pAtlModule->m_nLockCnt == 0) // if no activity let's really bail
{
#if defined(_ATL_FREE_THREADED)
CoSuspendClassObjects();
if (!bActivity && _pAtlModule->m_nLockCnt == 0)
#endif
break;
}
}
CloseHandle(hEventShutdown);
PostThreadMessage(dwThreadID, WM_QUIT, 0, 0);
}
bool CAppExeModule::StartMonitor()
{
hEventShutdown = CreateEvent(NULL, false, false, NULL);
if (hEventShutdown == NULL)
return false;
DWORD dwThreadID;
HANDLE h = CreateThread(NULL, 0, MonitorProc, this, 0, &dwThreadID);
return (h != NULL);
}
LPCTSTR FindOneOf(LPCTSTR p1, LPCTSTR p2)
{
while (p1 != NULL && *p1 != NULL)
{
LPCTSTR p = p2;
while (p != NULL && *p != NULL)
{
if (*p1 == *p)
return CharNext(p1);
p = CharNext(p);
}
p1 = CharNext(p1);
}
return NULL;
}
| [
"ericmitt@corp.microsoft.com"
] | ericmitt@corp.microsoft.com |
e3f8ea545df305e81885357847a8db167401be07 | 02999553daed42d369b272c1c4193992496647cb | /TornadoEngine/Source/Modules/MMOEngine/src/Slave.cpp | df149b295e65841fdbf1862f3a6401bac7054809 | [] | no_license | eshcrow/MMO-Framework | ee43144d58e8bf0e31310a21501d4ad7235b1a0d | 0e691c0f21875186b440cd53fc33fb794c169176 | refs/heads/master | 2020-04-21T19:11:56.668434 | 2019-02-08T16:49:08 | 2019-02-08T16:49:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,224 | cpp | /*
Author: Gudakov Ramil Sergeevich a.k.a. Gauss
Гудаков Рамиль Сергеевич
Contacts: [ramil2085@mail.ru, ramil2085@gmail.com]
See for more information License.h.
*/
#include "Slave.h"
#include "Logger.h"
#include "ControlScenario.h"
#include "SessionManager.h"
#include "Events.h"
#include "ManagerContextClient_slave.h"
#include "ContainerContextSc.h"
#include "ScenarioDisconnectClient.h"
#include "ScenarioFlow.h"
#include "ScenarioLoginClient.h"
#include "ScenarioLoginSlave.h"
#include "ScenarioRecommutationClient.h"
#include "ScenarioSendToClient.h"
#include "ScenarioSynchroSlave.h"
#include "DescRequestConnectForRecipient.h"
using namespace nsMMOEngine;
using namespace std;
TSlave::TSlave()
{
mMngContextClient.reset( new TManagerContextClient_slave( this ) );
mMngContextClientSlaveRecipient.reset( new TManagerContextClient_slave( this ) );
mTimeNeedSendSynchro = 0;
mControlSc->mLoginClient->SetBehavior( TScenarioLoginClient::eSlave );
mControlSc->mRcm->SetBehavior( TScenarioRecommutationClient::eSlave );
}
//-------------------------------------------------------------------------
TSlave::~TSlave()
{
}
//-------------------------------------------------------------------------
void TSlave::SaveContext( unsigned int sessionID, void* data, int size )
{
TContainerContextSc* pC = mMngContextClient->FindContextBySession( sessionID );
if( pC && pC->IsRcmActive() ) // передать контекст в сценарий
{
mControlSc->mRcm->SetContext( &pC->mRcm );
mControlSc->mRcm->SaveContext( data, size );// это уже вызов функции сценария
}
}
//-------------------------------------------------------------------------
bool TSlave::FindClientKeyBySession( unsigned int sessionID, unsigned int &id )
{
return mMngContextClient->FindKeyBySession( sessionID, id );
}
//-------------------------------------------------------------------------
bool TSlave::FindSessionByClientKey( unsigned int id, unsigned int& sessionID )
{
return mMngContextClient->FindSessionByKey( id, sessionID );
}
//-------------------------------------------------------------------------
void TSlave::DisconnectInherit( unsigned int sessionID )
{
// либо обрыв связи с верхним соединением - тогда мы одни, нерабочее состояние
if( sessionID == mSessionUpID )
{
flgConnectUp = false;
DisconnectAllClient();// распустить всех клиентов
mSessionUpID = INVALID_HANDLE_SESSION;
TDisconnectUpEvent event;
event.sessionID = sessionID;
AddEventCopy( &event, sizeof( event ) );
return;
}
// либо обрыв с одним из клиентов - уничтожить клиента
// физический обрыв или сценарий сам оборвал
unsigned int id_client;
if( mMngContextClient->FindKeyBySession( sessionID, id_client ) == false )
return;
TContainerContextSc* pC = mMngContextClient->FindContextBySession( sessionID );
if( pC == nullptr )
{
BL_FIX_BUG();
return;
}
// если есть активный сценарий, то завершить и начать сценарий дисконнекта
mControlSc->mDisClient->SetContext( &pC->mDisClient );
pC->mDisClient.SetSessionID( mSessionUpID );
mControlSc->mDisClient->DisconnectFromSlave( id_client );// отправка Мастеру информации о потере связи с Клиентом
mMngContextClient->DeleteByKey( id_client );
if( pC->IsLoginClientActive() == false )
{
TDisconnectDownEvent event;
event.sessionID = sessionID;
AddEventCopy( &event, sizeof( event ) );
}
}
//-------------------------------------------------------------------------
int TSlave::GetCountDown()
{
return mMngContextClient->GetCountSession();
}
//-------------------------------------------------------------------------
bool TSlave::GetDescDown( int index, void* pDesc, int& sizeDesc )
{
if( sizeDesc < sizeof( TDescDownSlave ) )
{
GetLogger( STR_NAME_MMO_ENGINE )->
WriteF_time( "TSlave::GetDescDown() size of buffer less then size of structure.\n" );
return false;
}
unsigned int sessionID;
if( mMngContextClient->GetSessionByIndex( index, sessionID ) == false )
return false;
TDescDownSlave* pDescDownSlave = (TDescDownSlave*) pDesc;
pDescDownSlave->sessionID = sessionID;
sizeDesc = sizeof( TDescDownSlave );
return true;
}
//-------------------------------------------------------------------------
void TSlave::ConnectUp( TIP_Port& ip_port, std::string& login, std::string& password, unsigned char subNet )
{
// если сессия жива, то значит либо соединились, либо соединяемся
if( mSessionUpID != INVALID_HANDLE_SESSION )
return;
mControlSc->mLoginSlave->ConnectToMaster( ip_port, login, password, subNet );
}
//-------------------------------------------------------------------------
void TSlave::WorkInherit()
{
// пока нет связи с Мастером - синхронизацию не проводить
if( flgConnectUp == false )
return;
//-------------------------------------------------------
unsigned int now_ms = ht_GetMSCount();
if( mTimeNeedSendSynchro < now_ms )
{
mControlSc->mSynchroSlave->SendSynchro( mLoadProcent );
mTimeNeedSendSynchro = now_ms + eDeltaSynchro;
}
}
//-------------------------------------------------------------------------
void TSlave::DisconnectAllClient()
{
unsigned int id;
// перечисляем всех клиентов и узнаем их ключи
while( mMngContextClient->GetFirstKey( id ) )
{
// по ключу ищем сессию
unsigned int sessionID;
if( mMngContextClient->FindSessionByKey( id, sessionID ) )
{
// закрываем сессию
mSessionManager->CloseSession( sessionID );
// удаляем по ключу
mMngContextClient->DeleteByKey( id );
// генерация события о дисконнекте
TDisconnectDownEvent event;
event.sessionID = sessionID;
AddEventCopy( &event, sizeof( event ) );
}
}
}
//-------------------------------------------------------------------------
void TSlave::SendDown( unsigned int sessionID, char* p, int size, bool check )
{
TContainerContextSc* pC = mMngContextClient->FindContextBySession( sessionID );
if( pC )
{
mControlSc->mFlow->SetContext( &pC->mFlow );
SetupBP( p, size );
mControlSc->mFlow->SendDown( mBP, check );
}
}
//-------------------------------------------------------------------------
void TSlave::EndLoginClient( IScenario* pSc )
{
TContextScLoginClient* pContext = (TContextScLoginClient*) pSc->GetContext();
if( pContext->IsAccept() )
{
// сохранить сессию Клиента
TContainerContextSc* pC = mMngContextClient->FindContextByKey( pContext->GetClientKey() );
BL_ASSERT( pC );
pC->SetSessionID( pContext->GetID_SessionClientSlave() );
return;
}
mMngContextClient->DeleteByKey( pContext->GetClientKey() );
}
//-------------------------------------------------------------------------
void TSlave::EndLoginSlave( IScenario* pSc )
{
// взять по этому контексту, задать всем контекстам
mSessionUpID = pSc->GetContext()->GetSessionID();
mContainerUp->SetSessionID( mSessionUpID );
flgConnectUp = mContainerUp->mLoginSlave.IsConnect();
if( flgConnectUp )
{
// вход в кластер закончен
TConnectUpEvent event;
event.sessionID = mSessionUpID;
AddEventCopy( &event, sizeof( event ) );
}
}
//-------------------------------------------------------------------------
void TSlave::EndRcm( IScenario* pSc )
{
TContextScRecommutationClient* pContext = (TContextScRecommutationClient*) pSc->GetContext();
unsigned int key = pContext->GetClientKey();
if( pContext->IsDonor() )
{
// просто удалить
mMngContextClient->DeleteByKey( key );
return;
}
if( pContext->IsRecipient() == false )
{
GetLogger( STR_NAME_MMO_ENGINE )->
WriteF_time( "TSlave::EndRcm() Undef state.\n" );
BL_FIX_BUG();
return;
}
// переместить из временного хранилища в постоянное
mMngContextClientSlaveRecipient->DeleteByKey( key );
unsigned int sessionID = pContext->GetID_SessionClientSlave();
TContainerContextSc* pC = mMngContextClient->AddContextByKey( key );
mMngContextClient->AddSessionByKey( key, sessionID );
// для всех контекстов назначить связь вниз
pC->SetSessionID( sessionID );
}
//-------------------------------------------------------------------------
void TSlave::NeedContextSendToClient( unsigned int id_client )
{
// запрос на отправку какому-то клиенту
TContainerContextSc* pContext = mMngContextClient->FindContextByKey( id_client );
if( pContext )
mControlSc->mSendToClient->SetContext( &pContext->mSendToClient );
else
mControlSc->mSendToClient->SetContext( nullptr );
}
//-------------------------------------------------------------------------
void TSlave::SendByClientKey( list<unsigned int>& lKey, char* p, int size )
{
SetupBP( p, size );
mControlSc->mSendToClient->SendFromSlave( lKey, mBP );
}
//-------------------------------------------------------------------------
void TSlave::NeedContextLoginClientByClientSessionByKeyClient( unsigned int id_session_client, unsigned int id_client )
{
TContainerContextSc* pC = mMngContextClient->FindContextByKey( id_client );
if( pC == nullptr )
{
mControlSc->mLoginClient->SetContext( nullptr );
return;
}
// надо проверить, вдруг клиент решил взять не свой ключ и ключ совпал
unsigned int id_session_exist;
if( mMngContextClient->FindSessionByKey( id_client, id_session_exist ) == false )
{
mControlSc->mLoginClient->SetContext( nullptr );
return;
}
// сессии не должно быть, он ведь впервые соединяется
if( id_session_exist != INVALID_HANDLE_SESSION )
{
mControlSc->mLoginClient->SetContext( nullptr );
return;
}
mMngContextClient->AddSessionByKey( id_client, id_session_client );
mControlSc->mLoginClient->SetContext( &pC->mLoginClient );
}
//-------------------------------------------------------------------------
void TSlave::NeedContextLoginClientByClientKey( unsigned int id_client )
{
TContainerContextSc* pC = mMngContextClient->FindContextByKey( id_client );
if( pC == nullptr )
pC = mMngContextClient->AddContextByKey( id_client );
mControlSc->mLoginClient->SetContext( &pC->mLoginClient );
}
//-------------------------------------------------------------------------
void TSlave::NeedContextLoginClientByClientKey_SecondCallSlave( unsigned int id_client )
{
TContainerContextSc* pC = mMngContextClient->FindContextByKey( id_client );
if( pC == nullptr )
{
mControlSc->mLoginClient->SetContext( nullptr );
return;
}
mControlSc->mLoginClient->SetContext( &pC->mLoginClient );
}
//-------------------------------------------------------------------------
void TSlave::NeedContextByClientForSlaveKeyRcm( unsigned int key, bool donor )
{
if( donor )
{
TContainerContextSc* pC = mMngContextClient->FindContextByKey( key );
if( pC )
{
// настроить сессии наверх и вниз
pC->mRcm.SetID_SessionClientSlave( pC->GetSessionID() );
pC->mRcm.SetID_SessionMasterSlave( mSessionUpID );
mControlSc->mRcm->SetContext( &pC->mRcm );
}
else
mControlSc->mRcm->SetContext( nullptr );
}
else
{
TContainerContextSc* pC = mMngContextClientSlaveRecipient->FindContextByKey( key );
if( pC == nullptr )
pC = mMngContextClientSlaveRecipient->AddContextByKey( key );
// верх и низ сессия назначит сам сценарий
mControlSc->mRcm->SetContext( &pC->mRcm );
}
}
//-------------------------------------------------------------------------
void TSlave::EventDisconnectClientRcm( unsigned int key )
{
// для подстраховки и там и там удалить
TContainerContextSc* pC = mMngContextClientSlaveRecipient->FindContextByKey( key );
if( pC )
mMngContextClientSlaveRecipient->DeleteByKey( key );
else
{
// если Клиент исхитрился и вместо отсылки "CheckInfoRecipient, ready to disconnect"
// просто разорвал соединение - удалить из системы
pC = mMngContextClient->FindContextByKey( key );
if( pC == nullptr )
return;
mMngContextClient->DeleteByKey( key );
}
unsigned int sessionID = pC->mRcm.GetID_SessionClientSlave();
mSessionManager->CloseSession( sessionID );
}
//-------------------------------------------------------------------------
void TSlave::NeedContextByClientSessionForSlaveRcm( unsigned sessionID, bool donor )
{
TContainerContextSc* pC = nullptr;
if( donor )
pC = mMngContextClient->FindContextBySession( sessionID );
else
pC = mMngContextClientSlaveRecipient->FindContextBySession( sessionID );
//----------
if( pC )
mControlSc->mRcm->SetContext( &pC->mRcm );
else
mControlSc->mRcm->SetContext( nullptr );
}
//-------------------------------------------------------------------------
void TSlave::NeedContextByRequestForRecipient( TDescRequestConnectForRecipient* pDescRequest )
{
TContainerContextSc*pC = mMngContextClientSlaveRecipient->FindContextByKey( pDescRequest->key );
if( pC )
{
// проверка числа
if( pC->mRcm.GetRandomNum() == pDescRequest->random_num )
{
mControlSc->mRcm->SetContext( &pC->mRcm );
// сохранить сессию
mMngContextClientSlaveRecipient->
AddSessionByKey( pDescRequest->key, pDescRequest->sessionID );
// запомнить откуда Клиент вообще
pC->SetSessionID( pDescRequest->sessionID );
return;
}
}
mControlSc->mRcm->SetContext( nullptr );
}
//-------------------------------------------------------------------------
void TSlave::EventTimeClientElapsedRcm( unsigned int id_client )
{
// Донор или Реципиент
TContainerContextSc* pC = mMngContextClient->FindContextByKey( id_client );
if( pC )
{
// Донор
mMngContextClient->DeleteByKey( id_client );
}
else
{
pC = mMngContextClientSlaveRecipient->FindContextByKey( id_client );
if( pC == nullptr )
return;
// реципиент
mMngContextClientSlaveRecipient->DeleteByKey( id_client );
}
// если есть активный сценарий, то завершить и начать сценарий дисконнекта
mControlSc->mDisClient->SetContext( &pC->mDisClient );
pC->mDisClient.SetSessionID( mSessionUpID );
mControlSc->mDisClient->DisconnectFromSlave( id_client );
}
//-------------------------------------------------------------------------
| [
"ramil2085@mail.ru"
] | ramil2085@mail.ru |
d8ead75b7ca37e2232f78a4c81dac04f7100b603 | 1d9df1156e49f768ed2633641075f4c307d24ad2 | /third_party/WebKit/Source/core/exported/WebSecurityPolicy.cpp | 3fe66b4a00ca62ba9b0d551e173bf9f80a0bc00d | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | GSIL-Monitor/platform.framework.web.chromium-efl | 8056d94301c67a8524f6106482087fd683c889ce | e156100b0c5cfc84c19de612dbdb0987cddf8867 | refs/heads/master | 2022-10-26T00:23:44.061873 | 2018-10-30T03:41:51 | 2018-10-30T03:41:51 | 161,171,104 | 0 | 1 | BSD-3-Clause | 2022-10-20T23:50:20 | 2018-12-10T12:24:06 | C++ | UTF-8 | C++ | false | false | 4,773 | cpp | /*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "public/web/WebSecurityPolicy.h"
#include "core/loader/FrameLoader.h"
#include "platform/weborigin/SchemeRegistry.h"
#include "platform/weborigin/SecurityOrigin.h"
#include "platform/weborigin/SecurityPolicy.h"
#include "public/platform/WebSecurityOrigin.h"
#include "public/platform/WebString.h"
#include "public/platform/WebURL.h"
namespace blink {
void WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(
const WebString& scheme) {
SchemeRegistry::RegisterURLSchemeAsDisplayIsolated(scheme);
}
void WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers(
const WebString& scheme) {
SchemeRegistry::RegisterURLSchemeAsAllowingServiceWorkers(scheme);
}
void WebSecurityPolicy::RegisterURLSchemeAsSupportingFetchAPI(
const WebString& scheme) {
SchemeRegistry::RegisterURLSchemeAsSupportingFetchAPI(scheme);
}
void WebSecurityPolicy::RegisterURLSchemeAsFirstPartyWhenTopLevel(
const WebString& scheme) {
SchemeRegistry::RegisterURLSchemeAsFirstPartyWhenTopLevel(scheme);
}
void WebSecurityPolicy::AddOriginAccessWhitelistEntry(
const WebURL& source_origin,
const WebString& destination_protocol,
const WebString& destination_host,
bool allow_destination_subdomains) {
SecurityPolicy::AddOriginAccessWhitelistEntry(
*SecurityOrigin::Create(source_origin), destination_protocol,
destination_host, allow_destination_subdomains);
}
void WebSecurityPolicy::RemoveOriginAccessWhitelistEntry(
const WebURL& source_origin,
const WebString& destination_protocol,
const WebString& destination_host,
bool allow_destination_subdomains) {
SecurityPolicy::RemoveOriginAccessWhitelistEntry(
*SecurityOrigin::Create(source_origin), destination_protocol,
destination_host, allow_destination_subdomains);
}
void WebSecurityPolicy::ResetOriginAccessWhitelists() {
SecurityPolicy::ResetOriginAccessWhitelists();
}
void WebSecurityPolicy::AddOriginTrustworthyWhiteList(
const WebSecurityOrigin& origin) {
SecurityPolicy::AddOriginTrustworthyWhiteList(*origin.Get());
}
void WebSecurityPolicy::AddSchemeToBypassSecureContextWhitelist(
const WebString& scheme) {
SchemeRegistry::RegisterURLSchemeBypassingSecureContextCheck(scheme);
}
WebString WebSecurityPolicy::GenerateReferrerHeader(
WebReferrerPolicy referrer_policy,
const WebURL& url,
const WebString& referrer) {
return SecurityPolicy::GenerateReferrer(
static_cast<ReferrerPolicy>(referrer_policy), url, referrer)
.referrer;
}
void WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
const WebString& scheme) {
SchemeRegistry::RegisterURLSchemeAsNotAllowingJavascriptURLs(scheme);
}
void WebSecurityPolicy::RegisterURLSchemeAsAllowedForReferrer(
const WebString& scheme) {
SchemeRegistry::RegisterURLSchemeAsAllowedForReferrer(scheme);
}
#if defined(OS_TIZEN_TV_PRODUCT)
void WebSecurityPolicy::RegisterURLSchemeAsCORSEnabled(
const WebString& scheme) {
SchemeRegistry::RegisterURLSchemeAsCORSEnabled(scheme);
}
void WebSecurityPolicy::RegisterURLSchemeAsSecure(
const WebString& scheme) {
SchemeRegistry::RegisterURLSchemeAsSecure(scheme);
}
#endif
} // namespace blink
| [
"RetZero@desktop"
] | RetZero@desktop |
685a3544cf106b832c253c5057ef3d755613922d | 048ab5348b0c7240606463c99acb73e8f68e3c41 | /QT_Open/Login/mainwindow.cpp | e85fd1f622a4ecf2016d4f6b98a0542f1da3fc1f | [] | no_license | Le-Van-Long2k/AppQuanLiBanHangTapHoa | e8b284aa4fdf393e87f47c5bca8caf1bc873dee5 | 6bb49500f7de0094e756dc438e57c955b05fe2bf | refs/heads/master | 2023-01-16T03:36:17.079731 | 2020-11-22T14:16:51 | 2020-11-22T14:16:51 | 313,828,317 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 170 | cpp | #include "DangNhap.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
| [
"longlevan2k@gmail.com"
] | longlevan2k@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.