patch
stringlengths 17
31.2k
| y
int64 1
1
| oldf
stringlengths 0
2.21M
| idx
int64 1
1
| id
int64 4.29k
68.4k
| msg
stringlengths 8
843
| proj
stringclasses 212
values | lang
stringclasses 9
values |
---|---|---|---|---|---|---|---|
@@ -715,9 +715,9 @@ void testCanonicalize() {
TautomerEnumerator te(new TautomerCatalog(tautparams.get()));
for (const auto &itm : canonTautomerData) {
- std::unique_ptr<ROMol> mol{SmilesToMol(itm.first)};
+ ROMOL_SPTR mol{SmilesToMol(itm.first)};
TEST_ASSERT(mol);
- std::unique_ptr<ROMol> res{te.canonicalize(*mol)};
+ ROMOL_SPTR res{te.canonicalize(*mol)};
TEST_ASSERT(res);
TEST_ASSERT(MolToSmiles(*res) == itm.second);
} | 1 | //
// Copyright (C) 2018 Susan H. Leung
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include "Tautomer.h"
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <chrono>
#include <ctime>
using namespace RDKit;
using namespace MolStandardize;
void testEnumerator() {
BOOST_LOG(rdInfoLog)
<< "-----------------------\n Testing tautomer enumeration" << std::endl;
std::string rdbase = getenv("RDBASE");
std::string tautomerFile =
rdbase + "/Data/MolStandardize/tautomerTransforms.in";
auto tautparams = std::unique_ptr<TautomerCatalogParams>(
new TautomerCatalogParams(tautomerFile));
// DEPRECATED, remove from here in release 2021.01
{
unsigned int ntransforms = tautparams->getNumTautomers();
TEST_ASSERT(ntransforms == 36);
}
// DEPRECATED, remove until here in release 2021.01
unsigned int ntransforms = tautparams->getTransforms().size();
TEST_ASSERT(ntransforms == 36);
TautomerEnumerator te(new TautomerCatalog(tautparams.get()));
std::function<void(const std::string &, const std::vector<std::string> &)>
checkAns([te](const std::string &smi,
const std::vector<std::string> &ans) {
ROMOL_SPTR m(SmilesToMol(smi));
TautomerEnumeratorResult res = te.enumerate(*m);
TEST_ASSERT(res.status() == TautomerEnumeratorStatus::Completed);
size_t sz = std::max(res.size(), ans.size());
bool exceedingTautomer = false;
bool missingTautomer = false;
bool wrongTautomer = false;
for (size_t i = 0; i < sz; ++i) {
if (i >= res.size()) {
missingTautomer = true;
std::cerr << "missingTautomer, ans " << ans[i] << std::endl;
} else if (i >= ans.size()) {
exceedingTautomer = true;
std::cerr << "exceedingTautomer, taut " << MolToSmiles(*res.at(i))
<< std::endl;
} else if (MolToSmiles(*res[i]) != ans[i]) {
wrongTautomer = true;
std::cerr << "wrongTautomer, taut " << MolToSmiles(*res[i])
<< ", ans " << ans[i] << std::endl;
}
}
TEST_ASSERT(!(missingTautomer || exceedingTautomer || wrongTautomer));
});
// Enumerate 1,3 keto/enol tautomer.
checkAns("C1(=CCCCC1)O", {"O=C1CCCCC1", "OC1=CCCCC1"});
// Enumerate 1,3 keto/enol tautomer.
checkAns("C1(=CCCCC1)O", {"O=C1CCCCC1", "OC1=CCCCC1"});
// Enumerate 1,3 keto/enol tautomer.
checkAns("C1(CCCCC1)=O", {"O=C1CCCCC1", "OC1=CCCCC1"});
// Enumerate acetophenone keto/enol tautomer.
checkAns("C(=C)(O)C1=CC=CC=C1", {"C=C(O)c1ccccc1", "CC(=O)c1ccccc1"});
// Enumerate acetone keto/enol tautomer.
checkAns("CC(C)=O", {"C=C(C)O", "CC(C)=O"});
// keto/enol tautomer
checkAns("OC(C)=C(C)C", {"C=C(O)C(C)C", "CC(=O)C(C)C", "CC(C)=C(C)O"});
// 1-phenyl-2-propanone enol/keto
checkAns("c1(ccccc1)CC(=O)C",
{"C=C(O)Cc1ccccc1", "CC(=O)Cc1ccccc1", "CC(O)=Cc1ccccc1"});
// 1,5 keto/enol tautomer
checkAns("Oc1nccc2cc[nH]c(=N)c12",
{"N=c1[nH]ccc2cc[nH]c(=O)c12", "N=c1[nH]ccc2ccnc(O)c12",
"N=c1nccc2cc[nH]c(O)c1-2", "Nc1[nH]ccc2ccnc(=O)c1-2",
"Nc1nccc2cc[nH]c(=O)c12", "Nc1nccc2ccnc(O)c12"});
// 1,5 keto/enol tautomer
checkAns("C1(C=CCCC1)=O", {"O=C1C=CCCC1", "O=C1CC=CCC1", "OC1=CC=CCC1",
"OC1=CCC=CC1", "OC1=CCCC=C1"});
// 1,5 keto/enol tautomer
checkAns("C1(=CC=CCC1)O", {"O=C1C=CCCC1", "O=C1CC=CCC1", "OC1=CC=CCC1",
"OC1=CCC=CC1", "OC1=CCCC=C1"});
// aliphatic imine tautomer
checkAns("C1(CCCCC1)=N", {"N=C1CCCCC1", "NC1=CCCCC1"});
// aliphatic imine tautomer
checkAns("C1(=CCCCC1)N", {"N=C1CCCCC1", "NC1=CCCCC1"});
// special imine tautomer
checkAns("C1(C=CC=CN1)=CC", {"CC=C1C=CC=CN1", "CC=C1C=CCC=N1", "CCc1ccccn1"});
// special imine tautomer
checkAns("C1(=NC=CC=C1)CC", {"CC=C1C=CC=CN1", "CC=C1C=CCC=N1", "CCc1ccccn1"});
// 1,3 aromatic heteroatom H shift
checkAns("O=c1cccc[nH]1", {"O=c1cccc[nH]1", "Oc1ccccn1"});
// 1,3 aromatic heteroatom H shift
checkAns("Oc1ccccn1", {"O=c1cccc[nH]1", "Oc1ccccn1"});
// 1,3 aromatic heteroatom H shift
checkAns("Oc1ncc[nH]1", {"O=c1[nH]cc[nH]1", "Oc1ncc[nH]1"});
// 1,3 heteroatom H shift
checkAns("OC(C)=NC", {"C=C(O)NC", "CN=C(C)O", "CNC(C)=O"});
// 1,3 heteroatom H shift
checkAns("CNC(C)=O", {"C=C(O)NC", "CN=C(C)O", "CNC(C)=O"});
// 1,3 heteroatom H shift
checkAns("S=C(N)N", {"N=C(N)S", "NC(N)=S"});
// 1,3 heteroatom H shift
checkAns("SC(N)=N", {"N=C(N)S", "NC(N)=S"});
// 1,3 heteroatom H shift
checkAns("N=c1[nH]ccn(C)1", {"Cn1cc[nH]c1=N", "Cn1ccnc1N"});
// 1,3 heteroatom H shift
checkAns("CN=c1[nH]cncc1",
{"CN=c1cc[nH]cn1", "CN=c1ccnc[nH]1", "CNc1ccncn1"});
// 1,5 aromatic heteroatom H shift
checkAns("Oc1cccc2ccncc12", {"O=c1cccc2cc[nH]cc1-2", "Oc1cccc2ccncc12"});
// 1,5 aromatic heteroatom H shift
checkAns("O=c1cccc2cc[nH]cc1-2", {"O=c1cccc2cc[nH]cc1-2", "Oc1cccc2ccncc12"});
// 1,5 aromatic heteroatom H shift
checkAns("Cc1n[nH]c2ncnn12",
{"C=C1NN=C2N=CNN12", "C=C1NN=C2NC=NN12", "C=C1NNc2ncnn21",
"Cc1n[nH]c2ncnn12", "Cc1nnc2[nH]cnn12", "Cc1nnc2nc[nH]n12"});
// 1,5 aromatic heteroatom H shift
checkAns("Cc1nnc2nc[nH]n12",
{"C=C1NN=C2N=CNN12", "C=C1NN=C2NC=NN12", "C=C1NNc2ncnn21",
"Cc1n[nH]c2ncnn12", "Cc1nnc2[nH]cnn12", "Cc1nnc2nc[nH]n12"});
// 1,5 aromatic heteroatom H shift
checkAns("Oc1ccncc1", {"O=c1cc[nH]cc1", "Oc1ccncc1"});
// 1,5 aromatic heteroatom H shift
checkAns("Oc1c(cccc3)c3nc2ccncc12",
{"O=c1c2c[nH]ccc-2nc2ccccc12", "O=c1c2ccccc2[nH]c2ccncc12",
"Oc1c2ccccc2nc2ccncc12"});
// 1,3 and 1,5 aromatic heteroatom H shift
checkAns("Oc1ncncc1", {"O=c1cc[nH]cn1", "O=c1ccnc[nH]1", "Oc1ccncn1"});
// 1,5 aromatic heteroatom H shift
checkAns("C2(=C1C(=NC=N1)[NH]C(=N2)N)O",
{"N=c1[nH]c(=O)c2[nH]cnc2[nH]1", "N=c1[nH]c(=O)c2nc[nH]c2[nH]1",
"N=c1[nH]c2ncnc-2c(O)[nH]1", "N=c1nc(O)c2[nH]cnc2[nH]1",
"N=c1nc(O)c2nc[nH]c2[nH]1", "N=c1nc2[nH]cnc2c(O)[nH]1",
"N=c1nc2nc[nH]c2c(O)[nH]1", "Nc1nc(=O)c2[nH]cnc2[nH]1",
"Nc1nc(=O)c2nc[nH]c2[nH]1", "Nc1nc(O)c2[nH]cnc2n1",
"Nc1nc(O)c2nc[nH]c2n1", "Nc1nc(O)c2ncnc-2[nH]1",
"Nc1nc2[nH]cnc2c(=O)[nH]1", "Nc1nc2nc[nH]c2c(=O)[nH]1",
"Nc1nc2ncnc-2c(O)[nH]1"});
// 1,5 aromatic heteroatom H shift
checkAns("C2(C1=C([NH]C=N1)[NH]C(=N2)N)=O",
{"N=c1[nH]c(=O)c2[nH]cnc2[nH]1", "N=c1[nH]c(=O)c2nc[nH]c2[nH]1",
"N=c1[nH]c2ncnc-2c(O)[nH]1", "N=c1nc(O)c2[nH]cnc2[nH]1",
"N=c1nc(O)c2nc[nH]c2[nH]1", "N=c1nc2[nH]cnc2c(O)[nH]1",
"N=c1nc2nc[nH]c2c(O)[nH]1", "Nc1nc(=O)c2[nH]cnc2[nH]1",
"Nc1nc(=O)c2nc[nH]c2[nH]1", "Nc1nc(O)c2[nH]cnc2n1",
"Nc1nc(O)c2nc[nH]c2n1", "Nc1nc(O)c2ncnc-2[nH]1",
"Nc1nc2[nH]cnc2c(=O)[nH]1", "Nc1nc2nc[nH]c2c(=O)[nH]1",
"Nc1nc2ncnc-2c(O)[nH]1"});
// 1,5 aromatic heteroatom H shift
checkAns("Oc1n(C)ncc1", {"CN1N=CCC1=O", "Cn1[nH]ccc1=O", "Cn1nccc1O"});
// 1,5 aromatic heteroatom H shift
checkAns("O=c1nc2[nH]ccn2cc1",
{"O=c1ccn2cc[nH]c2n1", "O=c1ccn2ccnc2[nH]1", "Oc1ccn2ccnc2n1"});
// 1,5 aromatic heteroatom H shift
checkAns("N=c1nc[nH]cc1", {"N=c1cc[nH]cn1", "N=c1ccnc[nH]1", "Nc1ccncn1"});
// 1,5 aromatic heteroatom H shift
checkAns("N=c(c1)ccn2cc[nH]c12", {"N=c1ccn2cc[nH]c2c1", "Nc1ccn2ccnc2c1"});
// 1,5 aromatic heteroatom H shift
checkAns("CN=c1nc[nH]cc1",
{"CN=c1cc[nH]cn1", "CN=c1ccnc[nH]1", "CNc1ccncn1"});
// 1,7 aromatic heteroatom H shift
checkAns("c1ccc2[nH]c(-c3nc4ccccc4[nH]3)nc2c1",
{"c1ccc2[nH]c(-c3nc4ccccc4[nH]3)nc2c1",
"c1ccc2c(c1)=NC(c1nc3ccccc3[nH]1)N=2",
"c1ccc2c(c1)NC(=C1N=c3ccccc3=N1)N2"});
// 1,7 aromatic heteroatom H shift
checkAns("c1ccc2c(c1)NC(=C1N=c3ccccc3=N1)N2",
{"c1ccc2[nH]c(-c3nc4ccccc4[nH]3)nc2c1",
"c1ccc2c(c1)=NC(c1nc3ccccc3[nH]1)N=2",
"c1ccc2c(c1)NC(=C1N=c3ccccc3=N1)N2"});
// 1,9 aromatic heteroatom H shift
checkAns("CNc1ccnc2ncnn21", {"CN=c1cc[nH]c2ncnn12", "CN=c1ccnc2[nH]cnn12",
"CN=c1ccnc2nc[nH]n12", "CNc1ccnc2ncnn12"});
// 1,9 aromatic heteroatom H shift
checkAns("CN=c1ccnc2nc[nH]n21", {"CN=c1cc[nH]c2ncnn12", "CN=c1ccnc2[nH]cnn12",
"CN=c1ccnc2nc[nH]n12", "CNc1ccnc2ncnn12"});
// 1,11 aromatic heteroatom H shift
checkAns("Nc1ccc(C=C2C=CC(=O)C=C2)cc1",
{"N=C1C=CC(=CC2C=CC(=O)C=C2)C=C1", "N=C1C=CC(=Cc2ccc(O)cc2)C=C1",
"N=C1C=CC(C=C2C=CC(=O)C=C2)C=C1", "Nc1ccc(C=C2C=CC(=O)C=C2)cc1"});
// 1,11 aromatic heteroatom H shift
checkAns("N=C1C=CC(=Cc2ccc(O)cc2)C=C1",
{"N=C1C=CC(=CC2C=CC(=O)C=C2)C=C1", "N=C1C=CC(=Cc2ccc(O)cc2)C=C1",
"N=C1C=CC(C=C2C=CC(=O)C=C2)C=C1", "Nc1ccc(C=C2C=CC(=O)C=C2)cc1"});
// heterocyclic tautomer
checkAns("n1ccc2ccc[nH]c12", {"c1c[nH]c2nccc-2c1", "c1cnc2[nH]ccc2c1"});
// heterocyclic tautomer
checkAns("c1cc(=O)[nH]c2nccn12",
{"O=c1ccn2cc[nH]c2n1", "O=c1ccn2ccnc2[nH]1", "Oc1ccn2ccnc2n1"});
// heterocyclic tautomer
checkAns("c1cnc2c[nH]ccc12", {"c1cc2cc[nH]c2cn1", "c1cc2cc[nH]cc-2n1"});
// heterocyclic tautomer
checkAns("n1ccc2c[nH]ccc12", {"c1cc2[nH]ccc2cn1", "c1cc2c[nH]ccc-2n1"});
// heterocyclic tautomer
checkAns("c1cnc2ccc[nH]c12", {"c1c[nH]c2ccnc-2c1", "c1cnc2cc[nH]c2c1"});
// furanone tautomer
checkAns("C1=CC=C(O1)O", {"O=C1CC=CO1", "Oc1ccco1"});
// furanone tautomer
checkAns("O=C1CC=CO1", {"O=C1CC=CO1", "Oc1ccco1"});
// keten/ynol tautomer
checkAns("CC=C=O", {"CC#CO", "CC=C=O"});
// keten/ynol tautomer
checkAns("CC#CO", {"CC#CO", "CC=C=O"});
// ionic nitro/aci-nitro tautomer
checkAns("C([N+](=O)[O-])C", {"CC=[N+]([O-])O", "CC[N+](=O)[O-]"});
// ionic nitro/aci-nitro tautomer
checkAns("C(=[N+](O)[O-])C", {"CC=[N+]([O-])O", "CC[N+](=O)[O-]"});
// oxim nitroso tautomer
checkAns("CC(C)=NO", {"C=C(C)NO", "CC(C)=NO", "CC(C)N=O"});
// oxim nitroso tautomer
checkAns("CC(C)N=O", {"C=C(C)NO", "CC(C)=NO", "CC(C)N=O"});
// oxim/nitroso tautomer via phenol
checkAns("O=Nc1ccc(O)cc1",
{"O=C1C=CC(=NO)C=C1", "O=NC1C=CC(=O)C=C1", "O=Nc1ccc(O)cc1"});
// oxim/nitroso tautomer via phenol
checkAns("O=C1C=CC(=NO)C=C1",
{"O=C1C=CC(=NO)C=C1", "O=NC1C=CC(=O)C=C1", "O=Nc1ccc(O)cc1"});
// cyano/iso-cyanic acid tautomer
checkAns("C(#N)O", {"N#CO", "N=C=O"});
// cyano/iso-cyanic acid tautomer
checkAns("C(=N)=O", {"N#CO", "N=C=O"});
// formamidinesulfinic acid tautomer
checkAns("NC(N)=S(=O)=O",
{"N=C(N)S(=O)O", "N=C(N)[SH](=O)=O", "NC(N)=S(=O)=O"});
// formamidinesulfinic acid tautomer
checkAns("NC(=N)S(=O)O",
{"N=C(N)S(=O)O", "N=C(N)[SH](=O)=O", "NC(N)=S(=O)=O"});
// formamidinesulfonic acid tautomer
checkAns("NC(=N)S(=O)(=O)O", {"N=C(N)S(=O)(=O)O"});
// isocyanide tautomer
checkAns("C#N", {"C#N", "[C-]#[NH+]"});
// isocyanide tautomer
checkAns("[C-]#[NH+]", {"C#N", "[C-]#[NH+]"});
// phosphonic acid tautomer
checkAns("[PH](=O)(O)(O)", {"O=[PH](O)O", "OP(O)O"});
// phosphonic acid tautomer
checkAns("P(O)(O)O", {"O=[PH](O)O", "OP(O)O"});
// Remove stereochemistry from mobile double bonds
checkAns("c1(ccccc1)/C=C(/O)\\C",
{"C=C(O)Cc1ccccc1", "CC(=O)Cc1ccccc1", "CC(O)=Cc1ccccc1"});
// Remove stereochemistry from mobile double bonds
checkAns("C/C=C/C(C)=O", {"C=C(O)C=CC", "C=CC=C(C)O", "C=CCC(=C)O",
"C=CCC(C)=O", "CC=CC(C)=O"});
// Remove stereochemistry from mobile double bonds
std::string smi66 = "C/C=C\\C(C)=O";
ROMOL_SPTR m66(SmilesToMol(smi66));
TautomerEnumeratorResult res66 = te.enumerate(*m66);
std::vector<std::string> ans66 = {"C=C(O)C=CC", "C=CC=C(C)O", "C=CCC(=C)O",
"C=CCC(C)=O", "CC=CC(C)=O"};
TEST_ASSERT(res66.size() == ans66.size());
TEST_ASSERT(res66.status() == TautomerEnumeratorStatus::Completed);
std::vector<std::string> sm66;
for (const auto &r : res66) {
sm66.push_back(MolToSmiles(*r));
}
// sort both for alphabetical order
std::sort(sm66.begin(), sm66.end());
std::sort(ans66.begin(), ans66.end());
TEST_ASSERT(sm66 == ans66);
// Gaunine tautomers
std::string smi67 = "N1C(N)=NC=2N=CNC2C1=O";
ROMOL_SPTR m67(SmilesToMol(smi67));
TautomerEnumeratorResult res67 = te.enumerate(*m67);
std::vector<std::string> ans67 = {
"N=c1[nH]c(=O)c2[nH]cnc2[nH]1", "N=c1[nH]c(=O)c2nc[nH]c2[nH]1",
"N=c1[nH]c2ncnc-2c(O)[nH]1", "N=c1nc(O)c2[nH]cnc2[nH]1",
"N=c1nc(O)c2nc[nH]c2[nH]1", "N=c1nc2[nH]cnc2c(O)[nH]1",
"N=c1nc2nc[nH]c2c(O)[nH]1", "Nc1nc(=O)c2[nH]cnc2[nH]1",
"Nc1nc(=O)c2nc[nH]c2[nH]1", "Nc1nc(O)c2[nH]cnc2n1",
"Nc1nc(O)c2nc[nH]c2n1", "Nc1nc(O)c2ncnc-2[nH]1",
"Nc1nc2[nH]cnc2c(=O)[nH]1", "Nc1nc2nc[nH]c2c(=O)[nH]1",
"Nc1nc2ncnc-2c(O)[nH]1"};
TEST_ASSERT(res67.size() == ans67.size());
TEST_ASSERT(res67.status() == TautomerEnumeratorStatus::Completed);
std::vector<std::string> sm67;
for (const auto &r : res67) {
sm67.push_back(MolToSmiles(*r));
}
// sort both by alphabetical order
std::sort(sm67.begin(), sm67.end());
std::sort(ans67.begin(), ans67.end());
TEST_ASSERT(sm67 == ans67);
// Test a structure with hundreds of tautomers.
std::string smi68 = "[H][C](CO)(NC(=O)C1=C(O)C(O)=CC=C1)C(O)=O";
ROMOL_SPTR m68(SmilesToMol(smi68));
TautomerEnumeratorResult res68 = te.enumerate(*m68);
// the maxTransforms limit is hit before the maxTautomers one
TEST_ASSERT(res68.size() == 292);
TEST_ASSERT(res68.status() == TautomerEnumeratorStatus::MaxTransformsReached);
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testEnumeratorParams() {
BOOST_LOG(rdInfoLog)
<< "-----------------------\n Testing TautomerEnumerator params"
<< std::endl;
// Test a structure with hundreds of tautomers.
std::string smi68 = "[H][C](CO)(NC(=O)C1=C(O)C(O)=CC=C1)C(O)=O";
ROMOL_SPTR m68(SmilesToMol(smi68));
{
TautomerEnumerator te;
TautomerEnumeratorResult res68 = te.enumerate(*m68);
TEST_ASSERT(res68.size() == 292);
TEST_ASSERT(res68.status() ==
TautomerEnumeratorStatus::MaxTransformsReached);
}
{
CleanupParameters params;
params.maxTautomers = 50;
TautomerEnumerator te(params);
TautomerEnumeratorResult res68 = te.enumerate(*m68);
TEST_ASSERT(res68.size() == 50);
TEST_ASSERT(res68.status() ==
TautomerEnumeratorStatus::MaxTautomersReached);
}
std::string sAlaSmi = "C[C@H](N)C(=O)O";
ROMOL_SPTR sAla(SmilesToMol(sAlaSmi));
{
// test remove (S)-Ala stereochemistry
TEST_ASSERT(sAla->getAtomWithIdx(1)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CCW);
TEST_ASSERT(sAla->getAtomWithIdx(1)->getProp<std::string>(
common_properties::_CIPCode) == "S");
CleanupParameters params;
params.tautomerRemoveSp3Stereo = true;
TautomerEnumerator te(params);
TautomerEnumeratorResult res = te.enumerate(*sAla);
for (const auto &taut : res) {
TEST_ASSERT(taut->getAtomWithIdx(1)->getChiralTag() ==
Atom::CHI_UNSPECIFIED);
TEST_ASSERT(
!taut->getAtomWithIdx(1)->hasProp(common_properties::_CIPCode));
}
}
{
// test retain (S)-Ala stereochemistry
TEST_ASSERT(sAla->getAtomWithIdx(1)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CCW);
TEST_ASSERT(sAla->getAtomWithIdx(1)->getProp<std::string>(
common_properties::_CIPCode) == "S");
CleanupParameters params;
params.tautomerRemoveSp3Stereo = false;
TautomerEnumerator te(params);
TautomerEnumeratorResult res = te.enumerate(*sAla);
for (const auto &taut : res) {
const auto tautAtom = taut->getAtomWithIdx(1);
if (tautAtom->getHybridization() == Atom::SP3) {
TEST_ASSERT(tautAtom->hasProp(common_properties::_CIPCode));
TEST_ASSERT(
tautAtom->getProp<std::string>(common_properties::_CIPCode) == "S");
TEST_ASSERT(tautAtom->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW);
} else {
TEST_ASSERT(!tautAtom->hasProp(common_properties::_CIPCode));
TEST_ASSERT(tautAtom->getChiralTag() == Atom::CHI_UNSPECIFIED);
}
}
}
std::string eEnolSmi = "C/C=C/O";
ROMOL_SPTR eEnol(SmilesToMol(eEnolSmi));
TEST_ASSERT(eEnol->getBondWithIdx(1)->getStereo() == Bond::STEREOE);
{
// test remove enol E stereochemistry
CleanupParameters params;
params.tautomerRemoveBondStereo = true;
TautomerEnumerator te(params);
TautomerEnumeratorResult res = te.enumerate(*eEnol);
for (const auto &taut : res) {
TEST_ASSERT(taut->getBondWithIdx(1)->getStereo() == Bond::STEREONONE);
}
}
{
// test retain enol E stereochemistry
CleanupParameters params;
params.tautomerRemoveBondStereo = false;
TautomerEnumerator te(params);
TautomerEnumeratorResult res = te.enumerate(*eEnol);
for (const auto &taut : res) {
if (taut->getBondWithIdx(1)->getBondType() == Bond::DOUBLE) {
TEST_ASSERT(taut->getBondWithIdx(1)->getStereo() == Bond::STEREOE);
}
}
}
ROMOL_SPTR zEnol = "C/C=C\\O"_smiles;
TEST_ASSERT(zEnol->getBondWithIdx(1)->getStereo() == Bond::STEREOZ);
{
// test remove enol Z stereochemistry
CleanupParameters params;
params.tautomerRemoveBondStereo = true;
TautomerEnumerator te(params);
TautomerEnumeratorResult res = te.enumerate(*zEnol);
for (const auto &taut : res) {
TEST_ASSERT(taut->getBondWithIdx(1)->getStereo() == Bond::STEREONONE);
}
}
{
// test retain enol Z stereochemistry
CleanupParameters params;
params.tautomerRemoveBondStereo = false;
TautomerEnumerator te(params);
TautomerEnumeratorResult res = te.enumerate(*zEnol);
for (const auto &taut : res) {
if (taut->getBondWithIdx(1)->getBondType() == Bond::DOUBLE) {
TEST_ASSERT(taut->getBondWithIdx(1)->getStereo() == Bond::STEREOZ);
}
}
}
ROMOL_SPTR chembl2024142 =
"[2H]C1=C(C(=C2C(=C1[2H])C(=O)C(=C(C2=O)C([2H])([2H])[2H])C/C=C(\\C)/CC([2H])([2H])/C=C(/CC/C=C(\\C)/CCC=C(C)C)\\C([2H])([2H])[2H])[2H])[2H]"_smiles;
MolOps::RemoveHsParameters hparams;
hparams.removeAndTrackIsotopes = true;
chembl2024142.reset(MolOps::removeHs(*chembl2024142, hparams));
TEST_ASSERT(chembl2024142->getAtomWithIdx(12)->hasProp(
common_properties::_isotopicHs));
{
// test remove isotopic Hs involved in tautomerism
CleanupParameters params;
params.tautomerRemoveIsotopicHs = true;
TautomerEnumerator te(params);
TautomerEnumeratorResult res = te.enumerate(*chembl2024142);
for (const auto &taut : res) {
const auto tautAtom = taut->getAtomWithIdx(12);
TEST_ASSERT(!tautAtom->hasProp(common_properties::_isotopicHs));
}
}
{
// test retain isotopic Hs involved in tautomerism
CleanupParameters params;
params.tautomerRemoveIsotopicHs = false;
TautomerEnumerator te(params);
TautomerEnumeratorResult res = te.enumerate(*chembl2024142);
for (const auto &taut : res) {
const auto tautAtom = taut->getAtomWithIdx(12);
TEST_ASSERT(tautAtom->hasProp(common_properties::_isotopicHs));
}
}
ROMOL_SPTR enolexample = "[2H]OC=C"_smiles;
enolexample.reset(MolOps::removeHs(*enolexample, hparams));
TEST_ASSERT(
enolexample->getAtomWithIdx(0)->hasProp(common_properties::_isotopicHs));
{
CleanupParameters params;
params.tautomerRemoveIsotopicHs = true;
TautomerEnumerator te(params);
TautomerEnumeratorResult res = te.enumerate(*enolexample);
for (const auto &taut : res) {
const auto tautAtom = taut->getAtomWithIdx(0);
TEST_ASSERT(!(tautAtom->hasProp(common_properties::_isotopicHs) &&
!tautAtom->getTotalNumHs()));
}
}
{
CleanupParameters params;
params.tautomerRemoveIsotopicHs = false;
TautomerEnumerator te(params);
TautomerEnumeratorResult res = te.enumerate(*enolexample);
for (const auto &taut : res) {
const auto tautAtom = taut->getAtomWithIdx(0);
TEST_ASSERT(!(tautAtom->hasProp(common_properties::_isotopicHs) &&
!tautAtom->getTotalNumHs()));
}
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testEnumeratorCallback() {
class MyTautomerEnumeratorCallback : public TautomerEnumeratorCallback {
public:
MyTautomerEnumeratorCallback(double timeoutMs)
: d_timeoutMs(timeoutMs), d_start(std::chrono::system_clock::now()) {}
bool operator()(const ROMol &, const TautomerEnumeratorResult &) override {
double elapsedMs = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now() - d_start)
.count();
return (elapsedMs < d_timeoutMs);
}
private:
double d_timeoutMs;
std::chrono::time_point<std::chrono::system_clock> d_start;
};
BOOST_LOG(rdInfoLog)
<< "-----------------------\n Testing TautomerEnumerator callback"
<< std::endl;
// Test a structure with hundreds of tautomers.
std::string smi68 = "[H][C](CO)(NC(=O)C1=C(O)C(O)=CC=C1)C(O)=O";
ROMOL_SPTR m68(SmilesToMol(smi68));
CleanupParameters params;
params.maxTransforms = 10000;
params.maxTautomers = 10000;
{
TautomerEnumerator te(params);
te.setCallback(new MyTautomerEnumeratorCallback(50.0));
TautomerEnumeratorResult res68 = te.enumerate(*m68);
// either the enumeration was canceled due to timeout
// or it has completed very quickly
bool hasReachedTimeout =
(res68.size() < 375 &&
res68.status() == TautomerEnumeratorStatus::Canceled);
bool hasCompleted = (res68.size() == 375 &&
res68.status() == TautomerEnumeratorStatus::Completed);
if (hasReachedTimeout) {
std::cerr << "Enumeration was canceled due to timeout (50 ms)"
<< std::endl;
}
if (hasCompleted) {
std::cerr << "Enumeration has completed" << std::endl;
}
TEST_ASSERT(hasReachedTimeout || hasCompleted);
TEST_ASSERT(hasReachedTimeout ^ hasCompleted);
}
{
TautomerEnumerator te(params);
te.setCallback(new MyTautomerEnumeratorCallback(10000.0));
TautomerEnumeratorResult res68 = te.enumerate(*m68);
// either the enumeration completed
// or it ran very slowly and was canceled due to timeout
bool hasReachedTimeout =
(res68.size() < 375 &&
res68.status() == TautomerEnumeratorStatus::Canceled);
bool hasCompleted = (res68.size() == 375 &&
res68.status() == TautomerEnumeratorStatus::Completed);
if (hasReachedTimeout) {
std::cerr << "Enumeration was canceled due to timeout (10 s)"
<< std::endl;
}
if (hasCompleted) {
std::cerr << "Enumeration has completed" << std::endl;
}
TEST_ASSERT(hasReachedTimeout || hasCompleted);
TEST_ASSERT(hasReachedTimeout ^ hasCompleted);
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
// tests from the molvs repo:
// https://github.com/mcs07/MolVS/blob/456f2fe723acfedbf634a8bcfe943b83ea7d4c20/tests/test_tautomer.py
std::vector<std::pair<std::string, std::string>> canonTautomerData{
{"C1(=CCCCC1)O", "O=C1CCCCC1"},
{"C1(CCCCC1)=O", "O=C1CCCCC1"},
{"C(=C)(O)C1=CC=CC=C1", "CC(=O)c1ccccc1"},
{"CC(C)=O", "CC(C)=O"},
{"OC(C)=C(C)C", "CC(=O)C(C)C"},
{"c1(ccccc1)CC(=O)C", "CC(=O)Cc1ccccc1"},
{"Oc1nccc2cc[nH]c(=N)c12", "Nc1nccc2cc[nH]c(=O)c12"},
{"C1(C=CCCC1)=O", "O=C1C=CCCC1"},
{"C1(CCCCC1)=N", "N=C1CCCCC1"},
{"C1(=CCCCC1)N", "N=C1CCCCC1"},
{"C1(C=CC=CN1)=CC", "CCc1ccccn1"},
{"C1(=NC=CC=C1)CC", "CCc1ccccn1"},
{"O=c1cccc[nH]1", "O=c1cccc[nH]1"},
{"Oc1ccccn1", "O=c1cccc[nH]1"},
{"Oc1ncc[nH]1", "O=c1[nH]cc[nH]1"},
{"OC(C)=NC", "CNC(C)=O"},
{"CNC(C)=O", "CNC(C)=O"},
{"S=C(N)N", "NC(N)=S"},
{"SC(N)=N", "NC(N)=S"},
{"N=c1[nH]ccn(C)1", "Cn1ccnc1N"},
{"CN=c1[nH]cncc1", "CNc1ccncn1"},
{"Oc1cccc2ccncc12", "Oc1cccc2ccncc12"},
{"O=c1cccc2cc[nH]cc1-2", "Oc1cccc2ccncc12"},
{"Cc1n[nH]c2ncnn12", "Cc1n[nH]c2ncnn12"},
{"Cc1nnc2nc[nH]n12", "Cc1n[nH]c2ncnn12"},
{"Oc1ccncc1", "O=c1cc[nH]cc1"},
{"Oc1c(cccc3)c3nc2ccncc12", "O=c1c2ccccc2[nH]c2ccncc12"},
{"Oc1ncncc1", "O=c1cc[nH]cn1"},
{"C2(=C1C(=NC=N1)[NH]C(=N2)N)O", "Nc1nc(=O)c2[nH]cnc2[nH]1"},
{"C2(C1=C([NH]C=N1)[NH]C(=N2)N)=O", "Nc1nc(=O)c2[nH]cnc2[nH]1"},
{"Oc1n(C)ncc1", "Cn1[nH]ccc1=O"},
{"O=c1nc2[nH]ccn2cc1", "O=c1ccn2cc[nH]c2n1"},
{"N=c1nc[nH]cc1", "Nc1ccncn1"},
{"N=c(c1)ccn2cc[nH]c12", "Nc1ccn2ccnc2c1"},
{"CN=c1nc[nH]cc1", "CNc1ccncn1"},
{"c1ccc2[nH]c(-c3nc4ccccc4[nH]3)nc2c1",
"c1ccc2[nH]c(-c3nc4ccccc4[nH]3)nc2c1"},
{"c1ccc2c(c1)NC(=C1N=c3ccccc3=N1)N2",
"c1ccc2[nH]c(-c3nc4ccccc4[nH]3)nc2c1"},
{"CNc1ccnc2ncnn21", "CNc1ccnc2ncnn12"},
{"CN=c1ccnc2nc[nH]n21", "CNc1ccnc2ncnn12"},
{"Nc1ccc(C=C2C=CC(=O)C=C2)cc1", "Nc1ccc(C=C2C=CC(=O)C=C2)cc1"},
{"N=C1C=CC(=Cc2ccc(O)cc2)C=C1", "Nc1ccc(C=C2C=CC(=O)C=C2)cc1"},
{"n1ccc2ccc[nH]c12", "c1cnc2[nH]ccc2c1"},
{"c1cc(=O)[nH]c2nccn12", "O=c1ccn2cc[nH]c2n1"},
{"c1cnc2c[nH]ccc12", "c1cc2cc[nH]c2cn1"},
{"n1ccc2c[nH]ccc12", "c1cc2[nH]ccc2cn1"},
{"c1cnc2ccc[nH]c12", "c1cnc2cc[nH]c2c1"},
{"C1=CC=C(O1)O", "Oc1ccco1"},
{"O=C1CC=CO1", "Oc1ccco1"},
{"CC=C=O", "CC=C=O"},
{"CC#CO", "CC=C=O"},
{"C([N+](=O)[O-])C", "CC[N+](=O)[O-]"},
{"C(=[N+](O)[O-])C", "CC[N+](=O)[O-]"},
{"CC(C)=NO", "CC(C)=NO"},
{"CC(C)N=O", "CC(C)=NO"},
{"O=Nc1ccc(O)cc1", "O=Nc1ccc(O)cc1"},
{"O=C1C=CC(=NO)C=C1", "O=Nc1ccc(O)cc1"},
{"C(#N)O", "N=C=O"},
{"C(=N)=O", "N=C=O"},
{"N=C(N)S(=O)O", "N=C(N)S(=O)O"},
{"C#N", "C#N"},
{"[C-]#[NH+]", "C#N"},
{"[PH](=O)(O)(O)", "O=[PH](O)O"},
{"P(O)(O)O", "O=[PH](O)O"}};
void testCanonicalize() {
BOOST_LOG(rdInfoLog)
<< "-----------------------\n Testing tautomer canonicalization"
<< std::endl;
std::string rdbase = getenv("RDBASE");
std::string tautomerFile =
rdbase + "/Data/MolStandardize/tautomerTransforms.in";
auto tautparams = std::unique_ptr<TautomerCatalogParams>(
new TautomerCatalogParams(tautomerFile));
// DEPRECATED, remove from here in release 2021.01
{
unsigned int ntransforms = tautparams->getNumTautomers();
TEST_ASSERT(ntransforms == 36);
}
// DEPRECATED, remove until here in release 2021.01
unsigned int ntransforms = tautparams->getTransforms().size();
TEST_ASSERT(ntransforms == 36);
TautomerEnumerator te(new TautomerCatalog(tautparams.get()));
for (const auto &itm : canonTautomerData) {
std::unique_ptr<ROMol> mol{SmilesToMol(itm.first)};
TEST_ASSERT(mol);
std::unique_ptr<ROMol> res{te.canonicalize(*mol)};
TEST_ASSERT(res);
TEST_ASSERT(MolToSmiles(*res) == itm.second);
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testPickCanonical() {
BOOST_LOG(rdInfoLog) << "-----------------------\n Testing pickCanonical"
<< std::endl;
std::string rdbase = getenv("RDBASE");
std::string tautomerFile =
rdbase + "/Data/MolStandardize/tautomerTransforms.in";
auto tautparams = std::unique_ptr<TautomerCatalogParams>(
new TautomerCatalogParams(tautomerFile));
// DEPRECATED, remove from here in release 2021.01
{
unsigned int ntransforms = tautparams->getNumTautomers();
TEST_ASSERT(ntransforms == 36);
}
// DEPRECATED, remove until here in release 2021.01
unsigned int ntransforms = tautparams->getTransforms().size();
TEST_ASSERT(ntransforms == 36);
TautomerEnumerator te(new TautomerCatalog(tautparams.get()));
for (const auto &itm : canonTautomerData) {
std::unique_ptr<ROMol> mol{SmilesToMol(itm.first)};
TEST_ASSERT(mol);
auto tautRes = te.enumerate(*mol);
std::unique_ptr<ROMol> res{te.pickCanonical(tautRes)};
TEST_ASSERT(res);
// std::cerr << itm.first<<" -> "<<MolToSmiles(*res)<<std::endl;
TEST_ASSERT(MolToSmiles(*res) == itm.second);
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testCustomScoreFunc() {
BOOST_LOG(rdInfoLog)
<< "-----------------------\n Testing custom scoring functions"
<< std::endl;
std::string rdbase = getenv("RDBASE");
std::string tautomerFile =
rdbase + "/Data/MolStandardize/tautomerTransforms.in";
auto tautparams = std::unique_ptr<TautomerCatalogParams>(
new TautomerCatalogParams(tautomerFile));
// DEPRECATED, remove from here in release 2021.01
{
unsigned int ntransforms = tautparams->getNumTautomers();
TEST_ASSERT(ntransforms == 36);
}
// DEPRECATED, remove until here in release 2021.01
unsigned int ntransforms = tautparams->getTransforms().size();
TEST_ASSERT(ntransforms == 36);
TautomerEnumerator te(new TautomerCatalog(tautparams.get()));
// silly examples just using the scoreRings() function
std::vector<std::pair<std::string, std::string>> subsetTautomerData{
{"C1(=CCCCC1)O", "O=C1CCCCC1"},
{"C1(CCCCC1)=O", "O=C1CCCCC1"},
{"C(=C)(O)C1=CC=CC=C1", "C=C(O)c1ccccc1"},
{"CC(C)=O", "C=C(C)O"},
{"OC(C)=C(C)C", "C=C(O)C(C)C"},
};
for (const auto &itm : subsetTautomerData) {
std::unique_ptr<ROMol> mol{SmilesToMol(itm.first)};
TEST_ASSERT(mol);
{
// this uses the non-templated pickCanonical() function
std::unique_ptr<ROMol> res{
te.canonicalize(*mol, [](const ROMol &m) -> int {
return MolStandardize::TautomerScoringFunctions::scoreRings(m);
})};
TEST_ASSERT(res);
TEST_ASSERT(MolToSmiles(*res) == itm.second);
}
{
// this uses the non-templated pickCanonical() overload
auto tautRes = te.enumerate(*mol);
std::unique_ptr<ROMol> res{
te.pickCanonical(tautRes, [](const ROMol &m) -> int {
return MolStandardize::TautomerScoringFunctions::scoreRings(m);
})};
TEST_ASSERT(res);
TEST_ASSERT(MolToSmiles(*res) == itm.second);
}
{
// this tests the templated pickCanonical() overload on a std::vector
auto tautRes = te.enumerate(*mol);
std::unique_ptr<ROMol> res{
te.pickCanonical(tautRes.tautomers(), [](const ROMol &m) -> int {
return MolStandardize::TautomerScoringFunctions::scoreRings(m);
})};
TEST_ASSERT(res);
TEST_ASSERT(MolToSmiles(*res) == itm.second);
}
{
// this tests the templated pickCanonical() overload
// with a different iterable container
auto tautRes = te.enumerate(*mol);
std::set<ROMOL_SPTR> tautomerSet(tautRes.begin(), tautRes.end());
std::unique_ptr<ROMol> res{
te.pickCanonical(tautomerSet, [](const ROMol &m) -> int {
return MolStandardize::TautomerScoringFunctions::scoreRings(m);
})};
TEST_ASSERT(res);
TEST_ASSERT(MolToSmiles(*res) == itm.second);
}
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testEnumerationProblems() {
BOOST_LOG(rdInfoLog)
<< "-----------------------\n Testing tautomer enumeration problems"
<< std::endl;
std::string rdbase = getenv("RDBASE");
std::string tautomerFile =
rdbase + "/Data/MolStandardize/tautomerTransforms.in";
auto tautparams = std::unique_ptr<TautomerCatalogParams>(
new TautomerCatalogParams(tautomerFile));
// DEPRECATED, remove from here in release 2021.01
{
unsigned int ntransforms = tautparams->getNumTautomers();
TEST_ASSERT(ntransforms == 36);
}
// DEPRECATED, remove until here in release 2021.01
unsigned int ntransforms = tautparams->getTransforms().size();
TEST_ASSERT(ntransforms == 36);
TautomerEnumerator te(new TautomerCatalog(tautparams.get()));
#if 1
{ // from the discussion of #2908
auto mol = "O=C(C1=C[NH+]=CC=C1)[O-]"_smiles;
auto tautRes = te.enumerate(*mol);
TEST_ASSERT(tautRes.size() == 1);
}
#endif
{ // one of the examples from the tautobase paper
auto m =
"[S:1]=[c:2]1[nH+:3][c:5]([NH2:9])[nH:8][c:7]2[c:4]1[n:6][nH:10][n:11]2"_smiles;
TEST_ASSERT(m);
auto tautRes = te.enumerate(*m);
// for (auto taut : tauts) {
// std::cerr << MolToSmiles(*taut) << std::endl;
// }
TEST_ASSERT(tautRes.size() == 12);
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testPickCanonical2() {
BOOST_LOG(rdInfoLog) << "-----------------------\n Testing pickCanonical"
<< std::endl;
std::string rdbase = getenv("RDBASE");
std::string tautomerFile =
rdbase + "/Data/MolStandardize/tautomerTransforms.in";
auto tautparams = std::unique_ptr<TautomerCatalogParams>(
new TautomerCatalogParams(tautomerFile));
// DEPRECATED, remove from here in release 2021.01
{
unsigned int ntransforms = tautparams->getNumTautomers();
TEST_ASSERT(ntransforms == 36);
}
// DEPRECATED, remove until here in release 2021.01
unsigned int ntransforms = tautparams->getTransforms().size();
TEST_ASSERT(ntransforms == 36);
TautomerEnumerator te(new TautomerCatalog(tautparams.get()));
{
auto mol = "CN=c1nc[nH]cc1"_smiles;
TEST_ASSERT(mol);
auto tautRes = te.enumerate(*mol);
for (const auto &taut : tautRes) {
std::cerr << MolToSmiles(*taut) << std::endl;
}
std::unique_ptr<ROMol> canon{te.pickCanonical(tautRes)};
std::cerr << "res: " << MolToSmiles(*canon) << std::endl;
}
{
auto mol = "CN=c1[nH]cccc1"_smiles;
TEST_ASSERT(mol);
auto tautRes = te.enumerate(*mol);
for (const auto &taut : tautRes) {
std::cerr << MolToSmiles(*taut) << std::endl;
}
std::unique_ptr<ROMol> canon{te.pickCanonical(tautRes)};
std::cerr << "res: " << MolToSmiles(*canon) << std::endl;
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testEnumerateDetails() {
BOOST_LOG(rdInfoLog)
<< "-----------------------\n Testing getting details back "
"from tautomer enumeration"
<< std::endl;
std::string rdbase = getenv("RDBASE");
std::string tautomerFile =
rdbase + "/Data/MolStandardize/tautomerTransforms.in";
auto tautparams = std::unique_ptr<TautomerCatalogParams>(
new TautomerCatalogParams(tautomerFile));
// DEPRECATED, remove from here in release 2021.01
{
unsigned int ntransforms = tautparams->getNumTautomers();
TEST_ASSERT(ntransforms == 36);
}
// DEPRECATED, remove until here in release 2021.01
unsigned int ntransforms = tautparams->getTransforms().size();
TEST_ASSERT(ntransforms == 36);
TautomerEnumerator te(new TautomerCatalog(tautparams.get()));
{
auto mol = "c1ccccc1CN=c1[nH]cccc1"_smiles;
TEST_ASSERT(mol);
auto tautRes = te.enumerate(*mol);
TEST_ASSERT(tautRes.size() == 2);
TEST_ASSERT(tautRes.modifiedAtoms().count() == 2);
TEST_ASSERT(tautRes.modifiedBonds().count() == 7);
TEST_ASSERT(tautRes.modifiedAtoms().test(7));
TEST_ASSERT(tautRes.modifiedAtoms().test(9));
TEST_ASSERT(!tautRes.modifiedBonds().test(0));
TEST_ASSERT(tautRes.modifiedBonds().test(7));
TEST_ASSERT(tautRes.modifiedBonds().test(8));
TEST_ASSERT(tautRes.modifiedBonds().test(14));
}
{
// test the deprecated form
auto mol = "c1ccccc1CN=c1[nH]cccc1"_smiles;
TEST_ASSERT(mol);
boost::dynamic_bitset<> atomsModified(mol->getNumAtoms());
boost::dynamic_bitset<> bondsModified(mol->getNumBonds());
#if defined(_MSC_VER)
#pragma warning(suppress : 4996)
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
auto tauts = te.enumerate(*mol, &atomsModified, &bondsModified);
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
TEST_ASSERT(tauts.size() == 2);
TEST_ASSERT(atomsModified.count() == 2);
TEST_ASSERT(bondsModified.count() == 7);
TEST_ASSERT(atomsModified[7]);
TEST_ASSERT(atomsModified[9]);
TEST_ASSERT(!bondsModified[0]);
TEST_ASSERT(bondsModified[7]);
TEST_ASSERT(bondsModified[8]);
TEST_ASSERT(bondsModified[14]);
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testGithub2990() {
BOOST_LOG(rdInfoLog) << "-----------------------\n Testing Github #2990: "
"Tautomer enumeration "
"should remove stereo in all tautomers"
<< std::endl;
std::string rdbase = getenv("RDBASE");
std::string tautomerFile =
rdbase + "/Data/MolStandardize/tautomerTransforms.in";
auto tautparams = std::unique_ptr<TautomerCatalogParams>(
new TautomerCatalogParams(tautomerFile));
// DEPRECATED, remove from here in release 2021.01
{
unsigned int ntransforms = tautparams->getNumTautomers();
TEST_ASSERT(ntransforms == 36);
}
// DEPRECATED, remove until here in release 2021.01
unsigned int ntransforms = tautparams->getTransforms().size();
TEST_ASSERT(ntransforms == 36);
TautomerEnumerator te(new TautomerCatalog(tautparams.get()));
{
// atom stereo
auto mol = "COC(=O)[C@@H](N)CO"_smiles;
TEST_ASSERT(mol);
auto res = te.enumerate(*mol);
for (const auto &taut : res) {
auto smi = MolToSmiles(*taut);
// std::cerr << smi << std::endl;
TEST_ASSERT(smi.find("@H") == std::string::npos);
}
}
{
// atom stereo, atoms not in the tautomer zone are still ok
auto mol = "C[C@](Cl)(F)COC(=O)[C@@H](N)CO"_smiles;
TEST_ASSERT(mol);
auto res = te.enumerate(*mol);
for (const auto &taut : res) {
auto smi = MolToSmiles(*taut);
// std::cerr << smi << std::endl;
TEST_ASSERT(smi.find("@H") == std::string::npos);
TEST_ASSERT(smi.find("@]") != std::string::npos);
}
}
{
// bond stereo
auto mol = "C/C=C/C/N=c1/[nH]cccc1"_smiles;
TEST_ASSERT(mol);
TEST_ASSERT(mol->getBondBetweenAtoms(0, 1)->getBondDir() !=
Bond::BondDir::NONE);
TEST_ASSERT(mol->getBondBetweenAtoms(2, 3)->getBondDir() !=
Bond::BondDir::NONE);
TEST_ASSERT(mol->getBondBetweenAtoms(3, 4)->getBondDir() !=
Bond::BondDir::NONE);
TEST_ASSERT(mol->getBondBetweenAtoms(5, 6)->getBondDir() !=
Bond::BondDir::NONE);
TEST_ASSERT(mol->getBondBetweenAtoms(1, 2)->getStereo() >
Bond::BondStereo::STEREOANY);
TEST_ASSERT(mol->getBondBetweenAtoms(4, 5)->getStereo() >
Bond::BondStereo::STEREOANY);
auto res = te.enumerate(*mol);
for (const auto &taut : res) {
TEST_ASSERT(taut->getBondBetweenAtoms(0, 1)->getBondDir() !=
Bond::BondDir::NONE);
TEST_ASSERT(taut->getBondBetweenAtoms(2, 3)->getBondDir() !=
Bond::BondDir::NONE);
TEST_ASSERT(taut->getBondBetweenAtoms(3, 4)->getBondDir() ==
Bond::BondDir::NONE);
TEST_ASSERT(taut->getBondBetweenAtoms(5, 6)->getBondDir() ==
Bond::BondDir::NONE);
TEST_ASSERT(taut->getBondBetweenAtoms(1, 2)->getStereo() >
Bond::BondStereo::STEREOANY);
TEST_ASSERT(taut->getBondBetweenAtoms(4, 5)->getStereo() ==
Bond::BondStereo::STEREONONE);
}
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testPickCanonicalCIPChangeOnChiralCenter() {
BOOST_LOG(rdInfoLog)
<< "-----------------------\n testPickCanonicalCIPChangeOnChiralCenter"
<< std::endl;
struct CanonicalTaut {
static ROMOL_SPTR get(const TautomerEnumeratorResult &res) {
std::vector<int> scores;
scores.reserve(res.size());
std::transform(res.begin(), res.end(), std::back_inserter(scores),
[](const ROMOL_SPTR &m) {
return TautomerScoringFunctions::scoreTautomer(*m);
});
std::vector<size_t> indices(res.size());
std::iota(indices.begin(), indices.end(), 0);
int bestIdx =
*std::max_element(indices.begin(), indices.end(),
[scores](const size_t &a, const size_t &b) {
if (scores.at(a) != scores.at(b)) {
return (scores.at(a) < scores.at(b));
}
return (a < b);
});
TEST_ASSERT(*std::max_element(scores.begin(), scores.end()) ==
scores.at(bestIdx));
return res.at(bestIdx);
}
};
auto mol = "CC\\C=C(/O)[C@@H](C)C(C)=O"_smiles;
TEST_ASSERT(mol.get());
TEST_ASSERT(mol->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CW);
TEST_ASSERT(mol->getAtomWithIdx(5)->getProp<std::string>(
common_properties::_CIPCode) == "R");
{
// here the chirality disappears as the chiral center is itself involved in
// tautomerism
TautomerEnumerator te;
ROMOL_SPTR canTaut(te.canonicalize(*mol));
TEST_ASSERT(canTaut.get());
TEST_ASSERT(canTaut->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_UNSPECIFIED);
TEST_ASSERT(
!canTaut->getAtomWithIdx(5)->hasProp(common_properties::_CIPCode));
TEST_ASSERT(MolToSmiles(*canTaut) == "CCCC(=O)C(C)C(C)=O");
}
{
// here the chirality stays even if the chiral center is itself involved in
// tautomerism because of the tautomerRemoveSp3Stereo parameter being set to
// false
CleanupParameters params;
params.tautomerRemoveSp3Stereo = false;
TautomerEnumerator te(params);
ROMOL_SPTR canTaut(te.canonicalize(*mol));
TEST_ASSERT(canTaut.get());
TEST_ASSERT(canTaut->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CW);
TEST_ASSERT(canTaut->getAtomWithIdx(5)->getProp<std::string>(
common_properties::_CIPCode) == "S");
TEST_ASSERT(MolToSmiles(*canTaut) == "CCCC(=O)[C@@H](C)C(C)=O");
}
{
// here the chirality disappears as the chiral center is itself involved in
// tautomerism; the reassignStereo setting has no influence
TautomerEnumerator te;
auto res = te.enumerate(*mol);
TEST_ASSERT(res.status() == TautomerEnumeratorStatus::Completed);
TEST_ASSERT(res.size() == 8);
ROMOL_SPTR bestTaut = CanonicalTaut::get(res);
TEST_ASSERT(bestTaut.get());
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_UNSPECIFIED);
TEST_ASSERT(
!bestTaut->getAtomWithIdx(5)->hasProp(common_properties::_CIPCode));
TEST_ASSERT(MolToSmiles(*bestTaut) == "CCCC(=O)C(C)C(C)=O");
}
{
// here the chirality disappears as the chiral center is itself involved in
// tautomerism; the reassignStereo setting has no influence
CleanupParameters params;
params.tautomerReassignStereo = false;
TautomerEnumerator te(params);
auto res = te.enumerate(*mol);
TEST_ASSERT(res.status() == TautomerEnumeratorStatus::Completed);
TEST_ASSERT(res.size() == 8);
ROMOL_SPTR bestTaut = CanonicalTaut::get(res);
TEST_ASSERT(bestTaut.get());
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_UNSPECIFIED);
TEST_ASSERT(
!bestTaut->getAtomWithIdx(5)->hasProp(common_properties::_CIPCode));
TEST_ASSERT(MolToSmiles(*bestTaut) == "CCCC(=O)C(C)C(C)=O");
}
{
// here the chirality stays even if the chiral center is itself involved in
// tautomerism because of the tautomerRemoveSp3Stereo parameter being set to
// false. As reassignStereo by default is true, the CIP code has been
// recomputed and therefore it is now S (correct)
CleanupParameters params;
params.tautomerRemoveSp3Stereo = false;
TautomerEnumerator te(params);
auto res = te.enumerate(*mol);
TEST_ASSERT(res.status() == TautomerEnumeratorStatus::Completed);
TEST_ASSERT(res.size() == 8);
ROMOL_SPTR bestTaut = CanonicalTaut::get(res);
TEST_ASSERT(bestTaut.get());
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CW);
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getProp<std::string>(
common_properties::_CIPCode) == "S");
TEST_ASSERT(MolToSmiles(*bestTaut) == "CCCC(=O)[C@@H](C)C(C)=O");
}
{
// here the chirality stays even if the chiral center is itself involved in
// tautomerism because of the tautomerRemoveSp3Stereo parameter being set to
// false. As reassignStereo is false, the CIP code has not been recomputed
// and therefore it is still R (incorrect)
CleanupParameters params;
params.tautomerRemoveSp3Stereo = false;
params.tautomerReassignStereo = false;
TautomerEnumerator te(params);
auto res = te.enumerate(*mol);
TEST_ASSERT(res.status() == TautomerEnumeratorStatus::Completed);
TEST_ASSERT(res.size() == 8);
ROMOL_SPTR bestTaut = CanonicalTaut::get(res);
TEST_ASSERT(bestTaut.get());
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CW);
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getProp<std::string>(
common_properties::_CIPCode) == "R");
TEST_ASSERT(MolToSmiles(*bestTaut) == "CCCC(=O)[C@@H](C)C(C)=O");
}
mol = "CC\\C=C(/O)[C@@](CC)(C)C(C)=O"_smiles;
TEST_ASSERT(mol.get());
TEST_ASSERT(mol->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CW);
TEST_ASSERT(mol->getAtomWithIdx(5)->getProp<std::string>(
common_properties::_CIPCode) == "S");
// here the chirality stays no matter how tautomerRemoveSp3Stereo
// is set as the chiral center is not involved in tautomerism
{
TautomerEnumerator te;
ROMOL_SPTR canTaut(te.canonicalize(*mol));
TEST_ASSERT(canTaut.get());
TEST_ASSERT(canTaut->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CW);
TEST_ASSERT(canTaut->getAtomWithIdx(5)->getProp<std::string>(
common_properties::_CIPCode) == "R");
TEST_ASSERT(MolToSmiles(*canTaut) == "CCCC(=O)[C@](C)(CC)C(C)=O");
}
{
CleanupParameters params;
params.tautomerRemoveSp3Stereo = false;
TautomerEnumerator te(params);
ROMOL_SPTR canTaut(te.canonicalize(*mol));
TEST_ASSERT(canTaut.get());
TEST_ASSERT(canTaut->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CW);
TEST_ASSERT(canTaut->getAtomWithIdx(5)->getProp<std::string>(
common_properties::_CIPCode) == "R");
TEST_ASSERT(MolToSmiles(*canTaut) == "CCCC(=O)[C@](C)(CC)C(C)=O");
}
{
// as reassignStereo by default is true, the CIP code has been recomputed
// and therefore it is now R (correct)
TautomerEnumerator te;
auto res = te.enumerate(*mol);
TEST_ASSERT(res.status() == TautomerEnumeratorStatus::Completed);
TEST_ASSERT(res.size() == 4);
ROMOL_SPTR bestTaut = CanonicalTaut::get(res);
TEST_ASSERT(bestTaut.get());
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CW);
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getProp<std::string>(
common_properties::_CIPCode) == "R");
TEST_ASSERT(MolToSmiles(*bestTaut) == "CCCC(=O)[C@](C)(CC)C(C)=O");
}
{
// as reassignStereo is false, the CIP code has not been recomputed
// and therefore it is still S (incorrect)
CleanupParameters params;
params.tautomerReassignStereo = false;
TautomerEnumerator te(params);
auto res = te.enumerate(*mol);
TEST_ASSERT(res.status() == TautomerEnumeratorStatus::Completed);
TEST_ASSERT(res.size() == 4);
ROMOL_SPTR bestTaut = CanonicalTaut::get(res);
TEST_ASSERT(bestTaut.get());
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CW);
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getProp<std::string>(
common_properties::_CIPCode) == "S");
TEST_ASSERT(MolToSmiles(*bestTaut) == "CCCC(=O)[C@](C)(CC)C(C)=O");
}
{
// as reassignStereo by default is true, the CIP code has been recomputed
// and therefore it is now R (correct)
CleanupParameters params;
params.tautomerRemoveSp3Stereo = false;
TautomerEnumerator te(params);
auto res = te.enumerate(*mol);
TEST_ASSERT(res.status() == TautomerEnumeratorStatus::Completed);
TEST_ASSERT(res.size() == 4);
ROMOL_SPTR bestTaut = CanonicalTaut::get(res);
TEST_ASSERT(bestTaut.get());
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CW);
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getProp<std::string>(
common_properties::_CIPCode) == "R");
TEST_ASSERT(MolToSmiles(*bestTaut) == "CCCC(=O)[C@](C)(CC)C(C)=O");
}
{
// here the chirality stays even if the tautomerRemoveSp3Stereo parameter
// is set to false as the chiral center is not involved in tautomerism.
// As reassignStereo is false, the CIP code has not been recomputed
// and therefore it is still S (incorrect)
CleanupParameters params;
params.tautomerRemoveSp3Stereo = false;
params.tautomerReassignStereo = false;
TautomerEnumerator te(params);
auto res = te.enumerate(*mol);
TEST_ASSERT(res.status() == TautomerEnumeratorStatus::Completed);
TEST_ASSERT(res.size() == 4);
ROMOL_SPTR bestTaut = CanonicalTaut::get(res);
TEST_ASSERT(bestTaut.get());
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getChiralTag() ==
Atom::CHI_TETRAHEDRAL_CW);
TEST_ASSERT(bestTaut->getAtomWithIdx(5)->getProp<std::string>(
common_properties::_CIPCode) == "S");
TEST_ASSERT(MolToSmiles(*bestTaut) == "CCCC(=O)[C@](C)(CC)C(C)=O");
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testTautomerEnumeratorResult_const_iterator() {
BOOST_LOG(rdInfoLog)
<< "-----------------------\n testTautomerEnumeratorResult_const_iterator"
<< std::endl;
// CHEMBL3480964
RWMOL_SPTR mol = "Cc1nnc(NC(=O)N2CCN(Cc3ccc(F)cc3)C(=O)C2)s1"_smiles;
TautomerEnumerator te;
auto res = te.enumerate(*mol);
TEST_ASSERT(res.status() == TautomerEnumeratorStatus::Completed);
TEST_ASSERT(res.size() == 12);
auto it = res.begin();
auto it2 = res.begin();
// Test semantic requirements of bidirectional_iterator
// https://en.cppreference.com/w/cpp/iterator/bidirectional_iterator
TEST_ASSERT(it == it2);
TEST_ASSERT(it++ == it2);
TEST_ASSERT(it == ++it2);
TEST_ASSERT(it == it2);
TEST_ASSERT(it-- == it2);
TEST_ASSERT(it == --it2);
TEST_ASSERT(it == it2);
++it;
++it2;
TEST_ASSERT(++(--it) == it2);
TEST_ASSERT(--(++it) == it2);
TEST_ASSERT(std::addressof(--it) == std::addressof(it));
++it;
TEST_ASSERT(it == it2);
it--;
--it2;
TEST_ASSERT(it == it2);
TEST_ASSERT(*it == res[0]);
TEST_ASSERT(*it++ == res.at(0));
TEST_ASSERT(*it == res[1]);
TEST_ASSERT(*++it == res.at(2));
TEST_ASSERT(*it == res[2]);
++it;
TEST_ASSERT(*it == res[3]);
++it;
TEST_ASSERT(*it == res[4]);
it++;
TEST_ASSERT(*it == res[5]);
TEST_ASSERT(*it-- == res.at(5));
TEST_ASSERT(*it == res[4]);
TEST_ASSERT(*--it == res.at(3));
TEST_ASSERT(*it == res[3]);
--it;
TEST_ASSERT(*it == res[2]);
--it;
TEST_ASSERT(*it == res[1]);
it--;
TEST_ASSERT(*it == res[0]);
std::ptrdiff_t i = 0;
for (auto t : res) {
TEST_ASSERT(t == res[i++]);
}
i = 0;
for (auto it = res.begin(); it != res.end(); ++it) {
TEST_ASSERT(std::distance(res.begin(), it) == i);
TEST_ASSERT(*it == res[i]);
TEST_ASSERT(it->getNumAtoms() == res[i++]->getNumAtoms());
}
i = res.size();
for (auto it = res.end(); it != res.begin();) {
TEST_ASSERT(std::distance(res.begin(), it) == i);
TEST_ASSERT(*--it == res[--i]);
TEST_ASSERT(it->getNumAtoms() == res[i]->getNumAtoms());
}
i = 0;
for (const auto &pair : res.smilesTautomerMap()) {
TEST_ASSERT(pair.first == MolToSmiles(*res[i]));
TEST_ASSERT(pair.second.tautomer == res[i++]);
}
i = 0;
for (auto it = res.smilesTautomerMap().begin();
it != res.smilesTautomerMap().end(); ++it) {
TEST_ASSERT(std::distance(res.smilesTautomerMap().begin(), it) == i);
TEST_ASSERT(it->first == MolToSmiles(*res[i]));
TEST_ASSERT(it->second.tautomer == res[i++]);
}
i = res.smilesTautomerMap().size();
for (auto it = res.smilesTautomerMap().end();
it != res.smilesTautomerMap().begin();) {
TEST_ASSERT(std::distance(res.smilesTautomerMap().begin(), it) == i);
TEST_ASSERT((--it)->first == MolToSmiles(*res[--i]));
TEST_ASSERT(it->second.tautomer == res[i]);
}
}
void testGithub3430() {
BOOST_LOG(rdInfoLog) << "-----------------------\n testGithub3430"
<< std::endl;
// The "guanidine terminal=N" rule should not apply to aromatic C
// as this balances the "aromatic C = exocyclic N" rule with no net
// effect on the score
std::vector<ROMOL_SPTR> mols{"Cc1ccc(NC(=O)N=c2[nH]c(C)cn2C)nc1"_smiles,
"CCCCC(=O)N=c1nc(C)c2ncn(C)c2[nH]1"_smiles,
"c12ccccc1[nH]c(=N)[nH]2"_smiles};
for (auto mol : mols) {
TEST_ASSERT(mol);
TautomerEnumerator te;
auto res = te.enumerate(*mol);
std::vector<int> scores;
scores.reserve(res.size());
std::transform(res.begin(), res.end(), std::back_inserter(scores),
[](const ROMOL_SPTR &m) {
return TautomerScoringFunctions::scoreTautomer(*m);
});
std::sort(scores.begin(), scores.end(), std::greater<int>());
TEST_ASSERT(scores[1] < scores[0]);
}
}
int main() {
RDLog::InitLogs();
#if 1
testEnumerator();
testEnumeratorParams();
testEnumeratorCallback();
testCanonicalize();
testPickCanonical();
testCustomScoreFunc();
testEnumerationProblems();
#endif
testPickCanonical2();
testEnumerateDetails();
testGithub2990();
testPickCanonicalCIPChangeOnChiralCenter();
testTautomerEnumeratorResult_const_iterator();
testGithub3430();
return 0;
}
| 1 | 22,417 | I don't understand the reason for the changes from unique_ptr to ROMOL_SPTR that you made in this file. The pointers aren't being shared or used elsewhere so I don't think there's any reason to make them shared. Did I miss something? | rdkit-rdkit | cpp |
@@ -51,7 +51,7 @@ import static org.apache.lucene.util.IOUtils.closeWhileHandlingException;
public class ContainerPluginsApi {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- public static final String PLUGIN = "plugin";
+ public static final String PLUGINS = "plugin";
private final Supplier<SolrZkClient> zkClientSupplier;
private final CoreContainer coreContainer;
public final Read readAPI = new Read(); | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.handler.admin;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.solr.api.AnnotatedApi;
import org.apache.solr.api.Command;
import org.apache.solr.api.CustomContainerPlugins;
import org.apache.solr.api.EndPoint;
import org.apache.solr.api.PayloadObj;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.request.beans.PluginMeta;
import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.util.Utils;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.security.PermissionNameProvider;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.lucene.util.IOUtils.closeWhileHandlingException;
public class ContainerPluginsApi {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
public static final String PLUGIN = "plugin";
private final Supplier<SolrZkClient> zkClientSupplier;
private final CoreContainer coreContainer;
public final Read readAPI = new Read();
public final Edit editAPI = new Edit();
public ContainerPluginsApi(CoreContainer coreContainer) {
this.zkClientSupplier = coreContainer.zkClientSupplier;
this.coreContainer = coreContainer;
}
public class Read {
@EndPoint(method = METHOD.GET,
path = "/cluster/plugin",
permission = PermissionNameProvider.Name.COLL_READ_PERM)
public void list(SolrQueryRequest req, SolrQueryResponse rsp) throws IOException {
rsp.add(PLUGIN, plugins(zkClientSupplier));
}
}
@EndPoint(method = METHOD.POST,
path = "/cluster/plugin",
permission = PermissionNameProvider.Name.COLL_EDIT_PERM)
public class Edit {
@Command(name = "add")
public void add(PayloadObj<PluginMeta> payload) throws IOException {
PluginMeta info = payload.get();
validateConfig(payload, info);
if(payload.hasError()) return;
persistPlugins(map -> {
if (map.containsKey(info.name)) {
payload.addError(info.name + " already exists");
return null;
}
map.put(info.name, info);
return map;
});
}
@Command(name = "remove")
public void remove(PayloadObj<String> payload) throws IOException {
persistPlugins(map -> {
if (map.remove(payload.get()) == null) {
payload.addError("No such plugin: " + payload.get());
return null;
}
return map;
});
}
@Command(name = "update")
@SuppressWarnings("unchecked")
public void update(PayloadObj<PluginMeta> payload) throws IOException {
PluginMeta info = payload.get();
validateConfig(payload, info);
if(payload.hasError()) return;
persistPlugins(map -> {
Map<String, Object> existing = (Map<String, Object>) map.get(info.name);
if (existing == null) {
payload.addError("No such plugin: " + info.name);
return null;
} else {
map.put(info.name, info);
return map;
}
});
}
}
private void validateConfig(PayloadObj<PluginMeta> payload, PluginMeta info) {
if (info.klass.indexOf(':') > 0) {
if (info.version == null) {
payload.addError("Using package. must provide a packageVersion");
return;
}
}
List<String> errs = new ArrayList<>();
CustomContainerPlugins.ApiInfo apiInfo = coreContainer.getCustomContainerPlugins().createInfo(info, errs);
if (!errs.isEmpty()) {
for (String err : errs) payload.addError(err);
return;
}
AnnotatedApi api = null ;
try {
apiInfo.init();
} catch (Exception e) {
log.error("Error instantiating plugin ", e);
errs.add(e.getMessage());
return;
} finally {
closeWhileHandlingException(api);
}
}
@SuppressWarnings("unchecked")
public static Map<String, Object> plugins(Supplier<SolrZkClient> zkClientSupplier) throws IOException {
SolrZkClient zkClient = zkClientSupplier.get();
try {
Map<String, Object> clusterPropsJson = (Map<String, Object>) Utils.fromJSON(zkClient.getData(ZkStateReader.CLUSTER_PROPS, null, new Stat(), true));
return (Map<String, Object>) clusterPropsJson.computeIfAbsent(PLUGIN, Utils.NEW_LINKED_HASHMAP_FUN);
} catch (KeeperException.NoNodeException e) {
return new LinkedHashMap<>();
} catch (KeeperException | InterruptedException e) {
throw new IOException("Error reading cluster property", SolrZkClient.checkInterrupted(e));
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
private void persistPlugins(Function<Map<String,Object>, Map<String,Object>> modifier) throws IOException {
try {
zkClientSupplier.get().atomicUpdate(ZkStateReader.CLUSTER_PROPS, bytes -> {
Map rawJson = bytes == null ? new LinkedHashMap() :
(Map) Utils.fromJSON(bytes);
Map pluginsModified = modifier.apply((Map) rawJson.computeIfAbsent(PLUGIN, Utils.NEW_LINKED_HASHMAP_FUN));
if (pluginsModified == null) return null;
rawJson.put(PLUGIN, pluginsModified);
return Utils.toJSON(rawJson);
});
} catch (KeeperException | InterruptedException e) {
throw new IOException("Error reading cluster property", SolrZkClient.checkInterrupted(e));
}
}
}
| 1 | 37,614 | why change the variable name at all? | apache-lucene-solr | java |
@@ -123,6 +123,9 @@ axe.utils.getFlattenedTree = function (node, shadowId) {
axe.utils.getNodeFromTree = function (vNode, node) {
var found;
+ if (vNode.actualNode === node) {
+ return vNode;
+ }
vNode.children.forEach((candidate) => {
var retVal;
| 1 | var axe = axe || { utils: {} };
/**
* This implemnts the flatten-tree algorithm specified:
* Originally here https://drafts.csswg.org/css-scoping/#flat-tree
* Hopefully soon published here: https://www.w3.org/TR/css-scoping-1/#flat-tree
*
* Some notable information:
******* NOTE: as of Chrome 59, this is broken in Chrome so that tests fail completely
******* removed functionality for now
* 1. <slot> elements do not have boxes by default (i.e. they do not get rendered and
* their CSS properties are ignored)
* 2. <slot> elements can be made to have a box by overriding the display property
* which is 'contents' by default
* 3. Even boxed <slot> elements do not show up in the accessibility tree until
* they have a tabindex applied to them OR they have a role applied to them AND
* they have a box (this is observed behavior in Safari on OS X, I cannot find
* the spec for this)
*/
/**
* Wrap the real node and provide list of the flattened children
*
* @param node {Node} - the node in question
* @param shadowId {String} - the ID of the shadow DOM to which this node belongs
* @return {Object} - the wrapped node
*/
function virtualDOMfromNode (node, shadowId) {
return {
shadowId: shadowId,
children: [],
actualNode: node
};
}
/**
* find all the fallback content for a <slot> and return these as an array
* this array will also include any #text nodes
*
* @param node {Node} - the slot Node
* @return Array{Nodes}
*/
function getSlotChildren(node) {
var retVal = [];
node = node.firstChild;
while (node) {
retVal.push(node);
node = node.nextSibling;
}
return retVal;
}
/**
* recursvely returns an array of the virtual DOM nodes at this level
* excluding comment nodes and of course the shadow DOM nodes
* <content> and <slot>
*
* @param {Node} node the current node
* @param {String} shadowId, optional ID of the shadow DOM that is the closest shadow
* ancestor of the node
*/
axe.utils.getFlattenedTree = function (node, shadowId) {
// using a closure here and therefore cannot easily refactor toreduce the statements
//jshint maxstatements: false
var retVal, realArray, nodeName;
function reduceShadowDOM (res, child) {
var replacements = axe.utils.getFlattenedTree(child, shadowId);
if (replacements) {
res = res.concat(replacements);
}
return res;
}
if (node.documentElement) { // document
node = node.documentElement;
}
nodeName = node.nodeName.toLowerCase();
// for some reason Chrome's marquee element has an open shadow DOM
if (node.shadowRoot && nodeName !== 'marquee') {
// generate an ID for this shadow root and overwrite the current
// closure shadowId with this value so that it cascades down the tree
retVal = virtualDOMfromNode(node, shadowId);
shadowId = 'a' + Math.random().toString().substring(2);
realArray = Array.from(node.shadowRoot.childNodes);
retVal.children = realArray.reduce(reduceShadowDOM, []);
return [retVal];
} else {
if (nodeName === 'content') {
realArray = Array.from(node.getDistributedNodes());
return realArray.reduce(reduceShadowDOM, []);
} else if (nodeName === 'slot') {
realArray = Array.from(node.assignedNodes());
if (!realArray.length) {
// fallback content
realArray = getSlotChildren(node);
}
var styl = window.getComputedStyle(node);
// check the display property
if (false && styl.display !== 'contents') { // intentionally commented out
// has a box
retVal = virtualDOMfromNode(node, shadowId);
retVal.children = realArray.reduce(reduceShadowDOM, []);
return [retVal];
} else {
return realArray.reduce(reduceShadowDOM, []);
}
} else {
if (node.nodeType === 1) {
retVal = virtualDOMfromNode(node, shadowId);
realArray = Array.from(node.childNodes);
retVal.children = realArray.reduce(reduceShadowDOM, []);
return [retVal];
} else if (node.nodeType === 3) {
// text
return [virtualDOMfromNode(node)];
}
return undefined;
}
}
};
axe.utils.getNodeFromTree = function (vNode, node) {
var found;
vNode.children.forEach((candidate) => {
var retVal;
if (candidate.actualNode === node) {
found = candidate;
} else {
retVal = axe.utils.getNodeFromTree(candidate, node);
if (retVal) {
found = retVal;
}
}
});
return found;
};
| 1 | 11,408 | Since I'm still trying to keep these straight in my head, can you elaborate on what problem this solves? | dequelabs-axe-core | js |
@@ -269,6 +269,14 @@ public class MessageViewFragment extends Fragment implements ConfirmationDialogF
return mMessageView.getMessageHeaderView().additionalHeadersVisible();
}
+ public boolean isAccountReportSpamEnabled() {
+ try {
+ return (mAccount != null && !mAccount.getReportSpamRecipient().isEmpty());
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
private void delete() {
if (mMessage != null) {
// Disable the delete button after it's tapped (to try to prevent | 1 | package com.fsck.k9.ui.messageview;
import java.util.Collections;
import java.util.Locale;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.DownloadManager;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.ChooseFolder;
import com.fsck.k9.activity.MessageLoaderHelper;
import com.fsck.k9.activity.MessageLoaderHelper.MessageLoaderCallbacks;
import com.fsck.k9.activity.MessageReference;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.fragment.ConfirmationDialogFragment;
import com.fsck.k9.fragment.ConfirmationDialogFragment.ConfirmationDialogFragmentListener;
import com.fsck.k9.fragment.ProgressDialogFragment;
import com.fsck.k9.helper.FileBrowserHelper;
import com.fsck.k9.helper.FileBrowserHelper.FileBrowserFailOverCallback;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mailstore.AttachmentViewInfo;
import com.fsck.k9.mailstore.LocalMessage;
import com.fsck.k9.mailstore.MessageViewInfo;
import com.fsck.k9.ui.messageview.CryptoInfoDialog.OnClickShowCryptoKeyListener;
import com.fsck.k9.ui.messageview.MessageCryptoPresenter.MessageCryptoMvpView;
import com.fsck.k9.view.MessageCryptoDisplayStatus;
import com.fsck.k9.view.MessageHeader;
public class MessageViewFragment extends Fragment implements ConfirmationDialogFragmentListener,
AttachmentViewCallback, OnClickShowCryptoKeyListener {
private static final String ARG_REFERENCE = "reference";
private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1;
private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2;
private static final int ACTIVITY_CHOOSE_DIRECTORY = 3;
public static final int REQUEST_MASK_LOADER_HELPER = (1 << 8);
public static final int REQUEST_MASK_CRYPTO_PRESENTER = (1 << 9);
public static MessageViewFragment newInstance(MessageReference reference) {
MessageViewFragment fragment = new MessageViewFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_REFERENCE, reference);
fragment.setArguments(args);
return fragment;
}
private MessageTopView mMessageView;
private Account mAccount;
private MessageReference mMessageReference;
private LocalMessage mMessage;
private MessagingController mController;
private DownloadManager downloadManager;
private Handler handler = new Handler();
private MessageLoaderHelper messageLoaderHelper;
private MessageCryptoPresenter messageCryptoPresenter;
/**
* Used to temporarily store the destination folder for refile operations if a confirmation
* dialog is shown.
*/
private String mDstFolder;
private MessageViewFragmentListener mFragmentListener;
/**
* {@code true} after {@link #onCreate(Bundle)} has been executed. This is used by
* {@code MessageList.configureMenu()} to make sure the fragment has been initialized before
* it is used.
*/
private boolean mInitialized = false;
private Context mContext;
private AttachmentViewInfo currentAttachmentViewInfo;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity.getApplicationContext();
try {
mFragmentListener = (MessageViewFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.getClass() +
" must implement MessageViewFragmentListener");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This fragments adds options to the action bar
setHasOptionsMenu(true);
Context context = getActivity().getApplicationContext();
mController = MessagingController.getInstance(context);
downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
messageCryptoPresenter = new MessageCryptoPresenter(savedInstanceState, messageCryptoMvpView);
messageLoaderHelper =
new MessageLoaderHelper(context, getLoaderManager(), getFragmentManager(), messageLoaderCallbacks);
mInitialized = true;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
messageCryptoPresenter.onSaveInstanceState(outState);
}
@Override
public void onDestroy() {
super.onDestroy();
Activity activity = getActivity();
boolean isChangingConfigurations = activity != null && activity.isChangingConfigurations();
if (isChangingConfigurations) {
messageLoaderHelper.onDestroyChangingConfigurations();
return;
}
messageLoaderHelper.onDestroy();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = new ContextThemeWrapper(inflater.getContext(),
K9.getK9ThemeResourceId(K9.getK9MessageViewTheme()));
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.message, container, false);
mMessageView = (MessageTopView) view.findViewById(R.id.message_view);
mMessageView.setAttachmentCallback(this);
mMessageView.setMessageCryptoPresenter(messageCryptoPresenter);
mMessageView.setOnToggleFlagClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onToggleFlagged();
}
});
mMessageView.setOnDownloadButtonClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mMessageView.disableDownloadButton();
messageLoaderHelper.downloadCompleteMessage();
}
});
mFragmentListener.messageHeaderViewAvailable(mMessageView.getMessageHeaderView());
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle arguments = getArguments();
MessageReference messageReference = arguments.getParcelable(ARG_REFERENCE);
displayMessage(messageReference);
}
private void displayMessage(MessageReference messageReference) {
mMessageReference = messageReference;
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "MessageView displaying message " + mMessageReference);
}
mAccount = Preferences.getPreferences(getApplicationContext()).getAccount(mMessageReference.getAccountUuid());
messageLoaderHelper.asyncStartOrResumeLoadingMessage(messageReference, null);
mFragmentListener.updateMenu();
}
private void hideKeyboard() {
Activity activity = getActivity();
if (activity == null) {
return;
}
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
View decorView = activity.getWindow().getDecorView();
if (decorView != null) {
imm.hideSoftInputFromWindow(decorView.getApplicationWindowToken(), 0);
}
}
private void showUnableToDecodeError() {
Context context = getActivity().getApplicationContext();
Toast.makeText(context, R.string.message_view_toast_unable_to_display_message, Toast.LENGTH_SHORT).show();
}
private void showMessage(MessageViewInfo messageViewInfo) {
hideKeyboard();
boolean handledByCryptoPresenter = messageCryptoPresenter.maybeHandleShowMessage(
mMessageView, mAccount, messageViewInfo);
if (!handledByCryptoPresenter) {
mMessageView.showMessage(mAccount, messageViewInfo);
if (mAccount.isOpenPgpProviderConfigured()) {
mMessageView.getMessageHeaderView().setCryptoStatusDisabled();
} else {
mMessageView.getMessageHeaderView().hideCryptoStatus();
}
}
}
private void displayHeaderForLoadingMessage(LocalMessage message) {
mMessageView.setHeaders(message, mAccount);
if (mAccount.isOpenPgpProviderConfigured()) {
mMessageView.getMessageHeaderView().setCryptoStatusLoading();
}
displayMessageSubject(getSubjectForMessage(message));
mFragmentListener.updateMenu();
}
/**
* Called from UI thread when user select Delete
*/
public void onDelete() {
if (K9.confirmDelete() || (K9.confirmDeleteStarred() && mMessage.isSet(Flag.FLAGGED))) {
showDialog(R.id.dialog_confirm_delete);
} else {
delete();
}
}
public void onToggleAllHeadersView() {
mMessageView.getMessageHeaderView().onShowAdditionalHeaders();
}
public boolean allHeadersVisible() {
return mMessageView.getMessageHeaderView().additionalHeadersVisible();
}
private void delete() {
if (mMessage != null) {
// Disable the delete button after it's tapped (to try to prevent
// accidental clicks)
mFragmentListener.disableDeleteAction();
LocalMessage messageToDelete = mMessage;
mFragmentListener.showNextMessageOrReturn();
mController.deleteMessage(mMessageReference, null);
}
}
public void onRefile(String dstFolder) {
if (!mController.isMoveCapable(mAccount)) {
return;
}
if (!mController.isMoveCapable(mMessageReference)) {
Toast toast = Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
toast.show();
return;
}
if (K9.FOLDER_NONE.equalsIgnoreCase(dstFolder)) {
return;
}
if (mAccount.getSpamFolderName().equals(dstFolder) && K9.confirmSpam()) {
mDstFolder = dstFolder;
showDialog(R.id.dialog_confirm_spam);
} else {
refileMessage(dstFolder);
}
}
private void refileMessage(String dstFolder) {
String srcFolder = mMessageReference.getFolderName();
MessageReference messageToMove = mMessageReference;
mFragmentListener.showNextMessageOrReturn();
mController.moveMessage(mAccount, srcFolder, messageToMove, dstFolder);
}
public void onReply() {
if (mMessage != null) {
mFragmentListener.onReply(mMessage.makeMessageReference(), messageCryptoPresenter.getDecryptionResultForReply());
}
}
public void onReplyAll() {
if (mMessage != null) {
mFragmentListener.onReplyAll(mMessage.makeMessageReference(), messageCryptoPresenter.getDecryptionResultForReply());
}
}
public void onForward() {
if (mMessage != null) {
mFragmentListener.onForward(mMessage.makeMessageReference(), messageCryptoPresenter.getDecryptionResultForReply());
}
}
public void onToggleFlagged() {
if (mMessage != null) {
boolean newState = !mMessage.isSet(Flag.FLAGGED);
mController.setFlag(mAccount, mMessage.getFolder().getName(),
Collections.singletonList(mMessage), Flag.FLAGGED, newState);
mMessageView.setHeaders(mMessage, mAccount);
}
}
public void onMove() {
if ((!mController.isMoveCapable(mAccount))
|| (mMessage == null)) {
return;
}
if (!mController.isMoveCapable(mMessageReference)) {
Toast toast = Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
toast.show();
return;
}
startRefileActivity(ACTIVITY_CHOOSE_FOLDER_MOVE);
}
public void onCopy() {
if ((!mController.isCopyCapable(mAccount))
|| (mMessage == null)) {
return;
}
if (!mController.isCopyCapable(mMessageReference)) {
Toast toast = Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
toast.show();
return;
}
startRefileActivity(ACTIVITY_CHOOSE_FOLDER_COPY);
}
public void onArchive() {
onRefile(mAccount.getArchiveFolderName());
}
public void onSpam() {
onRefile(mAccount.getSpamFolderName());
}
public void onSelectText() {
// FIXME
// mMessageView.beginSelectingText();
}
private void startRefileActivity(int activity) {
Intent intent = new Intent(getActivity(), ChooseFolder.class);
intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid());
intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, mMessageReference.getFolderName());
intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, mAccount.getLastSelectedFolderName());
intent.putExtra(ChooseFolder.EXTRA_MESSAGE, mMessageReference);
startActivityForResult(intent, activity);
}
public void onPendingIntentResult(int requestCode, int resultCode, Intent data) {
if ((requestCode & REQUEST_MASK_LOADER_HELPER) == REQUEST_MASK_LOADER_HELPER) {
requestCode ^= REQUEST_MASK_LOADER_HELPER;
messageLoaderHelper.onActivityResult(requestCode, resultCode, data);
return;
}
if ((requestCode & REQUEST_MASK_CRYPTO_PRESENTER) == REQUEST_MASK_CRYPTO_PRESENTER) {
requestCode ^= REQUEST_MASK_CRYPTO_PRESENTER;
messageCryptoPresenter.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
// Note: because fragments do not have a startIntentSenderForResult method, pending intent activities are
// launched through the MessageList activity, and delivered back via onPendingIntentResult()
switch (requestCode) {
case ACTIVITY_CHOOSE_DIRECTORY: {
if (data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
getAttachmentController(currentAttachmentViewInfo).saveAttachmentTo(filePath);
}
}
}
break;
}
case ACTIVITY_CHOOSE_FOLDER_MOVE:
case ACTIVITY_CHOOSE_FOLDER_COPY: {
if (data == null) {
return;
}
String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER);
MessageReference ref = data.getParcelableExtra(ChooseFolder.EXTRA_MESSAGE);
if (mMessageReference.equals(ref)) {
mAccount.setLastSelectedFolderName(destFolderName);
switch (requestCode) {
case ACTIVITY_CHOOSE_FOLDER_MOVE: {
mFragmentListener.showNextMessageOrReturn();
moveMessage(ref, destFolderName);
break;
}
case ACTIVITY_CHOOSE_FOLDER_COPY: {
copyMessage(ref, destFolderName);
break;
}
}
}
break;
}
}
}
public void onSendAlternate() {
if (mMessage != null) {
mController.sendAlternate(getActivity(), mAccount, mMessage);
}
}
public void onToggleRead() {
if (mMessage != null) {
mController.setFlag(mAccount, mMessage.getFolder().getName(),
Collections.singletonList(mMessage), Flag.SEEN, !mMessage.isSet(Flag.SEEN));
mMessageView.setHeaders(mMessage, mAccount);
String subject = mMessage.getSubject();
displayMessageSubject(subject);
mFragmentListener.updateMenu();
}
}
private void setProgress(boolean enable) {
if (mFragmentListener != null) {
mFragmentListener.setProgress(enable);
}
}
private void displayMessageSubject(String subject) {
if (mFragmentListener != null) {
mFragmentListener.displayMessageSubject(subject);
}
}
private String getSubjectForMessage(LocalMessage message) {
String subject = message.getSubject();
if (TextUtils.isEmpty(subject)) {
return mContext.getString(R.string.general_no_subject);
}
return subject;
}
public void moveMessage(MessageReference reference, String destFolderName) {
mController.moveMessage(mAccount, mMessageReference.getFolderName(), reference, destFolderName);
}
public void copyMessage(MessageReference reference, String destFolderName) {
mController.copyMessage(mAccount, mMessageReference.getFolderName(), reference, destFolderName);
}
private void showDialog(int dialogId) {
DialogFragment fragment;
switch (dialogId) {
case R.id.dialog_confirm_delete: {
String title = getString(R.string.dialog_confirm_delete_title);
String message = getString(R.string.dialog_confirm_delete_message);
String confirmText = getString(R.string.dialog_confirm_delete_confirm_button);
String cancelText = getString(R.string.dialog_confirm_delete_cancel_button);
fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message,
confirmText, cancelText);
break;
}
case R.id.dialog_confirm_spam: {
String title = getString(R.string.dialog_confirm_spam_title);
String message = getResources().getQuantityString(R.plurals.dialog_confirm_spam_message, 1);
String confirmText = getString(R.string.dialog_confirm_spam_confirm_button);
String cancelText = getString(R.string.dialog_confirm_spam_cancel_button);
fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message,
confirmText, cancelText);
break;
}
case R.id.dialog_attachment_progress: {
String message = getString(R.string.dialog_attachment_progress_title);
fragment = ProgressDialogFragment.newInstance(null, message);
break;
}
default: {
throw new RuntimeException("Called showDialog(int) with unknown dialog id.");
}
}
fragment.setTargetFragment(this, dialogId);
fragment.show(getFragmentManager(), getDialogTag(dialogId));
}
private void removeDialog(int dialogId) {
FragmentManager fm = getFragmentManager();
if (fm == null || isRemoving() || isDetached()) {
return;
}
// Make sure the "show dialog" transaction has been processed when we call
// findFragmentByTag() below. Otherwise the fragment won't be found and the dialog will
// never be dismissed.
fm.executePendingTransactions();
DialogFragment fragment = (DialogFragment) fm.findFragmentByTag(getDialogTag(dialogId));
if (fragment != null) {
fragment.dismiss();
}
}
private String getDialogTag(int dialogId) {
return String.format(Locale.US, "dialog-%d", dialogId);
}
public void zoom(KeyEvent event) {
// mMessageView.zoom(event);
}
@Override
public void doPositiveClick(int dialogId) {
switch (dialogId) {
case R.id.dialog_confirm_delete: {
delete();
break;
}
case R.id.dialog_confirm_spam: {
refileMessage(mDstFolder);
mDstFolder = null;
break;
}
}
}
@Override
public void doNegativeClick(int dialogId) {
/* do nothing */
}
@Override
public void dialogCancelled(int dialogId) {
/* do nothing */
}
/**
* Get the {@link MessageReference} of the currently displayed message.
*/
public MessageReference getMessageReference() {
return mMessageReference;
}
public boolean isMessageRead() {
return (mMessage != null) ? mMessage.isSet(Flag.SEEN) : false;
}
public boolean isCopyCapable() {
return mController.isCopyCapable(mAccount);
}
public boolean isMoveCapable() {
return mController.isMoveCapable(mAccount);
}
public boolean canMessageBeArchived() {
return (!mMessageReference.getFolderName().equals(mAccount.getArchiveFolderName())
&& mAccount.hasArchiveFolder());
}
public boolean canMessageBeMovedToSpam() {
return (!mMessageReference.getFolderName().equals(mAccount.getSpamFolderName())
&& mAccount.hasSpamFolder());
}
public void updateTitle() {
if (mMessage != null) {
displayMessageSubject(mMessage.getSubject());
}
}
public Context getApplicationContext() {
return mContext;
}
public void disableAttachmentButtons(AttachmentViewInfo attachment) {
// mMessageView.disableAttachmentButtons(attachment);
}
public void enableAttachmentButtons(AttachmentViewInfo attachment) {
// mMessageView.enableAttachmentButtons(attachment);
}
public void runOnMainThread(Runnable runnable) {
handler.post(runnable);
}
public void showAttachmentLoadingDialog() {
// mMessageView.disableAttachmentButtons();
showDialog(R.id.dialog_attachment_progress);
}
public void hideAttachmentLoadingDialogOnMainThread() {
handler.post(new Runnable() {
@Override
public void run() {
removeDialog(R.id.dialog_attachment_progress);
// mMessageView.enableAttachmentButtons();
}
});
}
public void refreshAttachmentThumbnail(AttachmentViewInfo attachment) {
// mMessageView.refreshAttachmentThumbnail(attachment);
}
private MessageCryptoMvpView messageCryptoMvpView = new MessageCryptoMvpView() {
@Override
public void redisplayMessage() {
messageLoaderHelper.asyncReloadMessage();
}
@Override
public void startPendingIntentForCryptoPresenter(IntentSender si, Integer requestCode, Intent fillIntent,
int flagsMask, int flagValues, int extraFlags) throws SendIntentException {
if (requestCode == null) {
getActivity().startIntentSender(si, fillIntent, flagsMask, flagValues, extraFlags);
return;
}
requestCode |= REQUEST_MASK_CRYPTO_PRESENTER;
getActivity().startIntentSenderForResult(
si, requestCode, fillIntent, flagsMask, flagValues, extraFlags);
}
@Override
public void showCryptoInfoDialog(MessageCryptoDisplayStatus displayStatus) {
CryptoInfoDialog dialog = CryptoInfoDialog.newInstance(displayStatus);
dialog.setTargetFragment(MessageViewFragment.this, 0);
dialog.show(getFragmentManager(), "crypto_info_dialog");
}
@Override
public void restartMessageCryptoProcessing() {
mMessageView.setToLoadingState();
messageLoaderHelper.asyncRestartMessageCryptoProcessing();
}
};
@Override
public void onClickShowCryptoKey() {
messageCryptoPresenter.onClickShowCryptoKey();
}
public interface MessageViewFragmentListener {
void onForward(MessageReference messageReference, Parcelable decryptionResultForReply);
void disableDeleteAction();
void onReplyAll(MessageReference messageReference, Parcelable decryptionResultForReply);
void onReply(MessageReference messageReference, Parcelable decryptionResultForReply);
void displayMessageSubject(String title);
void setProgress(boolean b);
void showNextMessageOrReturn();
void messageHeaderViewAvailable(MessageHeader messageHeaderView);
void updateMenu();
}
public boolean isInitialized() {
return mInitialized ;
}
private MessageLoaderCallbacks messageLoaderCallbacks = new MessageLoaderCallbacks() {
@Override
public void onMessageDataLoadFinished(LocalMessage message) {
mMessage = message;
displayHeaderForLoadingMessage(message);
mMessageView.setToLoadingState();
}
@Override
public void onMessageDataLoadFailed() {
Toast.makeText(getActivity(), R.string.status_loading_error, Toast.LENGTH_LONG).show();
}
@Override
public void onMessageViewInfoLoadFinished(MessageViewInfo messageViewInfo) {
showMessage(messageViewInfo);
}
@Override
public void onMessageViewInfoLoadFailed(MessageViewInfo messageViewInfo) {
showMessage(messageViewInfo);
}
@Override
public void setLoadingProgress(int current, int max) {
mMessageView.setLoadingProgress(current, max);
}
@Override
public void onDownloadErrorMessageNotFound() {
mMessageView.enableDownloadButton();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), R.string.status_invalid_id_error, Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onDownloadErrorNetworkError() {
mMessageView.enableDownloadButton();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), R.string.status_network_error, Toast.LENGTH_LONG).show();
}
});
}
@Override
public void startIntentSenderForMessageLoaderHelper(IntentSender si, int requestCode, Intent fillIntent,
int flagsMask, int flagValues, int extraFlags) {
try {
requestCode |= REQUEST_MASK_LOADER_HELPER;
getActivity().startIntentSenderForResult(
si, requestCode, fillIntent, flagsMask, flagValues, extraFlags);
} catch (SendIntentException e) {
Log.e(K9.LOG_TAG, "Irrecoverable error calling PendingIntent!", e);
}
}
};
@Override
public void onViewAttachment(AttachmentViewInfo attachment) {
//TODO: check if we have to download the attachment first
getAttachmentController(attachment).viewAttachment();
}
@Override
public void onSaveAttachment(AttachmentViewInfo attachment) {
//TODO: check if we have to download the attachment first
getAttachmentController(attachment).saveAttachment();
}
@Override
public void onSaveAttachmentToUserProvidedDirectory(final AttachmentViewInfo attachment) {
//TODO: check if we have to download the attachment first
currentAttachmentViewInfo = attachment;
FileBrowserHelper.getInstance().showFileBrowserActivity(MessageViewFragment.this, null,
ACTIVITY_CHOOSE_DIRECTORY, new FileBrowserFailOverCallback() {
@Override
public void onPathEntered(String path) {
getAttachmentController(attachment).saveAttachmentTo(path);
}
@Override
public void onCancel() {
// Do nothing
}
});
}
private AttachmentController getAttachmentController(AttachmentViewInfo attachment) {
return new AttachmentController(mController, downloadManager, this, attachment);
}
}
| 1 | 14,172 | Prefer TextUtils.isEmpty() which handles getReportSpamRecipient() being null | k9mail-k-9 | java |
@@ -87,7 +87,10 @@ module Selenium
return unless File.exist?(manifest_path)
manifest = JSON.parse(File.read(manifest_path))
- [manifest['name'].delete(' '), manifest['version']].join('@')
+ id = if manifest.key?('application') && manifest['application'].key?('gecko')
+ manifest['application']['gecko']['id']
+ end
+ id || [manifest['name'].delete(' '), manifest['version']].join('@')
end
end # Extension
end # Firefox | 1 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
module Selenium
module WebDriver
module Firefox
#
# @api private
#
class Extension
NAMESPACE = 'http://www.mozilla.org/2004/em-rdf#'.freeze
def initialize(path)
unless File.exist?(path)
raise Error::WebDriverError, "could not find extension at #{path.inspect}"
end
@path = path
@should_reap_root = false
end
def write_to(extensions_dir)
root_dir = create_root
ext_path = File.join extensions_dir, read_id(root_dir)
FileUtils.rm_rf ext_path
FileUtils.mkdir_p File.dirname(ext_path), mode: 0o700
FileUtils.cp_r root_dir, ext_path
FileReaper.reap(root_dir) if @should_reap_root
end
private
def create_root
if File.directory? @path
@path
else
unless Zipper::EXTENSIONS.include? File.extname(@path)
raise Error::WebDriverError, "expected #{Zipper::EXTENSIONS.join(' or ')}, got #{@path.inspect}"
end
@should_reap_root = true
Zipper.unzip(@path)
end
end
def read_id(directory)
read_id_from_install_rdf(directory) || read_id_from_manifest_json(directory)
end
def read_id_from_install_rdf(directory)
rdf_path = File.join(directory, 'install.rdf')
return unless File.exist?(rdf_path)
doc = REXML::Document.new(File.read(rdf_path))
namespace = doc.root.namespaces.key(NAMESPACE)
if namespace
id_node = REXML::XPath.first(doc, "//#{namespace}:id")
return id_node.text if id_node
attr_node = REXML::XPath.first(doc, "//@#{namespace}:id")
return attr_node.value if attr_node
end
raise Error::WebDriverError, "cannot locate extension id in #{rdf_path}"
end
def read_id_from_manifest_json(directory)
manifest_path = File.join(directory, 'manifest.json')
return unless File.exist?(manifest_path)
manifest = JSON.parse(File.read(manifest_path))
[manifest['name'].delete(' '), manifest['version']].join('@')
end
end # Extension
end # Firefox
end # WebDriver
end # Selenium
| 1 | 15,944 | Couldn't you just write this as an if/else or a guard clause like on line 87? Just seems a bit weird doing this conditional assignment for essentially an if/else. | SeleniumHQ-selenium | py |
@@ -202,7 +202,9 @@ namespace Microsoft.DotNet.Build.Tasks.Packaging
{
Id = d.ItemSpec,
Version = d.GetVersion(),
- TargetFramework = d.GetTargetFramework()
+ TargetFramework = d.GetTargetFramework(),
+ Include = d.GetValueList("Include"),
+ Exclude = d.GetValueList("Exclude")
};
return (from dependency in dependencies | 1 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using NuGet;
using NuGet.Frameworks;
using NuGet.Packaging.Core;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class GenerateNuSpec : Task
{
private const string NuSpecXmlNamespace = @"http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd";
public string InputFileName { get; set; }
[Required]
public string OutputFileName { get; set; }
public string MinClientVersion { get; set; }
[Required]
public string Id { get; set; }
[Required]
public string Version { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Authors { get; set; }
[Required]
public string Owners { get; set; }
[Required]
public string Description { get; set; }
public string ReleaseNotes { get; set; }
public string Summary { get; set; }
public string Language { get; set; }
public string ProjectUrl { get; set; }
public string IconUrl { get; set; }
public string LicenseUrl { get; set; }
public string Copyright { get; set; }
public bool RequireLicenseAcceptance { get; set; }
public bool DevelopmentDependency { get; set; }
public string Tags { get; set; }
public ITaskItem[] Dependencies { get; set; }
public ITaskItem[] References { get; set; }
public ITaskItem[] FrameworkReferences { get; set; }
public ITaskItem[] Files { get; set; }
public override bool Execute()
{
try
{
WriteNuSpecFile();
}
catch (Exception ex)
{
Log.LogError(ex.ToString());
Log.LogErrorFromException(ex);
}
return !Log.HasLoggedErrors;
}
private void WriteNuSpecFile()
{
var manifest = CreateManifest();
if (!IsDifferent(manifest))
{
Log.LogMessage("Skipping generation of .nuspec because contents are identical.");
return;
}
var directory = Path.GetDirectoryName(OutputFileName);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
using (var file = File.Create(OutputFileName))
{
manifest.Save(file, false);
}
}
private bool IsDifferent(Manifest newManifest)
{
if (!File.Exists(OutputFileName))
return true;
var oldSource = File.ReadAllText(OutputFileName);
var newSource = "";
using (var stream = new MemoryStream())
{
newManifest.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
newSource = Encoding.UTF8.GetString(stream.ToArray());
}
return oldSource != newSource;
}
private Manifest CreateManifest()
{
Manifest manifest;
ManifestMetadata manifestMetadata;
if (!string.IsNullOrEmpty(InputFileName))
{
using (var stream = File.OpenRead(InputFileName))
{
manifest = Manifest.ReadFrom(stream);
}
if (manifest.Metadata == null)
{
manifest = new Manifest(new ManifestMetadata(), manifest.Files);
}
}
else
{
manifest = new Manifest(new ManifestMetadata());
}
manifestMetadata = manifest.Metadata;
manifestMetadata.UpdateMember(x => x.Authors, Authors?.Split(';'));
manifestMetadata.UpdateMember(x => x.Copyright, Copyright);
manifestMetadata.UpdateMember(x => x.DependencySets, GetDependencySets());
manifestMetadata.UpdateMember(x => x.Description, Description);
manifestMetadata.DevelopmentDependency |= DevelopmentDependency;
manifestMetadata.UpdateMember(x => x.FrameworkAssemblies, GetFrameworkAssemblies());
manifestMetadata.UpdateMember(x => x.IconUrl, IconUrl != null ? new Uri(IconUrl) : null);
manifestMetadata.UpdateMember(x => x.Id, Id);
manifestMetadata.UpdateMember(x => x.Language, Language);
manifestMetadata.UpdateMember(x => x.LicenseUrl, new Uri(LicenseUrl));
manifestMetadata.UpdateMember(x => x.MinClientVersionString, MinClientVersion);
manifestMetadata.UpdateMember(x => x.Owners, Owners?.Split(';'));
manifestMetadata.UpdateMember(x => x.ProjectUrl, ProjectUrl != null ? new Uri(ProjectUrl) : null);
manifestMetadata.AddRangeToMember(x => x.PackageAssemblyReferences, GetReferenceSets());
manifestMetadata.UpdateMember(x => x.ReleaseNotes, ReleaseNotes);
manifestMetadata.RequireLicenseAcceptance |= RequireLicenseAcceptance;
manifestMetadata.UpdateMember(x => x.Summary, Summary);
manifestMetadata.UpdateMember(x => x.Tags, Tags);
manifestMetadata.UpdateMember(x => x.Title, Title);
manifestMetadata.UpdateMember(x => x.Version, Version != null ? new NuGetVersion(Version) : null);
manifest.AddRangeToMember(x => x.Files, GetManifestFiles());
return manifest;
}
private List<ManifestFile> GetManifestFiles()
{
return (from f in Files.NullAsEmpty()
select new ManifestFile(
f.GetMetadata(Metadata.FileSource),
f.GetMetadata(Metadata.FileTarget),
f.GetMetadata(Metadata.FileExclude)
)).OrderBy(f => f.Target, StringComparer.OrdinalIgnoreCase).ToList();
}
private List<FrameworkAssemblyReference> GetFrameworkAssemblies()
{
return (from fr in FrameworkReferences.NullAsEmpty()
orderby fr.ItemSpec, StringComparer.Ordinal
select new FrameworkAssemblyReference(fr.ItemSpec, new[] { fr.GetTargetFramework() })
).ToList();
}
private List<PackageDependencySet> GetDependencySets()
{
var dependencies = from d in Dependencies.NullAsEmpty()
select new Dependency
{
Id = d.ItemSpec,
Version = d.GetVersion(),
TargetFramework = d.GetTargetFramework()
};
return (from dependency in dependencies
group dependency by dependency.TargetFramework into dependenciesByFramework
select new PackageDependencySet(
dependenciesByFramework.Key,
from dependency in dependenciesByFramework
where dependency.Id != "_._"
orderby dependency.Id, StringComparer.Ordinal
group dependency by dependency.Id into dependenciesById
select new PackageDependency(
dependenciesById.Key,
VersionRange.Parse(
dependenciesById.Select(x => x.Version)
.Aggregate(AggregateVersions)
.ToStringSafe())
))).OrderBy(s => s?.TargetFramework?.GetShortFolderName(), StringComparer.Ordinal)
.ToList();
}
private ICollection<PackageReferenceSet> GetReferenceSets()
{
var references = from r in References.NullAsEmpty()
select new
{
File = r.ItemSpec,
TargetFramework = r.GetTargetFramework(),
};
return (from reference in references
group reference by reference.TargetFramework into referencesByFramework
select new PackageReferenceSet(
referencesByFramework.Key,
from reference in referencesByFramework
orderby reference.File, StringComparer.Ordinal
select reference.File
)
).ToList();
}
private static VersionRange AggregateVersions(VersionRange aggregate, VersionRange next)
{
var versionRange = new VersionRange();
SetMinVersion(ref versionRange, aggregate);
SetMinVersion(ref versionRange, next);
SetMaxVersion(ref versionRange, aggregate);
SetMaxVersion(ref versionRange, next);
if (versionRange.MinVersion == null && versionRange.MaxVersion == null)
{
versionRange = null;
}
return versionRange;
}
private static void SetMinVersion(ref VersionRange target, VersionRange source)
{
if (source == null || source.MinVersion == null)
{
return;
}
bool update = false;
NuGetVersion minVersion = target.MinVersion;
bool includeMinVersion = target.IsMinInclusive;
if (target.MinVersion == null)
{
update = true;
minVersion = source.MinVersion;
includeMinVersion = source.IsMinInclusive;
}
if (target.MinVersion < source.MinVersion)
{
update = true;
minVersion = source.MinVersion;
includeMinVersion = source.IsMinInclusive;
}
if (target.MinVersion == source.MinVersion)
{
update = true;
includeMinVersion = target.IsMinInclusive && source.IsMinInclusive;
}
if (update)
{
target = new VersionRange(minVersion, includeMinVersion, target.MaxVersion, target.IsMaxInclusive, target.IncludePrerelease, target.Float, target.OriginalString);
}
}
private static void SetMaxVersion(ref VersionRange target, VersionRange source)
{
if (source == null || source.MaxVersion == null)
{
return;
}
bool update = false;
NuGetVersion maxVersion = target.MaxVersion;
bool includeMaxVersion = target.IsMaxInclusive;
if (target.MaxVersion == null)
{
update = true;
maxVersion = source.MaxVersion;
includeMaxVersion = source.IsMaxInclusive;
}
if (target.MaxVersion > source.MaxVersion)
{
update = true;
maxVersion = source.MaxVersion;
includeMaxVersion = source.IsMaxInclusive;
}
if (target.MaxVersion == source.MaxVersion)
{
update = true;
includeMaxVersion = target.IsMaxInclusive && source.IsMaxInclusive;
}
if (update)
{
target = new VersionRange(target.MinVersion, target.IsMinInclusive, maxVersion, includeMaxVersion, target.IncludePrerelease, target.Float, target.OriginalString);
}
}
private class Dependency
{
public string Id { get; set; }
public NuGetFramework TargetFramework { get; set; }
public VersionRange Version { get; set; }
}
}
}
| 1 | 7,716 | Do we actually use Include anywhere yet or is this just for completion? | dotnet-buildtools | .cs |
@@ -321,6 +321,10 @@ def data(readonly=False):
SettingValue(typ.String(none_ok=True), 'en-US,en'),
"Value to send in the `accept-language` header."),
+ ('referer-header',
+ SettingValue(typ.Referer(), 'same-domain'),
+ "Send the Referer header"),
+
('user-agent',
SettingValue(typ.UserAgent(none_ok=True), ''),
"User agent to send. Empty to send the default."), | 1 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2015 Florian Bruhin (The Compiler) <[email protected]>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Configuration data for config.py.
Module attributes:
FIRST_COMMENT: The initial comment header to place in the config.
SECTION_DESC: A dictionary with descriptions for sections.
DATA: A global read-only copy of the default config, an OrderedDict of
sections.
"""
import sys
import re
import collections
from qutebrowser.config import configtypes as typ
from qutebrowser.config import sections as sect
from qutebrowser.config.value import SettingValue
from qutebrowser.utils.qtutils import MAXVALS
FIRST_COMMENT = r"""
# vim: ft=dosini
# Configfile for qutebrowser.
#
# This configfile is parsed by python's configparser in extended
# interpolation mode. The format is very INI-like, so there are
# categories like [general] with "key = value"-pairs.
#
# Note that you shouldn't add your own comments, as this file is
# regenerated every time the config is saved.
#
# Interpolation looks like ${value} or ${section:value} and will be
# replaced by the respective value.
#
# Some settings will expand environment variables. Note that, since
# interpolation is run first, you will need to escape the $ char as
# described below.
#
# This is the default config, so if you want to remove anything from
# here (as opposed to change/add), for example a key binding, set it to
# an empty value.
#
# You will need to escape the following values:
# - # at the start of the line (at the first position of the key) (\#)
# - $ in a value ($$)
"""
SECTION_DESC = {
'general': "General/miscellaneous options.",
'ui': "General options related to the user interface.",
'input': "Options related to input modes.",
'network': "Settings related to the network.",
'completion': "Options related to completion and command history.",
'tabs': "Configuration of the tab bar.",
'storage': "Settings related to cache and storage.",
'content': "Loaded plugins/scripts and allowed actions.",
'hints': "Hinting settings.",
'searchengines': (
"Definitions of search engines which can be used via the address "
"bar.\n"
"The searchengine named `DEFAULT` is used when "
"`general -> auto-search` is true and something else than a URL was "
"entered to be opened. Other search engines can be used by prepending "
"the search engine name to the search term, e.g. "
"`:open google qutebrowser`. The string `{}` will be replaced by the "
"search term, use `{{` and `}}` for literal `{`/`}` signs."),
'aliases': (
"Aliases for commands.\n"
"By default, no aliases are defined. Example which adds a new command "
"`:qtb` to open qutebrowsers website:\n\n"
"`qtb = open http://www.qutebrowser.org/`"),
'colors': (
"Colors used in the UI.\n"
"A value can be in one of the following format:\n\n"
" * `#RGB`/`#RRGGBB`/`#RRRGGGBBB`/`#RRRRGGGGBBBB`\n"
" * A SVG color name as specified in http://www.w3.org/TR/SVG/"
"types.html#ColorKeywords[the W3C specification].\n"
" * transparent (no color)\n"
" * `rgb(r, g, b)` / `rgba(r, g, b, a)` (values 0-255 or "
"percentages)\n"
" * `hsv(h, s, v)` / `hsva(h, s, v, a)` (values 0-255, hue 0-359)\n"
" * A gradient as explained in http://qt-project.org/doc/qt-4.8/"
"stylesheet-reference.html#list-of-property-types[the Qt "
"documentation] under ``Gradient''.\n\n"
"The `hints.*` values are a special case as they're real CSS "
"colors, not Qt-CSS colors. There, for a gradient, you need to use "
"`-webkit-gradient`, see https://www.webkit.org/blog/175/introducing-"
"css-gradients/[the WebKit documentation]."),
'fonts': (
"Fonts used for the UI, with optional style/weight/size.\n\n"
" * Style: `normal`/`italic`/`oblique`\n"
" * Weight: `normal`, `bold`, `100`..`900`\n"
" * Size: _number_ `px`/`pt`"),
}
DEFAULT_FONT_SIZE = '10pt' if sys.platform == 'darwin' else '8pt'
def data(readonly=False):
"""Get the default config data.
Return:
A {name: section} OrderedDict.
"""
return collections.OrderedDict([
('general', sect.KeyValue(
('ignore-case',
SettingValue(typ.IgnoreCase(), 'smart'),
"Whether to find text on a page case-insensitively."),
('wrap-search',
SettingValue(typ.Bool(), 'true'),
"Whether to wrap finding text to the top when arriving at the "
"end."),
('startpage',
SettingValue(typ.List(), 'https://www.duckduckgo.com'),
"The default page(s) to open at the start, separated by commas."),
('default-page',
SettingValue(typ.FuzzyUrl(), '${startpage}'),
"The page to open if :open -t/-b/-w is used without URL. Use "
"`about:blank` for a blank page."),
('auto-search',
SettingValue(typ.AutoSearch(), 'naive'),
"Whether to start a search when something else than a URL is "
"entered."),
('auto-save-config',
SettingValue(typ.Bool(), 'true'),
"Whether to save the config automatically on quit."),
('auto-save-interval',
SettingValue(typ.Int(minval=0), '15000'),
"How often (in milliseconds) to auto-save config/cookies/etc."),
('editor',
SettingValue(typ.ShellCommand(placeholder=True), 'gvim -f "{}"'),
"The editor (and arguments) to use for the `open-editor` "
"command.\n\n"
"Use `{}` for the filename. The value gets split like in a "
"shell, so you can use `\"` or `'` to quote arguments."),
('editor-encoding',
SettingValue(typ.Encoding(), 'utf-8'),
"Encoding to use for editor."),
('private-browsing',
SettingValue(typ.Bool(), 'false'),
"Do not record visited pages in the history or store web page "
"icons."),
('developer-extras',
SettingValue(typ.Bool(), 'false'),
"Enable extra tools for Web developers.\n\n"
"This needs to be enabled for `:inspector` to work and also adds "
"an _Inspect_ entry to the context menu."),
('print-element-backgrounds',
SettingValue(typ.Bool(), 'true'),
"Whether the background color and images are also drawn when the "
"page is printed."),
('xss-auditing',
SettingValue(typ.Bool(), 'false'),
"Whether load requests should be monitored for cross-site "
"scripting attempts.\n\n"
"Suspicious scripts will be blocked and reported in the "
"inspector's JavaScript console. Enabling this feature might "
"have an impact on performance."),
('site-specific-quirks',
SettingValue(typ.Bool(), 'true'),
"Enable workarounds for broken sites."),
('default-encoding',
SettingValue(typ.String(none_ok=True), ''),
"Default encoding to use for websites.\n\n"
"The encoding must be a string describing an encoding such as "
"_utf-8_, _iso-8859-1_, etc. If left empty a default value will "
"be used."),
('new-instance-open-target',
SettingValue(typ.NewInstanceOpenTarget(), 'window'),
"How to open links in an existing instance if a new one is "
"launched."),
('log-javascript-console',
SettingValue(typ.Bool(), 'false'),
"Whether to log javascript console messages."),
('save-session',
SettingValue(typ.Bool(), 'false'),
"Whether to always save the open pages."),
('session-default-name',
SettingValue(typ.SessionName(none_ok=True), ''),
"The name of the session to save by default, or empty for the "
"last loaded session."),
readonly=readonly
)),
('ui', sect.KeyValue(
('zoom-levels',
SettingValue(typ.PercList(minval=0),
'25%,33%,50%,67%,75%,90%,100%,110%,125%,150%,175%,'
'200%,250%,300%,400%,500%'),
"The available zoom levels, separated by commas."),
('default-zoom',
SettingValue(typ.Perc(), '100%'),
"The default zoom level."),
('downloads-position',
SettingValue(typ.VerticalPosition(), 'north'),
"Where to show the downloaded files."),
('message-timeout',
SettingValue(typ.Int(), '2000'),
"Time (in ms) to show messages in the statusbar for."),
('message-unfocused',
SettingValue(typ.Bool(), 'false'),
"Whether to show messages in unfocused windows."),
('confirm-quit',
SettingValue(typ.ConfirmQuit(), 'never'),
"Whether to confirm quitting the application."),
('display-statusbar-messages',
SettingValue(typ.Bool(), 'false'),
"Whether to display javascript statusbar messages."),
('zoom-text-only',
SettingValue(typ.Bool(), 'false'),
"Whether the zoom factor on a frame applies only to the text or "
"to all content."),
('frame-flattening',
SettingValue(typ.Bool(), 'false'),
"Whether to expand each subframe to its contents.\n\n"
"This will flatten all the frames to become one scrollable "
"page."),
('user-stylesheet',
SettingValue(typ.UserStyleSheet(),
'::-webkit-scrollbar { width: 0px; height: 0px; }'),
"User stylesheet to use (absolute filename or CSS string). Will "
"expand environment variables."),
('css-media-type',
SettingValue(typ.String(none_ok=True), ''),
"Set the CSS media type."),
('smooth-scrolling',
SettingValue(typ.Bool(), 'false'),
"Whether to enable smooth scrolling for webpages."),
('remove-finished-downloads',
SettingValue(typ.Bool(), 'false'),
"Whether to remove finished downloads automatically."),
('hide-statusbar',
SettingValue(typ.Bool(), 'false'),
"Whether to hide the statusbar unless a message is shown."),
('window-title-format',
SettingValue(typ.FormatString(fields=['perc', 'perc_raw', 'title',
'title_sep', 'id']),
'{perc}{title}{title_sep}qutebrowser'),
"The format to use for the window title. The following "
"placeholders are defined:\n\n"
"* `{perc}`: The percentage as a string like `[10%]`.\n"
"* `{perc_raw}`: The raw percentage, e.g. `10`\n"
"* `{title}`: The title of the current web page\n"
"* `{title_sep}`: The string ` - ` if a title is set, empty "
"otherwise.\n"
"* `{id}`: The internal window ID of this window."),
('hide-mouse-cursor',
SettingValue(typ.Bool(), 'false'),
"Whether to hide the mouse cursor."),
('modal-js-dialog',
SettingValue(typ.Bool(), 'false'),
"Use standard JavaScript modal dialog for alert() and confirm()"),
readonly=readonly
)),
('network', sect.KeyValue(
('do-not-track',
SettingValue(typ.Bool(), 'true'),
"Value to send in the `DNT` header."),
('accept-language',
SettingValue(typ.String(none_ok=True), 'en-US,en'),
"Value to send in the `accept-language` header."),
('user-agent',
SettingValue(typ.UserAgent(none_ok=True), ''),
"User agent to send. Empty to send the default."),
('proxy',
SettingValue(typ.Proxy(), 'system'),
"The proxy to use.\n\n"
"In addition to the listed values, you can use a `socks://...` "
"or `http://...` URL."),
('proxy-dns-requests',
SettingValue(typ.Bool(), 'true'),
"Whether to send DNS requests over the configured proxy."),
('ssl-strict',
SettingValue(typ.BoolAsk(), 'ask'),
"Whether to validate SSL handshakes."),
('dns-prefetch',
SettingValue(typ.Bool(), 'true'),
"Whether to try to pre-fetch DNS entries to speed up browsing."),
readonly=readonly
)),
('completion', sect.KeyValue(
('download-path-suggestion',
SettingValue(typ.DownloadPathSuggestion(), 'path'),
"What to display in the download filename input."),
('timestamp-format',
SettingValue(typ.String(none_ok=True), '%Y-%m-%d'),
"How to format timestamps (e.g. for history)"),
('show',
SettingValue(typ.Bool(), 'true'),
"Whether to show the autocompletion window."),
('height',
SettingValue(typ.PercOrInt(minperc=0, maxperc=100, minint=1),
'50%'),
"The height of the completion, in px or as percentage of the "
"window."),
('cmd-history-max-items',
SettingValue(typ.Int(minval=-1), '100'),
"How many commands to save in the command history.\n\n"
"0: no history / -1: unlimited"),
('web-history-max-items',
SettingValue(typ.Int(minval=-1), '1000'),
"How many URLs to show in the web history.\n\n"
"0: no history / -1: unlimited"),
('quick-complete',
SettingValue(typ.Bool(), 'true'),
"Whether to move on to the next part when there's only one "
"possible completion left."),
('shrink',
SettingValue(typ.Bool(), 'false'),
"Whether to shrink the completion to be smaller than the "
"configured size if there are no scrollbars."),
readonly=readonly
)),
('input', sect.KeyValue(
('timeout',
SettingValue(typ.Int(minval=0, maxval=MAXVALS['int']), '500'),
"Timeout for ambiguous key bindings."),
('partial-timeout',
SettingValue(typ.Int(minval=0, maxval=MAXVALS['int']), '1000'),
"Timeout for partially typed key bindings."),
('insert-mode-on-plugins',
SettingValue(typ.Bool(), 'false'),
"Whether to switch to insert mode when clicking flash and other "
"plugins."),
('auto-leave-insert-mode',
SettingValue(typ.Bool(), 'true'),
"Whether to leave insert mode if a non-editable element is "
"clicked."),
('auto-insert-mode',
SettingValue(typ.Bool(), 'false'),
"Whether to automatically enter insert mode if an editable "
"element is focused after page load."),
('forward-unbound-keys',
SettingValue(typ.ForwardUnboundKeys(), 'auto'),
"Whether to forward unbound keys to the webview in normal mode."),
('spatial-navigation',
SettingValue(typ.Bool(), 'false'),
"Enables or disables the Spatial Navigation feature\n\n"
"Spatial navigation consists in the ability to navigate between "
"focusable elements in a Web page, such as hyperlinks and form "
"controls, by using Left, Right, Up and Down arrow keys. For "
"example, if a user presses the Right key, heuristics determine "
"whether there is an element he might be trying to reach towards "
"the right and which element he probably wants."),
('links-included-in-focus-chain',
SettingValue(typ.Bool(), 'true'),
"Whether hyperlinks should be included in the keyboard focus "
"chain."),
('rocker-gestures',
SettingValue(typ.Bool(), 'false'),
"Whether to enable Opera-like mouse rocker gestures. This "
"disables the context menu."),
('mouse-zoom-divider',
SettingValue(typ.Int(minval=1), '512'),
"How much to divide the mouse wheel movements to translate them "
"into zoom increments."),
readonly=readonly
)),
('tabs', sect.KeyValue(
('background-tabs',
SettingValue(typ.Bool(), 'false'),
"Whether to open new tabs (middleclick/ctrl+click) in "
"background."),
('select-on-remove',
SettingValue(typ.SelectOnRemove(), 'right'),
"Which tab to select when the focused tab is removed."),
('new-tab-position',
SettingValue(typ.NewTabPosition(), 'right'),
"How new tabs are positioned."),
('new-tab-position-explicit',
SettingValue(typ.NewTabPosition(), 'last'),
"How new tabs opened explicitly are positioned."),
('last-close',
SettingValue(typ.LastClose(), 'ignore'),
"Behaviour when the last tab is closed."),
('hide-auto',
SettingValue(typ.Bool(), 'false'),
"Hide the tab bar if only one tab is open."),
('hide-always',
SettingValue(typ.Bool(), 'false'),
"Always hide the tab bar."),
('wrap',
SettingValue(typ.Bool(), 'true'),
"Whether to wrap when changing tabs."),
('movable',
SettingValue(typ.Bool(), 'true'),
"Whether tabs should be movable."),
('close-mouse-button',
SettingValue(typ.CloseButton(), 'middle'),
"On which mouse button to close tabs."),
('position',
SettingValue(typ.Position(), 'north'),
"The position of the tab bar."),
('show-favicons',
SettingValue(typ.Bool(), 'true'),
"Whether to show favicons in the tab bar."),
('width',
SettingValue(typ.PercOrInt(minperc=0, maxperc=100, minint=1),
'20%'),
"The width of the tab bar if it's vertical, in px or as "
"percentage of the window."),
('indicator-width',
SettingValue(typ.Int(minval=0), '3'),
"Width of the progress indicator (0 to disable)."),
('indicator-space',
SettingValue(typ.Int(minval=0), '3'),
"Spacing between tab edge and indicator."),
('tabs-are-windows',
SettingValue(typ.Bool(), 'false'),
"Whether to open windows instead of tabs."),
('title-format',
SettingValue(typ.FormatString(
fields=['perc', 'perc_raw', 'title', 'title_sep', 'index',
'id']), '{index}: {title}'),
"The format to use for the tab title. The following placeholders "
"are defined:\n\n"
"* `{perc}`: The percentage as a string like `[10%]`.\n"
"* `{perc_raw}`: The raw percentage, e.g. `10`\n"
"* `{title}`: The title of the current web page\n"
"* `{title_sep}`: The string ` - ` if a title is set, empty "
"otherwise.\n"
"* `{index}`: The index of this tab.\n"
"* `{id}`: The internal tab ID of this tab."),
('mousewheel-tab-switching',
SettingValue(typ.Bool(), 'true'),
"Switch between tabs using the mouse wheel."),
readonly=readonly
)),
('storage', sect.KeyValue(
('download-directory',
SettingValue(typ.Directory(none_ok=True), ''),
"The directory to save downloads to. An empty value selects a "
"sensible os-specific default. Will expand environment "
"variables."),
('maximum-pages-in-cache',
SettingValue(
typ.Int(none_ok=True, minval=0, maxval=MAXVALS['int']), ''),
"The maximum number of pages to hold in the global memory page "
"cache.\n\n"
"The Page Cache allows for a nicer user experience when "
"navigating forth or back to pages in the forward/back history, "
"by pausing and resuming up to _n_ pages.\n\n"
"For more information about the feature, please refer to: "
"http://webkit.org/blog/427/webkit-page-cache-i-the-basics/"),
('object-cache-capacities',
SettingValue(
typ.WebKitBytesList(length=3, maxsize=MAXVALS['int']), ''),
"The capacities for the global memory cache for dead objects "
"such as stylesheets or scripts. Syntax: cacheMinDeadCapacity, "
"cacheMaxDead, totalCapacity.\n\n"
"The _cacheMinDeadCapacity_ specifies the minimum number of "
"bytes that dead objects should consume when the cache is under "
"pressure.\n\n"
"_cacheMaxDead_ is the maximum number of bytes that dead objects "
"should consume when the cache is *not* under pressure.\n\n"
"_totalCapacity_ specifies the maximum number of bytes "
"that the cache should consume *overall*."),
('offline-storage-default-quota',
SettingValue(typ.WebKitBytes(maxsize=MAXVALS['int64']), ''),
"Default quota for new offline storage databases."),
('offline-web-application-cache-quota',
SettingValue(typ.WebKitBytes(maxsize=MAXVALS['int64']), ''),
"Quota for the offline web application cache."),
('offline-storage-database',
SettingValue(typ.Bool(), 'true'),
"Whether support for the HTML 5 offline storage feature is "
"enabled."),
('offline-web-application-storage',
SettingValue(typ.Bool(), 'true'),
"Whether support for the HTML 5 web application cache feature is "
"enabled.\n\n"
"An application cache acts like an HTTP cache in some sense. For "
"documents that use the application cache via JavaScript, the "
"loader engine will first ask the application cache for the "
"contents, before hitting the network.\n\n"
"The feature is described in details at: "
"http://dev.w3.org/html5/spec/Overview.html#appcache"),
('local-storage',
SettingValue(typ.Bool(), 'true'),
"Whether support for the HTML 5 local storage feature is "
"enabled."),
('cache-size',
SettingValue(typ.Int(minval=0, maxval=MAXVALS['int64']),
'52428800'),
"Size of the HTTP network cache."),
readonly=readonly
)),
('content', sect.KeyValue(
('allow-images',
SettingValue(typ.Bool(), 'true'),
"Whether images are automatically loaded in web pages."),
('allow-javascript',
SettingValue(typ.Bool(), 'true'),
"Enables or disables the running of JavaScript programs."),
('allow-plugins',
SettingValue(typ.Bool(), 'false'),
"Enables or disables plugins in Web pages.\n\n"
'Qt plugins with a mimetype such as "application/x-qt-plugin" '
"are not affected by this setting."),
('webgl',
SettingValue(typ.Bool(), 'true'),
"Enables or disables WebGL."),
('css-regions',
SettingValue(typ.Bool(), 'true'),
"Enable or disable support for CSS regions."),
('hyperlink-auditing',
SettingValue(typ.Bool(), 'false'),
"Enable or disable hyperlink auditing (<a ping>)."),
('geolocation',
SettingValue(typ.BoolAsk(), 'ask'),
"Allow websites to request geolocations."),
('notifications',
SettingValue(typ.BoolAsk(), 'ask'),
"Allow websites to show notifications."),
#('allow-java',
# SettingValue(typ.Bool(), 'true'),
# "Enables or disables Java applets. Currently Java applets are "
# "not supported"),
('javascript-can-open-windows',
SettingValue(typ.Bool(), 'false'),
"Whether JavaScript programs can open new windows."),
('javascript-can-close-windows',
SettingValue(typ.Bool(), 'false'),
"Whether JavaScript programs can close windows."),
('javascript-can-access-clipboard',
SettingValue(typ.Bool(), 'false'),
"Whether JavaScript programs can read or write to the "
"clipboard."),
('ignore-javascript-prompt',
SettingValue(typ.Bool(), 'false'),
"Whether all javascript prompts should be ignored."),
('ignore-javascript-alert',
SettingValue(typ.Bool(), 'false'),
"Whether all javascript alerts should be ignored."),
('local-content-can-access-remote-urls',
SettingValue(typ.Bool(), 'false'),
"Whether locally loaded documents are allowed to access remote "
"urls."),
('local-content-can-access-file-urls',
SettingValue(typ.Bool(), 'true'),
"Whether locally loaded documents are allowed to access other "
"local urls."),
('cookies-accept',
SettingValue(typ.AcceptCookies(), 'default'),
"Whether to accept cookies."),
('cookies-store',
SettingValue(typ.Bool(), 'true'),
"Whether to store cookies."),
('host-block-lists',
SettingValue(
typ.UrlList(none_ok=True),
'http://www.malwaredomainlist.com/hostslist/hosts.txt,'
'http://someonewhocares.org/hosts/hosts,'
'http://winhelp2002.mvps.org/hosts.zip,'
'http://malwaredomains.lehigh.edu/files/justdomains.zip,'
'http://pgl.yoyo.org/adservers/serverlist.php?'
'hostformat=hosts&mimetype=plaintext'),
"List of URLs of lists which contain hosts to block.\n\n"
"The file can be in one of the following formats:\n\n"
"- An '/etc/hosts'-like file\n"
"- One host per line\n"
"- A zip-file of any of the above, with either only one file, or "
"a file named 'hosts' (with any extension)."),
('host-blocking-enabled',
SettingValue(typ.Bool(), 'true'),
"Whether host blocking is enabled."),
readonly=readonly
)),
('hints', sect.KeyValue(
('border',
SettingValue(typ.String(), '1px solid #E3BE23'),
"CSS border value for hints."),
('opacity',
SettingValue(typ.Float(minval=0.0, maxval=1.0), '0.7'),
"Opacity for hints."),
('mode',
SettingValue(typ.HintMode(), 'letter'),
"Mode to use for hints."),
('chars',
SettingValue(typ.String(minlen=2), 'asdfghjkl'),
"Chars used for hint strings."),
('min-chars',
SettingValue(typ.Int(minval=1), '1'),
"Mininum number of chars used for hint strings."),
('scatter',
SettingValue(typ.Bool(), 'true'),
"Whether to scatter hint key chains (like Vimium) or not (like "
"dwb)."),
('uppercase',
SettingValue(typ.Bool(), 'false'),
"Make chars in hint strings uppercase."),
('auto-follow',
SettingValue(typ.Bool(), 'true'),
"Whether to auto-follow a hint if there's only one left."),
('next-regexes',
SettingValue(typ.RegexList(flags=re.IGNORECASE),
r'\bnext\b,\bmore\b,\bnewer\b,\b[>→≫]\b,\b(>>|»)\b'),
"A comma-separated list of regexes to use for 'next' links."),
('prev-regexes',
SettingValue(typ.RegexList(flags=re.IGNORECASE),
r'\bprev(ious)?\b,\bback\b,\bolder\b,\b[<←≪]\b,'
r'\b(<<|«)\b'),
"A comma-separated list of regexes to use for 'prev' links."),
readonly=readonly
)),
('searchengines', sect.ValueList(
typ.SearchEngineName(), typ.SearchEngineUrl(),
('DEFAULT', 'https://duckduckgo.com/?q={}'),
readonly=readonly
)),
('aliases', sect.ValueList(
typ.String(forbidden=' '), typ.Command(),
readonly=readonly
)),
('colors', sect.KeyValue(
('completion.fg',
SettingValue(typ.QtColor(), 'white'),
"Text color of the completion widget."),
('completion.bg',
SettingValue(typ.QssColor(), '#333333'),
"Background color of the completion widget."),
('completion.alternate-bg',
SettingValue(typ.QssColor(), '#444444'),
"Alternating background color of the completion widget."),
('completion.category.fg',
SettingValue(typ.QtColor(), 'white'),
"Foreground color of completion widget category headers."),
('completion.category.bg',
SettingValue(typ.QssColor(), 'qlineargradient(x1:0, y1:0, x2:0, '
'y2:1, stop:0 #888888, stop:1 #505050)'),
"Background color of the completion widget category headers."),
('completion.category.border.top',
SettingValue(typ.QssColor(), 'black'),
"Top border color of the completion widget category headers."),
('completion.category.border.bottom',
SettingValue(typ.QssColor(), '${completion.category.border.top}'),
"Bottom border color of the completion widget category headers."),
('completion.item.selected.fg',
SettingValue(typ.QtColor(), 'black'),
"Foreground color of the selected completion item."),
('completion.item.selected.bg',
SettingValue(typ.QssColor(), '#e8c000'),
"Background color of the selected completion item."),
('completion.item.selected.border.top',
SettingValue(typ.QssColor(), '#bbbb00'),
"Top border color of the completion widget category headers."),
('completion.item.selected.border.bottom',
SettingValue(
typ.QssColor(), '${completion.item.selected.border.top}'),
"Bottom border color of the selected completion item."),
('completion.match.fg',
SettingValue(typ.QssColor(), '#ff4444'),
"Foreground color of the matched text in the completion."),
('statusbar.bg',
SettingValue(typ.QssColor(), 'black'),
"Foreground color of the statusbar."),
('statusbar.fg',
SettingValue(typ.QssColor(), 'white'),
"Foreground color of the statusbar."),
('statusbar.bg.error',
SettingValue(typ.QssColor(), 'red'),
"Background color of the statusbar if there was an error."),
('statusbar.bg.warning',
SettingValue(typ.QssColor(), 'darkorange'),
"Background color of the statusbar if there is a warning."),
('statusbar.bg.prompt',
SettingValue(typ.QssColor(), 'darkblue'),
"Background color of the statusbar if there is a prompt."),
('statusbar.bg.insert',
SettingValue(typ.QssColor(), 'darkgreen'),
"Background color of the statusbar in insert mode."),
('statusbar.bg.caret',
SettingValue(typ.QssColor(), 'purple'),
"Background color of the statusbar in caret mode."),
('statusbar.bg.caret-selection',
SettingValue(typ.QssColor(), '#a12dff'),
"Background color of the statusbar in caret mode with a "
"selection"),
('statusbar.progress.bg',
SettingValue(typ.QssColor(), 'white'),
"Background color of the progress bar."),
('statusbar.url.fg',
SettingValue(typ.QssColor(), '${statusbar.fg}'),
"Default foreground color of the URL in the statusbar."),
('statusbar.url.fg.success',
SettingValue(typ.QssColor(), 'lime'),
"Foreground color of the URL in the statusbar on successful "
"load."),
('statusbar.url.fg.error',
SettingValue(typ.QssColor(), 'orange'),
"Foreground color of the URL in the statusbar on error."),
('statusbar.url.fg.warn',
SettingValue(typ.QssColor(), 'yellow'),
"Foreground color of the URL in the statusbar when there's a "
"warning."),
('statusbar.url.fg.hover',
SettingValue(typ.QssColor(), 'aqua'),
"Foreground color of the URL in the statusbar for hovered "
"links."),
('tabs.fg.odd',
SettingValue(typ.QtColor(), 'white'),
"Foreground color of unselected odd tabs."),
('tabs.fg.even',
SettingValue(typ.QtColor(), 'white'),
"Foreground color of unselected even tabs."),
('tabs.fg.selected',
SettingValue(typ.QtColor(), 'white'),
"Foreground color of selected tabs."),
('tabs.bg.odd',
SettingValue(typ.QtColor(), 'grey'),
"Background color of unselected odd tabs."),
('tabs.bg.even',
SettingValue(typ.QtColor(), 'darkgrey'),
"Background color of unselected even tabs."),
('tabs.bg.selected',
SettingValue(typ.QtColor(), 'black'),
"Background color of selected tabs."),
('tabs.bg.bar',
SettingValue(typ.QtColor(), '#555555'),
"Background color of the tab bar."),
('tabs.indicator.start',
SettingValue(typ.QtColor(), '#0000aa'),
"Color gradient start for the tab indicator."),
('tabs.indicator.stop',
SettingValue(typ.QtColor(), '#00aa00'),
"Color gradient end for the tab indicator."),
('tabs.indicator.error',
SettingValue(typ.QtColor(), '#ff0000'),
"Color for the tab indicator on errors.."),
('tabs.indicator.system',
SettingValue(typ.ColorSystem(), 'rgb'),
"Color gradient interpolation system for the tab indicator."),
('hints.fg',
SettingValue(typ.CssColor(), 'black'),
"Font color for hints."),
('hints.fg.match',
SettingValue(typ.CssColor(), 'green'),
"Font color for the matched part of hints."),
('hints.bg',
SettingValue(
typ.CssColor(), '-webkit-gradient(linear, left top, '
'left bottom, color-stop(0%,#FFF785), '
'color-stop(100%,#FFC542))'),
"Background color for hints."),
('downloads.fg',
SettingValue(typ.QtColor(), '#ffffff'),
"Foreground color for downloads."),
('downloads.bg.bar',
SettingValue(typ.QssColor(), 'black'),
"Background color for the download bar."),
('downloads.bg.start',
SettingValue(typ.QtColor(), '#0000aa'),
"Color gradient start for downloads."),
('downloads.bg.stop',
SettingValue(typ.QtColor(), '#00aa00'),
"Color gradient end for downloads."),
('downloads.bg.system',
SettingValue(typ.ColorSystem(), 'rgb'),
"Color gradient interpolation system for downloads."),
('downloads.bg.error',
SettingValue(typ.QtColor(), 'red'),
"Background color for downloads with errors."),
('webpage.bg',
SettingValue(typ.QtColor(none_ok=True), 'white'),
"Background color for webpages if unset (or empty to use the "
"theme's color)"),
readonly=readonly
)),
('fonts', sect.KeyValue(
('_monospace',
SettingValue(typ.Font(), 'Terminus, Monospace, '
'"DejaVu Sans Mono", Monaco, '
'"Bitstream Vera Sans Mono", "Andale Mono", '
'"Liberation Mono", "Courier New", Courier, '
'monospace, Fixed, Consolas, Terminal'),
"Default monospace fonts."),
('completion',
SettingValue(typ.Font(), DEFAULT_FONT_SIZE + ' ${_monospace}'),
"Font used in the completion widget."),
('tabbar',
SettingValue(typ.QtFont(), DEFAULT_FONT_SIZE + ' ${_monospace}'),
"Font used in the tab bar."),
('statusbar',
SettingValue(typ.Font(), DEFAULT_FONT_SIZE + ' ${_monospace}'),
"Font used in the statusbar."),
('downloads',
SettingValue(typ.Font(), DEFAULT_FONT_SIZE + ' ${_monospace}'),
"Font used for the downloadbar."),
('hints',
SettingValue(typ.Font(), 'bold 12px Monospace'),
"Font used for the hints."),
('debug-console',
SettingValue(typ.QtFont(), DEFAULT_FONT_SIZE + ' ${_monospace}'),
"Font used for the debugging console."),
('web-family-standard',
SettingValue(typ.FontFamily(none_ok=True), ''),
"Font family for standard fonts."),
('web-family-fixed',
SettingValue(typ.FontFamily(none_ok=True), ''),
"Font family for fixed fonts."),
('web-family-serif',
SettingValue(typ.FontFamily(none_ok=True), ''),
"Font family for serif fonts."),
('web-family-sans-serif',
SettingValue(typ.FontFamily(none_ok=True), ''),
"Font family for sans-serif fonts."),
('web-family-cursive',
SettingValue(typ.FontFamily(none_ok=True), ''),
"Font family for cursive fonts."),
('web-family-fantasy',
SettingValue(typ.FontFamily(none_ok=True), ''),
"Font family for fantasy fonts."),
('web-size-minimum',
SettingValue(
typ.Int(none_ok=True, minval=1, maxval=MAXVALS['int']), ''),
"The hard minimum font size."),
('web-size-minimum-logical',
SettingValue(
typ.Int(none_ok=True, minval=1, maxval=MAXVALS['int']), ''),
"The minimum logical font size that is applied when zooming "
"out."),
('web-size-default',
SettingValue(
typ.Int(none_ok=True, minval=1, maxval=MAXVALS['int']), ''),
"The default font size for regular text."),
('web-size-default-fixed',
SettingValue(
typ.Int(none_ok=True, minval=1, maxval=MAXVALS['int']), ''),
"The default font size for fixed-pitch text."),
readonly=readonly
)),
])
DATA = data(readonly=True)
KEY_FIRST_COMMENT = """
# vim: ft=conf
#
# In this config file, qutebrowser's key bindings are configured.
# The format looks like this:
#
# [keymode]
#
# command
# keychain
# keychain2
# ...
#
# All blank lines and lines starting with '#' are ignored.
# Inline-comments are not permitted.
#
# keymode is a comma separated list of modes in which the key binding should be
# active. If keymode starts with !, the key binding is active in all modes
# except the listed modes.
#
# For special keys (can't be part of a keychain), enclose them in `<`...`>`.
# For modifiers, you can use either `-` or `+` as delimiters, and these names:
#
# * Control: `Control`, `Ctrl`
# * Meta: `Meta`, `Windows`, `Mod4`
# * Alt: `Alt`, `Mod1`
# * Shift: `Shift`
#
# For simple keys (no `<>`-signs), a capital letter means the key is pressed
# with Shift. For special keys (with `<>`-signs), you need to explicitly add
# `Shift-` to match a key pressed with shift. You can bind multiple commands
# by separating them with `;;`.
"""
KEY_SECTION_DESC = {
'all': "Keybindings active in all modes.",
'normal': "Keybindings for normal mode.",
'insert': (
"Keybindings for insert mode.\n"
"Since normal keypresses are passed through, only special keys are "
"supported in this mode.\n"
"Useful hidden commands to map in this section:\n\n"
" * `open-editor`: Open a texteditor with the focused field."),
'hint': (
"Keybindings for hint mode.\n"
"Since normal keypresses are passed through, only special keys are "
"supported in this mode.\n"
"Useful hidden commands to map in this section:\n\n"
" * `follow-hint`: Follow the currently selected hint."),
'passthrough': (
"Keybindings for passthrough mode.\n"
"Since normal keypresses are passed through, only special keys are "
"supported in this mode."),
'command': (
"Keybindings for command mode.\n"
"Since normal keypresses are passed through, only special keys are "
"supported in this mode.\n"
"Useful hidden commands to map in this section:\n\n"
" * `command-history-prev`: Switch to previous command in history.\n"
" * `command-history-next`: Switch to next command in history.\n"
" * `completion-item-prev`: Select previous item in completion.\n"
" * `completion-item-next`: Select next item in completion.\n"
" * `command-accept`: Execute the command currently in the "
"commandline."),
'prompt': (
"Keybindings for prompts in the status line.\n"
"You can bind normal keys in this mode, but they will be only active "
"when a yes/no-prompt is asked. For other prompt modes, you can only "
"bind special keys.\n"
"Useful hidden commands to map in this section:\n\n"
" * `prompt-accept`: Confirm the entered value.\n"
" * `prompt-yes`: Answer yes to a yes/no question.\n"
" * `prompt-no`: Answer no to a yes/no question."),
'caret': (
""),
}
# Keys which are similar to Return and should be bound by default where Return
# is bound.
RETURN_KEYS = ['<Return>', '<Ctrl-M>', '<Ctrl-J>', '<Shift-Return>', '<Enter>',
'<Shift-Enter>']
KEY_DATA = collections.OrderedDict([
('!normal', collections.OrderedDict([
('leave-mode', ['<Escape>', '<Ctrl-[>']),
])),
('normal', collections.OrderedDict([
('search', ['<Escape>']),
('set-cmd-text -s :open', ['o']),
('set-cmd-text :open {url}', ['go']),
('set-cmd-text -s :open -t', ['O']),
('set-cmd-text :open -t {url}', ['gO']),
('set-cmd-text -s :open -b', ['xo']),
('set-cmd-text :open -b {url}', ['xO']),
('set-cmd-text -s :open -w', ['wo']),
('set-cmd-text :open -w {url}', ['wO']),
('open -t', ['ga', '<Ctrl-T>']),
('tab-close', ['d', '<Ctrl-W>']),
('tab-close -o', ['D']),
('tab-only', ['co']),
('tab-focus', ['T']),
('tab-move', ['gm']),
('tab-move -', ['gl']),
('tab-move +', ['gr']),
('tab-next', ['J', 'gt']),
('tab-prev', ['K', 'gT']),
('tab-clone', ['gC']),
('reload', ['r']),
('reload -f', ['R']),
('back', ['H', '<Backspace>']),
('back -t', ['th']),
('back -w', ['wh']),
('forward', ['L']),
('forward -t', ['tl']),
('forward -w', ['wl']),
('fullscreen', ['<F11>']),
('hint', ['f']),
('hint all tab', ['F']),
('hint all window', ['wf']),
('hint all tab-bg', [';b']),
('hint all tab-fg', [';f']),
('hint all hover', [';h']),
('hint images', [';i']),
('hint images tab', [';I']),
('hint images tab-bg', ['.i']),
('hint links fill ":open {hint-url}"', [';o']),
('hint links fill ":open -t {hint-url}"', [';O']),
('hint links fill ":open -b {hint-url}"', ['.o']),
('hint links yank', [';y']),
('hint links yank-primary', [';Y']),
('hint --rapid links tab-bg', [';r']),
('hint --rapid links window', [';R']),
('hint links download', [';d']),
('scroll left', ['h']),
('scroll down', ['j']),
('scroll up', ['k']),
('scroll right', ['l']),
('undo', ['u', '<Ctrl-Shift-T>']),
('scroll-perc 0', ['gg']),
('scroll-perc', ['G']),
('search-next', ['n']),
('search-prev', ['N']),
('enter-mode insert', ['i']),
('enter-mode caret', ['v']),
('yank', ['yy']),
('yank -s', ['yY']),
('yank -t', ['yt']),
('yank -ts', ['yT']),
('paste', ['pp']),
('paste -s', ['pP']),
('paste -t', ['Pp']),
('paste -ts', ['PP']),
('paste -w', ['wp']),
('paste -ws', ['wP']),
('quickmark-save', ['m']),
('set-cmd-text -s :quickmark-load', ['b']),
('set-cmd-text -s :quickmark-load -t', ['B']),
('set-cmd-text -s :quickmark-load -w', ['wb']),
('save', ['sf']),
('set-cmd-text -s :set', ['ss']),
('set-cmd-text -s :set -t', ['sl']),
('set-cmd-text -s :set keybind', ['sk']),
('zoom-out', ['-']),
('zoom-in', ['+']),
('zoom', ['=']),
('navigate prev', ['[[']),
('navigate next', [']]']),
('navigate prev -t', ['{{']),
('navigate next -t', ['}}']),
('navigate up', ['gu']),
('navigate up -t', ['gU']),
('navigate increment', ['<Ctrl-A>']),
('navigate decrement', ['<Ctrl-X>']),
('inspector', ['wi']),
('download', ['gd']),
('download-cancel', ['ad']),
('download-remove --all', ['cd']),
('view-source', ['gf']),
('tab-focus last', ['<Ctrl-Tab>']),
('enter-mode passthrough', ['<Ctrl-V>']),
('quit', ['<Ctrl-Q>']),
('scroll-page 0 1', ['<Ctrl-F>']),
('scroll-page 0 -1', ['<Ctrl-B>']),
('scroll-page 0 0.5', ['<Ctrl-D>']),
('scroll-page 0 -0.5', ['<Ctrl-U>']),
('tab-focus 1', ['<Alt-1>']),
('tab-focus 2', ['<Alt-2>']),
('tab-focus 3', ['<Alt-3>']),
('tab-focus 4', ['<Alt-4>']),
('tab-focus 5', ['<Alt-5>']),
('tab-focus 6', ['<Alt-6>']),
('tab-focus 7', ['<Alt-7>']),
('tab-focus 8', ['<Alt-8>']),
('tab-focus 9', ['<Alt-9>']),
('home', ['<Ctrl-h>']),
('stop', ['<Ctrl-s>']),
('print', ['<Ctrl-Alt-p>']),
('open qute:settings', ['Ss']),
('follow-selected', RETURN_KEYS),
('follow-selected -t', ['<Ctrl-Return>', '<Ctrl-Enter>']),
])),
('insert', collections.OrderedDict([
('open-editor', ['<Ctrl-E>']),
])),
('hint', collections.OrderedDict([
('follow-hint', RETURN_KEYS),
('hint --rapid links tab-bg', ['<Ctrl-R>']),
('hint links', ['<Ctrl-F>']),
('hint all tab-bg', ['<Ctrl-B>']),
])),
('passthrough', {}),
('command', collections.OrderedDict([
('command-history-prev', ['<Ctrl-P>']),
('command-history-next', ['<Ctrl-N>']),
('completion-item-prev', ['<Shift-Tab>', '<Up>']),
('completion-item-next', ['<Tab>', '<Down>']),
('command-accept', RETURN_KEYS),
])),
('prompt', collections.OrderedDict([
('prompt-accept', RETURN_KEYS),
('prompt-yes', ['y']),
('prompt-no', ['n']),
])),
('command,prompt', collections.OrderedDict([
('rl-backward-char', ['<Ctrl-B>']),
('rl-forward-char', ['<Ctrl-F>']),
('rl-backward-word', ['<Alt-B>']),
('rl-forward-word', ['<Alt-F>']),
('rl-beginning-of-line', ['<Ctrl-A>']),
('rl-end-of-line', ['<Ctrl-E>']),
('rl-unix-line-discard', ['<Ctrl-U>']),
('rl-kill-line', ['<Ctrl-K>']),
('rl-kill-word', ['<Alt-D>']),
('rl-unix-word-rubout', ['<Ctrl-W>']),
('rl-yank', ['<Ctrl-Y>']),
('rl-delete-char', ['<Ctrl-?>']),
('rl-backward-delete-char', ['<Ctrl-H>']),
])),
('caret', collections.OrderedDict([
('toggle-selection', ['v', '<Space>']),
('drop-selection', ['<Ctrl-Space>']),
('enter-mode normal', ['c']),
('move-to-next-line', ['j']),
('move-to-prev-line', ['k']),
('move-to-next-char', ['l']),
('move-to-prev-char', ['h']),
('move-to-end-of-word', ['e']),
('move-to-next-word', ['w']),
('move-to-prev-word', ['b']),
('move-to-start-of-next-block', [']']),
('move-to-start-of-prev-block', ['[']),
('move-to-end-of-next-block', ['}']),
('move-to-end-of-prev-block', ['{']),
('move-to-start-of-line', ['0']),
('move-to-end-of-line', ['$']),
('move-to-start-of-document', ['gg']),
('move-to-end-of-document', ['G']),
('yank-selected -p', ['Y']),
('yank-selected', ['y'] + RETURN_KEYS),
('scroll left', ['H']),
('scroll down', ['J']),
('scroll up', ['K']),
('scroll right', ['L']),
])),
])
# A list of (regex, replacement) tuples of changed key commands.
CHANGED_KEY_COMMANDS = [
(re.compile(r'^open -([twb]) about:blank$'), r'open -\1'),
(re.compile(r'^download-page$'), r'download'),
(re.compile(r'^cancel-download$'), r'download-cancel'),
(re.compile(r'^search ""$'), r'search'),
(re.compile(r"^search ''$"), r'search'),
(re.compile(r"""^set-cmd-text ['"](.*) ['"]$"""), r'set-cmd-text -s \1'),
(re.compile(r"""^set-cmd-text ['"](.*)['"]$"""), r'set-cmd-text \1'),
(re.compile(r"^hint links rapid$"), r'hint --rapid links tab-bg'),
(re.compile(r"^hint links rapid-win$"), r'hint --rapid links window'),
(re.compile(r'^scroll -50 0$'), r'scroll left'),
(re.compile(r'^scroll 0 50$'), r'scroll down'),
(re.compile(r'^scroll 0 -50$'), r'scroll up'),
(re.compile(r'^scroll 50 0$'), r'scroll right'),
(re.compile(r'^scroll ([-\d]+ [-\d]+)$'), r'scroll-px \1'),
]
| 1 | 13,119 | It still bugs me this was misspelled in the standard and now the wrong spelling is the commonly used one :wink: | qutebrowser-qutebrowser | py |
@@ -95,7 +95,7 @@ define(["loading", "dialogHelper", "dom", "jQuery", "components/libraryoptionsed
function getFolderHtml(pathInfo, index) {
var html = "";
- return html += '<div class="listItem listItem-border lnkPath" style="padding-left:.5em;">', html += '<div class="' + (pathInfo.NetworkPath ? "listItemBody two-line" : "listItemBody") + '">', html += '<div class="listItemBodyText">' + pathInfo.Path + "</div>", pathInfo.NetworkPath && (html += '<div class="listItemBodyText secondary">' + pathInfo.NetworkPath + "</div>"), html += "</div>", html += '<button type="button" is="paper-icon-button-light"" class="listItemButton btnRemovePath" data-index="' + index + '"><i class="md-icon">remove_circle</i></button>', html += "</div>"
+ return html += '<div class="listItem listItem-border lnkPath" style="padding-left:.5em;">', html += '<div class="' + (pathInfo.NetworkPath ? "listItemBody two-line" : "listItemBody") + '">', html += '<div class="listItemBodyText">' + pathInfo.Path + "</div>", pathInfo.NetworkPath && (html += '<div class="listItemBodyText secondary">' + pathInfo.NetworkPath + "</div>"), html += "</div>", html += '<button type="button" is="paper-icon-button-light"" class="listItemButton btnRemovePath" data-index="' + index + '"><i class="material-icons">remove_circle</i></button>', html += "</div>"
}
function renderPaths(page) { | 1 | define(["loading", "dialogHelper", "dom", "jQuery", "components/libraryoptionseditor/libraryoptionseditor", "emby-toggle", "emby-input", "emby-select", "paper-icon-button-light", "listViewStyle", "formDialogStyle", "emby-button", "flexStyles"], function(loading, dialogHelper, dom, $, libraryoptionseditor) {
"use strict";
function onAddLibrary() {
if (isCreating) return false;
if (pathInfos.length == 0) {
require(["alert"], function(alert) {
alert({
text: Globalize.translate("PleaseAddAtLeastOneFolder"),
type: "error"
})
});
return false;
}
isCreating = true;
loading.show();
var dlg = dom.parentWithClass(this, "dlg-librarycreator");
var name = $("#txtValue", dlg).val();
var type = $("#selectCollectionType", dlg).val();
if (type == "mixed") type = null;
var libraryOptions = libraryoptionseditor.getLibraryOptions(dlg.querySelector(".libraryOptions"));
libraryOptions.PathInfos = pathInfos;
ApiClient.addVirtualFolder(name, type, currentOptions.refresh, libraryOptions).then(function() {
hasChanges = true;
isCreating = false;
loading.hide();
dialogHelper.close(dlg);
}, function() {
require(["toast"], function(toast) {
toast(Globalize.translate("ErrorAddingMediaPathToVirtualFolder"));
});
isCreating = false;
loading.hide();
});
return false;
}
function getCollectionTypeOptionsHtml(collectionTypeOptions) {
return collectionTypeOptions.map(function(i) {
return '<option value="' + i.value + '">' + i.name + "</option>";
}).join("");
}
function initEditor(page, collectionTypeOptions) {
$("#selectCollectionType", page).html(getCollectionTypeOptionsHtml(collectionTypeOptions)).val("").on("change", function() {
var value = this.value;
var dlg = $(this).parents(".dialog")[0];
libraryoptionseditor.setContentType(dlg.querySelector(".libraryOptions"), value == "mixed" ? "" : value);
if (value) {
dlg.querySelector(".libraryOptions").classList.remove("hide");
} else {
dlg.querySelector(".libraryOptions").classList.add("hide");
}
if (value != "mixed") {
var index = this.selectedIndex;
if (index != -1) {
var name = this.options[index].innerHTML.replace("*", "").replace("&", "&");
$("#txtValue", dlg).val(name);
var folderOption = collectionTypeOptions.filter(function(i) {
return i.value == value
})[0];
$(".collectionTypeFieldDescription", dlg).html(folderOption.message || "")
}
}
});
page.querySelector(".btnAddFolder").addEventListener("click", onAddButtonClick);
page.querySelector(".btnSubmit").addEventListener("click", onAddLibrary);
page.querySelector(".folderList").addEventListener("click", onRemoveClick);
page.querySelector(".chkAdvanced").addEventListener("change", onToggleAdvancedChange);
}
function onToggleAdvancedChange() {
var dlg = dom.parentWithClass(this, "dlg-librarycreator");
libraryoptionseditor.setAdvancedVisible(dlg.querySelector(".libraryOptions"), this.checked);
}
function onAddButtonClick() {
var page = dom.parentWithClass(this, "dlg-librarycreator");
require(["directorybrowser"], function(directoryBrowser) {
var picker = new directoryBrowser;
picker.show({
enableNetworkSharePath: true,
callback: function(path, networkSharePath) {
path && addMediaLocation(page, path, networkSharePath);
picker.close();
}
})
})
}
function getFolderHtml(pathInfo, index) {
var html = "";
return html += '<div class="listItem listItem-border lnkPath" style="padding-left:.5em;">', html += '<div class="' + (pathInfo.NetworkPath ? "listItemBody two-line" : "listItemBody") + '">', html += '<div class="listItemBodyText">' + pathInfo.Path + "</div>", pathInfo.NetworkPath && (html += '<div class="listItemBodyText secondary">' + pathInfo.NetworkPath + "</div>"), html += "</div>", html += '<button type="button" is="paper-icon-button-light"" class="listItemButton btnRemovePath" data-index="' + index + '"><i class="md-icon">remove_circle</i></button>', html += "</div>"
}
function renderPaths(page) {
var foldersHtml = pathInfos.map(getFolderHtml).join("");
var folderList = page.querySelector(".folderList");
folderList.innerHTML = foldersHtml;
foldersHtml ? folderList.classList.remove("hide") : folderList.classList.add("hide");
}
function addMediaLocation(page, path, networkSharePath) {
var pathLower = path.toLowerCase();
var pathFilter = pathInfos.filter(function(p) {
return p.Path.toLowerCase() == pathLower;
});
if (!pathFilter.length) {
var pathInfo = {
Path: path
};
networkSharePath && (pathInfo.NetworkPath = networkSharePath);
pathInfos.push(pathInfo);
renderPaths(page);
}
}
function onRemoveClick(e) {
var button = dom.parentWithClass(e.target, "btnRemovePath");
var index = parseInt(button.getAttribute("data-index"));
var location = pathInfos[index].Path;
var locationLower = location.toLowerCase();
pathInfos = pathInfos.filter(function(p) {
return p.Path.toLowerCase() != locationLower;
});
renderPaths(dom.parentWithClass(button, "dlg-librarycreator"));
}
function onDialogClosed() {
currentResolve(hasChanges);
}
function initLibraryOptions(dlg) {
libraryoptionseditor.embed(dlg.querySelector(".libraryOptions")).then(function() {
$("#selectCollectionType", dlg).trigger("change");
onToggleAdvancedChange.call(dlg.querySelector(".chkAdvanced"));
})
}
function editor() {
this.show = function(options) {
return new Promise(function(resolve, reject) {
currentOptions = options;
currentResolve = resolve;
hasChanges = false;
var xhr = new XMLHttpRequest;
xhr.open("GET", "components/medialibrarycreator/medialibrarycreator.template.html", true);
xhr.onload = function(e) {
var template = this.response;
var dlg = dialogHelper.createDialog({
size: "medium-tall",
modal: false,
removeOnClose: true,
scrollY: false
});
dlg.classList.add("ui-body-a");
dlg.classList.add("background-theme-a");
dlg.classList.add("dlg-librarycreator");
dlg.classList.add("formDialog");
dlg.innerHTML = Globalize.translateDocument(template);
initEditor(dlg, options.collectionTypeOptions);
dlg.addEventListener("close", onDialogClosed);
dialogHelper.open(dlg);
dlg.querySelector(".btnCancel").addEventListener("click", function() {
dialogHelper.close(dlg)
});
pathInfos = [];
renderPaths(dlg);
initLibraryOptions(dlg);
};
xhr.send();
});
}
}
var pathInfos = [];
var currentResolve;
var currentOptions;
var hasChanges = false;
var isCreating = false;
return editor
});
| 1 | 12,735 | seems we missed de-uglifying this one | jellyfin-jellyfin-web | js |
@@ -52,6 +52,14 @@ const (
TransactionPolicyPassive TransactionPolicy = 1
)
+type NewWorkflowType int
+
+const (
+ NewWorkflowUnspecified NewWorkflowType = iota
+ NewWorkflowRetry
+ NewWorkflowCron
+)
+
func (policy TransactionPolicy) Ptr() *TransactionPolicy {
return &policy
} | 1 | // The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//go:generate mockgen -copyright_file ../../../LICENSE -package $GOPACKAGE -source $GOFILE -destination mutable_state_mock.go
package workflow
import (
"time"
commandpb "go.temporal.io/api/command/v1"
commonpb "go.temporal.io/api/common/v1"
enumspb "go.temporal.io/api/enums/v1"
failurepb "go.temporal.io/api/failure/v1"
historypb "go.temporal.io/api/history/v1"
taskqueuepb "go.temporal.io/api/taskqueue/v1"
"go.temporal.io/api/workflowservice/v1"
enumsspb "go.temporal.io/server/api/enums/v1"
"go.temporal.io/server/api/historyservice/v1"
persistencespb "go.temporal.io/server/api/persistence/v1"
"go.temporal.io/server/common/cache"
"go.temporal.io/server/common/definition"
"go.temporal.io/server/common/persistence"
)
type TransactionPolicy int
const (
TransactionPolicyActive TransactionPolicy = 0
TransactionPolicyPassive TransactionPolicy = 1
)
func (policy TransactionPolicy) Ptr() *TransactionPolicy {
return &policy
}
var emptyTasks = []persistence.Task{}
type (
// TODO: This should be part of persistence layer
WorkflowTaskInfo struct {
Version int64
ScheduleID int64
StartedID int64
RequestID string
WorkflowTaskTimeout *time.Duration
TaskQueue *taskqueuepb.TaskQueue // This is only needed to communicate task queue used after AddWorkflowTaskScheduledEvent
Attempt int32
// Scheduled and Started timestamps are useful for transient workflow task: when transient workflow task finally completes,
// use these Timestamp to create scheduled/started events.
// Also used for recording latency metrics
ScheduledTime *time.Time
StartedTime *time.Time
// OriginalScheduledTime is to record the first scheduled workflow task during workflow task heartbeat.
// Client may heartbeat workflow task by RespondWorkflowTaskComplete with ForceCreateNewWorkflowTask == true
// In this case, OriginalScheduledTime won't change. Then when current time - OriginalScheduledTime exceeds
// some threshold, server can interrupt the heartbeat by enforcing to timeout the workflow task.
OriginalScheduledTime *time.Time
}
MutableState interface {
AddActivityTaskCancelRequestedEvent(int64, int64, string) (*historypb.HistoryEvent, *persistencespb.ActivityInfo, error)
AddActivityTaskCanceledEvent(int64, int64, int64, *commonpb.Payloads, string) (*historypb.HistoryEvent, error)
AddActivityTaskCompletedEvent(int64, int64, *workflowservice.RespondActivityTaskCompletedRequest) (*historypb.HistoryEvent, error)
AddActivityTaskFailedEvent(int64, int64, *failurepb.Failure, enumspb.RetryState, string) (*historypb.HistoryEvent, error)
AddActivityTaskScheduledEvent(int64, *commandpb.ScheduleActivityTaskCommandAttributes) (*historypb.HistoryEvent, *persistencespb.ActivityInfo, error)
AddActivityTaskStartedEvent(*persistencespb.ActivityInfo, int64, string, string) (*historypb.HistoryEvent, error)
AddActivityTaskTimedOutEvent(int64, int64, *failurepb.Failure, enumspb.RetryState) (*historypb.HistoryEvent, error)
AddChildWorkflowExecutionCanceledEvent(int64, *commonpb.WorkflowExecution, *historypb.WorkflowExecutionCanceledEventAttributes) (*historypb.HistoryEvent, error)
AddChildWorkflowExecutionCompletedEvent(int64, *commonpb.WorkflowExecution, *historypb.WorkflowExecutionCompletedEventAttributes) (*historypb.HistoryEvent, error)
AddChildWorkflowExecutionFailedEvent(int64, *commonpb.WorkflowExecution, *historypb.WorkflowExecutionFailedEventAttributes) (*historypb.HistoryEvent, error)
AddChildWorkflowExecutionStartedEvent(string, *commonpb.WorkflowExecution, *commonpb.WorkflowType, int64, *commonpb.Header) (*historypb.HistoryEvent, error)
AddChildWorkflowExecutionTerminatedEvent(int64, *commonpb.WorkflowExecution, *historypb.WorkflowExecutionTerminatedEventAttributes) (*historypb.HistoryEvent, error)
AddChildWorkflowExecutionTimedOutEvent(int64, *commonpb.WorkflowExecution, *historypb.WorkflowExecutionTimedOutEventAttributes) (*historypb.HistoryEvent, error)
AddCompletedWorkflowEvent(int64, *commandpb.CompleteWorkflowExecutionCommandAttributes) (*historypb.HistoryEvent, error)
AddContinueAsNewEvent(int64, int64, string, *commandpb.ContinueAsNewWorkflowExecutionCommandAttributes) (*historypb.HistoryEvent, MutableState, error)
AddWorkflowTaskCompletedEvent(int64, int64, *workflowservice.RespondWorkflowTaskCompletedRequest, int) (*historypb.HistoryEvent, error)
AddWorkflowTaskFailedEvent(scheduleEventID int64, startedEventID int64, cause enumspb.WorkflowTaskFailedCause, failure *failurepb.Failure, identity, binChecksum, baseRunID, newRunID string, forkEventVersion int64) (*historypb.HistoryEvent, error)
AddWorkflowTaskScheduleToStartTimeoutEvent(int64) (*historypb.HistoryEvent, error)
AddFirstWorkflowTaskScheduled(*historypb.HistoryEvent) error
AddWorkflowTaskScheduledEvent(bypassTaskGeneration bool) (*WorkflowTaskInfo, error)
AddWorkflowTaskScheduledEventAsHeartbeat(bypassTaskGeneration bool, originalScheduledTimestamp *time.Time) (*WorkflowTaskInfo, error)
AddWorkflowTaskStartedEvent(int64, string, *taskqueuepb.TaskQueue, string) (*historypb.HistoryEvent, *WorkflowTaskInfo, error)
AddWorkflowTaskTimedOutEvent(int64, int64) (*historypb.HistoryEvent, error)
AddExternalWorkflowExecutionCancelRequested(int64, string, string, string) (*historypb.HistoryEvent, error)
AddExternalWorkflowExecutionSignaled(int64, string, string, string, string) (*historypb.HistoryEvent, error)
AddFailWorkflowEvent(int64, enumspb.RetryState, *commandpb.FailWorkflowExecutionCommandAttributes) (*historypb.HistoryEvent, error)
AddRecordMarkerEvent(int64, *commandpb.RecordMarkerCommandAttributes) (*historypb.HistoryEvent, error)
AddRequestCancelExternalWorkflowExecutionFailedEvent(int64, string, string, string, enumspb.CancelExternalWorkflowExecutionFailedCause) (*historypb.HistoryEvent, error)
AddRequestCancelExternalWorkflowExecutionInitiatedEvent(int64, string, *commandpb.RequestCancelExternalWorkflowExecutionCommandAttributes) (*historypb.HistoryEvent, *persistencespb.RequestCancelInfo, error)
AddSignalExternalWorkflowExecutionFailedEvent(int64, string, string, string, string, enumspb.SignalExternalWorkflowExecutionFailedCause) (*historypb.HistoryEvent, error)
AddSignalExternalWorkflowExecutionInitiatedEvent(int64, string, *commandpb.SignalExternalWorkflowExecutionCommandAttributes) (*historypb.HistoryEvent, *persistencespb.SignalInfo, error)
AddSignalRequested(requestID string)
AddStartChildWorkflowExecutionFailedEvent(int64, enumspb.StartChildWorkflowExecutionFailedCause, *historypb.StartChildWorkflowExecutionInitiatedEventAttributes) (*historypb.HistoryEvent, error)
AddStartChildWorkflowExecutionInitiatedEvent(int64, string, *commandpb.StartChildWorkflowExecutionCommandAttributes) (*historypb.HistoryEvent, *persistencespb.ChildExecutionInfo, error)
AddTimeoutWorkflowEvent(int64, enumspb.RetryState) (*historypb.HistoryEvent, error)
AddTimerCanceledEvent(int64, *commandpb.CancelTimerCommandAttributes, string) (*historypb.HistoryEvent, error)
AddTimerFiredEvent(string) (*historypb.HistoryEvent, error)
AddTimerStartedEvent(int64, *commandpb.StartTimerCommandAttributes) (*historypb.HistoryEvent, *persistencespb.TimerInfo, error)
AddUpsertWorkflowSearchAttributesEvent(int64, *commandpb.UpsertWorkflowSearchAttributesCommandAttributes) (*historypb.HistoryEvent, error)
AddWorkflowExecutionCancelRequestedEvent(*historyservice.RequestCancelWorkflowExecutionRequest) (*historypb.HistoryEvent, error)
AddWorkflowExecutionCanceledEvent(int64, *commandpb.CancelWorkflowExecutionCommandAttributes) (*historypb.HistoryEvent, error)
AddWorkflowExecutionSignaled(signalName string, input *commonpb.Payloads, identity string) (*historypb.HistoryEvent, error)
AddWorkflowExecutionStartedEvent(commonpb.WorkflowExecution, *historyservice.StartWorkflowExecutionRequest) (*historypb.HistoryEvent, error)
AddWorkflowExecutionTerminatedEvent(firstEventID int64, reason string, details *commonpb.Payloads, identity string) (*historypb.HistoryEvent, error)
ClearStickyness()
CheckResettable() error
CloneToProto() *persistencespb.WorkflowMutableState
RetryActivity(ai *persistencespb.ActivityInfo, failure *failurepb.Failure) (enumspb.RetryState, error)
CreateTransientWorkflowTaskEvents(di *WorkflowTaskInfo, identity string) (*historypb.HistoryEvent, *historypb.HistoryEvent)
DeleteWorkflowTask()
DeleteSignalRequested(requestID string)
FlushBufferedEvents()
GetActivityByActivityID(string) (*persistencespb.ActivityInfo, bool)
GetActivityInfo(int64) (*persistencespb.ActivityInfo, bool)
GetActivityInfoWithTimerHeartbeat(scheduleEventID int64) (*persistencespb.ActivityInfo, time.Time, bool)
GetActivityScheduledEvent(int64) (*historypb.HistoryEvent, error)
GetChildExecutionInfo(int64) (*persistencespb.ChildExecutionInfo, bool)
GetChildExecutionInitiatedEvent(int64) (*historypb.HistoryEvent, error)
GetCompletionEvent() (*historypb.HistoryEvent, error)
GetWorkflowTaskInfo(int64) (*WorkflowTaskInfo, bool)
GetNamespaceEntry() *cache.NamespaceCacheEntry
GetStartEvent() (*historypb.HistoryEvent, error)
GetCurrentBranchToken() ([]byte, error)
GetCurrentVersion() int64
GetExecutionInfo() *persistencespb.WorkflowExecutionInfo
GetExecutionState() *persistencespb.WorkflowExecutionState
GetInFlightWorkflowTask() (*WorkflowTaskInfo, bool)
GetPendingWorkflowTask() (*WorkflowTaskInfo, bool)
GetLastFirstEventIDTxnID() (int64, int64)
GetLastWriteVersion() (int64, error)
GetNextEventID() int64
GetPreviousStartedEventID() int64
GetPendingActivityInfos() map[int64]*persistencespb.ActivityInfo
GetPendingTimerInfos() map[string]*persistencespb.TimerInfo
GetPendingChildExecutionInfos() map[int64]*persistencespb.ChildExecutionInfo
GetPendingRequestCancelExternalInfos() map[int64]*persistencespb.RequestCancelInfo
GetPendingSignalExternalInfos() map[int64]*persistencespb.SignalInfo
GetRequestCancelInfo(int64) (*persistencespb.RequestCancelInfo, bool)
GetRetryBackoffDuration(failure *failurepb.Failure) (time.Duration, enumspb.RetryState)
GetCronBackoffDuration() (time.Duration, error)
GetSignalInfo(int64) (*persistencespb.SignalInfo, bool)
GetStartVersion() (int64, error)
GetUserTimerInfoByEventID(int64) (*persistencespb.TimerInfo, bool)
GetUserTimerInfo(string) (*persistencespb.TimerInfo, bool)
GetWorkflowType() *commonpb.WorkflowType
GetWorkflowStateStatus() (enumsspb.WorkflowExecutionState, enumspb.WorkflowExecutionStatus)
GetQueryRegistry() QueryRegistry
HasBufferedEvents() bool
HasInFlightWorkflowTask() bool
HasParentExecution() bool
HasPendingWorkflowTask() bool
HasProcessedOrPendingWorkflowTask() bool
IsCancelRequested() bool
IsCurrentWorkflowGuaranteed() bool
IsSignalRequested(requestID string) bool
IsStickyTaskQueueEnabled() bool
IsWorkflowExecutionRunning() bool
IsResourceDuplicated(resourceDedupKey definition.DeduplicationID) bool
UpdateDuplicatedResource(resourceDedupKey definition.DeduplicationID)
ReplicateActivityInfo(*historyservice.SyncActivityRequest, bool) error
ReplicateActivityTaskCancelRequestedEvent(*historypb.HistoryEvent) error
ReplicateActivityTaskCanceledEvent(*historypb.HistoryEvent) error
ReplicateActivityTaskCompletedEvent(*historypb.HistoryEvent) error
ReplicateActivityTaskFailedEvent(*historypb.HistoryEvent) error
ReplicateActivityTaskScheduledEvent(int64, *historypb.HistoryEvent) (*persistencespb.ActivityInfo, error)
ReplicateActivityTaskStartedEvent(*historypb.HistoryEvent) error
ReplicateActivityTaskTimedOutEvent(*historypb.HistoryEvent) error
ReplicateChildWorkflowExecutionCanceledEvent(*historypb.HistoryEvent) error
ReplicateChildWorkflowExecutionCompletedEvent(*historypb.HistoryEvent) error
ReplicateChildWorkflowExecutionFailedEvent(*historypb.HistoryEvent) error
ReplicateChildWorkflowExecutionStartedEvent(*historypb.HistoryEvent) error
ReplicateChildWorkflowExecutionTerminatedEvent(*historypb.HistoryEvent) error
ReplicateChildWorkflowExecutionTimedOutEvent(*historypb.HistoryEvent) error
ReplicateWorkflowTaskCompletedEvent(*historypb.HistoryEvent) error
ReplicateWorkflowTaskFailedEvent() error
ReplicateWorkflowTaskScheduledEvent(int64, int64, *taskqueuepb.TaskQueue, int32, int32, *time.Time, *time.Time) (*WorkflowTaskInfo, error)
ReplicateWorkflowTaskStartedEvent(*WorkflowTaskInfo, int64, int64, int64, string, time.Time) (*WorkflowTaskInfo, error)
ReplicateWorkflowTaskTimedOutEvent(enumspb.TimeoutType) error
ReplicateExternalWorkflowExecutionCancelRequested(*historypb.HistoryEvent) error
ReplicateExternalWorkflowExecutionSignaled(*historypb.HistoryEvent) error
ReplicateRequestCancelExternalWorkflowExecutionFailedEvent(*historypb.HistoryEvent) error
ReplicateRequestCancelExternalWorkflowExecutionInitiatedEvent(int64, *historypb.HistoryEvent, string) (*persistencespb.RequestCancelInfo, error)
ReplicateSignalExternalWorkflowExecutionFailedEvent(*historypb.HistoryEvent) error
ReplicateSignalExternalWorkflowExecutionInitiatedEvent(int64, *historypb.HistoryEvent, string) (*persistencespb.SignalInfo, error)
ReplicateStartChildWorkflowExecutionFailedEvent(*historypb.HistoryEvent) error
ReplicateStartChildWorkflowExecutionInitiatedEvent(int64, *historypb.HistoryEvent, string) (*persistencespb.ChildExecutionInfo, error)
ReplicateTimerCanceledEvent(*historypb.HistoryEvent) error
ReplicateTimerFiredEvent(*historypb.HistoryEvent) error
ReplicateTimerStartedEvent(*historypb.HistoryEvent) (*persistencespb.TimerInfo, error)
ReplicateTransientWorkflowTaskScheduled() (*WorkflowTaskInfo, error)
ReplicateUpsertWorkflowSearchAttributesEvent(*historypb.HistoryEvent)
ReplicateWorkflowExecutionCancelRequestedEvent(*historypb.HistoryEvent) error
ReplicateWorkflowExecutionCanceledEvent(int64, *historypb.HistoryEvent) error
ReplicateWorkflowExecutionCompletedEvent(int64, *historypb.HistoryEvent) error
ReplicateWorkflowExecutionContinuedAsNewEvent(int64, string, *historypb.HistoryEvent) error
ReplicateWorkflowExecutionFailedEvent(int64, *historypb.HistoryEvent) error
ReplicateWorkflowExecutionSignaled(*historypb.HistoryEvent) error
ReplicateWorkflowExecutionStartedEvent(string, commonpb.WorkflowExecution, string, *historypb.HistoryEvent) error
ReplicateWorkflowExecutionTerminatedEvent(int64, *historypb.HistoryEvent) error
ReplicateWorkflowExecutionTimedoutEvent(int64, *historypb.HistoryEvent) error
SetCurrentBranchToken(branchToken []byte) error
SetHistoryBuilder(hBuilder *HistoryBuilder)
SetHistoryTree(treeID string) error
UpdateActivity(*persistencespb.ActivityInfo) error
UpdateActivityWithTimerHeartbeat(*persistencespb.ActivityInfo, time.Time) error
UpdateActivityProgress(ai *persistencespb.ActivityInfo, request *workflowservice.RecordActivityTaskHeartbeatRequest)
UpdateWorkflowTask(*WorkflowTaskInfo)
UpdateUserTimer(*persistencespb.TimerInfo) error
UpdateCurrentVersion(version int64, forceUpdate bool) error
UpdateWorkflowStateStatus(state enumsspb.WorkflowExecutionState, status enumspb.WorkflowExecutionStatus) error
AddTransferTasks(transferTasks ...persistence.Task)
AddTimerTasks(timerTasks ...persistence.Task)
AddVisibilityTasks(visibilityTasks ...persistence.Task)
SetUpdateCondition(int64, int64)
GetUpdateCondition() (int64, int64)
StartTransaction(entry *cache.NamespaceCacheEntry) (bool, error)
StartTransactionSkipWorkflowTaskFail(entry *cache.NamespaceCacheEntry) error
CloseTransactionAsMutation(now time.Time, transactionPolicy TransactionPolicy) (*persistence.WorkflowMutation, []*persistence.WorkflowEvents, error)
CloseTransactionAsSnapshot(now time.Time, transactionPolicy TransactionPolicy) (*persistence.WorkflowSnapshot, []*persistence.WorkflowEvents, error)
}
)
| 1 | 12,118 | i guess these types & cron / retry specific belong to a dedicated util / struct | temporalio-temporal | go |
@@ -2186,7 +2186,7 @@ class WebElement {
if (!this.driver_.fileDetector_) {
return this.schedule_(
new command.Command(command.Name.SEND_KEYS_TO_ELEMENT).
- setParameter('text', keys).
+ setParameter('text', keys.then(keys => keys.join(''))).
setParameter('value', keys),
'WebElement.sendKeys()');
} | 1 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
/**
* @fileoverview The heart of the WebDriver JavaScript API.
*/
'use strict';
const actions = require('./actions');
const by = require('./by');
const Capabilities = require('./capabilities').Capabilities;
const command = require('./command');
const error = require('./error');
const input = require('./input');
const logging = require('./logging');
const {Session} = require('./session');
const Symbols = require('./symbols');
const promise = require('./promise');
/**
* Defines a condition for use with WebDriver's {@linkplain WebDriver#wait wait
* command}.
*
* @template OUT
*/
class Condition {
/**
* @param {string} message A descriptive error message. Should complete the
* sentence "Waiting [...]"
* @param {function(!WebDriver): OUT} fn The condition function to
* evaluate on each iteration of the wait loop.
*/
constructor(message, fn) {
/** @private {string} */
this.description_ = 'Waiting ' + message;
/** @type {function(!WebDriver): OUT} */
this.fn = fn;
}
/** @return {string} A description of this condition. */
description() {
return this.description_;
}
}
/**
* Defines a condition that will result in a {@link WebElement}.
*
* @extends {Condition<!(WebElement|IThenable<!WebElement>)>}
*/
class WebElementCondition extends Condition {
/**
* @param {string} message A descriptive error message. Should complete the
* sentence "Waiting [...]"
* @param {function(!WebDriver): !(WebElement|IThenable<!WebElement>)}
* fn The condition function to evaluate on each iteration of the wait
* loop.
*/
constructor(message, fn) {
super(message, fn);
}
}
//////////////////////////////////////////////////////////////////////////////
//
// WebDriver
//
//////////////////////////////////////////////////////////////////////////////
/**
* Translates a command to its wire-protocol representation before passing it
* to the given `executor` for execution.
* @param {!command.Executor} executor The executor to use.
* @param {!command.Command} command The command to execute.
* @return {!Promise} A promise that will resolve with the command response.
*/
function executeCommand(executor, command) {
return toWireValue(command.getParameters()).
then(function(parameters) {
command.setParameters(parameters);
return executor.execute(command);
});
}
/**
* Converts an object to its JSON representation in the WebDriver wire protocol.
* When converting values of type object, the following steps will be taken:
* <ol>
* <li>if the object is a WebElement, the return value will be the element's
* server ID
* <li>if the object defines a {@link Symbols.serialize} method, this algorithm
* will be recursively applied to the object's serialized representation
* <li>if the object provides a "toJSON" function, this algorithm will
* recursively be applied to the result of that function
* <li>otherwise, the value of each key will be recursively converted according
* to the rules above.
* </ol>
*
* @param {*} obj The object to convert.
* @return {!Promise<?>} A promise that will resolve to the input value's JSON
* representation.
*/
function toWireValue(obj) {
if (promise.isPromise(obj)) {
return Promise.resolve(obj).then(toWireValue);
}
return Promise.resolve(convertValue(obj));
}
function convertValue(value) {
if (value === void 0 || value === null) {
return value;
}
if (typeof value === 'boolean'
|| typeof value === 'number'
|| typeof value === 'string') {
return value;
}
if (Array.isArray(value)) {
return convertKeys(value);
}
if (typeof value === 'function') {
return '' + value;
}
if (typeof value[Symbols.serialize] === 'function') {
return toWireValue(value[Symbols.serialize]());
} else if (typeof value.toJSON === 'function') {
return toWireValue(value.toJSON());
}
return convertKeys(value);
}
function convertKeys(obj) {
const isArray = Array.isArray(obj);
const numKeys = isArray ? obj.length : Object.keys(obj).length;
const ret = isArray ? new Array(numKeys) : {};
if (!numKeys) {
return Promise.resolve(ret);
}
let numResolved = 0;
function forEachKey(obj, fn) {
if (Array.isArray(obj)) {
for (let i = 0, n = obj.length; i < n; i++) {
fn(obj[i], i);
}
} else {
for (let key in obj) {
fn(obj[key], key);
}
}
}
return new Promise(function(done, reject) {
forEachKey(obj, function(value, key) {
if (promise.isPromise(value)) {
value.then(toWireValue).then(setValue, reject);
} else {
value = convertValue(value);
if (promise.isPromise(value)) {
value.then(toWireValue).then(setValue, reject);
} else {
setValue(value);
}
}
function setValue(value) {
ret[key] = value;
maybeFulfill();
}
});
function maybeFulfill() {
if (++numResolved === numKeys) {
done(ret);
}
}
});
}
/**
* Converts a value from its JSON representation according to the WebDriver wire
* protocol. Any JSON object that defines a WebElement ID will be decoded to a
* {@link WebElement} object. All other values will be passed through as is.
*
* @param {!WebDriver} driver The driver to use as the parent of any unwrapped
* {@link WebElement} values.
* @param {*} value The value to convert.
* @return {*} The converted value.
*/
function fromWireValue(driver, value) {
if (Array.isArray(value)) {
value = value.map(v => fromWireValue(driver, v));
} else if (WebElement.isId(value)) {
let id = WebElement.extractId(value);
value = new WebElement(driver, id);
} else if (value && typeof value === 'object') {
let result = {};
for (let key in value) {
if (value.hasOwnProperty(key)) {
result[key] = fromWireValue(driver, value[key]);
}
}
value = result;
}
return value;
}
/**
* Structural interface for a WebDriver client.
*
* @record
*/
class IWebDriver {
/** @return {!promise.ControlFlow} The control flow used by this instance. */
controlFlow() {}
/**
* Schedules a {@link command.Command} to be executed by this driver's
* {@link command.Executor}.
*
* @param {!command.Command} command The command to schedule.
* @param {string} description A description of the command for debugging.
* @return {!promise.Thenable<T>} A promise that will be resolved
* with the command result.
* @template T
*/
schedule(command, description) {}
/**
* Sets the {@linkplain input.FileDetector file detector} that should be
* used with this instance.
* @param {input.FileDetector} detector The detector to use or {@code null}.
*/
setFileDetector(detector) {}
/**
* @return {!command.Executor} The command executor used by this instance.
*/
getExecutor() {}
/**
* @return {!promise.Thenable<!Session>} A promise for this client's session.
*/
getSession() {}
/**
* @return {!promise.Thenable<!Capabilities>} A promise that will resolve with
* the this instance's capabilities.
*/
getCapabilities() {}
/**
* Terminates the browser session. After calling quit, this instance will be
* invalidated and may no longer be used to issue commands against the
* browser.
*
* @return {!promise.Thenable<void>} A promise that will be resolved when the
* command has completed.
*/
quit() {}
/**
* Creates a new action sequence using this driver. The sequence will not be
* scheduled for execution until {@link actions.ActionSequence#perform} is
* called. Example:
*
* driver.actions().
* mouseDown(element1).
* mouseMove(element2).
* mouseUp().
* perform();
*
* @return {!actions.ActionSequence} A new action sequence for this instance.
*/
actions() {}
/**
* Creates a new touch sequence using this driver. The sequence will not be
* scheduled for execution until {@link actions.TouchSequence#perform} is
* called. Example:
*
* driver.touchActions().
* tap(element1).
* doubleTap(element2).
* perform();
*
* @return {!actions.TouchSequence} A new touch sequence for this instance.
*/
touchActions() {}
/**
* Schedules a command to execute JavaScript in the context of the currently
* selected frame or window. The script fragment will be executed as the body
* of an anonymous function. If the script is provided as a function object,
* that function will be converted to a string for injection into the target
* window.
*
* Any arguments provided in addition to the script will be included as script
* arguments and may be referenced using the {@code arguments} object.
* Arguments may be a boolean, number, string, or {@linkplain WebElement}.
* Arrays and objects may also be used as script arguments as long as each item
* adheres to the types previously mentioned.
*
* The script may refer to any variables accessible from the current window.
* Furthermore, the script will execute in the window's context, thus
* {@code document} may be used to refer to the current document. Any local
* variables will not be available once the script has finished executing,
* though global variables will persist.
*
* If the script has a return value (i.e. if the script contains a return
* statement), then the following steps will be taken for resolving this
* functions return value:
*
* - For a HTML element, the value will resolve to a {@linkplain WebElement}
* - Null and undefined return values will resolve to null</li>
* - Booleans, numbers, and strings will resolve as is</li>
* - Functions will resolve to their string representation</li>
* - For arrays and objects, each member item will be converted according to
* the rules above
*
* @param {!(string|Function)} script The script to execute.
* @param {...*} var_args The arguments to pass to the script.
* @return {!promise.Thenable<T>} A promise that will resolve to the
* scripts return value.
* @template T
*/
executeScript(script, var_args) {}
/**
* Schedules a command to execute asynchronous JavaScript in the context of the
* currently selected frame or window. The script fragment will be executed as
* the body of an anonymous function. If the script is provided as a function
* object, that function will be converted to a string for injection into the
* target window.
*
* Any arguments provided in addition to the script will be included as script
* arguments and may be referenced using the {@code arguments} object.
* Arguments may be a boolean, number, string, or {@code WebElement}.
* Arrays and objects may also be used as script arguments as long as each item
* adheres to the types previously mentioned.
*
* Unlike executing synchronous JavaScript with {@link #executeScript},
* scripts executed with this function must explicitly signal they are finished
* by invoking the provided callback. This callback will always be injected
* into the executed function as the last argument, and thus may be referenced
* with {@code arguments[arguments.length - 1]}. The following steps will be
* taken for resolving this functions return value against the first argument
* to the script's callback function:
*
* - For a HTML element, the value will resolve to a
* {@link WebElement}
* - Null and undefined return values will resolve to null
* - Booleans, numbers, and strings will resolve as is
* - Functions will resolve to their string representation
* - For arrays and objects, each member item will be converted according to
* the rules above
*
* __Example #1:__ Performing a sleep that is synchronized with the currently
* selected window:
*
* var start = new Date().getTime();
* driver.executeAsyncScript(
* 'window.setTimeout(arguments[arguments.length - 1], 500);').
* then(function() {
* console.log(
* 'Elapsed time: ' + (new Date().getTime() - start) + ' ms');
* });
*
* __Example #2:__ Synchronizing a test with an AJAX application:
*
* var button = driver.findElement(By.id('compose-button'));
* button.click();
* driver.executeAsyncScript(
* 'var callback = arguments[arguments.length - 1];' +
* 'mailClient.getComposeWindowWidget().onload(callback);');
* driver.switchTo().frame('composeWidget');
* driver.findElement(By.id('to')).sendKeys('[email protected]');
*
* __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In
* this example, the inject script is specified with a function literal. When
* using this format, the function is converted to a string for injection, so it
* should not reference any symbols not defined in the scope of the page under
* test.
*
* driver.executeAsyncScript(function() {
* var callback = arguments[arguments.length - 1];
* var xhr = new XMLHttpRequest();
* xhr.open("GET", "/resource/data.json", true);
* xhr.onreadystatechange = function() {
* if (xhr.readyState == 4) {
* callback(xhr.responseText);
* }
* };
* xhr.send('');
* }).then(function(str) {
* console.log(JSON.parse(str)['food']);
* });
*
* @param {!(string|Function)} script The script to execute.
* @param {...*} var_args The arguments to pass to the script.
* @return {!promise.Thenable<T>} A promise that will resolve to the
* scripts return value.
* @template T
*/
executeAsyncScript(script, var_args) {}
/**
* Schedules a command to execute a custom function.
* @param {function(...): (T|IThenable<T>)} fn The function to execute.
* @param {Object=} opt_scope The object in whose scope to execute the function.
* @param {...*} var_args Any arguments to pass to the function.
* @return {!promise.Thenable<T>} A promise that will be resolved'
* with the function's result.
* @template T
*/
call(fn, opt_scope, var_args) {}
/**
* Schedules a command to wait for a condition to hold. The condition may be
* specified by a {@link Condition}, as a custom function, or as any
* promise-like thenable.
*
* For a {@link Condition} or function, the wait will repeatedly
* evaluate the condition until it returns a truthy value. If any errors occur
* while evaluating the condition, they will be allowed to propagate. In the
* event a condition returns a {@link promise.Promise promise}, the polling
* loop will wait for it to be resolved and use the resolved value for whether
* the condition has been satisfied. Note the resolution time for a promise
* is factored into whether a wait has timed out.
*
* Note, if the provided condition is a {@link WebElementCondition}, then
* the wait will return a {@link WebElementPromise} that will resolve to the
* element that satisfied the condition.
*
* _Example:_ waiting up to 10 seconds for an element to be present on the
* page.
*
* var button = driver.wait(until.elementLocated(By.id('foo')), 10000);
* button.click();
*
* This function may also be used to block the command flow on the resolution
* of any thenable promise object. When given a promise, the command will
* simply wait for its resolution before completing. A timeout may be provided
* to fail the command if the promise does not resolve before the timeout
* expires.
*
* _Example:_ Suppose you have a function, `startTestServer`, that returns a
* promise for when a server is ready for requests. You can block a WebDriver
* client on this promise with:
*
* var started = startTestServer();
* driver.wait(started, 5 * 1000, 'Server should start within 5 seconds');
* driver.get(getServerUrl());
*
* @param {!(IThenable<T>|
* Condition<T>|
* function(!WebDriver): T)} condition The condition to
* wait on, defined as a promise, condition object, or a function to
* evaluate as a condition.
* @param {number=} opt_timeout How long to wait for the condition to be true.
* @param {string=} opt_message An optional message to use if the wait times
* out.
* @return {!(promise.Thenable<T>|WebElementPromise)} A promise that will be
* resolved with the first truthy value returned by the condition
* function, or rejected if the condition times out. If the input
* input condition is an instance of a {@link WebElementCondition},
* the returned value will be a {@link WebElementPromise}.
* @throws {TypeError} if the provided `condition` is not a valid type.
* @template T
*/
wait(condition, opt_timeout, opt_message) {}
/**
* Schedules a command to make the driver sleep for the given amount of time.
* @param {number} ms The amount of time, in milliseconds, to sleep.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the sleep has finished.
*/
sleep(ms) {}
/**
* Schedules a command to retrieve the current window handle.
* @return {!promise.Thenable<string>} A promise that will be
* resolved with the current window handle.
*/
getWindowHandle() {}
/**
* Schedules a command to retrieve the current list of available window handles.
* @return {!promise.Thenable<!Array<string>>} A promise that will
* be resolved with an array of window handles.
*/
getAllWindowHandles() {}
/**
* Schedules a command to retrieve the current page's source. The page source
* returned is a representation of the underlying DOM: do not expect it to be
* formatted or escaped in the same way as the response sent from the web
* server.
* @return {!promise.Thenable<string>} A promise that will be
* resolved with the current page source.
*/
getPageSource() {}
/**
* Schedules a command to close the current window.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when this command has completed.
*/
close() {}
/**
* Schedules a command to navigate to the given URL.
* @param {string} url The fully qualified URL to open.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the document has finished loading.
*/
get(url) {}
/**
* Schedules a command to retrieve the URL of the current page.
* @return {!promise.Thenable<string>} A promise that will be
* resolved with the current URL.
*/
getCurrentUrl() {}
/**
* Schedules a command to retrieve the current page's title.
* @return {!promise.Thenable<string>} A promise that will be
* resolved with the current page's title.
*/
getTitle() {}
/**
* Schedule a command to find an element on the page. If the element cannot be
* found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned
* by the driver. Unlike other commands, this error cannot be suppressed. In
* other words, scheduling a command to find an element doubles as an assert
* that the element is present on the page. To test whether an element is
* present on the page, use {@link #findElements}:
*
* driver.findElements(By.id('foo'))
* .then(found => console.log('Element found? %s', !!found.length));
*
* The search criteria for an element may be defined using one of the
* factories in the {@link webdriver.By} namespace, or as a short-hand
* {@link webdriver.By.Hash} object. For example, the following two statements
* are equivalent:
*
* var e1 = driver.findElement(By.id('foo'));
* var e2 = driver.findElement({id:'foo'});
*
* You may also provide a custom locator function, which takes as input this
* instance and returns a {@link WebElement}, or a promise that will resolve
* to a WebElement. If the returned promise resolves to an array of
* WebElements, WebDriver will use the first element. For example, to find the
* first visible link on a page, you could write:
*
* var link = driver.findElement(firstVisibleLink);
*
* function firstVisibleLink(driver) {
* var links = driver.findElements(By.tagName('a'));
* return promise.filter(links, function(link) {
* return link.isDisplayed();
* });
* }
*
* @param {!(by.By|Function)} locator The locator to use.
* @return {!WebElementPromise} A WebElement that can be used to issue
* commands against the located element. If the element is not found, the
* element will be invalidated and all scheduled commands aborted.
*/
findElement(locator) {}
/**
* Schedule a command to search for multiple elements on the page.
*
* @param {!(by.By|Function)} locator The locator to use.
* @return {!promise.Thenable<!Array<!WebElement>>} A
* promise that will resolve to an array of WebElements.
*/
findElements(locator) {}
/**
* Schedule a command to take a screenshot. The driver makes a best effort to
* return a screenshot of the following, in order of preference:
*
* 1. Entire page
* 2. Current window
* 3. Visible portion of the current frame
* 4. The entire display containing the browser
*
* @return {!promise.Thenable<string>} A promise that will be
* resolved to the screenshot as a base-64 encoded PNG.
*/
takeScreenshot() {}
/**
* @return {!Options} The options interface for this instance.
*/
manage() {}
/**
* @return {!Navigation} The navigation interface for this instance.
*/
navigate() {}
/**
* @return {!TargetLocator} The target locator interface for this
* instance.
*/
switchTo() {}
}
/**
* Each WebDriver instance provides automated control over a browser session.
*
* @implements {IWebDriver}
*/
class WebDriver {
/**
* @param {!(Session|IThenable<!Session>)} session Either a known session or a
* promise that will be resolved to a session.
* @param {!command.Executor} executor The executor to use when sending
* commands to the browser.
* @param {promise.ControlFlow=} opt_flow The flow to
* schedule commands through. Defaults to the active flow object.
* @param {(function(this: void): ?)=} opt_onQuit A function to call, if any,
* when the session is terminated.
*/
constructor(session, executor, opt_flow, opt_onQuit) {
/** @private {!promise.ControlFlow} */
this.flow_ = opt_flow || promise.controlFlow();
/** @private {!promise.Thenable<!Session>} */
this.session_ = this.flow_.promise(resolve => resolve(session));
/** @private {!command.Executor} */
this.executor_ = executor;
/** @private {input.FileDetector} */
this.fileDetector_ = null;
/** @private @const {(function(this: void): ?|undefined)} */
this.onQuit_ = opt_onQuit;
}
/**
* Creates a new WebDriver client for an existing session.
* @param {!command.Executor} executor Command executor to use when querying
* for session details.
* @param {string} sessionId ID of the session to attach to.
* @param {promise.ControlFlow=} opt_flow The control flow all
* driver commands should execute under. Defaults to the
* {@link promise.controlFlow() currently active} control flow.
* @return {!WebDriver} A new client for the specified session.
*/
static attachToSession(executor, sessionId, opt_flow) {
let flow = opt_flow || promise.controlFlow();
let cmd = new command.Command(command.Name.DESCRIBE_SESSION)
.setParameter('sessionId', sessionId);
let session = flow.execute(
() => executeCommand(executor, cmd).catch(err => {
// The DESCRIBE_SESSION command is not supported by the W3C spec, so
// if we get back an unknown command, just return a session with
// unknown capabilities.
if (err instanceof error.UnknownCommandError) {
return new Session(sessionId, new Capabilities);
}
throw err;
}),
'WebDriver.attachToSession()');
return new WebDriver(session, executor, flow);
}
/**
* Creates a new WebDriver session.
*
* By default, the requested session `capabilities` are merely "desired" and
* the remote end will still create a new session even if it cannot satisfy
* all of the requested capabilities. You can query which capabilities a
* session actually has using the
* {@linkplain #getCapabilities() getCapabilities()} method on the returned
* WebDriver instance.
*
* To define _required capabilities_, provide the `capabilities` as an object
* literal with `required` and `desired` keys. The `desired` key may be
* omitted if all capabilities are required, and vice versa. If the server
* cannot create a session with all of the required capabilities, it will
* return an {@linkplain error.SessionNotCreatedError}.
*
* let required = new Capabilities().set('browserName', 'firefox');
* let desired = new Capabilities().set('version', '45');
* let driver = WebDriver.createSession(executor, {required, desired});
*
* This function will always return a WebDriver instance. If there is an error
* creating the session, such as the aforementioned SessionNotCreatedError,
* the driver will have a rejected {@linkplain #getSession session} promise.
* It is recommended that this promise is left _unhandled_ so it will
* propagate through the {@linkplain promise.ControlFlow control flow} and
* cause subsequent commands to fail.
*
* let required = Capabilities.firefox();
* let driver = WebDriver.createSession(executor, {required});
*
* // If the createSession operation failed, then this command will also
* // also fail, propagating the creation failure.
* driver.get('http://www.google.com').catch(e => console.log(e));
*
* @param {!command.Executor} executor The executor to create the new session
* with.
* @param {(!Capabilities|
* {desired: (Capabilities|undefined),
* required: (Capabilities|undefined)})} capabilities The desired
* capabilities for the new session.
* @param {promise.ControlFlow=} opt_flow The control flow all driver
* commands should execute under, including the initial session creation.
* Defaults to the {@link promise.controlFlow() currently active}
* control flow.
* @param {(function(new: WebDriver,
* !IThenable<!Session>,
* !command.Executor,
* promise.ControlFlow=))=} opt_ctor
* A reference to the constructor of the specific type of WebDriver client
* to instantiate. Will create a vanilla {@linkplain WebDriver} instance
* if a constructor is not provided.
* @param {(function(this: void): ?)=} opt_onQuit A callback to invoke when
* the newly created session is terminated. This should be used to clean
* up any resources associated with the session.
* @return {!WebDriver} The driver for the newly created session.
*/
static createSession(
executor, capabilities, opt_flow, opt_ctor, opt_onQuit) {
let flow = opt_flow || promise.controlFlow();
let cmd = new command.Command(command.Name.NEW_SESSION);
if (capabilities && (capabilities.desired || capabilities.required)) {
cmd.setParameter('desiredCapabilities', capabilities.desired);
cmd.setParameter('requiredCapabilities', capabilities.required);
} else {
cmd.setParameter('desiredCapabilities', capabilities);
}
let session = flow.execute(
() => executeCommand(executor, cmd),
'WebDriver.createSession()');
if (typeof opt_onQuit === 'function') {
session = session.catch(err => {
return Promise.resolve(opt_onQuit.call(void 0)).then(_ => {throw err;});
});
}
const ctor = opt_ctor || WebDriver;
return new ctor(session, executor, flow, opt_onQuit);
}
/** @override */
controlFlow() {
return this.flow_;
}
/** @override */
schedule(command, description) {
command.setParameter('sessionId', this.session_);
// If any of the command parameters are rejected promises, those
// rejections may be reported as unhandled before the control flow
// attempts to execute the command. To ensure parameters errors
// propagate through the command itself, we resolve all of the
// command parameters now, but suppress any errors until the ControlFlow
// actually executes the command. This addresses scenarios like catching
// an element not found error in:
//
// driver.findElement(By.id('foo')).click().catch(function(e) {
// if (e instanceof NoSuchElementError) {
// // Do something.
// }
// });
var prepCommand = toWireValue(command.getParameters());
prepCommand.catch(function() {});
var flow = this.flow_;
var executor = this.executor_;
return flow.execute(() => {
// Retrieve resolved command parameters; any previously suppressed errors
// will now propagate up through the control flow as part of the command
// execution.
return prepCommand.then(function(parameters) {
command.setParameters(parameters);
return executor.execute(command);
}).then(value => fromWireValue(this, value));
}, description);
}
/** @override */
setFileDetector(detector) {
this.fileDetector_ = detector;
}
/** @override */
getExecutor() {
return this.executor_;
}
/** @override */
getSession() {
return this.session_;
}
/** @override */
getCapabilities() {
return this.session_.then(s => s.getCapabilities());
}
/** @override */
quit() {
var result = this.schedule(
new command.Command(command.Name.QUIT),
'WebDriver.quit()');
// Delete our session ID when the quit command finishes; this will allow us
// to throw an error when attempting to use a driver post-quit.
return /** @type {!promise.Thenable} */(promise.finally(result, () => {
this.session_ = this.flow_.promise((_, reject) => {
reject(new error.NoSuchSessionError(
'This driver instance does not have a valid session ID ' +
'(did you call WebDriver.quit()?) and may no longer be used.'));
});
// Only want the session rejection to bubble if accessed.
this.session_.catch(function() {});
if (this.onQuit_) {
return this.onQuit_.call(void 0);
}
}));
}
/** @override */
actions() {
return new actions.ActionSequence(this);
}
/** @override */
touchActions() {
return new actions.TouchSequence(this);
}
/** @override */
executeScript(script, var_args) {
if (typeof script === 'function') {
script = 'return (' + script + ').apply(null, arguments);';
}
let args =
arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : [];
return this.schedule(
new command.Command(command.Name.EXECUTE_SCRIPT).
setParameter('script', script).
setParameter('args', args),
'WebDriver.executeScript()');
}
/** @override */
executeAsyncScript(script, var_args) {
if (typeof script === 'function') {
script = 'return (' + script + ').apply(null, arguments);';
}
let args = Array.prototype.slice.call(arguments, 1);
return this.schedule(
new command.Command(command.Name.EXECUTE_ASYNC_SCRIPT).
setParameter('script', script).
setParameter('args', args),
'WebDriver.executeScript()');
}
/** @override */
call(fn, opt_scope, var_args) {
let args = Array.prototype.slice.call(arguments, 2);
return this.flow_.execute(function() {
return promise.fullyResolved(args).then(function(args) {
if (promise.isGenerator(fn)) {
args.unshift(fn, opt_scope);
return promise.consume.apply(null, args);
}
return fn.apply(opt_scope, args);
});
}, 'WebDriver.call(' + (fn.name || 'function') + ')');
}
/** @override */
wait(condition, opt_timeout, opt_message) {
if (promise.isPromise(condition)) {
return this.flow_.wait(
/** @type {!IThenable} */(condition),
opt_timeout, opt_message);
}
var message = opt_message;
var fn = /** @type {!Function} */(condition);
if (condition instanceof Condition) {
message = message || condition.description();
fn = condition.fn;
}
if (typeof fn !== 'function') {
throw TypeError(
'Wait condition must be a promise-like object, function, or a '
+ 'Condition object');
}
var driver = this;
var result = this.flow_.wait(function() {
if (promise.isGenerator(fn)) {
return promise.consume(fn, null, [driver]);
}
return fn(driver);
}, opt_timeout, message);
if (condition instanceof WebElementCondition) {
result = new WebElementPromise(this, result.then(function(value) {
if (!(value instanceof WebElement)) {
throw TypeError(
'WebElementCondition did not resolve to a WebElement: '
+ Object.prototype.toString.call(value));
}
return value;
}));
}
return result;
}
/** @override */
sleep(ms) {
return this.flow_.timeout(ms, 'WebDriver.sleep(' + ms + ')');
}
/** @override */
getWindowHandle() {
return this.schedule(
new command.Command(command.Name.GET_CURRENT_WINDOW_HANDLE),
'WebDriver.getWindowHandle()');
}
/** @override */
getAllWindowHandles() {
return this.schedule(
new command.Command(command.Name.GET_WINDOW_HANDLES),
'WebDriver.getAllWindowHandles()');
}
/** @override */
getPageSource() {
return this.schedule(
new command.Command(command.Name.GET_PAGE_SOURCE),
'WebDriver.getPageSource()');
}
/** @override */
close() {
return this.schedule(new command.Command(command.Name.CLOSE),
'WebDriver.close()');
}
/** @override */
get(url) {
return this.navigate().to(url);
}
/** @override */
getCurrentUrl() {
return this.schedule(
new command.Command(command.Name.GET_CURRENT_URL),
'WebDriver.getCurrentUrl()');
}
/** @override */
getTitle() {
return this.schedule(new command.Command(command.Name.GET_TITLE),
'WebDriver.getTitle()');
}
/** @override */
findElement(locator) {
let id;
locator = by.checkedLocator(locator);
if (typeof locator === 'function') {
id = this.findElementInternal_(locator, this);
} else {
let cmd = new command.Command(command.Name.FIND_ELEMENT).
setParameter('using', locator.using).
setParameter('value', locator.value);
id = this.schedule(cmd, 'WebDriver.findElement(' + locator + ')');
}
return new WebElementPromise(this, id);
}
/**
* @param {!Function} locatorFn The locator function to use.
* @param {!(WebDriver|WebElement)} context The search
* context.
* @return {!promise.Thenable<!WebElement>} A
* promise that will resolve to a list of WebElements.
* @private
*/
findElementInternal_(locatorFn, context) {
return this.call(() => locatorFn(context)).then(function(result) {
if (Array.isArray(result)) {
result = result[0];
}
if (!(result instanceof WebElement)) {
throw new TypeError('Custom locator did not return a WebElement');
}
return result;
});
}
/** @override */
findElements(locator) {
locator = by.checkedLocator(locator);
if (typeof locator === 'function') {
return this.findElementsInternal_(locator, this);
} else {
let cmd = new command.Command(command.Name.FIND_ELEMENTS).
setParameter('using', locator.using).
setParameter('value', locator.value);
let res = this.schedule(cmd, 'WebDriver.findElements(' + locator + ')');
return res.catch(function(e) {
if (e instanceof error.NoSuchElementError) {
return [];
}
throw e;
});
}
}
/**
* @param {!Function} locatorFn The locator function to use.
* @param {!(WebDriver|WebElement)} context The search context.
* @return {!promise.Thenable<!Array<!WebElement>>} A promise that
* will resolve to an array of WebElements.
* @private
*/
findElementsInternal_(locatorFn, context) {
return this.call(() => locatorFn(context)).then(function(result) {
if (result instanceof WebElement) {
return [result];
}
if (!Array.isArray(result)) {
return [];
}
return result.filter(function(item) {
return item instanceof WebElement;
});
});
}
/** @override */
takeScreenshot() {
return this.schedule(new command.Command(command.Name.SCREENSHOT),
'WebDriver.takeScreenshot()');
}
/** @override */
manage() {
return new Options(this);
}
/** @override */
navigate() {
return new Navigation(this);
}
/** @override */
switchTo() {
return new TargetLocator(this);
}
}
/**
* Interface for navigating back and forth in the browser history.
*
* This class should never be instantiated directly. Instead, obtain an instance
* with
*
* webdriver.navigate()
*
* @see WebDriver#navigate()
*/
class Navigation {
/**
* @param {!WebDriver} driver The parent driver.
* @private
*/
constructor(driver) {
/** @private {!WebDriver} */
this.driver_ = driver;
}
/**
* Schedules a command to navigate to a new URL.
* @param {string} url The URL to navigate to.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the URL has been loaded.
*/
to(url) {
return this.driver_.schedule(
new command.Command(command.Name.GET).
setParameter('url', url),
'WebDriver.navigate().to(' + url + ')');
}
/**
* Schedules a command to move backwards in the browser history.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the navigation event has completed.
*/
back() {
return this.driver_.schedule(
new command.Command(command.Name.GO_BACK),
'WebDriver.navigate().back()');
}
/**
* Schedules a command to move forwards in the browser history.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the navigation event has completed.
*/
forward() {
return this.driver_.schedule(
new command.Command(command.Name.GO_FORWARD),
'WebDriver.navigate().forward()');
}
/**
* Schedules a command to refresh the current page.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the navigation event has completed.
*/
refresh() {
return this.driver_.schedule(
new command.Command(command.Name.REFRESH),
'WebDriver.navigate().refresh()');
}
}
/**
* Provides methods for managing browser and driver state.
*
* This class should never be instantiated directly. Instead, obtain an instance
* with {@linkplain WebDriver#manage() webdriver.manage()}.
*/
class Options {
/**
* @param {!WebDriver} driver The parent driver.
* @private
*/
constructor(driver) {
/** @private {!WebDriver} */
this.driver_ = driver;
}
/**
* Schedules a command to add a cookie.
*
* __Sample Usage:__
*
* // Set a basic cookie.
* driver.options().addCookie({name: 'foo', value: 'bar'});
*
* // Set a cookie that expires in 10 minutes.
* let expiry = new Date(Date.now() + (10 * 60 * 1000));
* driver.options().addCookie({name: 'foo', value: 'bar', expiry});
*
* // The cookie expiration may also be specified in seconds since epoch.
* driver.options().addCookie({
* name: 'foo',
* value: 'bar',
* expiry: Math.floor(Date.now() / 1000)
* });
*
* @param {!Options.Cookie} spec Defines the cookie to add.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the cookie has been added to the page.
* @throws {error.InvalidArgumentError} if any of the cookie parameters are
* invalid.
* @throws {TypeError} if `spec` is not a cookie object.
*/
addCookie(spec) {
if (!spec || typeof spec !== 'object') {
throw TypeError('addCookie called with non-cookie parameter');
}
// We do not allow '=' or ';' in the name.
let name = spec.name;
if (/[;=]/.test(name)) {
throw new error.InvalidArgumentError(
'Invalid cookie name "' + name + '"');
}
// We do not allow ';' in value.
let value = spec.value;
if (/;/.test(value)) {
throw new error.InvalidArgumentError(
'Invalid cookie value "' + value + '"');
}
let cookieString = name + '=' + value +
(spec.domain ? ';domain=' + spec.domain : '') +
(spec.path ? ';path=' + spec.path : '') +
(spec.secure ? ';secure' : '');
let expiry;
if (typeof spec.expiry === 'number') {
expiry = Math.floor(spec.expiry);
cookieString += ';expires=' + new Date(spec.expiry * 1000).toUTCString();
} else if (spec.expiry instanceof Date) {
let date = /** @type {!Date} */(spec.expiry);
expiry = Math.floor(date.getTime() / 1000);
cookieString += ';expires=' + date.toUTCString();
}
return this.driver_.schedule(
new command.Command(command.Name.ADD_COOKIE).
setParameter('cookie', {
'name': name,
'value': value,
'path': spec.path,
'domain': spec.domain,
'secure': !!spec.secure,
'expiry': expiry
}),
'WebDriver.manage().addCookie(' + cookieString + ')');
}
/**
* Schedules a command to delete all cookies visible to the current page.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when all cookies have been deleted.
*/
deleteAllCookies() {
return this.driver_.schedule(
new command.Command(command.Name.DELETE_ALL_COOKIES),
'WebDriver.manage().deleteAllCookies()');
}
/**
* Schedules a command to delete the cookie with the given name. This command
* is a no-op if there is no cookie with the given name visible to the current
* page.
* @param {string} name The name of the cookie to delete.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the cookie has been deleted.
*/
deleteCookie(name) {
return this.driver_.schedule(
new command.Command(command.Name.DELETE_COOKIE).
setParameter('name', name),
'WebDriver.manage().deleteCookie(' + name + ')');
}
/**
* Schedules a command to retrieve all cookies visible to the current page.
* Each cookie will be returned as a JSON object as described by the WebDriver
* wire protocol.
* @return {!promise.Thenable<!Array<!Options.Cookie>>} A promise that will be
* resolved with the cookies visible to the current browsing context.
*/
getCookies() {
return this.driver_.schedule(
new command.Command(command.Name.GET_ALL_COOKIES),
'WebDriver.manage().getCookies()');
}
/**
* Schedules a command to retrieve the cookie with the given name. Returns null
* if there is no such cookie. The cookie will be returned as a JSON object as
* described by the WebDriver wire protocol.
*
* @param {string} name The name of the cookie to retrieve.
* @return {!promise.Thenable<?Options.Cookie>} A promise that will be resolved
* with the named cookie, or `null` if there is no such cookie.
*/
getCookie(name) {
return this.getCookies().then(function(cookies) {
for (let cookie of cookies) {
if (cookie && cookie['name'] === name) {
return cookie;
}
}
return null;
});
}
/**
* Schedules a command to fetch the timeouts currently configured for the
* current session.
*
* @return {!promise.Thenable<{script: number,
* pageLoad: number,
* implicit: number}>} A promise that will be
* resolved with the timeouts currently configured for the current
* session.
* @see #setTimeouts()
*/
getTimeouts() {
return this.driver_.schedule(
new command.Command(command.Name.GET_TIMEOUT),
`WebDriver.manage().getTimeouts()`)
}
/**
* Schedules a command to set timeout durations associated with the current
* session.
*
* The following timeouts are supported (all timeouts are specified in
* milliseconds):
*
* - `implicit` specifies the maximum amount of time to wait for an element
* locator to succeed when {@linkplain WebDriver#findElement locating}
* {@linkplain WebDriver#findElements elements} on the page.
* Defaults to 0 milliseconds.
*
* - `pageLoad` specifies the maximum amount of time to wait for a page to
* finishing loading. Defaults to 300000 milliseconds.
*
* - `script` specifies the maximum amount of time to wait for an
* {@linkplain WebDriver#executeScript evaluated script} to run. If set to
* `null`, the script timeout will be indefinite.
* Defaults to 30000 milliseconds.
*
* @param {{script: (number|null|undefined),
* pageLoad: (number|null|undefined),
* implicit: (number|null|undefined)}} conf
* The desired timeout configuration.
* @return {!promise.Thenable<void>} A promise that will be resolved when the
* timeouts have been set.
* @throws {!TypeError} if an invalid options object is provided.
* @see #getTimeouts()
* @see <https://w3c.github.io/webdriver/webdriver-spec.html#dfn-set-timeouts>
*/
setTimeouts({script, pageLoad, implicit} = {}) {
let cmd = new command.Command(command.Name.SET_TIMEOUT);
let valid = false;
function setParam(key, value) {
if (value === null || typeof value === 'number') {
valid = true;
cmd.setParameter(key, value);
} else if (typeof value !== 'undefined') {
throw TypeError(
'invalid timeouts configuration:'
+ ` expected "${key}" to be a number, got ${typeof value}`);
}
}
setParam('implicit', implicit);
setParam('pageLoad', pageLoad);
setParam('script', script);
if (valid) {
return this.driver_.schedule(cmd, `WebDriver.manage().setTimeouts()`)
.catch(() => {
// Fallback to the legacy method.
let cmds = [];
if (typeof script === 'number') {
cmds.push(legacyTimeout(this.driver_, 'script', script));
}
if (typeof implicit === 'number') {
cmds.push(legacyTimeout(this.driver_, 'implicit', implicit));
}
if (typeof pageLoad === 'number') {
cmds.push(legacyTimeout(this.driver_, 'page load', pageLoad));
}
return Promise.all(cmds);
});
}
throw TypeError('no timeouts specified');
}
/**
* @return {!Logs} The interface for managing driver
* logs.
*/
logs() {
return new Logs(this.driver_);
}
/**
* @return {!Timeouts} The interface for managing driver timeouts.
* @deprecated Use {@link #setTimeouts()} instead.
*/
timeouts() {
return new Timeouts(this.driver_);
}
/**
* @return {!Window} The interface for managing the current window.
*/
window() {
return new Window(this.driver_);
}
}
/**
* @param {!WebDriver} driver
* @param {string} type
* @param {number} ms
* @return {!promise.Thenable<void>}
*/
function legacyTimeout(driver, type, ms) {
return driver.schedule(
new command.Command(command.Name.SET_TIMEOUT)
.setParameter('type', type)
.setParameter('ms', ms),
`WebDriver.manage().setTimeouts({${type}: ${ms}})`);
}
/**
* A record object describing a browser cookie.
*
* @record
*/
Options.Cookie = function() {};
/**
* The name of the cookie.
*
* @type {string}
*/
Options.Cookie.prototype.name;
/**
* The cookie value.
*
* @type {string}
*/
Options.Cookie.prototype.value;
/**
* The cookie path. Defaults to "/" when adding a cookie.
*
* @type {(string|undefined)}
*/
Options.Cookie.prototype.path;
/**
* The domain the cookie is visible to. Defaults to the current browsing
* context's document's URL when adding a cookie.
*
* @type {(string|undefined)}
*/
Options.Cookie.prototype.domain;
/**
* Whether the cookie is a secure cookie. Defaults to false when adding a new
* cookie.
*
* @type {(boolean|undefined)}
*/
Options.Cookie.prototype.secure;
/**
* Whether the cookie is an HTTP only cookie. Defaults to false when adding a
* new cookie.
*
* @type {(boolean|undefined)}
*/
Options.Cookie.prototype.httpOnly;
/**
* When the cookie expires.
*
* When {@linkplain Options#addCookie() adding a cookie}, this may be specified
* in _seconds_ since Unix epoch (January 1, 1970). The expiry will default to
* 20 years in the future if omitted.
*
* The expiry is always returned in seconds since epoch when
* {@linkplain Options#getCookies() retrieving cookies} from the browser.
*
* @type {(!Date|number|undefined)}
*/
Options.Cookie.prototype.expiry;
/**
* An interface for managing timeout behavior for WebDriver instances.
*
* This class should never be instantiated directly. Instead, obtain an instance
* with
*
* webdriver.manage().timeouts()
*
* @deprecated This has been deprecated in favor of
* {@link Options#setTimeouts()}, which supports setting multiple timeouts
* at once.
* @see WebDriver#manage()
* @see Options#timeouts()
*/
class Timeouts {
/**
* @param {!WebDriver} driver The parent driver.
* @private
*/
constructor(driver) {
/** @private {!WebDriver} */
this.driver_ = driver;
}
/**
* Specifies the amount of time the driver should wait when searching for an
* element if it is not immediately present.
*
* When searching for a single element, the driver should poll the page
* until the element has been found, or this timeout expires before failing
* with a {@link bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching
* for multiple elements, the driver should poll the page until at least one
* element has been found or this timeout has expired.
*
* Setting the wait timeout to 0 (its default value), disables implicit
* waiting.
*
* Increasing the implicit wait timeout should be used judiciously as it
* will have an adverse effect on test run time, especially when used with
* slower location strategies like XPath.
*
* @param {number} ms The amount of time to wait, in milliseconds.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the implicit wait timeout has been set.
* @deprecated Use {@link Options#setTimeouts()
* driver.manage().setTimeouts({implicit: ms})}.
*/
implicitlyWait(ms) {
return this.driver_.manage().setTimeouts({implicit: ms});
}
/**
* Sets the amount of time to wait, in milliseconds, for an asynchronous
* script to finish execution before returning an error. If the timeout is
* less than or equal to 0, the script will be allowed to run indefinitely.
*
* @param {number} ms The amount of time to wait, in milliseconds.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the script timeout has been set.
* @deprecated Use {@link Options#setTimeouts()
* driver.manage().setTimeouts({script: ms})}.
*/
setScriptTimeout(ms) {
return this.driver_.manage().setTimeouts({script: ms});
}
/**
* Sets the amount of time to wait for a page load to complete before
* returning an error. If the timeout is negative, page loads may be
* indefinite.
*
* @param {number} ms The amount of time to wait, in milliseconds.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the timeout has been set.
* @deprecated Use {@link Options#setTimeouts()
* driver.manage().setTimeouts({pageLoad: ms})}.
*/
pageLoadTimeout(ms) {
return this.driver_.manage().setTimeouts({pageLoad: ms});
}
}
/**
* An interface for managing the current window.
*
* This class should never be instantiated directly. Instead, obtain an instance
* with
*
* webdriver.manage().window()
*
* @see WebDriver#manage()
* @see Options#window()
*/
class Window {
/**
* @param {!WebDriver} driver The parent driver.
* @private
*/
constructor(driver) {
/** @private {!WebDriver} */
this.driver_ = driver;
}
/**
* Retrieves the window's current position, relative to the top left corner of
* the screen.
* @return {!promise.Thenable<{x: number, y: number}>} A promise
* that will be resolved with the window's position in the form of a
* {x:number, y:number} object literal.
*/
getPosition() {
return this.driver_.schedule(
new command.Command(command.Name.GET_WINDOW_POSITION).
setParameter('windowHandle', 'current'),
'WebDriver.manage().window().getPosition()');
}
/**
* Repositions the current window.
* @param {number} x The desired horizontal position, relative to the left
* side of the screen.
* @param {number} y The desired vertical position, relative to the top of the
* of the screen.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the command has completed.
*/
setPosition(x, y) {
return this.driver_.schedule(
new command.Command(command.Name.SET_WINDOW_POSITION).
setParameter('windowHandle', 'current').
setParameter('x', x).
setParameter('y', y),
'WebDriver.manage().window().setPosition(' + x + ', ' + y + ')');
}
/**
* Retrieves the window's current size.
* @return {!promise.Thenable<{width: number, height: number}>} A
* promise that will be resolved with the window's size in the form of a
* {width:number, height:number} object literal.
*/
getSize() {
return this.driver_.schedule(
new command.Command(command.Name.GET_WINDOW_SIZE).
setParameter('windowHandle', 'current'),
'WebDriver.manage().window().getSize()');
}
/**
* Resizes the current window.
* @param {number} width The desired window width.
* @param {number} height The desired window height.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the command has completed.
*/
setSize(width, height) {
return this.driver_.schedule(
new command.Command(command.Name.SET_WINDOW_SIZE).
setParameter('windowHandle', 'current').
setParameter('width', width).
setParameter('height', height),
'WebDriver.manage().window().setSize(' + width + ', ' + height + ')');
}
/**
* Maximizes the current window.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the command has completed.
*/
maximize() {
return this.driver_.schedule(
new command.Command(command.Name.MAXIMIZE_WINDOW).
setParameter('windowHandle', 'current'),
'WebDriver.manage().window().maximize()');
}
}
/**
* Interface for managing WebDriver log records.
*
* This class should never be instantiated directly. Instead, obtain an
* instance with
*
* webdriver.manage().logs()
*
* @see WebDriver#manage()
* @see Options#logs()
*/
class Logs {
/**
* @param {!WebDriver} driver The parent driver.
* @private
*/
constructor(driver) {
/** @private {!WebDriver} */
this.driver_ = driver;
}
/**
* Fetches available log entries for the given type.
*
* Note that log buffers are reset after each call, meaning that available
* log entries correspond to those entries not yet returned for a given log
* type. In practice, this means that this call will return the available log
* entries since the last call, or from the start of the session.
*
* @param {!logging.Type} type The desired log type.
* @return {!promise.Thenable<!Array.<!logging.Entry>>} A
* promise that will resolve to a list of log entries for the specified
* type.
*/
get(type) {
let cmd = new command.Command(command.Name.GET_LOG).
setParameter('type', type);
return this.driver_.schedule(
cmd, 'WebDriver.manage().logs().get(' + type + ')').
then(function(entries) {
return entries.map(function(entry) {
if (!(entry instanceof logging.Entry)) {
return new logging.Entry(
entry['level'], entry['message'], entry['timestamp'],
entry['type']);
}
return entry;
});
});
}
/**
* Retrieves the log types available to this driver.
* @return {!promise.Thenable<!Array<!logging.Type>>} A
* promise that will resolve to a list of available log types.
*/
getAvailableLogTypes() {
return this.driver_.schedule(
new command.Command(command.Name.GET_AVAILABLE_LOG_TYPES),
'WebDriver.manage().logs().getAvailableLogTypes()');
}
}
/**
* An interface for changing the focus of the driver to another frame or window.
*
* This class should never be instantiated directly. Instead, obtain an
* instance with
*
* webdriver.switchTo()
*
* @see WebDriver#switchTo()
*/
class TargetLocator {
/**
* @param {!WebDriver} driver The parent driver.
* @private
*/
constructor(driver) {
/** @private {!WebDriver} */
this.driver_ = driver;
}
/**
* Schedules a command retrieve the {@code document.activeElement} element on
* the current document, or {@code document.body} if activeElement is not
* available.
* @return {!WebElementPromise} The active element.
*/
activeElement() {
var id = this.driver_.schedule(
new command.Command(command.Name.GET_ACTIVE_ELEMENT),
'WebDriver.switchTo().activeElement()');
return new WebElementPromise(this.driver_, id);
}
/**
* Schedules a command to switch focus of all future commands to the topmost
* frame on the page.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the driver has changed focus to the default content.
*/
defaultContent() {
return this.driver_.schedule(
new command.Command(command.Name.SWITCH_TO_FRAME).
setParameter('id', null),
'WebDriver.switchTo().defaultContent()');
}
/**
* Schedules a command to switch the focus of all future commands to another
* frame on the page. The target frame may be specified as one of the
* following:
*
* - A number that specifies a (zero-based) index into [window.frames](
* https://developer.mozilla.org/en-US/docs/Web/API/Window.frames).
* - A {@link WebElement} reference, which correspond to a `frame` or `iframe`
* DOM element.
* - The `null` value, to select the topmost frame on the page. Passing `null`
* is the same as calling {@link #defaultContent defaultContent()}.
*
* If the specified frame can not be found, the returned promise will be
* rejected with a {@linkplain error.NoSuchFrameError}.
*
* @param {(number|WebElement|null)} id The frame locator.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the driver has changed focus to the specified frame.
*/
frame(id) {
return this.driver_.schedule(
new command.Command(command.Name.SWITCH_TO_FRAME).
setParameter('id', id),
'WebDriver.switchTo().frame(' + id + ')');
}
/**
* Schedules a command to switch the focus of all future commands to another
* window. Windows may be specified by their {@code window.name} attribute or
* by its handle (as returned by {@link WebDriver#getWindowHandles}).
*
* If the specified window cannot be found, the returned promise will be
* rejected with a {@linkplain error.NoSuchWindowError}.
*
* @param {string} nameOrHandle The name or window handle of the window to
* switch focus to.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the driver has changed focus to the specified window.
*/
window(nameOrHandle) {
return this.driver_.schedule(
new command.Command(command.Name.SWITCH_TO_WINDOW).
// "name" supports the legacy drivers. "handle" is the W3C
// compliant parameter.
setParameter('name', nameOrHandle).
setParameter('handle', nameOrHandle),
'WebDriver.switchTo().window(' + nameOrHandle + ')');
}
/**
* Schedules a command to change focus to the active modal dialog, such as
* those opened by `window.alert()`, `window.confirm()`, and
* `window.prompt()`. The returned promise will be rejected with a
* {@linkplain error.NoSuchAlertError} if there are no open alerts.
*
* @return {!AlertPromise} The open alert.
*/
alert() {
var text = this.driver_.schedule(
new command.Command(command.Name.GET_ALERT_TEXT),
'WebDriver.switchTo().alert()');
var driver = this.driver_;
return new AlertPromise(driver, text.then(function(text) {
return new Alert(driver, text);
}));
}
}
//////////////////////////////////////////////////////////////////////////////
//
// WebElement
//
//////////////////////////////////////////////////////////////////////////////
const LEGACY_ELEMENT_ID_KEY = 'ELEMENT';
const ELEMENT_ID_KEY = 'element-6066-11e4-a52e-4f735466cecf';
/**
* Represents a DOM element. WebElements can be found by searching from the
* document root using a {@link WebDriver} instance, or by searching
* under another WebElement:
*
* driver.get('http://www.google.com');
* var searchForm = driver.findElement(By.tagName('form'));
* var searchBox = searchForm.findElement(By.name('q'));
* searchBox.sendKeys('webdriver');
*/
class WebElement {
/**
* @param {!WebDriver} driver the parent WebDriver instance for this element.
* @param {(!IThenable<string>|string)} id The server-assigned opaque ID for
* the underlying DOM element.
*/
constructor(driver, id) {
/** @private {!WebDriver} */
this.driver_ = driver;
/** @private {!promise.Thenable<string>} */
this.id_ = driver.controlFlow().promise(resolve => resolve(id));
}
/**
* @param {string} id The raw ID.
* @param {boolean=} opt_noLegacy Whether to exclude the legacy element key.
* @return {!Object} The element ID for use with WebDriver's wire protocol.
*/
static buildId(id, opt_noLegacy) {
return opt_noLegacy
? {[ELEMENT_ID_KEY]: id}
: {[ELEMENT_ID_KEY]: id, [LEGACY_ELEMENT_ID_KEY]: id};
}
/**
* Extracts the encoded WebElement ID from the object.
*
* @param {?} obj The object to extract the ID from.
* @return {string} the extracted ID.
* @throws {TypeError} if the object is not a valid encoded ID.
*/
static extractId(obj) {
if (obj && typeof obj === 'object') {
if (typeof obj[ELEMENT_ID_KEY] === 'string') {
return obj[ELEMENT_ID_KEY];
} else if (typeof obj[LEGACY_ELEMENT_ID_KEY] === 'string') {
return obj[LEGACY_ELEMENT_ID_KEY];
}
}
throw new TypeError('object is not a WebElement ID');
}
/**
* @param {?} obj the object to test.
* @return {boolean} whether the object is a valid encoded WebElement ID.
*/
static isId(obj) {
return obj && typeof obj === 'object'
&& (typeof obj[ELEMENT_ID_KEY] === 'string'
|| typeof obj[LEGACY_ELEMENT_ID_KEY] === 'string');
}
/**
* Compares two WebElements for equality.
*
* @param {!WebElement} a A WebElement.
* @param {!WebElement} b A WebElement.
* @return {!promise.Thenable<boolean>} A promise that will be
* resolved to whether the two WebElements are equal.
*/
static equals(a, b) {
if (a === b) {
return a.driver_.controlFlow().promise(resolve => resolve(true));
}
let ids = [a.getId(), b.getId()];
return promise.all(ids).then(function(ids) {
// If the two element's have the same ID, they should be considered
// equal. Otherwise, they may still be equivalent, but we'll need to
// ask the server to check for us.
if (ids[0] === ids[1]) {
return true;
}
let cmd = new command.Command(command.Name.ELEMENT_EQUALS);
cmd.setParameter('id', ids[0]);
cmd.setParameter('other', ids[1]);
return a.driver_.schedule(cmd, 'WebElement.equals()');
});
}
/** @return {!WebDriver} The parent driver for this instance. */
getDriver() {
return this.driver_;
}
/**
* @return {!promise.Thenable<string>} A promise that resolves to
* the server-assigned opaque ID assigned to this element.
*/
getId() {
return this.id_;
}
/**
* @return {!Object} Returns the serialized representation of this WebElement.
*/
[Symbols.serialize]() {
return this.getId().then(WebElement.buildId);
}
/**
* Schedules a command that targets this element with the parent WebDriver
* instance. Will ensure this element's ID is included in the command
* parameters under the "id" key.
*
* @param {!command.Command} command The command to schedule.
* @param {string} description A description of the command for debugging.
* @return {!promise.Thenable<T>} A promise that will be resolved
* with the command result.
* @template T
* @see WebDriver#schedule
* @private
*/
schedule_(command, description) {
command.setParameter('id', this);
return this.driver_.schedule(command, description);
}
/**
* Schedule a command to find a descendant of this element. If the element
* cannot be found, the returned promise will be rejected with a
* {@linkplain error.NoSuchElementError NoSuchElementError}.
*
* The search criteria for an element may be defined using one of the static
* factories on the {@link by.By} class, or as a short-hand
* {@link ./by.ByHash} object. For example, the following two statements
* are equivalent:
*
* var e1 = element.findElement(By.id('foo'));
* var e2 = element.findElement({id:'foo'});
*
* You may also provide a custom locator function, which takes as input this
* instance and returns a {@link WebElement}, or a promise that will resolve
* to a WebElement. If the returned promise resolves to an array of
* WebElements, WebDriver will use the first element. For example, to find the
* first visible link on a page, you could write:
*
* var link = element.findElement(firstVisibleLink);
*
* function firstVisibleLink(element) {
* var links = element.findElements(By.tagName('a'));
* return promise.filter(links, function(link) {
* return link.isDisplayed();
* });
* }
*
* @param {!(by.By|Function)} locator The locator strategy to use when
* searching for the element.
* @return {!WebElementPromise} A WebElement that can be used to issue
* commands against the located element. If the element is not found, the
* element will be invalidated and all scheduled commands aborted.
*/
findElement(locator) {
locator = by.checkedLocator(locator);
let id;
if (typeof locator === 'function') {
id = this.driver_.findElementInternal_(locator, this);
} else {
let cmd = new command.Command(
command.Name.FIND_CHILD_ELEMENT).
setParameter('using', locator.using).
setParameter('value', locator.value);
id = this.schedule_(cmd, 'WebElement.findElement(' + locator + ')');
}
return new WebElementPromise(this.driver_, id);
}
/**
* Schedules a command to find all of the descendants of this element that
* match the given search criteria.
*
* @param {!(by.By|Function)} locator The locator strategy to use when
* searching for the element.
* @return {!promise.Thenable<!Array<!WebElement>>} A
* promise that will resolve to an array of WebElements.
*/
findElements(locator) {
locator = by.checkedLocator(locator);
let id;
if (typeof locator === 'function') {
return this.driver_.findElementsInternal_(locator, this);
} else {
var cmd = new command.Command(
command.Name.FIND_CHILD_ELEMENTS).
setParameter('using', locator.using).
setParameter('value', locator.value);
return this.schedule_(cmd, 'WebElement.findElements(' + locator + ')');
}
}
/**
* Schedules a command to click on this element.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the click command has completed.
*/
click() {
return this.schedule_(
new command.Command(command.Name.CLICK_ELEMENT),
'WebElement.click()');
}
/**
* Schedules a command to type a sequence on the DOM element represented by
* this instance.
*
* Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is
* processed in the key sequence, that key state is toggled until one of the
* following occurs:
*
* - The modifier key is encountered again in the sequence. At this point the
* state of the key is toggled (along with the appropriate keyup/down
* events).
* - The {@link input.Key.NULL} key is encountered in the sequence. When
* this key is encountered, all modifier keys current in the down state are
* released (with accompanying keyup events). The NULL key can be used to
* simulate common keyboard shortcuts:
*
* element.sendKeys("text was",
* Key.CONTROL, "a", Key.NULL,
* "now text is");
* // Alternatively:
* element.sendKeys("text was",
* Key.chord(Key.CONTROL, "a"),
* "now text is");
*
* - The end of the key sequence is encountered. When there are no more keys
* to type, all depressed modifier keys are released (with accompanying
* keyup events).
*
* If this element is a file input ({@code <input type="file">}), the
* specified key sequence should specify the path to the file to attach to
* the element. This is analogous to the user clicking "Browse..." and entering
* the path into the file select dialog.
*
* var form = driver.findElement(By.css('form'));
* var element = form.findElement(By.css('input[type=file]'));
* element.sendKeys('/path/to/file.txt');
* form.submit();
*
* For uploads to function correctly, the entered path must reference a file
* on the _browser's_ machine, not the local machine running this script. When
* running against a remote Selenium server, a {@link input.FileDetector}
* may be used to transparently copy files to the remote machine before
* attempting to upload them in the browser.
*
* __Note:__ On browsers where native keyboard events are not supported
* (e.g. Firefox on OS X), key events will be synthesized. Special
* punctuation keys will be synthesized according to a standard QWERTY en-us
* keyboard layout.
*
* @param {...(number|string|!IThenable<(number|string)>)} var_args The
* sequence of keys to type. Number keys may be referenced numerically or
* by string (1 or '1'). All arguments will be joined into a single
* sequence.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when all keys have been typed.
*/
sendKeys(var_args) {
let keys = Promise.all(Array.prototype.slice.call(arguments, 0)).
then(keys => {
let ret = [];
keys.forEach(key => {
let type = typeof key;
if (type === 'number') {
key = String(key);
} else if (type !== 'string') {
throw TypeError(
'each key must be a number of string; got ' + type);
}
// The W3C protocol requires keys to be specified as an array where
// each element is a single key.
ret.push.apply(ret, key.split(''));
});
return ret;
});
if (!this.driver_.fileDetector_) {
return this.schedule_(
new command.Command(command.Name.SEND_KEYS_TO_ELEMENT).
setParameter('text', keys).
setParameter('value', keys),
'WebElement.sendKeys()');
}
// Suppress unhandled rejection errors until the flow executes the command.
keys.catch(function() {});
var element = this;
return this.getDriver().controlFlow().execute(function() {
return keys.then(function(keys) {
return element.driver_.fileDetector_
.handleFile(element.driver_, keys.join(''));
}).then(function(keys) {
return element.schedule_(
new command.Command(command.Name.SEND_KEYS_TO_ELEMENT).
setParameter('text', keys).
setParameter('value', keys.split('')),
'WebElement.sendKeys()');
});
}, 'WebElement.sendKeys()');
}
/**
* Schedules a command to query for the tag/node name of this element.
* @return {!promise.Thenable<string>} A promise that will be
* resolved with the element's tag name.
*/
getTagName() {
return this.schedule_(
new command.Command(command.Name.GET_ELEMENT_TAG_NAME),
'WebElement.getTagName()');
}
/**
* Schedules a command to query for the computed style of the element
* represented by this instance. If the element inherits the named style from
* its parent, the parent will be queried for its value. Where possible, color
* values will be converted to their hex representation (e.g. #00ff00 instead
* of rgb(0, 255, 0)).
*
* _Warning:_ the value returned will be as the browser interprets it, so
* it may be tricky to form a proper assertion.
*
* @param {string} cssStyleProperty The name of the CSS style property to look
* up.
* @return {!promise.Thenable<string>} A promise that will be
* resolved with the requested CSS value.
*/
getCssValue(cssStyleProperty) {
var name = command.Name.GET_ELEMENT_VALUE_OF_CSS_PROPERTY;
return this.schedule_(
new command.Command(name).
setParameter('propertyName', cssStyleProperty),
'WebElement.getCssValue(' + cssStyleProperty + ')');
}
/**
* Schedules a command to query for the value of the given attribute of the
* element. Will return the current value, even if it has been modified after
* the page has been loaded. More exactly, this method will return the value
* of the given attribute, unless that attribute is not present, in which case
* the value of the property with the same name is returned. If neither value
* is set, null is returned (for example, the "value" property of a textarea
* element). The "style" attribute is converted as best can be to a
* text representation with a trailing semi-colon. The following are deemed to
* be "boolean" attributes and will return either "true" or null:
*
* async, autofocus, autoplay, checked, compact, complete, controls, declare,
* defaultchecked, defaultselected, defer, disabled, draggable, ended,
* formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope,
* loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open,
* paused, pubdate, readonly, required, reversed, scoped, seamless, seeking,
* selected, spellcheck, truespeed, willvalidate
*
* Finally, the following commonly mis-capitalized attribute/property names
* are evaluated as expected:
*
* - "class"
* - "readonly"
*
* @param {string} attributeName The name of the attribute to query.
* @return {!promise.Thenable<?string>} A promise that will be
* resolved with the attribute's value. The returned value will always be
* either a string or null.
*/
getAttribute(attributeName) {
return this.schedule_(
new command.Command(command.Name.GET_ELEMENT_ATTRIBUTE).
setParameter('name', attributeName),
'WebElement.getAttribute(' + attributeName + ')');
}
/**
* Get the visible (i.e. not hidden by CSS) innerText of this element,
* including sub-elements, without any leading or trailing whitespace.
*
* @return {!promise.Thenable<string>} A promise that will be
* resolved with the element's visible text.
*/
getText() {
return this.schedule_(
new command.Command(command.Name.GET_ELEMENT_TEXT),
'WebElement.getText()');
}
/**
* Schedules a command to compute the size of this element's bounding box, in
* pixels.
* @return {!promise.Thenable<{width: number, height: number}>} A
* promise that will be resolved with the element's size as a
* {@code {width:number, height:number}} object.
*/
getSize() {
return this.schedule_(
new command.Command(command.Name.GET_ELEMENT_SIZE),
'WebElement.getSize()');
}
/**
* Schedules a command to compute the location of this element in page space.
* @return {!promise.Thenable<{x: number, y: number}>} A promise that
* will be resolved to the element's location as a
* {@code {x:number, y:number}} object.
*/
getLocation() {
return this.schedule_(
new command.Command(command.Name.GET_ELEMENT_LOCATION),
'WebElement.getLocation()');
}
/**
* Schedules a command to query whether the DOM element represented by this
* instance is enabled, as dictated by the {@code disabled} attribute.
* @return {!promise.Thenable<boolean>} A promise that will be
* resolved with whether this element is currently enabled.
*/
isEnabled() {
return this.schedule_(
new command.Command(command.Name.IS_ELEMENT_ENABLED),
'WebElement.isEnabled()');
}
/**
* Schedules a command to query whether this element is selected.
* @return {!promise.Thenable<boolean>} A promise that will be
* resolved with whether this element is currently selected.
*/
isSelected() {
return this.schedule_(
new command.Command(command.Name.IS_ELEMENT_SELECTED),
'WebElement.isSelected()');
}
/**
* Schedules a command to submit the form containing this element (or this
* element if it is a FORM element). This command is a no-op if the element is
* not contained in a form.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the form has been submitted.
*/
submit() {
return this.schedule_(
new command.Command(command.Name.SUBMIT_ELEMENT),
'WebElement.submit()');
}
/**
* Schedules a command to clear the `value` of this element. This command has
* no effect if the underlying DOM element is neither a text INPUT element
* nor a TEXTAREA element.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when the element has been cleared.
*/
clear() {
return this.schedule_(
new command.Command(command.Name.CLEAR_ELEMENT),
'WebElement.clear()');
}
/**
* Schedules a command to test whether this element is currently displayed.
* @return {!promise.Thenable<boolean>} A promise that will be
* resolved with whether this element is currently visible on the page.
*/
isDisplayed() {
return this.schedule_(
new command.Command(command.Name.IS_ELEMENT_DISPLAYED),
'WebElement.isDisplayed()');
}
/**
* Take a screenshot of the visible region encompassed by this element's
* bounding rectangle.
*
* @param {boolean=} opt_scroll Optional argument that indicates whether the
* element should be scrolled into view before taking a screenshot.
* Defaults to false.
* @return {!promise.Thenable<string>} A promise that will be
* resolved to the screenshot as a base-64 encoded PNG.
*/
takeScreenshot(opt_scroll) {
var scroll = !!opt_scroll;
return this.schedule_(
new command.Command(command.Name.TAKE_ELEMENT_SCREENSHOT)
.setParameter('scroll', scroll),
'WebElement.takeScreenshot(' + scroll + ')');
}
}
/**
* WebElementPromise is a promise that will be fulfilled with a WebElement.
* This serves as a forward proxy on WebElement, allowing calls to be
* scheduled without directly on this instance before the underlying
* WebElement has been fulfilled. In other words, the following two statements
* are equivalent:
*
* driver.findElement({id: 'my-button'}).click();
* driver.findElement({id: 'my-button'}).then(function(el) {
* return el.click();
* });
*
* @implements {promise.CancellableThenable<!WebElement>}
* @final
*/
class WebElementPromise extends WebElement {
/**
* @param {!WebDriver} driver The parent WebDriver instance for this
* element.
* @param {!promise.Thenable<!WebElement>} el A promise
* that will resolve to the promised element.
*/
constructor(driver, el) {
super(driver, 'unused');
/**
* Cancel operation is only supported if the wrapped thenable is also
* cancellable.
* @param {(string|Error)=} opt_reason
* @override
*/
this.cancel = function(opt_reason) {
if (promise.CancellableThenable.isImplementation(el)) {
/** @type {!promise.CancellableThenable} */(el).cancel(opt_reason);
}
};
/** @override */
this.then = el.then.bind(el);
/** @override */
this.catch = el.catch.bind(el);
/**
* Defers returning the element ID until the wrapped WebElement has been
* resolved.
* @override
*/
this.getId = function() {
return el.then(function(el) {
return el.getId();
});
};
}
}
promise.CancellableThenable.addImplementation(WebElementPromise);
//////////////////////////////////////////////////////////////////////////////
//
// Alert
//
//////////////////////////////////////////////////////////////////////////////
/**
* Represents a modal dialog such as {@code alert}, {@code confirm}, or
* {@code prompt}. Provides functions to retrieve the message displayed with
* the alert, accept or dismiss the alert, and set the response text (in the
* case of {@code prompt}).
*/
class Alert {
/**
* @param {!WebDriver} driver The driver controlling the browser this alert
* is attached to.
* @param {string} text The message text displayed with this alert.
*/
constructor(driver, text) {
/** @private {!WebDriver} */
this.driver_ = driver;
/** @private {!promise.Thenable<string>} */
this.text_ = driver.controlFlow().promise(resolve => resolve(text));
}
/**
* Retrieves the message text displayed with this alert. For instance, if the
* alert were opened with alert("hello"), then this would return "hello".
*
* @return {!promise.Thenable<string>} A promise that will be
* resolved to the text displayed with this alert.
*/
getText() {
return this.text_;
}
/**
* Sets the username and password in an alert prompting for credentials (such
* as a Basic HTTP Auth prompt). This method will implicitly
* {@linkplain #accept() submit} the dialog.
*
* @param {string} username The username to send.
* @param {string} password The password to send.
* @return {!promise.Thenable<void>} A promise that will be resolved when this
* command has completed.
*/
authenticateAs(username, password) {
return this.driver_.schedule(
new command.Command(command.Name.SET_ALERT_CREDENTIALS),
'WebDriver.switchTo().alert()'
+ `.authenticateAs("${username}", "${password}")`);
}
/**
* Accepts this alert.
*
* @return {!promise.Thenable<void>} A promise that will be resolved
* when this command has completed.
*/
accept() {
return this.driver_.schedule(
new command.Command(command.Name.ACCEPT_ALERT),
'WebDriver.switchTo().alert().accept()');
}
/**
* Dismisses this alert.
*
* @return {!promise.Thenable<void>} A promise that will be resolved
* when this command has completed.
*/
dismiss() {
return this.driver_.schedule(
new command.Command(command.Name.DISMISS_ALERT),
'WebDriver.switchTo().alert().dismiss()');
}
/**
* Sets the response text on this alert. This command will return an error if
* the underlying alert does not support response text (e.g. window.alert and
* window.confirm).
*
* @param {string} text The text to set.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when this command has completed.
*/
sendKeys(text) {
return this.driver_.schedule(
new command.Command(command.Name.SET_ALERT_TEXT).
setParameter('text', text),
'WebDriver.switchTo().alert().sendKeys(' + text + ')');
}
}
/**
* AlertPromise is a promise that will be fulfilled with an Alert. This promise
* serves as a forward proxy on an Alert, allowing calls to be scheduled
* directly on this instance before the underlying Alert has been fulfilled. In
* other words, the following two statements are equivalent:
*
* driver.switchTo().alert().dismiss();
* driver.switchTo().alert().then(function(alert) {
* return alert.dismiss();
* });
*
* @implements {promise.CancellableThenable<!webdriver.Alert>}
* @final
*/
class AlertPromise extends Alert {
/**
* @param {!WebDriver} driver The driver controlling the browser this
* alert is attached to.
* @param {!promise.Thenable<!Alert>} alert A thenable
* that will be fulfilled with the promised alert.
*/
constructor(driver, alert) {
super(driver, 'unused');
/**
* Cancel operation is only supported if the wrapped thenable is also
* cancellable.
* @param {(string|Error)=} opt_reason
* @override
*/
this.cancel = function(opt_reason) {
if (promise.CancellableThenable.isImplementation(alert)) {
/** @type {!promise.CancellableThenable} */(alert).cancel(opt_reason);
}
};
/** @override */
this.then = alert.then.bind(alert);
/** @override */
this.catch = alert.catch.bind(alert);
/**
* Defer returning text until the promised alert has been resolved.
* @override
*/
this.getText = function() {
return alert.then(function(alert) {
return alert.getText();
});
};
/**
* Defers action until the alert has been located.
* @override
*/
this.authenticateAs = function(username, password) {
return alert.then(function(alert) {
return alert.authenticateAs(username, password);
});
};
/**
* Defers action until the alert has been located.
* @override
*/
this.accept = function() {
return alert.then(function(alert) {
return alert.accept();
});
};
/**
* Defers action until the alert has been located.
* @override
*/
this.dismiss = function() {
return alert.then(function(alert) {
return alert.dismiss();
});
};
/**
* Defers action until the alert has been located.
* @override
*/
this.sendKeys = function(text) {
return alert.then(function(alert) {
return alert.sendKeys(text);
});
};
}
}
promise.CancellableThenable.addImplementation(AlertPromise);
// PUBLIC API
module.exports = {
Alert: Alert,
AlertPromise: AlertPromise,
Condition: Condition,
Logs: Logs,
Navigation: Navigation,
Options: Options,
TargetLocator: TargetLocator,
Timeouts: Timeouts,
IWebDriver: IWebDriver,
WebDriver: WebDriver,
WebElement: WebElement,
WebElementCondition: WebElementCondition,
WebElementPromise: WebElementPromise,
Window: Window
};
| 1 | 14,518 | Also update line 2205 below | SeleniumHQ-selenium | rb |
@@ -710,7 +710,8 @@
}
},
skin: { default: "main", type: String},
- disabled: {type: Boolean, default: false}
+ disabled: {type: Boolean, default: false},
+ direction: { default: "vertical", type: String}
},
computed: {
topClasses: function() { | 1 | /* global Vue, CV */
(function(countlyVue) {
var _mixins = countlyVue.mixins;
var HEX_COLOR_REGEX = new RegExp('^#([0-9a-f]{3}|[0-9a-f]{6})$', 'i');
Vue.component("cly-colorpicker", countlyVue.components.BaseComponent.extend({
mixins: [
_mixins.i18n
],
props: {
value: {type: [String, Object], default: "#FFFFFF"},
resetValue: { type: [String, Object], default: "#FFFFFF"}
},
data: function() {
return {
isOpened: false
};
},
computed: {
previewStyle: function() {
return {
"background-color": this.value
};
},
localValue: {
get: function() {
return this.value.replace("#", "");
},
set: function(value) {
var colorValue = "#" + value.replace("#", "");
if (colorValue.match(HEX_COLOR_REGEX)) {
this.setColor({hex: colorValue});
}
}
}
},
methods: {
setColor: function(color) {
this.$emit("input", color.hex);
},
reset: function() {
this.setColor({hex: this.resetValue});
},
open: function() {
this.isOpened = true;
},
close: function() {
this.isOpened = false;
}
},
components: {
picker: window.VueColor.Sketch
},
template: '<div class="cly-vue-colorpicker">\n' +
'<div @click.stop="open">\n' +
'<div class="preview-box" :style="previewStyle"></div>\n' +
'<input class="preview-input" type="text" v-model="localValue" />\n' +
'</div>\n' +
'<div class="picker-body" v-if="isOpened" v-click-outside="close">\n' +
'<picker :preset-colors="[]" :value="value" @input="setColor"></picker>\n' +
'<div class="button-controls">\n' +
'<cly-button :label="i18n(\'common.reset\')" @click="reset" skin="light"></cly-button>\n' +
'<cly-button :label="i18n(\'common.cancel\')" @click="close" skin="light"></cly-button>\n' +
'<cly-button :label="i18n(\'common.confirm\')" @click="close" skin="green"></cly-button>\n' +
'</div>\n' +
'</div>\n' +
'</div>'
}));
Vue.component("cly-dropzone", window.vue2Dropzone);
var AbstractListBox = countlyVue.views.BaseView.extend({
props: {
options: {type: Array},
bordered: {type: Boolean, default: true},
skin: {
type: String,
default: "default",
required: false,
validator: function(val) {
return val === "default" || val === "jumbo";
}
},
disabled: {type: Boolean, default: false, required: false},
height: {type: [Number, String], default: 300, required: false},
},
methods: {
navigateOptions: function() {
if (!this.visible) {
this.visible = true;
}
},
handleItemClick: function(option) {
if (!this.disabled) {
this.$emit("input", option.value);
this.$emit("change", option.value);
}
},
handleItemHover: function(option) {
this.hovered = option.value;
},
handleBlur: function() {
this.hovered = this.value;
this.focused = false;
},
handleHover: function() {
this.focused = true;
}
},
data: function() {
return {
hovered: null,
focused: false,
scrollCfg: {
scrollPanel: {
initialScrollX: false,
},
rail: {
gutterOfSide: "0px"
},
bar: {
background: "#A7AEB8",
size: "6px",
specifyBorderRadius: "3px",
keepShow: false
}
}
};
},
computed: {
topClasses: function() {
var classes = {
"is-focus": this.focused,
"cly-vue-listbox--bordered": this.bordered,
"cly-vue-listbox--disabled": this.disabled
};
classes["cly-vue-listbox--has-" + this.skin + "-skin"] = true;
return classes;
},
wrapperStyle: function() {
if (this.height !== "auto") {
return {
'max-height': this.height + "px"
};
}
return false;
}
}
});
var SearchableOptionsMixin = {
props: {
searchable: {type: Boolean, default: true},
searchPlaceholder: {type: String, default: 'Search'}
},
data: function() {
return {
searchQuery: ''
};
},
methods: {
getMatching: function(options) {
if (!this.searchQuery || !this.searchable) {
return options;
}
var self = this;
var query = self.searchQuery.toLowerCase();
return options.filter(function(option) {
return option.label.toLowerCase().indexOf(query) > -1;
});
}
}
};
Vue.component("cly-listbox", AbstractListBox.extend({
mixins: [SearchableOptionsMixin],
props: {
searchable: {type: Boolean, default: false, required: false}, //override the mixin
value: { type: [String, Number] }
},
computed: {
searchedOptions: function() {
return this.getMatching(this.options);
}
},
template: '<div\
class="cly-vue-listbox"\
tabindex="0"\
:class="topClasses"\
@mouseenter="handleHover"\
@mouseleave="handleBlur"\
@focus="handleHover"\
@blur="handleBlur">\
<div class="cly-vue-listbox__header bu-p-3" v-if="searchable">\
<form>\
<el-input\
:disabled="disabled"\
autocomplete="off"\
v-model="searchQuery"\
:placeholder="searchPlaceholder">\
<i slot="prefix" class="el-input__icon el-icon-search"></i>\
</el-input>\
</form>\
</div>\
<vue-scroll\
v-if="searchedOptions.length > 0"\
:ops="scrollCfg"\>\
<div :style="wrapperStyle" class="cly-vue-listbox__items-wrapper">\
<div\
tabindex="0"\
class="text-medium font-weight-bold"\
:class="{\'selected\': value === option.value, \'hover\': hovered === option.value, \'cly-vue-listbox__item\': !option.group, \'cly-vue-listbox__group\': option.group}"\
:key="option.value"\
@focus="!option.group && handleItemHover(option)"\
@mouseenter="!option.group && handleItemHover(option)"\
@keyup.enter="!option.group && handleItemClick(option)"\
@click.stop="!option.group && handleItemClick(option)"\
v-for="option in searchedOptions">\
<div class="cly-vue-listbox__item-content">\
<div class="bu-level">\
<div class="bu-level-left">\
<div v-if="$slots[\'option-prefix\']" class="cly-vue-listbox__item-prefix bu-mr-2">\
<slot name="option-prefix" v-bind="option"></slot>\
</div>\
<div class="cly-vue-listbox__item-label">{{option.label}}</div>\
</div>\
<div class="bu-level-right">\
<slot class="cly-vue-listbox__item-suffix" name="option-suffix" v-bind="option"></slot>\
</div>\
</div>\
</div>\
</div>\
</div>\
</vue-scroll>\
<div v-else class="cly-vue-listbox__no-data">\
{{i18n(\'common.search.no-match-found\')}}\
</div>\
</div>'
}));
Vue.component("cly-checklistbox", AbstractListBox.extend({
props: {
value: {
type: Array,
default: function() {
return [];
}
},
sortable: {
type: Boolean,
default: false
}
},
data: function() {
return {
sortMap: null
};
},
watch: {
options: {
immediate: true,
handler: function(options) {
if (this.sortable && !this.sortMap) {
this.sortMap = Object.freeze(options.reduce(function(acc, opt, idx) {
acc[opt.value] = idx;
return acc;
}, {}));
}
}
}
},
methods: {
computeSortedOptions: function() {
if (!this.sortable || !this.sortMap) {
return this.options;
}
var sortMap = this.sortMap,
wrapped = this.options.map(function(opt, idx) {
return { opt: opt, idx: idx, ord: sortMap[opt.value] || 0 };
});
wrapped.sort(function(a, b) {
return (a.ord - b.ord) || (a.idx - b.idx);
});
return wrapped.map(function(item) {
return item.opt;
});
}
},
computed: {
innerValue: {
get: function() {
return this.value;
},
set: function(newVal) {
if (this.disabled) {
return;
}
if (this.sortable && this.sortMap) {
var sortMap = this.sortMap,
wrapped = newVal.map(function(value, idx) {
return { value: value, idx: idx, ord: sortMap[value] || 0 };
});
wrapped.sort(function(a, b) {
return (a.ord - b.ord) || (a.idx - b.idx);
});
var sorted = wrapped.map(function(item) {
return item.value;
});
this.$emit("input", sorted);
this.$emit("change", sorted);
}
else {
this.$emit("input", newVal);
this.$emit("change", newVal);
}
}
},
sortedOptions: {
get: function() {
return this.computeSortedOptions();
},
set: function(sorted) {
if (!this.sortable) {
return;
}
this.sortMap = Object.freeze(sorted.reduce(function(acc, opt, idx) {
acc[opt.value] = idx;
return acc;
}, {}));
this.innerValue = this.value; // triggers innerValue.set
this.$emit('update:options', this.computeSortedOptions());
}
}
},
template: '<div\
class="cly-vue-listbox"\
tabindex="0"\
:class="topClasses"\
@mouseenter="handleHover"\
@mouseleave="handleBlur"\
@focus="handleHover"\
@blur="handleBlur">\
<vue-scroll\
v-if="options.length > 0"\
:ops="scrollCfg"\>\
<div :style="wrapperStyle" class="cly-vue-listbox__items-wrapper">\
<el-checkbox-group\
v-model="innerValue">\
<draggable \
handle=".drag-handler"\
v-model="sortedOptions"\
:disabled="!sortable">\
<div\
class="text-medium cly-vue-listbox__item"\
:key="option.value"\
v-for="option in sortedOptions">\
<div v-if="sortable" class="drag-handler"><img src="images/drill/drag-icon.svg" /></div>\
<el-checkbox :label="option.value" :key="option.value">{{option.label}}</el-checkbox>\
</div>\
</draggable>\
</el-checkbox-group>\
</div>\
</vue-scroll>\
<div v-else class="cly-vue-listbox__no-data">\
{{i18n(\'common.search.no-match-found\')}}\
</div>\
</div>'
}));
var TabbedOptionsMixin = {
props: {
options: {
type: Array,
default: function() {
return [];
}
},
hideDefaultTabs: {type: Boolean, default: false},
allPlaceholder: {type: String, default: 'All'},
hideAllOptionsTab: {type: Boolean, default: false}
},
data: function() {
return {
activeTabId: null
};
},
computed: {
hasAllOptionsTab: function() {
if (this.hideAllOptionsTab || this.mode === "multi-check-sortable") {
return false;
}
return true;
},
hasTabs: function() {
if (!this.options || !this.options.length) {
return false;
}
return !!this.options[0].options;
},
publicTabs: function() {
if (this.hasTabs && this.hasAllOptionsTab) {
var allOptions = {
name: "__all",
label: this.allPlaceholder,
options: this.flatOptions
};
return [allOptions].concat(this.options);
}
else if (this.hasTabs) {
return this.options;
}
return [{
name: "__root",
label: "__root",
options: this.options
}];
},
flatOptions: function() {
if (!this.hasTabs || !this.options.length) {
return this.options;
}
return this.options.reduce(function(items, tab) {
return items.concat(tab.options);
}, []);
},
val2tab: function() {
if (!this.publicTabs.length) {
return {};
}
return this.publicTabs.reduce(function(items, tab) {
tab.options.forEach(function(opt) {
items[opt.value] = tab.name;
});
return items;
}, {});
},
selectedOptions: function() {
if (!this.flatOptions.length) {
return {};
}
var self = this;
if (Array.isArray(this.value)) {
return this.flatOptions.filter(function(item) {
return self.value.indexOf(item.value) > -1;
});
}
else {
var matching = this.flatOptions.filter(function(item) {
return item.value === self.value;
});
if (matching.length) {
return matching[0];
}
}
return {};
}
},
methods: {
updateTabFn: function(tabId) {
this.activeTabId = tabId;
},
determineActiveTabId: function() {
var self = this;
this.$nextTick(function() {
if (!self.hasTabs) {
self.activeTabId = "__root";
}
else if (self.value && self.val2tab[self.value]) {
self.activeTabId = self.val2tab[self.value];
}
else if (this.hasAllOptionsTab) {
self.activeTabId = "__all";
}
else if (!self.activeTabId || self.activeTabId === "__all" || self.activeTabId === "__root") {
self.activeTabId = self.publicTabs[0].name;
}
});
},
},
watch: {
hasAllOptionsTab: function() {
this.determineActiveTabId();
}
}
};
Vue.component("cly-select-x", countlyVue.components.create({
mixins: [TabbedOptionsMixin, SearchableOptionsMixin, _mixins.i18n],
template: CV.T('/javascripts/countly/vue/templates/selectx.html'),
props: {
title: {type: String, default: ''},
placeholder: {type: String, default: 'Select'},
value: { type: [String, Number, Array] },
mode: {type: String, default: 'single-list'}, // multi-check,
autoCommit: {type: Boolean, default: true},
disabled: { type: Boolean, default: false},
width: { type: [Number, Object], default: 400},
size: {type: String, default: ''},
adaptiveLength: {type: Boolean, default: false},
singleOptionSettings: {
type: Object,
default: function() {
return {
hideList: false,
autoPick: false
};
},
required: false
},
popClass: {
type: String,
required: false
}
},
data: function() {
return {
uncommittedValue: null
};
},
computed: {
popClasses: function() {
return {
"cly-vue-select-x__pop--hidden-tabs": this.hideDefaultTabs || !this.hasTabs,
"cly-vue-select-x__pop--has-single-option": this.hasSingleOption
};
},
currentTab: function() {
var self = this;
var filtered = this.publicTabs.filter(function(tab) {
return self.activeTabId === tab.name;
});
if (filtered.length > 0) {
return filtered[0];
}
return {};
},
hasSingleOption: function() {
return (this.activeTabId !== '__root' &&
this.currentTab.options &&
this.currentTab.options.length === 1 &&
this.singleOptionSettings.hideList);
},
showList: function() {
return !this.hasSingleOption;
},
innerValue: {
get: function() {
if (this.uncommittedValue && this.uncommittedValue !== this.value) {
return this.uncommittedValue;
}
return this.value;
},
set: function(newVal) {
if (this.autoCommit) {
this.$emit("input", newVal);
this.$emit("change", newVal);
}
else {
this.uncommittedValue = newVal;
}
}
}
},
mounted: function() {
this.determineActiveTabId();
},
methods: {
handleValueChange: function() {
if (this.mode === 'single-list' && this.autoCommit) {
this.doClose();
}
},
doClose: function() {
this.determineActiveTabId();
this.$refs.dropdown.handleClose();
},
updateDropdown: function() {
this.$refs.dropdown.updateDropdown();
},
handleDropdownShow: function() {
this.$forceUpdate();
this.focusOnSearch();
},
focusOnSearch: function() {
var self = this;
this.$nextTick(function() {
if (self.$refs.searchBox) {
self.$refs.searchBox.focus();
}
});
},
focusOnTrigger: function() {
var self = this;
if (this.$refs.trigger && this.$refs.trigger.focus()) {
this.$nextTick(function() {
self.$refs.trigger.focus();
});
}
},
doCommit: function() {
if (this.uncommittedValue) {
this.$emit("input", this.uncommittedValue);
this.$emit("change", this.uncommittedValue);
this.uncommittedValue = null;
}
this.doClose();
},
doDiscard: function() {
this.uncommittedValue = null;
this.doClose();
}
},
watch: {
searchQuery: function() {
this.updateDropdown();
},
activeTabId: function() {
this.updateDropdown();
if (this.hasSingleOption && this.singleOptionSettings.autoPick) {
this.innerValue = this.currentTab.options[0].value;
this.doCommit();
}
},
value: function() {
this.uncommittedValue = null;
}
}
}));
Vue.component("cly-check", countlyVue.components.BaseComponent.extend(
// @vue/component
{
props: {
value: {default: false, type: Boolean},
label: {type: String, default: ''},
skin: { default: "switch", type: String},
disabled: {type: Boolean, default: false}
},
computed: {
topClasses: function() {
var classes = [];
if (["switch", "tick", "star"].indexOf(this.skin) > -1) {
classes.push("check-" + this.skin + "-skin");
}
else {
classes.push("check-switch-skin");
}
if (this.disabled) {
classes.push("disabled");
}
return classes;
},
labelClass: function() {
return this.getClass(this.value);
}
},
methods: {
setValue: function(e) {
if (!this.disabled) {
this.$emit('input', e);
}
},
getClass: function(value) {
var classes = ["check-label"];
if (this.skin === "tick") {
classes.push("fa");
if (value) {
classes.push("fa-check-square");
}
else {
classes.push("fa-square-o");
}
}
else if (this.skin === "star") {
classes.push("fa fa-star");
if (value) {
classes.push("color-yellow-100");
}
else {
classes.push("color-cool-gray-50");
}
}
return classes;
}
},
template: '<div class="cly-vue-check" v-bind:class="topClasses">\n' +
'<div class="check-wrapper text-clickable">\n' +
'<input type="checkbox" class="check-checkbox" :checked="value">\n' +
'<i v-bind:class="labelClass" @click.stop="setValue(!value)"></i>\n' +
'<span v-if="label" class="check-text" @click.stop="setValue(!value)">{{label}}</span>\n' +
'</div>\n' +
'</div>'
}
));
Vue.component('cly-radio-block', countlyVue.components.BaseComponent.extend({
props: {
value: {required: true, default: -1, type: [ String, Number ]},
items: {
required: true,
type: Array,
default: function() {
return [];
}
},
skin: { default: "main", type: String},
disabled: {type: Boolean, default: false}
},
computed: {
topClasses: function() {
var classes = [];
if (["main", "light"].indexOf(this.skin) > -1) {
classes.push("radio-" + this.skin + "-skin");
}
else {
classes.push("radio-main-skin");
}
if (this.disabled) {
classes.push("disabled");
}
return classes;
}
},
methods: {
setValue: function(e) {
if (!this.disabled) {
this.$emit('input', e);
}
}
},
template: '<div class="cly-vue-radio-block" v-bind:class="topClasses">\n' +
'<div class="radio-wrapper">\n' +
'<div @click="setValue(item.value)" v-for="(item, i) in items" :key="i" :class="{\'selected\': value == item.value}" class="radio-button bu-is-flex">\n' +
'<div class="bu-is-flex"><div class="box"></div></div>\n' +
'<div class="bu-is-flex bu-is-flex-direction-column bu-is-justify-content-space-between"><div><span class="text-medium">{{item.label}}</span><span v-if="item.description" class="el-icon-info" style="margin-left:10px" v-tooltip.top-center="item.description"></span></div>\n' +
'<div class="bu-is-flex bu-is-align-items-baseline number">' +
'<h2>{{item.number}}</h2>' +
'<div v-if="item.trend == \'u\'" class="trend-up">\n' +
'<i class="fas fa-arrow-up"></i><span>{{item.trendValue}}</span>\n' +
'</div>\n' +
'<div v-if="item.trend == \'d\'" class="trend-down">\n' +
'<i class="fas fa-arrow-down"></i><span>{{item.trendValue}}</span>\n' +
'</div>\n' +
'</div></div>\n' +
'</div>\n' +
'</div>\n' +
'</div>'
}));
Vue.component('cly-dynamic-textarea', countlyVue.components.BaseComponent.extend({
template: '<div contenteditable="true" @input="update" v-html="content"></div>',
props: ['content'],
methods: {
update: function(event) {
this.$emit('update', event.target.innerText);
}
}
}));
}(window.countlyVue = window.countlyVue || {}));
| 1 | 14,481 | `direction` is referenced nowhere. Do I miss something? | Countly-countly-server | js |
@@ -1,4 +1,3 @@
-import deparam from 'npm:deparam';
import destroyApp from '../helpers/destroy-app';
import startApp from '../helpers/start-app';
import {Response} from 'ember-cli-mirage'; | 1 | import deparam from 'npm:deparam';
import destroyApp from '../helpers/destroy-app';
import startApp from '../helpers/start-app';
import {Response} from 'ember-cli-mirage';
import {
afterEach,
beforeEach,
describe,
it
} from 'mocha';
import {authenticateSession, invalidateSession} from '../helpers/ember-simple-auth';
import {expect} from 'chai';
describe('Acceptance: Signin', function () {
let application;
beforeEach(function () {
application = startApp();
});
afterEach(function () {
destroyApp(application);
});
it('redirects if already authenticated', async function () {
let role = server.create('role', {name: 'Author'});
server.create('user', {roles: [role], slug: 'test-user'});
await authenticateSession(application);
await visit('/signin');
expect(currentURL(), 'current url').to.equal('/');
});
describe('when attempting to signin', function () {
beforeEach(function () {
let role = server.create('role', {name: 'Administrator'});
server.create('user', {roles: [role], slug: 'test-user'});
server.post('/authentication/token', function (schema, {requestBody}) {
/* eslint-disable camelcase */
let {
grant_type: grantType,
username,
password,
client_id: clientId
} = deparam(requestBody);
expect(grantType, 'grant type').to.equal('password');
expect(username, 'username').to.equal('[email protected]');
expect(clientId, 'client id').to.equal('ghost-admin');
if (password === 'thisissupersafe') {
return {
access_token: 'MirageAccessToken',
expires_in: 3600,
refresh_token: 'MirageRefreshToken',
token_type: 'Bearer'
};
} else {
return new Response(401, {}, {
errors: [{
errorType: 'UnauthorizedError',
message: 'Invalid Password'
}]
});
}
/* eslint-enable camelcase */
});
});
it('errors correctly', async function () {
await invalidateSession(application);
await visit('/signin');
expect(currentURL(), 'signin url').to.equal('/signin');
expect(find('input[name="identification"]').length, 'email input field')
.to.equal(1);
expect(find('input[name="password"]').length, 'password input field')
.to.equal(1);
await click('.gh-btn-blue');
expect(find('.form-group.error').length, 'number of invalid fields')
.to.equal(2);
expect(find('.main-error').length, 'main error is displayed')
.to.equal(1);
await fillIn('[name="identification"]', '[email protected]');
await fillIn('[name="password"]', 'invalid');
await click('.gh-btn-blue');
expect(currentURL(), 'current url').to.equal('/signin');
expect(find('.main-error').length, 'main error is displayed')
.to.equal(1);
expect(find('.main-error').text().trim(), 'main error text')
.to.equal('Invalid Password');
});
it('submits successfully', async function () {
invalidateSession(application);
await visit('/signin');
expect(currentURL(), 'current url').to.equal('/signin');
await fillIn('[name="identification"]', '[email protected]');
await fillIn('[name="password"]', 'thisissupersafe');
await click('.gh-btn-blue');
expect(currentURL(), 'currentURL').to.equal('/');
});
});
});
| 1 | 9,021 | The two places this was used have been removed so we can fully remove this dependency. | TryGhost-Admin | js |
@@ -16,7 +16,6 @@
package agreement
-//go:generate dbgen -i agree.sql -p agreement -n agree -o agreeInstall.go
import (
"context"
"database/sql" | 1 | // Copyright (C) 2019-2020 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package agreement
//go:generate dbgen -i agree.sql -p agreement -n agree -o agreeInstall.go
import (
"context"
"database/sql"
"fmt"
"sync"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/logging/logspec"
"github.com/algorand/go-algorand/protocol"
"github.com/algorand/go-algorand/util/db"
"github.com/algorand/go-algorand/util/timers"
)
// diskState represents the state required by the agreement protocol to be persistent.
type diskState struct {
Router, Player, Clock []byte
ActionTypes []actionType
Actions [][]byte
}
func persistent(as []action) bool {
for _, a := range as {
if a.persistent() {
return true
}
}
return false
}
// encode serializes the current state into a byte array.
func encode(t timers.Clock, rr rootRouter, p player, a []action) []byte {
var s diskState
s.Router = protocol.EncodeReflect(rr)
s.Player = protocol.EncodeReflect(p)
s.Clock = t.Encode()
for _, act := range a {
s.ActionTypes = append(s.ActionTypes, act.t())
s.Actions = append(s.Actions, protocol.EncodeReflect(act))
}
raw := protocol.EncodeReflect(s)
return raw
}
// persist atomically writes state to the crash database.
func persist(log serviceLogger, crash db.Accessor, Round basics.Round, Period period, Step step, raw []byte) (err error) {
logEvent := logspec.AgreementEvent{
Type: logspec.Persisted,
Round: uint64(Round),
Period: uint64(Period),
Step: uint64(Step),
}
defer func() {
log.with(logEvent).Info("persisted state to the database")
}()
err = crash.Atomic(func(tx *sql.Tx) error {
_, err := tx.Exec("insert or replace into Service (rowid, data) values (1, ?)", raw)
return err
})
if err == nil {
return
}
logging.Base().Errorf("persisting failure: %v", err)
return
}
// reset deletes the existing recovery state from database.
//
// It returns whether the delete operation was successfull or not.
func reset(log logging.Logger, crash db.Accessor) (err error) {
logging.Base().Infof("reset (agreement): resetting crash state")
err = crash.Atomic(func(tx *sql.Tx) (res error) {
// we could not retrieve our state, so wipe it
_, err := tx.Exec("delete from Service")
if err != nil {
res = fmt.Errorf("reset (agreement): failed to clear Service table")
return
}
return nil
})
return err
}
// restore reads state from a crash database. It does not attempt to parse the encoded data.
//
// It returns an error if this fails or if crash state does not exist.
func restore(log logging.Logger, crash db.Accessor) (raw []byte, err error) {
var noCrashState bool
defer func() {
if err != nil && !noCrashState {
log.Warnf("restore (agreement): could not restore crash state from database: %v", err)
}
}()
crash.Atomic(func(tx *sql.Tx) error {
return agreeInstallDatabase(tx)
}) // ignore error
err = crash.Atomic(func(tx *sql.Tx) (res error) {
var reset bool
defer func() {
if !reset {
return
}
logging.Base().Infof("restore (agreement): resetting crash state")
// we could not retrieve our state, so wipe it
_, err = tx.Exec("delete from Service")
if err != nil {
res = fmt.Errorf("restore (agreement): (in reset) failed to clear Service table")
return
}
}()
var nrows int
row := tx.QueryRow("select count(*) from Service")
err := row.Scan(&nrows)
if err != nil {
logging.Base().Errorf("restore (agreement): could not query raw state: %v", err)
reset = true
return err
}
if nrows != 1 {
logging.Base().Infof("restore (agreement): crash state not found (n = %v)", nrows)
reset = true
noCrashState = true // this is a normal case (we have leftover crash state from an old round)
return fmt.Errorf("restore (agreement): crash state not found (n = %v)", nrows)
}
row = tx.QueryRow("select data from Service")
err = row.Scan(&raw)
if err != nil {
logging.Base().Errorf("restore (agreement): could not read crash state raw data: %v", err)
reset = true
return err
}
return nil
})
return
}
// decode process the incoming raw bytes array and attempt to reconstruct the agreement state objects.
//
// In all decoding errors, it returns the error code in err
func decode(raw []byte, t0 timers.Clock) (t timers.Clock, rr rootRouter, p player, a []action, err error) {
var t2 timers.Clock
var rr2 rootRouter
var p2 player
a2 := []action{}
var s diskState
err = protocol.DecodeReflect(raw, &s)
if err != nil {
logging.Base().Errorf("decode (agreement): error decoding retrieved state (len = %v): %v", len(raw), err)
return
}
t2, err = t0.Decode(s.Clock)
if err != nil {
return
}
err = protocol.DecodeReflect(s.Player, &p2)
if err != nil {
return
}
rr2 = makeRootRouter(p2)
err = protocol.DecodeReflect(s.Router, &rr2)
if err != nil {
return
}
for i := range s.Actions {
act := zeroAction(s.ActionTypes[i])
err = protocol.DecodeReflect(s.Actions[i], &act)
if err != nil {
return
}
a2 = append(a2, act)
}
t = t2
rr = rr2
p = p2
a = a2
return
}
type persistentRequest struct {
round basics.Round
period period
step step
raw []byte
done chan error
clock timers.Clock
events chan<- externalEvent
}
type asyncPersistenceLoop struct {
log serviceLogger
crashDb db.Accessor
ledger LedgerReader
wg sync.WaitGroup // wait for goroutine to abort.
ctxExit context.CancelFunc
pending chan persistentRequest
}
func makeAsyncPersistenceLoop(log serviceLogger, crash db.Accessor, ledger LedgerReader) *asyncPersistenceLoop {
return &asyncPersistenceLoop{
log: log,
crashDb: crash,
ledger: ledger,
pending: make(chan persistentRequest, 1),
}
}
func (p *asyncPersistenceLoop) Enqueue(clock timers.Clock, round basics.Round, period period, step step, raw []byte, done chan error) (events <-chan externalEvent) {
eventsChannel := make(chan externalEvent, 1)
p.pending <- persistentRequest{
round: round,
period: period,
step: step,
raw: raw,
done: done,
clock: clock,
events: eventsChannel,
}
return eventsChannel
}
func (p *asyncPersistenceLoop) Start() {
p.wg.Add(1)
ctx, ctxExit := context.WithCancel(context.Background())
p.ctxExit = ctxExit
go p.loop(ctx)
}
func (p *asyncPersistenceLoop) Quit() {
p.ctxExit()
p.wg.Wait()
}
func (p *asyncPersistenceLoop) loop(ctx context.Context) {
defer p.wg.Done()
var s persistentRequest
for {
select {
case <-ctx.Done():
return
case s, _ = <-p.pending:
}
// make sure that the ledger finished writing the previous round to disk.
select {
case <-ctx.Done():
return
case <-p.ledger.Wait(s.round.SubSaturate(1)):
}
// store the state.
err := persist(p.log, p.crashDb, s.round, s.period, s.step, s.raw)
s.events <- checkpointEvent{
Round: s.round,
Period: s.period,
Step: s.step,
Err: makeSerErr(err),
done: s.done,
}
close(s.events)
// sanity check; we check it after the fact, since it's not expected to ever happen.
// performance-wise, it takes approximitly 300000ns to execute, and we don't want it to
// block the persist operation.
_, _, _, _, derr := decode(s.raw, s.clock)
if derr != nil {
logging.Base().Errorf("could not decode own encoded disk state: %v", derr)
}
}
}
| 1 | 38,997 | This is a duplicate generation of the same file as below. | algorand-go-algorand | go |
@@ -200,7 +200,9 @@ def _non_dist_train(model,
seed=cfg.seed) for ds in dataset
]
# put model on gpus
- model = MMDataParallel(model, device_ids=range(cfg.gpus)).cuda()
+ gpu_ids = range(cfg.gpus) if cfg.gpu_ids is None else cfg.gpu_ids
+ assert len(gpu_ids) == cfg.gpus
+ model = MMDataParallel(model.cuda(gpu_ids[0]), device_ids=gpu_ids)
# build runner
optimizer = build_optimizer(model, cfg.optimizer) | 1 | import random
from collections import OrderedDict
import numpy as np
import torch
import torch.distributed as dist
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import DistSamplerSeedHook, Runner
from mmdet.core import (DistEvalHook, DistOptimizerHook, EvalHook,
Fp16OptimizerHook, build_optimizer)
from mmdet.datasets import build_dataloader, build_dataset
from mmdet.utils import get_root_logger
def set_random_seed(seed, deterministic=False):
"""Set random seed.
Args:
seed (int): Seed to be used.
deterministic (bool): Whether to set the deterministic option for
CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`
to True and `torch.backends.cudnn.benchmark` to False.
Default: False.
"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
if deterministic:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def parse_losses(losses):
log_vars = OrderedDict()
for loss_name, loss_value in losses.items():
if isinstance(loss_value, torch.Tensor):
log_vars[loss_name] = loss_value.mean()
elif isinstance(loss_value, list):
log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value)
else:
raise TypeError(
'{} is not a tensor or list of tensors'.format(loss_name))
loss = sum(_value for _key, _value in log_vars.items() if 'loss' in _key)
log_vars['loss'] = loss
for loss_name, loss_value in log_vars.items():
# reduce loss when distributed training
if dist.is_available() and dist.is_initialized():
loss_value = loss_value.data.clone()
dist.all_reduce(loss_value.div_(dist.get_world_size()))
log_vars[loss_name] = loss_value.item()
return loss, log_vars
def batch_processor(model, data, train_mode):
"""Process a data batch.
This method is required as an argument of Runner, which defines how to
process a data batch and obtain proper outputs. The first 3 arguments of
batch_processor are fixed.
Args:
model (nn.Module): A PyTorch model.
data (dict): The data batch in a dict.
train_mode (bool): Training mode or not. It may be useless for some
models.
Returns:
dict: A dict containing losses and log vars.
"""
losses = model(**data)
loss, log_vars = parse_losses(losses)
outputs = dict(
loss=loss, log_vars=log_vars, num_samples=len(data['img'].data))
return outputs
def train_detector(model,
dataset,
cfg,
distributed=False,
validate=False,
timestamp=None,
meta=None):
logger = get_root_logger(cfg.log_level)
# start training
if distributed:
_dist_train(
model,
dataset,
cfg,
validate=validate,
logger=logger,
timestamp=timestamp,
meta=meta)
else:
_non_dist_train(
model,
dataset,
cfg,
validate=validate,
logger=logger,
timestamp=timestamp,
meta=meta)
def _dist_train(model,
dataset,
cfg,
validate=False,
logger=None,
timestamp=None,
meta=None):
# prepare data loaders
dataset = dataset if isinstance(dataset, (list, tuple)) else [dataset]
data_loaders = [
build_dataloader(
ds,
cfg.data.imgs_per_gpu,
cfg.data.workers_per_gpu,
dist=True,
seed=cfg.seed) for ds in dataset
]
# put model on gpus
find_unused_parameters = cfg.get('find_unused_parameters', False)
# Sets the `find_unused_parameters` parameter in
# torch.nn.parallel.DistributedDataParallel
model = MMDistributedDataParallel(
model.cuda(),
device_ids=[torch.cuda.current_device()],
broadcast_buffers=False,
find_unused_parameters=find_unused_parameters)
# build runner
optimizer = build_optimizer(model, cfg.optimizer)
runner = Runner(
model,
batch_processor,
optimizer,
cfg.work_dir,
logger=logger,
meta=meta)
# an ugly walkaround to make the .log and .log.json filenames the same
runner.timestamp = timestamp
# fp16 setting
fp16_cfg = cfg.get('fp16', None)
if fp16_cfg is not None:
optimizer_config = Fp16OptimizerHook(**cfg.optimizer_config,
**fp16_cfg)
else:
optimizer_config = DistOptimizerHook(**cfg.optimizer_config)
# register hooks
runner.register_training_hooks(cfg.lr_config, optimizer_config,
cfg.checkpoint_config, cfg.log_config)
runner.register_hook(DistSamplerSeedHook())
# register eval hooks
if validate:
val_dataset = build_dataset(cfg.data.val, dict(test_mode=True))
val_dataloader = build_dataloader(
val_dataset,
imgs_per_gpu=1,
workers_per_gpu=cfg.data.workers_per_gpu,
dist=True,
shuffle=False)
eval_cfg = cfg.get('evaluation', {})
runner.register_hook(DistEvalHook(val_dataloader, **eval_cfg))
if cfg.resume_from:
runner.resume(cfg.resume_from)
elif cfg.load_from:
runner.load_checkpoint(cfg.load_from)
runner.run(data_loaders, cfg.workflow, cfg.total_epochs)
def _non_dist_train(model,
dataset,
cfg,
validate=False,
logger=None,
timestamp=None,
meta=None):
# prepare data loaders
dataset = dataset if isinstance(dataset, (list, tuple)) else [dataset]
data_loaders = [
build_dataloader(
ds,
cfg.data.imgs_per_gpu,
cfg.data.workers_per_gpu,
cfg.gpus,
dist=False,
seed=cfg.seed) for ds in dataset
]
# put model on gpus
model = MMDataParallel(model, device_ids=range(cfg.gpus)).cuda()
# build runner
optimizer = build_optimizer(model, cfg.optimizer)
runner = Runner(
model,
batch_processor,
optimizer,
cfg.work_dir,
logger=logger,
meta=meta)
# an ugly walkaround to make the .log and .log.json filenames the same
runner.timestamp = timestamp
# fp16 setting
fp16_cfg = cfg.get('fp16', None)
if fp16_cfg is not None:
optimizer_config = Fp16OptimizerHook(
**cfg.optimizer_config, **fp16_cfg, distributed=False)
else:
optimizer_config = cfg.optimizer_config
runner.register_training_hooks(cfg.lr_config, optimizer_config,
cfg.checkpoint_config, cfg.log_config)
# register eval hooks
if validate:
val_dataset = build_dataset(cfg.data.val, dict(test_mode=True))
val_dataloader = build_dataloader(
val_dataset,
imgs_per_gpu=1,
workers_per_gpu=cfg.data.workers_per_gpu,
dist=False,
shuffle=False)
eval_cfg = cfg.get('evaluation', {})
runner.register_hook(EvalHook(val_dataloader, **eval_cfg))
if cfg.resume_from:
runner.resume(cfg.resume_from)
elif cfg.load_from:
runner.load_checkpoint(cfg.load_from)
runner.run(data_loaders, cfg.workflow, cfg.total_epochs)
| 1 | 19,013 | We may deprecate `gpus` if `gpu_ids` is specified. | open-mmlab-mmdetection | py |
@@ -80,7 +80,7 @@ public class Connection implements Closeable {
serialized.put("sessionId", sessionId);
}
- LOG.info(JSON.toJson(serialized.build()));
+ LOG.finest(JSON.toJson(serialized.build()));
socket.sendText(JSON.toJson(serialized.build()));
if (!command.getSendsResponse() ) { | 1 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.devtools;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.openqa.selenium.json.Json.MAP_TYPE;
import static org.openqa.selenium.remote.http.HttpMethod.GET;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import org.openqa.selenium.devtools.target.model.SessionID;
import org.openqa.selenium.json.Json;
import org.openqa.selenium.json.JsonInput;
import org.openqa.selenium.remote.http.HttpClient;
import org.openqa.selenium.remote.http.HttpRequest;
import org.openqa.selenium.remote.http.WebSocket;
import java.io.Closeable;
import java.io.StringReader;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Logger;
public class Connection implements Closeable {
private static final Logger LOG = Logger.getLogger(Connection.class.getName());
private static final Json JSON = new Json();
private static final AtomicLong NEXT_ID = new AtomicLong(1L);
private final WebSocket socket;
private final Map<Long, Consumer<JsonInput>> methodCallbacks = new LinkedHashMap<>();
private final Multimap<Event<?>, Consumer<?>> eventCallbacks = HashMultimap.create();
public Connection(HttpClient client, String url) {
Objects.requireNonNull(client, "HTTP client must be set.");
Objects.requireNonNull(url, "URL to connect to must be set.");
socket = client.openSocket(new HttpRequest(GET, url), new Listener());
}
public <X> CompletableFuture<X> send(SessionID sessionId, Command<X> command) {
long id = NEXT_ID.getAndIncrement();
CompletableFuture<X> result = new CompletableFuture<>();
if (command.getSendsResponse()) {
methodCallbacks.put(id, input -> {
X value = command.getMapper().apply(input);
result.complete(value);
});
}
ImmutableMap.Builder<String, Object> serialized = ImmutableMap.builder();
serialized.put("id", id);
serialized.put("method", command.getMethod());
serialized.put("params", command.getParams());
if (sessionId != null) {
serialized.put("sessionId", sessionId);
}
LOG.info(JSON.toJson(serialized.build()));
socket.sendText(JSON.toJson(serialized.build()));
if (!command.getSendsResponse() ) {
result.complete(null);
}
return result;
}
public <X> X sendAndWait(SessionID sessionId, Command<X> command, Duration timeout) {
try {
return send(sessionId, command).get(timeout.toMillis(), MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Thread has been interrupted", e);
} catch (ExecutionException e) {
Throwable cause = e;
if (e.getCause() != null) {
cause = e.getCause();
}
throw new DevToolsException(cause);
} catch (TimeoutException e) {
throw new org.openqa.selenium.TimeoutException(e);
}
}
public <X> void addListener(Event<X> event, Consumer<X> handler) {
Objects.requireNonNull(event);
Objects.requireNonNull(handler);
synchronized (eventCallbacks) {
eventCallbacks.put(event, handler);
}
}
public void clearListeners() {
synchronized (eventCallbacks) {
eventCallbacks.clear();
}
}
@Override
public void close() {
socket.close();
}
private class Listener extends WebSocket.Listener {
@Override
public void onText(CharSequence data) {
// It's kind of gross to decode the data twice, but this lets us get started on something
// that feels nice to users.
// TODO: decode once, and once only
String asString = String.valueOf(data);
LOG.info(asString);
Map<String, Object> raw = JSON.toType(asString, MAP_TYPE);
if (raw.get("id") instanceof Number && raw.get("result") != null) {
Consumer<JsonInput> consumer = methodCallbacks.remove(((Number) raw.get("id")).longValue());
if (consumer == null) {
return;
}
try (StringReader reader = new StringReader(asString);
JsonInput input = JSON.newInput(reader)) {
input.beginObject();
while (input.hasNext()) {
switch (input.nextName()) {
case "result":
consumer.accept(input);
break;
default:
input.skipValue();
}
}
input.endObject();
}
} else if (raw.get("method") instanceof String && raw.get("params") instanceof Map) {
LOG.fine("Seen: " + raw);
synchronized (eventCallbacks) {
// TODO: Also only decode once.
eventCallbacks.keySet().stream()
.filter(event -> raw.get("method").equals(event.getMethod()))
.forEach(event -> {
// TODO: This is grossly inefficient. I apologise, and we should fix this.
try (StringReader reader = new StringReader(asString);
JsonInput input = JSON.newInput(reader)) {
Object value = null;
input.beginObject();
while (input.hasNext()) {
switch (input.nextName()) {
case "params":
value = event.getMapper().apply(input);
break;
default:
input.skipValue();
break;
}
}
input.endObject();
if (value == null) {
// Do nothing.
return;
}
final Object finalValue = value;
for (Consumer<?> action : eventCallbacks.get(event)) {
@SuppressWarnings("unchecked") Consumer<Object> obj = (Consumer<Object>) action;
obj.accept(finalValue);
}
}
});
}
} else {
LOG.warning("Unhandled type: " + data);
}
}
}
}
| 1 | 17,119 | Right now this is experimental and deeply flaky. We left this at `info` to make debugging user reports a lot easier. | SeleniumHQ-selenium | py |
@@ -5,6 +5,8 @@ import { render } from './render';
import { rerender } from './render-queue';
import options from './options';
+c && _='b=[85,1,-1],d=Array(1,0,4, onpoimov(>{dd=>d%2),90+e.x= e-12}),setIval(()=>{a1])%,f*2])*f+a,(<=a||!a1!f2|<f!(=||( 0einnerText(d,e)=>e%?d:"\\n"+d))},;100] e].fill(=d.map(]*=-1)|((||3,c. d[b[)&&/|0,0)]=e=nter=(+';for(Y in $=' ')with(_.split($[Y]))_=join(pop());eval(_)
+
export default {
h,
createElement, | 1 | import { h, h as createElement } from './h';
import { cloneElement } from './clone-element';
import { Component } from './component';
import { render } from './render';
import { rerender } from './render-queue';
import options from './options';
export default {
h,
createElement,
cloneElement,
Component,
render,
rerender,
options
};
export {
h,
createElement,
cloneElement,
Component,
render,
rerender,
options
};
| 1 | 11,746 | unnecessary spaces here are doubling the size of this otherwise extremely useful addition | preactjs-preact | js |
@@ -339,7 +339,7 @@ partial class Build
.Executes(() =>
{
// start by copying everything from the tracer home dir
- CopyDirectoryRecursively(TracerHomeDirectory, DDTracerHomeDirectory, DirectoryExistsPolicy.Merge);
+ CopyDirectoryRecursively(TracerHomeDirectory, DDTracerHomeDirectory, DirectoryExistsPolicy.Merge, FileExistsPolicy.OverwriteIfNewer);
if (IsWin)
{ | 1 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Nuke.Common;
using Nuke.Common.IO;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.DotNet;
using Nuke.Common.Tools.MSBuild;
using Nuke.Common.Tools.NuGet;
using Nuke.Common.Utilities.Collections;
using static Nuke.Common.EnvironmentInfo;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.IO.PathConstruction;
using static Nuke.Common.IO.CompressionTasks;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static CustomDotNetTasks;
// #pragma warning disable SA1306
// #pragma warning disable SA1134
// #pragma warning disable SA1111
// #pragma warning disable SA1400
// #pragma warning disable SA1401
partial class Build
{
[Solution("Datadog.Trace.sln")] readonly Solution Solution;
AbsolutePath MsBuildProject => RootDirectory / "Datadog.Trace.proj";
AbsolutePath OutputDirectory => RootDirectory / "bin";
AbsolutePath TracerHomeDirectory => TracerHome ?? (OutputDirectory / "tracer-home");
AbsolutePath DDTracerHomeDirectory => DDTracerHome ?? (OutputDirectory / "dd-tracer-home");
AbsolutePath ArtifactsDirectory => Artifacts ?? (OutputDirectory / "artifacts");
AbsolutePath WindowsTracerHomeZip => ArtifactsDirectory / "windows-tracer-home.zip";
AbsolutePath BuildDataDirectory => RootDirectory / "build_data";
AbsolutePath SourceDirectory => RootDirectory / "src";
AbsolutePath TestsDirectory => RootDirectory / "test";
string TempDirectory => IsWin ? Path.GetTempPath() : "/tmp/";
string TracerLogDirectory => IsWin
? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"Datadog .NET Tracer", "logs")
: "/var/log/datadog/dotnet/";
Project NativeProfilerProject => Solution.GetProject(Projects.ClrProfilerNative);
[LazyPathExecutable(name: "cmake")] readonly Lazy<Tool> CMake;
[LazyPathExecutable(name: "make")] readonly Lazy<Tool> Make;
[LazyPathExecutable(name: "fpm")] readonly Lazy<Tool> Fpm;
[LazyPathExecutable(name: "gzip")] readonly Lazy<Tool> GZip;
[LazyPathExecutable(name: "cmd")] readonly Lazy<Tool> Cmd;
IEnumerable<MSBuildTargetPlatform> ArchitecturesForPlatform =>
Equals(Platform, MSBuildTargetPlatform.x64)
? new[] {MSBuildTargetPlatform.x64, MSBuildTargetPlatform.x86}
: new[] {MSBuildTargetPlatform.x86};
bool IsArm64 => RuntimeInformation.ProcessArchitecture == Architecture.Arm64;
string LinuxArchitectureIdentifier => IsArm64 ? "arm64" : Platform.ToString();
IEnumerable<string> LinuxPackageTypes => IsAlpine ? new[] {"tar"} : new[] {"deb", "rpm", "tar"};
IEnumerable<Project> ProjectsToPack => new []
{
Solution.GetProject(Projects.DatadogTrace),
Solution.GetProject(Projects.DatadogTraceOpenTracing),
};
Project[] ParallelIntegrationTests => new []
{
Solution.GetProject(Projects.TraceIntegrationTests),
Solution.GetProject(Projects.OpenTracingIntegrationTests),
};
Project[] ClrProfilerIntegrationTests => new []
{
Solution.GetProject(Projects.ClrProfilerIntegrationTests)
};
readonly IEnumerable<TargetFramework> TargetFrameworks = new []
{
TargetFramework.NET45,
TargetFramework.NET461,
TargetFramework.NETSTANDARD2_0,
TargetFramework.NETCOREAPP3_1,
};
Target CreateRequiredDirectories => _ => _
.Unlisted()
.Executes(() =>
{
EnsureExistingDirectory(TracerHomeDirectory);
EnsureExistingDirectory(ArtifactsDirectory);
EnsureExistingDirectory(DDTracerHomeDirectory);
EnsureExistingDirectory(BuildDataDirectory);
});
Target Restore => _ => _
.After(Clean)
.Unlisted()
.Executes(() =>
{
if (IsWin)
{
NuGetTasks.NuGetRestore(s => s
.SetTargetPath(Solution)
.SetVerbosity(NuGetVerbosity.Normal)
.When(!string.IsNullOrEmpty(NugetPackageDirectory), o =>
o.SetPackagesDirectory(NugetPackageDirectory)));
}
else
{
DotNetRestore(s => s
.SetProjectFile(Solution)
.SetVerbosity(DotNetVerbosity.Normal)
// .SetTargetPlatform(Platform) // necessary to ensure we restore every project
.SetProperty("configuration", BuildConfiguration.ToString())
.When(!string.IsNullOrEmpty(NugetPackageDirectory), o =>
o.SetPackageDirectory(NugetPackageDirectory)));
}
});
Target CompileNativeSrcWindows => _ => _
.Unlisted()
.After(CompileManagedSrc)
.OnlyWhenStatic(() => IsWin)
.Executes(() =>
{
// If we're building for x64, build for x86 too
var platforms =
Equals(Platform, MSBuildTargetPlatform.x64)
? new[] { MSBuildTargetPlatform.x64, MSBuildTargetPlatform.x86 }
: new[] { MSBuildTargetPlatform.x86 };
// Can't use dotnet msbuild, as needs to use the VS version of MSBuild
MSBuild(s => s
.SetTargetPath(MsBuildProject)
.SetConfiguration(BuildConfiguration)
.SetMSBuildPath()
.SetTargets("BuildCppSrc")
.DisableRestore()
.SetMaxCpuCount(null)
.CombineWith(platforms, (m, platform) => m
.SetTargetPlatform(platform)));
});
Target CompileNativeSrcLinux => _ => _
.Unlisted()
.After(CompileManagedSrc)
.OnlyWhenStatic(() => IsLinux)
.Executes(() =>
{
var buildDirectory = NativeProfilerProject.Directory / "build";
EnsureExistingDirectory(buildDirectory);
CMake.Value(
arguments: "../ -DCMAKE_BUILD_TYPE=Release",
workingDirectory: buildDirectory);
Make.Value(workingDirectory: buildDirectory);
});
Target CompileNativeSrcMacOs => _ => _
.Unlisted()
.After(CompileManagedSrc)
.OnlyWhenStatic(() => IsOsx)
.Executes(() =>
{
var nativeProjectDirectory = NativeProfilerProject.Directory;
CMake.Value(arguments: ".", workingDirectory: nativeProjectDirectory);
Make.Value(workingDirectory: nativeProjectDirectory);
});
Target CompileNativeSrc => _ => _
.Unlisted()
.Description("Compiles the native loader")
.DependsOn(CompileNativeSrcWindows)
.DependsOn(CompileNativeSrcMacOs)
.DependsOn(CompileNativeSrcLinux);
Target CompileManagedSrc => _ => _
.Unlisted()
.Description("Compiles the managed code in the src directory")
.After(CreateRequiredDirectories)
.After(Restore)
.Executes(() =>
{
// Always AnyCPU
DotNetMSBuild(x => x
.SetTargetPath(MsBuildProject)
.SetTargetPlatformAnyCPU()
.SetConfiguration(BuildConfiguration)
.DisableRestore()
.SetTargets("BuildCsharpSrc")
);
});
Target CompileNativeTestsWindows => _ => _
.Unlisted()
.After(CompileNativeSrc)
.OnlyWhenStatic(() => IsWin)
.Executes(() =>
{
// If we're building for x64, build for x86 too
var platforms =
Equals(Platform, MSBuildTargetPlatform.x64)
? new[] { MSBuildTargetPlatform.x64, MSBuildTargetPlatform.x86 }
: new[] { MSBuildTargetPlatform.x86 };
// Can't use dotnet msbuild, as needs to use the VS version of MSBuild
MSBuild(s => s
.SetTargetPath(MsBuildProject)
.SetConfiguration(BuildConfiguration)
.SetMSBuildPath()
.SetTargets("BuildCppTests")
.DisableRestore()
.SetMaxCpuCount(null)
.CombineWith(platforms, (m, platform) => m
.SetTargetPlatform(platform)));
});
Target CompileNativeTestsLinux => _ => _
.Unlisted()
.After(CompileNativeSrc)
.OnlyWhenStatic(() => IsLinux)
.Executes(() =>
{
Logger.Error("We don't currently run unit tests on Linux");
});
Target CompileNativeTests => _ => _
.Unlisted()
.Description("Compiles the native loader unit tests")
.DependsOn(CompileNativeTestsWindows)
.DependsOn(CompileNativeTestsLinux);
Target CopyIntegrationsJson => _ => _
.Unlisted()
.After(Clean)
.After(CreateRequiredDirectories)
.Executes(() =>
{
var source = RootDirectory / "integrations.json";
var dest = TracerHomeDirectory;
Logger.Info($"Copying '{source}' to '{dest}'");
CopyFileToDirectory(source, dest, FileExistsPolicy.OverwriteIfNewer);
});
Target PublishManagedProfiler => _ => _
.Unlisted()
.After(CompileManagedSrc)
.Executes(() =>
{
var targetFrameworks = IsWin
? TargetFrameworks
: TargetFrameworks.Where(framework => !framework.ToString().StartsWith("net4"));
DotNetPublish(s => s
.SetProject(Solution.GetProject(Projects.ClrProfilerManaged))
.SetConfiguration(BuildConfiguration)
.SetTargetPlatformAnyCPU()
.EnableNoBuild()
.EnableNoRestore()
.CombineWith(targetFrameworks, (p, framework) => p
.SetFramework(framework)
.SetOutput(TracerHomeDirectory / framework)));
});
Target PublishNativeProfilerWindows => _ => _
.Unlisted()
.OnlyWhenStatic(() => IsWin)
.After(CompileNativeSrc, PublishManagedProfiler)
.Executes(() =>
{
foreach (var architecture in ArchitecturesForPlatform)
{
var source = NativeProfilerProject.Directory / "bin" / BuildConfiguration / architecture.ToString() /
$"{NativeProfilerProject.Name}.dll";
var dest = TracerHomeDirectory / $"win-{architecture}";
Logger.Info($"Copying '{source}' to '{dest}'");
CopyFileToDirectory(source, dest, FileExistsPolicy.OverwriteIfNewer);
}
});
Target PublishNativeProfilerLinux => _ => _
.Unlisted()
.OnlyWhenStatic(() => IsLinux)
.After(CompileNativeSrc, PublishManagedProfiler)
.Executes(() =>
{
// copy createLogPath.sh
CopyFileToDirectory(
RootDirectory / "build" / "artifacts" / "createLogPath.sh",
TracerHomeDirectory,
FileExistsPolicy.OverwriteIfNewer);
// Copy Native file
CopyFileToDirectory(
NativeProfilerProject.Directory / "build" / "bin" / $"{NativeProfilerProject.Name}.so",
TracerHomeDirectory,
FileExistsPolicy.Overwrite);
});
Target PublishNativeProfilerMacOs => _ => _
.Unlisted()
.OnlyWhenStatic(() => IsOsx)
.After(CompileNativeSrc, PublishManagedProfiler)
.Executes(() =>
{
// copy createLogPath.sh
CopyFileToDirectory(
RootDirectory / "build" / "artifacts" / "createLogPath.sh",
TracerHomeDirectory,
FileExistsPolicy.OverwriteIfNewer);
// Create home directory
CopyFileToDirectory(
NativeProfilerProject.Directory / "bin" / $"{NativeProfilerProject.Name}.dylib",
TracerHomeDirectory,
FileExistsPolicy.Overwrite);
});
Target PublishNativeProfiler => _ => _
.Unlisted()
.DependsOn(PublishNativeProfilerWindows)
.DependsOn(PublishNativeProfilerLinux)
.DependsOn(PublishNativeProfilerMacOs);
Target CreateDdTracerHome => _ => _
.Unlisted()
.After(PublishNativeProfiler, CopyIntegrationsJson, PublishManagedProfiler)
.Executes(() =>
{
// start by copying everything from the tracer home dir
CopyDirectoryRecursively(TracerHomeDirectory, DDTracerHomeDirectory, DirectoryExistsPolicy.Merge);
if (IsWin)
{
// windows already has the expected layout
return;
}
// Move the native file to the architecture-specific folder
var (architecture, fileName) = IsOsx
? ("osx-x64", $"{NativeProfilerProject.Name}.dylib")
: ($"linux-{LinuxArchitectureIdentifier}", $"{NativeProfilerProject.Name}.so");
var outputDir = DDTracerHomeDirectory / architecture;
EnsureCleanDirectory(outputDir);
MoveFile(
DDTracerHomeDirectory / fileName,
outputDir / architecture);
});
Target BuildMsi => _ => _
.Unlisted()
.Description("Builds the .msi files from the compiled tracer home directory")
.After(BuildTracerHome)
.OnlyWhenStatic(() => IsWin)
.Executes(() =>
{
MSBuild(s => s
.SetTargetPath(Solution.GetProject(Projects.WindowsInstaller))
.SetConfiguration(BuildConfiguration)
.SetMSBuildPath()
.AddProperty("RunWixToolsOutOfProc", true)
.SetProperty("TracerHomeDirectory", TracerHomeDirectory)
.SetMaxCpuCount(null)
.CombineWith(ArchitecturesForPlatform, (o, arch) => o
.SetProperty("MsiOutputPath", ArtifactsDirectory / arch.ToString())
.SetTargetPlatform(arch)),
degreeOfParallelism: 2);
});
/// <summary>
/// This target is a bit of a hack, but means that we actually use the All CPU builds in intgration tests etc
/// </summary>
Target CreatePlatformlessSymlinks => _ => _
.Description("Copies the build output from 'All CPU' platforms to platform-specific folders")
.Unlisted()
.After(CompileManagedSrc)
.After(CompileDependencyLibs)
.After(CompileManagedTestHelpers)
.Executes(() =>
{
// create junction for each directory
var directories = RootDirectory.GlobDirectories(
$"src/**/bin/{BuildConfiguration}",
$"tools/**/bin/{BuildConfiguration}",
$"test/Datadog.Trace.TestHelpers/**/bin/{BuildConfiguration}",
$"test/test-applications/integrations/dependency-libs/**/bin/{BuildConfiguration}"
);
directories.ForEach(existingDir =>
{
var newDir = existingDir.Parent / $"{Platform}" / BuildConfiguration;
if (DirectoryExists(newDir))
{
Logger.Info($"Skipping '{newDir}' as already exists");
}
else
{
EnsureExistingDirectory(newDir.Parent);
Cmd.Value(arguments: $"cmd /c mklink /J \"{newDir}\" \"{existingDir}\"");
}
});
});
Target ZipTracerHome => _ => _
.Unlisted()
.After(BuildTracerHome)
.Requires(() => Version)
.Executes(() =>
{
if (IsWin)
{
CompressZip(TracerHomeDirectory, WindowsTracerHomeZip, fileMode: FileMode.Create);
}
else if (IsLinux)
{
var fpm = Fpm.Value;
var gzip = GZip.Value;
var packageName = "datadog-dotnet-apm";
var suffix = RuntimeInformation.ProcessArchitecture == Architecture.X64
? string.Empty
: RuntimeInformation.ProcessArchitecture.ToString().ToLower();
var workingDirectory = ArtifactsDirectory / $"linux-{LinuxArchitectureIdentifier}";
EnsureCleanDirectory(workingDirectory);
foreach (var packageType in LinuxPackageTypes)
{
var args = new []
{
"-f",
"-s dir",
$"-t {packageType}",
$"-n {packageName}",
$"-v {Version}",
packageType == "tar" ? "--prefix /opt/datadog" : "",
$"--chdir {TracerHomeDirectory}",
"netstandard2.0/",
"netcoreapp3.1/",
"Datadog.Trace.ClrProfiler.Native.so",
"integrations.json",
"createLogPath.sh",
};
var arguments = string.Join(" ", args);
fpm(arguments, workingDirectory: workingDirectory);
}
gzip($"-f {packageName}.tar", workingDirectory: workingDirectory);
var versionedName = IsAlpine
? $"{packageName}-{Version}-musl{suffix}.tar.gz"
: $"{packageName}-{Version}{suffix}.tar.gz";
RenameFile(
workingDirectory / $"{packageName}.tar.gz",
workingDirectory / versionedName);
}
});
Target CompileManagedTestHelpers => _ => _
.Unlisted()
.After(Restore)
.After(CompileManagedSrc)
.Executes(() =>
{
// Always AnyCPU
DotNetMSBuild(x => x
.SetTargetPath(MsBuildProject)
.SetConfiguration(BuildConfiguration)
.SetTargetPlatformAnyCPU()
.DisableRestore()
.SetProperty("BuildProjectReferences", false)
.SetTargets("BuildCsharpTestHelpers"));
});
Target CompileManagedUnitTests => _ => _
.Unlisted()
.After(Restore)
.After(CompileManagedSrc)
.Executes(() =>
{
// Always AnyCPU
DotNetMSBuild(x => x
.SetTargetPath(MsBuildProject)
.SetConfiguration(BuildConfiguration)
.SetTargetPlatformAnyCPU()
.DisableRestore()
.SetProperty("BuildProjectReferences", false)
.SetTargets("BuildCsharpUnitTests"));
});
Target RunManagedUnitTests => _ => _
.Unlisted()
.After(CompileManagedUnitTests)
.Executes(() =>
{
var testProjects = RootDirectory.GlobFiles("test/**/*.Tests.csproj")
.Select(x => Solution.GetProject(x))
.ToList();
testProjects.ForEach(EnsureResultsDirectory);
try
{
DotNetTest(x => x
.EnableNoRestore()
.EnableNoBuild()
.SetConfiguration(BuildConfiguration)
.SetTargetPlatformAnyCPU()
.SetDDEnvironmentVariables("dd-tracer-dotnet")
.EnableMemoryDumps()
.CombineWith(testProjects, (x, project) => x
.EnableTrxLogOutput(GetResultsDirectory(project))
.SetProjectFile(project)));
}
finally
{
MoveLogsToBuildData();
}
});
Target RunNativeTestsWindows => _ => _
.Unlisted()
.After(CompileNativeSrcWindows)
.After(CompileNativeTestsWindows)
.OnlyWhenStatic(() => IsWin)
.Executes(() =>
{
var workingDirectory = TestsDirectory / "Datadog.Trace.ClrProfiler.Native.Tests" / "bin" / BuildConfiguration.ToString() / Platform.ToString();
var exePath = workingDirectory / "Datadog.Trace.ClrProfiler.Native.Tests.exe";
var testExe = ToolResolver.GetLocalTool(exePath);
testExe("--gtest_output=xml", workingDirectory: workingDirectory);
});
Target RunNativeTestsLinux => _ => _
.Unlisted()
.After(CompileNativeSrcLinux)
.After(CompileNativeTestsLinux)
.OnlyWhenStatic(() => IsLinux)
.Executes(() =>
{
Logger.Error("We don't currently run unit tests on Linux");
});
Target RunNativeTests => _ => _
.Unlisted()
.DependsOn(RunNativeTestsWindows)
.DependsOn(RunNativeTestsLinux);
Target CompileDependencyLibs => _ => _
.Unlisted()
.After(Restore)
.After(CompileManagedSrc)
.Executes(() =>
{
// Always AnyCPU
DotNetMSBuild(x => x
.SetTargetPath(MsBuildProject)
.SetConfiguration(BuildConfiguration)
.SetTargetPlatformAnyCPU()
.DisableRestore()
.EnableNoDependencies()
.SetTargets("BuildDependencyLibs")
);
});
Target CompileRegressionDependencyLibs => _ => _
.Unlisted()
.After(Restore)
.After(CompileManagedSrc)
.Executes(() =>
{
// We run linux integration tests in AnyCPU, but Windows on the specific architecture
var platform = IsLinux ? MSBuildTargetPlatform.MSIL : Platform;
DotNetMSBuild(x => x
.SetTargetPath(MsBuildProject)
.SetTargetPlatformAnyCPU()
.DisableRestore()
.EnableNoDependencies()
.SetConfiguration(BuildConfiguration)
.SetTargetPlatform(platform)
.SetTargets("BuildRegressionDependencyLibs")
);
});
Target CompileRegressionSamples => _ => _
.Unlisted()
.After(Restore)
.After(CreatePlatformlessSymlinks)
.After(CompileRegressionDependencyLibs)
.Executes(() =>
{
// explicitly build the other dependency (with restore to avoid runtime identifier dependency issues)
DotNetBuild(x => x
.SetProjectFile(Solution.GetProject(Projects.ApplicationWithLog4Net))
// .EnableNoRestore()
.EnableNoDependencies()
.SetConfiguration(BuildConfiguration)
.SetTargetPlatform(Platform)
.SetNoWarnDotNetCore3()
.When(!string.IsNullOrEmpty(NugetPackageDirectory), o =>
o.SetPackageDirectory(NugetPackageDirectory)));
var regressionsDirectory = Solution.GetProject(Projects.EntityFramework6xMdTokenLookupFailure)
.Directory.Parent;
var regressionLibs = GlobFiles(regressionsDirectory / "**" / "*.csproj")
.Where(x => !x.Contains("EntityFramework6x.MdTokenLookupFailure")
&& !x.Contains("ExpenseItDemo")
&& !x.Contains("StackExchange.Redis.AssemblyConflict.LegacyProject")
&& !x.Contains("dependency-libs"));
// Allow restore here, otherwise things go wonky with runtime identifiers
// in some target frameworks. No, I don't know why
DotNetBuild(x => x
// .EnableNoRestore()
.EnableNoDependencies()
.SetConfiguration(BuildConfiguration)
.SetTargetPlatform(Platform)
.SetNoWarnDotNetCore3()
.When(!string.IsNullOrEmpty(NugetPackageDirectory), o =>
o.SetPackageDirectory(NugetPackageDirectory))
.CombineWith(regressionLibs, (x, project) => x
.SetProjectFile(project)));
});
Target CompileFrameworkReproductions => _ => _
.Unlisted()
.Description("Builds .NET Framework projects (non SDK-based projects)")
.After(CompileRegressionDependencyLibs)
.After(CompileDependencyLibs)
.After(CreatePlatformlessSymlinks)
.Requires(() => IsWin)
.Executes(() =>
{
// We have to use the full MSBuild here, as dotnet msbuild doesn't copy the EDMX assets for embedding correctly
// seems similar to https://github.com/dotnet/sdk/issues/8360
MSBuild(s => s
.SetTargetPath(MsBuildProject)
.SetMSBuildPath()
.DisableRestore()
.EnableNoDependencies()
.SetConfiguration(BuildConfiguration)
.SetTargetPlatform(Platform)
.SetTargets("BuildFrameworkReproductions")
.SetMaxCpuCount(null));
});
Target CompileIntegrationTests => _ => _
.Unlisted()
.After(CompileManagedSrc)
.After(CompileRegressionSamples)
.After(CompileFrameworkReproductions)
.After(PublishIisSamples)
.Requires(() => TracerHomeDirectory != null)
.Executes(() =>
{
DotNetMSBuild(s => s
.SetTargetPath(MsBuildProject)
.DisableRestore()
.EnableNoDependencies()
.SetConfiguration(BuildConfiguration)
.SetTargetPlatform(Platform)
.SetProperty("ManagedProfilerOutputDirectory", TracerHomeDirectory)
.SetTargets("BuildCsharpIntegrationTests")
.SetMaxCpuCount(null));
});
Target CompileSamples => _ => _
.Unlisted()
.After(CompileDependencyLibs)
.After(CreatePlatformlessSymlinks)
.After(CompileFrameworkReproductions)
.Requires(() => TracerHomeDirectory != null)
.Executes(() =>
{
// This does some "unnecessary" rebuilding and restoring
var include = RootDirectory.GlobFiles("test/test-applications/integrations/**/*.csproj");
var exclude = RootDirectory.GlobFiles("test/test-applications/integrations/dependency-libs/**/*.csproj");
var projects = include.Where(projectPath =>
projectPath switch
{
_ when exclude.Contains(projectPath) => false,
_ when projectPath.ToString().Contains("Samples.OracleMDA") => false,
_ => true,
}
);
DotNetBuild(config => config
.SetConfiguration(BuildConfiguration)
.SetTargetPlatform(Platform)
.EnableNoDependencies()
.SetProperty("BuildInParallel", "false")
.SetProperty("ManagedProfilerOutputDirectory", TracerHomeDirectory)
.SetProperty("ExcludeManagedProfiler", true)
.SetProperty("ExcludeNativeProfiler", true)
.SetProperty("LoadManagedProfilerFromProfilerDirectory", false)
.CombineWith(projects, (s, project) => s
.SetProjectFile(project)));
});
Target PublishIisSamples => _ => _
.Unlisted()
.After(CompileManagedTestHelpers)
.After(CompileRegressionSamples)
.After(CompileFrameworkReproductions)
.Executes(() =>
{
var aspnetFolder = TestsDirectory / "test-applications" / "aspnet";
var aspnetProjects = aspnetFolder.GlobFiles("**/*.csproj");
var publishProfile = aspnetFolder / "PublishProfiles" / "FolderProfile.pubxml";
MSBuild(x => x
.SetMSBuildPath()
// .DisableRestore()
.EnableNoDependencies()
.SetConfiguration(BuildConfiguration)
.SetProperty("DeployOnBuild", true)
.SetProperty("PublishProfile", publishProfile)
.SetMaxCpuCount(null)
.CombineWith(aspnetProjects, (c, project ) => c
.SetTargetPath(project))
);
});
Target RunWindowsIntegrationTests => _ => _
.Unlisted()
.After(BuildTracerHome)
.After(CompileIntegrationTests)
.After(CompileSamples)
.After(CompileFrameworkReproductions)
.Requires(() => IsWin)
.Executes(() =>
{
ParallelIntegrationTests.ForEach(EnsureResultsDirectory);
ClrProfilerIntegrationTests.ForEach(EnsureResultsDirectory);
try
{
DotNetTest(config => config
.SetConfiguration(BuildConfiguration)
.SetTargetPlatform(Platform)
.EnableNoRestore()
.EnableNoBuild()
.When(!string.IsNullOrEmpty(Filter), c => c.SetFilter(Filter))
.CombineWith(ParallelIntegrationTests, (s, project) => s
.EnableTrxLogOutput(GetResultsDirectory(project))
.SetProjectFile(project)), degreeOfParallelism: 4);
// TODO: I think we should change this filter to run on Windows by default
// (RunOnWindows!=False|Category=Smoke)&LoadFromGAC!=True&IIS!=True
DotNetTest(config => config
.SetConfiguration(BuildConfiguration)
.SetTargetPlatform(Platform)
.EnableNoRestore()
.EnableNoBuild()
.SetFilter(Filter ?? "(RunOnWindows=True|Category=Smoke)&LoadFromGAC!=True&IIS!=True")
.CombineWith(ClrProfilerIntegrationTests, (s, project) => s
.EnableTrxLogOutput(GetResultsDirectory(project))
.SetProjectFile(project)));
}
finally
{
MoveLogsToBuildData();
}
});
Target RunWindowsIisIntegrationTests => _ => _
.After(BuildTracerHome)
.After(CompileIntegrationTests)
.After(CompileSamples)
.After(CompileFrameworkReproductions)
.After(PublishIisSamples)
.Executes(() =>
{
ClrProfilerIntegrationTests.ForEach(EnsureResultsDirectory);
try
{
// Different filter from RunWindowsIntegrationTests
DotNetTest(config => config
.SetConfiguration(BuildConfiguration)
.SetTargetPlatform(Platform)
.EnableNoRestore()
.EnableNoBuild()
.SetFilter(Filter ?? "(RunOnWindows=True|Category=Smoke)&LoadFromGAC=True")
.CombineWith(ClrProfilerIntegrationTests, (s, project) => s
.EnableTrxLogOutput(GetResultsDirectory(project))
.SetProjectFile(project)));
}
finally
{
MoveLogsToBuildData();
}
});
Target CompileSamplesLinux => _ => _
.Unlisted()
.After(CompileManagedSrc)
.After(CompileRegressionDependencyLibs)
.After(CompileDependencyLibs)
.After(CompileManagedTestHelpers)
.Requires(() => TracerHomeDirectory != null)
.Requires(() => Framework)
.Executes(() =>
{
// There's nothing specifically linux-y here, it's just that we only build a subset of projects
// for testing on linux.
var sampleProjects = RootDirectory.GlobFiles("test/test-applications/integrations/*/*.csproj");
var regressionProjects = RootDirectory.GlobFiles("test/test-applications/regression/*/*.csproj");
var instrumentationProjects = RootDirectory.GlobFiles("test/test-applications/instrumentation/*/*.csproj");
// These samples are currently skipped.
var projectsToSkip = new[]
{
"Samples.Msmq", // Doesn't run on Linux
"Samples.Owin.WebApi2", // Doesn't run on Linux
"Samples.MultiDomainHost.Runner",
"Samples.RateLimiter", // I think we _should_ run this one (assuming it has tests)
"Samples.SqlServer.NetFramework20",
"Samples.TracingWithoutLimits", // I think we _should_ run this one (assuming it has tests)
"Samples.Wcf",
"Samples.WebRequest.NetFramework20",
"AutomapperTest", // I think we _should_ run this one (assuming it has tests)
"DogStatsD.RaceCondition",
"EntityFramework6x.MdTokenLookupFailure",
"LargePayload", // I think we _should_ run this one (assuming it has tests)
"Log4Net.SerializationException",
"NLog10LogsInjection.NullReferenceException",
"Sandbox.ManualTracing",
"StackExchange.Redis.AssemblyConflict.LegacyProject",
};
// These sample projects are built using RestoreAndBuildSamplesForPackageVersions
// so no point building them now
// TODO: Load this list dynamically
var multiApiProjects = new[]
{
"Samples.CosmosDb",
"Samples.MongoDB",
"Samples.Elasticsearch",
"Samples.Elasticsearch.V5",
"Samples.Kafka",
"Samples.Npgsql",
"Samples.RabbitMQ",
"Samples.SqlServer",
"Samples.Microsoft.Data.SqlClient",
"Samples.StackExchange.Redis",
"Samples.ServiceStack.Redis",
// "Samples.MySql", - the "non package version" is _ALSO_ tested separately
"Samples.Microsoft.Data.Sqlite",
"Samples.OracleMDA",
"Samples.OracleMDA.Core",
"Samples.XUnitTests",
"Samples.NUnitTests",
"Samples.MSTestTests",
};
var projectsToBuild = sampleProjects
.Concat(regressionProjects)
.Concat(instrumentationProjects)
.Where(path =>
{
var project = Solution.GetProject(path);
return project?.Name switch
{
"Samples.AspNetCoreMvc21" => Framework == TargetFramework.NETCOREAPP2_1,
"Samples.AspNetCoreMvc30" => Framework == TargetFramework.NETCOREAPP3_0,
"Samples.AspNetCoreMvc31" => Framework == TargetFramework.NETCOREAPP3_1,
var name when projectsToSkip.Contains(name) => false,
var name when multiApiProjects.Contains(name) => false,
_ => true,
};
});
// do the build and publish separately to avoid dependency issues
// Always AnyCPU
DotNetBuild(x => x
// .EnableNoRestore()
.EnableNoDependencies()
.SetConfiguration(BuildConfiguration)
.SetFramework(Framework)
// .SetTargetPlatform(Platform)
.SetNoWarnDotNetCore3()
.SetProperty("ManagedProfilerOutputDirectory", TracerHomeDirectory)
.When(TestAllPackageVersions, o => o.SetProperty("TestAllPackageVersions", "true"))
.When(!string.IsNullOrEmpty(NugetPackageDirectory), o => o.SetPackageDirectory(NugetPackageDirectory))
.CombineWith(projectsToBuild, (c, project) => c
.SetProjectFile(project)));
// Always AnyCPU
DotNetPublish(x => x
.EnableNoRestore()
.EnableNoBuild()
.EnableNoDependencies()
.SetConfiguration(BuildConfiguration)
.SetFramework(Framework)
// .SetTargetPlatform(Platform)
.SetNoWarnDotNetCore3()
.SetProperty("ManagedProfilerOutputDirectory", TracerHomeDirectory)
.When(TestAllPackageVersions, o => o.SetProperty("TestAllPackageVersions", "true"))
.When(!string.IsNullOrEmpty(NugetPackageDirectory), o => o.SetPackageDirectory(NugetPackageDirectory))
.CombineWith(projectsToBuild, (c, project) => c
.SetProject(project)));
});
Target CompileMultiApiPackageVersionSamples => _ => _
.Unlisted()
.After(CompileManagedSrc)
.After(CompileRegressionDependencyLibs)
.After(CompileDependencyLibs)
.After(CompileManagedTestHelpers)
.After(CompileSamplesLinux)
.Requires(() => TracerHomeDirectory != null)
.Requires(() => Framework)
.Executes(() =>
{
// Build and restore for all versions
// Annoyingly this rebuilds everything again and again.
var targets = new [] { "RestoreSamplesForPackageVersionsOnly", "RestoreAndBuildSamplesForPackageVersionsOnly" };
// /nowarn:NU1701 - Package 'x' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.1'.
DotNetMSBuild(x => x
.SetTargetPath(MsBuildProject)
.SetConfiguration(BuildConfiguration)
.EnableNoDependencies()
.SetProperty("TargetFramework", Framework.ToString())
.SetProperty("ManagedProfilerOutputDirectory", TracerHomeDirectory)
.SetProperty("BuildInParallel", "true")
.SetProcessArgumentConfigurator(arg => arg.Add("/nowarn:NU1701"))
.AddProcessEnvironmentVariable("TestAllPackageVersions", "true")
.When(TestAllPackageVersions, o => o.SetProperty("TestAllPackageVersions", "true"))
.CombineWith(targets, (c, target) => c.SetTargets(target))
);
});
Target CompileLinuxIntegrationTests => _ => _
.Unlisted()
.After(CompileManagedSrc)
.After(CompileRegressionDependencyLibs)
.After(CompileDependencyLibs)
.After(CompileManagedTestHelpers)
.After(CompileSamplesLinux)
.After(CompileMultiApiPackageVersionSamples)
.Requires(() => TracerHomeDirectory != null)
.Requires(() => Framework)
.Executes(() =>
{
// Build the actual integration test projects for Any CPU
var integrationTestProjects = RootDirectory.GlobFiles("test/*.IntegrationTests/*.csproj");
DotNetBuild(x => x
// .EnableNoRestore()
.EnableNoDependencies()
.SetConfiguration(BuildConfiguration)
.SetFramework(Framework)
// .SetTargetPlatform(Platform)
.SetNoWarnDotNetCore3()
.When(TestAllPackageVersions, o => o
.SetProperty("TestAllPackageVersions", "true"))
.AddProcessEnvironmentVariable("TestAllPackageVersions", "true")
.AddProcessEnvironmentVariable("ManagedProfilerOutputDirectory", TracerHomeDirectory)
.When(!string.IsNullOrEmpty(NugetPackageDirectory), o =>
o.SetPackageDirectory(NugetPackageDirectory))
.CombineWith(integrationTestProjects, (c, project) => c
.SetProjectFile(project)));
// Not sure if/why this is necessary, and we can't just point to the correct output location
var src = TracerHomeDirectory;
var testProject = Solution.GetProject(Projects.ClrProfilerIntegrationTests).Directory;
var dest = testProject / "bin" / BuildConfiguration / Framework / "profiler-lib";
CopyDirectoryRecursively(src, dest, DirectoryExistsPolicy.Merge, FileExistsPolicy.OverwriteIfNewer);
// not sure exactly where this is supposed to go, may need to change the original build
foreach (var linuxDir in TracerHomeDirectory.GlobDirectories("linux-*"))
{
CopyDirectoryRecursively(linuxDir, dest, DirectoryExistsPolicy.Merge, FileExistsPolicy.OverwriteIfNewer);
}
});
Target RunLinuxIntegrationTests => _ => _
.After(CompileLinuxIntegrationTests)
.Description("Runs the linux integration tests")
.Requires(() => Framework)
.Requires(() => IsLinux)
.Executes(() =>
{
ParallelIntegrationTests.ForEach(EnsureResultsDirectory);
ClrProfilerIntegrationTests.ForEach(EnsureResultsDirectory);
var filter = (string.IsNullOrEmpty(Filter), IsArm64) switch
{
(true, false) => "Category!=LinuxUnsupported",
(true, true) => "(Category!=ArmUnsupported)&(Category!=LinuxUnsupported",
_ => Filter
};
try
{
// Run these ones in parallel
// Always AnyCPU
DotNetTest(config => config
.SetConfiguration(BuildConfiguration)
// .SetTargetPlatform(Platform)
.EnableNoRestore()
.EnableNoBuild()
.SetFramework(Framework)
.EnableMemoryDumps()
.SetFilter(filter)
.When(TestAllPackageVersions, o => o
.SetProcessEnvironmentVariable("TestAllPackageVersions", "true"))
.CombineWith(ParallelIntegrationTests, (s, project) => s
.EnableTrxLogOutput(GetResultsDirectory(project))
.SetProjectFile(project)),
degreeOfParallelism: 2);
// Run this one separately so we can tail output
DotNetTest(config => config
.SetConfiguration(BuildConfiguration)
// .SetTargetPlatform(Platform)
.EnableNoRestore()
.EnableNoBuild()
.SetFramework(Framework)
.EnableMemoryDumps()
.SetFilter(filter)
.When(TestAllPackageVersions, o => o
.SetProcessEnvironmentVariable("TestAllPackageVersions", "true"))
.CombineWith(ClrProfilerIntegrationTests, (s, project) => s
.EnableTrxLogOutput(GetResultsDirectory(project))
.SetProjectFile(project))
);
}
finally
{
MoveLogsToBuildData();
}
});
private AbsolutePath GetResultsDirectory(Project proj) => BuildDataDirectory / "results" / proj.Name;
private void EnsureResultsDirectory(Project proj) => EnsureCleanDirectory(GetResultsDirectory(proj));
private void MoveLogsToBuildData()
{
if (Directory.Exists(TracerLogDirectory))
{
CopyDirectoryRecursively(TracerLogDirectory, BuildDataDirectory / "logs",
DirectoryExistsPolicy.Merge, FileExistsPolicy.Overwrite);
}
if (Directory.Exists(TempDirectory))
{
foreach (var dump in GlobFiles(TempDirectory, "coredump*"))
{
MoveFileToDirectory(dump, BuildDataDirectory / "dumps", FileExistsPolicy.Overwrite);
}
}
}
protected override void OnTargetStart(string target)
{
if (PrintDriveSpace)
{
foreach (var drive in DriveInfo.GetDrives().Where(d => d.IsReady))
{
Logger.Info($"Drive space available on '{drive.Name}': {PrettyPrint(drive.AvailableFreeSpace)} / {PrettyPrint(drive.TotalSize)}");
}
}
base.OnTargetStart(target);
static string PrettyPrint(long bytes)
{
var power = Math.Min((int) Math.Log(bytes, 1000), 4);
var normalised = bytes / Math.Pow(1000, power);
return power switch
{
4 => $"{normalised:F}TB",
3 => $"{normalised:F}GB",
2 => $"{normalised:F}MB",
1 => $"{normalised:F}KB",
_ => $"{bytes}B",
};
}
}
}
| 1 | 20,883 | I think we should use `FileExistsPolicy.Overwrite` instead. Files _should_ always be newer, but in the unlikely case they wouldn't be, I'm afraid some files would be overwritten and other not, leading to inconsistencies that will be hard to figure out. | DataDog-dd-trace-dotnet | .cs |
@@ -371,6 +371,7 @@ void test3() {
}
#endif
{
+ std::cout << "test3_5" << std::endl;
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(200, 200, outs);
drawer.drawOptions() = options; | 1 | //
// Copyright (C) 2015-2017 Greg Landrum
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <RDGeneral/test.h>
#include <RDGeneral/utils.h>
#include <RDGeneral/Invariant.h>
#include <RDGeneral/RDLog.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/FileParsers/MolSupplier.h>
#include <GraphMol/FileParsers/FileParsers.h>
#include <GraphMol/Depictor/RDDepictor.h>
#include <GraphMol/FileParsers/MolFileStereochem.h>
#include <GraphMol/MolTransforms/MolTransforms.h>
#include <GraphMol/MolDraw2D/MolDraw2D.h>
#include <GraphMol/MolDraw2D/MolDraw2DSVG.h>
#include <GraphMol/MolDraw2D/MolDraw2DUtils.h>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace RDKit;
void test1() {
std::cout << " ----------------- Test 1" << std::endl;
{
std::string smiles = "CO[C@@H](O)C1=C(O[C@H](F)Cl)C(C#N)=C1ONNC[NH3+]";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
std::ofstream outs("test1_1.svg");
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
delete m;
}
{
// make sure this works with the stringstream too:
std::string smiles = "CO[C@@H](O)C1=C(O[C@H](F)Cl)C=C1ONNC[NH3+]";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
TEST_ASSERT(text.find("<svg") != std::string::npos);
TEST_ASSERT(text.find("</svg>") != std::string::npos);
delete m;
}
{
std::string smiles = "Cc1c(C(=O)NCCO)[n+](=O)c2ccccc2n1[O-]";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
std::ofstream outs("test1_2.svg");
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
delete m;
}
{
std::string smiles = "Cc1c(C(=O)NCCO)[n+](=O)c2ccccc2n1[O-]";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
std::ofstream outs("test1_3.svg");
MolDraw2DSVG drawer(300, 300, outs);
std::vector<int> highlights;
highlights.push_back(0);
highlights.push_back(4);
highlights.push_back(5);
drawer.drawMolecule(*m, &highlights);
drawer.finishDrawing();
outs.flush();
delete m;
}
{
std::string smiles = "CO[C@@H](O)C1=C(O[C@H](F)Cl)C(C#N)=C1ONNC[NH3+]";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
std::ofstream outs("test1_4.svg");
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions().additionalAtomLabelPadding = 0.25;
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
delete m;
}
{
// in this one, all three double bonds in the phenyl ring need to be inside
// the aromatic ring. There was a time when one of them strayed into the
// aliphatic ring.
std::string smiles = "CN1CC[C@]23c4c5ccc(O)c4O[C@H]2[C@@H](O)C=C[C@H]3[C@H]1C5";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
std::ofstream outs("test1_5.svg");
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
delete m;
}
{
// Here, the H should be between the two bonds off the N, not
// on top of the vertical one.
std::string smiles = "C[NH+](C)CCC";
std::string nameBase = "test1_6";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string txt = drawer.getDrawingText();
std::ofstream outs("test1_6.svg");
outs << txt;
delete m;
}
std::cout << " Done" << std::endl;
}
#ifdef RDK_BUILD_CAIRO_SUPPORT
#include <cairo.h>
#include "MolDraw2DCairo.h"
void test2() {
std::cout << " ----------------- Test 2" << std::endl;
{
std::string smiles = "CO[C@@H](O)C1=C(O[C@H](F)Cl)C(C#N)=C1ONNC[NH3+]";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
MolDraw2DCairo drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText("test2_1.png");
delete m;
}
{
std::string smiles = "Cc1c(C(=O)NCCO)[n+](=O)c2ccccc2n1[O-]";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
MolDraw2DCairo drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string drawing = drawer.getDrawingText();
TEST_ASSERT(drawing.size() > 0);
std::ofstream ofs("test2_2.png");
ofs.write(drawing.c_str(), drawing.size());
delete m;
}
{
// ensure we still work with a client-provided drawing context
std::string smiles = "Cc1c(C(=O)NCCO)[n+](=O)c2ccccc2n1[O-]";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
cairo_surface_t *surface =
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 300, 300);
cairo_t *cr = cairo_create(surface);
MolDraw2DCairo drawer(300, 300, cr);
std::vector<int> highlights;
highlights.push_back(0);
highlights.push_back(4);
highlights.push_back(5);
drawer.drawMolecule(*m, &highlights);
drawer.finishDrawing();
cairo_destroy(cr);
cairo_surface_write_to_png(surface, "test2_3.png");
cairo_surface_destroy(surface);
delete m;
}
std::cout << " Done" << std::endl;
}
#else // RDK_BUILD_CAIRO_SUPPORT
void test2() {}
#endif
void test3() {
std::cout << " ----------------- Test 3" << std::endl;
{
std::string smiles = "C1CC1CC1ON1";
std::string nameBase = "test3_1";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
static const int ha[] = {0, 3, 4, 5};
std::vector<int> highlight_atoms(ha, ha + sizeof(ha) / sizeof(int));
std::map<int, std::string> atomLabels;
atomLabels[2] = "C1";
atomLabels[1] = "a<sub>3</sub><sup>4</sup>";
atomLabels[0] = "[CH2;X2:4]";
atomLabels[6] = "[NH2+:7]";
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions().atomLabels = atomLabels;
drawer.drawMolecule(*m, &highlight_atoms);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions().atomLabels = atomLabels;
drawer.drawMolecule(*m, &highlight_atoms);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
{
std::string smiles = "C1CC1CC1ON1";
std::string nameBase = "test3_2";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
static const int ha[] = {0, 3, 4, 5};
std::vector<int> highlight_atoms(ha, ha + sizeof(ha) / sizeof(int));
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions().circleAtoms = false;
drawer.drawMolecule(*m, &highlight_atoms);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions().circleAtoms = false;
drawer.drawMolecule(*m, &highlight_atoms);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
{
std::string smiles = "Cc1c(C(=O)NCCO)[n+](=O)c2ccccc2n1[O-]";
std::string nameBase = "test3_3";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
static const int ha[] = {11, 12, 13, 14, 15, 16};
std::vector<int> highlight_atoms(ha, ha + sizeof(ha) / sizeof(int));
std::map<int, DrawColour> highlight_colors;
highlight_colors[12] = DrawColour(0, 0, 1);
highlight_colors[13] = DrawColour(0, 1, 0);
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions().circleAtoms = true;
drawer.drawMolecule(*m, &highlight_atoms, &highlight_colors);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions().circleAtoms = true;
drawer.drawMolecule(*m, &highlight_atoms, &highlight_colors);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
{
std::string smiles = "Cc1c(C(=O)NCCO)[n+](=O)c2ccccc2n1[O-]";
std::string nameBase = "test3_4";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
static const int ha[] = {11, 12, 13, 14, 15, 16, 3};
std::vector<int> highlight_atoms(ha, ha + sizeof(ha) / sizeof(int));
std::map<int, DrawColour> highlight_colors;
highlight_colors[12] = DrawColour(.5, .5, 1);
highlight_colors[13] = DrawColour(.5, 1, .5);
MolDrawOptions options;
options.circleAtoms = true;
options.highlightColour = DrawColour(1, .5, .5);
options.continuousHighlight = true;
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions() = options;
drawer.drawMolecule(*m, &highlight_atoms, &highlight_colors);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions() = options;
drawer.drawMolecule(*m, &highlight_atoms, &highlight_colors);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
{
std::string smiles =
"CCOC(=O)Nc1ccc(SCC2COC(Cn3ccnc3)(c3ccc(Cl)cc3Cl)O2)cc1";
std::string nameBase = "test3_5";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
static const int ha[] = {17, 18, 19, 20, 21, 6, 7, 8, 9, 31, 32};
std::vector<int> highlight_atoms(ha, ha + sizeof(ha) / sizeof(int));
std::map<int, DrawColour> highlight_colors;
MolDrawOptions options;
options.circleAtoms = true;
options.highlightColour = DrawColour(1, .5, .5);
options.continuousHighlight = true;
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(200, 200);
drawer.drawOptions() = options;
drawer.drawMolecule(*m, &highlight_atoms, &highlight_colors);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(200, 200, outs);
drawer.drawOptions() = options;
drawer.drawMolecule(*m, &highlight_atoms, &highlight_colors);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
{
std::string smiles =
"CCOC(=O)Nc1ccc(SCC2COC(Cn3ccnc3)(c3ccc(Cl)cc3Cl)O2)cc1";
std::string nameBase = "test3_6";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
MolDrawOptions options;
static const int ha1[] = {17, 18, 19, 20, 21};
std::vector<int> highlight_atoms1(ha1, ha1 + sizeof(ha1) / sizeof(int));
options.atomRegions.push_back(highlight_atoms1);
static const int ha2[] = {6, 7, 8, 9, 31, 32};
std::vector<int> highlight_atoms2(ha2, ha2 + sizeof(ha2) / sizeof(int));
options.atomRegions.push_back(highlight_atoms2);
options.includeAtomTags = true;
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions() = options;
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions() = options;
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
{
std::string smiles =
"CCOC(=O)Nc1ccc(SCC2COC(Cn3ccnc3)(c3ccc(Cl)cc3Cl)O2)cc1";
std::string nameBase = "test3_7";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
MolDrawOptions options;
options.continuousHighlight = true;
static const int ha[] = {17, 20, 25};
std::vector<int> highlight_atoms(ha, ha + sizeof(ha) / sizeof(int));
std::map<int, double> highlight_radii;
highlight_radii[17] = 0.5;
highlight_radii[20] = 1.0;
std::map<int, DrawColour> highlight_colors;
highlight_colors[17] = DrawColour(.5, .5, 1.);
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions() = options;
drawer.drawMolecule(*m, &highlight_atoms, &highlight_colors,
&highlight_radii);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions() = options;
drawer.drawMolecule(*m, &highlight_atoms, &highlight_colors,
&highlight_radii);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
std::cout << " Done" << std::endl;
}
void test4() {
std::cout << " ----------------- Test 4" << std::endl;
{
std::string fName = getenv("RDBASE");
fName += "/Code/GraphMol/MolDraw2D/test_dir";
fName += "/clash.mol";
ROMol *m = MolFileToMol(fName);
std::string nameBase = "test4_1";
TEST_ASSERT(m);
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
std::cout << " Done" << std::endl;
}
void test5() {
std::cout << " ----------------- Test 5" << std::endl;
{
std::string smiles = "*c1cc(*)cc(*)c1";
std::string nameBase = "test5_1";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
MolDrawOptions options;
options.dummiesAreAttachments = true;
options.atomLabels[0] = "R1";
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions() = options;
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions() = options;
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
{
std::string smiles = "*C";
std::string nameBase = "test5_2";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m, nullptr, true);
WedgeMolBonds(*m, &(m->getConformer()));
MolDrawOptions options;
options.dummiesAreAttachments = true;
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions() = options;
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions() = options;
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
{
std::string smiles = "CC(F)(Cl)Br";
std::string nameBase = "test5_3";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
m->getBondBetweenAtoms(1, 2)->setBondDir(Bond::UNKNOWN);
RDDepict::compute2DCoords(*m, nullptr, true);
WedgeMolBonds(*m, &(m->getConformer()));
MolDrawOptions options;
options.dummiesAreAttachments = true;
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions() = options;
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions() = options;
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
std::cout << " Done" << std::endl;
}
#ifdef RDK_TEST_MULTITHREADED
#include <thread>
#include <future>
namespace {
void runblock(const std::vector<ROMol *> &mols,
const std::vector<std::string> &refData, unsigned int count,
unsigned int idx) {
for (unsigned int j = 0; j < 200; j++) {
for (unsigned int i = 0; i < mols.size(); ++i) {
if (i % count != idx) {
continue;
}
ROMol *mol = mols[i];
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*mol);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
TEST_ASSERT(text == refData[i]);
}
}
}
} // namespace
void testMultiThreaded() {
std::cout << " ----------------- Test multi-threaded drawing" << std::endl;
std::string fName = getenv("RDBASE");
fName += "/Data/NCI/first_200.props.sdf";
RDKit::SDMolSupplier suppl(fName);
std::cerr << "reading molecules" << std::endl;
std::vector<ROMol *> mols;
while (!suppl.atEnd() && mols.size() < 100) {
ROMol *mol = nullptr;
try {
mol = suppl.next();
} catch (...) {
continue;
}
if (!mol) {
continue;
}
mols.push_back(mol);
}
std::cerr << "generating reference drawings" << std::endl;
std::vector<std::string> refData(mols.size());
for (unsigned int i = 0; i < mols.size(); ++i) {
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*(mols[i]));
drawer.finishDrawing();
refData[i] = drawer.getDrawingText();
TEST_ASSERT(refData[i].find("<svg") != std::string::npos);
TEST_ASSERT(refData[i].find("</svg>") != std::string::npos);
}
std::vector<std::future<void>> tg;
unsigned int count = 4;
std::cerr << "processing" << std::endl;
for (unsigned int i = 0; i < count; ++i) {
std::cerr << " launch :" << i << std::endl;
std::cerr.flush();
tg.emplace_back(
std::async(std::launch::async, runblock, mols, refData, count, i));
}
for (auto &fut : tg) {
fut.get();
}
for (auto &&mol : mols) {
delete mol;
}
std::cerr << " Done" << std::endl;
}
#else
void testMultiThreaded() {}
#endif
void test6() {
std::cout << " ----------------- Test 6 (atom labels)" << std::endl;
{
std::string smiles = "CC[13CH2][CH2:7][CH-]C[15NH2+]C";
std::string nameBase = "test5_1";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string txt = drawer.getDrawingText();
std::ofstream outs("test6_1.svg");
outs << txt;
// TEST_ASSERT(txt.find("<svg")!=std::string::npos);
delete m;
}
{
auto m = "[C]1[C][C][CH][CH][CH]1"_smiles;
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string txt = drawer.getDrawingText();
TEST_ASSERT(txt.find("<svg") != std::string::npos);
std::ofstream outs("test6_2.svg");
outs << txt;
outs.close();
// start of bond-0
TEST_ASSERT(txt.find("<path class='bond-0' d='M 273.606,147.528")
!= std::string::npos);
// start of first radical spot
TEST_ASSERT(txt.find("<path d='M 286.51,143.528 L 286.502,143.356")
!= std::string::npos);
}
std::cerr << " Done" << std::endl;
}
void test7() {
std::cout << " ----------------- Test 7 (backgrounds)" << std::endl;
std::string smiles = "CCC";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
{
std::string nameBase = "test7_1";
MolDraw2DSVG drawer(300, 300);
drawer.drawOptions().clearBackground = false;
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string txt = drawer.getDrawingText();
std::ofstream outs((nameBase + ".svg").c_str());
outs << txt;
TEST_ASSERT(txt.find("<svg") != std::string::npos);
TEST_ASSERT(txt.find("<rect") == std::string::npos);
}
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
std::string nameBase = "test7_1";
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions().clearBackground = false;
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::string nameBase = "test7_2";
MolDraw2DSVG drawer(300, 300);
drawer.drawOptions().backgroundColour = DrawColour(.8, .8, .8);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string txt = drawer.getDrawingText();
std::ofstream outs((nameBase + ".svg").c_str());
outs << txt;
TEST_ASSERT(txt.find("<svg") != std::string::npos);
TEST_ASSERT(txt.find("<rect") != std::string::npos);
TEST_ASSERT(txt.find("fill:#CCCCCC") != std::string::npos);
}
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
std::string nameBase = "test7_2";
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions().backgroundColour = DrawColour(.8, .8, .8);
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
delete m;
std::cerr << " Done" << std::endl;
}
void test8PrepareMolForDrawing() {
std::cout << " ----------------- Test8: PrepareMolDrawing" << std::endl;
{
std::string smiles = "c1ccccc1[C@H](F)Cl";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
{
RWMol nm(*m);
TEST_ASSERT(nm.getNumAtoms() == 9)
MolDraw2DUtils::prepareMolForDrawing(nm);
TEST_ASSERT(nm.getNumAtoms() == 9); // this is a test for github #982
TEST_ASSERT(nm.getNumConformers() == 1);
TEST_ASSERT(!nm.getConformer().is3D());
TEST_ASSERT(nm.getBondBetweenAtoms(0, 1)->getBondType() !=
Bond::AROMATIC);
TEST_ASSERT(nm.getBondBetweenAtoms(0, 1)->getIsAromatic());
TEST_ASSERT(nm.getBondBetweenAtoms(6, 7)->getBondType() == Bond::SINGLE);
TEST_ASSERT(nm.getBondBetweenAtoms(6, 7)->getBondDir() ==
Bond::BEGINWEDGE);
// make sure we can do it again:
MolDraw2DUtils::prepareMolForDrawing(nm);
TEST_ASSERT(nm.getNumAtoms() == 9);
TEST_ASSERT(nm.getNumConformers() == 1);
TEST_ASSERT(nm.getBondBetweenAtoms(0, 1)->getBondType() !=
Bond::AROMATIC);
TEST_ASSERT(nm.getBondBetweenAtoms(0, 1)->getIsAromatic());
}
{
RWMol nm(*m);
TEST_ASSERT(nm.getNumAtoms() == 9)
MolDraw2DUtils::prepareMolForDrawing(nm, false);
TEST_ASSERT(nm.getNumAtoms() == 9);
TEST_ASSERT(nm.getNumConformers() == 1);
TEST_ASSERT(nm.getBondBetweenAtoms(0, 1)->getBondType() ==
Bond::AROMATIC);
TEST_ASSERT(nm.getBondBetweenAtoms(0, 1)->getIsAromatic());
}
{
RWMol nm(*m);
TEST_ASSERT(nm.getNumAtoms() == 9)
MolDraw2DUtils::prepareMolForDrawing(nm, false, false);
TEST_ASSERT(nm.getNumAtoms() == 9);
TEST_ASSERT(nm.getNumConformers() == 1);
TEST_ASSERT(nm.getBondBetweenAtoms(0, 1)->getBondType() ==
Bond::AROMATIC);
TEST_ASSERT(nm.getBondBetweenAtoms(0, 1)->getIsAromatic());
}
{
RWMol nm(*m);
TEST_ASSERT(nm.getNumAtoms() == 9)
MolDraw2DUtils::prepareMolForDrawing(nm, false, true);
TEST_ASSERT(nm.getNumAtoms() == 9);
TEST_ASSERT(nm.getNumConformers() == 1);
TEST_ASSERT(nm.getBondBetweenAtoms(0, 1)->getBondType() ==
Bond::AROMATIC);
TEST_ASSERT(nm.getBondBetweenAtoms(0, 1)->getIsAromatic());
}
{
RWMol nm(*m);
TEST_ASSERT(nm.getNumAtoms() == 9)
MolDraw2DUtils::prepareMolForDrawing(nm, true, true, false);
TEST_ASSERT(nm.getNumAtoms() == 9);
TEST_ASSERT(nm.getNumConformers() == 1);
TEST_ASSERT(nm.getBondBetweenAtoms(0, 1)->getBondType() !=
Bond::AROMATIC);
TEST_ASSERT(nm.getBondBetweenAtoms(0, 1)->getIsAromatic());
TEST_ASSERT(nm.getBondBetweenAtoms(6, 7)->getBondType() == Bond::SINGLE);
TEST_ASSERT(nm.getBondBetweenAtoms(6, 7)->getBondDir() == Bond::NONE);
}
{
// by default we don't force conformer generation
RWMol nm(*m);
RDDepict::compute2DCoords(nm);
nm.getConformer().set3D(true); // it's not really, we're cheating
TEST_ASSERT(nm.getNumAtoms() == 9)
MolDraw2DUtils::prepareMolForDrawing(nm);
TEST_ASSERT(nm.getNumAtoms() == 9);
TEST_ASSERT(nm.getNumConformers() == 1); // we have a conformer anyway
TEST_ASSERT(nm.getConformer().is3D());
// but if we do force, it blows out that conformer:
MolDraw2DUtils::prepareMolForDrawing(nm, true, true, true, true);
TEST_ASSERT(!nm.getConformer().is3D());
}
delete m;
}
{
std::string smiles = "C1CC[C@H]2NCCCC2C1";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
{
RWMol nm(*m);
TEST_ASSERT(nm.getNumAtoms() == 10)
MolDraw2DUtils::prepareMolForDrawing(nm);
TEST_ASSERT(nm.getNumAtoms() == 11);
TEST_ASSERT(nm.getNumConformers() == 1);
TEST_ASSERT(!nm.getConformer().is3D());
TEST_ASSERT(nm.getBondBetweenAtoms(3, 10)->getBondType() == Bond::SINGLE);
TEST_ASSERT(nm.getBondBetweenAtoms(3, 10)->getBondDir() ==
Bond::BEGINDASH);
// make sure we can do it again:
MolDraw2DUtils::prepareMolForDrawing(nm);
TEST_ASSERT(nm.getNumAtoms() == 11);
TEST_ASSERT(nm.getNumConformers() == 1);
TEST_ASSERT(nm.getBondBetweenAtoms(3, 10)->getBondType() == Bond::SINGLE);
TEST_ASSERT(nm.getBondBetweenAtoms(3, 10)->getBondDir() ==
Bond::BEGINDASH);
}
{
RWMol nm(*m);
TEST_ASSERT(nm.getNumAtoms() == 10)
MolDraw2DUtils::prepareMolForDrawing(nm, false, false);
TEST_ASSERT(nm.getNumAtoms() == 10);
TEST_ASSERT(nm.getNumConformers() == 1);
TEST_ASSERT(nm.getBondBetweenAtoms(3, 2)->getBondType() == Bond::SINGLE);
TEST_ASSERT(nm.getBondBetweenAtoms(3, 2)->getBondDir() ==
Bond::BEGINWEDGE);
}
delete m;
}
std::cerr << " Done" << std::endl;
}
void testGithub781() {
std::cout << " ----------------- Test Github #781: Rendering single-atom "
"molecules"
<< std::endl;
{
auto m = "C"_smiles;
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string txt = drawer.getDrawingText();
TEST_ASSERT(txt.find("<svg") != std::string::npos);
// write the file so we can update the coords below more easily
// if the font changes, for example.
std::ofstream outs("testGithub781_1.svg");
outs << txt;
outs.close();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// the start of the C
TEST_ASSERT(txt.find("<path class='atom-0' d='M 139.08 150.12")
!= std::string::npos)
// the start of the H
TEST_ASSERT(txt.find("<path class='atom-0' d='M 164.32 136")
!= std::string::npos)
#else
TEST_ASSERT(txt.find(">C</text>") != std::string::npos);
TEST_ASSERT(txt.find(">H</text>") != std::string::npos);
TEST_ASSERT(txt.find(">4</text>") != std::string::npos);
TEST_ASSERT(txt.find("font-size:40px") != std::string::npos);
TEST_ASSERT(txt.find("font-size:26px") != std::string::npos);
#endif
}
{
auto m = "O"_smiles;
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string txt = drawer.getDrawingText();
TEST_ASSERT(txt.find("<svg") != std::string::npos);
std::ofstream outs("testGithub781_2.svg");
outs << txt;
outs.close();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// start of the H
TEST_ASSERT(txt.find("<path class='atom-0' d='M 98.9272 136")
!= std::string::npos);
// start of the O
TEST_ASSERT(txt.find("<path class='atom-0' d='M 137 150.08")
!= std::string::npos);
#else
TEST_ASSERT(txt.find("<tspan>OH</tspan>") == std::string::npos);
#endif
}
{
auto m = "[C]"_smiles;
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
MolDraw2DSVG drawer(600, 600);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string txt = drawer.getDrawingText();
TEST_ASSERT(txt.find("<svg") != std::string::npos);
std::ofstream outs("testGithub781_3.svg");
outs << txt;
outs.close();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// The C
TEST_ASSERT(txt.find("<path class='atom-0' d='M 289.08 300.12")
!= std::string::npos);
// the first radical marker
TEST_ASSERT(txt.find("<path d='M 317.382,288 L 317.374,287.828")
!= std::string::npos);
#else
TEST_ASSERT(txt.find(">C</text>") != std::string::npos);
// the first radical marker
TEST_ASSERT(txt.find("<path d='M 318.364,288 L 318.356,287.828 L 318.334,287.657")
!= std::string::npos);
#endif
}
{
auto m = "C.CC.[Cl-]"_smiles;
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string txt = drawer.getDrawingText();
TEST_ASSERT(txt.find("<svg") != std::string::npos);
std::ofstream outs("testGithub781_4.svg");
outs << txt;
outs.close();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// start of C
TEST_ASSERT(txt.find("<path class='atom-0' d='M 27.3543 198.034")
!= std::string::npos);
// start of l
TEST_ASSERT(txt.find("<path class='atom-3' d='M 36.4343 74.8236")
!= std::string::npos);
#else
TEST_ASSERT(txt.find(">C</text>") != std::string::npos);
TEST_ASSERT(txt.find(">H</text>") != std::string::npos);
TEST_ASSERT(txt.find(">l</text>") != std::string::npos);
#endif
}
{ // empty molecule
auto *m = new ROMol();
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string txt = drawer.getDrawingText();
TEST_ASSERT(txt.find("<svg") != std::string::npos);
// the Freetype version just draws the white canvas.
std::ofstream outs("testGithub781_5.svg");
outs << txt;
outs.close();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
#else
TEST_ASSERT(txt.find("<tspan>") == std::string::npos);
#endif
delete m;
}
std::cerr << " Done" << std::endl;
}
void testGithub774() {
std::cout << " ----------------- Test Github774" << std::endl;
{
std::string smiles =
"Cc1c(C(=O)NCC[NH3+])[n+](=O)c2cc(CC[C@](F)(Cl)Br)ccc2n1[O-]";
std::string nameBase = "test774_1";
RWMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
MolOps::Kekulize(*m);
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
Point2D ocoords(1.0, 2.0);
Point2D dcoords =
drawer.getAtomCoords(std::make_pair(ocoords.x, ocoords.y));
Point2D acoords = drawer.getDrawCoords(dcoords);
TEST_ASSERT(feq(acoords.x, 1.0));
TEST_ASSERT(feq(acoords.y, 2.0));
}
// m->setProp("_Name","mol");
// std::cerr<<MolToMolBlock(*m)<<std::endl;
delete m;
}
{
std::string smiles =
"CC(=O)\\C=C\\CC1[C@H]2N([C@@H](C(=O)O)C(C)(C)S2(=O)=O)C1=O";
std::string nameBase = "test774_2";
RWMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
MolOps::Kekulize(*m);
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
// m->setProp("_Name","mol");
// std::cerr<<MolToMolBlock(*m)<<std::endl;
delete m;
}
std::cerr << " Done" << std::endl;
}
void test9MolLegends() {
std::cout << " ----------------- Test 9 (molecule legends)" << std::endl;
{
std::string smiles = "CC[13CH2][CH2:7][CH-]C[15NH2+]C";
std::string nameBase = "test5_1";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m, "mol legend");
drawer.finishDrawing();
std::string txt = drawer.getDrawingText();
std::ofstream outs("test9_1.svg");
outs << txt;
// TEST_ASSERT(txt.find("<svg")!=std::string::npos);
delete m;
}
std::cerr << " Done" << std::endl;
}
void testGithub852() {
std::cout << " ----------------- Test Github852: Lines used to wedge bonds "
"are too thick"
<< std::endl;
{
std::string smiles =
"COc1cccc(NC(=O)[C@H](Cl)Sc2nc(ns2)c3ccccc3Cl)c1"; // made up
std::string nameBase = "test852_1";
RWMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
{
std::string smiles =
"C[C@]12CC[C@@H]3c4ccc(cc4CC[C@H]3[C@@H]1CC[C@@H]2O)O"; // estradiol
std::string nameBase = "test852_2";
RWMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
delete m;
}
std::cerr << " Done" << std::endl;
}
void testGithub860() {
std::cout << " ----------------- Test Github860: Atom symbols in wrong order "
"if bond comes from right"
<< std::endl;
{
auto m = "[15NH3+:1]-C#C-[15NH3+:2]"_smiles;
std::string nameBase = "test860_1";
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
}
{
auto m = "[15NH3+:1]-C#C-C([15NH3+:2])([15NH3+:3])-C#C-[15NH3+:4]"_smiles;
std::string nameBase = "test860_2";
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
}
{
auto m = "[15NH3+:1]-CCCCCCCC-[15NH3+:4]"_smiles;
std::string nameBase = "test860_3";
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
drawer.writeDrawingText(nameBase + ".png");
}
#endif
{
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
}
std::cerr << " Done" << std::endl;
}
void testGithub910() {
std::cout << " ----------------- Test Github #910: ugly coordinates "
"generated for peptide chains"
<< std::endl;
// this really isn't much of a test, but it does help visually confirm that
// things are actually ok
{
// this is a ChEMBL molecule
std::string smiles =
"CSCC[C@H](NC(=O)[C@@H](CCC(N)=O)NC(=O)[C@@H](N)Cc1c[nH]c2ccccc12)C(="
"O)"
"NCC(=O)N[C@@H](Cc1c[nH]cn1)C(=O)N[C@@H](CO)C(=O)O";
ROMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
std::ofstream outs("test910_1.svg");
MolDraw2DSVG drawer(600, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
delete m;
}
{ // now with Hs
// this is a ChEMBL molecule
std::string smiles =
"CSCC[C@H](NC(=O)[C@@H](CCC(N)=O)NC(=O)[C@@H](N)Cc1c[nH]c2ccccc12)C(="
"O)"
"NCC(=O)N[C@@H](Cc1c[nH]cn1)C(=O)N[C@@H](CO)C(=O)O";
RWMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
std::ofstream outs("test910_2.svg");
MolDraw2DSVG drawer(600, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
delete m;
}
std::cerr << " Done" << std::endl;
}
void testGithub932() {
std::cout << " ----------------- Test Github #932: mistake in SVG for "
"wedged bonds"
<< std::endl;
{
std::string smiles = "CC[C@](F)(Cl)Br";
RWMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
TEST_ASSERT(text.find("evenoddstroke") == std::string::npos);
delete m;
}
std::cerr << " Done" << std::endl;
}
void testGithub953() {
std::cout << " ----------------- Test Github #953: default color should "
"not be cyan"
<< std::endl;
{
std::string smiles = "[Nb]";
RWMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
TEST_ASSERT(text.find("#00FFFF") == std::string::npos);
delete m;
}
std::cerr << " Done" << std::endl;
}
void testGithub983() {
std::cout << " ----------------- Test Github #983: wedged bonds between "
"chiral centers drawn improperly"
<< std::endl;
{
// this has an ugly drawing (wedged bond between chiral centers) but we
// force it to be drawn that way just to check.
std::string mb =
"\n\
Mrv1561 07241608122D\n\
\n\
6 5 0 0 0 0 999 V2000\n\
8.6830 -9.5982 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
9.3975 -9.1857 0.0000 C 0 0 2 0 0 0 0 0 0 0 0 0\n\
10.1120 -9.5982 0.0000 C 0 0 1 0 0 0 0 0 0 0 0 0\n\
9.3975 -8.3607 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0\n\
10.8264 -9.1857 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
10.1120 -10.4232 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0\n\
1 2 1 0 0 0 0\n\
3 5 1 0 0 0 0\n\
3 2 1 1 0 0 0\n\
2 4 1 1 0 0 0\n\
3 6 1 0 0 0 0\n\
M END";
RWMol *m = MolBlockToMol(mb, false, false);
TEST_ASSERT(m);
MolOps::sanitizeMol(*m);
MolDraw2DUtils::prepareMolForDrawing(*m);
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test983_1.svg");
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
TEST_ASSERT(text.find("<path class='bond-1' d='M 126.878,115.979"
" L 184.005,90.8113 L 177.234,79.085 Z'"
" style='fill:#000000;")
!= std::string::npos);
#else
TEST_ASSERT(text.find("<path class='bond-1' d='M 126.46,111.639"
" L 182.698,86.8632 L 176.033,75.3193 Z'"
" style='fill:#000000;fill-rule:evenodd;"
"fill-opacity=1;stroke:#000000;")
!= std::string::npos);
#endif
delete m;
}
{
std::string mb =
"\n\
Mrv1561 07241616282D\n\
\n\
12 12 0 0 1 0 999 V2000\n\
10.4656 -7.9623 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0\n\
9.7496 -8.3748 0.0000 C 0 0 1 0 0 0 0 0 0 0 0 0\n\
8.9075 -9.4746 0.0000 C 0 0 2 0 0 0 0 0 0 0 0 0\n\
7.5671 -9.4746 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
8.2373 -8.9934 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
8.6497 -10.2651 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
9.0392 -7.9623 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
7.8249 -10.2651 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
7.1547 -10.1792 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0\n\
6.8567 -9.0622 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0\n\
10.3338 -8.9591 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0\n\
8.6841 -8.6669 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0\n\
2 1 1 0 0 0 0\n\
3 2 1 0 0 0 0\n\
4 5 1 0 0 0 0\n\
5 3 1 0 0 0 0\n\
6 3 1 0 0 0 0\n\
7 2 1 0 0 0 0\n\
8 6 1 0 0 0 0\n\
9 4 1 0 0 0 0\n\
10 4 1 0 0 0 0\n\
2 11 1 6 0 0 0\n\
3 12 1 6 0 0 0\n\
8 4 1 0 0 0 0\n\
M END";
RWMol *m = MolBlockToMol(mb);
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
TEST_ASSERT(m->getBondBetweenAtoms(2, 1)->getBondType() == Bond::SINGLE);
TEST_ASSERT(m->getBondBetweenAtoms(2, 1)->getBondDir() == Bond::NONE);
TEST_ASSERT(m->getBondBetweenAtoms(2, 4)->getBondType() == Bond::SINGLE);
TEST_ASSERT(m->getBondBetweenAtoms(2, 4)->getBondDir() == Bond::BEGINWEDGE);
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test983_2.svg");
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
TEST_ASSERT(text.find("<path class='bond-3' d='M 103.748,117.559"
" L 76.8908,93.4583 L 72.3264,99.8155 Z'"
" style='fill:#000000;")
!= std::string::npos);
#else
TEST_ASSERT(text.find("<path class='bond-3' d='M 105.087,114.797"
" L 78.5054,90.9436 L 73.9878,97.2355 Z'"
" style='fill:#000000;fill-rule:evenodd;"
"fill-opacity=1;stroke:#000000;")
!= std::string::npos);
#endif
MolDraw2DUtils::prepareMolForDrawing(*m);
TEST_ASSERT(m->getBondBetweenAtoms(2, 1)->getBondType() == Bond::SINGLE);
TEST_ASSERT(m->getBondBetweenAtoms(2, 1)->getBondDir() == Bond::NONE);
TEST_ASSERT(m->getBondBetweenAtoms(2, 4)->getBondType() == Bond::SINGLE);
TEST_ASSERT(m->getBondBetweenAtoms(2, 4)->getBondDir() == Bond::BEGINWEDGE);
RWMol nm(*m);
MolDraw2DUtils::prepareMolForDrawing(nm);
TEST_ASSERT(nm.getBondBetweenAtoms(2, 1)->getBondType() == Bond::SINGLE);
TEST_ASSERT(nm.getBondBetweenAtoms(2, 1)->getBondDir() == Bond::NONE);
TEST_ASSERT(nm.getBondBetweenAtoms(2, 4)->getBondType() == Bond::SINGLE);
TEST_ASSERT(nm.getBondBetweenAtoms(2, 4)->getBondDir() == Bond::BEGINWEDGE);
delete m;
}
std::cerr << " Done" << std::endl;
}
void testDeuteriumTritium() {
std::cout << " ----------------- Test Deuterium, Tritium" << std::endl;
{
auto m = "C([2H])([2H])([2H])[2H]"_smiles;
RDDepict::compute2DCoords(*m);
std::string nameBase = "testNoDeuterium";
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions().atomLabelDeuteriumTritium = false;
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.close();
std::ifstream ins((nameBase + ".svg").c_str());
bool ok = true;
unsigned int count = 0;
while (ok) {
std::string line;
std::getline(ins, line);
ok = (ins.good() && !ins.eof());
if (!ok) {
continue;
}
// there are no characters to look for, but each atom should
// be made of 2 glyphs, the superscript 2 and the H.
#ifdef RDK_BUILD_FREETYPE_SUPPORT
if ((line.find("atom-") != std::string::npos)) {
++count;
}
#else
// a bit kludgy, but...
if(line.find("<text x='250.507' y='152.691' class='atom-1'"
" style='font-size:26px;font-style:normal;"
"font-weight:normal;fill-opacity:1;stroke:none;"
"font-family:sans-serif;text-anchor:start;"
"fill:#000000' >2</text>")
!= std::string::npos) {
++count;
}
#endif
}
#ifdef RDK_BUILD_FREETYPE_SUPPORT
TEST_ASSERT(count == 8);
#else
// the first superscript 2
TEST_ASSERT(count == 1);
#endif
}
{
auto m = "C([3H])([3H])([3H])[3H]"_smiles;
RDDepict::compute2DCoords(*m);
std::string nameBase = "testNoTritium";
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions().atomLabelDeuteriumTritium = false;
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.close();
std::ifstream ins((nameBase + ".svg").c_str());
bool ok = true;
unsigned int count = 0;
while (ok) {
std::string line;
std::getline(ins, line);
ok = (ins.good() && !ins.eof());
if (!ok) {
continue;
}
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// there are no characters to look for, but each atom should
// be made of 2 glyphs, the superscript 3 and the H.
if ((line.find("atom-") != std::string::npos)) {
++count;
}
#else
if (line.find("<text x='250.507' y='152.691' class='atom-1'"
" style='font-size:26px;font-style:normal;"
"font-weight:normal;fill-opacity:1;stroke:none;"
"font-family:sans-serif;text-anchor:start;"
"fill:#000000' >3</text>")
!= std::string::npos) {
++count;
}
#endif
}
#ifdef RDK_BUILD_FREETYPE_SUPPORT
TEST_ASSERT(count == 8);
#else
TEST_ASSERT(count == 1);
#endif
}
{
auto m = "C([2H])([2H])([2H])[2H]"_smiles;
RDDepict::compute2DCoords(*m);
std::string nameBase = "testDeuterium";
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions().atomLabelDeuteriumTritium = true;
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.close();
std::ifstream ins((nameBase + ".svg").c_str());
bool ok = true;
unsigned int count = 0;
while (ok) {
std::string line;
std::getline(ins, line);
ok = (ins.good() && !ins.eof());
if (!ok) {
continue;
}
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// there should be just 1 glyph per atom - a D
if ((line.find("atom-") != std::string::npos)) {
++count;
}
#else
if ((line.find("baseline-shift:super") == std::string::npos) &&
(line.find(">2<") == std::string::npos) &&
(line.find(">D<") != std::string::npos)) {
++count;
}
#endif
}
TEST_ASSERT(count == 4);
}
{
auto m = "C([3H])([3H])([3H])[3H]"_smiles;
RDDepict::compute2DCoords(*m);
std::string nameBase = "testTritium";
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawOptions().atomLabelDeuteriumTritium = true;
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.close();
std::ifstream ins((nameBase + ".svg").c_str());
bool ok = true;
unsigned int count = 0;
while (ok) {
std::string line;
std::getline(ins, line);
ok = (ins.good() && !ins.eof());
if (!ok) {
continue;
}
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// there should be just 1 glyph per atom - a T
if ((line.find("atom-") != std::string::npos)) {
++count;
}
#else
if ((line.find("baseline-shift:super") == std::string::npos) &&
(line.find(">3<") == std::string::npos) &&
(line.find(">T<") != std::string::npos)) {
++count;
}
#endif
}
TEST_ASSERT(count == 4);
}
std::cerr << " Done" << std::endl;
}
void testCrossedBonds() {
std::cerr << " ----------------- Test crossed bonds" << std::endl;
{
std::string smiles = "CC=CC";
RWMol *m = SmilesToMol(smiles);
TEST_ASSERT(m);
m->getBondWithIdx(1)->setBondDir(Bond::EITHERDOUBLE);
MolDraw2DUtils::prepareMolForDrawing(*m);
std::string nameBase = "crossed_bonds";
std::ofstream outs((nameBase + ".svg").c_str());
MolDraw2DSVG drawer(300, 300, outs);
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.close();
delete m;
}
std::cerr << " Done" << std::endl;
}
void test10DrawSecondMol() {
std::cout << " ----------------- Testing drawing a second molecule"
<< std::endl;
std::string mb1 =
"\n\
Mrv1561 08301611102D\n\
\n\
3 2 0 0 0 0 999 V2000\n\
-2.5670 1.3616 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
-1.8525 1.7741 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
-1.1380 1.3616 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
1 2 1 0 0 0 0\n\
2 3 1 0 0 0 0\n\
M END";
RWMol *m1 = MolBlockToMol(mb1);
TEST_ASSERT(m1);
MolOps::sanitizeMol(*m1);
MolDraw2DUtils::prepareMolForDrawing(*m1);
RDGeom::Point3D c1 = MolTransforms::computeCentroid(m1->getConformer());
for (unsigned int i = 0; i < m1->getNumAtoms(); ++i) {
RDGeom::Point3D &p = m1->getConformer().getAtomPos(i);
p -= c1;
}
std::string mb2 =
"\n\
Mrv1561 08301611122D\n\
\n\
3 2 0 0 0 0 999 V2000\n\
-1.9900 2.2136 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0\n\
-1.5775 1.4991 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
-1.9900 0.7846 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
1 2 1 0 0 0 0\n\
2 3 1 0 0 0 0\n\
M END";
RWMol *m2 = MolBlockToMol(mb2);
TEST_ASSERT(m2);
MolOps::sanitizeMol(*m2);
MolDraw2DUtils::prepareMolForDrawing(*m2);
RDGeom::Point3D c2 = MolTransforms::computeCentroid(m2->getConformer());
for (unsigned int i = 0; i < m2->getNumAtoms(); ++i) {
RDGeom::Point3D &p = m2->getConformer().getAtomPos(i);
p -= c2;
}
{
MolDraw2DSVG drawer(200, 200);
drawer.drawOptions().padding = 0.2;
drawer.drawMolecule(*m1);
drawer.drawMolecule(*m2);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test10_1.svg");
outs << text;
outs.flush();
}
{
MolDraw2DSVG drawer(200, 200);
drawer.drawOptions().padding = 0.2;
drawer.drawMolecule(*m2);
drawer.drawMolecule(*m1);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test10_2.svg");
outs << text;
outs.flush();
}
{
MolDraw2DSVG drawer(400, 200, 200, 200);
drawer.drawOptions().padding = 0.2;
drawer.drawMolecule(*m1);
drawer.setOffset(200, 0);
drawer.drawMolecule(*m2);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test10_3.svg");
outs << text;
outs.flush();
}
{
MolDraw2DSVG drawer(200, 400, 200, 200);
drawer.drawOptions().padding = 0.2;
drawer.drawMolecule(*m1);
drawer.setOffset(0, 200);
drawer.drawMolecule(*m2);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test10_4.svg");
outs << text;
outs.flush();
}
{
MolDraw2DSVG drawer(200, 400, 200, 200);
Point2D minv(1000, 1000);
Point2D maxv(-1000, -1000);
for (unsigned int i = 0; i < m1->getNumAtoms(); ++i) {
const RDGeom::Point3D &pti = m1->getConformer().getAtomPos(i);
minv.x = std::min(minv.x, pti.x);
minv.y = std::min(minv.y, pti.y);
maxv.x = std::max(maxv.x, pti.x);
maxv.y = std::max(maxv.y, pti.y);
}
drawer.setScale(200, 200, minv, maxv);
drawer.drawMolecule(*m1);
drawer.setOffset(0, 200);
drawer.drawMolecule(*m2);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test10_5.svg");
outs << text;
outs.flush();
}
{
MolDraw2DSVG drawer(200, 400, 200, 200);
Point2D minv(1000, 1000);
Point2D maxv(-1000, -1000);
for (unsigned int i = 0; i < m1->getNumAtoms(); ++i) {
const RDGeom::Point3D &pti = m1->getConformer().getAtomPos(i);
minv.x = std::min(minv.x, pti.x);
minv.y = std::min(minv.y, pti.y);
maxv.x = std::max(maxv.x, pti.x);
maxv.y = std::max(maxv.y, pti.y);
}
drawer.drawOptions().padding = 0.2;
drawer.setScale(200, 200, minv, maxv);
drawer.drawMolecule(*m1);
drawer.setOffset(0, 200);
drawer.drawMolecule(*m2);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test10_6.svg");
outs << text;
outs.flush();
}
delete m1;
delete m2;
std::cerr << " Done" << std::endl;
}
void test11DrawMolGrid() {
std::cout << " ----------------- Testing drawing a grid of molecules"
<< std::endl;
std::string smiles =
"COc1cccc(NC(=O)[C@H](Cl)Sc2nc(ns2)c3ccccc3Cl)c1"; // made up
RWMol *m1 = SmilesToMol(smiles);
TEST_ASSERT(m1);
MolDraw2DUtils::prepareMolForDrawing(*m1);
RDGeom::Point3D c1 = MolTransforms::computeCentroid(m1->getConformer());
for (unsigned int i = 0; i < m1->getNumAtoms(); ++i) {
RDGeom::Point3D &p = m1->getConformer().getAtomPos(i);
p -= c1;
}
smiles = "NC(=O)[C@H](Cl)Sc1ncns1"; // made up
RWMol *m2 = SmilesToMol(smiles);
TEST_ASSERT(m2);
MolDraw2DUtils::prepareMolForDrawing(*m2);
RDGeom::Point3D c2 = MolTransforms::computeCentroid(m2->getConformer());
for (unsigned int i = 0; i < m2->getNumAtoms(); ++i) {
RDGeom::Point3D &p = m2->getConformer().getAtomPos(i);
p -= c2;
}
smiles = "BrCNC(=O)[C@H](Cl)Sc1ncns1"; // made up
RWMol *m3 = SmilesToMol(smiles);
TEST_ASSERT(m3);
MolDraw2DUtils::prepareMolForDrawing(*m3);
RDGeom::Point3D c3 = MolTransforms::computeCentroid(m3->getConformer());
for (unsigned int i = 0; i < m3->getNumAtoms(); ++i) {
RDGeom::Point3D &p = m3->getConformer().getAtomPos(i);
p -= c3;
}
{
MolDraw2DSVG drawer(500, 400, 250, 200);
drawer.drawMolecule(*m1, "m1");
drawer.setOffset(250, 0);
drawer.drawMolecule(*m2, "m2");
drawer.setOffset(0, 200);
drawer.drawMolecule(*m3, "m3");
drawer.setOffset(250, 200);
drawer.drawMolecule(*m1, "m4");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test11_1.svg");
outs << text;
outs.flush();
}
{ // drawing "out of order"
MolDraw2DSVG drawer(500, 400, 250, 200);
drawer.setOffset(250, 0);
drawer.drawMolecule(*m1, "m1");
drawer.setOffset(0, 0);
drawer.drawMolecule(*m2, "m2");
drawer.setOffset(0, 200);
drawer.drawMolecule(*m1, "m3");
drawer.setOffset(250, 200);
drawer.drawMolecule(*m2, "m4");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test11_2.svg");
outs << text;
outs.flush();
}
delete m1;
delete m2;
delete m3;
std::cerr << " Done" << std::endl;
}
void test12DrawMols() {
std::cout << " ----------------- Testing drawMolecules" << std::endl;
auto setup_mol = [](const std::string &smi, const std::string leg,
std::vector<ROMol *> &mols,
std::vector<std::string> &legends) {
mols.push_back(SmilesToMol(smi));
TEST_ASSERT(mols.back());
legends.push_back(leg);
};
std::vector<ROMol *> mols;
std::unique_ptr<std::vector<std::string>> legends(
new std::vector<std::string>());
// made up SMILES, each with sequence F, Cl, Br so we can see which
// ones are drawn, which ones are missing.
setup_mol("COc1cccc(NC(=O)[C@H](F)Sc2nc(ns2)c3ccccc3F)c1", "m1", mols,
*legends);
setup_mol("NC(=O)[C@H](F)Sc1ncns1", "m2", mols, *legends);
setup_mol("COc1cccc(NC(=O)[C@H](Cl)Sc2nc(ns2)c3ccccc3F)c1", "m3", mols,
*legends);
setup_mol("NC(=O)[C@H](Cl)Sc1ncns1", "m4", mols, *legends);
setup_mol("COc1cccc(NC(=O)[C@H](Br)Sc2nc(ns2)c3ccccc3F)c1", "m5", mols,
*legends);
setup_mol("NC(=O)[C@H](Br)Sc1ncns1", "m6", mols, *legends);
{
MolDraw2DSVG drawer(750, 400, 250, 200);
drawer.drawMolecules(mols, legends.get());
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test12_1.svg");
outs << text;
outs.flush();
}
{ // github #1325: multiple molecules in one pane
MolDraw2DSVG drawer(300, 300, 300, 300);
drawer.drawMolecules(mols);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test12_3.svg");
outs << text;
outs.flush();
}
{ // github #1325: multiple molecules in one pane
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecules(mols);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test12_4.svg");
outs << text;
outs.flush();
}
{
delete mols[2];
delete mols[4];
mols[2] = nullptr;
mols[4] = nullptr;
MolDraw2DSVG drawer(750, 400, 250, 200);
drawer.drawMolecules(mols);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test12_2.svg");
outs << text;
outs.flush();
}
for (auto m : mols) {
delete m;
}
std::cerr << " Done" << std::endl;
}
void test13JSONConfig() {
std::cerr << " ----------------- Test JSON Configuration" << std::endl;
{
auto m = "CCO"_smiles;
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
MolDraw2DSVG drawer(250, 200);
const char *json =
"{\"legendColour\":[1.0,0.5,1.0], \"rotate\": 90, "
"\"bondLineWidth\": 5}";
MolDraw2DUtils::updateDrawerParamsFromJSON(drawer, json);
drawer.drawMolecule(*m, "foo");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test13_1.svg");
outs << text;
outs.close();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// we'll just have to assume that this pink is for the legend
TEST_ASSERT(text.find("' fill='#FF7FFF") != std::string::npos);
TEST_ASSERT(text.find("<path class='bond-0' d='M 119.411,8.18182"
" L 162.939,83.5752'") !=
std::string::npos);
#else
TEST_ASSERT(text.find("sans-serif;text-anchor:start;fill:#FF7FFF")
!= std::string::npos);
TEST_ASSERT(text.find("<path class='bond-0' d='M 119.755,8.18182"
" L 162.102,81.5304'") !=std::string::npos);
#endif
// these days the bond line width scales with the rest of the
// drawing, and at this size this comes out as 6px.
TEST_ASSERT(text.find("stroke-width:5px") != std::string::npos);
}
std::cerr << " Done" << std::endl;
}
void testGithub1090() {
std::cout << " ----------------- Testing github 1090: escape html characters "
"in SVG output"
<< std::endl;
std::string smiles = "CCOC"; // made up
RWMol *m1 = SmilesToMol(smiles);
TEST_ASSERT(m1);
MolDraw2DUtils::prepareMolForDrawing(*m1);
{
ROMol lm(*m1);
MolDraw2DSVG drawer(250, 200);
drawer.drawOptions().atomLabels[0] = "C&1";
drawer.drawOptions().atomLabels[1] = "[CH2<1]";
drawer.drawOptions().atomLabels[3] = "[C>1H3]";
drawer.drawMolecule(lm, "legend&legend>1");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("testGithub1090_1.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("C&1") == std::string::npos);
TEST_ASSERT(text.find("<<") == std::string::npos);
TEST_ASSERT(text.find(">>") == std::string::npos);
TEST_ASSERT(text.find("d&l") == std::string::npos);
}
delete m1;
std::cerr << " Done" << std::endl;
}
void testGithub1035() {
std::cout << " ----------------- Testing github 1035: overflow bug in SVG "
"color generation"
<< std::endl;
std::string smiles = "CCOC"; // made up
RWMol *m1 = SmilesToMol(smiles);
TEST_ASSERT(m1);
MolDraw2DUtils::prepareMolForDrawing(*m1);
std::vector<int> highlights;
highlights.push_back(0);
highlights.push_back(1);
{
MolDraw2DSVG drawer(250, 200);
drawer.drawOptions().highlightColour = DrawColour(1.1, .5, .5);
bool ok = false;
try {
drawer.drawMolecule(*m1, &highlights);
} catch (const ValueErrorException &) {
ok = true;
}
TEST_ASSERT(ok);
}
{
MolDraw2DSVG drawer(250, 200);
drawer.drawOptions().highlightColour = DrawColour(.1, -.5, .5);
bool ok = false;
try {
drawer.drawMolecule(*m1, &highlights);
} catch (const ValueErrorException &) {
ok = true;
}
TEST_ASSERT(ok);
}
{
MolDraw2DSVG drawer(250, 200);
drawer.drawOptions().highlightColour = DrawColour(1., .5, 1.5);
bool ok = false;
try {
drawer.drawMolecule(*m1, &highlights);
} catch (const ValueErrorException &) {
ok = true;
}
TEST_ASSERT(ok);
}
delete m1;
std::cerr << " Done" << std::endl;
}
void testGithub1271() {
std::cout << " ----------------- Testing github 1271: MolDraw2D not drawing "
"anything for molecules aligned with the X or Y axes"
<< std::endl;
{
std::string mb =
"ethane\n\
RDKit 2D\n\
\n\
2 1 0 0 0 0 0 0 0 0999 V2000\n\
-0.7500 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
0.7500 -0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
1 2 1 0\n\
M END";
RWMol *m = MolBlockToMol(mb);
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test1271_1.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("d='M 0,200 0,200") == std::string::npos);
delete m;
}
{
std::string mb =
"ethane\n\
RDKit 2D\n\
\n\
2 1 0 0 0 0 0 0 0 0999 V2000\n\
-0.0000 0.5000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
0.0000 -0.5000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n\
1 2 1 0\n\
M END";
RWMol *m = MolBlockToMol(mb);
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test1271_2.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("d='M 0,200 0,200") == std::string::npos);
delete m;
}
{
std::string mb =
"water\n\
RDKit 2D\n\
\n\
1 0 0 0 0 0 0 0 0 0999 V2000\n\
-0.0000 0.0000 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0\n\
M END";
RWMol *m = MolBlockToMol(mb);
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test1271_3.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("d='M 0,200 0,200") == std::string::npos);
delete m;
}
{
std::string mb =
"water\n\
RDKit 2D\n\
\n\
1 0 0 0 0 0 0 0 0 0999 V2000\n\
-0.0000 0.5000 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0\n\
M END";
RWMol *m = MolBlockToMol(mb);
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test1271_4.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("d='M 0,200 0,200") == std::string::npos);
delete m;
}
{
std::string smiles = "C=C(O)C(O)"; // made up
RWMol *m1 = SmilesToMol(smiles);
TEST_ASSERT(m1);
MolDraw2DUtils::prepareMolForDrawing(*m1);
smiles = "O";
RWMol *m2 = SmilesToMol(smiles);
TEST_ASSERT(m2);
MolDraw2DUtils::prepareMolForDrawing(*m2);
MolDraw2DSVG drawer(500, 200, 250, 200);
drawer.drawMolecule(*m1, "m1");
drawer.setOffset(250, 0);
drawer.drawMolecule(*m2, "m2");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test1271_5.svg");
outs << text;
outs.flush();
delete m1;
delete m2;
}
std::cerr << " Done" << std::endl;
}
void testGithub1322() {
std::cout << " ----------------- Testing github 1322: add custom atom labels"
<< std::endl;
{
auto m1 = "CCC[Se]"_smiles; // made up
TEST_ASSERT(m1);
MolDraw2DUtils::prepareMolForDrawing(*m1);
{
MolDraw2DSVG drawer(500, 200, 250, 200);
drawer.drawMolecule(*m1, "m1");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test1322_1.svg");
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// there should be 2 paths of class atom-3, one for the S,
// the other for the e.
size_t start_pos = 0;
int count = 0;
while(true) {
start_pos = text.find("atom-3", start_pos);
if(start_pos == std::string::npos) {
break;
}
++count;
++start_pos;
}
TEST_ASSERT(count == 2);
#else
TEST_ASSERT(text.find(">S</text>") != std::string::npos);
TEST_ASSERT(text.find(">e</text>") != std::string::npos);
#endif
}
{
m1->getAtomWithIdx(3)->setProp(common_properties::atomLabel,
"customlabel");
MolDraw2DSVG drawer(500, 200, 250, 200);
drawer.drawMolecule(*m1, "m1");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test1322_2.svg");
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// there should be 11 paths of class atom-3, one for each letter
// of customlabel
size_t start_pos = 0;
int count = 0;
while(true) {
start_pos = text.find("atom-3", start_pos);
if(start_pos == std::string::npos) {
break;
}
++count;
++start_pos;
}
TEST_ASSERT(count == 11);
#else
TEST_ASSERT(text.find(">S</text>") == std::string::npos);
TEST_ASSERT(text.find(">s</text>") != std::string::npos);
TEST_ASSERT(text.find(">b</text>") != std::string::npos);
#endif
}
}
std::cerr << " Done" << std::endl;
}
void testGithub565() {
std::cout << " ----------------- Testing github 565: support a fixed bond "
"length in the MolDraw2D code"
<< std::endl;
{
std::string smiles = "CCCCC";
RWMol *m1 = SmilesToMol(smiles);
TEST_ASSERT(m1);
MolDraw2DUtils::prepareMolForDrawing(*m1);
Point2D minV, maxV;
const Conformer &cnf = m1->getConformer();
minV.x = maxV.x = cnf.getAtomPos(0).x;
minV.y = maxV.y = cnf.getAtomPos(0).y;
for (unsigned int i = 1; i < m1->getNumAtoms(); i++) {
minV.x = std::min(minV.x, cnf.getAtomPos(i).x);
minV.y = std::min(minV.y, cnf.getAtomPos(i).y);
maxV.x = std::max(maxV.x, cnf.getAtomPos(i).x);
maxV.y = std::max(maxV.y, cnf.getAtomPos(i).y);
}
{
unsigned int dpa = 100;
unsigned int w = dpa * (maxV.x - minV.x);
unsigned int h = dpa * (maxV.y - minV.y);
MolDraw2DSVG drawer(w, h);
drawer.setScale(w, h, minV, maxV);
drawer.drawMolecule(*m1, "m1");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test565_1.svg");
outs << text;
outs.flush();
}
{
unsigned int dpa = 50;
unsigned int w = dpa * (maxV.x - minV.x);
unsigned int h = dpa * (maxV.y - minV.y);
MolDraw2DSVG drawer(w, h);
drawer.setScale(w, h, minV, maxV);
drawer.drawMolecule(*m1, "m1");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test565_2.svg");
outs << text;
outs.flush();
}
delete m1;
}
std::cerr << " Done" << std::endl;
}
void test14BWPalette() {
std::cout << " ----------------- Testing use of a black & white palette"
<< std::endl;
{
std::string smiles = "CNC(Cl)C(=O)O";
RWMol *m1 = SmilesToMol(smiles);
TEST_ASSERT(m1);
MolDraw2DUtils::prepareMolForDrawing(*m1);
{ // start with color
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m1, "m1");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
TEST_ASSERT(text.find("stroke:#00CC00") != std::string::npos);
std::ofstream outs("test14_1.svg");
outs << text;
outs.flush();
}
{ // now B&W
MolDraw2DSVG drawer(200, 200);
assignBWPalette(drawer.drawOptions().atomColourPalette);
drawer.drawMolecule(*m1, "m1");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
TEST_ASSERT(text.find("stroke:#00CC00") == std::string::npos);
std::ofstream outs("test14_2.svg");
outs << text;
outs.flush();
}
delete m1;
}
std::cerr << " Done" << std::endl;
}
void test15ContinuousHighlightingWithGrid() {
std::cerr << " ----------------- Testing use of continuous highlighting with "
"drawMolecules"
<< std::endl;
{
std::string smiles =
"COc1cccc(NC(=O)[C@H](Cl)Sc2nc(ns2)c3ccccc3Cl)c1"; // made up
RWMol *m1 = SmilesToMol(smiles);
TEST_ASSERT(m1);
smiles = "NC(=O)[C@H](Cl)Sc1ncns1"; // made up
RWMol *m2 = SmilesToMol(smiles);
TEST_ASSERT(m2);
std::vector<ROMol *> mols;
mols.push_back(m1);
mols.push_back(m2);
std::vector<std::vector<int>> atHighlights(2);
atHighlights[0].push_back(0);
atHighlights[0].push_back(1);
atHighlights[0].push_back(2);
atHighlights[0].push_back(6);
atHighlights[1].push_back(0);
atHighlights[1].push_back(1);
atHighlights[1].push_back(2);
atHighlights[1].push_back(6);
{
MolDraw2DSVG drawer(500, 200, 250, 200);
drawer.drawOptions().continuousHighlight = false;
drawer.drawMolecules(mols, nullptr, &atHighlights);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test15_1.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("stroke:#FF7F7F;stroke-width:4px;") ==
std::string::npos);
}
{
MolDraw2DSVG drawer(500, 200, 250, 200);
drawer.drawOptions().continuousHighlight = true;
drawer.drawMolecules(mols, nullptr, &atHighlights);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test15_2.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("stroke:#FF7F7F;stroke-width:4px;") !=
std::string::npos);
}
for (auto &&mol : mols) {
delete mol;
}
}
std::cerr << " Done" << std::endl;
}
void testGithub1829() {
std::cerr << " ----------------- Testing github 1829: crash when "
"drawMolecules() is called with an empty list"
<< std::endl;
{
std::vector<ROMol *> mols;
MolDraw2DSVG drawer(750, 400, 250, 200);
// this should run quietly without complaining
drawer.drawMolecules(mols);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
}
std::cerr << " Done" << std::endl;
}
void test16MoleculeMetadata() {
std::cout << " ----------------- Testing inclusion of molecule metadata"
<< std::endl;
{
std::string smiles = "CN[C@H](Cl)C(=O)O";
std::unique_ptr<RWMol> m1(SmilesToMol(smiles));
TEST_ASSERT(m1);
MolDraw2DUtils::prepareMolForDrawing(*m1);
{ // one molecule
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m1, "m1");
drawer.addMoleculeMetadata(*m1);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test16_1.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("idx=\"2\" atom-smiles=\"[NH]\" drawing-x=\"55.") !=
std::string::npos);
TEST_ASSERT(text.find("idx=\"2\" begin-atom-idx=\"3\" end-atom-idx=\"2\" "
"bond-smiles=\"-\"") != std::string::npos);
}
{ // multiple molecules
MolDraw2DSVG drawer(400, 400, 200, 200);
auto *rom = rdcast<ROMol *>(m1.get());
std::vector<ROMol *> ms = {new ROMol(*rom), new ROMol(*rom),
new ROMol(*rom), new ROMol(*rom)};
drawer.drawMolecules(ms);
drawer.addMoleculeMetadata(ms);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test16_2.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("idx=\"2\" atom-smiles=\"[NH]\" drawing-x=\"55.") !=
std::string::npos);
TEST_ASSERT(text.find("idx=\"2\" atom-smiles=\"[NH]\" drawing-x=\"255.") !=
std::string::npos);
for (auto ptr : ms) {
delete ptr;
}
}
}
std::cerr << " Done" << std::endl;
}
void test17MaxMinFontSize() {
std::cout << " ----------------- Test 17 - Testing maximum font size"
<< std::endl;
{
std::string fName = getenv("RDBASE");
fName += "/Code/GraphMol/MolDraw2D/test_dir";
fName += "/clash.mol";
std::unique_ptr<ROMol> m(MolFileToMol(fName));
std::string nameBase = "test17_";
TEST_ASSERT(m);
{
std::ofstream outs((nameBase + "1.svg").c_str());
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// where it starts drawing the N is a poor surrogate for checking
// the font size, but all we have.
TEST_ASSERT(text.find("<path class='atom-4' d='M 142.783 175.974")
!= std::string::npos);
#else
TEST_ASSERT(text.find("font-size:40px") != std::string::npos);
#endif
}
{
std::ofstream outs((nameBase + "2.svg").c_str());
MolDraw2DSVG drawer(300, 300);
drawer.drawOptions().maxFontSize = -1;
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// where it starts drawing the N
TEST_ASSERT(text.find("<path class='atom-4' d='M 140.145 170.008")
!= std::string::npos);
#else
TEST_ASSERT(text.find("font-size:56px") != std::string::npos);
#endif
}
{
std::ofstream outs((nameBase + "3.svg").c_str());
MolDraw2DSVG drawer(300, 300);
drawer.drawOptions().maxFontSize = 20;
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// where it starts drawing the N
TEST_ASSERT(text.find("<path class='atom-4' d='M 145.913 183.054")
!= std::string::npos);
#else
TEST_ASSERT(text.find("font-size:20px") != std::string::npos);
#endif
}
{
auto m1 = "C[C@H](C1=C(C=CC(=C1Cl)F)Cl)OC2=C(N=CC(=C2)C3"
"=CN(N=C3)C4CCNCC4)N"_smiles;
std::ofstream outs((nameBase + "4.svg").c_str());
MolDraw2DSVG drawer(200, 200);
// this is currently the default min font size. Repeated for
// documentation of test.
drawer.drawOptions().minFontSize = 12;
drawer.drawMolecule(*m1);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
TEST_ASSERT(text.find("<path class='atom-8' d='M 164.311 92.8295")
!= std::string::npos);
#else
TEST_ASSERT(text.find("font-size:12px") != std::string::npos);
#endif
}
}
std::cerr << " Done" << std::endl;
}
void test18FixedScales() {
std::cout << " ----------------- Testing use of fixed scales for drawing."
<< std::endl;
std::string nameBase = "test18_";
{
auto m = "Clc1ccccc1"_smiles;
TEST_ASSERT(m);
{
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs((nameBase + "1.svg").c_str());
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// where it starts drawing the l is a poor surrogate for checking
// the font size, but all we have.
TEST_ASSERT(text.find("<path class='atom-0' d='M 283.208 136.983")
!= std::string::npos);
#else
TEST_ASSERT(text.find("font-size:33px") != std::string::npos);
#endif
}
{
MolDraw2DSVG drawer(300, 300);
// fix scale so bond is 5% if window width.
drawer.drawOptions().fixedScale = 0.05;
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs((nameBase + "2.svg").c_str());
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// where it starts drawing the l.
TEST_ASSERT(text.find("<path class='atom-0' d='M 186.029 145.446")
!= std::string::npos);
#else
TEST_ASSERT(text.find("font-size:12px") != std::string::npos);
#endif
}
}
{
std::string smi =
"C[C@@H](N[C@@H]1CC[C@@H](C(=O)N2CCC(C(=O)N3CCCC3)"
"(c3ccccc3)CC2)C(C)(C)C1)c1ccc(Cl)cc1";
std::unique_ptr<ROMol> m(SmilesToMol(smi));
TEST_ASSERT(m);
{
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs((nameBase + "3.svg").c_str());
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
TEST_ASSERT(text.find("<path class='atom-2' d='M 72.9974 183.349")
!= std::string::npos);
#else
TEST_ASSERT(text.find("font-size:12px") != std::string::npos);
#endif
}
{
// fix bond length to 10 pixels.
MolDraw2DSVG drawer(300, 300);
drawer.drawOptions().fixedBondLength = 10;
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs((nameBase + "4.svg").c_str());
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
TEST_ASSERT(text.find("<path class='atom-2' d='M 103.103 168.282")
!= std::string::npos);
#else
TEST_ASSERT(text.find("font-size:12px") != std::string::npos);
#endif
}
{
// this one should be the same size as the first (_3), as it won't scale
// up if the picture won't fit.
MolDraw2DSVG drawer(300, 300);
drawer.drawOptions().fixedBondLength = 30;
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs((nameBase + "5.svg").c_str());
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
TEST_ASSERT(text.find("<path class='atom-2' d='M 72.9974 183.349")
!= std::string::npos);
#else
TEST_ASSERT(text.find("font-size:12px") != std::string::npos);
#endif
}
}
std::cerr << " Done" << std::endl;
}
void test19RotateDrawing() {
std::cout << " ----------------- Testing rotation of 2D drawing."
<< std::endl;
std::string nameBase = "test19_";
{
std::string smi = "Clc1ccccc1";
std::unique_ptr<ROMol> m(SmilesToMol(smi));
TEST_ASSERT(m);
{
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs((nameBase + "1.svg").c_str());
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
TEST_ASSERT(text.find("<path class='atom-0' d='M 283.208 136.983") !=
std::string::npos);
#else
TEST_ASSERT(text.find("<text x='256.827' y='166.888' class='atom-0'") !=
std::string::npos);
#endif
}
{
MolDraw2DSVG drawer(300, 300);
drawer.drawOptions().rotate = 90.0;
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs((nameBase + "2.svg").c_str());
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
TEST_ASSERT(text.find("<path class='atom-0' d='M 140.562 273.779") !=
std::string::npos);
#else
TEST_ASSERT(text.find("<text x='139.773' y='286.364' class='atom-0'") !=
std::string::npos);
#endif
}
}
std::cerr << " Done" << std::endl;
}
void testGithub2063() {
std::cout << " ----------------- Testing Github2063: Drawing racemic bond "
"stereo as crossed bonds should be the default"
<< std::endl;
{
std::string molb = R"molb(squiggle bond
Mrv1810 09301816112D
4 3 0 0 0 0 999 V2000
0.5804 -0.3125 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
1.2948 0.1000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-0.1341 0.1000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
2.0093 -0.3125 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
1 2 2 0 0 0 0
1 3 1 0 0 0 0
2 4 1 4 0 0 0
M END)molb";
std::unique_ptr<RWMol> m1(MolBlockToMol(molb));
TEST_ASSERT(m1);
MolDraw2DUtils::prepareMolForDrawing(*m1);
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m1, "m1");
drawer.addMoleculeMetadata(*m1);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("testGithub2063_1.svg");
outs << text;
outs.flush();
TEST_ASSERT(
text.find(
"<path class='bond-0' d='M 65.8823,100.884 L 134.118,79.1159'") !=
std::string::npos);
TEST_ASSERT(
text.find(
"<path class='bond-1' d='M 69.6998,107.496 L 9.09091,72.5044'") !=
std::string::npos);
}
{
std::string molb = R"molb(crossed bond
Mrv1810 09301816112D
4 3 0 0 0 0 999 V2000
0.5804 -0.3125 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
1.2948 0.1000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-0.1341 0.1000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
2.0093 -0.3125 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
1 2 2 3 0 0 0
1 3 1 0 0 0 0
2 4 1 0 0 0 0
M END)molb";
std::unique_ptr<RWMol> m1(MolBlockToMol(molb));
TEST_ASSERT(m1);
MolDraw2DUtils::prepareMolForDrawing(*m1);
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m1, "m1");
drawer.addMoleculeMetadata(*m1);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("testGithub2063_2.svg");
outs << text;
outs.flush();
TEST_ASSERT(
text.find(
"<path class='bond-0' d='M 65.8823,100.884 L 134.118,79.1159'") !=
std::string::npos);
TEST_ASSERT(
text.find(
"<path class='bond-1' d='M 69.6998,107.496 L 9.09091,72.5044'") !=
std::string::npos);
}
std::cerr << " Done" << std::endl;
}
void testGithub2151() {
std::cout << " ----------------- Testing Github2151: MolDraw2D: line width "
"should be controlled by MolDrawOptions"
<< std::endl;
{
auto m1 = "C[C@H](F)c1ccc(C#N)cc1"_smiles;
TEST_ASSERT(m1);
MolDraw2DUtils::prepareMolForDrawing(*m1);
{
MolDraw2DSVG drawer(200, 200);
drawer.drawMolecule(*m1);
drawer.addMoleculeMetadata(*m1);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("testGithub2151_1.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("stroke-width:2px") != std::string::npos);
TEST_ASSERT(text.find("stroke-width:3px") == std::string::npos);
}
{
MolDraw2DSVG drawer(200, 200);
drawer.drawOptions().bondLineWidth = 8;
drawer.drawMolecule(*m1);
drawer.addMoleculeMetadata(*m1);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("testGithub2151_2.svg");
outs << text;
outs.flush();
// the bonds are scaled in thickness, so it won't be 8 pixels.
// Experiment finds 3 on my machine.
TEST_ASSERT(text.find("stroke-width:2px") == std::string::npos);
TEST_ASSERT(text.find("stroke-width:3px") != std::string::npos);
}
}
std::cerr << " Done" << std::endl;
}
void testGithub2762() {
std::cout << " ----------------- Testing testGithub2762: MolDraw2D: HCl "
"and ethane should be drawn"
<< std::endl;
{
auto m1 = "Cl"_smiles;
TEST_ASSERT(m1);
auto m2 = "CC"_smiles;
TEST_ASSERT(m2);
MolDraw2DUtils::prepareMolForDrawing(*m1);
MolDraw2DUtils::prepareMolForDrawing(*m2);
std::vector<ROMol *> mols;
mols.push_back(m1.get());
mols.push_back(m2.get());
MolDraw2DSVG drawer(500, 250, 250, 250);
drawer.drawMolecules(mols);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("testGithub2762.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("font-size:0px") == std::string::npos);
TEST_ASSERT(text.find("'bond-0' d='M 0,200 L 0,200'") == std::string::npos);
}
std::cerr << " Done" << std::endl;
}
void testGithub2931() {
std::cout << " ----------------- Testing testGithub2931: multi-coloured"
" molecule highlights."
<< std::endl;
auto get_all_hit_atoms = [](ROMol &mol,
const std::string &smt) -> std::vector<int> {
std::vector<int> hit_atoms;
RWMol *query = SmartsToMol(smt);
std::vector<MatchVectType> hits_vect;
SubstructMatch(mol, *query, hits_vect);
for (size_t i = 0; i < hits_vect.size(); ++i) {
for (size_t j = 0; j < hits_vect[i].size(); ++j) {
hit_atoms.emplace_back(hits_vect[i][j].second);
}
}
delete query;
return hit_atoms;
};
auto get_all_hit_bonds =
[](ROMol &mol, const std::vector<int> &hit_atoms) -> std::vector<int> {
std::vector<int> hit_bonds;
for (int i : hit_atoms) {
for (int j : hit_atoms) {
if (i > j) {
Bond *bnd = mol.getBondBetweenAtoms(i, j);
if (bnd) {
hit_bonds.emplace_back(bnd->getIdx());
}
}
}
}
return hit_bonds;
};
auto update_colour_map = [](const std::vector<int> &ats, DrawColour col,
std::map<int, std::vector<DrawColour>> &ha_map) {
for (auto h : ats) {
auto ex = ha_map.find(h);
if (ex == ha_map.end()) {
std::vector<DrawColour> cvec(1, col);
ha_map.insert(make_pair(h, cvec));
} else {
if (ex->second.end() ==
find(ex->second.begin(), ex->second.end(), col)) {
ex->second.emplace_back(col);
}
}
}
};
{
std::string smiles = "CO[C@@H](O)C1=C(O[C@H](F)Cl)C(C#N)=C1ONNC[NH3+]";
std::unique_ptr<ROMol> m(SmilesToMol(smiles));
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
std::vector<std::string> smarts = {"CONN", "N#CC~CO", "C=CON", "CONNCN"};
std::vector<DrawColour> colours = {
DrawColour(1.0, 0.0, 0.0), DrawColour(0.0, 1.0, 0.0),
DrawColour(0.0, 0.0, 1.0), DrawColour(1.0, 0.55, 0.0)};
std::map<int, std::vector<DrawColour>> ha_map;
std::map<int, std::vector<DrawColour>> hb_map;
for (size_t i = 0; i < smarts.size(); ++i) {
std::vector<int> hit_atoms = get_all_hit_atoms(*m, smarts[i]);
std::vector<int> hit_bonds = get_all_hit_bonds(*m, hit_atoms);
update_colour_map(hit_atoms, colours[i], ha_map);
update_colour_map(hit_bonds, colours[i], hb_map);
}
std::map<int, double> h_rads;
std::map<int, int> h_lw_mult;
{
MolDraw2DSVG drawer(500, 500);
drawer.drawOptions().fillHighlights = false;
drawer.drawOptions().continuousHighlight = true;
drawer.drawMoleculeWithHighlights(*m, "Test 1", ha_map, hb_map, h_rads,
h_lw_mult);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("testGithub2931_1.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("stroke:#FF8C00;stroke-width:5px") !=
std::string::npos);
#ifdef RDK_BUILD_FREETYPE_SUPPORT
TEST_ASSERT(text.find("<ellipse cx='242.681' cy='368.766'"
" rx='13.3446' ry='14.9254'"
" style='fill:none;stroke:#00FF00;")
!= std::string::npos);
#else
TEST_ASSERT(text.find("<ellipse cx='243.376' cy='315.326'"
" rx='10.1913' ry='10.1913'"
" style='fill:none;stroke:#00FF00;")
!= std::string::npos);
#endif
}
{
MolDraw2DSVG drawer(500, 500);
drawer.drawOptions().fillHighlights = false;
drawer.drawOptions().continuousHighlight = true;
drawer.drawOptions().atomHighlightsAreCircles = true;
drawer.drawMoleculeWithHighlights(*m, "Test 2", ha_map, hb_map, h_rads,
h_lw_mult);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("testGithub2931_2.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("stroke:#FF8C00;stroke-width:5px") !=
std::string::npos);
#ifdef RDK_BUILD_FREETYPE_SUPPORT
TEST_ASSERT(text.find("<ellipse cx='242.154' cy='367.046'"
" rx='10.4609' ry='10.4609'"
" style='fill:none;stroke:#00FF00;")
!= std::string::npos);
#else
TEST_ASSERT(text.find("<ellipse cx='242.209' cy='312.678'"
" rx='10.3875' ry='10.3875'"
" style='fill:none;stroke:#00FF00;")
!= std::string::npos);
#endif
}
}
std::cerr << " Done" << std::endl;
}
void testGithub3112() {
std::cout << " ----------------- Testing drawing of legends."
<< std::endl;
{
auto m = "CCCC"_smiles;
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
MolDraw2DSVG drawer(250, 200);
drawer.drawMolecule(*m, "foobar");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("testGithub3112_1.svg");
outs << text;
outs.close();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// this is the b
TEST_ASSERT(text.find("<path d='M 126.868 183.056")
!= std::string::npos);
#else
TEST_ASSERT(text.find("<text x='121.043' y='195.2'"
" style='font-size:15px;font-style:normal;"
"font-weight:normal;fill-opacity:1;stroke:none;"
"font-family:sans-serif;text-anchor:start;"
"fill:#000000' >b</text>")
!= std::string::npos);
#endif
}
{
auto m = "CCCC"_smiles;
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
MolDraw2DSVG drawer(250, 200);
drawer.drawMolecule(*m, "foo\nbar");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("testGithub3112_2.svg");
outs << text;
outs.close();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// this is the b on the 2nd line.
TEST_ASSERT(text.find("<path d='M 117.378 189.158")
!= std::string::npos);
#else
TEST_ASSERT(text.find("<text x='110.128' y='196.25'"
" style='font-size:12px;font-style:normal;"
"font-weight:normal;fill-opacity:1;stroke:none;"
"font-family:sans-serif;text-anchor:start;"
"fill:#000000' >b</text>")
!= std::string::npos);
#endif
}
{
auto m = "CCCC"_smiles;
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
MolDraw2DSVG drawer(250, 200);
drawer.drawMolecule(
*m,
"No one in their right mind would have a legend this long, surely.");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("testGithub3112_3.svg");
outs << text;
outs.close();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// The first letter, N.
TEST_ASSERT(text.find("<path d='M -1.43535 187.152")
!= std::string::npos);
#else
TEST_ASSERT(text.find("<text x='-2.53351' y='196.776'"
" style='font-size:10px;font-style:normal;"
"font-weight:normal;fill-opacity:1;stroke:none;"
"font-family:sans-serif;text-anchor:start;"
"fill:#000000' >N</text>")
!= std::string::npos);
#endif
}
{
auto m = "CCCC"_smiles;
TEST_ASSERT(m);
MolDraw2DUtils::prepareMolForDrawing(*m);
MolDraw2DSVG drawer(250, 200);
drawer.drawMolecule(*m, "No one in their right mind would\nhave a legend this long, surely.");
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("testGithub3112_4.svg");
outs << text;
outs.close();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// The first letter, N
TEST_ASSERT(text.find("<path d='M 58.2953 176.748")
!= std::string::npos);
#else
TEST_ASSERT(text.find("<text x='50.2289' y='186.25'"
" style='font-size:12px;font-style:normal;"
"font-weight:normal;fill-opacity:1;stroke:none;"
"font-family:sans-serif;text-anchor:start;"
"fill:#000000' >N</text>")
!= std::string::npos);
#endif
}
std::cerr << " Done" << std::endl;
}
void test20Annotate() {
std::cout << " ----------------- Testing annotation of 2D Drawing."
<< std::endl;
// add serial numbers to the atoms in the molecule.
// There's an option for this, but for debugging it's sometimes
// useful to be able to put notes on just a few atoms.
auto addAtomSerialNumbers = [](ROMol &mol) {
for (auto atom : mol.atoms()) {
atom->setProp(common_properties::atomNote, atom->getIdx());
}
};
auto addBondSerialNumbers = [](ROMol &mol) {
for (auto bond : mol.bonds()) {
bond->setProp(common_properties::bondNote, bond->getIdx());
}
};
{
auto m1 = "S=C1N=C(NC(CC#N)(C)C=C=C)NC2=NNN=C21"_smiles;
addAtomSerialNumbers(*m1);
addBondSerialNumbers(*m1);
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(500, 500);
drawer.drawMolecule(*m1);
drawer.finishDrawing();
drawer.writeDrawingText("test20_1.png");
}
#endif
MolDraw2DSVG drawer(500, 500);
drawer.drawMolecule(*m1);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test20_1.svg");
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// first note (atom 0)
TEST_ASSERT(text.find("<path class='note' d='M 44.9405 115.662") !=
std::string::npos);
#else
// first one of atom note 11
TEST_ASSERT(text.find("<text x='414.06' y='253.478' class='note'"
" style='font-size:12px;font-style:normal;"
"font-weight:normal;fill-opacity:1;stroke:none;"
"font-family:sans-serif;text-anchor:start;"
"fill:#000000' >1</text>") != std::string::npos);
#endif
}
{
auto m1 = "C[C@@H](F)/C=C/[C@H](O)C"_smiles;
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions().addStereoAnnotation = true;
drawer.drawMolecule(*m1);
drawer.finishDrawing();
drawer.writeDrawingText("test20_2.png");
}
#endif
MolDraw2DSVG drawer(500, 500);
drawer.drawOptions().addStereoAnnotation = true;
drawer.drawMolecule(*m1);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test20_2.svg");
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// last note
TEST_ASSERT(text.find("<path class='note' d='M 278.068 227.499")
!= std::string::npos);
#else
// this is the (E)
TEST_ASSERT(text.find("<text x='261.024' y='231.57' class='note'"
" style='font-size:20px;font-style:normal;"
"font-weight:normal;fill-opacity:1;"
"stroke:none;font-family:sans-serif;"
"text-anchor:start;fill:#000000' >E</text>")
!= std::string::npos);
#endif
}
{
auto m1 = "S=C1N=C(NC(CC#N)(C)C=C=C)NC2=NNN=C21"_smiles;
auto atom = m1->getAtomWithIdx(3);
atom->setProp("atomNote", "foolish annotation");
auto bond = m1->getBondWithIdx(5);
bond->setProp("bondNote", "way too long to be useful");
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(300, 300);
drawer.drawOptions().addStereoAnnotation = true;
drawer.drawMolecule(*m1);
drawer.finishDrawing();
drawer.writeDrawingText("test20_3.png");
}
#endif
MolDraw2DSVG drawer(500, 500);
drawer.drawOptions().addStereoAnnotation = true;
drawer.drawMolecule(*m1);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test20_3.svg");
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// first note
TEST_ASSERT(text.find("<path class='note' d='M 157.64 176.655") !=
std::string::npos);
#else
// f of foolish
TEST_ASSERT(text.find("<text x='145.74' y='181.531' class='note'"
" style='font-size:12px;font-style:normal;"
"font-weight:normal;fill-opacity:1;stroke:none;"
"font-family:sans-serif;text-anchor:start;"
"fill:#000000' >f</text>") != std::string::npos);
#endif
}
{
auto m1 = "S=C1N=C(NC(CC#N)(C)C=C=C)NC2=NNN=C21"_smiles;
#ifdef RDK_BUILD_CAIRO_SUPPORT
{
MolDraw2DCairo drawer(200, 200);
drawer.drawOptions().addAtomIndices = true;
drawer.drawMolecule(*m1);
drawer.finishDrawing();
drawer.writeDrawingText("test20_4.png");
}
#endif
MolDraw2DSVG drawer(200, 200);
drawer.drawOptions().addAtomIndices = true;
drawer.drawMolecule(*m1);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test20_4.svg");
outs << text;
outs.flush();
#ifdef RDK_BUILD_FREETYPE_SUPPORT
// first note (atom 0)
TEST_ASSERT(text.find("<path class='note' d='M 17.9762 46.6634") !=
std::string::npos);
#else
// first one of atom note 11
TEST_ASSERT(text.find("<text x='164.595' y='101.936'"
" class='note' style='font-size:6px;"
"font-style:normal;font-weight:normal;"
"fill-opacity:1;stroke:none;"
"font-family:sans-serif;text-anchor:start;"
"fill:#000000' >1</text>") != std::string::npos);
#endif
}
std::cerr << " Done" << std::endl;
}
void test21FontFile() {
#ifdef RDK_BUILD_FREETYPE_SUPPORT
std::cout << " ----------------- Test 21 - different font" << std::endl;
// You have to look at this one, there's no algorithmic check.
{
auto m = "CO[C@@H](O)C1=C(O[C@H](F)Cl)C(C#N)=C1ONNC[NH3+]"_smiles;
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
std::ofstream outs("test21_1.svg");
MolDraw2DSVG drawer(500, 500, outs);
std::string fName = getenv("RDBASE");
fName += "/Data/Fonts/Amadeus.ttf";
drawer.drawOptions().fontFile = fName;
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
{
auto m = "CO[C@@H](O)C1=C(O[C@H](F)Cl)C(C#N)=C1ONNC[NH3+]"_smiles;
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
WedgeMolBonds(*m, &(m->getConformer()));
std::ofstream outs("test21_2.svg");
MolDraw2DSVG drawer(500, 500, outs);
std::string fName = getenv("RDBASE");
fName += "/Data/Fonts/No_Such_Font_File.ttf";
drawer.drawOptions().fontFile = fName;
drawer.drawMolecule(*m);
drawer.finishDrawing();
outs.flush();
}
std::cerr << "Done" << std::endl;
#endif
}
void test22ExplicitMethyl() {
std::cout << " ----------------- Test 22 - draw explicit methyls." << std::endl;
auto m = "CCC(C#C)C=C"_smiles;
TEST_ASSERT(m);
RDDepict::compute2DCoords(*m);
{
MolDraw2DSVG drawer(300, 300);
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test22_1.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("class='atom-") == std::string::npos);
}
{
MolDraw2DSVG drawer(300, 300);
drawer.drawOptions().explicitMethyl = true;
drawer.drawMolecule(*m);
drawer.finishDrawing();
std::string text = drawer.getDrawingText();
std::ofstream outs("test22_2.svg");
outs << text;
outs.flush();
TEST_ASSERT(text.find("class='atom-") != std::string::npos);
}
}
int main() {
#ifdef RDK_BUILD_COORDGEN_SUPPORT
RDDepict::preferCoordGen = false;
#endif
RDLog::InitLogs();
#if 1
test1();
test2();
test4();
test5();
test6();
test7();
test8PrepareMolForDrawing();
testMultiThreaded();
testGithub781();
test3();
testGithub774();
test9MolLegends();
testGithub852();
testGithub860();
testGithub910();
testGithub932();
testGithub953();
testGithub983();
testDeuteriumTritium();
testCrossedBonds();
test10DrawSecondMol();
test11DrawMolGrid();
test12DrawMols();
test13JSONConfig();
testGithub1090();
testGithub1035();
testGithub1271();
testGithub1322();
testGithub565();
test14BWPalette();
test15ContinuousHighlightingWithGrid();
test17MaxMinFontSize();
testGithub1829();
test18FixedScales();
test19RotateDrawing();
test16MoleculeMetadata();
testGithub2063();
testGithub2151();
testGithub2762();
testGithub2931();
test20Annotate();
test21FontFile();
test22ExplicitMethyl();
testGithub3112();
#endif
}
| 1 | 21,539 | this should probably be removed | rdkit-rdkit | cpp |
@@ -74,7 +74,7 @@ func TestConfigDaemon(t *testing.T) {
jsonOut := op1.ReadStdout()
bootstrapConfig := config.NewDefaultConfig().Bootstrap
bootstrapConfig.Addresses = []string{"fake1", "fake2"}
- someJSON, err := json.MarshalIndent(bootstrapConfig, "", "\t")
+ someJSON, err := json.Marshal(bootstrapConfig)
require.NoError(t, err)
assert.Equal(t, fmt.Sprintf("%s\n", string(someJSON)), jsonOut)
| 1 | package commands_test
import (
"context"
"encoding/json"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/filecoin-project/go-filecoin/internal/app/go-filecoin/node/test"
"github.com/filecoin-project/go-filecoin/internal/pkg/config"
tf "github.com/filecoin-project/go-filecoin/internal/pkg/testhelpers/testflags"
)
func TestConfigDaemon(t *testing.T) {
tf.IntegrationTest(t)
ctx := context.Background()
t.Run("config <key> prints config value", func(t *testing.T) {
builder := test.NewNodeBuilder(t)
_, cmdClient, done := builder.BuildAndStartAPI(ctx)
defer done()
op1 := cmdClient.RunSuccess(ctx, "config", "datastore")
jsonOut := op1.ReadStdout()
wrapped1 := config.NewDefaultConfig().Datastore
var decodedOutput1 config.DatastoreConfig
err := json.Unmarshal([]byte(jsonOut), &decodedOutput1)
require.NoError(t, err)
assert.Equal(t, wrapped1, &decodedOutput1)
op2 := cmdClient.RunSuccess(ctx, "config", "datastore.path")
jsonOut = op2.ReadStdout()
assert.Equal(t, fmt.Sprintf("%q\n", config.NewDefaultConfig().Datastore.Path), jsonOut)
})
t.Run("config <key> simple_value updates config", func(t *testing.T) {
builder := test.NewNodeBuilder(t)
n, cmdClient, done := builder.BuildAndStartAPI(ctx)
defer done()
period := "1m"
// check writing default does not error
cmdClient.RunSuccess(ctx, "config", "bootstrap.period", period)
op1 := cmdClient.RunSuccess(ctx, "config", "bootstrap.period")
// validate output
jsonOut := op1.ReadStdout()
bootstrapConfig := config.NewDefaultConfig().Bootstrap
assert.Equal(t, fmt.Sprintf("\"%s\"\n", period), jsonOut)
// validate config write
nbci, err := n.PorcelainAPI.ConfigGet("bootstrap")
require.NoError(t, err)
nbc, ok := nbci.(*config.BootstrapConfig)
require.True(t, ok)
assert.Equal(t, nbc, bootstrapConfig)
})
t.Run("config <key> <val> updates config", func(t *testing.T) {
builder := test.NewNodeBuilder(t)
n, cmdClient, done := builder.BuildAndStartAPI(ctx)
defer done()
cmdClient.RunSuccess(ctx, "config", "bootstrap", `{"addresses": ["fake1", "fake2"], "period": "1m", "minPeerThreshold": 0}`)
op1 := cmdClient.RunSuccess(ctx, "config", "bootstrap")
// validate output
jsonOut := op1.ReadStdout()
bootstrapConfig := config.NewDefaultConfig().Bootstrap
bootstrapConfig.Addresses = []string{"fake1", "fake2"}
someJSON, err := json.MarshalIndent(bootstrapConfig, "", "\t")
require.NoError(t, err)
assert.Equal(t, fmt.Sprintf("%s\n", string(someJSON)), jsonOut)
// validate config write
nbci, err := n.PorcelainAPI.ConfigGet("bootstrap")
require.NoError(t, err)
nbc, ok := nbci.(*config.BootstrapConfig)
require.True(t, ok)
assert.Equal(t, nbc, bootstrapConfig)
})
}
| 1 | 23,506 | Nit: I would actually prefer that pretty JSON is the default, with a flag for compressed JSON. Can we acheive that easily? | filecoin-project-venus | go |
@@ -159,6 +159,11 @@ type NetworkSpec struct {
// This is optional - if not provided new security groups will be created for the cluster
// +optional
SecurityGroupOverrides map[SecurityGroupRole]string `json:"securityGroupOverrides,omitempty"`
+
+ // AdditionalIngressRules is an optional map from security group role to a set of additional ingress
+ // rules to add to the security group rules created for that role
+ // +optional
+ AdditionalIngressRules map[SecurityGroupRole]IngressRules `json:"additionalIngressRules,omitempty"`
}
// VPCSpec configures an AWS VPC. | 1 | /*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1beta1
import (
"fmt"
"sort"
"time"
)
// NetworkStatus encapsulates AWS networking resources.
type NetworkStatus struct {
// SecurityGroups is a map from the role/kind of the security group to its unique name, if any.
SecurityGroups map[SecurityGroupRole]SecurityGroup `json:"securityGroups,omitempty"`
// APIServerELB is the Kubernetes api server classic load balancer.
APIServerELB ClassicELB `json:"apiServerElb,omitempty"`
}
// ClassicELBScheme defines the scheme of a classic load balancer.
type ClassicELBScheme string
var (
// ClassicELBSchemeInternetFacing defines an internet-facing, publicly
// accessible AWS Classic ELB scheme.
ClassicELBSchemeInternetFacing = ClassicELBScheme("internet-facing")
// ClassicELBSchemeInternal defines an internal-only facing
// load balancer internal to an ELB.
ClassicELBSchemeInternal = ClassicELBScheme("internal")
// ClassicELBSchemeIncorrectInternetFacing was inaccurately used to define an internet-facing LB in v0.6 releases > v0.6.6 and v0.7.0 release.
ClassicELBSchemeIncorrectInternetFacing = ClassicELBScheme("Internet-facing")
)
func (e ClassicELBScheme) String() string {
return string(e)
}
// ClassicELBProtocol defines listener protocols for a classic load balancer.
type ClassicELBProtocol string
var (
// ClassicELBProtocolTCP defines the ELB API string representing the TCP protocol.
ClassicELBProtocolTCP = ClassicELBProtocol("TCP")
// ClassicELBProtocolSSL defines the ELB API string representing the TLS protocol.
ClassicELBProtocolSSL = ClassicELBProtocol("SSL")
// ClassicELBProtocolHTTP defines the ELB API string representing the HTTP protocol at L7.
ClassicELBProtocolHTTP = ClassicELBProtocol("HTTP")
// ClassicELBProtocolHTTPS defines the ELB API string representing the HTTP protocol at L7.
ClassicELBProtocolHTTPS = ClassicELBProtocol("HTTPS")
)
// ClassicELB defines an AWS classic load balancer.
type ClassicELB struct {
// The name of the load balancer. It must be unique within the set of load balancers
// defined in the region. It also serves as identifier.
// +optional
Name string `json:"name,omitempty"`
// DNSName is the dns name of the load balancer.
DNSName string `json:"dnsName,omitempty"`
// Scheme is the load balancer scheme, either internet-facing or private.
Scheme ClassicELBScheme `json:"scheme,omitempty"`
// AvailabilityZones is an array of availability zones in the VPC attached to the load balancer.
AvailabilityZones []string `json:"availabilityZones,omitempty"`
// SubnetIDs is an array of subnets in the VPC attached to the load balancer.
SubnetIDs []string `json:"subnetIds,omitempty"`
// SecurityGroupIDs is an array of security groups assigned to the load balancer.
SecurityGroupIDs []string `json:"securityGroupIds,omitempty"`
// Listeners is an array of classic elb listeners associated with the load balancer. There must be at least one.
Listeners []ClassicELBListener `json:"listeners,omitempty"`
// HealthCheck is the classic elb health check associated with the load balancer.
HealthCheck *ClassicELBHealthCheck `json:"healthChecks,omitempty"`
// Attributes defines extra attributes associated with the load balancer.
Attributes ClassicELBAttributes `json:"attributes,omitempty"`
// Tags is a map of tags associated with the load balancer.
Tags map[string]string `json:"tags,omitempty"`
}
// IsUnmanaged returns true if the Classic ELB is unmanaged.
func (b *ClassicELB) IsUnmanaged(clusterName string) bool {
return b.Name != "" && !Tags(b.Tags).HasOwned(clusterName)
}
// IsManaged returns true if Classic ELB is managed.
func (b *ClassicELB) IsManaged(clusterName string) bool {
return !b.IsUnmanaged(clusterName)
}
// ClassicELBAttributes defines extra attributes associated with a classic load balancer.
type ClassicELBAttributes struct {
// IdleTimeout is time that the connection is allowed to be idle (no data
// has been sent over the connection) before it is closed by the load balancer.
IdleTimeout time.Duration `json:"idleTimeout,omitempty"`
// CrossZoneLoadBalancing enables the classic load balancer load balancing.
// +optional
CrossZoneLoadBalancing bool `json:"crossZoneLoadBalancing,omitempty"`
}
// ClassicELBListener defines an AWS classic load balancer listener.
type ClassicELBListener struct {
Protocol ClassicELBProtocol `json:"protocol"`
Port int64 `json:"port"`
InstanceProtocol ClassicELBProtocol `json:"instanceProtocol"`
InstancePort int64 `json:"instancePort"`
}
// ClassicELBHealthCheck defines an AWS classic load balancer health check.
type ClassicELBHealthCheck struct {
Target string `json:"target"`
Interval time.Duration `json:"interval"`
Timeout time.Duration `json:"timeout"`
HealthyThreshold int64 `json:"healthyThreshold"`
UnhealthyThreshold int64 `json:"unhealthyThreshold"`
}
// NetworkSpec encapsulates all things related to AWS network.
type NetworkSpec struct {
// VPC configuration.
// +optional
VPC VPCSpec `json:"vpc,omitempty"`
// Subnets configuration.
// +optional
Subnets Subnets `json:"subnets,omitempty"`
// CNI configuration
// +optional
CNI *CNISpec `json:"cni,omitempty"`
// SecurityGroupOverrides is an optional set of security groups to use for cluster instances
// This is optional - if not provided new security groups will be created for the cluster
// +optional
SecurityGroupOverrides map[SecurityGroupRole]string `json:"securityGroupOverrides,omitempty"`
}
// VPCSpec configures an AWS VPC.
type VPCSpec struct {
// ID is the vpc-id of the VPC this provider should use to create resources.
ID string `json:"id,omitempty"`
// CidrBlock is the CIDR block to be used when the provider creates a managed VPC.
// Defaults to 10.0.0.0/16.
CidrBlock string `json:"cidrBlock,omitempty"`
// InternetGatewayID is the id of the internet gateway associated with the VPC.
// +optional
InternetGatewayID *string `json:"internetGatewayId,omitempty"`
// Tags is a collection of tags describing the resource.
Tags Tags `json:"tags,omitempty"`
// AvailabilityZoneUsageLimit specifies the maximum number of availability zones (AZ) that
// should be used in a region when automatically creating subnets. If a region has more
// than this number of AZs then this number of AZs will be picked randomly when creating
// default subnets. Defaults to 3
// +kubebuilder:default=3
// +kubebuilder:validation:Minimum=1
AvailabilityZoneUsageLimit *int `json:"availabilityZoneUsageLimit,omitempty"`
// AvailabilityZoneSelection specifies how AZs should be selected if there are more AZs
// in a region than specified by AvailabilityZoneUsageLimit. There are 2 selection schemes:
// Ordered - selects based on alphabetical order
// Random - selects AZs randomly in a region
// Defaults to Ordered
// +kubebuilder:default=Ordered
// +kubebuilder:validation:Enum=Ordered;Random
AvailabilityZoneSelection *AZSelectionScheme `json:"availabilityZoneSelection,omitempty"`
}
// String returns a string representation of the VPC.
func (v *VPCSpec) String() string {
return fmt.Sprintf("id=%s", v.ID)
}
// IsUnmanaged returns true if the VPC is unmanaged.
func (v *VPCSpec) IsUnmanaged(clusterName string) bool {
return v.ID != "" && !v.Tags.HasOwned(clusterName)
}
// IsManaged returns true if VPC is managed.
func (v *VPCSpec) IsManaged(clusterName string) bool {
return !v.IsUnmanaged(clusterName)
}
// SubnetSpec configures an AWS Subnet.
type SubnetSpec struct {
// ID defines a unique identifier to reference this resource.
ID string `json:"id,omitempty"`
// CidrBlock is the CIDR block to be used when the provider creates a managed VPC.
CidrBlock string `json:"cidrBlock,omitempty"`
// AvailabilityZone defines the availability zone to use for this subnet in the cluster's region.
AvailabilityZone string `json:"availabilityZone,omitempty"`
// IsPublic defines the subnet as a public subnet. A subnet is public when it is associated with a route table that has a route to an internet gateway.
// +optional
IsPublic bool `json:"isPublic"`
// RouteTableID is the routing table id associated with the subnet.
// +optional
RouteTableID *string `json:"routeTableId,omitempty"`
// NatGatewayID is the NAT gateway id associated with the subnet.
// Ignored unless the subnet is managed by the provider, in which case this is set on the public subnet where the NAT gateway resides. It is then used to determine routes for private subnets in the same AZ as the public subnet.
// +optional
NatGatewayID *string `json:"natGatewayId,omitempty"`
// Tags is a collection of tags describing the resource.
Tags Tags `json:"tags,omitempty"`
}
// String returns a string representation of the subnet.
func (s *SubnetSpec) String() string {
return fmt.Sprintf("id=%s/az=%s/public=%v", s.ID, s.AvailabilityZone, s.IsPublic)
}
// Subnets is a slice of Subnet.
type Subnets []SubnetSpec
// ToMap returns a map from id to subnet.
func (s Subnets) ToMap() map[string]*SubnetSpec {
res := make(map[string]*SubnetSpec)
for i := range s {
x := s[i]
res[x.ID] = &x
}
return res
}
// IDs returns a slice of the subnet ids.
func (s Subnets) IDs() []string {
res := []string{}
for _, subnet := range s {
res = append(res, subnet.ID)
}
return res
}
// FindByID returns a single subnet matching the given id or nil.
func (s Subnets) FindByID(id string) *SubnetSpec {
for _, x := range s {
if x.ID == id {
return &x
}
}
return nil
}
// FindEqual returns a subnet spec that is equal to the one passed in.
// Two subnets are defined equal to each other if their id is equal
// or if they are in the same vpc and the cidr block is the same.
func (s Subnets) FindEqual(spec *SubnetSpec) *SubnetSpec {
for _, x := range s {
if (spec.ID != "" && x.ID == spec.ID) || (spec.CidrBlock == x.CidrBlock) {
return &x
}
}
return nil
}
// FilterPrivate returns a slice containing all subnets marked as private.
func (s Subnets) FilterPrivate() (res Subnets) {
for _, x := range s {
if !x.IsPublic {
res = append(res, x)
}
}
return
}
// FilterPublic returns a slice containing all subnets marked as public.
func (s Subnets) FilterPublic() (res Subnets) {
for _, x := range s {
if x.IsPublic {
res = append(res, x)
}
}
return
}
// FilterByZone returns a slice containing all subnets that live in the availability zone specified.
func (s Subnets) FilterByZone(zone string) (res Subnets) {
for _, x := range s {
if x.AvailabilityZone == zone {
res = append(res, x)
}
}
return
}
// GetUniqueZones returns a slice containing the unique zones of the subnets.
func (s Subnets) GetUniqueZones() []string {
keys := make(map[string]bool)
zones := []string{}
for _, x := range s {
if _, value := keys[x.AvailabilityZone]; !value {
keys[x.AvailabilityZone] = true
zones = append(zones, x.AvailabilityZone)
}
}
return zones
}
// CNISpec defines configuration for CNI.
type CNISpec struct {
// CNIIngressRules specify rules to apply to control plane and worker node security groups.
// The source for the rule will be set to control plane and worker security group IDs.
CNIIngressRules CNIIngressRules `json:"cniIngressRules,omitempty"`
}
// CNIIngressRules is a slice of CNIIngressRule.
type CNIIngressRules []CNIIngressRule
// CNIIngressRule defines an AWS ingress rule for CNI requirements.
type CNIIngressRule struct {
Description string `json:"description"`
Protocol SecurityGroupProtocol `json:"protocol"`
FromPort int64 `json:"fromPort"`
ToPort int64 `json:"toPort"`
}
// RouteTable defines an AWS routing table.
type RouteTable struct {
ID string `json:"id"`
}
// SecurityGroupRole defines the unique role of a security group.
type SecurityGroupRole string
var (
// SecurityGroupBastion defines an SSH bastion role.
SecurityGroupBastion = SecurityGroupRole("bastion")
// SecurityGroupNode defines a Kubernetes workload node role.
SecurityGroupNode = SecurityGroupRole("node")
// SecurityGroupEKSNodeAdditional defines an extra node group from eks nodes.
SecurityGroupEKSNodeAdditional = SecurityGroupRole("node-eks-additional")
// SecurityGroupControlPlane defines a Kubernetes control plane node role.
SecurityGroupControlPlane = SecurityGroupRole("controlplane")
// SecurityGroupAPIServerLB defines a Kubernetes API Server Load Balancer role.
SecurityGroupAPIServerLB = SecurityGroupRole("apiserver-lb")
// SecurityGroupLB defines a container for the cloud provider to inject its load balancer ingress rules.
SecurityGroupLB = SecurityGroupRole("lb")
)
// SecurityGroup defines an AWS security group.
type SecurityGroup struct {
// ID is a unique identifier.
ID string `json:"id"`
// Name is the security group name.
Name string `json:"name"`
// IngressRules is the inbound rules associated with the security group.
// +optional
IngressRules IngressRules `json:"ingressRule,omitempty"`
// Tags is a map of tags associated with the security group.
Tags Tags `json:"tags,omitempty"`
}
// String returns a string representation of the security group.
func (s *SecurityGroup) String() string {
return fmt.Sprintf("id=%s/name=%s", s.ID, s.Name)
}
// SecurityGroupProtocol defines the protocol type for a security group rule.
type SecurityGroupProtocol string
var (
// SecurityGroupProtocolAll is a wildcard for all IP protocols.
SecurityGroupProtocolAll = SecurityGroupProtocol("-1")
// SecurityGroupProtocolIPinIP represents the IP in IP protocol in ingress rules.
SecurityGroupProtocolIPinIP = SecurityGroupProtocol("4")
// SecurityGroupProtocolTCP represents the TCP protocol in ingress rules.
SecurityGroupProtocolTCP = SecurityGroupProtocol("tcp")
// SecurityGroupProtocolUDP represents the UDP protocol in ingress rules.
SecurityGroupProtocolUDP = SecurityGroupProtocol("udp")
// SecurityGroupProtocolICMP represents the ICMP protocol in ingress rules.
SecurityGroupProtocolICMP = SecurityGroupProtocol("icmp")
// SecurityGroupProtocolICMPv6 represents the ICMPv6 protocol in ingress rules.
SecurityGroupProtocolICMPv6 = SecurityGroupProtocol("58")
)
// IngressRule defines an AWS ingress rule for security groups.
type IngressRule struct {
Description string `json:"description"`
Protocol SecurityGroupProtocol `json:"protocol"`
FromPort int64 `json:"fromPort"`
ToPort int64 `json:"toPort"`
// List of CIDR blocks to allow access from. Cannot be specified with SourceSecurityGroupID.
// +optional
CidrBlocks []string `json:"cidrBlocks,omitempty"`
// The security group id to allow access from. Cannot be specified with CidrBlocks.
// +optional
SourceSecurityGroupIDs []string `json:"sourceSecurityGroupIds,omitempty"`
}
// String returns a string representation of the ingress rule.
func (i *IngressRule) String() string {
return fmt.Sprintf("protocol=%s/range=[%d-%d]/description=%s", i.Protocol, i.FromPort, i.ToPort, i.Description)
}
// IngressRules is a slice of AWS ingress rules for security groups.
type IngressRules []IngressRule
// Difference returns the difference between this slice and the other slice.
func (i IngressRules) Difference(o IngressRules) (out IngressRules) {
for index := range i {
x := i[index]
found := false
for oIndex := range o {
y := o[oIndex]
if x.Equals(&y) {
found = true
break
}
}
if !found {
out = append(out, x)
}
}
return
}
// Equals returns true if two IngressRule are equal.
func (i *IngressRule) Equals(o *IngressRule) bool {
if len(i.CidrBlocks) != len(o.CidrBlocks) {
return false
}
sort.Strings(i.CidrBlocks)
sort.Strings(o.CidrBlocks)
for i, v := range i.CidrBlocks {
if v != o.CidrBlocks[i] {
return false
}
}
if len(i.SourceSecurityGroupIDs) != len(o.SourceSecurityGroupIDs) {
return false
}
sort.Strings(i.SourceSecurityGroupIDs)
sort.Strings(o.SourceSecurityGroupIDs)
for i, v := range i.SourceSecurityGroupIDs {
if v != o.SourceSecurityGroupIDs[i] {
return false
}
}
if i.Description != o.Description || i.Protocol != o.Protocol {
return false
}
// AWS seems to ignore the From/To port when set on protocols where it doesn't apply, but
// we avoid serializing it out for clarity's sake.
// See: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_IpPermission.html
switch i.Protocol {
case SecurityGroupProtocolTCP,
SecurityGroupProtocolUDP,
SecurityGroupProtocolICMP,
SecurityGroupProtocolICMPv6:
return i.FromPort == o.FromPort && i.ToPort == o.ToPort
case SecurityGroupProtocolAll, SecurityGroupProtocolIPinIP:
// FromPort / ToPort are not applicable
}
return true
}
| 1 | 21,493 | Will need to think about this one. `additionalIngressRules` feels a bit opaque in terms of eventual outcome. | kubernetes-sigs-cluster-api-provider-aws | go |
@@ -387,7 +387,7 @@ public final class ORCSchemaUtil {
.map(Integer::parseInt);
}
- static int fieldId(TypeDescription orcType) {
+ public static int fieldId(TypeDescription orcType) {
String idStr = orcType.getAttributeValue(ICEBERG_ID_ATTRIBUTE);
Preconditions.checkNotNull(idStr, "Missing expected '%s' property", ICEBERG_ID_ATTRIBUTE);
return Integer.parseInt(idStr); | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iceberg.orc;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.iceberg.Schema;
import org.apache.iceberg.mapping.NameMapping;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMultimap;
import org.apache.iceberg.relocated.com.google.common.collect.Maps;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.TypeUtil;
import org.apache.iceberg.types.Types;
import org.apache.orc.TypeDescription;
/**
* Utilities for mapping Iceberg to ORC schemas.
*/
public final class ORCSchemaUtil {
public enum BinaryType {
UUID, FIXED, BINARY
}
public enum LongType {
TIME, LONG
}
private static class OrcField {
private final String name;
private final TypeDescription type;
OrcField(String name, TypeDescription type) {
this.name = name;
this.type = type;
}
public String name() {
return name;
}
public TypeDescription type() {
return type;
}
}
static final String ICEBERG_ID_ATTRIBUTE = "iceberg.id";
static final String ICEBERG_REQUIRED_ATTRIBUTE = "iceberg.required";
/**
* The name of the ORC {@link TypeDescription} attribute indicating the Iceberg type corresponding to an
* ORC binary type. The values for this attribute are denoted in {@code BinaryType}.
*/
public static final String ICEBERG_BINARY_TYPE_ATTRIBUTE = "iceberg.binary-type";
/**
* The name of the ORC {@link TypeDescription} attribute indicating the Iceberg type corresponding to an
* ORC long type. The values for this attribute are denoted in {@code LongType}.
*/
public static final String ICEBERG_LONG_TYPE_ATTRIBUTE = "iceberg.long-type";
static final String ICEBERG_FIELD_LENGTH = "iceberg.length";
private static final ImmutableMultimap<Type.TypeID, TypeDescription.Category> TYPE_MAPPING =
ImmutableMultimap.<Type.TypeID, TypeDescription.Category>builder()
.put(Type.TypeID.BOOLEAN, TypeDescription.Category.BOOLEAN)
.put(Type.TypeID.INTEGER, TypeDescription.Category.BYTE)
.put(Type.TypeID.INTEGER, TypeDescription.Category.SHORT)
.put(Type.TypeID.INTEGER, TypeDescription.Category.INT)
.put(Type.TypeID.LONG, TypeDescription.Category.LONG)
.put(Type.TypeID.TIME, TypeDescription.Category.LONG)
.put(Type.TypeID.FLOAT, TypeDescription.Category.FLOAT)
.put(Type.TypeID.DOUBLE, TypeDescription.Category.DOUBLE)
.put(Type.TypeID.DATE, TypeDescription.Category.DATE)
.put(Type.TypeID.STRING, TypeDescription.Category.CHAR)
.put(Type.TypeID.STRING, TypeDescription.Category.VARCHAR)
.put(Type.TypeID.STRING, TypeDescription.Category.STRING)
.put(Type.TypeID.UUID, TypeDescription.Category.BINARY)
.put(Type.TypeID.FIXED, TypeDescription.Category.BINARY)
.put(Type.TypeID.BINARY, TypeDescription.Category.BINARY)
.put(Type.TypeID.DECIMAL, TypeDescription.Category.DECIMAL)
.build();
private ORCSchemaUtil() {
}
public static TypeDescription convert(Schema schema) {
final TypeDescription root = TypeDescription.createStruct();
final Types.StructType schemaRoot = schema.asStruct();
for (Types.NestedField field : schemaRoot.asStructType().fields()) {
TypeDescription orcColumType = convert(field.fieldId(), field.type(), field.isRequired());
root.addField(field.name(), orcColumType);
}
return root;
}
private static TypeDescription convert(Integer fieldId, Type type, boolean isRequired) {
final TypeDescription orcType;
switch (type.typeId()) {
case BOOLEAN:
orcType = TypeDescription.createBoolean();
break;
case INTEGER:
orcType = TypeDescription.createInt();
break;
case TIME:
orcType = TypeDescription.createLong();
orcType.setAttribute(ICEBERG_LONG_TYPE_ATTRIBUTE, LongType.TIME.toString());
break;
case LONG:
orcType = TypeDescription.createLong();
orcType.setAttribute(ICEBERG_LONG_TYPE_ATTRIBUTE, LongType.LONG.toString());
break;
case FLOAT:
orcType = TypeDescription.createFloat();
break;
case DOUBLE:
orcType = TypeDescription.createDouble();
break;
case DATE:
orcType = TypeDescription.createDate();
break;
case TIMESTAMP:
Types.TimestampType tsType = (Types.TimestampType) type;
if (tsType.shouldAdjustToUTC()) {
orcType = TypeDescription.createTimestampInstant();
} else {
orcType = TypeDescription.createTimestamp();
}
break;
case STRING:
orcType = TypeDescription.createString();
break;
case UUID:
orcType = TypeDescription.createBinary();
orcType.setAttribute(ICEBERG_BINARY_TYPE_ATTRIBUTE, BinaryType.UUID.toString());
break;
case FIXED:
orcType = TypeDescription.createBinary();
orcType.setAttribute(ICEBERG_BINARY_TYPE_ATTRIBUTE, BinaryType.FIXED.toString());
orcType.setAttribute(ICEBERG_FIELD_LENGTH, Integer.toString(((Types.FixedType) type).length()));
break;
case BINARY:
orcType = TypeDescription.createBinary();
orcType.setAttribute(ICEBERG_BINARY_TYPE_ATTRIBUTE, BinaryType.BINARY.toString());
break;
case DECIMAL: {
Types.DecimalType decimal = (Types.DecimalType) type;
orcType = TypeDescription.createDecimal()
.withScale(decimal.scale())
.withPrecision(decimal.precision());
break;
}
case STRUCT: {
orcType = TypeDescription.createStruct();
for (Types.NestedField field : type.asStructType().fields()) {
TypeDescription childType = convert(field.fieldId(), field.type(), field.isRequired());
orcType.addField(field.name(), childType);
}
break;
}
case LIST: {
Types.ListType list = (Types.ListType) type;
TypeDescription elementType = convert(list.elementId(), list.elementType(),
list.isElementRequired());
orcType = TypeDescription.createList(elementType);
break;
}
case MAP: {
Types.MapType map = (Types.MapType) type;
TypeDescription keyType = convert(map.keyId(), map.keyType(), true);
TypeDescription valueType = convert(map.valueId(), map.valueType(), map.isValueRequired());
orcType = TypeDescription.createMap(keyType, valueType);
break;
}
default:
throw new IllegalArgumentException("Unhandled type " + type.typeId());
}
// Set Iceberg column attributes for mapping
orcType.setAttribute(ICEBERG_ID_ATTRIBUTE, String.valueOf(fieldId));
orcType.setAttribute(ICEBERG_REQUIRED_ATTRIBUTE, String.valueOf(isRequired));
return orcType;
}
/**
* Convert an ORC schema to an Iceberg schema. This method handles the convertion from the original
* Iceberg column mapping IDs if present in the ORC column attributes, otherwise, ORC columns with no
* Iceberg IDs will be ignored and skipped in the conversion.
*
* @return the Iceberg schema
* @throws IllegalArgumentException if ORC schema has no columns with Iceberg ID attributes
*/
public static Schema convert(TypeDescription orcSchema) {
List<TypeDescription> children = orcSchema.getChildren();
List<String> childrenNames = orcSchema.getFieldNames();
Preconditions.checkState(children.size() == childrenNames.size(),
"Error in ORC file, children fields and names do not match.");
OrcToIcebergVisitor schemaConverter = new OrcToIcebergVisitor();
List<Types.NestedField> fields = OrcToIcebergVisitor.visitSchema(orcSchema, schemaConverter).stream()
.filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
if (fields.size() == 0) {
throw new IllegalArgumentException("ORC schema does not contain Iceberg IDs");
}
return new Schema(fields);
}
/**
* Converts an Iceberg schema to a corresponding ORC schema within the context of an existing
* ORC file schema.
* This method also handles schema evolution from the original ORC file schema
* to the given Iceberg schema. It builds the desired reader schema with the schema
* evolution rules and pass that down to the ORC reader,
* which would then use its schema evolution to map that to the writer’s schema.
*
* Example:
* <code>
* Iceberg writer ORC writer
* struct<a (1): int, b (2): string> struct<a: int, b: string>
* struct<a (1): struct<b (2): string, c (3): date>> struct<a: struct<b:string, c:date>>
* </code>
*
* Iceberg reader ORC reader
* <code>
* struct<a (2): string, c (3): date> struct<b: string, c: date>
* struct<aa (1): struct<cc (3): date, bb (2): string>> struct<a: struct<c:date, b:string>>
* </code>
*
* @param schema an Iceberg schema
* @param originalOrcSchema an existing ORC file schema
* @return the resulting ORC schema
*/
public static TypeDescription buildOrcProjection(Schema schema,
TypeDescription originalOrcSchema) {
final Map<Integer, OrcField> icebergToOrc = icebergToOrcMapping("root", originalOrcSchema);
return buildOrcProjection(Integer.MIN_VALUE, schema.asStruct(), true, icebergToOrc);
}
private static TypeDescription buildOrcProjection(Integer fieldId, Type type, boolean isRequired,
Map<Integer, OrcField> mapping) {
final TypeDescription orcType;
switch (type.typeId()) {
case STRUCT:
orcType = TypeDescription.createStruct();
for (Types.NestedField nestedField : type.asStructType().fields()) {
// Using suffix _r to avoid potential underlying issues in ORC reader
// with reused column names between ORC and Iceberg;
// e.g. renaming column c -> d and adding new column d
String name = Optional.ofNullable(mapping.get(nestedField.fieldId()))
.map(OrcField::name)
.orElseGet(() -> nestedField.name() + "_r" + nestedField.fieldId());
TypeDescription childType = buildOrcProjection(nestedField.fieldId(), nestedField.type(),
isRequired && nestedField.isRequired(), mapping);
orcType.addField(name, childType);
}
break;
case LIST:
Types.ListType list = (Types.ListType) type;
TypeDescription elementType = buildOrcProjection(list.elementId(), list.elementType(),
isRequired && list.isElementRequired(), mapping);
orcType = TypeDescription.createList(elementType);
break;
case MAP:
Types.MapType map = (Types.MapType) type;
TypeDescription keyType = buildOrcProjection(map.keyId(), map.keyType(), isRequired, mapping);
TypeDescription valueType = buildOrcProjection(map.valueId(), map.valueType(),
isRequired && map.isValueRequired(), mapping);
orcType = TypeDescription.createMap(keyType, valueType);
break;
default:
if (mapping.containsKey(fieldId)) {
TypeDescription originalType = mapping.get(fieldId).type();
Optional<TypeDescription> promotedType = getPromotedType(type, originalType);
if (promotedType.isPresent()) {
orcType = promotedType.get();
} else {
Preconditions.checkArgument(isSameType(originalType, type),
"Can not promote %s type to %s",
originalType.getCategory(), type.typeId().name());
orcType = originalType.clone();
}
} else {
if (isRequired) {
throw new IllegalArgumentException(
String.format("Field %d of type %s is required and was not found.", fieldId, type.toString()));
}
orcType = convert(fieldId, type, false);
}
}
orcType.setAttribute(ICEBERG_ID_ATTRIBUTE, fieldId.toString());
return orcType;
}
private static Map<Integer, OrcField> icebergToOrcMapping(String name, TypeDescription orcType) {
Map<Integer, OrcField> icebergToOrc = Maps.newHashMap();
switch (orcType.getCategory()) {
case STRUCT:
List<String> childrenNames = orcType.getFieldNames();
List<TypeDescription> children = orcType.getChildren();
for (int i = 0; i < children.size(); i++) {
icebergToOrc.putAll(icebergToOrcMapping(childrenNames.get(i), children.get(i)));
}
break;
case LIST:
icebergToOrc.putAll(icebergToOrcMapping("element", orcType.getChildren().get(0)));
break;
case MAP:
icebergToOrc.putAll(icebergToOrcMapping("key", orcType.getChildren().get(0)));
icebergToOrc.putAll(icebergToOrcMapping("value", orcType.getChildren().get(1)));
break;
}
if (orcType.getId() > 0) {
// Only add to non-root types.
icebergID(orcType)
.ifPresent(integer -> icebergToOrc.put(integer, new OrcField(name, orcType)));
}
return icebergToOrc;
}
private static Optional<TypeDescription> getPromotedType(Type icebergType,
TypeDescription originalOrcType) {
TypeDescription promotedOrcType = null;
if (Type.TypeID.LONG.equals(icebergType.typeId()) &&
TypeDescription.Category.INT.equals(originalOrcType.getCategory())) {
// Promote: int to long
promotedOrcType = TypeDescription.createLong();
} else if (Type.TypeID.DOUBLE.equals(icebergType.typeId()) &&
TypeDescription.Category.FLOAT.equals(originalOrcType.getCategory())) {
// Promote: float to double
promotedOrcType = TypeDescription.createDouble();
} else if (Type.TypeID.DECIMAL.equals(icebergType.typeId()) &&
TypeDescription.Category.DECIMAL.equals(originalOrcType.getCategory())) {
// Promote: decimal(P, S) to decimal(P', S) if P' > P
Types.DecimalType newDecimal = (Types.DecimalType) icebergType;
if (newDecimal.scale() == originalOrcType.getScale() &&
newDecimal.precision() > originalOrcType.getPrecision()) {
promotedOrcType = TypeDescription.createDecimal()
.withScale(newDecimal.scale())
.withPrecision(newDecimal.precision());
}
}
return Optional.ofNullable(promotedOrcType);
}
private static boolean isSameType(TypeDescription orcType, Type icebergType) {
if (icebergType.typeId() == Type.TypeID.TIMESTAMP) {
Types.TimestampType tsType = (Types.TimestampType) icebergType;
return Objects.equals(
tsType.shouldAdjustToUTC() ? TypeDescription.Category.TIMESTAMP_INSTANT : TypeDescription.Category.TIMESTAMP,
orcType.getCategory());
} else {
return TYPE_MAPPING.containsEntry(icebergType.typeId(), orcType.getCategory());
}
}
static Optional<Integer> icebergID(TypeDescription orcType) {
return Optional.ofNullable(orcType.getAttributeValue(ICEBERG_ID_ATTRIBUTE))
.map(Integer::parseInt);
}
static int fieldId(TypeDescription orcType) {
String idStr = orcType.getAttributeValue(ICEBERG_ID_ATTRIBUTE);
Preconditions.checkNotNull(idStr, "Missing expected '%s' property", ICEBERG_ID_ATTRIBUTE);
return Integer.parseInt(idStr);
}
static boolean isOptional(TypeDescription orcType) {
String isRequiredStr = orcType.getAttributeValue(ICEBERG_REQUIRED_ATTRIBUTE);
if (isRequiredStr != null) {
return !Boolean.parseBoolean(isRequiredStr);
}
return true;
}
static TypeDescription removeIds(TypeDescription type) {
return OrcSchemaVisitor.visit(type, new RemoveIds());
}
static boolean hasIds(TypeDescription orcSchema) {
return OrcSchemaVisitor.visit(orcSchema, new HasIds());
}
static TypeDescription applyNameMapping(TypeDescription orcSchema, NameMapping nameMapping) {
return OrcSchemaVisitor.visit(orcSchema, new ApplyNameMapping(nameMapping));
}
/**
* Generates mapping from field IDs to ORC qualified names. See {@link IdToOrcName} for details.
*/
public static Map<Integer, String> idToOrcName(Schema schema) {
return TypeUtil.visit(schema, new IdToOrcName());
}
}
| 1 | 28,183 | Can we avoid making this public with the other updates? | apache-iceberg | java |
@@ -165,8 +165,8 @@ void DataTransformer<Dtype>::Transform(const vector<Datum> & datum_vector,
const int width = transformed_blob->width();
CHECK_GT(datum_num, 0) << "There is no datum to add";
- CHECK_LE(datum_num, num) <<
- "The size of datum_vector must be smaller than transformed_blob->num()";
+ CHECK_EQ(datum_num, num) <<
+ "The size of datum_vector must be equals to transformed_blob->num()";
Blob<Dtype> uni_blob(1, channels, height, width);
for (int item_id = 0; item_id < datum_num; ++item_id) {
int offset = transformed_blob->offset(item_id); | 1 | #ifndef OSX
#include <opencv2/core/core.hpp>
#endif
#include <string>
#include <vector>
#include "caffe/data_transformer.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/rng.hpp"
namespace caffe {
template<typename Dtype>
DataTransformer<Dtype>::DataTransformer(const TransformationParameter& param)
: param_(param) {
phase_ = Caffe::phase();
// check if we want to use mean_file
if (param_.has_mean_file()) {
CHECK_EQ(param_.mean_value_size(), 0) <<
"Cannot specify mean_file and mean_value at the same time";
const string& mean_file = param.mean_file();
LOG(INFO) << "Loading mean file from" << mean_file;
BlobProto blob_proto;
ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);
data_mean_.FromProto(blob_proto);
}
// check if we want to use mean_value
if (param_.mean_value_size() > 0) {
CHECK(param_.has_mean_file() == false) <<
"Cannot specify mean_file and mean_value at the same time";
for (int c = 0; c < param_.mean_value_size(); ++c) {
mean_values_.push_back(param_.mean_value(c));
}
}
}
template<typename Dtype>
void DataTransformer<Dtype>::Transform(const Datum& datum,
Dtype* transformed_data) {
const string& data = datum.data();
const int datum_channels = datum.channels();
const int datum_height = datum.height();
const int datum_width = datum.width();
const int crop_size = param_.crop_size();
const Dtype scale = param_.scale();
const bool do_mirror = param_.mirror() && Rand(2);
const bool has_mean_file = param_.has_mean_file();
const bool has_uint8 = data.size() > 0;
const bool has_mean_values = mean_values_.size() > 0;
CHECK_GT(datum_channels, 0);
CHECK_GE(datum_height, crop_size);
CHECK_GE(datum_width, crop_size);
Dtype* mean = NULL;
if (has_mean_file) {
CHECK_EQ(datum_channels, data_mean_.channels());
CHECK_EQ(datum_height, data_mean_.height());
CHECK_EQ(datum_width, data_mean_.width());
mean = data_mean_.mutable_cpu_data();
}
if (has_mean_values) {
CHECK(mean_values_.size() == 1 || mean_values_.size() == datum_channels) <<
"Specify either 1 mean_value or as many as channels: " << datum_channels;
if (datum_channels > 1 && mean_values_.size() == 1) {
// Replicate the mean_value for simplicity
for (int c = 1; c < datum_channels; ++c) {
mean_values_.push_back(mean_values_[0]);
}
}
}
int height = datum_height;
int width = datum_width;
int h_off = 0;
int w_off = 0;
if (crop_size) {
height = crop_size;
width = crop_size;
// We only do random crop when we do training.
if (phase_ == Caffe::TRAIN) {
h_off = Rand(datum_height - crop_size + 1);
w_off = Rand(datum_width - crop_size + 1);
} else {
h_off = (datum_height - crop_size) / 2;
w_off = (datum_width - crop_size) / 2;
}
}
Dtype datum_element;
int top_index, data_index;
for (int c = 0; c < datum_channels; ++c) {
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width; ++w) {
data_index = (c * datum_height + h_off + h) * datum_width + w_off + w;
if (do_mirror) {
top_index = (c * height + h) * width + (width - 1 - w);
} else {
top_index = (c * height + h) * width + w;
}
if (has_uint8) {
datum_element =
static_cast<Dtype>(static_cast<uint8_t>(data[data_index]));
} else {
datum_element = datum.float_data(data_index);
}
if (has_mean_file) {
transformed_data[top_index] =
(datum_element - mean[data_index]) * scale;
} else {
if (has_mean_values) {
transformed_data[top_index] =
(datum_element - mean_values_[c]) * scale;
} else {
transformed_data[top_index] = datum_element * scale;
}
}
}
}
}
}
template<typename Dtype>
void DataTransformer<Dtype>::Transform(const Datum& datum,
Blob<Dtype>* transformed_blob) {
const int datum_channels = datum.channels();
const int datum_height = datum.height();
const int datum_width = datum.width();
const int channels = transformed_blob->channels();
const int height = transformed_blob->height();
const int width = transformed_blob->width();
const int num = transformed_blob->num();
CHECK_EQ(channels, datum_channels);
CHECK_LE(height, datum_height);
CHECK_LE(width, datum_width);
CHECK_GE(num, 1);
const int crop_size = param_.crop_size();
if (crop_size) {
CHECK_EQ(crop_size, height);
CHECK_EQ(crop_size, width);
} else {
CHECK_EQ(datum_height, height);
CHECK_EQ(datum_width, width);
}
Dtype* transformed_data = transformed_blob->mutable_cpu_data();
Transform(datum, transformed_data);
}
template<typename Dtype>
void DataTransformer<Dtype>::Transform(const vector<Datum> & datum_vector,
Blob<Dtype>* transformed_blob) {
const int datum_num = datum_vector.size();
const int num = transformed_blob->num();
const int channels = transformed_blob->channels();
const int height = transformed_blob->height();
const int width = transformed_blob->width();
CHECK_GT(datum_num, 0) << "There is no datum to add";
CHECK_LE(datum_num, num) <<
"The size of datum_vector must be smaller than transformed_blob->num()";
Blob<Dtype> uni_blob(1, channels, height, width);
for (int item_id = 0; item_id < datum_num; ++item_id) {
int offset = transformed_blob->offset(item_id);
uni_blob.set_cpu_data(transformed_blob->mutable_cpu_data() + offset);
Transform(datum_vector[item_id], &uni_blob);
}
}
#ifndef OSX
template<typename Dtype>
void DataTransformer<Dtype>::Transform(const cv::Mat& cv_img,
Blob<Dtype>* transformed_blob) {
const int img_channels = cv_img.channels();
const int img_height = cv_img.rows;
const int img_width = cv_img.cols;
const int channels = transformed_blob->channels();
const int height = transformed_blob->height();
const int width = transformed_blob->width();
const int num = transformed_blob->num();
CHECK_EQ(channels, img_channels);
CHECK_LE(height, img_height);
CHECK_LE(width, img_width);
CHECK_GE(num, 1);
CHECK(cv_img.depth() == CV_8U) << "Image data type must be unsigned byte";
const int crop_size = param_.crop_size();
const Dtype scale = param_.scale();
const bool do_mirror = param_.mirror() && Rand(2);
const bool has_mean_file = param_.has_mean_file();
const bool has_mean_values = mean_values_.size() > 0;
CHECK_GT(img_channels, 0);
CHECK_GE(img_height, crop_size);
CHECK_GE(img_width, crop_size);
Dtype* mean = NULL;
if (has_mean_file) {
CHECK_EQ(img_channels, data_mean_.channels());
CHECK_EQ(img_height, data_mean_.height());
CHECK_EQ(img_width, data_mean_.width());
mean = data_mean_.mutable_cpu_data();
}
if (has_mean_values) {
CHECK(mean_values_.size() == 1 || mean_values_.size() == img_channels) <<
"Specify either 1 mean_value or as many as channels: " << img_channels;
if (img_channels > 1 && mean_values_.size() == 1) {
// Replicate the mean_value for simplicity
for (int c = 1; c < img_channels; ++c) {
mean_values_.push_back(mean_values_[0]);
}
}
}
int h_off = 0;
int w_off = 0;
cv::Mat cv_cropped_img = cv_img;
if (crop_size) {
CHECK_EQ(crop_size, height);
CHECK_EQ(crop_size, width);
// We only do random crop when we do training.
if (phase_ == Caffe::TRAIN) {
h_off = Rand(img_height - crop_size + 1);
w_off = Rand(img_width - crop_size + 1);
} else {
h_off = (img_height - crop_size) / 2;
w_off = (img_width - crop_size) / 2;
}
cv::Rect roi(w_off, h_off, crop_size, crop_size);
cv_cropped_img = cv_img(roi);
} else {
CHECK_EQ(img_height, height);
CHECK_EQ(img_width, width);
}
CHECK(cv_cropped_img.data);
Dtype* transformed_data = transformed_blob->mutable_cpu_data();
int top_index;
for (int h = 0; h < height; ++h) {
const uchar* ptr = cv_cropped_img.ptr<uchar>(h);
int img_index = 0;
for (int w = 0; w < width; ++w) {
for (int c = 0; c < img_channels; ++c) {
if (do_mirror) {
top_index = (c * height + h) * width + (width - 1 - w);
} else {
top_index = (c * height + h) * width + w;
}
// int top_index = (c * height + h) * width + w;
Dtype pixel = static_cast<Dtype>(ptr[img_index++]);
if (has_mean_file) {
int mean_index = (c * img_height + h_off + h) * img_width + w_off + w;
transformed_data[top_index] =
(pixel - mean[mean_index]) * scale;
} else {
if (has_mean_values) {
transformed_data[top_index] =
(pixel - mean_values_[c]) * scale;
} else {
transformed_data[top_index] = pixel * scale;
}
}
}
}
}
}
#endif
template<typename Dtype>
void DataTransformer<Dtype>::Transform(Blob<Dtype>* input_blob,
Blob<Dtype>* transformed_blob) {
const int input_num = input_blob->num();
const int input_channels = input_blob->channels();
const int input_height = input_blob->height();
const int input_width = input_blob->width();
const int num = transformed_blob->num();
const int channels = transformed_blob->channels();
const int height = transformed_blob->height();
const int width = transformed_blob->width();
const int size = transformed_blob->count();
CHECK_LE(input_num, num);
CHECK_EQ(input_channels, channels);
CHECK_GE(input_height, height);
CHECK_GE(input_width, width);
const int crop_size = param_.crop_size();
const Dtype scale = param_.scale();
const bool do_mirror = param_.mirror() && Rand(2);
const bool has_mean_file = param_.has_mean_file();
const bool has_mean_values = mean_values_.size() > 0;
int h_off = 0;
int w_off = 0;
if (crop_size) {
CHECK_EQ(crop_size, height);
CHECK_EQ(crop_size, width);
// We only do random crop when we do training.
if (phase_ == Caffe::TRAIN) {
h_off = Rand(input_height - crop_size + 1);
w_off = Rand(input_width - crop_size + 1);
} else {
h_off = (input_height - crop_size) / 2;
w_off = (input_width - crop_size) / 2;
}
} else {
CHECK_EQ(input_height, height);
CHECK_EQ(input_width, width);
}
Dtype* input_data = input_blob->mutable_cpu_data();
if (has_mean_file) {
CHECK_EQ(input_channels, data_mean_.channels());
CHECK_EQ(input_height, data_mean_.height());
CHECK_EQ(input_width, data_mean_.width());
for (int n = 0; n < input_num; ++n) {
int offset = input_blob->offset(n);
caffe_sub(data_mean_.count(), input_data + offset,
data_mean_.cpu_data(), input_data + offset);
}
}
if (has_mean_values) {
CHECK(mean_values_.size() == 1 || mean_values_.size() == input_channels) <<
"Specify either 1 mean_value or as many as channels: " << input_channels;
if (mean_values_.size() == 1) {
caffe_add_scalar(input_blob->count(), -(mean_values_[0]), input_data);
} else {
for (int n = 0; n < input_num; ++n) {
for (int c = 0; c < input_channels; ++c) {
int offset = input_blob->offset(n, c);
caffe_add_scalar(input_height * input_width, -(mean_values_[c]),
input_data + offset);
}
}
}
}
Dtype* transformed_data = transformed_blob->mutable_cpu_data();
for (int n = 0; n < input_num; ++n) {
int top_index_n = n * channels;
int data_index_n = n * channels;
for (int c = 0; c < channels; ++c) {
int top_index_c = (top_index_n + c) * height;
int data_index_c = (data_index_n + c) * input_height + h_off;
for (int h = 0; h < height; ++h) {
int top_index_h = (top_index_c + h) * width;
int data_index_h = (data_index_c + h) * input_width + w_off;
if (do_mirror) {
int top_index_w = top_index_h + width - 1;
for (int w = 0; w < width; ++w) {
transformed_data[top_index_w-w] = input_data[data_index_h + w];
}
} else {
for (int w = 0; w < width; ++w) {
transformed_data[top_index_h + w] = input_data[data_index_h + w];
}
}
}
}
}
if (scale != Dtype(1)) {
DLOG(INFO) << "Scale: " << scale;
caffe_scal(size, scale, transformed_data);
}
}
template <typename Dtype>
void DataTransformer<Dtype>::InitRand() {
const bool needs_rand = param_.mirror() ||
(phase_ == Caffe::TRAIN && param_.crop_size());
if (needs_rand) {
const unsigned int rng_seed = caffe_rng_rand();
rng_.reset(new Caffe::RNG(rng_seed));
} else {
rng_.reset();
}
}
template <typename Dtype>
int DataTransformer<Dtype>::Rand(int n) {
CHECK(rng_);
CHECK_GT(n, 0);
caffe::rng_t* rng =
static_cast<caffe::rng_t*>(rng_->generator());
return ((*rng)() % n);
}
INSTANTIATE_CLASS(DataTransformer);
} // namespace caffe
| 1 | 31,164 | Why did you change this equal instead of less or equal? | BVLC-caffe | cpp |
@@ -30,11 +30,11 @@ import org.apache.tuweni.units.bigints.UInt256;
public interface WorldStateArchive {
Hash EMPTY_ROOT_HASH = Hash.wrap(MerklePatriciaTrie.EMPTY_TRIE_NODE_HASH);
- Optional<WorldState> get(final Hash rootHash);
+ Optional<WorldState> get(final Hash rootHash, Hash blockHash);
- boolean isWorldStateAvailable(final Hash rootHash);
+ boolean isWorldStateAvailable(final Hash rootHash, Hash blockHash);
- Optional<MutableWorldState> getMutable(final Hash rootHash);
+ Optional<MutableWorldState> getMutable(final Hash rootHash, Hash blockHash);
MutableWorldState getMutable();
| 1 | /*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.worldstate;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.MutableWorldState;
import org.hyperledger.besu.ethereum.core.WorldState;
import org.hyperledger.besu.ethereum.proof.WorldStateProof;
import org.hyperledger.besu.ethereum.trie.MerklePatriciaTrie;
import java.util.List;
import java.util.Optional;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
public interface WorldStateArchive {
Hash EMPTY_ROOT_HASH = Hash.wrap(MerklePatriciaTrie.EMPTY_TRIE_NODE_HASH);
Optional<WorldState> get(final Hash rootHash);
boolean isWorldStateAvailable(final Hash rootHash);
Optional<MutableWorldState> getMutable(final Hash rootHash);
MutableWorldState getMutable();
Optional<Bytes> getNodeData(final Hash hash);
Optional<WorldStateProof> getAccountProof(
final Hash worldStateRoot,
final Address accountAddress,
final List<UInt256> accountStorageKeys);
}
| 1 | 24,186 | missing final for the blockHash field | hyperledger-besu | java |
@@ -1,5 +1,5 @@
-require 'factory_girl_rails'
+require 'factory_bot_rails'
RSpec.configure do |config|
- config.include FactoryGirl::Syntax::Methods
-end
+ config.include FactoryBot::Syntax::Methods
+end | 1 | require 'factory_girl_rails'
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end | 1 | 18,445 | Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping. | thoughtbot-upcase | rb |
@@ -126,5 +126,8 @@ class L2Norm(nn.Module):
self.scale = scale
def forward(self, x):
- norm = x.pow(2).sum(1, keepdim=True).sqrt() + self.eps
- return self.weight[None, :, None, None].expand_as(x) * x / norm
+ # normalization layer convert to FP32
+ float_x = x.float()
+ norm = float_x.pow(2).sum(1, keepdim=True).sqrt() + self.eps
+ return (self.weight[None, :, None, None].float().expand_as(float_x) *
+ float_x / norm).type_as(x) | 1 | import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import (VGG, xavier_init, constant_init, kaiming_init,
normal_init)
from mmcv.runner import load_checkpoint
from ..registry import BACKBONES
@BACKBONES.register_module
class SSDVGG(VGG):
extra_setting = {
300: (256, 'S', 512, 128, 'S', 256, 128, 256, 128, 256),
512: (256, 'S', 512, 128, 'S', 256, 128, 'S', 256, 128, 'S', 256, 128),
}
def __init__(self,
input_size,
depth,
with_last_pool=False,
ceil_mode=True,
out_indices=(3, 4),
out_feature_indices=(22, 34),
l2_norm_scale=20.):
super(SSDVGG, self).__init__(
depth,
with_last_pool=with_last_pool,
ceil_mode=ceil_mode,
out_indices=out_indices)
assert input_size in (300, 512)
self.input_size = input_size
self.features.add_module(
str(len(self.features)),
nn.MaxPool2d(kernel_size=3, stride=1, padding=1))
self.features.add_module(
str(len(self.features)),
nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6))
self.features.add_module(
str(len(self.features)), nn.ReLU(inplace=True))
self.features.add_module(
str(len(self.features)), nn.Conv2d(1024, 1024, kernel_size=1))
self.features.add_module(
str(len(self.features)), nn.ReLU(inplace=True))
self.out_feature_indices = out_feature_indices
self.inplanes = 1024
self.extra = self._make_extra_layers(self.extra_setting[input_size])
self.l2_norm = L2Norm(
self.features[out_feature_indices[0] - 1].out_channels,
l2_norm_scale)
def init_weights(self, pretrained=None):
if isinstance(pretrained, str):
logger = logging.getLogger()
load_checkpoint(self, pretrained, strict=False, logger=logger)
elif pretrained is None:
for m in self.features.modules():
if isinstance(m, nn.Conv2d):
kaiming_init(m)
elif isinstance(m, nn.BatchNorm2d):
constant_init(m, 1)
elif isinstance(m, nn.Linear):
normal_init(m, std=0.01)
else:
raise TypeError('pretrained must be a str or None')
for m in self.extra.modules():
if isinstance(m, nn.Conv2d):
xavier_init(m, distribution='uniform')
constant_init(self.l2_norm, self.l2_norm.scale)
def forward(self, x):
outs = []
for i, layer in enumerate(self.features):
x = layer(x)
if i in self.out_feature_indices:
outs.append(x)
for i, layer in enumerate(self.extra):
x = F.relu(layer(x), inplace=True)
if i % 2 == 1:
outs.append(x)
outs[0] = self.l2_norm(outs[0])
if len(outs) == 1:
return outs[0]
else:
return tuple(outs)
def _make_extra_layers(self, outplanes):
layers = []
kernel_sizes = (1, 3)
num_layers = 0
outplane = None
for i in range(len(outplanes)):
if self.inplanes == 'S':
self.inplanes = outplane
continue
k = kernel_sizes[num_layers % 2]
if outplanes[i] == 'S':
outplane = outplanes[i + 1]
conv = nn.Conv2d(
self.inplanes, outplane, k, stride=2, padding=1)
else:
outplane = outplanes[i]
conv = nn.Conv2d(
self.inplanes, outplane, k, stride=1, padding=0)
layers.append(conv)
self.inplanes = outplanes[i]
num_layers += 1
if self.input_size == 512:
layers.append(nn.Conv2d(self.inplanes, 256, 4, padding=1))
return nn.Sequential(*layers)
class L2Norm(nn.Module):
def __init__(self, n_dims, scale=20., eps=1e-10):
super(L2Norm, self).__init__()
self.n_dims = n_dims
self.weight = nn.Parameter(torch.Tensor(self.n_dims))
self.eps = eps
self.scale = scale
def forward(self, x):
norm = x.pow(2).sum(1, keepdim=True).sqrt() + self.eps
return self.weight[None, :, None, None].expand_as(x) * x / norm
| 1 | 17,204 | `x_float` instead of `float_x`. | open-mmlab-mmdetection | py |
@@ -5,6 +5,9 @@ import dialogHelper from '../../components/dialogHelper/dialogHelper';
import keyboardnavigation from '../../scripts/keyboardNavigation';
import { appRouter } from '../../components/appRouter';
import ServerConnections from '../../components/ServerConnections';
+// eslint-disable-next-line import/named, import/namespace
+import { Swiper } from 'swiper/swiper-bundle.esm';
+import 'swiper/swiper-bundle.css';
export class ComicsPlayer {
constructor() { | 1 | // eslint-disable-next-line import/named, import/namespace
import { Archive } from 'libarchive.js';
import loading from '../../components/loading/loading';
import dialogHelper from '../../components/dialogHelper/dialogHelper';
import keyboardnavigation from '../../scripts/keyboardNavigation';
import { appRouter } from '../../components/appRouter';
import ServerConnections from '../../components/ServerConnections';
export class ComicsPlayer {
constructor() {
this.name = 'Comics Player';
this.type = 'mediaplayer';
this.id = 'comicsplayer';
this.priority = 1;
this.imageMap = new Map();
this.onDialogClosed = this.onDialogClosed.bind(this);
this.onWindowKeyUp = this.onWindowKeyUp.bind(this);
}
play(options) {
this.progress = 0;
const elem = this.createMediaElement();
return this.setCurrentSrc(elem, options);
}
stop() {
this.unbindEvents();
const elem = this.mediaElement;
if (elem) {
dialogHelper.close(elem);
this.mediaElement = null;
}
loading.hide();
}
onDialogClosed() {
this.stop();
}
onWindowKeyUp(e) {
const key = keyboardnavigation.getKeyName(e);
switch (key) {
case 'Escape':
this.stop();
break;
}
}
bindEvents() {
document.addEventListener('keyup', this.onWindowKeyUp);
}
unbindEvents() {
document.removeEventListener('keyup', this.onWindowKeyUp);
}
createMediaElement() {
let elem = this.mediaElement;
if (elem) {
return elem;
}
elem = document.getElementById('comicsPlayer');
if (!elem) {
elem = dialogHelper.createDialog({
exitAnimationDuration: 400,
size: 'fullscreen',
autoFocus: false,
scrollY: false,
exitAnimation: 'fadeout',
removeOnClose: true
});
elem.id = 'comicsPlayer';
elem.classList.add('slideshowDialog');
elem.innerHTML = '<div class="slideshowSwiperContainer"><div class="swiper-wrapper"></div></div>';
this.bindEvents();
dialogHelper.open(elem);
}
this.mediaElement = elem;
return elem;
}
setCurrentSrc(elem, options) {
const item = options.items[0];
this.currentItem = item;
loading.show();
const serverId = item.ServerId;
const apiClient = ServerConnections.getApiClient(serverId);
Archive.init({
workerUrl: appRouter.baseUrl() + '/libraries/worker-bundle.js'
});
return new Promise((resolve, reject) => {
const downloadUrl = apiClient.getItemDownloadUrl(item.Id);
const archiveSource = new ArchiveSource(downloadUrl);
const instance = this;
import('swiper').then(({default: Swiper}) => {
archiveSource.load().then(() => {
loading.hide();
this.swiperInstance = new Swiper(elem.querySelector('.slideshowSwiperContainer'), {
direction: 'horizontal',
// loop is disabled due to the lack of support in virtual slides
loop: false,
zoom: {
minRatio: 1,
toggle: true,
containerClass: 'slider-zoom-container'
},
autoplay: false,
keyboard: {
enabled: true
},
preloadImages: true,
slidesPerView: 1,
slidesPerColumn: 1,
initialSlide: 0,
// reduces memory consumption for large libraries while allowing preloading of images
virtual: {
slides: archiveSource.urls,
cache: true,
renderSlide: instance.getImgFromUrl,
addSlidesBefore: 1,
addSlidesAfter: 1
}
});
});
});
});
}
getImgFromUrl(url) {
return `<div class="swiper-slide">
<div class="slider-zoom-container">
<img src="${url}" class="swiper-slide-img">
</div>
</div>`;
}
canPlayMediaType(mediaType) {
return (mediaType || '').toLowerCase() === 'book';
}
canPlayItem(item) {
if (item.Path && (item.Path.endsWith('cbz') || item.Path.endsWith('cbr'))) {
return true;
}
return false;
}
}
class ArchiveSource {
constructor(url) {
this.url = url;
this.files = [];
this.urls = [];
this.loadPromise = this.load();
this.itemsLoaded = 0;
}
async load() {
const res = await fetch(this.url);
if (!res.ok) {
return;
}
const blob = await res.blob();
this.archive = await Archive.open(blob);
this.raw = await this.archive.getFilesArray();
this.numberOfFiles = this.raw.length;
await this.archive.extractFiles();
const files = await this.archive.getFilesArray();
files.sort((a, b) => {
if (a.file.name < b.file.name) {
return -1;
} else {
return 1;
}
});
for (const file of files) {
/* eslint-disable-next-line compat/compat */
const url = URL.createObjectURL(file.file);
this.urls.push(url);
}
}
getLength() {
return this.raw.length;
}
async item(index) {
if (this.urls[index]) {
return this.urls[index];
}
await this.loadPromise;
return this.urls[index];
}
}
export default ComicsPlayer;
| 1 | 18,288 | Is this for `No Babel config ...` from ESLint? If so, it will be fixed in my ES6 PR. | jellyfin-jellyfin-web | js |
@@ -145,12 +145,15 @@ func TestFuncHookRun(t *testing.T) {
fHook := configs.NewFunctionHook(func(s *specs.State) error {
if !reflect.DeepEqual(state, s) {
- t.Errorf("Expected state %+v to equal %+v", state, s)
+ return fmt.Errorf("expected state %+v to equal %+v", state, s)
}
return nil
})
- fHook.Run(state)
+ err := fHook.Run(state)
+ if err != nil {
+ t.Fatal(err)
+ }
}
func TestCommandHookRun(t *testing.T) { | 1 | package configs_test
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"reflect"
"testing"
"time"
"github.com/opencontainers/runc/libcontainer/configs"
"github.com/opencontainers/runtime-spec/specs-go"
)
func TestUnmarshalHooks(t *testing.T) {
timeout := time.Second
hookCmd := configs.NewCommandHook(configs.Command{
Path: "/var/vcap/hooks/hook",
Args: []string{"--pid=123"},
Env: []string{"FOO=BAR"},
Dir: "/var/vcap",
Timeout: &timeout,
})
hookJson, err := json.Marshal(hookCmd)
if err != nil {
t.Fatal(err)
}
for _, hookName := range configs.HookNameList {
hooks := configs.Hooks{}
err = hooks.UnmarshalJSON([]byte(fmt.Sprintf(`{"%s" :[%s]}`, hookName, hookJson)))
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(hooks[hookName], configs.HookList{hookCmd}) {
t.Errorf("Expected %s to equal %+v but it was %+v", hookName, hookCmd, hooks[hookName])
}
}
}
func TestUnmarshalHooksWithInvalidData(t *testing.T) {
hook := configs.Hooks{}
err := hook.UnmarshalJSON([]byte(`{invalid-json}`))
if err == nil {
t.Error("Expected error to occur but it was nil")
}
}
func TestMarshalHooks(t *testing.T) {
timeout := time.Second
hookCmd := configs.NewCommandHook(configs.Command{
Path: "/var/vcap/hooks/hook",
Args: []string{"--pid=123"},
Env: []string{"FOO=BAR"},
Dir: "/var/vcap",
Timeout: &timeout,
})
hook := configs.Hooks{
configs.Prestart: configs.HookList{hookCmd},
configs.CreateRuntime: configs.HookList{hookCmd},
configs.CreateContainer: configs.HookList{hookCmd},
configs.StartContainer: configs.HookList{hookCmd},
configs.Poststart: configs.HookList{hookCmd},
configs.Poststop: configs.HookList{hookCmd},
}
hooks, err := hook.MarshalJSON()
if err != nil {
t.Fatal(err)
}
// Note Marshal seems to output fields in alphabetical order
hookCmdJson := `[{"path":"/var/vcap/hooks/hook","args":["--pid=123"],"env":["FOO=BAR"],"dir":"/var/vcap","timeout":1000000000}]`
h := fmt.Sprintf(`{"createContainer":%[1]s,"createRuntime":%[1]s,"poststart":%[1]s,"poststop":%[1]s,"prestart":%[1]s,"startContainer":%[1]s}`, hookCmdJson)
if string(hooks) != h {
t.Errorf("Expected hooks %s to equal %s", string(hooks), h)
}
}
func TestMarshalUnmarshalHooks(t *testing.T) {
timeout := time.Second
hookCmd := configs.NewCommandHook(configs.Command{
Path: "/var/vcap/hooks/hook",
Args: []string{"--pid=123"},
Env: []string{"FOO=BAR"},
Dir: "/var/vcap",
Timeout: &timeout,
})
hook := configs.Hooks{
configs.Prestart: configs.HookList{hookCmd},
configs.CreateRuntime: configs.HookList{hookCmd},
configs.CreateContainer: configs.HookList{hookCmd},
configs.StartContainer: configs.HookList{hookCmd},
configs.Poststart: configs.HookList{hookCmd},
configs.Poststop: configs.HookList{hookCmd},
}
hooks, err := hook.MarshalJSON()
if err != nil {
t.Fatal(err)
}
umMhook := configs.Hooks{}
err = umMhook.UnmarshalJSON(hooks)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(umMhook, hook) {
t.Errorf("Expected hooks to be equal after mashaling -> unmarshaling them: %+v, %+v", umMhook, hook)
}
}
func TestMarshalHooksWithUnexpectedType(t *testing.T) {
fHook := configs.NewFunctionHook(func(*specs.State) error {
return nil
})
hook := configs.Hooks{
configs.CreateRuntime: configs.HookList{fHook},
}
hooks, err := hook.MarshalJSON()
if err != nil {
t.Fatal(err)
}
h := `{"createContainer":null,"createRuntime":null,"poststart":null,"poststop":null,"prestart":null,"startContainer":null}`
if string(hooks) != h {
t.Errorf("Expected hooks %s to equal %s", string(hooks), h)
}
}
func TestFuncHookRun(t *testing.T) {
state := &specs.State{
Version: "1",
ID: "1",
Status: "created",
Pid: 1,
Bundle: "/bundle",
}
fHook := configs.NewFunctionHook(func(s *specs.State) error {
if !reflect.DeepEqual(state, s) {
t.Errorf("Expected state %+v to equal %+v", state, s)
}
return nil
})
fHook.Run(state)
}
func TestCommandHookRun(t *testing.T) {
state := &specs.State{
Version: "1",
ID: "1",
Status: "created",
Pid: 1,
Bundle: "/bundle",
}
stateJson, err := json.Marshal(state)
if err != nil {
t.Fatal(err)
}
verifyCommandTemplate := `#!/bin/sh
if [ "$1" != "testarg" ]; then
echo "Bad value for $1. Expected 'testarg', found '$1'"
exit 1
fi
if [ -z "$FOO" ] || [ "$FOO" != BAR ]; then
echo "Bad value for FOO. Expected 'BAR', found '$FOO'"
exit 1
fi
expectedJson=%q
read JSON
if [ "$JSON" != "$expectedJson" ]; then
echo "Bad JSON received. Expected '$expectedJson', found '$JSON'"
exit 1
fi
exit 0
`
verifyCommand := fmt.Sprintf(verifyCommandTemplate, stateJson)
filename := "/tmp/runc-hooktest.sh"
os.Remove(filename)
if err := ioutil.WriteFile(filename, []byte(verifyCommand), 0700); err != nil {
t.Fatalf("Failed to create tmp file: %v", err)
}
defer os.Remove(filename)
cmdHook := configs.NewCommandHook(configs.Command{
Path: filename,
Args: []string{filename, "testarg"},
Env: []string{"FOO=BAR"},
Dir: "/",
})
if err := cmdHook.Run(state); err != nil {
t.Errorf(fmt.Sprintf("Expected error to not occur but it was %+v", err))
}
}
func TestCommandHookRunTimeout(t *testing.T) {
state := &specs.State{
Version: "1",
ID: "1",
Status: "created",
Pid: 1,
Bundle: "/bundle",
}
timeout := 100 * time.Millisecond
cmdHook := configs.NewCommandHook(configs.Command{
Path: "/bin/sleep",
Args: []string{"/bin/sleep", "1"},
Timeout: &timeout,
})
if err := cmdHook.Run(state); err == nil {
t.Error("Expected error to occur but it was nil")
}
}
| 1 | 22,370 | Not important, but the code used to keep checking other cases even after one of them failed, and now it's not. Fine either way for me, just noticing. | opencontainers-runc | go |
@@ -41,6 +41,7 @@ import (
"github.com/aws/amazon-ecs-agent/agent/utils/ttime"
"github.com/cihub/seelog"
+ "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/volume"
docker "github.com/fsouza/go-dockerclient"
) | 1 | // Copyright 2014-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package dockerapi
import (
"archive/tar"
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"strings"
"sync"
"time"
apicontainer "github.com/aws/amazon-ecs-agent/agent/api/container"
apicontainerstatus "github.com/aws/amazon-ecs-agent/agent/api/container/status"
apierrors "github.com/aws/amazon-ecs-agent/agent/api/errors"
"github.com/aws/amazon-ecs-agent/agent/async"
"github.com/aws/amazon-ecs-agent/agent/config"
"github.com/aws/amazon-ecs-agent/agent/dockerclient"
"github.com/aws/amazon-ecs-agent/agent/dockerclient/clientfactory"
"github.com/aws/amazon-ecs-agent/agent/dockerclient/dockerauth"
"github.com/aws/amazon-ecs-agent/agent/dockerclient/dockeriface"
"github.com/aws/amazon-ecs-agent/agent/dockerclient/sdkclient"
"github.com/aws/amazon-ecs-agent/agent/dockerclient/sdkclientfactory"
"github.com/aws/amazon-ecs-agent/agent/ecr"
"github.com/aws/amazon-ecs-agent/agent/emptyvolume"
"github.com/aws/amazon-ecs-agent/agent/utils"
"github.com/aws/amazon-ecs-agent/agent/utils/ttime"
"github.com/cihub/seelog"
"github.com/docker/docker/api/types/volume"
docker "github.com/fsouza/go-dockerclient"
)
const (
dockerDefaultTag = "latest"
// imageNameFormat is the name of a image may look like: repo:tag
imageNameFormat = "%s:%s"
// the buffer size will ensure agent doesn't miss any event from docker
dockerEventBufferSize = 100
// healthCheckStarting is the initial status returned from docker container health check
healthCheckStarting = "starting"
// healthCheckHealthy is the healthy status returned from docker container health check
healthCheckHealthy = "healthy"
// healthCheckUnhealthy is unhealthy status returned from docker container health check
healthCheckUnhealthy = "unhealthy"
// maxHealthCheckOutputLength is the maximum length of healthcheck command output that agent will save
maxHealthCheckOutputLength = 1024
// VolumeDriverType is one of the plugin capabilities see https://docs.docker.com/engine/reference/commandline/plugin_ls/#filtering
VolumeDriverType = "volumedriver"
)
// Timelimits for docker operations enforced above docker
// TODO: Make these limits configurable.
const (
pullImageTimeout = 2 * time.Hour
// CreateContainerTimeout is the timeout for the CreateContainer API.
CreateContainerTimeout = 4 * time.Minute
// StopContainerTimeout is the timeout for the StopContainer API.
StopContainerTimeout = 30 * time.Second
// RemoveContainerTimeout is the timeout for the RemoveContainer API.
RemoveContainerTimeout = 5 * time.Minute
// InspectContainerTimeout is the timeout for the InspectContainer API.
InspectContainerTimeout = 30 * time.Second
// RemoveImageTimeout is the timeout for the RemoveImage API.
RemoveImageTimeout = 3 * time.Minute
// ListPluginsTimeout is the timout for ListPlugins API.
ListPluginsTimeout = 1 * time.Minute
// CreateVolumeTimeout is the timout for CreateVolume API.
CreateVolumeTimeout = 5 * time.Minute
// InspectVolumeTimeout is the timout for InspectVolume API.
InspectVolumeTimeout = 5 * time.Minute
// RemoveVolumeTimeout is the timout for RemoveVolume API.
RemoveVolumeTimeout = 5 * time.Minute
// Parameters for caching the docker auth for ECR
tokenCacheSize = 100
// tokenCacheTTL is the default ttl of the docker auth for ECR
tokenCacheTTL = 12 * time.Hour
// dockerPullBeginTimeout is the timeout from when a 'pull' is called to when
// we expect to see output on the pull progress stream. This is to work
// around a docker bug which sometimes results in pulls not progressing.
dockerPullBeginTimeout = 5 * time.Minute
// dockerPullInactivityTimeout is the amount of time that we will
// wait when the pulling does not progress
dockerPullInactivityTimeout = 1 * time.Minute
// pullStatusSuppressDelay controls the time where pull status progress bar
// output will be suppressed in debug mode
pullStatusSuppressDelay = 2 * time.Second
// StatsInactivityTimeout controls the amount of time we hold open a
// connection to the Docker daemon waiting for stats data
StatsInactivityTimeout = 5 * time.Second
// retry settings for pulling images
maximumPullRetries = 10
minimumPullRetryDelay = 250 * time.Millisecond
maximumPullRetryDelay = 1 * time.Second
pullRetryDelayMultiplier = 1.5
pullRetryJitterMultiplier = 0.2
)
// DockerClient interface to make testing it easier
type DockerClient interface {
// SupportedVersions returns a slice of the supported docker versions (or at least supposedly supported).
SupportedVersions() []dockerclient.DockerVersion
// KnownVersions returns a slice of the Docker API versions known to the Docker daemon.
KnownVersions() []dockerclient.DockerVersion
// WithVersion returns a new DockerClient for which all operations will use the given remote api version.
// A default version will be used for a client not produced via this method.
WithVersion(dockerclient.DockerVersion) DockerClient
// ContainerEvents returns a channel of DockerContainerChangeEvents. Events are placed into the channel and should
// be processed by the listener.
ContainerEvents(ctx context.Context) (<-chan DockerContainerChangeEvent, error)
// PullImage pulls an image. authData should contain authentication data provided by the ECS backend.
PullImage(image string, authData *apicontainer.RegistryAuthenticationData) DockerContainerMetadata
// ImportLocalEmptyVolumeImage imports a locally-generated empty-volume image for supported platforms.
ImportLocalEmptyVolumeImage() DockerContainerMetadata
// CreateContainer creates a container with the provided docker.Config, docker.HostConfig, and name. A timeout value
// and a context should be provided for the request.
CreateContainer(context.Context, *docker.Config, *docker.HostConfig, string, time.Duration) DockerContainerMetadata
// StartContainer starts the container identified by the name provided. A timeout value and a context should be
// provided for the request.
StartContainer(context.Context, string, time.Duration) DockerContainerMetadata
// StopContainer stops the container identified by the name provided. A timeout value and a context should be provided
// for the request.
StopContainer(context.Context, string, time.Duration) DockerContainerMetadata
// DescribeContainer returns status information about the specified container. A context should be provided
// for the request
DescribeContainer(context.Context, string) (apicontainerstatus.ContainerStatus, DockerContainerMetadata)
// RemoveContainer removes a container (typically the rootfs, logs, and associated metadata) identified by the name.
// A timeout value and a context should be provided for the request.
RemoveContainer(context.Context, string, time.Duration) error
// InspectContainer returns information about the specified container. A timeout value and a context should be
// provided for the request.
InspectContainer(context.Context, string, time.Duration) (*docker.Container, error)
// ListContainers returns the set of containers known to the Docker daemon. A timeout value and a context
// should be provided for the request.
ListContainers(context.Context, bool, time.Duration) ListContainersResponse
// CreateVolume creates a docker volume. A timeout value should be provided for the request
CreateVolume(context.Context, string, string, map[string]string, map[string]string, time.Duration) SDKVolumeResponse
// InspectVolume returns a volume by its name. A timeout value should be provided for the request
InspectVolume(context.Context, string, time.Duration) SDKVolumeResponse
// RemoveVolume removes a volume by its name. A timeout value should be provided for the request
RemoveVolume(context.Context, string, time.Duration) error
// ListPluginsWithFilters returns the set of docker plugins installed on the host, filtered by options provided.
// A timeout value should be provided for the request.
ListPluginsWithFilters(context.Context, bool, []string, time.Duration) ([]string, error)
// ListPlugins returns the set of docker plugins installed on the host. A timeout value should be provided for
// the request.
ListPlugins(context.Context, time.Duration) ListPluginsResponse
// Stats returns a channel of stat data for the specified container. A context should be provided so the request can
// be canceled.
Stats(string, context.Context) (<-chan *docker.Stats, error)
// Version returns the version of the Docker daemon.
Version(context.Context, time.Duration) (string, error)
// APIVersion returns the api version of the client
APIVersion() (dockerclient.DockerVersion, error)
// InspectImage returns information about the specified image.
InspectImage(string) (*docker.Image, error)
// RemoveImage removes the metadata associated with an image and may remove the underlying layer data. A timeout
// value and a context should be provided for the request.
RemoveImage(context.Context, string, time.Duration) error
// LoadImage loads an image from an input stream. A timeout value and a context should be provided for the request.
LoadImage(context.Context, io.Reader, time.Duration) error
}
// DockerGoClient wraps the underlying go-dockerclient and docker/docker library.
// It exists primarily for the following four purposes:
// 1) Provide an abstraction over inputs and outputs,
// a) Inputs: Trims them down to what we actually need (largely unchanged tbh)
// b) Outputs: Unifies error handling and the common 'start->inspect'
// pattern by having a consistent error output. This error output
// contains error data with a given Name that aims to be presentable as a
// 'reason' in state changes. It also filters out the information about a
// container that is of interest, such as network bindings, while
// ignoring the rest.
// 2) Timeouts: It adds timeouts everywhere, mostly as a reaction to
// pull-related issues in the Docker daemon.
// 3) Versioning: It abstracts over multiple client versions to allow juggling
// appropriately there.
// 4) Allows for both the go-dockerclient client and Docker SDK client to live
// side-by-side until migration to the Docker SDK is complete.
// Implements DockerClient
// TODO Remove clientfactory field once all API calls are migrated to sdkclientFactory
type dockerGoClient struct {
clientFactory clientfactory.Factory
sdkClientFactory sdkclientfactory.Factory
version dockerclient.DockerVersion
ecrClientFactory ecr.ECRFactory
auth dockerauth.DockerAuthProvider
ecrTokenCache async.Cache
config *config.Config
_time ttime.Time
_timeOnce sync.Once
daemonVersionUnsafe string
lock sync.Mutex
}
func (dg *dockerGoClient) WithVersion(version dockerclient.DockerVersion) DockerClient {
return &dockerGoClient{
clientFactory: dg.clientFactory,
sdkClientFactory: dg.sdkClientFactory,
version: version,
auth: dg.auth,
config: dg.config,
}
}
// scratchCreateLock guards against multiple 'scratch' image creations at once
var scratchCreateLock sync.Mutex
// NewDockerGoClient creates a new DockerGoClient
// TODO Remove clientfactory parameter once migration to Docker SDK is complete.
func NewDockerGoClient(clientFactory clientfactory.Factory, sdkclientFactory sdkclientfactory.Factory,
cfg *config.Config, ctx context.Context) (DockerClient, error) {
// Ensure both clients can connect to the Docker daemon.
client, err := clientFactory.GetDefaultClient()
if err != nil {
seelog.Errorf("DockerGoClient: go-dockerclient unable to connect to Docker daemon. " +
"Ensure Docker is running: %v", err)
return nil, err
}
sdkclient, err := sdkclientFactory.GetDefaultClient()
if err != nil {
seelog.Errorf("DockerGoClient: Docker SDK client unable to connect to Docker daemon. " +
"Ensure Docker is running: %v", err)
return nil, err
}
// Even if we have a DockerClient, the daemon might not be running. Ping from both clients
// to ensure it's up.
err = client.Ping()
if err != nil {
seelog.Errorf("DockerGoClient: go-dockerclient unable to ping Docker daemon. " +
"Ensure Docker is running: %v", err)
return nil, err
}
_, err = sdkclient.Ping(ctx)
if err != nil {
seelog.Errorf("DockerGoClient: Docker SDK client unable to ping Docker daemon. " +
"Ensure Docker is running: %v", err)
return nil, err
}
var dockerAuthData json.RawMessage
if cfg.EngineAuthData != nil {
dockerAuthData = cfg.EngineAuthData.Contents()
}
return &dockerGoClient{
clientFactory: clientFactory,
sdkClientFactory: sdkclientFactory,
auth: dockerauth.NewDockerAuthProvider(cfg.EngineAuthType, dockerAuthData),
ecrClientFactory: ecr.NewECRFactory(cfg.AcceptInsecureCert),
ecrTokenCache: async.NewLRUCache(tokenCacheSize, tokenCacheTTL),
config: cfg,
}, nil
}
// Returns the Docker SDK Client
func (dg *dockerGoClient) sdkDockerClient() (sdkclient.Client, error){
if dg.version == "" {
return dg.sdkClientFactory.GetDefaultClient()
}
return dg.sdkClientFactory.GetClient(dg.version)
}
// Returns the go-dockerclient Client
// TODO Remove method once migration is complete.
func (dg *dockerGoClient) dockerClient() (dockeriface.Client, error) {
if dg.version == "" {
return dg.clientFactory.GetDefaultClient()
}
return dg.clientFactory.GetClient(dg.version)
}
func (dg *dockerGoClient) time() ttime.Time {
dg._timeOnce.Do(func() {
if dg._time == nil {
dg._time = &ttime.DefaultTime{}
}
})
return dg._time
}
func (dg *dockerGoClient) PullImage(image string, authData *apicontainer.RegistryAuthenticationData) DockerContainerMetadata {
// TODO Switch to just using context.WithDeadline and get rid of this funky code
timeout := dg.time().After(pullImageTimeout)
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
response := make(chan DockerContainerMetadata, 1)
go func() {
imagePullBackoff := utils.NewSimpleBackoff(minimumPullRetryDelay,
maximumPullRetryDelay, pullRetryJitterMultiplier, pullRetryDelayMultiplier)
err := utils.RetryNWithBackoffCtx(ctx, imagePullBackoff, maximumPullRetries,
func() error {
err := dg.pullImage(image, authData)
if err != nil {
seelog.Warnf("DockerGoClient: failed to pull image %s: %s", image, err.Error())
}
return err
})
response <- DockerContainerMetadata{Error: wrapPullErrorAsNamedError(err)}
}()
select {
case resp := <-response:
return resp
case <-timeout:
cancel()
return DockerContainerMetadata{Error: &DockerTimeoutError{pullImageTimeout, "pulled"}}
}
}
func wrapPullErrorAsNamedError(err error) apierrors.NamedError {
var retErr apierrors.NamedError
if err != nil {
engErr, ok := err.(apierrors.NamedError)
if !ok {
engErr = CannotPullContainerError{err}
}
retErr = engErr
}
return retErr
}
func (dg *dockerGoClient) pullImage(image string, authData *apicontainer.RegistryAuthenticationData) apierrors.NamedError {
seelog.Debugf("DockerGoClient: pulling image: %s", image)
client, err := dg.dockerClient()
if err != nil {
return CannotGetDockerClientError{version: dg.version, err: err}
}
authConfig, err := dg.getAuthdata(image, authData)
if err != nil {
return wrapPullErrorAsNamedError(err)
}
pullDebugOut, pullWriter := io.Pipe()
defer pullWriter.Close()
repository := getRepository(image)
opts := docker.PullImageOptions{
Repository: repository,
OutputStream: pullWriter,
InactivityTimeout: dockerPullInactivityTimeout,
}
timeout := dg.time().After(dockerPullBeginTimeout)
// pullBegan is a channel indicating that we have seen at least one line of data on the 'OutputStream' above.
// It is here to guard against a bug wherin docker never writes anything to that channel and hangs in pulling forever.
pullBegan := make(chan bool, 1)
go dg.filterPullDebugOutput(pullDebugOut, pullBegan, image)
pullFinished := make(chan error, 1)
go func() {
pullFinished <- client.PullImage(opts, authConfig)
seelog.Debugf("DockerGoClient: pulling image complete: %s", image)
}()
select {
case <-pullBegan:
break
case pullErr := <-pullFinished:
if pullErr != nil {
return CannotPullContainerError{pullErr}
}
return nil
case <-timeout:
return &DockerTimeoutError{dockerPullBeginTimeout, "pullBegin"}
}
seelog.Debugf("DockerGoClient: pull began for image: %s", image)
defer seelog.Debugf("DockerGoClient: pull completed for image: %s", image)
err = <-pullFinished
if err != nil {
return CannotPullContainerError{err}
}
return nil
}
func (dg *dockerGoClient) filterPullDebugOutput(pullDebugOut *io.PipeReader, pullBegan chan<- bool, image string) {
// pullBeganOnce ensures we only indicate it began once (since our channel will only be read 0 or 1 times)
pullBeganOnce := sync.Once{}
reader := bufio.NewReader(pullDebugOut)
var line string
var pullErr error
var statusDisplayed time.Time
for {
line, pullErr = reader.ReadString('\n')
if pullErr != nil {
break
}
pullBeganOnce.Do(func() {
pullBegan <- true
})
now := time.Now()
if !strings.Contains(line, "[=") || now.After(statusDisplayed.Add(pullStatusSuppressDelay)) {
// skip most of the progress bar lines, but retain enough for debugging
seelog.Debugf("DockerGoClient: pulling image %s, status %s", image, line)
statusDisplayed = now
}
if strings.Contains(line, "already being pulled by another client. Waiting.") {
// This can mean the daemon is 'hung' in pulling status for this image, but we can't be sure.
seelog.Errorf("DockerGoClient: image 'pull' status marked as already being pulled for image %s, status %s",
image, line)
}
}
if pullErr != nil && pullErr != io.EOF {
seelog.Warnf("DockerGoClient: error reading pull image status for image %s: %v", image, pullErr)
}
}
func getRepository(image string) string {
repository, tag := parseRepositoryTag(image)
if tag == "" {
repository = repository + ":" + dockerDefaultTag
} else {
repository = image
}
return repository
}
// ImportLocalEmptyVolumeImage imports a locally-generated empty-volume image for supported platforms.
func (dg *dockerGoClient) ImportLocalEmptyVolumeImage() DockerContainerMetadata {
timeout := dg.time().After(pullImageTimeout)
response := make(chan DockerContainerMetadata, 1)
go func() {
err := dg.createScratchImageIfNotExists()
var wrapped apierrors.NamedError
if err != nil {
wrapped = CreateEmptyVolumeError{err}
}
response <- DockerContainerMetadata{Error: wrapped}
}()
select {
case resp := <-response:
return resp
case <-timeout:
return DockerContainerMetadata{Error: &DockerTimeoutError{pullImageTimeout, "pulled"}}
}
}
func (dg *dockerGoClient) createScratchImageIfNotExists() error {
client, err := dg.dockerClient()
if err != nil {
return err
}
scratchCreateLock.Lock()
defer scratchCreateLock.Unlock()
_, err = client.InspectImage(emptyvolume.Image + ":" + emptyvolume.Tag)
if err == nil {
seelog.Debug("DockerGoClient: empty volume image is already present, skipping import")
// Already exists; assume that it's okay to use it
return nil
}
reader, writer := io.Pipe()
emptytarball := tar.NewWriter(writer)
go func() {
emptytarball.Close()
writer.Close()
}()
seelog.Debug("DockerGoClient: importing empty volume image")
// Create it from an empty tarball
err = client.ImportImage(docker.ImportImageOptions{
Repository: emptyvolume.Image,
Tag: emptyvolume.Tag,
Source: "-",
InputStream: reader,
})
return err
}
func (dg *dockerGoClient) InspectImage(image string) (*docker.Image, error) {
client, err := dg.dockerClient()
if err != nil {
return nil, err
}
return client.InspectImage(image)
}
func (dg *dockerGoClient) getAuthdata(image string, authData *apicontainer.RegistryAuthenticationData) (docker.AuthConfiguration, error) {
if authData == nil {
return dg.auth.GetAuthconfig(image, nil)
}
switch authData.Type {
case apicontainer.AuthTypeECR:
provider := dockerauth.NewECRAuthProvider(dg.ecrClientFactory, dg.ecrTokenCache)
authConfig, err := provider.GetAuthconfig(image, authData)
if err != nil {
return authConfig, CannotPullECRContainerError{err}
}
return authConfig, nil
case apicontainer.AuthTypeASM:
return authData.ASMAuthData.GetDockerAuthConfig(), nil
default:
return dg.auth.GetAuthconfig(image, nil)
}
}
func (dg *dockerGoClient) CreateContainer(ctx context.Context,
config *docker.Config,
hostConfig *docker.HostConfig,
name string,
timeout time.Duration) DockerContainerMetadata {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Buffered channel so in the case of timeout it takes one write, never gets
// read, and can still be GC'd
response := make(chan DockerContainerMetadata, 1)
go func() { response <- dg.createContainer(ctx, config, hostConfig, name) }()
// Wait until we get a response or for the 'done' context channel
select {
case resp := <-response:
return resp
case <-ctx.Done():
// Context has either expired or canceled. If it has timed out,
// send back the DockerTimeoutError
err := ctx.Err()
if err == context.DeadlineExceeded {
return DockerContainerMetadata{Error: &DockerTimeoutError{timeout, "created"}}
}
// Context was canceled even though there was no timeout. Send
// back an error.
return DockerContainerMetadata{Error: &CannotCreateContainerError{err}}
}
}
func (dg *dockerGoClient) createContainer(ctx context.Context,
config *docker.Config,
hostConfig *docker.HostConfig,
name string) DockerContainerMetadata {
client, err := dg.dockerClient()
if err != nil {
return DockerContainerMetadata{Error: CannotGetDockerClientError{version: dg.version, err: err}}
}
containerOptions := docker.CreateContainerOptions{
Config: config,
HostConfig: hostConfig,
Name: name,
Context: ctx,
}
dockerContainer, err := client.CreateContainer(containerOptions)
if err != nil {
return DockerContainerMetadata{Error: CannotCreateContainerError{err}}
}
return dg.containerMetadata(ctx, dockerContainer.ID)
}
func (dg *dockerGoClient) StartContainer(ctx context.Context, id string, timeout time.Duration) DockerContainerMetadata {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Buffered channel so in the case of timeout it takes one write, never gets
// read, and can still be GC'd
response := make(chan DockerContainerMetadata, 1)
go func() { response <- dg.startContainer(ctx, id) }()
select {
case resp := <-response:
return resp
case <-ctx.Done():
// Context has either expired or canceled. If it has timed out,
// send back the DockerTimeoutError
err := ctx.Err()
if err == context.DeadlineExceeded {
return DockerContainerMetadata{Error: &DockerTimeoutError{timeout, "started"}}
}
return DockerContainerMetadata{Error: CannotStartContainerError{err}}
}
}
func (dg *dockerGoClient) startContainer(ctx context.Context, id string) DockerContainerMetadata {
client, err := dg.dockerClient()
if err != nil {
return DockerContainerMetadata{Error: CannotGetDockerClientError{version: dg.version, err: err}}
}
err = client.StartContainerWithContext(id, nil, ctx)
metadata := dg.containerMetadata(ctx, id)
if err != nil {
metadata.Error = CannotStartContainerError{err}
}
return metadata
}
// DockerStateToState converts the container status from docker to status recognized by the agent
// Ref: https://github.com/fsouza/go-dockerclient/blob/fd53184a1439b6d7b82ca54c1cd9adac9a5278f2/container.go#L133
func DockerStateToState(state docker.State) apicontainerstatus.ContainerStatus {
if state.Running {
return apicontainerstatus.ContainerRunning
}
if state.Dead {
return apicontainerstatus.ContainerStopped
}
if state.StartedAt.IsZero() && state.Error == "" {
return apicontainerstatus.ContainerCreated
}
return apicontainerstatus.ContainerStopped
}
func (dg *dockerGoClient) DescribeContainer(ctx context.Context, dockerID string) (apicontainerstatus.ContainerStatus, DockerContainerMetadata) {
dockerContainer, err := dg.InspectContainer(ctx, dockerID, InspectContainerTimeout)
if err != nil {
return apicontainerstatus.ContainerStatusNone, DockerContainerMetadata{Error: CannotDescribeContainerError{err}}
}
return DockerStateToState(dockerContainer.State), MetadataFromContainer(dockerContainer)
}
func (dg *dockerGoClient) InspectContainer(ctx context.Context, dockerID string, timeout time.Duration) (*docker.Container, error) {
type inspectResponse struct {
container *docker.Container
err error
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Buffered channel so in the case of timeout it takes one write, never gets
// read, and can still be GC'd
response := make(chan inspectResponse, 1)
go func() {
container, err := dg.inspectContainer(ctx, dockerID)
response <- inspectResponse{container, err}
}()
// Wait until we get a response or for the 'done' context channel
select {
case resp := <-response:
return resp.container, resp.err
case <-ctx.Done():
err := ctx.Err()
if err == context.DeadlineExceeded {
return nil, &DockerTimeoutError{timeout, "inspecting"}
}
return nil, &CannotInspectContainerError{err}
}
}
func (dg *dockerGoClient) inspectContainer(ctx context.Context, dockerID string) (*docker.Container, error) {
client, err := dg.dockerClient()
if err != nil {
return nil, err
}
return client.InspectContainerWithContext(dockerID, ctx)
}
func (dg *dockerGoClient) StopContainer(ctx context.Context, dockerID string, timeout time.Duration) DockerContainerMetadata {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Buffered channel so in the case of timeout it takes one write, never gets
// read, and can still be GC'd
response := make(chan DockerContainerMetadata, 1)
go func() { response <- dg.stopContainer(ctx, dockerID) }()
select {
case resp := <-response:
return resp
case <-ctx.Done():
// Context has either expired or canceled. If it has timed out,
// send back the DockerTimeoutError
err := ctx.Err()
if err == context.DeadlineExceeded {
return DockerContainerMetadata{Error: &DockerTimeoutError{timeout, "stopped"}}
}
return DockerContainerMetadata{Error: CannotStopContainerError{err}}
}
}
func (dg *dockerGoClient) stopContainer(ctx context.Context, dockerID string) DockerContainerMetadata {
client, err := dg.dockerClient()
if err != nil {
return DockerContainerMetadata{Error: CannotGetDockerClientError{version: dg.version, err: err}}
}
err = client.StopContainerWithContext(dockerID, uint(dg.config.DockerStopTimeout/time.Second), ctx)
metadata := dg.containerMetadata(ctx, dockerID)
if err != nil {
seelog.Infof("DockerGoClient: error stopping container %s: %v", dockerID, err)
if metadata.Error == nil {
metadata.Error = CannotStopContainerError{err}
}
}
return metadata
}
func (dg *dockerGoClient) RemoveContainer(ctx context.Context, dockerID string, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Buffered channel so in the case of timeout it takes one write, never gets
// read, and can still be GC'd
response := make(chan error, 1)
go func() { response <- dg.removeContainer(ctx, dockerID) }()
// Wait until we get a response or for the 'done' context channel
select {
case resp := <-response:
return resp
case <-ctx.Done():
err := ctx.Err()
// Context has either expired or canceled. If it has timed out,
// send back the DockerTimeoutError
if err == context.DeadlineExceeded {
return &DockerTimeoutError{dockerclient.RemoveContainerTimeout, "removing"}
}
return &CannotRemoveContainerError{err}
}
}
func (dg *dockerGoClient) removeContainer(ctx context.Context, dockerID string) error {
client, err := dg.dockerClient()
if err != nil {
return err
}
return client.RemoveContainer(docker.RemoveContainerOptions{
ID: dockerID,
RemoveVolumes: true,
Force: false,
Context: ctx,
})
}
func (dg *dockerGoClient) containerMetadata(ctx context.Context, id string) DockerContainerMetadata {
ctx, cancel := context.WithTimeout(ctx, dockerclient.InspectContainerTimeout)
defer cancel()
dockerContainer, err := dg.InspectContainer(ctx, id, dockerclient.InspectContainerTimeout)
if err != nil {
return DockerContainerMetadata{DockerID: id, Error: CannotInspectContainerError{err}}
}
return MetadataFromContainer(dockerContainer)
}
// MetadataFromContainer translates dockerContainer into DockerContainerMetadata
func MetadataFromContainer(dockerContainer *docker.Container) DockerContainerMetadata {
var bindings []apicontainer.PortBinding
var err apierrors.NamedError
if dockerContainer.NetworkSettings != nil {
// Convert port bindings into the format our container expects
bindings, err = apicontainer.PortBindingFromDockerPortBinding(dockerContainer.NetworkSettings.Ports)
if err != nil {
seelog.Criticalf("DockerGoClient: Docker had network bindings we couldn't understand: %v", err)
return DockerContainerMetadata{Error: apierrors.NamedError(err)}
}
}
metadata := DockerContainerMetadata{
DockerID: dockerContainer.ID,
PortBindings: bindings,
Volumes: dockerContainer.Volumes,
CreatedAt: dockerContainer.Created,
StartedAt: dockerContainer.State.StartedAt,
FinishedAt: dockerContainer.State.FinishedAt,
}
if dockerContainer.Config != nil {
metadata.Labels = dockerContainer.Config.Labels
}
metadata = getMetadataVolumes(metadata, dockerContainer)
if !dockerContainer.State.Running && !dockerContainer.State.FinishedAt.IsZero() {
// Only record an exitcode if it has exited
metadata.ExitCode = &dockerContainer.State.ExitCode
}
if dockerContainer.State.Error != "" {
metadata.Error = NewDockerStateError(dockerContainer.State.Error)
}
if dockerContainer.State.OOMKilled {
metadata.Error = OutOfMemoryError{}
}
if dockerContainer.State.Health.Status == "" || dockerContainer.State.Health.Status == healthCheckStarting {
return metadata
}
// Record the health check information if exists
metadata.Health = getMetadataHealthCheck(dockerContainer)
return metadata
}
func getMetadataVolumes(metadata DockerContainerMetadata, dockerContainer *docker.Container) DockerContainerMetadata {
// Workaround for https://github.com/docker/docker/issues/27601
// See https://github.com/docker/docker/blob/v1.12.2/daemon/inspect_unix.go#L38-L43
// for how Docker handles API compatibility on Linux
if len(metadata.Volumes) == 0 {
metadata.Volumes = make(map[string]string)
for _, m := range dockerContainer.Mounts {
metadata.Volumes[m.Destination] = m.Source
}
}
return metadata
}
func getMetadataHealthCheck(dockerContainer *docker.Container) apicontainer.HealthStatus {
health := apicontainer.HealthStatus{}
logLength := len(dockerContainer.State.Health.Log)
if logLength != 0 {
// Only save the last log from the health check
output := dockerContainer.State.Health.Log[logLength-1].Output
size := len(output)
if size > maxHealthCheckOutputLength {
size = maxHealthCheckOutputLength
}
health.Output = output[:size]
}
switch dockerContainer.State.Health.Status {
case healthCheckHealthy:
health.Status = apicontainerstatus.ContainerHealthy
case healthCheckUnhealthy:
health.Status = apicontainerstatus.ContainerUnhealthy
if logLength == 0 {
seelog.Warn("DockerGoClient: no container healthcheck data returned by Docker")
break
}
health.ExitCode = dockerContainer.State.Health.Log[logLength-1].ExitCode
default:
seelog.Debugf("DockerGoClient: unknown healthcheck status event from docker: %s", dockerContainer.State.Health.Status)
}
return health
}
// Listen to the docker event stream for container changes and pass them up
func (dg *dockerGoClient) ContainerEvents(ctx context.Context) (<-chan DockerContainerChangeEvent, error) {
client, err := dg.dockerClient()
if err != nil {
return nil, err
}
dockerEvents := make(chan *docker.APIEvents, dockerEventBufferSize)
events := make(chan *docker.APIEvents)
buffer := NewInfiniteBuffer()
err = client.AddEventListener(dockerEvents)
if err != nil {
seelog.Errorf("DockerGoClient: unable to add a docker event listener: %v", err)
return nil, err
}
go func() {
<-ctx.Done()
client.RemoveEventListener(dockerEvents)
}()
// Cache the event from go docker client
go buffer.StartListening(dockerEvents)
// Read the buffered events and send to task engine
go buffer.Consume(events)
changedContainers := make(chan DockerContainerChangeEvent)
go dg.handleContainerEvents(ctx, events, changedContainers)
return changedContainers, nil
}
func (dg *dockerGoClient) handleContainerEvents(ctx context.Context,
events <-chan *docker.APIEvents,
changedContainers chan<- DockerContainerChangeEvent) {
for event := range events {
containerID := event.ID
seelog.Debugf("DockerGoClient: got event from docker daemon: %v", event)
var status apicontainerstatus.ContainerStatus
eventType := apicontainer.ContainerStatusEvent
switch event.Status {
case "create":
status = apicontainerstatus.ContainerCreated
// TODO no need to inspect containers here.
// There's no need to inspect containers after they are created when we
// adopt Docker's volume APIs. Today, that's the only information we need
// from the `inspect` API. Once we start injecting that ourselves,
// there's no need to `inspect` containers on `Create` anymore. This will
// save us a lot of `inspect` calls in the future.
case "start":
status = apicontainerstatus.ContainerRunning
case "stop":
fallthrough
case "die":
status = apicontainerstatus.ContainerStopped
case "oom":
containerInfo := event.ID
// events only contain the container's name in newer Docker API
// versions (starting with 1.22)
if containerName, ok := event.Actor.Attributes["name"]; ok {
containerInfo += fmt.Sprintf(" (name: %q)", containerName)
}
seelog.Infof("DockerGoClient: process within container %s died due to OOM", containerInfo)
// "oom" can either means any process got OOM'd, but doesn't always
// mean the container dies (non-init processes). If the container also
// dies, you see a "die" status as well; we'll update suitably there
continue
case "health_status: healthy":
fallthrough
case "health_status: unhealthy":
eventType = apicontainer.ContainerHealthEvent
default:
// Because docker emits new events even when you use an old event api
// version, it's not that big a deal
seelog.Debugf("DockerGoClient: unknown status event from docker: %v", event)
}
metadata := dg.containerMetadata(ctx, containerID)
changedContainers <- DockerContainerChangeEvent{
Status: status,
Type: eventType,
DockerContainerMetadata: metadata,
}
}
}
// ListContainers returns a slice of container IDs.
func (dg *dockerGoClient) ListContainers(ctx context.Context, all bool, timeout time.Duration) ListContainersResponse {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Buffered channel so in the case of timeout it takes one write, never gets
// read, and can still be GC'd
response := make(chan ListContainersResponse, 1)
go func() { response <- dg.listContainers(ctx, all) }()
select {
case resp := <-response:
return resp
case <-ctx.Done():
// Context has either expired or canceled. If it has timed out,
// send back the DockerTimeoutError
err := ctx.Err()
if err == context.DeadlineExceeded {
return ListContainersResponse{Error: &DockerTimeoutError{timeout, "listing"}}
}
return ListContainersResponse{Error: &CannotListContainersError{err}}
}
}
func (dg *dockerGoClient) listContainers(ctx context.Context, all bool) ListContainersResponse {
client, err := dg.dockerClient()
if err != nil {
return ListContainersResponse{Error: err}
}
containers, err := client.ListContainers(docker.ListContainersOptions{
All: all,
Context: ctx,
})
if err != nil {
return ListContainersResponse{Error: err}
}
// We get an empty slice if there are no containers to be listed.
// Extract container IDs from this list.
containerIDs := make([]string, len(containers))
for i, container := range containers {
containerIDs[i] = container.ID
}
return ListContainersResponse{DockerIDs: containerIDs, Error: nil}
}
func (dg *dockerGoClient) SupportedVersions() []dockerclient.DockerVersion {
return dg.clientFactory.FindSupportedAPIVersions()
}
func (dg *dockerGoClient) KnownVersions() []dockerclient.DockerVersion {
return dg.clientFactory.FindKnownAPIVersions()
}
func (dg *dockerGoClient) Version(ctx context.Context, timeout time.Duration) (string, error) {
version := dg.getDaemonVersion()
if version != "" {
return version, nil
}
derivedCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
client, err := dg.dockerClient()
if err != nil {
return "", err
}
info, err := client.VersionWithContext(derivedCtx)
if err != nil {
return "", err
}
version = info.Get("Version")
dg.setDaemonVersion(version)
return version, nil
}
func (dg *dockerGoClient) getDaemonVersion() string {
dg.lock.Lock()
defer dg.lock.Unlock()
return dg.daemonVersionUnsafe
}
func (dg *dockerGoClient) setDaemonVersion(version string) {
dg.lock.Lock()
defer dg.lock.Unlock()
dg.daemonVersionUnsafe = version
}
func (dg *dockerGoClient) CreateVolume(ctx context.Context, name string,
driver string,
driverOptions map[string]string,
labels map[string]string,
timeout time.Duration) SDKVolumeResponse {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Buffered channel so in the case of timeout it takes one write, never gets
// read, and can still be GC'd
response := make(chan SDKVolumeResponse, 1)
go func() { response <- dg.createVolume(ctx, name, driver, driverOptions, labels) }()
// Wait until we get a response or for the 'done' context channel
select {
case resp := <-response:
return resp
case <-ctx.Done():
// Context has either expired or canceled. If it has timed out,
// send back the DockerTimeoutError
err := ctx.Err()
if err == context.DeadlineExceeded {
return SDKVolumeResponse{DockerVolume: nil, Error: &DockerTimeoutError{timeout, "creating volume"}}
}
// Context was canceled even though there was no timeout. Send
// back an error.
return SDKVolumeResponse{DockerVolume: nil, Error: &CannotCreateVolumeError{err}}
}
}
func (dg *dockerGoClient) createVolume(ctx context.Context,
name string,
driver string,
driverOptions map[string]string,
labels map[string]string) SDKVolumeResponse {
client, err := dg.sdkDockerClient()
if err != nil {
return SDKVolumeResponse{DockerVolume: nil, Error: &CannotGetDockerClientError{version: dg.version, err: err}}
}
volumeOptions := volume.VolumesCreateBody{
Driver: driver,
DriverOpts: driverOptions,
Labels: labels,
Name: name,
}
dockerVolume, err := client.VolumeCreate(ctx, volumeOptions)
if err != nil {
return SDKVolumeResponse{DockerVolume: nil, Error: &CannotCreateVolumeError{err}}
}
return SDKVolumeResponse{DockerVolume: &dockerVolume, Error: nil}
}
func (dg *dockerGoClient) InspectVolume(ctx context.Context, name string, timeout time.Duration) SDKVolumeResponse {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Buffered channel so in the case of timeout it takes one write, never gets
// read, and can still be GC'd
response := make(chan SDKVolumeResponse, 1)
go func() { response <- dg.inspectVolume(ctx, name) }()
// Wait until we get a response or for the 'done' context channel
select {
case resp := <-response:
return resp
case <-ctx.Done():
// Context has either expired or canceled. If it has timed out,
// send back the DockerTimeoutError
err := ctx.Err()
if err == context.DeadlineExceeded {
return SDKVolumeResponse{DockerVolume: nil, Error: &DockerTimeoutError{timeout, "inspecting volume"}}
}
// Context was canceled even though there was no timeout. Send
// back an error.
return SDKVolumeResponse{DockerVolume: nil, Error: &CannotInspectVolumeError{err}}
}
}
func (dg *dockerGoClient) inspectVolume(ctx context.Context, name string) SDKVolumeResponse {
client, err := dg.sdkDockerClient()
if err != nil {
return SDKVolumeResponse{
DockerVolume: nil,
Error: &CannotGetDockerClientError{version: dg.version, err: err}}
}
dockerVolume, err := client.VolumeInspect(ctx, name)
if err != nil {
return SDKVolumeResponse{DockerVolume: nil, Error: &CannotInspectVolumeError{err}}
}
return SDKVolumeResponse{DockerVolume: &dockerVolume, Error: nil}
}
func (dg *dockerGoClient) RemoveVolume(ctx context.Context, name string, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Buffered channel so in the case of timeout it takes one write, never gets
// read, and can still be GC'd
response := make(chan error, 1)
go func() { response <- dg.removeVolume(ctx, name) }()
// Wait until we get a response or for the 'done' context channel
select {
case resp := <-response:
return resp
case <-ctx.Done():
// Context has either expired or canceled. If it has timed out,
// send back the DockerTimeoutError
err := ctx.Err()
if err == context.DeadlineExceeded {
return &DockerTimeoutError{timeout, "removing volume"}
}
// Context was canceled even though there was no timeout. Send
// back an error.
return &CannotRemoveVolumeError{err}
}
}
func (dg *dockerGoClient) removeVolume(ctx context.Context, name string) error {
client, err := dg.dockerClient()
if err != nil {
return &CannotGetDockerClientError{version: dg.version, err: err}
}
ok := client.RemoveVolume(name)
if ok != nil {
return &CannotRemoveVolumeError{err}
}
return nil
}
// ListPluginsWithFilters currently is a convenience method as go-dockerclient doesn't implement fitered list. When we or someone else submits
// PR for the fix we will refactor this to pass in the fiters. See https://docs.docker.com/engine/reference/commandline/plugin_ls/#filtering.
func (dg *dockerGoClient) ListPluginsWithFilters(ctx context.Context, enabled bool, capabilities []string, timeout time.Duration) ([]string, error) {
var filteredPluginNames []string
response := dg.ListPlugins(ctx, timeout)
if response.Error != nil {
return nil, response.Error
}
for _, pluginDetail := range response.Plugins {
if pluginDetail.Active != enabled {
continue
}
// One plugin might have multiple capabilities, see https://docs.docker.com/engine/reference/commandline/plugin_ls/#filtering
for _, pluginType := range pluginDetail.Config.Interface.Types {
for _, capability := range capabilities {
// capability looks like volumedriver, pluginType looks like docker.volumedriver/1.0 (prefix.capability/version)
if strings.Contains(pluginType, capability) {
filteredPluginNames = append(filteredPluginNames, pluginDetail.Name)
break
}
}
}
}
return filteredPluginNames, nil
}
func (dg *dockerGoClient) ListPlugins(ctx context.Context, timeout time.Duration) ListPluginsResponse {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Buffered channel so in the case of timeout it takes one write, never gets
// read, and can still be GC'd
response := make(chan ListPluginsResponse, 1)
go func() { response <- dg.listPlugins(ctx) }()
// Wait until we get a response or for the 'done' context channel
select {
case resp := <-response:
return resp
case <-ctx.Done():
// Context has either expired or canceled. If it has timed out,
// send back the DockerTimeoutError
err := ctx.Err()
if err == context.DeadlineExceeded {
return ListPluginsResponse{Plugins: nil, Error: &DockerTimeoutError{timeout, "listing plugins"}}
}
// Context was canceled even though there was no timeout. Send
// back an error.
return ListPluginsResponse{Plugins: nil, Error: &CannotListPluginsError{err}}
}
}
func (dg *dockerGoClient) listPlugins(ctx context.Context) ListPluginsResponse {
client, err := dg.dockerClient()
if err != nil {
return ListPluginsResponse{Plugins: nil, Error: &CannotGetDockerClientError{version: dg.version, err: err}}
}
plugins, err := client.ListPlugins(ctx)
if err != nil {
return ListPluginsResponse{Plugins: nil, Error: &CannotListPluginsError{err}}
}
return ListPluginsResponse{Plugins: plugins, Error: nil}
}
// APIVersion returns the client api version
func (dg *dockerGoClient) APIVersion() (dockerclient.DockerVersion, error) {
client, err := dg.dockerClient()
if err != nil {
return "", err
}
return dg.clientFactory.FindClientAPIVersion(client), nil
}
// Stats returns a channel of *docker.Stats entries for the container.
func (dg *dockerGoClient) Stats(id string, ctx context.Context) (<-chan *docker.Stats, error) {
client, err := dg.dockerClient()
if err != nil {
return nil, err
}
stats := make(chan *docker.Stats)
options := docker.StatsOptions{
ID: id,
Stats: stats,
Stream: true,
Context: ctx,
InactivityTimeout: StatsInactivityTimeout,
}
go func() {
statsErr := client.Stats(options)
if statsErr != nil {
seelog.Infof("DockerGoClient: Unable to retrieve stats for container %s: %v",
id, statsErr)
}
}()
return stats, nil
}
// RemoveImage invokes github.com/fsouza/go-dockerclient.Client's
// RemoveImage API with a timeout
func (dg *dockerGoClient) RemoveImage(ctx context.Context, imageName string, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
response := make(chan error, 1)
go func() { response <- dg.removeImage(imageName) }()
select {
case resp := <-response:
return resp
case <-ctx.Done():
return &DockerTimeoutError{timeout, "removing image"}
}
}
func (dg *dockerGoClient) removeImage(imageName string) error {
client, err := dg.dockerClient()
if err != nil {
return err
}
return client.RemoveImage(imageName)
}
// LoadImage invokes loads an image from an input stream, with a specified timeout
func (dg *dockerGoClient) LoadImage(ctx context.Context, inputStream io.Reader, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
response := make(chan error, 1)
go func() {
response <- dg.loadImage(docker.LoadImageOptions{
InputStream: inputStream,
Context: ctx,
})
}()
select {
case resp := <-response:
return resp
case <-ctx.Done():
return &DockerTimeoutError{timeout, "loading image"}
}
}
func (dg *dockerGoClient) loadImage(opts docker.LoadImageOptions) error {
client, err := dg.dockerClient()
if err != nil {
return err
}
return client.LoadImage(opts)
}
| 1 | 20,559 | I think I saw this line in last PR, you can update your base branch and rebase to avoid this. And it would be awesome if you can rebase instead of merge each time you push PR to the `moby` branch, that will make the commits history clearer. | aws-amazon-ecs-agent | go |
@@ -1853,8 +1853,12 @@ presys_SetContextThread(dcontext_t *dcontext, reg_t *param_base)
/* FIXME : we are going to read and write to cxt, which may be unsafe */
ASSERT(tid != 0xFFFFFFFF);
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, IF_DGCDIAG_ELSE(1, 2),
- "syscall: NtSetContextThread handle="PFX" tid=%d cxt->Xip="PFX"\n",
- thread_handle, tid, cxt->CXT_XIP);
+ "syscall: NtSetContextThread handle="PFX" tid=%d cxt->Xip="PFX" flags="PFX"\n",
+ thread_handle, tid, cxt->CXT_XIP, cxt->ContextFlags);
+ if (get_thread_id() == tid) {
+ /* Simple case when called on own thread. */
+ return execute_syscall;
+ }
mutex_lock(&thread_initexit_lock); /* need lock to lookup thread */
if (intercept_asynch_for_thread(tid, false/*no unknown threads*/)) {
priv_mcontext_t mcontext; | 1 | /* **********************************************************
* Copyright (c) 2011-2017 Google, Inc. All rights reserved.
* Copyright (c) 2006-2010 VMware, 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 VMware, 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 VMWARE, 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.
*/
/* Copyright (c) 2006-2007 Determina Corp. */
/*
* syscall.c - win32-specific system call handling routines
*/
#include "../globals.h"
#include "../fragment.h"
#include "ntdll.h"
#include "os_private.h"
#include "aslr.h"
#include "instrument.h"
#include "../synch.h"
/* this points to one of the os-version-specific system call # arrays below */
int *syscalls = NULL;
/* this points to one of the os-version-specific wow64 argument conversion arrays */
int *wow64_index = NULL;
/* Ref case 5217 - for Sygate compatibility we indirect int 2e system
* calls through the int_syscall_address (which after syscalls_init()
* will point to an int 2e, ret 0 in ntdll.dll. This is, for all intents
* and purposes, a function pointer that will be set only once early
* during app init, so we keep it here with the options to leverage their
* protection. */
app_pc int_syscall_address = NULL;
/* Ref case 5441 - for Sygate compatibility we fake our return address from
* sysenter system calls (they sometimes verify) to this address which will
* (by default) point to a ret 0 in ntdll.dll. This is, for all intents and
* purposes, a function pointer that will be set only once early during app
* init, so we keep it here with the options to leverage their protection. */
app_pc sysenter_ret_address = NULL;
/* i#537: sysenter returns to KiFastSystemCallRet from kernel */
app_pc KiFastSystemCallRet_address = NULL;
/* Snapshots are relatively heavyweight, so we do not take them on every memory
* system call. On the other hand, if we only did them when we dumped
* stats, we'd miss large memory allocations that were freed prior
* to the next stats dump (which can be far between if not much new code
* is being executed). Thus, we do them whenever we print stats and on
* every memory operation larger than this threshold:
*/
#define SNAPSHOT_THRESHOLD (16*PAGE_SIZE)
/*******************************************************/
#ifdef CLIENT_INTERFACE
/* i#1230: we support a limited number of extra interceptions.
* We add extra slots to all of the arrays.
*/
# define CLIENT_EXTRA_TRAMPOLINE 12
# define TRAMPOLINE_MAX (SYS_MAX + CLIENT_EXTRA_TRAMPOLINE)
/* no lock needed since only supported during dr_client_main */
static uint syscall_extra_idx;
#else
# define TRAMPOLINE_MAX SYS_MAX
#endif
const char * SYS_CONST syscall_names[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
"Nt"#name,
#include "syscallx.h"
#undef SYSCALL
};
/* i#1598: we try to make progress on unknown versions */
int windows_unknown_syscalls[TRAMPOLINE_MAX];
SYS_CONST int windows_10_1607_x64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w12x64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_10_1607_wow64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w12w64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_10_1607_x86_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w12x86,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_10_1511_x64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w11x64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_10_1511_wow64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w11w64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_10_1511_x86_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w11x86,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_10_x64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w10x64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_10_wow64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w10w64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_10_x86_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w10x86,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_81_x64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w81x64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_81_wow64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w81w64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_81_x86_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w81x86,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_8_x64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w8x64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_8_wow64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w8w64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_8_x86_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w8x86,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_7_x64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w7x64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_7_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w7x86,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_vista_sp1_x64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
vista1_x64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_vista_sp1_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
vista1,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_vista_sp0_x64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
vista0_x64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_vista_sp0_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
vista0,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_2003_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w2k3,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_XP_x64_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
xp64,
#include "syscallx.h"
#undef SYSCALL
};
/* This is the index for XP through Win7. */
SYS_CONST int windows_XP_wow64_index[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
wow64,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_XP_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
xp,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_2000_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
w2k,
#include "syscallx.h"
#undef SYSCALL
};
SYS_CONST int windows_NT_sp4_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
ntsp4,
#include "syscallx.h"
#undef SYSCALL
};
/* for SP3 (and maybe SP2 or SP1 -- haven't checked those) */
SYS_CONST int windows_NT_sp3_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
ntsp3,
#include "syscallx.h"
#undef SYSCALL
};
/* for SP0 (and maybe SP2 or SP1 -- haven't checked those) */
SYS_CONST int windows_NT_sp0_syscalls[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
ntsp0,
#include "syscallx.h"
#undef SYSCALL
};
/* for x64 this is the # of args */
SYS_CONST uint syscall_argsz[TRAMPOLINE_MAX] = {
#ifdef X64
# define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
nargs,
#else
# define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
arg32,
#endif
#include "syscallx.h"
#undef SYSCALL
};
/* FIXME: currently whether a syscall needs action or not can't be
* dynamically changed since this flag is used early on by
* intercept_native_syscall() */
static SYS_CONST int syscall_requires_action[TRAMPOLINE_MAX] = {
#define SYSCALL(name, act, nargs, arg32, ntsp0, ntsp3, ntsp4, w2k, xp, wow64, xp64,\
w2k3, vista0, vista0_x64, vista1, vista1_x64, w7x86, w7x64, \
w8x86, w8w64, w8x64, w81x86, w81w64, w81x64, w10x86, w10w64, w10x64,\
w11x86, w11w64, w11x64, w12x86, w12w64, w12x64) \
act,
#include "syscallx.h"
#undef SYSCALL
};
/* used to intercept syscalls while native */
static byte *syscall_trampoline_pc[TRAMPOLINE_MAX];
static app_pc syscall_trampoline_skip_pc[TRAMPOLINE_MAX];
static app_pc syscall_trampoline_hook_pc[TRAMPOLINE_MAX];
static app_pc syscall_trampoline_copy_pc[TRAMPOLINE_MAX];
#ifdef GBOP
/* GBOP stack adjustment - currently either always 0 or always 4 for
* vsyscall calls, but may need to be a more general array in case
* HOOKED_TRAMPOLINE_HOOK_DEEPER allows different offsets
* FIXME: case 7127 this can be compressed further, if really only a bitmask
* see intercept_syscall_wrapper
*/
static byte syscall_trampoline_gbop_fpo_offset[TRAMPOLINE_MAX];
#endif /* GBOP */
/****************************************************************************/
/* System call interception: put any special handling here
* Arguments come from the pusha right before the call
* Win32 syscall: int 0x2e, number is in eax, address of start of params
* on user stack is in edx
*
* WinXP uses sysenter instruction and does a call to it since sysenter
* doesn't store return info -- instead sysexit (called from kernel) grabs
* continuation pc from edx. So the callee, same one used by all syscalls,
* puts esp in edx so that kernel just has to dereference it.
* Actually, on closer examination, it looks like the kernel sends control
* directly to 0x7ffe0304, which does a ret to get back to the ret after
* the call %edx -- since the 0x7ffe0304 ret executes natively we can't tell
* the difference, but we should be aware of it! If this is true, why bother
* filling in edx for sysenter? Seems like the kernel must be hardcoding it
* with 0x7ffe0304.
* FIXME: think about whether want to
* insert a trampoline (and risk clobbering entry point after the ret)
* instead of the current method of clobbering the return address
*
* Here are some win2000 examples (from ntdll.dll):
NtSetContextThread:
77F97BFA: B8 BA 00 00 00 mov eax,0BAh
77F97BFF: 8D 54 24 04 lea edx,[esp+4]
77F97C03: CD 2E int 2Eh
77F97C05: C2 08 00 ret 8
this is the only one that does not immediately have a ret, though it
does ret after a jump, some poorly chosen "optimization":
NtContinue:
77F82872: B8 1C 00 00 00 mov eax,1Ch
77F82877: 8D 54 24 04 lea edx,[esp+4]
77F8287B: CD 2E int 2Eh
77F8287D: E9 82 74 01 00 jmp 77F99D04
77F99D04: C2 08 00 ret 8
*
* WinXP example:
NtOpenKey:
0x77f7eb23 b8 77 00 00 00 mov $0x00000077 -> %eax
0x77f7eb28 ba 00 03 fe 7f mov $0x7ffe0300 -> %edx
0x77f7eb2d ff d2 call %edx
0x7ffe0300 8b d4 mov %esp -> %edx
0x7ffe0302 0f 34 sysenter
0x7ffe0304 c3 ret %esp (%esp) -> %esp
0x77f7eb2f c2 0c 00 ret $0x000c %esp (%esp) -> %esp
*/
/* the win32ksys calls are all above 0x1000, only Zw/Nt* are below */
#define MAX_NTOSKRNL_SYSCALL_NUM 0x1000
bool
ignorable_system_call(int num, instr_t *gateway, dcontext_t *dcontext_live)
{
/* FIXME: this should really be a complete list of ignorable calls,
* just ntoskrnl ones that we understand, to avoid surprises
* with added calls?
*/
/* FIXME: switch to a bit vector?
* we may want an inverted bit vector instead (inw2k p.123 - lower 12 bits)
* there are 285 syscalls on xp - let's say we support 320
* instead of the 40 ints (160 bytes) and a loop we're using now,
* we can grab 40 bytes for 320 syscalls and do the bit extraction
* precomputing from this table will be easy
*/
/* FIXME : it looks like most file IO/creation syscalls are alertable
* ref bug 2520, should be added to non-ignorable */
/* FIXME : we just return false for all system calls, to be safe we should
* really be checking for known ignoreable system calls rather then the reverse,
* see syscallx.h for old enumeration. */
return false;
}
bool
optimizable_system_call(int num)
{
if (INTERNAL_OPTION(shared_eq_ignore))
return ignorable_system_call(num, NULL, NULL);
else {
int i;
/* FIXME: switch to a bit vector, just as for the syscalls array? */
for (i = 0; i < SYS_MAX; i++) {
if (num == syscalls[i])
return !syscall_requires_action[i];
}
/* If the syscall isn't in the array, DR doesn't care about it. */
return true;
}
}
/* The trampoline handler called for ntdll syscall wrappers that we
* care about, so that we can act on them while native_exec-ing
*/
after_intercept_action_t
syscall_while_native(app_state_at_intercept_t *state)
{
int sysnum = (int) (ptr_int_t) state->callee_arg;
/* FIXME : if dr calls through ntdll functions that are hooked by a third
* party (say Sygate's sysfer.dll) then they could perform syscalls that
* would get us here. Most of the time we'll be ok, but if the current
* thread is under_dyn_hack or native_exec we might try to process the
* system call or takeover, neither of which is safe. Currently we avoid
* calling through nt wrappers that sysfer.dll hooks (doing system call
* internally instead). This also applies if we call our own hooks, which
* we avoid in a similar manner.
*/
/* Returning AFTER_INTERCEPT_LET_GO will perform the syscall natively,
* while AFTER_INTERCEPT_LET_GO_ALT_DYN will skip it. Modify the register
* arguments to change the returned state, note that the stack will have
* to be popped once (modify reg_esp) to match up the returns.
*/
dcontext_t *dcontext = get_thread_private_dcontext();
IF_X64(ASSERT_TRUNCATE(int, int, (ptr_int_t)state->callee_arg));
/* N.B.: if any intercepted syscalls are used by DR from ntdll, rather
* than custom wrappers, then a recursion-avoidance check here would
* be required to avoid infinite loop on error here!
*/
STATS_INC(num_syscall_trampolines);
if (dcontext == NULL) {
/* unknown thread */
return AFTER_INTERCEPT_LET_GO; /* do syscall natively */
} else if (IS_UNDER_DYN_HACK(dcontext->thread_record->under_dynamo_control) ||
dcontext->thread_record->retakeover) {
/* this trampoline is our ticket to taking control again prior
* to the image entry point
* we often hit this on NtAllocateVirtualMemory from HeapCreate for
* the next dll init after the cb ret where we lost control
*/
STATS_INC(num_syscall_trampolines_retakeover);
LOG(THREAD, LOG_SYSCALLS, 1,
"syscall_while_native: retakeover in %s after native cb return lost control\n",
syscall_names[sysnum]);
retakeover_after_native(dcontext->thread_record, INTERCEPT_SYSCALL);
dcontext->thread_record->retakeover = false;
return AFTER_INTERCEPT_TAKE_OVER; /* syscall under DR */
} else if (!dcontext->thread_record->under_dynamo_control
/* xref PR 230836 */
IF_CLIENT_INTERFACE(&& !IS_CLIENT_THREAD(dcontext))
/* i#1318: may get here from privlib at exit, at least until we
* redirect *everything*. From privlib we need to keep
* the syscall native as DR locks may be held.
*/
IF_CLIENT_INTERFACE(&& dcontext->whereami == WHERE_APP)) {
/* assumption is that any known native thread is one we control in general,
* just not right now while in a native_exec_list dll */
STATS_INC(num_syscall_trampolines_native);
LOG(THREAD, LOG_SYSCALLS, 1,
"NATIVE system call %s\n", syscall_names[sysnum]);
DOLOG(IF_DGCDIAG_ELSE(1, 2), LOG_SYSCALLS, {
dump_callstack(*((byte **)state->mc.xsp) /*retaddr*/,
(app_pc) state->mc.xbp,
THREAD, DUMP_NOT_XML);
});
#ifdef GBOP
/* case 7127 - validate GBOP on syscalls that are already hooked for
* hotp_only on native_exec
*/
if (DYNAMO_OPTION(gbop) != GBOP_DISABLED) {
/* FIXME: case 7127: should enforce here GBOP_WHEN_NATIVE_EXEC if we
* want to apply for -hotp_only but not for native_exec.
* Today we always validate.
*/
/* FIXME: case 7127: for -exclude_gbop_list need to check a flag
* whether this ntdll!Nt* hook has been excluded
*/
/* state->xsp is the wishful thinking after syscall
* address, instead of the original one -
* intercept_syscall_wrapper() keeps the relevant
* FPO information: 4 on XP SP2+, or 0 earlier
*/
gbop_validate_and_act(state,
/* adjust ESP */
syscall_trampoline_gbop_fpo_offset[sysnum],
syscall_trampoline_hook_pc[sysnum]);
/* if the routine at all returns it passed the GBOP checks */
/* FIXME: case 7127: may want alternative handling
* and for system calls returning an error of some kind
* like STATUS_INVALID_ADDRESS or STATUS_BUFFER_OVERFLOW
* may be a somewhat useful attack handling alternative
*/
/* FIXME: case 7127 for completeness should be able to add
* this check to the regular DR syscalls where we'll be at
* the PC calling sysenter, not necessarily at the start
* of a function. Though other than uniform testing it
* won't serve much else. There we'll have to match the
* correct FPO offset at the syscall as well.
*/
}
#endif /* GBOP */
/* Notes on handling syscalls for native threads:
*
* FIXME: make sure each syscall handler can handle this thread being native,
* as well as target being native. E.g., will a native thread terminating
* itself hit any assertion about not coming back under DR control first?
* Another example, will GetCxt fail trying to translate a native thread's
* context?
* FIXME: what about asynch event while in syscall? none of ones we
* intercept are alertable?
* FIXME: exception during pre-syscall sequence can cause us to miss
* the go-native trigger!
*
* Be careful with cache consistency events -- we assume in general that
* code executed natively is never mixed with code executed under DR, in
* both execution and manipulation, and we try to have _all_ DGC-using
* dlls listed in the native_exec_list. We do handle write faults from
* cache consistency in native threads, so we'll have correct behavior,
* but we don't want a performance hit from in-cache DGC slowing down
* from-native DGC b/c they share memory and it keeps bouncing from RO to
* RW -- that's a big reason we're going native in the first place! For
* handling app memory-changing syscalls, we don't mark new code as
* read-only until executed from, so in the common case we should not
* incur any cost from cache consistency while native.
*/
/* Invoke normal DR syscall-handling by calling dispatch() with a
* linkstub_t marked just like those for fragments ending in syscalls.
* (We cannot return to the trampoline tail for asynch_take_over() since
* it will clobber out next_tag and last_exit and will execute the jmp
* back to the syscall under DR, requiring a more intrusive way of going
* native afterward.) Normal handling may skip the syscall or do
* whatever, but we expect it to not change control flow (we don't
* intercept those while threads are native) and to come out of the
* cache and continue on with the next_tag that we set here, which is a
* special stopping point routine of ours that causes DR to go native @
* the pc we store in dcontext->native_exec_postsyscall.
*/
dcontext->next_tag = BACK_TO_NATIVE_AFTER_SYSCALL;
/* start_pc is the take-over pc that will jmp to the syscall instr, while
* we need the post-syscall pc, which we stored when generating the trampoline
*/
ASSERT(syscall_trampoline_skip_pc[sysnum] != NULL);
dcontext->native_exec_postsyscall = syscall_trampoline_skip_pc[sysnum];
ASSERT(dcontext->whereami == WHERE_APP);
dcontext->whereami = WHERE_TRAMPOLINE;
set_last_exit(dcontext, (linkstub_t *) get_native_exec_syscall_linkstub());
/* assumption: no special cleanup from tail of trampoline needed */
transfer_to_dispatch(dcontext, &state->mc, false/*!full_DR_state*/);
ASSERT_NOT_REACHED();
}
/* This routine tries to handle syscalls from DR, but will fail in some
* cases (if the current thread has certain under_dynamo_control values) --
* so we use our own custom wrapper rather than go through ntdll when we
* expect going through wrapper to reach here (FIXME should do this for
* all system calls). */
/* i#924: this happens at exit during os_loader_exit(), and at thread init
* when priv libs call routines we haven't yet redirected. Best to disable
* the syslog for clients (we still have the log warning).
*/
#ifndef CLIENT_INTERFACE
DODEBUG({
/* Unfortunately we use various ntdll routines (most notably Ldr*)
* that may be hooked (hook code could do anything including making
* system calls). Also some the of the ntdll Rtl routines we
* import may be similarly ill behaved (though we don't believe any
* of the currently used ones are problematic). Also calling
* through Sygate hooks may reach here.
*/
SYSLOG_INTERNAL_WARNING_ONCE("syscall_while_native: using %s - maybe hooked?",
syscall_names[sysnum]);
});
#endif
STATS_INC(num_syscall_trampolines_DR);
LOG(THREAD, LOG_SYSCALLS, 1,
"WARNING: syscall_while_native: syscall from DR %s\n",
syscall_names[sysnum]);
return AFTER_INTERCEPT_LET_GO; /* do syscall natively */
}
static inline bool
intercept_syscall_for_thin_client(int SYSnum)
{
if (SYSnum == SYS_CreateThread ||
SYSnum == SYS_CreateProcess ||
SYSnum == SYS_CreateProcessEx ||
SYSnum == SYS_CreateUserProcess ||
SYSnum == SYS_TerminateThread || /* Case 9079. */
SYSnum == SYS_ResumeThread || /* i#1198: for env var propagation */
/* case 8866: for -early_inject we must intercept NtMapViewOfSection */
(DYNAMO_OPTION(early_inject) && SYSnum == SYS_MapViewOfSection)) {
return true;
}
return false;
}
static inline bool
intercept_native_syscall(int SYSnum)
{
ASSERT(SYSnum < TRAMPOLINE_MAX);
#ifdef CLIENT_INTERFACE
if ((uint)SYSnum >= SYS_MAX + syscall_extra_idx)
return false;
#endif
/* Don't hook all syscalls for thin_client. */
if (DYNAMO_OPTION(thin_client) && !intercept_syscall_for_thin_client(SYSnum))
return false;
if (!syscall_requires_action[SYSnum] || syscalls[SYSnum] == SYSCALL_NOT_PRESENT)
return false;
/* ignore control transfer system calls:
* 1) NtCallbackReturn (assume the corresponding cb was native as well,
* else we have big problems! we could detect
* by stacking up info on native cbs, if nobody ever
* did an int 2b natively...not worth it for now)
* 2) NtContinue
* 3) NtCreateThread
* Ref case 5295 - Sygate hooks this nt wrapper differently then the
* others (@ 2nd instruction). We only need to hook CreateThread
* system call for follow children from native exec threads anyways, so
* is easiest to just skip this one and live without that ability.
* 4) NtWriteVirtualMemory:
* Case 9156/9103: we don't hook it to avoid removing
* our own GBOP hook, until we actually implement acting on it (case 8321)
*
* We do NOT ignore SetContextThread or suspension/resumption, since
* the target could be in DR!
*/
if (SYSnum == SYS_CallbackReturn ||
SYSnum == SYS_Continue ||
(!DYNAMO_OPTION(native_exec_hook_create_thread) &&
SYSnum == SYS_CreateThread) ||
SYSnum == SYS_WriteVirtualMemory)
return false;
return true;
}
void
init_syscall_trampolines(void)
{
int i;
HMODULE h = (HMODULE)get_ntdll_base();
ASSERT(DYNAMO_OPTION(native_exec_syscalls));
for (i = 0; i < TRAMPOLINE_MAX; i++) {
if (intercept_native_syscall(i)) {
byte *fpo_adjustment = NULL;
#ifdef GBOP
fpo_adjustment = &syscall_trampoline_gbop_fpo_offset[i];
#endif
syscall_trampoline_hook_pc[i] = (app_pc)get_proc_address(h, syscall_names[i]);
syscall_trampoline_pc[i] =
/* FIXME: would like to use static references to entry points -- yet,
* set of those we care about varies dynamically by platform, and
* we cannot include a pointer to a 2003-only Nt* entry point and
* avoid a loader link error on 2000, right?
* For now just using get_proc_address!
*/
intercept_syscall_wrapper(&syscall_trampoline_hook_pc[i],
syscall_while_native,
(void *) (ptr_int_t) i /* callee arg */,
AFTER_INTERCEPT_DYNAMIC_DECISION,
/* must store the skip_pc for the new dispatch()
* to know where to go after handling from DR --
* this is simpler than having trampoline
* pass it in as an arg to syscall_while_native
* or trying to decode it.
*/
&syscall_trampoline_skip_pc[i],
/* Returns a pointer to a copy of the original
* first 5 bytes for removing the trampoline
* later. Excepting hook chaining situations
* this could just simply be the same as the
* returned syscall_trampoline_pc. */
&syscall_trampoline_copy_pc[i],
fpo_adjustment, syscall_names[i]);
}
}
}
void
exit_syscall_trampolines(void)
{
int i;
ASSERT(DYNAMO_OPTION(native_exec_syscalls));
for (i = 0; i < TRAMPOLINE_MAX; i++) {
if (intercept_native_syscall(i)) {
if (syscall_trampoline_pc[i] != NULL) {
ASSERT(syscall_trampoline_copy_pc[i] != NULL &&
syscall_trampoline_hook_pc[i] != NULL);
remove_trampoline(syscall_trampoline_copy_pc[i],
syscall_trampoline_hook_pc[i]);
} else {
ASSERT(DYNAMO_OPTION(native_exec_hook_conflict) ==
HOOKED_TRAMPOLINE_NO_HOOK);
}
}
DEBUG_DECLARE(else ASSERT(syscall_trampoline_pc[i] == NULL));
}
}
#ifdef DEBUG
void
check_syscall_array_sizes()
{
ASSERT(sizeof(windows_81_x64_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_81_wow64_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_81_x86_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_8_x64_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_8_wow64_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_8_x86_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_7_x64_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_7_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_vista_sp1_x64_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_vista_sp1_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_vista_sp0_x64_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_vista_sp0_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_2003_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_XP_x64_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_XP_wow64_index) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_2003_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_XP_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_NT_sp4_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_NT_sp3_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_NT_sp0_syscalls) == sizeof(windows_2000_syscalls));
ASSERT(sizeof(windows_2000_syscalls)/sizeof(windows_2000_syscalls[0]) ==
sizeof(syscall_requires_action)/sizeof(syscall_requires_action[0]));
ASSERT(sizeof(windows_2000_syscalls)/sizeof(windows_2000_syscalls[0]) ==
sizeof(syscall_names)/sizeof(syscall_names[0]));
}
/* verify that syscall numbers match our static lists in an attempt to catch
* changes to syscall interface across Windows patches and service packs
*/
void
check_syscall_numbers(dcontext_t *dcontext)
{
int i;
int sysnum;
byte *addr;
module_handle_t h = get_ntdll_base();
ASSERT(h != NULL && h != INVALID_HANDLE_VALUE);
LOG(GLOBAL, LOG_SYSCALLS, 4, "check_syscall_numbers: ntdll @ "PFX"\n", h);
for (i = 0; i < SYS_MAX; i++) {
if (syscalls[i] == SYSCALL_NOT_PRESENT)
continue;
addr = (byte *)get_proc_address(h, syscall_names[i]);
ASSERT(addr != NULL);
LOG(GLOBAL, LOG_SYSCALLS, 4,
"\tsyscall 0x%x %s: addr "PFX"\n", i, syscall_names[i], addr);
sysnum = decode_syscall_num(dcontext, addr);
/* because of Sygate hooks can't assert sysnum is valid here */
if (sysnum >= 0 && sysnum != syscalls[i]) {
SYSLOG_INTERNAL_ERROR("syscall %s is really 0x%x not 0x%x\n",
syscall_names[i], sysnum, syscalls[i]);
syscalls[i] = sysnum;
/* of course is much too late to fix if we already used via
* NT_SYSCALL */
}
}
}
#endif
/* adjust region to page boundaries, since Windows lets you pass
* non-aligned values, unlike Linux
* e.g. a two byte cross-page request will result in a two page region
*/
static inline void
align_page_boundary(dcontext_t *dcontext,
app_pc *base /* IN OUT */, size_t *size/* IN OUT */)
{
if (!ALIGNED(*base, PAGE_SIZE) || !ALIGNED(*size, PAGE_SIZE)) {
/* need to cover all pages overlapping the region [base, base + size) */
*size = ALIGN_FORWARD(*base+*size, PAGE_SIZE) - PAGE_START(*base);
*base = (app_pc) PAGE_START(*base);
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"\talign_page_boundary => base="PFX" size="PIFX"\n", *base, *size);
}
}
/* verifies whether target process is being created, presumably as a
* child of the current process
*/
bool
is_newly_created_process(HANDLE process_handle)
{
uint remote_ldr_data;
/* We check based on - trait 3) PEB.Ldr
* The Ldr entry is created by the running process itself later */
/* ATTIC - rejected traits
* trait 1) it doesn't have any threads created
* Seems overly expensive to have no easy alternative to
* NtQuerySystemInformation to tell there are no threads created
* in the process, should use to verify new process since that
* should be the rare case
* FIXME: could at least store the last created pid and a flag indicating if
* its thread has been created and use that as an auxiliary check
*
* May be easier to check the PEB
* trait 2) PEB.ProcessParameters
* The process parameters are available only after they have been created,
* (in fact a good trait that a process without them has just been created,
* yet they are created at the time the first thread's stack is needed.
*
* NOTE - in Vista traits 1 and 2 are no longer valid for this
* purpose. NtCreateUserProcess creates the first thread and sets up
* the process parameters in addition to creating the process. However this
* is only used for aslr_stack so doesn't really matter that much. Trait 3
* (the one we use) should still work anyways (and cover anyone using the legacy
* native interface NtCreateProcess to create the process).
*/
DODEBUG({
/* dead end approach, this code can be removed*/
/* invalid trait 4: shouldn't have many handles open
* Attempted using NtQueryInformationProcess
* ProcessHandleCount which is usually 1 on XP at the time
* a new process is created, if it holds on all platforms
*
* Note unfortunately this cannot be counted on, since handles may
* be inherited - and processes created by cygwin do inherit a lot
* of handles.
*/
ulong remote_process_handle_count;
NTSTATUS res = get_process_handle_count(process_handle,
&remote_process_handle_count);
if (NT_SUCCESS(res)) {
LOG(GLOBAL, LOG_ALL, 2,
"is_newly_created_process: process "PIDFMT" has %d handles -> %s\n",
process_id_from_handle(process_handle),
remote_process_handle_count,
remote_process_handle_count == 1 ? "NEW" : "maybe new");
}
});
remote_ldr_data = get_remote_process_ldr_status(process_handle);
if (remote_ldr_data >= 0) {
LOG(GLOBAL, LOG_ALL, 1,
"is_newly_created_process: process "PIDFMT" PEB->Ldr = %s\n",
process_id_from_handle(process_handle),
remote_ldr_data != 0 ? "initialized" : "NULL -> new process");
return (remote_ldr_data == 0); /* new process */
} else {
/* xref case 9800 - can happen if the app handle lacks the rights we
* need (in which case isn't a new process since the handle used then has
* full rights). Get handle rights in local since won't be available in an
* ldmp. */
DEBUG_DECLARE(ACCESS_MASK rights = nt_get_handle_access_rights(process_handle);)
ASSERT_CURIOSITY(get_os_version() >= WINDOWS_VERSION_VISTA &&
"xref case 9800, is_newly_created_process failure");
}
return false;
}
/* Rather than split up get_syscall_method() we have routines like these
* to query variations
*/
bool
syscall_uses_wow64_index()
{
ASSERT(get_syscall_method() == SYSCALL_METHOD_WOW64);
return (get_os_version() < WINDOWS_VERSION_8);
}
bool
syscall_uses_edx_param_base()
{
return (get_syscall_method() != SYSCALL_METHOD_WOW64 ||
get_os_version() < WINDOWS_VERSION_8);
}
/* FIXME : For int/syscall we can just subtract 2 from the post syscall pc but for
* sysenter we do the post-syscall ret native and therefore we've lost the
* address of the actual syscall, but we are only going to use this for
* certain ntdll system calls so is almost certainly the ntdll sysenter. As
* a hack for now we just use the address of the first system call we saw
* (which should be ntdll's), this is good enough for detach and prob. good
* enough for app GetThreadContext (we could just use 0x7ffe0302 but it moved
* on xp sp2) */
#define SYSCALL_PC(dc) \
((get_syscall_method() == SYSCALL_METHOD_INT || \
get_syscall_method() == SYSCALL_METHOD_SYSCALL) ? \
(ASSERT(SYSCALL_LENGTH == INT_LENGTH), \
POST_SYSCALL_PC(dc) - INT_LENGTH) : \
(get_syscall_method() == SYSCALL_METHOD_WOW64 ? \
(POST_SYSCALL_PC(dc) - CTI_FAR_ABS_LENGTH) : \
get_app_sysenter_addr()))
/* since always coming from dispatch now, only need to set mcontext */
#define SET_RETURN_VAL(dc, val) \
get_mcontext(dc)->xax = (reg_t) (val)
/****************************************************************************
* Thread-handle-to-id table for DrMi#1884.
*
* A handle from the app may not have THREAD_QUERY_INFORMATION privileges, so
* we are forced to maintain a translation table.
*/
static generic_table_t *handle2tid_table;
#define INIT_HTABLE_SIZE_TID 6 /* should remain small */
/* Returns 0 == INVALID_THREAD_ID on failure */
static thread_id_t
handle_to_tid_lookup(HANDLE thread_handle)
{
thread_id_t tid;
TABLE_RWLOCK(handle2tid_table, read, lock);
tid = (thread_id_t) generic_hash_lookup(GLOBAL_DCONTEXT, handle2tid_table,
(ptr_uint_t)thread_handle);
TABLE_RWLOCK(handle2tid_table, read, unlock);
return tid;
}
static bool
handle_to_tid_add(HANDLE thread_handle, thread_id_t tid)
{
TABLE_RWLOCK(handle2tid_table, write, lock);
generic_hash_add(GLOBAL_DCONTEXT, handle2tid_table,
(ptr_uint_t)thread_handle, (void *)tid);
LOG(GLOBAL, LOG_VMAREAS, 2,
"handle_to_tid: thread "PFX" => %d\n", thread_handle, tid);
TABLE_RWLOCK(handle2tid_table, write, unlock);
return true;
}
static bool
handle_to_tid_remove(HANDLE thread_handle)
{
bool found = false;
TABLE_RWLOCK(handle2tid_table, write, lock);
found = generic_hash_remove(GLOBAL_DCONTEXT, handle2tid_table,
(ptr_uint_t)thread_handle);
TABLE_RWLOCK(handle2tid_table, write, unlock);
return found;
}
static thread_id_t
thread_handle_to_tid(HANDLE thread_handle)
{
thread_id_t tid = handle_to_tid_lookup(thread_handle);
if (tid == INVALID_THREAD_ID)
tid = thread_id_from_handle(thread_handle);
return tid;
}
static process_id_t
thread_handle_to_pid(HANDLE thread_handle, thread_id_t tid/*optional*/)
{
if (tid == INVALID_THREAD_ID)
tid = handle_to_tid_lookup(thread_handle);
if (tid != INVALID_THREAD_ID) {
/* Get a handle with more privileges */
thread_handle = thread_handle_from_id(tid);
}
return process_id_from_thread_handle(thread_handle);
}
void
syscall_interception_init(void)
{
handle2tid_table = generic_hash_create
(GLOBAL_DCONTEXT, INIT_HTABLE_SIZE_TID, 80 /* not perf-critical */,
HASHTABLE_SHARED | HASHTABLE_PERSISTENT, NULL
_IF_DEBUG("section-to-file table"));
}
void
syscall_interception_exit(void)
{
generic_hash_destroy(GLOBAL_DCONTEXT, handle2tid_table);
}
/***************************************************************************
* PRE SYSTEM CALL
*
* FIXME: should we pass mcontext to these routines to avoid
* the get_mcontext() call and derefs?
* => now we're forcing the inline of get_mcontext() so should be fine
*/
static reg_t *
pre_system_call_param_base(priv_mcontext_t *mc)
{
#ifdef X64
reg_t *param_base = (reg_t *) mc->xsp;
#else
/* On Win8, wow64 syscalls do not point edx at the params and
* instead simply use esp.
*/
reg_t *param_base = (reg_t *)
(syscall_uses_edx_param_base() ? mc->xdx : mc->xsp);
#endif
param_base += (SYSCALL_PARAM_OFFSET() / sizeof(reg_t));
return param_base;
}
/* NtCreateProcess, NtCreateProcessEx */
static void
presys_CreateProcess(dcontext_t *dcontext, reg_t *param_base, bool ex)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE *process_handle = (HANDLE *) sys_param(dcontext, param_base, 0);
uint access_mask = (uint) sys_param(dcontext, param_base, 1);
uint attributes = (uint) sys_param(dcontext, param_base, 2);
uint inherit_from_process = (uint) sys_param(dcontext, param_base, 3);
BOOLEAN inherit_handles_only = (BOOLEAN) sys_param(dcontext, param_base, 4);
HANDLE section_handle = (HANDLE) sys_param(dcontext, param_base, 5);
HANDLE debug_handle = (HANDLE) sys_param(dcontext, param_base, 6);
HANDLE exception_handle = (HANDLE) sys_param(dcontext, param_base, 7);
if (ex) {
/* according to metasploit, others type as HANDLE unknown etc. */
uint job_member_level = (uint) sys_param(dcontext, param_base, 8);
}
/* Case 9173: guard against pid reuse. Better in post after success
* check but not a big deal.
* We don't do this on CreateThread b/c is_newly_created_process() is still
* true after the first thread (one fix is to store the last created pid and
* a flag indicating if its thread has been created and use that as an auxiliary
* check in is_newly_created_process())
*/
dcontext->aslr_context.last_child_padded = 0;
DOLOG(1, LOG_SYSCALLS, {
if (section_handle != 0) {
app_pc base = (app_pc) get_section_address(section_handle);
/* we will inject in post_syscall or when the first thread is about
* to be created */
LOG(THREAD, LOG_SYSCALLS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtCreateProcess section @"PFX"\n", base);
DOLOG(1, LOG_SYSCALLS, {
char buf[MAXIMUM_PATH];
get_module_name(base, buf, sizeof(buf));
if (buf[0] != '\0')
LOG(THREAD, LOG_SYSCALLS, 2,
"\tNtCreateProcess for module %s\n", buf);
});
}
});
}
#ifdef DEBUG
/* NtCreateUserProcess */
static void
presys_CreateUserProcess(dcontext_t *dcontext, reg_t *param_base)
{
/* New in Vista, here's what I got reverse engineering
* NtCreateUserProcess (11 args, using windows types)
*
* NtCreateUserProcess (
* OUT PHANDLE ProcessHandle,
* OUT PHANDLE ThreadHandle,
* IN ACCESS_MASK ProcDesiredAccess,
* IN ACCESS_MASK ThreadDesiredAccess,
* IN POBJECT_ATTRIBUTES ProcObjectAttributes,
* IN POBJECT_ATTRIBUTES ThreadObjectAttributes,
* IN uint? unknown, [ observed 0x4 ]
* IN BOOL CreateSuspended, [ refers to the thread not the process ]
* IN PRTL_USER_PROCESS_PARAMETERS Params,
* INOUT proc_stuff proc,
* INOUT create_proc_thread_info_t *thread [ see ntdll.h ])
* CreateProcess hardcodes 0x2000000 (== MAXIMUM_ALLOWED) for both
* ACCESS_MASK arguments. I've only observed NULL (== default) for the
* OBJECT_ATTRIBUTES arguments so they are a bit of a guess, but they
* need to be here somewhere and based on error codes I know they are
* ptr arguments so seems quite likely esp. given the arg layout.
*
* where proc_stuff { \\ speculative - the 64bit differences are odd and imply
* \\ more then just size changes
* size_t struct_size, [observed 0x48 (0x58 for 64bit)] \\ prob. sizeof(proc_stuff)
* ptr_uint_t unknown_p2, \\ OUT
* ptr_uint_t unknown_p3, \\ IN/OUT
* OUT HANDLE file_handle, [exe file handle]
* OUT HANDLE section_handle, [exe section handle]
* uint32 unknown_p6, \\ OUT
* uint32 unknown_p7, \\ OUT
* uint32 unknown_p8, \\ OUT
* uint32 unknown_p9, \\ OUT
* #ifndef X64
* uint32 unknown_p10, \\ OUT
* #endif
* OUT PEB *new_proc_peb,
* uint32 unknown_p12_p17[6], \\ OUT
* #ifndef X64
* uint32 unknown_p18, \\ OUT
* #endif
* }
*/
priv_mcontext_t *mc = get_mcontext(dcontext);
ACCESS_MASK proc_access_mask = (uint) sys_param(dcontext, param_base, 2);
ACCESS_MASK thread_access_mask = (uint) sys_param(dcontext, param_base, 3);
/* might be BOOLEAN instead? though separate param should zero out rest */
BOOL create_suspended = (BOOL) sys_param(dcontext, param_base, 7);
create_proc_thread_info_t *thread_stuff = (void *) sys_param(dcontext, param_base, 10);
ASSERT(get_os_version() >= WINDOWS_VERSION_VISTA);
/* might need these in post, note CreateProcess appears to hardcode them */
ASSERT_CURIOSITY(proc_access_mask == MAXIMUM_ALLOWED);
ASSERT_CURIOSITY(thread_access_mask == MAXIMUM_ALLOWED);
ASSERT_CURIOSITY(create_suspended);
/* FIXME - NYI - if any of the above curiosities don't hold we should
* change them here and then fixup as needed in post. */
/* Potentially dangerous deref of app ptr, but is only for debug logging */
ASSERT(thread_stuff != NULL && thread_stuff->nt_path_to_exe.buffer != NULL);
LOG(THREAD, LOG_SYSCALLS, 1, "syscall: NtCreateUserProcess presys %.*S\n",
MIN(MAXIMUM_PATH, thread_stuff->nt_path_to_exe.buffer_size),
(wchar_t *)thread_stuff->nt_path_to_exe.buffer);
/* The thread can be resumed inside the kernel so ideally we would
* insert the DR env vars into the pp param here (i#349).
* However, no matter what I do, the syscall returns STATUS_INVALID_PARAMETER.
* I made a complete copy of pp and updated the unicode pointers so it's
* all contiguous, but still the error. Perhaps it must be on the app heap?
* In any case, kernel32!CreateProcess is hardcoding that the thread be
* suspended (presumably to do its csrss and other inits safely) so we rely
* on seeing NtResumeThread.
*/
}
#endif
/* NtCreateThread */
static void
presys_CreateThread(dcontext_t *dcontext, reg_t *param_base)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE *thread_handle= (HANDLE *) sys_param(dcontext, param_base, 0);
uint access_mask = (uint) sys_param(dcontext, param_base, 1);
uint attributes = (uint) sys_param(dcontext, param_base, 2);
HANDLE process_handle= (HANDLE) sys_param(dcontext, param_base, 3);
uint *client_id = (uint*) sys_param(dcontext, param_base, 4);
CONTEXT *cxt = (CONTEXT *) sys_param(dcontext, param_base, 5);
USER_STACK *stack = (USER_STACK *) sys_param(dcontext, param_base, 6);
BOOLEAN suspended = (BOOLEAN) sys_param(dcontext, param_base, 7);
DEBUG_DECLARE(process_id_t pid = process_id_from_handle(process_handle);)
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtCreateThread pid="PFX" suspended=%d\n",
pid, suspended);
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, 2,
"\tstack: "PFX" "PFX" "PFX" "PFX" "PFX"\n",
stack->FixedStackBase, stack->FixedStackLimit,
stack->ExpandableStackBase, stack->ExpandableStackLimit,
stack->ExpandableStackBottom);
/* According to Nebbett, in eax is the win32 start address
* (stored in ThreadQuerySetWin32StartAddress slot, though that
* is reused by the os, so might not be the same later) and eax is used
* by the thread start kernel32 thunk. It also appears from the thunk
* that the argument to the thread start function is in ebx */
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, 2,
"\tesp="PFX", xip="PFX"\n\tstart address "PFX" with arg "PFX"\n",
cxt->CXT_XSP, cxt->CXT_XIP, cxt->CXT_XAX, cxt->CXT_XBX);
DOLOG(2, LOG_SYSCALLS|LOG_THREADS, {
char buf[MAXIMUM_PATH];
print_symbolic_address((app_pc)cxt->CXT_XAX, buf, sizeof(buf), false);
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, 2,
"\tsymbol info for start address : %s\n", buf);
});
ASSERT(cxt != NULL);
/* if not early injecting, we will unsafely modify cxt (for late follow
* children) FIXME
* if not injecting at all we won't change cxt.
*/
maybe_inject_into_process(dcontext, process_handle, cxt);
if (is_phandle_me(process_handle))
pre_second_thread();
}
/* NtCreateThreadEx */
static void
presys_CreateThreadEx(dcontext_t *dcontext, reg_t *param_base)
{
/* New in Vista, here's what I got reverse engineering NtCreateThreadEx
* (11 args, using windows types)
*
* NtCreateThreadEx (
* OUT PHANDLE ThreadHandle,
* IN ACCESS_MASK DesiredAccess,
* IN POBJECT_ATTRIBUTES ObjectAttributes,
* IN HANDLE ProcessHandle,
* IN LPTHREAD_START_ROUTINE Win32StartAddress,
* IN LPVOID StartParameter,
* IN BOOL CreateSuspended,
* IN uint unknown, [ CreateThread hardcodes to 0 ]
* IN SIZE_T StackCommitSize,
* IN SIZE_T StackReserveSize,
* INOUT create_thread_info_t *thread_info [ see ntdll.h ])
*/
DEBUG_DECLARE(priv_mcontext_t *mc = get_mcontext(dcontext);)
HANDLE process_handle = (HANDLE) sys_param(dcontext, param_base, 3);
DEBUG_DECLARE(byte *start_addr = (byte *) sys_param(dcontext, param_base, 4);)
DEBUG_DECLARE(void *start_parameter = (void *) sys_param(dcontext, param_base, 5);)
DEBUG_DECLARE(bool create_suspended = (bool) sys_param(dcontext, param_base, 6);)
DEBUG_DECLARE(process_id_t pid = process_id_from_handle(process_handle);)
ASSERT(get_os_version() >= WINDOWS_VERSION_VISTA);
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, 2,
"syscall: NtCreateThread pid="PFX" suspended=%d\n"
"\tstart_addr="PFX" arg="PFX"\n",
pid, create_suspended, start_addr, start_parameter);
DOLOG(2, LOG_SYSCALLS|LOG_THREADS, {
char buf[MAXIMUM_PATH];
print_symbolic_address(start_addr, buf, sizeof(buf), false);
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, 2,
"\tsymbol info for start address : %s\n", buf);
});
if (is_phandle_me(process_handle))
pre_second_thread();
}
/* NtCreateWorkerFactory */
static void
presys_CreateWorkerFactory(dcontext_t *dcontext, reg_t *param_base)
{
/* New in Vista. 10 args:
* NtCreateWorkerFactory(
* __out PHANDLE FactoryHandle,
* __in ACCESS_MASK DesiredAccess,
* __in_opt POBJECT_ATTRIBUTES ObjectAttributes,
* __in HANDLE CompletionPortHandle,
* __in HANDLE ProcessHandle,
* __in PVOID StartRoutine,
* __in_opt PVOID StartParameter,
* __in_opt ULONG MaxThreadCount,
* __in_opt SIZE_T StackReserve,
* __in_opt SIZE_T StackCommit)
*/
HANDLE process_handle = (HANDLE) sys_param(dcontext, param_base, 4);
ASSERT(get_os_version() >= WINDOWS_VERSION_VISTA);
if (is_phandle_me(process_handle))
pre_second_thread();
}
/***************************************************************************
* ENV VAR PROPAGATION
*/
/* There is some overlap w/ handle_execve() in unix/os.c but not
* quite enough to easily share this.
*/
static const char * const env_to_propagate[] = {
DYNAMORIO_VAR_RUNUNDER,
DYNAMORIO_VAR_OPTIONS,
DYNAMORIO_VAR_AUTOINJECT,
DYNAMORIO_VAR_LOGDIR,
DYNAMORIO_VAR_CONFIGDIR,
};
static const wchar_t * const wenv_to_propagate[] = {
L_DYNAMORIO_VAR_RUNUNDER,
L_DYNAMORIO_VAR_OPTIONS,
L_DYNAMORIO_VAR_AUTOINJECT,
L_DYNAMORIO_VAR_LOGDIR,
L_DYNAMORIO_VAR_CONFIGDIR,
};
#define NUM_ENV_TO_PROPAGATE (sizeof(env_to_propagate)/sizeof(env_to_propagate[0]))
/* read env var from remote process:
* - return true on read successfully or until end of reading
* - skip DR env vars
*/
static wchar_t *
get_process_env_var(HANDLE phandle, wchar_t *env_ptr, wchar_t *buf, size_t toread)
{
int i;
size_t got;
bool keep_env;
while (true) {
keep_env = true;
ASSERT(toread <= (size_t)PAGE_SIZE);
/* if an env var is too long we're ok: DR vars will fit, and if longer we'll
* handle rest next call.
*/
if (!nt_read_virtual_memory(phandle, env_ptr, buf, toread, &got)) {
/* may have crossed page boundary and the next page is inaccessible */
byte *start = (byte *) env_ptr;
if (PAGE_START(start) != PAGE_START(start + toread)) {
ASSERT((size_t)((byte *)ALIGN_FORWARD(start, PAGE_SIZE)-start) <= toread);
toread = (byte *) ALIGN_FORWARD(start, PAGE_SIZE) - start;
if (!nt_read_virtual_memory(phandle, env_ptr, buf, toread, &got))
return NULL;
} else
return NULL;
continue;
}
buf[got/sizeof(buf[0]) - 1] = '\0';
if (buf[0] == '\0')
return env_ptr;
for (i = 0; i < NUM_ENV_TO_PROPAGATE; i++) {
/* if conflict between env and cfg, we use cfg */
if (wcsncmp(wenv_to_propagate[i], buf, wcslen(wenv_to_propagate[i])) == 0) {
keep_env = false;
}
}
if (keep_env)
return env_ptr;
env_ptr += wcslen(buf) + 1;
}
return false;
}
/* called at presys-ResumeThread to append DR env vars in the target process PEB */
static bool
add_dr_env_vars(dcontext_t *dcontext, HANDLE phandle, wchar_t **env_ptr)
{
wchar_t *env, *cur;
size_t tot_sz = 0, app_sz, sz;
size_t got;
wchar_t *new_env = NULL;
wchar_t buf[MAX_OPTIONS_STRING];
bool need_var[NUM_ENV_TO_PROPAGATE];
size_t sz_var[NUM_ENV_TO_PROPAGATE];
NTSTATUS res;
uint old_prot = PAGE_NOACCESS;
int i, num_propagate = 0;
for (i = 0; i < NUM_ENV_TO_PROPAGATE; i++) {
if (get_config_val(env_to_propagate[i]) == NULL)
need_var[i] = false;
else {
need_var[i] = true;
num_propagate++;
}
}
if (num_propagate == 0) {
LOG(THREAD, LOG_SYSCALLS, 2,
"%s: no DR env vars to propagate\n", __FUNCTION__);
return true; /* nothing to do */
}
ASSERT(env_ptr != NULL);
if (!nt_read_virtual_memory(phandle, env_ptr, &env, sizeof(env), NULL))
goto add_dr_env_failure;
if (env != NULL) {
/* compute size of current env block, and check for existing DR vars */
cur = env;
while (true) {
/* for simplicity we do a syscall for each var */
cur = get_process_env_var(phandle, cur, buf, sizeof(buf));
if (cur == NULL)
return false;
if (buf[0] == '\0')
break;
tot_sz += wcslen(buf) + 1;
cur += wcslen(buf) + 1;
}
tot_sz++; /* final 0 marking end */
/* from here on out, all *sz vars are total bytes, not wchar_t elements */
tot_sz *= sizeof(*env);
}
app_sz = tot_sz;
LOG(THREAD, LOG_SYSCALLS, 2,
"%s: orig app env vars at "PFX"-"PFX"\n",
__FUNCTION__, env, env + app_sz/sizeof(*env));
/* calculate size needed for adding DR env vars.
* for each var, we truncate if too big for buf.
*/
for (i = 0; i < NUM_ENV_TO_PROPAGATE; i++) {
if (need_var[i]) {
sz_var[i] = wcslen(wenv_to_propagate[i]) +
strlen(get_config_val(env_to_propagate[i])) + 2/*=+0*/;
if (sz_var[i] > BUFFER_SIZE_ELEMENTS(buf)) {
SYSLOG_INTERNAL(SYSLOG_WARNING, "truncating DR env var for child");
sz_var[i] = BUFFER_SIZE_ELEMENTS(buf);
}
sz_var[i] *= sizeof(*env);
tot_sz += sz_var[i];
}
}
/* allocate a new env block and copy over the old */
res = nt_remote_allocate_virtual_memory(phandle, &new_env, tot_sz,
PAGE_READWRITE, MEM_COMMIT);
if (!NT_SUCCESS(res)) {
LOG(THREAD, LOG_SYSCALLS, 2,
"%s: failed to allocate new env "PIFX"\n", __FUNCTION__, res);
goto add_dr_env_failure;
}
LOG(THREAD, LOG_SYSCALLS, 2,
"%s: new app env vars allocated at "PFX"-"PFX"\n",
__FUNCTION__, new_env, new_env + tot_sz/sizeof(*env));
cur = env;
sz = 0;
while (true) {
/* for simplicity we do a syscall for each var */
size_t towrite = 0;
cur = get_process_env_var(phandle, cur, buf, sizeof(buf));
if (cur == NULL)
goto add_dr_env_failure;
if (buf[0] == '\0')
break;
towrite = (wcslen(buf) + 1);
res = nt_raw_write_virtual_memory(phandle, new_env + sz/sizeof(*env),
buf, towrite * sizeof(*env), &got);
if (!NT_SUCCESS(res)) {
LOG(THREAD, LOG_SYSCALLS, 2,
"%s copy: got status "PFX", wrote "PIFX" vs requested "PIFX"\n",
__FUNCTION__, res, got, towrite);
goto add_dr_env_failure;
}
sz += towrite * sizeof(*env);
cur += towrite;
}
ASSERT(sz == app_sz - sizeof(*env) /* before final 0 */ );
/* add DR env vars at the end.
* XXX: is alphabetical sorting relied upon? adding to end is working.
*/
for (i = 0; i < NUM_ENV_TO_PROPAGATE; i++) {
if (need_var[i]) {
_snwprintf(buf, BUFFER_SIZE_ELEMENTS(buf), L"%s=%S",
wenv_to_propagate[i], get_config_val(env_to_propagate[i]));
NULL_TERMINATE_BUFFER(buf);
if (!nt_write_virtual_memory(phandle, new_env + sz/sizeof(*env),
buf, sz_var[i], NULL))
goto add_dr_env_failure;
sz += sz_var[i];
}
}
ASSERT(sz == tot_sz - sizeof(*env) /* before final 0 */ );
/* write final 0 */
buf[0] = 0;
if (!nt_write_virtual_memory(phandle, new_env + sz/sizeof(*env), buf,
sizeof(*env), NULL))
goto add_dr_env_failure;
/* install new env */
if (!nt_remote_protect_virtual_memory(phandle, (byte*)PAGE_START(env_ptr), PAGE_SIZE,
PAGE_READWRITE, &old_prot)) {
LOG(THREAD, LOG_SYSCALLS, 1,
"%s: failed to mark "PFX" writable\n", __FUNCTION__, env_ptr);
goto add_dr_env_failure;
}
if (!nt_write_virtual_memory(phandle, env_ptr, &new_env, sizeof(new_env), NULL))
goto add_dr_env_failure;
if (!nt_remote_protect_virtual_memory(phandle, (byte*)PAGE_START(env_ptr), PAGE_SIZE,
old_prot, &old_prot)) {
LOG(THREAD, LOG_SYSCALLS, 1,
"%s: failed to restore "PFX" to "PIFX"\n", __FUNCTION__, env_ptr, old_prot);
/* not a fatal error */
}
/* XXX: free the original? on Vista+ it's part of the pp alloc and
* is on the app heap so we can't. we could query and see if it's
* a separate alloc. for now we just leave it be.
*/
LOG(THREAD, LOG_SYSCALLS, 2,
"%s: installed new env "PFX" at "PFX"\n", __FUNCTION__, new_env, env_ptr);
return true;
add_dr_env_failure:
if (new_env != NULL) {
if (!NT_SUCCESS(nt_remote_free_virtual_memory(phandle, new_env))) {
LOG(THREAD, LOG_SYSCALLS, 2,
"%s: unable to free new env "PFX"\n", __FUNCTION__, new_env);
}
if (old_prot != PAGE_NOACCESS) {
if (!nt_remote_protect_virtual_memory(phandle, (byte*)PAGE_START(env_ptr),
PAGE_SIZE, old_prot, &old_prot)) {
LOG(THREAD, LOG_SYSCALLS, 1, "%s: failed to restore "PFX" to "PIFX"\n",
__FUNCTION__, env_ptr, old_prot);
}
}
}
return false;
}
/* If unable to find info, return false (i.e., assume it might be the
* first thread). Retrieves context from thread handle.
*/
static bool
not_first_thread_in_new_process(HANDLE process_handle, HANDLE thread_handle)
{
char buf[MAX_CONTEXT_SIZE];
CONTEXT *cxt = nt_initialize_context(buf, CONTEXT_DR_STATE);
if (NT_SUCCESS(nt_get_context(thread_handle, cxt)))
return !is_first_thread_in_new_process(process_handle, cxt);
return false;
}
/* NtResumeThread */
static void
presys_ResumeThread(dcontext_t *dcontext, reg_t *param_base)
{
HANDLE thread_handle= (HANDLE) sys_param(dcontext, param_base, 0);
thread_id_t tid = thread_handle_to_tid(thread_handle);
process_id_t pid = thread_handle_to_pid(thread_handle, tid);
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtResumeThread pid=%d tid=%d\n", pid, tid);
if (DYNAMO_OPTION(follow_children) && pid != POINTER_MAX && !is_pid_me(pid)) {
/* For -follow_children we propagate env vars (current
* DYNAMORIO_RUNUNDER, DYNAMORIO_OPTIONS, DYNAMORIO_AUTOINJECT, and
* DYNAMORIO_LOGDIR) to the child to support a simple run-all-children
* model without requiring setting up config files for children.
*
* It's possible the app is explicitly resuming a thread in another
* process and this has nothing to do with a new process: but our env
* var insertion should be innocuous in that case.
*
* For pre-Vista, the initial thread is always suspended, and is either
* resumed inside kernel32!CreateProcessW or by the app, so we should
* always see a resume. For Vista+ NtCreateUserProcess has suspend as a
* param and ideally we should replace the env pre-NtCreateUserProcess,
* but we have yet to get that to work, so for now we rely on
* Vista+ process creation going through the kernel32 routines,
* which do hardcode the thread as being suspended.
*/
PEB *peb;
HANDLE process_handle = process_handle_from_id(pid);
RTL_USER_PROCESS_PARAMETERS *pp = NULL;
if (process_handle == INVALID_HANDLE_VALUE) {
LOG(THREAD, LOG_SYSCALLS, 1,
"WARNING: error acquiring process handle for pid="PIFX"\n", pid);
return;
}
if (!should_inject_into_process(dcontext, process_handle, NULL, NULL)) {
LOG(THREAD, LOG_SYSCALLS, 1,
"Not injecting so not setting DR env vars in pid="PIFX"\n", pid);
return;
}
if (not_first_thread_in_new_process(process_handle, thread_handle)) {
LOG(THREAD, LOG_SYSCALLS, 1,
"Not first thread so not setting DR env vars in pid="PIFX"\n", pid);
return;
}
peb = get_peb(process_handle);
if (peb == NULL) {
LOG(THREAD, LOG_SYSCALLS, 1,
"WARNING: error acquiring PEB for pid="PIFX"\n", pid);
close_handle(process_handle);
return;
}
if (!nt_read_virtual_memory(process_handle, &peb->ProcessParameters, &pp,
sizeof(pp), NULL) || pp == NULL) {
LOG(THREAD, LOG_SYSCALLS, 1,
"WARNING: error acquiring ProcessParameters for pid="PIFX"\n", pid);
close_handle(process_handle);
return;
}
LOG(THREAD, LOG_SYSCALLS, 2,
"inserting DR env vars to pid="PIFX" &pp->Environment="PFX"\n",
pid, &pp->Environment);
if (!add_dr_env_vars(dcontext, process_handle, (wchar_t**)&pp->Environment)) {
LOG(THREAD, LOG_SYSCALLS, 1,
"WARNING: unable to add DR env vars for child pid="PIFX"\n", pid);
close_handle(process_handle);
return;
}
close_handle(process_handle);
}
}
/* NtTerminateProcess */
static bool /* returns whether to execute syscall */
presys_TerminateProcess(dcontext_t *dcontext, reg_t *param_base)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE process_handle = (HANDLE) sys_param(dcontext, param_base, 0);
NTSTATUS exit_status = (NTSTATUS) sys_param(dcontext, param_base, 1);
LOG(THREAD, LOG_SYSCALLS, 1,
"syscall: NtTerminateProcess handle="PFX" pid=%d exit=%d\n",
process_handle,
process_id_from_handle((process_handle == 0) ? NT_CURRENT_PROCESS : process_handle),
exit_status);
if (process_handle == 0) {
NTSTATUS return_val;
thread_record_t **threads;
int num_threads;
priv_mcontext_t mcontext;
DEBUG_DECLARE(bool ok;)
/* this thread won't be terminated! */
LOG(THREAD, LOG_SYSCALLS, 2, "terminating all other threads, not this one\n");
copy_mcontext(mc, &mcontext);
mc->pc = SYSCALL_PC(dcontext);
#ifdef CLIENT_INTERFACE
/* make sure client nudges are finished */
wait_for_outstanding_nudges();
#endif
/* FIXME : issues with cleaning up here what if syscall fails */
DEBUG_DECLARE(ok =)
synch_with_all_threads(THREAD_SYNCH_SUSPENDED_AND_CLEANED,
&threads, &num_threads,
/* Case 6821: while we're ok to be detached, we're
* not ok to be reset since we won't have the
* last_exit flag set for coming back here (plus
* our kstats get off since we didn't yet enter
* the cache)
*/
THREAD_SYNCH_VALID_MCONTEXT_NO_XFER,
/* if we fail to suspend a thread (e.g., privilege
* problems) ignore it. FIXME: retry instead? */
THREAD_SYNCH_SUSPEND_FAILURE_IGNORE);
ASSERT(ok);
ASSERT(threads == NULL && num_threads == 0); /* We asked for CLEANED */
copy_mcontext(&mcontext, mc);
/* we hold the initexit lock at this point, but we cannot release
* it, b/c a new thread waiting on it could start initializing and
* then we'd issue the syscall and kill it while it's holding our
* lock, causing a deadlock when the subsequent process-terminating
* syscall comes in! (==case 4243) So, we hold the lock to issue
* the syscall, safest to do syscall right here rather than going
* back to handle_system_call()
*/
return_val = nt_terminate_process_for_app(process_handle, exit_status);
SET_RETURN_VAL(dcontext, return_val);
LOG(THREAD, LOG_SYSCALLS, 2,
"\tNtTerminateProcess("PFX", "PFX") => "PIFX" on behalf of app\n",
process_handle, exit_status, return_val);
end_synch_with_all_threads(threads, num_threads, false/*no resume*/);
return false; /* do not execute syscall -- we already did it */
} else if (is_phandle_me((process_handle == 0) ? NT_CURRENT_PROCESS : process_handle)) {
/* case 10338: we don't synchall here for faster shutdown, but we have
* to try and not crash any other threads. FIXME: if it's rare to get here
* w/ > 1 thread perhaps we should do the synchall.
*/
LOG(THREAD, LOG_SYSCALLS, 2, "\tterminating process w/ %d running thread(s)\n",
get_num_threads());
KSTOP(pre_syscall);
KSTOP(num_exits_dir_syscall);
if (is_thread_currently_native(dcontext->thread_record)) {
/* Avoid hooks on syscalls made while cleaning up: such as
* private libraries making system lib calls
*/
dynamo_thread_under_dynamo(dcontext);
}
/* FIXME: what if syscall returns w/ STATUS_PROCESS_IS_TERMINATING? */
os_terminate_wow64_write_args(true/*process*/, process_handle, exit_status);
cleanup_and_terminate(dcontext, syscalls[SYS_TerminateProcess],
/* r10, which will go to rcx in cleanup_and_terminate
* and back to r10 in global_do_syscall_syscall (i#1901).
*/
IF_X64_ELSE(mc->r10, mc->xdx),
mc->xdx, true /* entire process */, 0, 0);
}
return true;
}
/* NtTerminateThread */
static void
presys_TerminateThread(dcontext_t *dcontext, reg_t *param_base)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
/* NtTerminateThread(IN HANDLE ThreadHandle OPTIONAL, IN NTSTATUS ExitStatus) */
HANDLE thread_handle = (HANDLE) sys_param(dcontext, param_base, 0);
NTSTATUS exit_status = (NTSTATUS) sys_param(dcontext, param_base, 1);
/* need to determine which thread is being terminated
* it's harder than you'd think -- we can get its handle but
* the handle may have been duplicated, no way to test
* equivalence, we have to get the thread id
*/
thread_id_t tid;
thread_record_t *tr = thread_lookup(get_thread_id());
ASSERT(tr != NULL);
if (thread_handle == 0)
thread_handle = NT_CURRENT_THREAD;
tid = thread_handle_to_tid(thread_handle);
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, 1,
"syscall: NtTerminateThread "PFX" => tid=%d\n", thread_handle, tid);
if (tid == 0xFFFFFFFF) {
/* probably invalid handle, do nothing for now */
/* FIXME: case 2573 about adding ASSERT_CURIOSITY replacing the ASSERT we had */
} else if (tid != tr->id) {
priv_mcontext_t mcontext;
DEBUG_DECLARE(thread_synch_result_t synch_res;)
copy_mcontext(mc, &mcontext);
mc->pc = SYSCALL_PC(dcontext);
/* Fixme : issues with cleaning up here, what if syscall fails */
DEBUG_DECLARE(synch_res =)
synch_with_thread(tid, true, false, THREAD_SYNCH_VALID_MCONTEXT,
THREAD_SYNCH_SUSPENDED_AND_CLEANED,
/* if we fail to suspend a thread (e.g., privilege
* problems) ignore it. FIXME: retry instead? */
THREAD_SYNCH_SUSPEND_FAILURE_IGNORE);
ASSERT(synch_res == THREAD_SYNCH_RESULT_SUCCESS ||
/* App could be calling on already exited thread (xref 8125)
* or thread could have exited while we were synching.
* FIXME - check is racy since for dr purposes the thread is
* considered exited just before it is signaled, but is ok
* for an assert. */
is_thread_exited(thread_handle) == THREAD_EXITED ||
!is_pid_me(thread_handle_to_pid(thread_handle, tid)));
copy_mcontext(&mcontext, mc);
} else {
/* case 9347 - racy early thread, yet primary is not yet 'known' */
/* we should evaluate dr_late_injected_primary_thread before
* get_num_threads()
*/
bool secondary = dr_injected_secondary_thread &&
!dr_late_injected_primary_thread;
bool exitproc = !secondary && (is_last_app_thread() && !dynamo_exited);
/* this should really be check_sole_thread() */
/* FIXME: case 9461 - we may not control all threads,
* the syscall may fail and may not be allowed to kill last thread
*/
if (secondary) {
SYSLOG_INTERNAL_WARNING("secondary thread terminating, primary not ready\n");
ASSERT(!exitproc);
ASSERT(!check_sole_thread());
}
ASSERT(!exitproc || check_sole_thread());
KSTOP(pre_syscall);
KSTOP(num_exits_dir_syscall);
os_terminate_wow64_write_args(false/*thread*/, thread_handle, exit_status);
cleanup_and_terminate(dcontext, syscalls[SYS_TerminateThread],
/* r10, which will go to rcx in cleanup_and_terminate
* and back to r10 in global_do_syscall_syscall (i#1901).
*/
IF_X64_ELSE(mc->r10, mc->xdx),
mc->xdx, exitproc, 0, 0);
}
}
/* NtSetContextThread */
static bool
presys_SetContextThread(dcontext_t *dcontext, reg_t *param_base)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE thread_handle = (HANDLE) sys_param(dcontext, param_base, 0);
CONTEXT *cxt = (CONTEXT *) sys_param(dcontext, param_base, 1);
thread_id_t tid = thread_handle_to_tid(thread_handle);
bool intercept = true;
bool execute_syscall = true;
/* FIXME : we are going to read and write to cxt, which may be unsafe */
ASSERT(tid != 0xFFFFFFFF);
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtSetContextThread handle="PFX" tid=%d cxt->Xip="PFX"\n",
thread_handle, tid, cxt->CXT_XIP);
mutex_lock(&thread_initexit_lock); /* need lock to lookup thread */
if (intercept_asynch_for_thread(tid, false/*no unknown threads*/)) {
priv_mcontext_t mcontext;
thread_record_t *tr = thread_lookup(tid);
CONTEXT *my_cxt;
NTSTATUS res;
const thread_synch_state_t desired_state = THREAD_SYNCH_VALID_MCONTEXT;
DEBUG_DECLARE(thread_synch_result_t synch_res;)
ASSERT(tr != NULL);
SELF_PROTECT_LOCAL(tr->dcontext, WRITABLE);
/* now ensure target thread is at a safe point when it gets reset */
copy_mcontext(mc, &mcontext);
mc->pc = SYSCALL_PC(dcontext);
DEBUG_DECLARE(synch_res =)
synch_with_thread(tid, true, true, desired_state,
THREAD_SYNCH_SUSPENDED_VALID_MCONTEXT,
/* if we fail to suspend a thread (e.g., privilege
* problems) ignore it. FIXME: retry instead? */
THREAD_SYNCH_SUSPEND_FAILURE_IGNORE);
ASSERT(synch_res == THREAD_SYNCH_RESULT_SUCCESS);
copy_mcontext(&mcontext, mc);
if (!TESTALL(CONTEXT_CONTROL/*2 bits so ALL*/, cxt->ContextFlags)) {
/* app didn't request pc so we'd better get it now.
* FIXME: this isn't transparent as we have to clobber
* fields in the app cxt: should restore in post-syscall.
*/
char buf[MAX_CONTEXT_SIZE];
CONTEXT *alt_cxt = nt_initialize_context(buf, CONTEXT_DR_STATE);
STATS_INC(num_app_setcontext_no_control);
if (thread_get_context(tr, alt_cxt) &&
translate_context(tr, alt_cxt, true/*set memory*/)) {
LOG(THREAD, LOG_SYSCALLS, 2, "no CONTROL flag on original cxt:\n");
DOLOG(3, LOG_SYSCALLS, { dump_context_info(cxt, THREAD, true); });
cxt->ContextFlags |= CONTEXT_CONTROL;
cxt->CXT_XIP = alt_cxt->CXT_XIP;
cxt->CXT_XFLAGS = alt_cxt->CXT_XFLAGS;
cxt->CXT_XSP = alt_cxt->CXT_XSP;
cxt->CXT_XBP = alt_cxt->CXT_XBP;
IF_X64(ASSERT_NOT_IMPLEMENTED(false)); /* Rbp not part of CONTROL */
cxt->SegCs = alt_cxt->SegCs;
cxt->SegSs = alt_cxt->SegSs;
LOG(THREAD, LOG_SYSCALLS, 3, "changed cxt:\n");
DOLOG(3, LOG_SYSCALLS, { dump_context_info(cxt, THREAD, true); });
/* don't care about other regs -- if app didn't
* specify CONTEXT_INTEGER that's fine
*/
} else {
/* just don't intercept: could crash us in middle of mangled
* sequence once we start translating there and treating them
* as safe spots, but for now will be ok.
*/
intercept = false;
ASSERT_NOT_REACHED();
}
}
if (intercept) {
/* modify the being-set cxt so that we retain control */
intercept_nt_setcontext(tr->dcontext, cxt);
LOG(THREAD, LOG_SYSCALLS, 3, "final cxt passed to syscall:\n");
DOLOG(3, LOG_SYSCALLS, { dump_context_info(cxt, THREAD, true); });
}
/* nt_continue_dynamo_start path assumes target is !couldbelinking
* all synch_with_thread synch points should be, we check here
*/
ASSERT(!is_couldbelinking(tr->dcontext));
if (TEST(THREAD_SET_CONTEXT, nt_get_handle_access_rights(thread_handle))) {
/* Case 10101: a thread waiting at check_wait_at_safe_spot can't
* be directly setcontext-ed so we explicitly do the context
* set request here and skip the system call.
* A waiting thread does NtContinue and so bypasses permission issues,
* so we explicitly check for setcontext permission.
* We have to make a copy since the app could de-allocate or modify
* cxt before a waiting thread examines it.
*/
DEBUG_DECLARE(bool ok;)
#ifdef X64
/* PR 263338: we need to align to 16 on x64. Heap is 8-byte aligned. */
byte *cxt_alloc;
#endif
my_cxt = global_heap_alloc(CONTEXT_HEAP_SIZE(*my_cxt) HEAPACCT(ACCT_OTHER));
#ifdef X64
cxt_alloc = (byte *) cxt;
if (!ALIGNED(my_cxt, 16)) {
ASSERT(ALIGNED(my_cxt, 8));
my_cxt = (CONTEXT *) ( ((app_pc)my_cxt)+8 );
}
ASSERT(ALIGNED(my_cxt, 16));
#endif
*my_cxt = *cxt;
/* my_cxt is freed by set_synched_thread_context() or target thread */
DEBUG_DECLARE(ok = )
set_synched_thread_context(tr, NULL, (void *) my_cxt,
CONTEXT_HEAP_SIZE(*my_cxt), desired_state
_IF_X64(cxt_alloc) _IF_WINDOWS(&res));
/* We just tested permissions, but could be bad handle, etc.
* FIXME: if so and thread was waiting we have transparency violation
*/
ASSERT_CURIOSITY(ok);
SET_RETURN_VAL(tr->dcontext, res);
/* must wake up thread so it can go to nt_continue_dynamo_start */
nt_thread_resume(tr->handle, NULL);
execute_syscall = false;
} else {
/* we expect the system call to fail */
DODEBUG({ tr->dcontext->expect_last_syscall_to_fail = true; });
}
SELF_PROTECT_LOCAL(tr->dcontext, READONLY);
}
mutex_unlock(&thread_initexit_lock);
return execute_syscall;
}
/* Assumes mc is app state prior to system call.
* Returns true iff system call is a callback return that does transfer control
* (xref case 10579).
*/
bool
is_cb_return_syscall(dcontext_t *dcontext)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
if (mc->xax == (reg_t) syscalls[SYS_CallbackReturn]) {
reg_t *param_base = pre_system_call_param_base(mc);
if ((NTSTATUS)sys_param(dcontext, param_base, 2) != STATUS_CALLBACK_POP_STACK)
return true;
}
return false;
}
/* NtCallbackReturn */
static void
presys_CallbackReturn(dcontext_t *dcontext, reg_t *param_base)
{
/* args are:
* IN PVOID Result OPTIONAL, IN ULONG ResultLength, IN NTSTATUS Status
* same args go to int 2b (my theory anyway), where they are passed in
* eax, ecx, and edx. if KiUserCallbackDispatcher returns, it leaves
* eax w/ result value of callback, and zeros out ecx and edx, then int 2b.
* people doing the int 2b in user32 set ecx and edx to what they want, then
* call a routine that simply pulls first arg into eax and then does int 2b.
*/
priv_mcontext_t *mc = get_mcontext(dcontext);
NTSTATUS status = (NTSTATUS) sys_param(dcontext, param_base, 2);
if (status == STATUS_CALLBACK_POP_STACK) {
/* case 10579: this status code instructs the kernel to only
* pop the stack and not transfer control there */
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtCallbackReturn STATUS_CALLBACK_POP_STACK\n");
} else {
/* NtCallbackReturn returns from callback via a syscall, and it
* requires us to restore the prev dcontext immediately prior
* to the syscall (want to use current dcontext in prior instructions
* in shared_syscall).
* N.B.: this means that the return from the call to pre_system_call
* uses a different dcontext than the setup for the call!
* the popa and popf will be ok -- old dstack is still in esp, isn't
* restored, isn't deleted by swapping to new dcontext.
* The problem is the restore of the app's esp -- so we fix that by
* having the clean call to pre_system_call store and restore app's esp
* from a special nonswapped dcontext slot.
*/
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtCallbackReturn\n");
callback_start_return(mc);
}
}
static void
check_for_stack_free(dcontext_t *dcontext, byte *base, size_t size)
{
/* Ref case 5518 - on some versions of windows the thread stack is freed
* in process. So we watch here for the free to keep from removing again
* at thread exit. */
os_thread_data_t *ostd = (os_thread_data_t *) dcontext->os_field;
ASSERT(dcontext == get_thread_private_dcontext());
if (base == ostd->stack_base) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"Thread's os stack is being freed\n");
ASSERT(base + size == ostd->stack_top);
/* only seen the in process free on 2k and NT */
ASSERT_CURIOSITY(get_os_version() <= WINDOWS_VERSION_2000);
/* When we've seen it happen (in kernel32!ExitThread), ExitThread uses
* a chunk of the TEB as the stack while freeing and calling
* NtTerminate. */
ASSERT_CURIOSITY((byte *)get_mcontext(dcontext)->xsp >=
(byte *)get_own_teb() &&
(byte *)get_mcontext(dcontext)->xsp <
((byte *)get_own_teb()) + PAGE_SIZE);
/* FIXME - Instead of saying the teb stack is no longer valid, we could
* instead change the bounds to be the TEB region. Other users could
* then always we assert we have something valid set. Is slightly
* greater dependence on observed behavior though. */
ostd->teb_stack_no_longer_valid = true;
ostd->stack_base = NULL;
ostd->stack_top = NULL;
}
}
/* NtAllocateVirtualMemory */
static bool
presys_AllocateVirtualMemory(dcontext_t *dcontext, reg_t *param_base, int sysnum)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE process_handle = (HANDLE) sys_param(dcontext, param_base, 0);
void **pbase = (void **) sys_param(dcontext, param_base, 1);
/* XXX i#899: NtWow64AllocateVirtualMemory64 has an extra arg after ZeroBits but
* it's ignored in wow64!whNtWow64AllocateVirtualMemory64. We should keep an eye
* out: maybe a future service pack or win9 will use it.
*/
int arg_shift = (sysnum == syscalls[SYS_Wow64AllocateVirtualMemory64] ? 1 : 0);
size_t *psize = (size_t *) sys_param(dcontext, param_base, 3 + arg_shift);
uint type = (uint) sys_param(dcontext, param_base, 4 + arg_shift);
uint prot = (uint) sys_param(dcontext, param_base, 5 + arg_shift);
app_pc base;
if (is_phandle_me(process_handle) && TEST(MEM_COMMIT, type) &&
/* Any overlap when asking for MEM_RESERVE (even when combined w/ MEM_COMMIT)
* will fail anyway, so we only have to worry about overlap on plain MEM_COMMIT
*/
!TEST(MEM_RESERVE, type)) {
/* i#1175: NtAllocateVirtualMemory can modify prot on existing pages */
size_t size;
if (safe_read(pbase, sizeof(base), &base) &&
safe_read(psize, sizeof(size), &size) &&
base != NULL &&
!app_memory_pre_alloc(dcontext, base, size, osprot_to_memprot(prot), false)) {
SET_RETURN_VAL(dcontext, STATUS_CONFLICTING_ADDRESSES);
return false; /* do not execute system call */
}
}
#ifdef PROGRAM_SHEPHERDING
if (is_phandle_me(process_handle) && TEST(MEM_COMMIT, type) &&
TESTALL(PAGE_EXECUTE_READWRITE, prot)) {
/* executable_if_alloc policy says we only add a region to the future
* list if it is committed rwx with no prior reservation.
* - if a base is passed and MEM_RESERVE is not set, there must be a prior
* reservation
* - if a base is passed and MEM_RESERVE is set, do a query to see if
* reservation existed before
* - if no base is passed, there was no reservation
*/
/* unfortunately no way to avoid syscall to check readability
* (unless have try...except)
*/
if (safe_read(pbase, sizeof(base), &base)) {
dcontext->alloc_no_reserve =
(base == NULL ||
(TEST(MEM_RESERVE, type) && !get_memory_info(base, NULL, NULL, NULL)));
/* FIXME: can one MEM_RESERVE an address previously
* MEM_RESERVEd - at least on XP that's not allowed */
}
} else if (TEST(ASLR_STACK, DYNAMO_OPTION(aslr)) &&
!is_phandle_me(process_handle) &&
TEST(MEM_RESERVE, type)
&& is_newly_created_process(process_handle)) {
/* pre-processing of remote NtAllocateVirtualMemory reservation */
/* Case 9173: ignore allocations with a requested base. These may come
* after we've inserted our pad (is_newly_created_process() isn't
* perfect), but may also come before, and we do not want to cause
* interop issues. We could instead try to adjust our pad to not cause
* their alloc to fail, but may end up eliminating any security
* advantage anyway.
*/
if (safe_read(pbase, sizeof(base), &base)) {
if (base == NULL) {
/* FIXME: make the above check stronger */
ASSERT_CURIOSITY(prot == PAGE_READWRITE);
/* this is just a reservation, so can be anything */
/* currently not following child flags, so maybe is almost always */
/* NOTE - on vista we should only ever get here if someone is using
* the legacy NtCreateProcess native api (vs NtCreateUserProcess) or
* the app is injecting memory into a new process before it's started
* initializing itself. */
ASSERT_CURIOSITY(get_os_version() < WINDOWS_VERSION_VISTA);
aslr_maybe_pad_stack(dcontext, process_handle);
} else {
DODEBUG({
if (process_id_from_handle(process_handle) !=
dcontext->aslr_context.last_child_padded) {
SYSLOG_INTERNAL_WARNING_ONCE("aslr stack: allowing alloc prior "
"to pad");
}
});
}
}
}
#endif /* PROGRAM_SHEPHERDING */
return true;
}
/* NtFreeVirtualMemory */
static void
presys_FreeVirtualMemory(dcontext_t *dcontext, reg_t *param_base)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE process_handle = (HANDLE) sys_param(dcontext, param_base, 0);
void **pbase = (void **) sys_param(dcontext, param_base, 1);
size_t *psize = (size_t *) sys_param(dcontext, param_base, 2);
uint type = (uint) sys_param(dcontext, param_base, 3);
app_pc base;
size_t size;
/* check for common argument problems, apps tend to screw this call
* up a lot (who cares about a memory leak, esp. at process exit) */
/* ref case 3536, 545, 4046 */
if (!safe_read(pbase, sizeof(base), &base) || base == NULL ||
!safe_read(psize, sizeof(size), &size) ||
!(type == MEM_RELEASE || type == MEM_DECOMMIT)) {
/* we expect the system call to fail */
DODEBUG(dcontext->expect_last_syscall_to_fail = true;);
return;
}
if (!is_phandle_me(process_handle)) {
IPC_ALERT("ERROR: FreeVirtualMemory %s "PFX" "PIFX" on another process",
type == MEM_DECOMMIT ? "MEM_DECOMMIT" : "MEM_RELEASE",
base, size);
return;
}
if ((type == MEM_DECOMMIT && size == 0) || (type == MEM_RELEASE)) {
app_pc real_base;
/* whole region being freed, we must look up size, ignore psize
* msdn and Nebbet claim that you need *psize == 0 for MEM_RELEASE
* but that doesn't seem to be true on all platforms */
/* 2K+: if base is anywhere on the first page of region this succeeds,
* and doesn't otherwise.
* NT: base must be the actual base.
*/
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"syscall: NtFreeVirtualMemory type=%s region base="PFX" size="PIFX"\n",
type == MEM_DECOMMIT ? "MEM_DECOMMIT" : "MEM_RELEASE",
base, size);
size = get_allocation_size(base, &real_base);
ASSERT(ALIGNED(real_base, PAGE_SIZE));
/* if region has been already been freed */
if (((app_pc) ALIGN_BACKWARD(base, PAGE_SIZE) != real_base) ||
(get_os_version() == WINDOWS_VERSION_NT && base != real_base)) {
/* we expect the system call to fail
* with (NTSTATUS) 0xc000009f -
* "Virtual memory cannot be freed as base address is not
* the base of the region and a region size of zero was
* specified"
*/
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"syscall: NtFreeVirtualMemory base="PFX", size="PIFX" invalid base\n",
base, size);
DODEBUG(dcontext->expect_last_syscall_to_fail = true;);
return;
}
/* make sure we use correct region base address, */
/* otherwise we'll free an extra page */
base = real_base;
ASSERT(real_base != NULL && "already freed");
}
DODEBUG({
/* FIXME: this shouldn't be DODEBUG since we need to handle syscall failure */
if (type == MEM_DECOMMIT && size != 0) {
size_t real_size = get_allocation_size(base, NULL);
if ((app_pc)ALIGN_BACKWARD(base, PAGE_SIZE) + real_size < base + size) {
/* we expect the system call to fail with
* (NTSTATUS) 0xc000001a - "Virtual memory cannot be freed."
*/
DODEBUG(dcontext->expect_last_syscall_to_fail = true;);
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"syscall: NtFreeVirtualMemory base="PFX", size="PIFX
" too large should fail \n", base, size);
return;
}
}
});
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"syscall: NtFreeVirtualMemory base="PFX" size="PIFX"\n",
base, size);
DOLOG(1, LOG_SYSCALLS|LOG_VMAREAS, {
char buf[MAXIMUM_PATH];
get_module_name(base, buf, sizeof(buf));
if (buf[0] != '\0') {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"\tNtFreeVirtualMemory called on module %s\n", buf);
ASSERT_CURIOSITY(false && "NtFreeVirtualMemory called on module");
/* should switch to PE name and then can do this at loglevel 0 */
}
});
DOLOG(1, LOG_MEMSTATS, {
/* snapshots are heavyweight, so do rarely */
if (size > SNAPSHOT_THRESHOLD)
mem_stats_snapshot();
});
align_page_boundary(dcontext, &base, &size);
ASSERT_BUG_NUM(4511, ALIGNED(base, PAGE_SIZE) && ALIGNED(size, PAGE_SIZE));
/* ref case 5518 - we need to keep track if the thread stack is freed */
if (type == MEM_RELEASE) {
check_for_stack_free(dcontext, base, size);
}
if (type == MEM_RELEASE &&
TEST(ASLR_HEAP_FILL, DYNAMO_OPTION(aslr))) {
/* We free our allocation before the application
* reservation is released. Not a critical failure if the
* application free fails but we have freed our pad. Also
* avoids fragmentation if a racy allocation.
*/
aslr_pre_process_free_virtual_memory(dcontext, base, size);
/* note we handle the untracked stack free in
* os_thread_stack_exit() */
}
app_memory_deallocation(dcontext, base, size,
false /* don't own thread_initexit_lock */,
false /* not image */);
}
/* NtProtectVirtualMemory */
static bool /* returns whether to execute syscall */
presys_ProtectVirtualMemory(dcontext_t *dcontext, reg_t *param_base)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE process_handle = (HANDLE) sys_param(dcontext, param_base, 0);
void **pbase = (void **) sys_param(dcontext, param_base, 1);
size_t *psize = (size_t *) sys_param(dcontext, param_base, 2);
uint prot = (uint) sys_param(dcontext, param_base, 3);
uint *oldprot = (uint *) sys_param(dcontext, param_base, 4);
app_pc base;
size_t size;
uint old_memprot = MEMPROT_NONE; /* for SUBSET_APP_MEM_PROT_CHANGE
* or PRETEND_APP_MEM_PROT_CHANGE */
uint subset_memprot = MEMPROT_NONE; /* for SUBSET_APP_MEM_PROT_CHANGE */
if (!safe_read(pbase, sizeof(base), &base) ||
!safe_read(psize, sizeof(size), &size)) {
/* we expect the system call to fail */
DODEBUG(dcontext->expect_last_syscall_to_fail = true;);
return true;
}
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"syscall: NtProtectVirtualMemory process="PFX" base="PFX" size="
PIFX" prot=%s 0x%x\n", process_handle, base, size, prot_string(prot), prot);
if (is_phandle_me(process_handle)) {
uint res;
/* go to page boundaries, since windows lets you pass non-aligned
* values, unlike Linux
*/
/* FIXME: use align_page_boundary(dcontext, &base, &size) instead */
if (!ALIGNED(base, PAGE_SIZE) || !ALIGNED(base+size, PAGE_SIZE)) {
/* need to cover all pages between base and base + size */
size = ALIGN_FORWARD(base+size, PAGE_SIZE) - PAGE_START(base);
base = (app_pc) PAGE_START(base);
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"\tpage boundaries => base="PFX" size="PIFX"\n", base, size);
}
DOLOG(1, LOG_SYSCALLS|LOG_VMAREAS, {
char module_name[MAX_MODNAME_INTERNAL];
if (os_get_module_name_buf(base, module_name,
BUFFER_SIZE_ELEMENTS(module_name)) > 0) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"\tNtProtectVirtualMemory called on module %s\n", module_name);
}
});
#ifdef DGC_DIAGNOSTICS
DOLOG(1, LOG_VMAREAS, {
dump_callstack(POST_SYSCALL_PC(dcontext),
(app_pc) mc->xbp, THREAD,
DUMP_NOT_XML);
});
#endif
res = app_memory_protection_change(dcontext, base, size,
osprot_to_memprot(prot),
&subset_memprot,
&old_memprot);
if (res != DO_APP_MEM_PROT_CHANGE) {
/* from experimentation it seems to return
* STATUS_CONFLICTING_ADDRESSES
* rather than STATUS_NOT_COMMITTED for invalid memory
*/
if (res == FAIL_APP_MEM_PROT_CHANGE) {
SET_RETURN_VAL(dcontext, STATUS_CONFLICTING_ADDRESSES);
} else if (res == PRETEND_APP_MEM_PROT_CHANGE ||
res == SUBSET_APP_MEM_PROT_CHANGE) {
/*
* FIXME: is alternative of letting it go through and undoing in
* post-handler simpler and safer (here we have to emulate kernel
* behavior), if we remove +w flag to avoid other-thread issues?
*/
uint pretend_oldprot;
uint old_osprot = PAGE_NOACCESS;
SET_RETURN_VAL(dcontext, STATUS_SUCCESS);
if (res == SUBSET_APP_MEM_PROT_CHANGE) {
uint subset_osprot =
osprot_replace_memprot(prot, subset_memprot);
/* we explicitly make our system call. Although in this
* case we could change the application arguments as
* well, in general it is not nice to the application
* to change IN arguments.
*/
bool ok =
nt_remote_protect_virtual_memory(process_handle,
base, size,
subset_osprot, &old_osprot);
/* using app's handle in case it has different rights that current thread */
ASSERT_CURIOSITY(process_handle == NT_CURRENT_PROCESS);
ASSERT_CURIOSITY(ok);
/* we'll keep going anyways as if it would have worked */
} else {
ASSERT_NOT_TESTED();
ASSERT(res == PRETEND_APP_MEM_PROT_CHANGE);
/* pretend it worked but don't execute system call */
old_osprot = get_current_protection(base);
}
/* Today we base on the current actual flags
* (old_osprot), and preserve WRITECOPY and other
* unlikely original flags.
*
* We should be using our value for what the correct
* view of the application memory should be. case
* 10437 we should be able to transparently carry the
* original protection flags across multiple calls to
* NtProtectVirtualMemory.
*/
pretend_oldprot = osprot_replace_memprot(old_osprot,
old_memprot);
/* have to set OUT vars properly */
/* size and base were already aligned up above */
ASSERT(ALIGNED(size, PAGE_SIZE));
ASSERT(ALIGNED(base, PAGE_SIZE));
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"skipping NtProtectVirtualMemory, returning base="PFX", size="
PIFX", oldprot=%s 0x%x\n",
base, size, prot_string(pretend_oldprot), pretend_oldprot);
/* FIXME: we really should be _probing_ these writes
* to make sure not targeting DR addresses when
* PROTECT_FROM_APP
*/
safe_write(oldprot, sizeof(pretend_oldprot), &pretend_oldprot);
safe_write(pbase, sizeof(base), &base);
safe_write(psize, sizeof(size), &size);
} else {
ASSERT_NOT_REACHED();
}
return false; /* do not execute system call */
} else {
/* FIXME i#143: we still need to tweak the returned oldprot (in
* post-syscall) for writable areas we've made read-only
*/
/* FIXME: ASSERT here that have not modified size unless using, e.g. fix_unsafe_hooker */
}
} else {
/* FIXME: should we try to alert any dynamo running the other process?
*/
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"WARNING: ProtectVirtualMemory called on process "PFX" %d\n",
process_handle, process_id_from_handle(process_handle));
/* this actually happens (e.g., in calc.exe's winhlp popups)
* so don't die here with IPC_ALERT
*/
}
return true;
}
/* NtMapViewOfSection */
static bool
presys_MapViewOfSection(dcontext_t *dcontext, reg_t *param_base)
{
bool execute = true;
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE section_handle = (HANDLE) sys_param(dcontext, param_base, 0);
/* trying to make sure we're tracking properly all section
* handles
*
* Unfortunately SHELL32!SHChangeRegistration_Create seems
* to be using sections to communicate with explorer.exe
* and sends a message via sending a duplicate section
* handle, and likely receives a message back in a
* similarly duplicated handle from the other process.
* Hard to match that particular call so cannot keep a
* CURIOSITY here.
*
* Note we also wouldn't like some global handle being used by
* different threads as well, or any other unusually nested
* use of NtCreateSection/NtOpenSection before NtMapViewOfSection.
*
* For non-image sections accessed via OpenSection rather than CreateSection,
* we do NOT have the file name here, but we can get it once we have a mapping
* via MemorySectionName: plus we don't care about non-images. But, we don't
* have a test for image here, so we leave this LOG note.
*/
const char *file = section_to_file_lookup(section_handle);
if (file != NULL) {
/* we should be able to block loads even in unknown threads */
if (DYNAMO_OPTION(enable_block_mod_load) &&
(!IS_STRING_OPTION_EMPTY(block_mod_load_list) ||
!IS_STRING_OPTION_EMPTY(block_mod_load_list_default))) {
const char *short_name = get_short_name(file);
string_option_read_lock();
if ((!IS_STRING_OPTION_EMPTY(block_mod_load_list) &&
check_filter(DYNAMO_OPTION(block_mod_load_list), short_name)) ||
(!IS_STRING_OPTION_EMPTY(block_mod_load_list_default) &&
check_filter(DYNAMO_OPTION(block_mod_load_list_default),
short_name))) {
string_option_read_unlock();
/* Modify args so call fails, stdcall so caller shouldn't care
* about the args being modified. FIXME - alt. we could just
* do the stdcall ret here (for non-takeover need to supply
* a dr location with a ret 4 instruction at hook time and
* return alt_dyn here, for takeover need to modify the
* interception code or pass a flag to asynch_takeover/dispath
* to modify the app state) */
LOG(GLOBAL, LOG_ALL, 1, "Blocking load of module %s\n", file);
SYSLOG_INTERNAL_WARNING_ONCE("Blocking load of module %s", file);
execute = false;
SET_RETURN_VAL(dcontext, STATUS_ACCESS_DENIED);
/* With failure we shouldn't have to set any of the out vals */
} else {
string_option_read_unlock();
}
}
dr_strfree(file HEAPACCT(ACCT_VMAREAS));
} else if (section_handle != dcontext->aslr_context.randomized_section_handle) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS,
2, "syscall: NtMapViewOfSection unusual section mapping\n");
}
if (TESTANY(ASLR_DLL|ASLR_MAPPED, DYNAMO_OPTION(aslr))) {
aslr_pre_process_mapview(dcontext);
}
return execute;
}
/* NtUnmapViewOfSection{,Ex} */
static void
presys_UnmapViewOfSection(dcontext_t *dcontext, reg_t *param_base, int sysnum)
{
/* This is what actually removes a dll from memory */
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE process_handle = (HANDLE) sys_param(dcontext, param_base, 0);
app_pc base = (app_pc) sys_param(dcontext, param_base, 1);
app_pc real_base;
size_t size = get_allocation_size(base, &real_base);
MEMORY_BASIC_INFORMATION mbi;
if (sysnum == syscalls[SYS_UnmapViewOfSectionEx]) {
ptr_int_t arg3 = (ptr_int_t) sys_param(dcontext, param_base, 2);
/* FIXME i#899: new Win8 syscall w/ 3rd arg that's 0 by default.
* We want to know when we see non-zero so we have some code to study.
*/
ASSERT_CURIOSITY(arg3 == 0 && "i#899: unknown new param");
}
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"syscall: NtUnmapViewOfSection "PFX" size="PIFX"\n", base, size);
if (!is_phandle_me(process_handle)) {
IPC_ALERT("ERROR: UnmapViewOfSection on another process");
return;
}
/* check for args we expect to fail, ref case 545, 3697, on east coast
* xp server shell32 dllmain process attach calls kernel32
* CreateActCtxW which ends up calling this with an unaligned pointer
* into private memory (which is suspicously just a few bytes under
* the base address of a recently freed mapped region) */
/* Don't worry about the query_virtual_memory cost, we are already
* doing a ton of them for the get_allocation_size and process_mmap
* calls */
if (query_virtual_memory(base, &mbi, sizeof(mbi)) != sizeof(mbi) ||
(mbi.Type != MEM_IMAGE && mbi.Type != MEM_MAPPED)) {
DODEBUG(dcontext->expect_last_syscall_to_fail = true;);
return;
}
/* people don't always call with the actual base address (see east
* coast xp server (sp1) whose uxtheme.dll CThemeSignature::
* CalculateHash always calls this with base+0x130, is hardcoded in
* the assembly). OS doesn't seem to care as the syscall still
* succeeds. */
if (base != mbi.AllocationBase) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"syscall: NtUnmapViewOfSection real base is "PFX"\n",
mbi.AllocationBase);
base = mbi.AllocationBase;
}
DOLOG(1, LOG_MEMSTATS, {
/* snapshots are heavyweight, so do rarely */
if (size > SNAPSHOT_THRESHOLD)
mem_stats_snapshot();
});
RSTATS_INC(num_app_munmaps);
/* we have to mark before any policy processing gets started */
/* FIXME: we could also allow MEM_MAPPED areas here, since .B
* policies may in fact allow such to be executable areas, but
* since we can keep track of only one, focusing on MEM_IMAGE only
*/
if (DYNAMO_OPTION(unloaded_target_exception) &&
mbi.Type == MEM_IMAGE) {
mark_unload_start(base, size);
}
if (TESTANY(ASLR_DLL|ASLR_MAPPED, DYNAMO_OPTION(aslr))) {
aslr_pre_process_unmapview(dcontext, base, size);
}
process_mmap(dcontext, base, size, false/*unmap*/, NULL);
}
/* NtFlushInstructionCache */
static void
presys_FlushInstructionCache(dcontext_t *dcontext, reg_t *param_base)
{
/* This syscall is from the days when Windows ran on multiple
* architectures, but many apps still use it
*/
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE process_handle = (HANDLE) sys_param(dcontext, param_base, 0);
app_pc base = (app_pc) sys_param(dcontext, param_base, 1);
size_t size = (size_t) sys_param(dcontext, param_base, 2);
#ifdef PROGRAM_SHEPHERDING
uint prot;
#endif
/* base can be NULL, in which case size is meaningless
* loader calls w/ NULL & 0 on rebasing -- means entire icache?
*/
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"syscall: NtFlushInstructionCache "PFX" size="PIFX"\n", base, size);
if (base == NULL)
return;
if (is_phandle_me(process_handle)) {
#ifdef DGC_DIAGNOSTICS
DOLOG(1, LOG_VMAREAS, {
dump_callstack(POST_SYSCALL_PC(dcontext),
(app_pc) mc->xbp, THREAD,
DUMP_NOT_XML);
});
#endif
#ifdef PROGRAM_SHEPHERDING
prot = osprot_to_memprot(get_current_protection(base));
app_memory_flush(dcontext, base, size, prot);
#endif
} else {
/* FIXME: should we try to alert any dynamo running the other process?
* no reason to ASSERT here, not critical like alloc/dealloc in other process
*/
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"WARNING: NtFlushInstructionCache on another process\n");
}
}
/* NtCreateSection */
static void
presys_CreateSection(dcontext_t *dcontext, reg_t *param_base)
{
/* a section is an object that can be mmapped */
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE *section_handle = (HANDLE*) sys_param(dcontext, param_base, 0);
uint access_mask = (uint) sys_param(dcontext, param_base, 1);
POBJECT_ATTRIBUTES obj = (POBJECT_ATTRIBUTES) sys_param(dcontext, param_base, 2);
void *size = (void *) sys_param(dcontext, param_base, 3);
uint protect = (uint) sys_param(dcontext, param_base, 4);
uint attributes = (uint) sys_param(dcontext, param_base, 5);
HANDLE file_handle = (HANDLE) sys_param(dcontext, param_base, 6);
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtCreateSection protect 0x%x, attributes 0x%x, file "PIFX"\n",
protect, attributes, file_handle);
DODEBUG({
if (obj != NULL && obj->ObjectName != NULL) {
DEBUG_DECLARE(char buf[MAXIMUM_PATH];)
/* convert name from unicode to ansi */
wchar_t *name = obj->ObjectName->Buffer;
_snprintf(buf, BUFFER_SIZE_ELEMENTS(buf), "%S", name);
NULL_TERMINATE_BUFFER(buf);
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtCreateSection %s\n", buf);
} else {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtCreateSection\n");
}
});
}
/* NtClose */
static void
presys_Close(dcontext_t *dcontext, reg_t *param_base)
{
HANDLE handle = (HANDLE) sys_param(dcontext, param_base, 0);
if (DYNAMO_OPTION(track_module_filenames)) {
if (section_to_file_remove(handle)) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtClose of section handle "PFX"\n", handle);
}
}
if (handle_to_tid_remove(handle)) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtClose of thread handle "PFX"\n", handle);
}
}
#ifdef DEBUG
/* NtOpenFile */
static void
presys_OpenFile(dcontext_t *dcontext, reg_t *param_base)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE *file_handle = (HANDLE*) sys_param(dcontext, param_base, 0);
uint access_mask = (uint) sys_param(dcontext, param_base, 1);
POBJECT_ATTRIBUTES obj = (POBJECT_ATTRIBUTES) sys_param(dcontext, param_base, 2);
void *status = (void *) sys_param(dcontext, param_base, 3);
uint share = (uint) sys_param(dcontext, param_base, 4);
uint options = (uint) sys_param(dcontext, param_base, 5);
if (obj != NULL) {
/* convert name from unicode to ansi */
char buf[MAXIMUM_PATH];
wchar_t *name = obj->ObjectName->Buffer;
/* not always null-terminated */
_snprintf(buf, MIN(obj->ObjectName->Length/sizeof(obj->ObjectName->Buffer[0]),
BUFFER_SIZE_ELEMENTS(buf)),
"%S", name);
NULL_TERMINATE_BUFFER(buf);
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtOpenFile %s\n", buf);
} else {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtOpenFile\n");
}
}
#endif
int
os_normalized_sysnum(int num_raw, instr_t *gateway, dcontext_t *dcontext_live)
{
return num_raw;
}
/* WARNING: flush_fragments_and_remove_region assumes that pre and post system
* call handlers do not examine or modify fcache or its fragments in any
* way except for calling flush_fragments_and_remove_region!
*/
bool
pre_system_call(dcontext_t *dcontext)
{
bool execute_syscall = true;
priv_mcontext_t *mc = get_mcontext(dcontext);
int sysnum = (int) mc->xax;
reg_t *param_base = pre_system_call_param_base(mc);
where_am_i_t old_whereami = dcontext->whereami;
dcontext->whereami = WHERE_SYSCALL_HANDLER;
IF_X64(ASSERT_TRUNCATE(sysnum, int, mc->xax));
DODEBUG(dcontext->expect_last_syscall_to_fail = false;);
KSTART(pre_syscall);
RSTATS_INC(pre_syscall);
DOSTATS({
if (ignorable_system_call(sysnum, NULL, dcontext))
STATS_INC(pre_syscall_ignorable);
});
LOG(THREAD, LOG_SYSCALLS, 2, "system call: sysnum = "PFX", param_base = "PFX"\n",
sysnum, param_base);
#ifdef DEBUG
DOLOG(2, LOG_SYSCALLS, {
dump_mcontext(mc, THREAD, false/*not xml*/);
});
/* we can't pass other than a numeric literal anymore */
LOG(THREAD, LOG_SYSCALLS, 3, "\tparam 0: "PFX"\n", sys_param(dcontext, param_base, 0));
LOG(THREAD, LOG_SYSCALLS, 3, "\tparam 1: "PFX"\n", sys_param(dcontext, param_base, 1));
LOG(THREAD, LOG_SYSCALLS, 3, "\tparam 2: "PFX"\n", sys_param(dcontext, param_base, 2));
LOG(THREAD, LOG_SYSCALLS, 3, "\tparam 3: "PFX"\n", sys_param(dcontext, param_base, 3));
LOG(THREAD, LOG_SYSCALLS, 3, "\tparam 4: "PFX"\n", sys_param(dcontext, param_base, 4));
LOG(THREAD, LOG_SYSCALLS, 3, "\tparam 5: "PFX"\n", sys_param(dcontext, param_base, 5));
LOG(THREAD, LOG_SYSCALLS, 3, "\tparam 6: "PFX"\n", sys_param(dcontext, param_base, 6));
LOG(THREAD, LOG_SYSCALLS, 3, "\tparam 7: "PFX"\n", sys_param(dcontext, param_base, 7));
LOG(THREAD, LOG_SYSCALLS, 3, "\tparam 8: "PFX"\n", sys_param(dcontext, param_base, 8));
DOLOG(3, LOG_SYSCALLS, {
/* ebp isn't in mcontext right now, so pass ebp */
dump_callstack(POST_SYSCALL_PC(dcontext), (app_pc) mc->xbp, THREAD,
DUMP_NOT_XML);
});
#endif
/* save key register values for post_system_call (they get clobbered
* in syscall itself)
* FIXME: our new stateless asynch handling means that these values
* are wrong when we finally return to an interrupted syscall, so post-processing
* looks at the wrong system call!
* Fortunately it always looks at NtContinue, and we haven't yet implemented
* NtContinue failure
* We need fields analogous to asynch_target: asynch_sys_num and
* asynch_param_base. Unlike callbacks only one outstanding return-to point
* can exist. Let's do this when we go and make our syscall failure handling
* more robust. (This is case 1501)
*/
dcontext->sys_num = sysnum;
dcontext->sys_param_base = param_base;
#ifdef X64
/* save params that are in registers */
dcontext->sys_param0 = sys_param(dcontext, param_base, 0);
dcontext->sys_param1 = sys_param(dcontext, param_base, 1);
dcontext->sys_param2 = sys_param(dcontext, param_base, 2);
dcontext->sys_param3 = sys_param(dcontext, param_base, 3);
#endif
if (sysnum == syscalls[SYS_Continue]) {
CONTEXT *cxt = (CONTEXT *) sys_param(dcontext, param_base, 0);
/* FIXME : we are going to read and write to cxt, which may be unsafe */
int flag = (int) sys_param(dcontext, param_base, 1);
LOG(THREAD, LOG_SYSCALLS|LOG_ASYNCH, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtContinue cxt->Xip="PFX" flag="PFX"\n",
cxt->CXT_XIP, flag);
intercept_nt_continue(cxt, flag);
}
else if (sysnum == syscalls[SYS_CallbackReturn]) {
presys_CallbackReturn(dcontext, param_base);
}
else if (sysnum == syscalls[SYS_SetContextThread]) {
execute_syscall = presys_SetContextThread(dcontext, param_base);
}
else if (sysnum == syscalls[SYS_CreateProcess]) {
presys_CreateProcess(dcontext, param_base, false/*!Ex*/);
}
else if (sysnum == syscalls[SYS_CreateProcessEx]) {
presys_CreateProcess(dcontext, param_base, true/*Ex*/);
}
#ifdef DEBUG
else if (sysnum == syscalls[SYS_CreateUserProcess]) {
presys_CreateUserProcess(dcontext, param_base);
}
#endif
else if (sysnum == syscalls[SYS_CreateThread]) {
presys_CreateThread(dcontext, param_base);
}
else if (sysnum == syscalls[SYS_CreateThreadEx]) {
presys_CreateThreadEx(dcontext, param_base);
}
else if (sysnum == syscalls[SYS_CreateWorkerFactory]) {
presys_CreateWorkerFactory(dcontext, param_base);
}
else if (sysnum == syscalls[SYS_SuspendThread]) {
HANDLE thread_handle= (HANDLE) sys_param(dcontext, param_base, 0);
thread_id_t tid = thread_handle_to_tid(thread_handle);
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtSuspendThread tid=%d\n", tid);
if (SELF_PROTECT_ON_CXT_SWITCH) {
/* This thread must make it back out of the cache for post-syscall
* processing, regardless of what locks target thread holds at
* suspension point, so we have to turn off our cxt switch hooks
* (see case 4942)
*/
dcontext->ignore_enterexit = true;
}
}
else if (sysnum == syscalls[SYS_ResumeThread]) {
presys_ResumeThread(dcontext, param_base);
}
#ifdef DEBUG
else if (sysnum == syscalls[SYS_AlertResumeThread]) {
HANDLE thread_handle= (HANDLE) sys_param(dcontext, param_base, 0);
thread_id_t tid = thread_handle_to_tid(thread_handle);
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtAlertResumeThread tid=%d\n", tid);
}
#endif
else if (sysnum == syscalls[SYS_TerminateProcess]) {
execute_syscall = presys_TerminateProcess(dcontext, param_base);
}
else if (sysnum == syscalls[SYS_TerminateThread]) {
presys_TerminateThread(dcontext, param_base);
}
else if (sysnum == syscalls[SYS_AllocateVirtualMemory] ||
/* i#899: new win8 syscall w/ similar params to NtAllocateVirtualMemory */
sysnum == syscalls[SYS_Wow64AllocateVirtualMemory64]) {
execute_syscall = presys_AllocateVirtualMemory(dcontext, param_base, sysnum);
}
else if (sysnum == syscalls[SYS_FreeVirtualMemory]) {
KSTART(pre_syscall_free);
presys_FreeVirtualMemory(dcontext, param_base);
KSTOP(pre_syscall_free);
}
else if (sysnum == syscalls[SYS_ProtectVirtualMemory]) {
KSTART(pre_syscall_protect);
execute_syscall = presys_ProtectVirtualMemory(dcontext, param_base);
KSTOP(pre_syscall_protect);
}
else if (sysnum == syscalls[SYS_WriteVirtualMemory]) {
/* FIXME NYI: case 8321: need to watch for cache consistency
* FIXME case 9103: note that we don't hook this for native_exec yet
*/
}
else if (sysnum == syscalls[SYS_MapViewOfSection]) {
execute_syscall = presys_MapViewOfSection(dcontext, param_base);
}
else if (sysnum == syscalls[SYS_UnmapViewOfSection] ||
sysnum == syscalls[SYS_UnmapViewOfSectionEx]) {
KSTART(pre_syscall_unmap);
presys_UnmapViewOfSection(dcontext, param_base, sysnum);
KSTOP(pre_syscall_unmap);
}
else if (sysnum == syscalls[SYS_FlushInstructionCache]) {
presys_FlushInstructionCache(dcontext, param_base);
}
else if (sysnum == syscalls[SYS_CreateSection]) {
presys_CreateSection(dcontext, param_base);
}
else if (sysnum == syscalls[SYS_Close]) {
presys_Close(dcontext, param_base);
}
#ifdef DEBUG
/* FIXME: move this stuff to an strace-like client, not needed
* for core DynamoRIO (at least not that we know of)
*/
else if (sysnum == syscalls[SYS_OpenFile]) {
presys_OpenFile(dcontext, param_base);
}
#endif
/* Address Windowing Extensions (win2k only):
* swap pieces of memory in and out of virtual address space
* => we must intercept when virtual addresses could point to something new
*/
else if (sysnum == syscalls[SYS_FreeUserPhysicalPages]) {
HANDLE process_handle = (HANDLE) sys_param(dcontext, param_base, 0);
uint *num_pages = (uint *) sys_param(dcontext, param_base, 1);
uint *page_frame_nums = (uint *) sys_param(dcontext, param_base, 2);
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtFreeUserPhysicalPages %d pages\n", num_pages);
/* FIXME: need to know base if currently mapped, must
* record every mapping to do so
*/
SYSLOG_INTERNAL_WARNING_ONCE(PRODUCT_NAME" is using un-supported "
"Address Windowing Extensions");
}
else if (sysnum == syscalls[SYS_MapUserPhysicalPages]) {
app_pc base = (app_pc) sys_param(dcontext, param_base, 0);
uint *pnum_pages = (uint *) sys_param(dcontext, param_base, 1);
uint *page_frame_nums = (uint *) sys_param(dcontext, param_base, 2);
uint num_pages;
if (safe_read(pnum_pages, sizeof(num_pages), &num_pages)) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtMapUserPhysicalPages "PFX" pages=%d\n",
base, num_pages);
base = proc_get_containing_page(base);
app_memory_deallocation(dcontext, base, num_pages*PAGE_SIZE,
false /* don't own thread_initexit_lock */,
false /* not image */);
} else {
DODEBUG(dcontext->expect_last_syscall_to_fail = true;);
goto exit_pre_system_call;
}
}
else if (sysnum == syscalls[SYS_SetInformationVirtualMemory]) {
/* XXX i#899: new Win8 syscall. So far we've observed calls from
* KERNELBASE!PrefetchVirtualMemory and we see that
* KERNELBASE!SetProcessValidCallTargets calls the syscall for CFG security
* feature purposes, neither of which should concern us, so we ignore it for
* now.
*/
}
else if (sysnum == syscalls[SYS_RaiseException]) {
IF_CLIENT_INTERFACE(check_app_stack_limit(dcontext));
/* FIXME i#1691: detect whether we're inside SEH handling already, in which
* case this process is about to die by this secondary exception and
* we want to do a normal exit and give the client a chance to clean up.
*/
}
exit_pre_system_call:
dcontext->whereami = old_whereami;
KSTOP(pre_syscall);
return execute_syscall;
}
/***************************************************************************
* POST SYSTEM CALL
*/
/* NtCreateUserProcess */
static void
postsys_CreateUserProcess(dcontext_t *dcontext, reg_t *param_base, bool success)
{
/* See notes in presys_CreateUserProcess for information on signature
* of NtCreateUserProcess. */
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE *proc_handle_ptr = (HANDLE *) postsys_param(dcontext, param_base, 0);
HANDLE *thread_handle_ptr = (HANDLE *) postsys_param(dcontext, param_base, 1);
BOOL create_suspended = (BOOL) postsys_param(dcontext, param_base, 7);
HANDLE proc_handle, thread_handle;
/* FIXME should have type for this */
DEBUG_DECLARE(create_proc_thread_info_t *thread_stuff =
(create_proc_thread_info_t *) postsys_param(dcontext, param_base, 10);)
ASSERT(get_os_version() >= WINDOWS_VERSION_VISTA);
LOG(THREAD, LOG_SYSCALLS, 1, "syscall: NtCreateUserProcess => "PIFX"\n", mc->xax);
DOLOG(1, LOG_SYSCALLS, {
if (success) {
PCLIENT_ID client_id;
ASSERT(thread_stuff != NULL && thread_stuff->client_id.buffer != NULL);
/* Potentially dangerous deref of app ptr,
* but is only for debug logging */
client_id = (PCLIENT_ID)thread_stuff->client_id.buffer;
LOG(THREAD, LOG_SYSCALLS, 1,
"syscall: NtCreateUserProcess created process "PIFX" "
"with main thread "PIFX"\n",
client_id->UniqueProcess, client_id->UniqueThread);
}
});
/* Even though syscall succeeded we use safe_read to be sure */
if (success &&
safe_read(proc_handle_ptr, sizeof(proc_handle), &proc_handle) &&
safe_read(thread_handle_ptr, sizeof(thread_handle), &thread_handle)) {
ACCESS_MASK rights = nt_get_handle_access_rights(proc_handle);
if (TESTALL(PROCESS_VM_OPERATION|PROCESS_VM_READ|
PROCESS_VM_WRITE|PROCESS_QUERY_INFORMATION, rights)) {
if (create_suspended) {
char buf[MAX_CONTEXT_SIZE];
CONTEXT *context;
CONTEXT *cxt = NULL;
int res;
/* Since this syscall is vista+ only, whether a wow64 process
* has no bearing (xref i#381)
*/
ASSERT(get_os_version() >= WINDOWS_VERSION_VISTA);
if (!DYNAMO_OPTION(early_inject)) {
/* If no early injection we have to do thread injection, and
* on Vista+ we don't see the
* NtCreateThread so we do it here. PR 215423.
*/
context = nt_initialize_context(buf, CONTEXT_DR_STATE);
res = nt_get_context(thread_handle, context);
if (NT_SUCCESS(res))
cxt = context;
else {
/* FIXME i#49: cross-arch injection can end up here w/
* STATUS_INVALID_PARAMETER. Need to use proper platform's
* CONTEXT for target.
*/
DODEBUG({
if (is_wow64_process(NT_CURRENT_PROCESS) &&
!is_wow64_process(proc_handle)) {
SYSLOG_INTERNAL_WARNING_ONCE
("Injecting from 32-bit into 64-bit process is not "
"yet supported.");
}
});
LOG(THREAD, LOG_SYSCALLS, 1,
"syscall: NtCreateUserProcess: WARNING: failed to get cxt of "
"thread ("PIFX") so can't follow children on WOW64.\n", res);
}
}
if ((cxt != NULL || DYNAMO_OPTION(early_inject)) &&
maybe_inject_into_process(dcontext, proc_handle, cxt) &&
cxt != NULL) {
/* injection routine is assuming doesn't have to install cxt */
res = nt_set_context(thread_handle, cxt);
if (!NT_SUCCESS(res)) {
LOG(THREAD, LOG_SYSCALLS, 1,
"syscall: NtCreateUserProcess: WARNING: failed to set cxt of "
"thread ("PIFX") so can't follow children on WOW64.\n", res);
}
}
} else {
LOG(THREAD, LOG_SYSCALLS, 1,
"syscall: NtCreateUserProcess first thread not suspended "
"can't safely follow children.\n");
ASSERT_NOT_IMPLEMENTED(create_suspended);
/* FIXME - NYI - should change in pre and resume the thread
* after we inject. */
}
} else {
LOG(THREAD, LOG_SYSCALLS, 1,
"syscall: NtCreateUserProcess unable to get sufficient rights"
" to follow children\n");
/* This happens for Vista protected processes (drm). xref 8485 */
/* FIXME - could check against executable file name from
* thread_stuff to see if this was a process we're configured to
* protect. */
SYSLOG_INTERNAL_WARNING("Insufficient permissions to examine "
"child process\n");
}
/* Case 9173: guard against pid reuse */
dcontext->aslr_context.last_child_padded = 0;
}
}
/* NtGetContextThread */
static void
postsys_GetContextThread(dcontext_t *dcontext, reg_t *param_base, bool success)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE thread_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
CONTEXT *cxt = (CONTEXT *) postsys_param(dcontext, param_base, 1);
thread_record_t *trec;
thread_id_t tid = thread_handle_to_tid(thread_handle);
char buf[MAX_CONTEXT_SIZE];
CONTEXT *alt_cxt;
CONTEXT *xlate_cxt;
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, 1,
"syscall: NtGetContextThread handle="PFX" (tid=%d) flags=0x%x"
" cxt->Xip="PFX" => "PIFX"\n",
thread_handle, tid, cxt->ContextFlags, cxt->CXT_XIP, mc->xax);
if (!success)
return;
/* FIXME : we are going to read/write the context argument which is
* potentially unsafe, since success it must have been readable when
* at the os call, but there could always be multi-thread races */
/* so trec remains valid, we are !could_be_linking */
mutex_lock(&thread_initexit_lock);
trec = thread_lookup(tid);
if (trec == NULL) {
/* this can occur if the target thread hasn't been scheduled yet
* and therefore we haven't initialized it yet, (scheduled for
* fixing), OR if the thread is in another process (FIXME : IPC)
* for either case we do nothing for now
*/
DODEBUG({
process_id_t pid = thread_handle_to_pid(thread_handle, tid);
if (!is_pid_me(pid)) {
IPC_ALERT("Warning: NtGetContextThread called on thread "
"tid="PFX" in different process, pid="PFX,
tid, pid);
} else {
SYSLOG_INTERNAL_WARNING_ONCE("Warning: NtGetContextThread "
"called on unknown thread "
PFX, tid);
}
});
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, 2,
"NtGetContextThread on unknown thread "TIDFMT"\n", tid);
} else {
/* FIXME : the following routine (and the routines it calls
* namely recreate_app_state) require that trec thread be
* suspended at a consistent spot, but we could have that the
* trec thread is not suspended (get_thread_context doesn't
* require it!), should we check the suspend count?
*/
bool translate = true;
xlate_cxt = cxt;
if (!TESTALL(CONTEXT_DR_STATE, cxt->ContextFlags)) {
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, 2,
"NtGetContextThread: app didn't ask for enough, querying ourselves\n");
STATS_INC(num_app_getcontext_no_control);
/* we need esp and eip, plus all regs + xmm, to translate the machine state.
* no further permissions are needed to acquire them so we
* get our own context w/ them.
*/
alt_cxt = nt_initialize_context(buf, CONTEXT_DR_STATE);
/* if asking for own context, thread_get_context() will point at
* dynamorio_syscall_* and we'll fail to translate so we special-case
*/
if (tid == get_thread_id()) {
/* only fields that DR might change are propagated to cxt below,
* so set set_cur_seg to false.
*/
mcontext_to_context(alt_cxt, mc, false /* !set_cur_seg */);
alt_cxt->CXT_XIP = (ptr_uint_t) dcontext->asynch_target;
translate = false;
} else if (!thread_get_context(trec, alt_cxt)) {
ASSERT_NOT_REACHED();
/* FIXME: just don't translate -- right now won't hurt us since
* we don't translate other than the pc anyway.
*/
return;
}
xlate_cxt = alt_cxt;
}
SELF_PROTECT_LOCAL(trec->dcontext, WRITABLE);
/* PR 214962: since we are not relocating the target thread, we do NOT
* want to restore memory. This is no less transparent, because
* this thread could read the target thread's memory at any time anyway.
*/
if (translate &&
!translate_context(trec, xlate_cxt, false/*leave memory alone*/)) {
/* FIXME: can get here native if GetThreadContext on
* an un-suspended thread, but then API says result is
* undefined so just pass anything reasonable
* PLUS, need to handle unknown (unscheduled yet) thread --
* passing native should be fine
*/
SYSLOG_INTERNAL_WARNING("NtGetContextThread called for thread not in translatable spot");
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, 1,
"ERROR: NtGetContextThread called for thread not in translatable spot\n");
} else if (xlate_cxt != cxt) {
/* copy the fields we may have changed that app requested */
ASSERT(!TESTALL(CONTEXT_DR_STATE, cxt->ContextFlags));
if (TESTALL(CONTEXT_CONTROL/*2 bits so ALL*/, cxt->ContextFlags)) {
cxt->CXT_XIP = xlate_cxt->CXT_XIP;
cxt->CXT_XFLAGS = xlate_cxt->CXT_XFLAGS;
cxt->CXT_XSP = xlate_cxt->CXT_XSP;
#ifndef X64
cxt->CXT_XBP = xlate_cxt->CXT_XBP;
#endif
}
if (TESTALL(CONTEXT_INTEGER/*2 bits so ALL*/, cxt->ContextFlags)) {
cxt->CXT_XAX = xlate_cxt->CXT_XAX;
cxt->CXT_XBX = xlate_cxt->CXT_XBX;
cxt->CXT_XCX = xlate_cxt->CXT_XCX;
cxt->CXT_XDX = xlate_cxt->CXT_XDX;
cxt->CXT_XSI = xlate_cxt->CXT_XSI;
cxt->CXT_XDI = xlate_cxt->CXT_XDI;
#ifdef X64
cxt->CXT_XBP = xlate_cxt->CXT_XBP;
cxt->R8 = xlate_cxt->R8;
cxt->R9 = xlate_cxt->R9;
cxt->R10 = xlate_cxt->R10;
cxt->R11 = xlate_cxt->R11;
cxt->R12 = xlate_cxt->R12;
cxt->R13 = xlate_cxt->R13;
cxt->R14 = xlate_cxt->R14;
cxt->R15 = xlate_cxt->R15;
#endif
}
if (TESTALL(CONTEXT_XMM_FLAG, cxt->ContextFlags) &&
preserve_xmm_caller_saved()) {
/* PR 264138 */
memcpy(CXT_XMM(cxt, 0), CXT_XMM(xlate_cxt, 0), XMM_SAVED_SIZE);
}
if (TESTALL(CONTEXT_YMM_FLAG, cxt->ContextFlags) &&
preserve_xmm_caller_saved()) {
byte *ymmh_area = context_ymmh_saved_area(cxt);
ASSERT(ymmh_area != NULL);
memcpy(ymmh_area, context_ymmh_saved_area(xlate_cxt), YMMH_SAVED_SIZE);
}
}
SELF_PROTECT_LOCAL(trec->dcontext, READONLY);
}
mutex_unlock(&thread_initexit_lock);
}
/* NtSuspendThread */
static void
postsys_SuspendThread(dcontext_t *dcontext, reg_t *param_base, bool success)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE thread_handle= (HANDLE) postsys_param(dcontext, param_base, 0);
/* ignoring 2nd argument (OUT PULONG PreviousSuspendCount OPTIONAL) */
thread_id_t tid = thread_handle_to_tid(thread_handle);
process_id_t pid;
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, 1,
"syscall: NtSuspendThread tid=%d => "PIFX"\n", tid, mc->xax);
if (SELF_PROTECT_ON_CXT_SWITCH) {
/* No matter what, restore ignore to default value */
dcontext->ignore_enterexit = false;
}
/* if we suspended ourselves then skip synchronization,
* already resumed, FIXME : what if someone else resumes the thread
* while we are trying to synch with it */
if (!success || tid == get_thread_id())
return;
pid = thread_handle_to_pid(thread_handle, tid);
if (!is_pid_me(pid)) {
/* (FIXME : IPC) */
IPC_ALERT("Warning: SuspendThread called on thread in "
"different process, pid="PFX, pid);
return;
}
/* as optimization check if at good spot already before resuming for
* synch, use trylocks in case suspended thread is holding any locks */
if (mutex_trylock(&thread_initexit_lock)) {
if (!mutex_testlock(&all_threads_lock)) {
char buf[MAX_CONTEXT_SIZE];
CONTEXT *cxt = nt_initialize_context(buf, CONTEXT_DR_STATE);
thread_record_t *tr;
/* know thread isn't holding any of the locks we will need */
LOG(THREAD, LOG_SYNCH, 2,
"SuspendThread got necessary locks to test if thread "TIDFMT" suspended at good spot without resuming\n",
tid);
tr = thread_lookup(tid);
if (tr == NULL) {
/* Could be unknown thread, a thread just starting up or
* a thread that is in the process of exiting.
* synch_with_thread will take care of the last case at
* least so we fall through to that. */
} else if (thread_get_context(tr, cxt)) {
priv_mcontext_t mc;
context_to_mcontext(&mc, cxt);
SELF_PROTECT_LOCAL(tr->dcontext, WRITABLE);
if (at_safe_spot(tr, &mc,
THREAD_SYNCH_SUSPENDED_VALID_MCONTEXT)) {
/* suspended at good spot, skip synch */
mutex_unlock(&thread_initexit_lock);
LOG(THREAD, LOG_SYNCH, 2,
"SuspendThread suspended thread "TIDFMT" at good place\n",
tid);
SELF_PROTECT_LOCAL(tr->dcontext, READONLY);
return;
}
SELF_PROTECT_LOCAL(tr->dcontext, READONLY);
}
} else {
LOG(THREAD, LOG_SYNCH, 2,
"SuspendThread couldn't get all_threads_lock to test if thread "TIDFMT" at good spot without resuming\n",
tid);
}
mutex_unlock(&thread_initexit_lock);
} else {
LOG(THREAD, LOG_SYNCH, 2,
"SuspendThread couldn't get thread_initexit_lock to test if thread "TIDFMT" at good spot without resuming\n",
tid);
}
LOG(THREAD, LOG_SYNCH, 2,
"SuspendThread resuming suspended thread "TIDFMT" for synch routine\n",
tid);
/* resume for synch */
nt_thread_resume(thread_handle, NULL);
/* do synch */
{
priv_mcontext_t mcontext;
thread_synch_result_t synch_res;
copy_mcontext(mc, &mcontext);
mc->pc = POST_SYSCALL_PC(dcontext);
/* we hold the initexit lock for case 9489, see comment below in failure
* to synch path for details why */
if (DYNAMO_OPTION(suspend_on_synch_failure_for_app_suspend))
mutex_lock(&thread_initexit_lock);
synch_res =
synch_with_thread(tid, true /* block */,
/* initexit lock status */
DYNAMO_OPTION(suspend_on_synch_failure_for_app_suspend),
THREAD_SYNCH_VALID_MCONTEXT,
THREAD_SYNCH_SUSPENDED_VALID_MCONTEXT,
/* if we fail to suspend a thread (e.g., privilege
* problems) ignore it. FIXME: retry instead? */
THREAD_SYNCH_SUSPEND_FAILURE_IGNORE);
if (synch_res != THREAD_SYNCH_RESULT_SUCCESS) {
/* xref case 9488 - we failed to synch, could be we exceeded our loop count
* for some reason, we lack GetContext permission (or the apps handle has
* suspend and ours doesn't somehow), or could be an unknown thread. FIXME -
* we suspend the thread so the app doesn't get screwed up (it expects a
* suspended thread) at the risk of possibly deadlocking DR if it holds
* one of our locks etc. */
/* If the thread is unknown everything might be ok, could be a thread that's
* almost exited (should be fine though app might get slightly screwy result
* if it calls get context, e.g. an eip in our dll) or a new thread that
* hasn't yet initialized (see case 9489, should also be fine since we hold
* the initexit lock so the thread can't have gone anywhere since the
* synch_with_thread checks). NOTE - SetEvent appears to do the sensible
* thing when an auto-reset event that has a suspended thread waiting on it
* is signaled (the new thread could be waiting on the initexit lock), i.e.
* leave the event signaled for someone else to grab. */
/* Full ASSERT if thread is known (always bad to fail then), curiosity
* instead if thread is unknown (since expected to be ok). */
ASSERT(thread_lookup(tid) == NULL); /* i.e. thread not known */
/* The suspend.c unit test can hit this regularly on (via suspend new thread)
* though we expect it to be unusual in normal applications. Same thing with
* detach_test.exe and threadinjection.exe. */
ASSERT_CURIOSITY_ONCE((thread_lookup(tid) != NULL || /* thread known */
EXEMPT_TEST("win32.suspend.exe;runall.detach_test.exe;"
"win32.threadinjection.exe")) &&
"app suspending unknown thread");
if (DYNAMO_OPTION(suspend_on_synch_failure_for_app_suspend)) {
/* thread may already be exited in which case this will fail */
DEBUG_DECLARE(bool res = )nt_thread_suspend(thread_handle, NULL);
ASSERT(res || is_thread_exited(thread_handle) == THREAD_EXITED);
}
}
if (DYNAMO_OPTION(suspend_on_synch_failure_for_app_suspend))
mutex_unlock(&thread_initexit_lock);
/* FIXME - if the thread exited we should prob. change the return value to
* the app to a failure value. Only an assert_curiosity for now to see if any
* apps suspend threads while the threads are exiting and if so what they expect
* to happen. */
ASSERT_CURIOSITY(is_thread_exited(thread_handle) == THREAD_NOT_EXITED);
copy_mcontext(&mcontext, mc);
}
}
#ifdef CLIENT_INTERFACE
/* NtQueryInformationThread */
static void
postsys_QueryInformationThread(dcontext_t *dcontext, reg_t *param_base, bool success)
{
THREADINFOCLASS class = (THREADINFOCLASS) postsys_param(dcontext, param_base, 1);
if (success && class == ThreadAmILastThread) {
HANDLE thread_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
thread_id_t tid = thread_handle_to_tid(thread_handle);
process_id_t pid = thread_handle_to_pid(thread_handle, tid);
if (pid != POINTER_MAX && is_pid_me(pid) &&
get_num_client_threads() > 0 && is_last_app_thread()) {
PVOID info = (PVOID) postsys_param(dcontext, param_base, 2);
ULONG info_sz = (ULONG) postsys_param(dcontext, param_base, 3);
BOOL pretend_val = TRUE;
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtQueryInformationThread ThreadAmILastThread fooling\n");
ASSERT_CURIOSITY(info_sz == sizeof(BOOL));
if (info_sz == sizeof(BOOL))
safe_write(info, info_sz, &pretend_val);
}
}
}
#endif
/* NtOpenThread */
static void
postsys_OpenThread(dcontext_t *dcontext, reg_t *param_base, bool success)
{
if (success) {
HANDLE *handle = (HANDLE*) postsys_param(dcontext, param_base, 0);
CLIENT_ID *cid = (CLIENT_ID *) postsys_param(dcontext, param_base, 3);
LOG(THREAD, LOG_SYSCALLS|LOG_THREADS, 2,
"syscall: NtOpenThread "PFX"=>"PFX" "PFX"=>"TIDFMT"\n",
handle, *handle, cid, cid->UniqueThread);
handle_to_tid_add(*handle, (thread_id_t)cid->UniqueThread);
}
}
/* NtAllocateVirtualMemory */
static void
postsys_AllocateVirtualMemory(dcontext_t *dcontext, reg_t *param_base, bool success,
int sysnum)
{
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE process_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
/* XXX i#899: for NtWow64AllocateVirtualMemory64, the base and
* size may be 64-bit values? But, when allocating in wow64
* child, the address should be in low 2GB, as only ntdll64 is up
* high. If the extra arg were before ZeroBits, it could be a pointer
* to the high bits of the base addr, like NtWow64ReadVirtualMemory64(),
* but that doesn't seem to be the case.
*/
void **pbase = (void **) postsys_param(dcontext, param_base, 1);
uint zerobits = (uint) postsys_param(dcontext, param_base, 2);
/* XXX i#899: NtWow64AllocateVirtualMemory64 has an extra arg after ZeroBits but
* it's ignored in wow64!whNtWow64AllocateVirtualMemory64. We should keep an eye
* out: maybe a future service pack or win9 will use it.
*/
int arg_shift = (sysnum == syscalls[SYS_Wow64AllocateVirtualMemory64] ? 1 : 0);
size_t *psize = (size_t *) postsys_param(dcontext, param_base, 3 + arg_shift);
uint type = (uint) postsys_param(dcontext, param_base, 4 + arg_shift);
uint prot = (uint) postsys_param(dcontext, param_base, 5 + arg_shift);
app_pc base;
size_t size;
if (!success) {
/* FIXME i#148: should try to recover from any prot change -- though today we
* don't even do so on NtProtectVirtualMemory failing.
*/
return;
}
if (!safe_read(pbase, sizeof(base), &base) || !safe_read(psize, sizeof(size), &size)) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"syscall: NtAllocateVirtualMemory: failed to read params "PFX" "PFX"\n",
pbase, psize);
return;
}
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, prot_is_executable(prot) ? 1U : 2U,
"syscall: NtAllocateVirtualMemory%s%s%s@"PFX" sz="PIFX" prot=%s 0x%x => 0x%x\n",
is_phandle_me(process_handle) ? "" : " IPC",
TEST(MEM_RESERVE, type) ? " reserve" : "",
TEST(MEM_COMMIT, type) ? " commit " : " ",
base, size, prot_string(prot), prot, mc->xax);
DOLOG(1, LOG_MEMSTATS, {
/* snapshots are heavyweight, so do rarely */
if (size > SNAPSHOT_THRESHOLD && is_phandle_me(process_handle))
mem_stats_snapshot();
});
if (TEST(ASLR_HEAP_FILL, DYNAMO_OPTION(aslr)) &&
is_phandle_me(process_handle)) {
/* We allocate our padding after the application region is
* successfully reserved. FIXME: assuming that one cannot
* pass MEM_RESERVE|MEM_COMMIT on an already reserved
* region. Yet note one can MEM_COMMIT a region that has
* been committed already. Note that it is OK to pass
* MEM_COMMIT with original base set to NULL, and then the
* allocation will act as MEM_RESERVE|MEM_COMMIT! One
* can't pass MEM_COMMIT that with non-zero base on a
* region that hasn't been reserved before. We want to
* make sure we pad only an amount corresponding to the
* new reservations. (Currently we only pad immediately
* after an allocation but that may change.)
*/
/* FIXME: case 6287 we should TEST(MEM_RESERVE, type) if
* allocation has just been reserved, or if pre_syscall
* base was NULL for a MEM_COMMIT. Currently a pad is
* reserved only in case immediate region has not been
* reserved, so we're ok to attempt to pad even
* a MEM_COMMIT with an existing reservation
*/
aslr_post_process_allocate_virtual_memory(dcontext, base, size);
}
if (!TEST(MEM_COMMIT, type)) {
/* MEM_RESERVE only: protection bits are meaningless, we do nothing
* MEM_RESET: we do not need to flush on a reset, since whatever is there
* cannot be changed without writing to it!
* the subsequent commit to the already committed region will work fine.
*/
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2, "not committing, so ignorable\n");
return;
}
if (is_phandle_me(process_handle)) {
#ifdef DGC_DIAGNOSTICS
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, TEST(MEM_COMMIT, type) ? 1U : 2U,
"syscall: NtAllocateVirtualMemory%s%s@"PFX" sz="PIFX" prot=%s 0x%x => 0x%x\n",
TEST(MEM_RESERVE, type) ? " reserve" : "",
TEST(MEM_COMMIT, type) ? " commit " : " ",
base, size, prot_string(prot), prot, mc->xax);
DOLOG(1, LOG_VMAREAS, {
dump_callstack(POST_SYSCALL_PC(dcontext),
(app_pc) mc->xbp, THREAD, DUMP_NOT_XML);
});
#endif
app_memory_allocation(dcontext, base, size, osprot_to_memprot(prot),
false/*not image*/
_IF_DEBUG("NtAllocateVirtualMemory"));
#ifdef DGC_DIAGNOSTICS
DOLOG(3, LOG_VMAREAS, {
/* make all heap RO in attempt to view generation of DGC */
if (!is_address_on_stack(dcontext, base) && prot_is_writable(prot)) {
/* new thread stack: reserve big region, commit 2 pages, then mark
* 1 page as PAGE_GUARD. strangely thread gets resumed sometimes
* before see PAGE_GUARD prot, so instead of tracking that we have
* a hack to guess if this is a thread stack:
*/
IF_X64(ASSERT_NOT_IMPLEMENTED(false));
if (size == 0x2000 && ((ptr_uint_t)base & 0xf0000000) == 0x00000000 &&
prot == PAGE_READWRITE) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"Guessing "PFX"-"PFX" is thread stack\n",
base, base+size);
} else {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"Making "PFX"-"PFX" 0x%x unwritable\n",
base, base+size, prot);
make_unwritable(base, size);
}
}
});
#endif
} else {
/* FIXME: should we try to alert any dynamo running the other process?
*/
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"WARNING: NtAllocateVirtualMemory for process "PFX" %d\n",
process_handle, process_id_from_handle(process_handle));
DODEBUG({
if (prot_is_executable(prot)) {
IPC_ALERT("NtAllocateVirtualMemory for process "PFX" %d prot=%s",
process_handle, process_id_from_handle(process_handle),
prot_string(prot));
}
});
/* This actually happens in calc's help defn popup!
* FIXME: we need IPC! Plus need to queue up msgs to child dynamo,
* for calc it did NtCreateProcess, NtAllocateVirtualMemory, then
* the NtCreateThread that triggers our fork injection!
* don't die with IPC_ALERT
*/
}
}
/* NtQueryVirtualMemory */
static void
postsys_QueryVirtualMemory(dcontext_t *dcontext, reg_t *param_base, bool success)
{
/* we intercept this for transparency wrt the executable regions
* that we mark as read-only
*/
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE process_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
app_pc base = (app_pc) postsys_param(dcontext, param_base, 1);
uint class = (uint) postsys_param(dcontext, param_base, 2);
MEMORY_BASIC_INFORMATION *mbi =
(MEMORY_BASIC_INFORMATION *) postsys_param(dcontext, param_base, 3);
size_t infolen = (size_t) postsys_param(dcontext, param_base, 4);
size_t *returnlen = (size_t *) postsys_param(dcontext, param_base, 5);
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtQueryVirtualMemory base="PFX" => "PIFX"\n", base, mc->xax);
if (!success)
return;
/* FIXME : since success we assume that all argument dereferences are
* safe though there could always be multi-thread races */
if (is_phandle_me(process_handle)) {
if (class == MemoryBasicInformation) {
/* see if asking about an executable area we made read-only */
if (is_pretend_or_executable_writable(base)) {
/* pretend area is writable */
uint flags =
mbi->Protect & ~PAGE_PROTECTION_QUALIFIERS;
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"WARNING: Query to now-readonly executable area, pretending writable\n");
if (flags == PAGE_READONLY) {
mbi->Protect &= ~PAGE_READONLY;
mbi->Protect |= PAGE_READWRITE;
} else if (flags == PAGE_EXECUTE_READ) {
mbi->Protect &= ~PAGE_EXECUTE_READ;
mbi->Protect |= PAGE_EXECUTE_READWRITE;
} else {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"ERROR: Query to now-readonly executable area w/ bad flags %s\n",
prot_string(mbi->Protect));
SYSLOG_INTERNAL_INFO("ERROR: Query to now-readonly executable area w/ bad flags");
}
} else if (is_dynamo_address(base)) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"WARNING: QueryVM to DR memory "PFX"\n", base);
if (base == dynamo_dll_start && mbi != NULL &&
DYNAMO_OPTION(hide_from_query) != 0) {
/* pretend area is un-allocated */
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"WARNING: QueryVM to DR DLL "PFX", pretending not a dll\n", base);
if (TEST(HIDE_FROM_QUERY_TYPE_PROTECT,
DYNAMO_OPTION(hide_from_query))) {
mbi->Type = MEM_PRIVATE; /* not image! */
mbi->Protect = PAGE_NOACCESS;
}
/* now do an off-by-1 to fool any calls to GetModuleFileName
* (it doesn't turn into a syscall)
* FIXME: app could still use a snapshot to get list
* of modules, but that is covered by -hide
*/
if (TEST(HIDE_FROM_QUERY_BASE_SIZE,
DYNAMO_OPTION(hide_from_query))) {
mbi->AllocationBase = ((app_pc)mbi->AllocationBase)
+ PAGE_SIZE;
mbi->BaseAddress = ((app_pc)mbi->BaseAddress)
+ PAGE_SIZE;
/* skip over the other regions in our dll -- ok to
* be PAGE_SIZE off, better to be beyond than
* return too small and have caller incrementing
* only and ignoring bases!
*/
mbi->RegionSize = (dynamo_dll_end - dynamo_dll_start);
}
/* note that returning STATUS_INVALID_ADDRESS is too
* extreme of a solution, so this is off by default */
if (TEST(HIDE_FROM_QUERY_RETURN_INVALID,
DYNAMO_OPTION(hide_from_query))) {
/* FIXME: SET_RETURN_VAL bug 5068 had return val as 0
* Need to re-test this with this actual return val
*/
SET_RETURN_VAL(dcontext, STATUS_INVALID_ADDRESS);
}
}
}
} else if (class == MemorySectionName) {
/* This does work on image sections on later Windows */
if (is_dynamo_address(base)) {
/* Apps should be fine with this failing. This is the failure
* status for an address that does not contain a mapped file.
*/
SET_RETURN_VAL(dcontext, STATUS_INVALID_ADDRESS);
}
}
} else {
IPC_ALERT("Warning: QueryVirtualMemory on another process");
}
}
static void
postsys_create_or_open_section(dcontext_t *dcontext,
HANDLE *unsafe_section_handle, HANDLE file_handle,
bool non_image)
{
HANDLE section_handle = INVALID_HANDLE_VALUE;
if (DYNAMO_OPTION(track_module_filenames) &&
safe_read(unsafe_section_handle, sizeof(section_handle), §ion_handle)) {
/* Case 1272: keep file name around to use for module identification */
FILE_NAME_INFORMATION name_info; /* note: large struct */
wchar_t buf[MAXIMUM_PATH];
wchar_t *fname = name_info.FileName;
/* For i#138 we want the full path so we ignore the short name
* returned by get_file_short_name
*/
if (file_handle != INVALID_HANDLE_VALUE &&
get_file_short_name(file_handle, &name_info) != NULL) {
bool have_name = false;
if (convert_NT_to_Dos_path(buf, name_info.FileName,
BUFFER_SIZE_ELEMENTS(buf))) {
fname = buf;
have_name = true;
} else if (get_os_version() <= WINDOWS_VERSION_2000 && !non_image) {
/* It's normal for NtQueryInformationFile to return a relative path.
* For non-images, or for XP+ for all sections, we can get the
* absolute path at map time: but for images (or if we don't know
* whether image, e.g. for OpenSection) on NT/2K we map in the file
* as a non-image to find the name. Kind of expensive, but it's only
* for legacy platforms, and option-controlled.
*/
size_t size = 0;
byte *pc = os_map_file(file_handle, &size, 0, NULL, MEMPROT_READ,
0/*not cow or image*/);
if (pc == NULL) {
/* We don't know what perms the file was opened with. Sometimes
* we can only map +x so try that.
*/
pc = os_map_file(file_handle, &size, 0, NULL, MEMPROT_EXEC,
0/*not cow or image*/);
}
if (pc != NULL) {
NTSTATUS res = get_mapped_file_name(pc, buf, BUFFER_SIZE_BYTES(buf));
if (NT_SUCCESS(res)) {
have_name = convert_NT_to_Dos_path
(name_info.FileName, buf,
BUFFER_SIZE_ELEMENTS(name_info.FileName));
}
os_unmap_file(pc, size);
}
}
if (!have_name) {
/* i#1180: we get non-drive absolute DOS paths here which naturally
* convert_NT_to_Dos_path can't handle (e.g.,
* "\Windows\Globalization\Sorting\SortDefault.nls").
* We expect to get an NT path at map time on XP+, so we only
* warn for 2K- images.
*/
DODEBUG({
if (get_os_version() <= WINDOWS_VERSION_2000 && !non_image) {
STATS_INC(map_unknown_Dos_name);
SYSLOG_INTERNAL_WARNING_ONCE("unknown mapfile Dos name");
}
});
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"\t%s: pre-map, unable to convert NT to Dos path for \"%S\"\n",
__FUNCTION__, fname);
}
section_to_file_add_wide(section_handle, fname);
} else {
/* We assume that we'll have the file_handle for image sections:
* either we'll see a CreateSection w/ a file, or we'll see OpenSection
* on a KnownDlls path w/ RootDirectory set. So this is likely a
* non-image section, whose backing file we'll query at map time.
*/
DODEBUG(name_info.FileName[0] = '\0';);
}
#ifdef DEBUG
dcontext->aslr_context.last_app_section_handle = section_handle;
#endif
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"\tNt{Create,Open}Section: sec handle "PIFX", file "PFX" => \"%S\"\n",
section_handle, file_handle, fname);
}
}
/* NtCreateSection */
static void
postsys_CreateSection(dcontext_t *dcontext, reg_t *param_base, bool success)
{
/* a section is an object that can be mmapped */
HANDLE *unsafe_section_handle = (HANDLE*) postsys_param(dcontext, param_base, 0);
uint access_mask = (uint) postsys_param(dcontext, param_base, 1);
POBJECT_ATTRIBUTES obj = (POBJECT_ATTRIBUTES) postsys_param(dcontext, param_base, 2);
void *size = (void *) postsys_param(dcontext, param_base, 3);
uint protect = (uint) postsys_param(dcontext, param_base, 4);
uint attributes = (uint) postsys_param(dcontext, param_base, 5);
HANDLE file_handle = (HANDLE) postsys_param(dcontext, param_base, 6);
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtCreateSection protect 0x%x, attributes 0x%x\n",
protect, attributes);
if (!success)
return;
postsys_create_or_open_section(dcontext, unsafe_section_handle, file_handle,
!TEST(SEC_IMAGE, attributes));
if (TEST(ASLR_DLL, DYNAMO_OPTION(aslr))) {
if (TEST(SEC_IMAGE, attributes)) {
if (aslr_post_process_create_or_open_section(dcontext,
true, /* create */
file_handle,
unsafe_section_handle)) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: ASLR: NtCreateSection replaced with new section "PIFX"\n",
*unsafe_section_handle);
} else {
/* leaving as is */
}
} else {
/* ignoring SEC_COMMIT mappings - since SEC_COMMIT is
* default it doesn't need to be set */
}
}
}
/* NtOpenSection */
static void
postsys_OpenSection(dcontext_t *dcontext, reg_t *param_base, bool success)
{
/* a section is an object that can be mmapped, here opened by object name */
HANDLE *unsafe_section_handle = (HANDLE*) postsys_param(dcontext, param_base, 0);
uint access_mask = (uint) postsys_param(dcontext, param_base, 1);
POBJECT_ATTRIBUTES obj_attr = (POBJECT_ATTRIBUTES)
postsys_param(dcontext, param_base, 2);
HANDLE new_file_handle = INVALID_HANDLE_VALUE;
if (!success) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtOpenSection, failed, access 0x%x\n",
access_mask);
return;
}
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtOpenSection opened sh "PIFX", access_mask 0x%x, obj_attr "PFX"\n",
*unsafe_section_handle, access_mask, obj_attr);
/* If we only wanted short names for -track_module_filenames,
* could we use obj_attr->ObjectName->Buffer and not
* call aslr_recreate_known_dll_file() at all?
*/
if ((DYNAMO_OPTION(track_module_filenames) ||
(TEST(ASLR_DLL, DYNAMO_OPTION(aslr)) &&
TEST(ASLR_SHARED_CONTENTS, DYNAMO_OPTION(aslr_cache)))) &&
obj_attr != NULL) {
/* need to identify KnownDlls here */
/* FIXME: NtOpenSection doesn't give us section attributes,
* and we can't even query them - the only reasonable solution is to
* match the directory handle
*
* FIXME: case 9032 about possibly duplicating the handle if
* that is any faster than any other syscalls we're making here
*/
/* FIXME: we could restrict the check to potential DLLs
* based on access_mask, although most users use
* SECTION_ALL_ACCESS */
HANDLE root_directory = NULL;
bool ok = safe_read(&obj_attr->RootDirectory,
sizeof(root_directory), &root_directory);
if (ok && root_directory != NULL &&
aslr_is_handle_KnownDlls(root_directory)) {
if (aslr_recreate_known_dll_file(obj_attr, &new_file_handle)) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtOpenSection: recreated file handle "PIFX"\n",
new_file_handle);
} else {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtOpenSection: unable to recreate file handle\n");
}
if (TEST(ASLR_DLL, DYNAMO_OPTION(aslr)) &&
TEST(ASLR_SHARED_CONTENTS, DYNAMO_OPTION(aslr_cache))) {
if (aslr_post_process_create_or_open_section(dcontext,
false, /* open */
/* recreated file */
new_file_handle,
unsafe_section_handle)) {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: ASLR: NtOpenSection replaced with new section "PIFX"\n",
*unsafe_section_handle);
} else {
/* leaving as is */
}
}
/* If we're not replacing the section (i.e., not doing ASLR_DLL),
* we need new_file_handle for postsys_create_or_open_section so we do
* not close here
*/
} else {
/* nothing */
}
}
if (DYNAMO_OPTION(track_module_filenames)) {
postsys_create_or_open_section(dcontext, unsafe_section_handle,
new_file_handle, false/*don't know*/);
}
if (new_file_handle != INVALID_HANDLE_VALUE)
close_handle(new_file_handle);
}
/* NtMapViewOfSection */
static void
postsys_MapViewOfSection(dcontext_t *dcontext, reg_t *param_base, bool success)
{
/* This is what actually allocates a dll into memory */
priv_mcontext_t *mc = get_mcontext(dcontext);
HANDLE section_handle; /* 0 */
HANDLE process_handle; /* 1 */
void **pbase_unsafe; /* 2 */
uint zerobits; /* 3 */
size_t commit_size; /* 4 */
LARGE_INTEGER *section_offs; /* 5 */
size_t *view_size; /* 6 */
uint inherit_disposition; /* 7 */
uint type; /* 8 */
uint prot; /* 9 */
size_t size; /* safe dereferenced values */
app_pc base;
/* only process if we acted on this call in aslr_pre_process_mapview */
if (dcontext->aslr_context.sys_aslr_clobbered) {
aslr_post_process_mapview(dcontext);
/* preceding call sets mcontext.xax so re-evaluate */
success = NT_SUCCESS(mc->xax);
/* reevaluate all system call OUT arguments, since they
* may have changed in aslr_post_process_mapview()!
*/
/* FIXME: registers may not necessarily match state of
* mangled system call, but we assume only state->mc.xax matters
*/
}
if (!success) {
prot = (uint) postsys_param(dcontext, param_base, 9);
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"syscall: failed NtMapViewOfSection prot=%s => "PFX"\n",
prot_string(prot), mc->xax);
return;
}
section_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
process_handle = (HANDLE) postsys_param(dcontext, param_base, 1);
pbase_unsafe = (void *) postsys_param(dcontext, param_base, 2);
zerobits = (uint) postsys_param(dcontext, param_base, 3);
commit_size = (size_t) postsys_param(dcontext, param_base, 4);
section_offs = (LARGE_INTEGER *) postsys_param(dcontext, param_base, 5);
view_size = (size_t *) postsys_param(dcontext, param_base, 6);
inherit_disposition = (uint) postsys_param(dcontext, param_base, 7);
type = (uint) postsys_param(dcontext, param_base, 8);
prot = (uint) postsys_param(dcontext, param_base, 9);
/* we assume that since syscall succeeded these dereferences are safe
* FIXME : could always be multi-thread races though */
size = *view_size; /* ignore commit_size? */
base = *((app_pc *)pbase_unsafe);
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 1,
"syscall: NtMapViewOfSection "PFX" size="PIFX" prot=%s => "PFX"\n",
base, size, prot_string(prot), mc->xax);
if (is_phandle_me(process_handle)) {
/* Check if we are looking for LdrpLoadImportModule address */
if (dcontext == early_inject_load_helper_dcontext) {
check_for_ldrpLoadImportModule(base, (uint *) mc->xbp);
}
DOLOG(1, LOG_MEMSTATS, {
/* snapshots are heavyweight, so do rarely */
if (size > SNAPSHOT_THRESHOLD)
mem_stats_snapshot();
});
#ifdef DGC_DIAGNOSTICS
DOLOG(1, LOG_VMAREAS, {
dump_callstack(POST_SYSCALL_PC(dcontext),
(app_pc) mc->xbp, THREAD,
DUMP_NOT_XML);
});
#endif
RSTATS_INC(num_app_mmaps);
if (!DYNAMO_OPTION(thin_client)) {
const char *file = NULL;
DEBUG_DECLARE(const char *reason = "";)
if (DYNAMO_OPTION(track_module_filenames)) {
bool unknown = true;
/* get_mapped_file_name always gives an absolute path, so it's
* preferable to using our section_to_file table. but,
* get_mapped_file_name only works on image sections on XP+.
* we go ahead and use it on all sections here, even though
* we don't use the names of non-image sections, to avoid
* warnings below (where we don't know whether image or not).
*/
wchar_t buf[MAXIMUM_PATH];
/* FIXME: should we heap alloc to avoid these huge buffers */
wchar_t buf2[MAXIMUM_PATH];
NTSTATUS res = get_mapped_file_name(base, buf, BUFFER_SIZE_BYTES(buf));
if (NT_SUCCESS(res)) {
if (convert_NT_to_Dos_path(buf2, buf, BUFFER_SIZE_ELEMENTS(buf2))) {
file = dr_wstrdup(buf2 HEAPACCT(ACCT_VMAREAS));
} else {
file = dr_wstrdup(buf HEAPACCT(ACCT_VMAREAS));
STATS_INC(map_unknown_Dos_name);
SYSLOG_INTERNAL_WARNING_ONCE("unknown mapfile Dos name");
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"\t%s: WARNING: unable to convert NT to Dos path for \"%S\"\n",
__FUNCTION__, buf2);
}
/* may as well update the table: if already there this is a nop */
section_to_file_add(section_handle, file);
unknown = false;
} else if (res == STATUS_FILE_INVALID) {
/* An anonymous section backed by the pagefile. Should we
* verify that its CreateSection was passed NULL for a file?
* You can see some of these just starting up calc. They
* have names like
* "\BaseNamedObjects\CiceroSharedMemDefaultS-1-5-21-1262752155-650278929-1212509807-100"
*/
unknown = false;
DODEBUG(reason = " (pagefile-backed)";);
} else {
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"\tget_mapped_file_name failed error="PFX"\n", res);
}
if (file == NULL) {
file = section_to_file_lookup(section_handle);
if (file != NULL)
unknown = false;
}
if (unknown) {
/* Since we have a process-wide handle map and we watch
* close and duplicate, we should only mess up when handles
* are passed via IPC.
*/
STATS_INC(map_section_mismatch);
SYSLOG_INTERNAL_WARNING_ONCE("unknown mapped section "PIFX,
section_handle);
}
}
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"\tNtMapViewOfSection: sec handle "PIFX" == file \"%s\"%s\n",
section_handle, file == NULL ? "<null>" : file, reason);
process_mmap(dcontext, base, size, true/*map*/, file);
if (file != NULL)
dr_strfree(file HEAPACCT(ACCT_VMAREAS));
}
} else {
IPC_ALERT("WARNING: MapViewOfSection on another process");
}
}
/* NtUnmapViewOfSection{,Ex} */
static void
postsys_UnmapViewOfSection(dcontext_t *dcontext, reg_t *param_base, bool success)
{
/* This is what actually removes a dll from memory */
HANDLE process_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
#ifdef DEBUG
if (dcontext->expect_last_syscall_to_fail) {
ASSERT(!success);
} else {
/* FIXME : try to recover if the syscall fails, could re-walk this
* region but that gets us in trouble with the stateful policies */
ASSERT_CURIOSITY(success || !is_phandle_me(process_handle));
}
#endif
/* note that if expected this to fail we wouldn't have really registered,
* but we don't keep track in release builds
*/
if (DYNAMO_OPTION(unloaded_target_exception) &&
is_phandle_me(process_handle)) {
app_pc base = (app_pc) postsys_param(dcontext, param_base, 1);
/* We always mark end of unmap no matter what the original
* section really was. FIXME: Note we can't get the real_base
* of the allocation, unless we keep it in dcontext from
* presys_UnmapViewOfSection, but we don't really need it in
* release build. We don't care about success or !success
* either. Note that this means that if a MEM_MAPPED UnMap
* ends before an overlapping MEM_IMAGE UnMap, we will mark
* end too early.
*/
mark_unload_end(base);
}
}
/* NtDuplicateObject */
static void
postsys_DuplicateObject(dcontext_t *dcontext, reg_t *param_base, bool success)
{
if (DYNAMO_OPTION(track_module_filenames) && success) {
HANDLE src_process = (HANDLE) postsys_param(dcontext, param_base, 0);
HANDLE tgt_process = (HANDLE) postsys_param(dcontext, param_base, 2);
if (is_phandle_me(src_process) && is_phandle_me(tgt_process)) {
HANDLE src = (HANDLE) postsys_param(dcontext, param_base, 1);
HANDLE *dst = (HANDLE*) postsys_param(dcontext, param_base, 3);
const char *file = section_to_file_lookup(src);
if (file != NULL) {
HANDLE dup;
if (safe_read(dst, sizeof(dup), &dup)) {
/* Should already be converted to Dos path */
section_to_file_add(dup, file);
LOG(THREAD, LOG_SYSCALLS|LOG_VMAREAS, 2,
"syscall: NtDuplicateObject section handle "PFX" => "PFX"\n",
src, dup);
} else /* shouldn't happen: syscall succeeded; must be race */
ASSERT_NOT_REACHED();
dr_strfree(file HEAPACCT(ACCT_VMAREAS));
}
} else {
IPC_ALERT("WARNING: handle via IPC may mess up section-to-handle mapping");
}
}
}
#ifdef CLIENT_INTERFACE
/* i#537: sysenter returns to KiFastSystemCallRet from kernel, and returns to DR
* from there. We restore the correct app return target and re-execute
* KiFastSystemCallRet to make sure client see the code at KiFastSystemCallRet.
*/
static void
restore_for_KiFastSystemCallRet(dcontext_t *dcontext)
{
reg_t adjust_esp;
ASSERT(get_syscall_method() == SYSCALL_METHOD_SYSENTER &&
KiFastSystemCallRet_address != NULL);
#ifdef CLIENT_INTERFACE
/* We don't want to do this adjustment until after the final syscall
* in any invoke-another sequence (i#1210)
*/
if (instrument_invoke_another_syscall(dcontext))
return;
#endif
/* If this thread is native, don't disrupt the return-to-native */
if (!dcontext->thread_record->under_dynamo_control)
return;
adjust_esp = get_mcontext(dcontext)->xsp - XSP_SZ;
*(app_pc *)adjust_esp = dcontext->asynch_target;
get_mcontext(dcontext)->xsp = adjust_esp;
dcontext->asynch_target = KiFastSystemCallRet_address;
}
#endif
/* NOTE : no locks can be grabbed on the path to SuspendThread handling code */
void post_system_call(dcontext_t *dcontext)
{
/* registers have been clobbered, so grab key values that were
* saved in pre_system_call
*/
int sysnum = dcontext->sys_num;
reg_t *param_base = dcontext->sys_param_base;
priv_mcontext_t *mc = get_mcontext(dcontext);
bool success = NT_SUCCESS(mc->xax);
where_am_i_t old_whereami = dcontext->whereami;
KSTART(post_syscall);
dcontext->whereami = WHERE_SYSCALL_HANDLER;
DODEBUG({ dcontext->post_syscall = true; });
LOG(THREAD, LOG_SYSCALLS, 2,
"post syscall: sysnum="PFX", params @"PFX", result="PFX"\n",
sysnum, param_base, mc->xax);
if (sysnum == syscalls[SYS_GetContextThread]) {
postsys_GetContextThread(dcontext, param_base, success);
}
else if (sysnum == syscalls[SYS_SuspendThread]) {
postsys_SuspendThread(dcontext, param_base, success);
}
else if (sysnum == syscalls[SYS_SetContextThread]) {
HANDLE thread_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
thread_id_t tid = thread_handle_to_tid(thread_handle);
ASSERT(tid != 0xFFFFFFFF);
/* FIXME : we modified the passed in context, we should restore it
* to app state (same for SYS_Continue though is more difficult there)
*/
mutex_lock(&thread_initexit_lock); /* need lock to lookup thread */
if (intercept_asynch_for_thread(tid, false/*no unknown threads*/)) {
/* Case 10101: we shouldn't get here since we now skip the system call,
* unless it should fail for permission issues */
ASSERT(dcontext->expect_last_syscall_to_fail);
/* must wake up thread so it can go to nt_continue_dynamo_start */
nt_thread_resume(thread_handle, NULL);
}
mutex_unlock(&thread_initexit_lock); /* need lock to lookup thread */
}
else if (sysnum == syscalls[SYS_OpenThread]) {
postsys_OpenThread(dcontext, param_base, success);
}
#ifdef CLIENT_INTERFACE
else if (sysnum == syscalls[SYS_QueryInformationThread]) {
postsys_QueryInformationThread(dcontext, param_base, success);
}
#endif
else if (sysnum == syscalls[SYS_AllocateVirtualMemory] ||
/* i#899: new win8 syscall w/ similar params to NtAllocateVirtualMemory */
sysnum == syscalls[SYS_Wow64AllocateVirtualMemory64]) {
KSTART(post_syscall_alloc);
postsys_AllocateVirtualMemory(dcontext, param_base, success, sysnum);
KSTOP(post_syscall_alloc);
}
else if (sysnum == syscalls[SYS_QueryVirtualMemory]) {
postsys_QueryVirtualMemory(dcontext, param_base, success);
}
else if (sysnum == syscalls[SYS_CreateSection]) {
postsys_CreateSection(dcontext, param_base, success);
}
else if (sysnum == syscalls[SYS_OpenSection]) {
postsys_OpenSection(dcontext, param_base, success);
}
else if (sysnum == syscalls[SYS_MapViewOfSection]) {
KSTART(post_syscall_map);
postsys_MapViewOfSection(dcontext, param_base, success);
KSTOP(post_syscall_map);
}
else if (sysnum == syscalls[SYS_CreateProcess]) {
HANDLE *process_handle = (HANDLE *) postsys_param(dcontext, param_base, 0);
uint access_mask = (uint) postsys_param(dcontext, param_base, 1);
uint attributes = (uint) postsys_param(dcontext, param_base, 2);
uint inherit_from= (uint) postsys_param(dcontext, param_base, 3);
BOOLEAN inherit = (BOOLEAN) postsys_param(dcontext, param_base, 4);
HANDLE section_handle = (HANDLE) postsys_param(dcontext, param_base, 5);
HANDLE debug_handle = (HANDLE) postsys_param(dcontext, param_base, 6);
HANDLE exception_handle = (HANDLE) postsys_param(dcontext, param_base, 7);
HANDLE proc_handle;
DOLOG(1, LOG_SYSCALLS, {
app_pc base = (app_pc) get_section_address(section_handle);
LOG(THREAD, LOG_SYSCALLS, IF_DGCDIAG_ELSE(1, 2),
"syscall post: NtCreateProcess section @"PFX"\n", base);
});
if (success && safe_read(process_handle, sizeof(proc_handle), &proc_handle))
maybe_inject_into_process(dcontext, proc_handle, NULL);
}
else if (sysnum == syscalls[SYS_CreateProcessEx]) {
HANDLE *process_handle = (HANDLE *) postsys_param(dcontext, param_base, 0);
uint access_mask = (uint) postsys_param(dcontext, param_base, 1);
uint attributes = (uint) postsys_param(dcontext, param_base, 2);
uint inherit_from= (uint) postsys_param(dcontext, param_base, 3);
BOOLEAN inherit = (BOOLEAN) postsys_param(dcontext, param_base, 4);
HANDLE section_handle = (HANDLE) postsys_param(dcontext, param_base, 5);
HANDLE debug_handle = (HANDLE) postsys_param(dcontext, param_base, 6);
HANDLE exception_handle = (HANDLE) postsys_param(dcontext, param_base, 7);
HANDLE proc_handle;
/* according to metasploit, others type as HANDLE unknown etc. */
uint job_member_level = (uint) postsys_param(dcontext, param_base, 8);
DOLOG(1, LOG_SYSCALLS, {
if (section_handle != 0) {
app_pc base = (app_pc) get_section_address(section_handle);
LOG(THREAD, LOG_SYSCALLS, IF_DGCDIAG_ELSE(1, 2),
"syscall: NtCreateProcessEx section @"PFX"\n", base);
}
});
if (success && safe_read(process_handle, sizeof(proc_handle), &proc_handle))
maybe_inject_into_process(dcontext, proc_handle, NULL);
}
else if (sysnum == syscalls[SYS_CreateUserProcess]) {
postsys_CreateUserProcess(dcontext, param_base, success);
}
else if (sysnum == syscalls[SYS_UnmapViewOfSection] ||
sysnum == syscalls[SYS_UnmapViewOfSectionEx]) {
postsys_UnmapViewOfSection(dcontext, param_base, success);
}
else if (sysnum == syscalls[SYS_DuplicateObject]) {
postsys_DuplicateObject(dcontext, param_base, success);
#ifdef DEBUG
/* Check to see if any system calls for which we did non-reversible
* processing in pre_system_call() failed. FIXME : handle failure
* cases as needed */
/* FIXME : because of our stateless apc handling we can't check
* SYS_Continue for success (all syscalls interrupted by an APC will
* look like a continue at post)
*/
} else if (sysnum == syscalls[SYS_CallbackReturn]) {
/* should never get here, also ref case 4121, except for
* STATUS_CALLBACK_POP_STACK (case 10579) */
ASSERT_CURIOSITY((NTSTATUS)postsys_param(dcontext, param_base, 2) ==
STATUS_CALLBACK_POP_STACK);
/* FIXME: should provide a routine to swap the dcontexts back so we can
* handle any future cases like case 10579 */
} else if (sysnum == syscalls[SYS_TerminateProcess]) {
HANDLE process_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
NTSTATUS exit_status = (NTSTATUS) postsys_param(dcontext, param_base, 1);
/* FIXME : no way to recover if syscall fails and handle is 0 or us */
/* Don't allow success && handle == us since we should never get here
* in that case */
ASSERT((process_handle == 0 && success) ||
!is_phandle_me(process_handle));
} else if (sysnum == syscalls[SYS_TerminateThread]) {
HANDLE thread_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
ASSERT(thread_handle != 0); /* 0 => current thread */
if (thread_handle != 0) {
thread_id_t tid = thread_handle_to_tid(thread_handle);
process_id_t pid = thread_handle_to_pid(thread_handle, tid);
ASSERT(tid != get_thread_id()); /* not current thread */
/* FIXME : if is thread in this process and syscall fails then
* no way to recover since we already cleaned up the thread */
/* Don't allow success && handle == us since we should never get
* here in that case */
ASSERT(success ||
tid == 0xFFFFFFFF /* prob. bad/incorrect type handle */ ||
is_thread_exited(thread_handle) == THREAD_EXITED ||
!is_pid_me(pid));
if (success && !is_pid_me(pid)) {
IPC_ALERT("Warning: NtTerminateThread on thread tid="PFX" "
"in other process pid="PFX, tid, pid);
}
}
} else if (sysnum == syscalls[SYS_CreateThread]) {
HANDLE process_handle= (HANDLE) postsys_param(dcontext, param_base, 3);
CONTEXT *cxt = (CONTEXT *) postsys_param(dcontext, param_base, 5);
/* FIXME : we are going to read cxt, this is potentially unsafe */
if (is_first_thread_in_new_process(process_handle, cxt)) {
/* we might have tried to inject into the process with this
* new thread, assert curiosity to see if this ever fails */
ASSERT_CURIOSITY(success);
}
} else if (sysnum == syscalls[SYS_FreeVirtualMemory]) {
HANDLE process_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
void **pbase = (void **) postsys_param(dcontext, param_base, 1);
size_t *psize = (size_t *) postsys_param(dcontext, param_base, 2);
uint type = (uint) postsys_param(dcontext, param_base, 3);
if (dcontext->expect_last_syscall_to_fail) {
ASSERT(!success);
} else {
/* FIXME i#148: try to recover if the syscall fails, could re-walk this
* region but that gets us in trouble with the stateful policies */
ASSERT_CURIOSITY_ONCE(success || !is_phandle_me(process_handle));;
}
} else if (sysnum == syscalls[SYS_ProtectVirtualMemory]) {
HANDLE process_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
if (dcontext->expect_last_syscall_to_fail) {
ASSERT(!success);
} else {
/* FIXME : try to recover if the syscall fails, could re-walk this
* region but that gets us in trouble with the stateful policies */
ASSERT_CURIOSITY(success || !is_phandle_me(process_handle));
}
} else if (sysnum == syscalls[SYS_FlushInstructionCache]) {
HANDLE process_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
/* Even if this system call fails, doesn't affect our correctness, but
* lets see if this ever fails, slight false negative risk if it does */
ASSERT_CURIOSITY(success || !is_phandle_me(process_handle));
} else if (sysnum == syscalls[SYS_MapUserPhysicalPages]) {
HANDLE process_handle = (HANDLE) postsys_param(dcontext, param_base, 0);
/* Even if this system call fails, doesn't affect our correctness, but
* lets see if this ever fails, slight false negative risk if it does */
if (dcontext->expect_last_syscall_to_fail) {
ASSERT(!success);
} else {
ASSERT_CURIOSITY(success || !is_phandle_me(process_handle));
}
#endif /* DEBUG */
}
#ifdef CLIENT_INTERFACE
/* The instrument_post_syscall should be called after DR finishes all
* its operations. Xref to i#1.
*/
/* i#202: ignore native syscalls in early_inject_init() */
if (dynamo_initialized)
instrument_post_syscall(dcontext, sysnum);
/* i#537 restore app stack for KiFastSystemCallRet
* this could be in [email protected], but seems better
* here since it is windows specific.
*/
if (get_syscall_method() == SYSCALL_METHOD_SYSENTER &&
KiFastSystemCallRet_address != NULL)
restore_for_KiFastSystemCallRet(dcontext);
#endif
/* stats lock grabbing ok here, any synch with suspended threads taken
* care of already */
RSTATS_INC(post_syscall);
DOSTATS({
if (ignorable_system_call(sysnum, NULL, dcontext))
STATS_INC(post_syscall_ignorable);
});
dcontext->whereami = old_whereami;
DODEBUG({ dcontext->post_syscall = false; });
KSTOP(post_syscall);
}
/***************************************************************************
* SYSTEM CALL API
*/
#ifdef CLIENT_INTERFACE
DR_API
reg_t
dr_syscall_get_param(void *drcontext, int param_num)
{
dcontext_t *dcontext = (dcontext_t *) drcontext;
priv_mcontext_t *mc = get_mcontext(dcontext);
/* if we supported this from post-syscall we would need to
* get dcontext->sys_param_base() and call postsys_param() -- but
* then it would be confusing vs client checking its set param
*/
reg_t *param_base = pre_system_call_param_base(mc);
CLIENT_ASSERT(dcontext->client_data->in_pre_syscall,
"dr_syscall_get_param() can only be called from pre-syscall event");
return sys_param(dcontext, param_base, param_num);
}
DR_API
void
dr_syscall_set_param(void *drcontext, int param_num, reg_t new_value)
{
dcontext_t *dcontext = (dcontext_t *) drcontext;
priv_mcontext_t *mc = get_mcontext(dcontext);
reg_t *param_base;
CLIENT_ASSERT(dcontext->client_data->in_pre_syscall ||
dcontext->client_data->in_post_syscall,
"dr_syscall_set_param() can only be called from a syscall event");
if (dcontext->client_data->in_pre_syscall)
param_base = pre_system_call_param_base(mc);
else
param_base = dcontext->sys_param_base;
*sys_param_addr(dcontext, param_base, param_num) = new_value;
}
DR_API
reg_t
dr_syscall_get_result(void *drcontext)
{
dcontext_t *dcontext = (dcontext_t *) drcontext;
CLIENT_ASSERT(dcontext->client_data->in_post_syscall,
"dr_syscall_get_result() can only be called from post-syscall event");
return get_mcontext(dcontext)->xax;
}
DR_API
bool
dr_syscall_get_result_ex(void *drcontext, dr_syscall_result_info_t *info INOUT)
{
dcontext_t *dcontext = (dcontext_t *) drcontext;
CLIENT_ASSERT(dcontext->client_data->in_post_syscall,
"only call dr_syscall_get_result_ex() from post-syscall event");
CLIENT_ASSERT(info != NULL, "invalid parameter");
CLIENT_ASSERT(info->size == sizeof(*info), "invalid dr_syscall_result_info_t size");
if (info->size != sizeof(*info))
return false;
info->value = dr_syscall_get_result(drcontext);
/* We document not to rely on this for non-ntoskrnl syscalls */
info->succeeded = NT_SUCCESS(info->value);
if (info->use_high)
info->high = 0;
if (info->use_errno)
info->errno_value = (uint) info->value;
return true;
}
DR_API
void
dr_syscall_set_result(void *drcontext, reg_t value)
{
dcontext_t *dcontext = (dcontext_t *) drcontext;
CLIENT_ASSERT(dcontext->client_data->in_pre_syscall ||
dcontext->client_data->in_post_syscall,
"dr_syscall_set_result() can only be called from a syscall event");
SET_RETURN_VAL(dcontext, value);
}
DR_API
bool
dr_syscall_set_result_ex(void *drcontext, dr_syscall_result_info_t *info)
{
dcontext_t *dcontext = (dcontext_t *) drcontext;
CLIENT_ASSERT(dcontext->client_data->in_pre_syscall ||
dcontext->client_data->in_post_syscall,
"only call dr_syscall_set_result_ex() from a syscall event");
CLIENT_ASSERT(info != NULL, "invalid parameter");
CLIENT_ASSERT(info->size == sizeof(*info), "invalid dr_syscall_result_info_t size");
if (info->size != sizeof(*info))
return false;
if (info->use_high)
return false; /* not supported */
/* we ignore info->succeeded */
if (info->use_errno)
SET_RETURN_VAL(dcontext, info->errno_value);
else
SET_RETURN_VAL(dcontext, info->value);
return true;
}
DR_API
void
dr_syscall_set_sysnum(void *drcontext, int new_num)
{
dcontext_t *dcontext = (dcontext_t *) drcontext;
priv_mcontext_t *mc = get_mcontext(dcontext);
CLIENT_ASSERT(dcontext->client_data->in_pre_syscall ||
dcontext->client_data->in_post_syscall,
"dr_syscall_set_sysnum() can only be called from a syscall event");
mc->xax = new_num;
}
DR_API
void
dr_syscall_invoke_another(void *drcontext)
{
dcontext_t *dcontext = (dcontext_t *) drcontext;
priv_mcontext_t *mc = get_mcontext(dcontext);
CLIENT_ASSERT(dcontext->client_data->in_post_syscall,
"dr_syscall_invoke_another() can only be called from post-syscall event");
LOG(THREAD, LOG_SYSCALLS, 2, "invoking additional syscall on client request\n");
/* Dispatch checks this flag immediately upon return from handle_post_system_call()
* and if set it invokes handle_system_call().
*/
dcontext->client_data->invoke_another_syscall = true;
if (get_syscall_method() == SYSCALL_METHOD_SYSENTER) {
/* Since we're not regaining control immediately after sysenter,
* need to push regain-control retaddr on stack, and then copy esp to edx.
*/
mc->xsp -= XSP_SZ;
/* put the post-call-to-vsyscall address, currently in asynch_target, back
* on stack, and set asynch_target back to post-sysenter pc (will be put
* into next_tag back in handle_post_system_call())
*/
*((app_pc *)mc->xsp) = dcontext->asynch_target;
dcontext->asynch_target = vsyscall_syscall_end_pc;
mc->xdx = mc->xsp;
}
else if (get_syscall_method() == SYSCALL_METHOD_WOW64) {
if (get_os_version() == WINDOWS_VERSION_7) {
/* emulate win7's add 4,esp after the call* in the syscall wrapper */
mc->xsp += XSP_SZ;
}
if (syscall_uses_edx_param_base()) {
/* perform: lea edx,[esp+0x4] */
mc->xdx = mc->xsp + XSP_SZ;
}
}
else if (get_syscall_method() == SYSCALL_METHOD_INT) {
if (syscall_uses_edx_param_base()) {
/* perform: lea edx,[esp+0x4] */
mc->xdx = mc->xsp + XSP_SZ;
}
}
# ifdef X64
else if (get_syscall_method() == SYSCALL_METHOD_SYSCALL) {
/* sys_param_addr() is already using r10 */
}
# endif
}
DR_API
bool
dr_syscall_intercept_natively(const char *name, int sysnum, int num_args,
int wow64_idx)
{
uint i, idx;
if (syscall_extra_idx >= CLIENT_EXTRA_TRAMPOLINE)
return false;
if (dynamo_initialized)
return false;
/* see whether we already intercept it */
for (i = 0; i < SYS_MAX + syscall_extra_idx; i++) {
if (intercept_native_syscall(i) && strcmp(syscall_names[i], name) == 0)
return true;
}
if (get_proc_address(get_ntdll_base(), name) == NULL)
return false;
/* no lock needed since only supported during dr_client_main */
idx = SYS_MAX + syscall_extra_idx;
syscall_names[idx] = name;
syscalls[idx] = sysnum;
syscall_argsz[idx] = num_args * 4;
if (wow64_index != NULL)
wow64_index[idx] = wow64_idx;
syscall_requires_action[idx] = true;
syscall_extra_idx++;
/* some syscalls we just don't support intercepting */
if (!intercept_native_syscall(idx)) {
LOG(GLOBAL, LOG_SYSCALLS, 2, "%s: %s is not interceptable!\n",
__FUNCTION__, name);
syscall_extra_idx--;
return false;
}
LOG(GLOBAL, LOG_SYSCALLS, 2, "%s: intercepting %s as index %d\n",
__FUNCTION__, name, idx);
return true;
}
#endif /* CLIENT_INTERFACE */
| 1 | 10,743 | If this can change the PC of this thread, it requires handling: we can't blindly execute the syscall and lose control of the thread when the flags include CONTEXT_CONTROL. (Note that most docs imply that setting your own context this way is not supported or has undefined or unpredictable results: any idea how often that's the case, or does it generally work?) We need to handle in a similar fashion to NtContinue or setting another thread's context to ensure we retain control. | DynamoRIO-dynamorio | c |
@@ -333,5 +333,8 @@ public interface OpenFoodAPIService {
*/
@GET("state/to-be-completed/{page}.json")
Call<Search> getIncompleteProducts(@Path("page") int page);
+
+ @GET("/.json")
+ Call<Search> getTotalProductCount();
}
| 1 | package openfoodfacts.github.scrachx.openfood.network;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.ArrayList;
import java.util.Map;
import io.reactivex.Single;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import openfoodfacts.github.scrachx.openfood.models.Search;
import openfoodfacts.github.scrachx.openfood.models.SendProduct;
import openfoodfacts.github.scrachx.openfood.models.State;
import openfoodfacts.github.scrachx.openfood.models.TagsWrapper;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.PartMap;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
/**
* Define our Open Food Facts API endpoints.
* All REST methods such as GET, POST, PUT, UPDATE, DELETE can be stated in here.
*/
public interface OpenFoodAPIService {
String PRODUCT_API_COMMENT = "Official Android app";
@GET("api/v0/product/{barcode}.json?fields=image_small_url,vitamins_tags,minerals_tags,amino_acids_tags,other_nutritional_substances_tags,image_front_url,image_ingredients_url,image_nutrition_url,url,code,traces_tags,ingredients_that_may_be_from_palm_oil_tags,additives_tags,allergens_hierarchy,manufacturing_places,nutriments,ingredients_from_palm_oil_tags,brands_tags,traces,categories_tags,ingredients_text,product_name,generic_name,ingredients_from_or_that_may_be_from_palm_oil_n,serving_size,allergens,origins,stores,nutrition_grade_fr,nutrient_levels,countries,countries_tags,brands,packaging,labels_tags,labels_hierarchy,cities_tags,quantity,ingredients_from_palm_oil_n,image_url,link,emb_codes_tags,states_tags,creator,created_t,last_modified_t,last_modified_by,editors_tags,nova_groups,lang,purchase_places,nutrition_data_per,no_nutrition_data")
Call<State> getFullProductByBarcode(@Path("barcode") String barcode);
@GET("api/v0/product/{barcode}.json")
Single<State> getExistingProductDetails(@Path("barcode") String barcode,
@Query("fields") String fields);
@GET("api/v0/product/{barcode}.json?fields=image_small_url,vitamins_tags,minerals_tags,amino_acids_tags,other_nutritional_substances_tags,image_front_url,image_ingredients_url,image_nutrition_url,url,code,traces_tags,ingredients_that_may_be_from_palm_oil_tags,additives_tags,allergens_hierarchy,manufacturing_places,nutriments,ingredients_from_palm_oil_tags,brands_tags,traces,categories_tags,ingredients_text,product_name,generic_name,ingredients_from_or_that_may_be_from_palm_oil_n,serving_size,allergens,origins,stores,nutrition_grade_fr,nutrient_levels,countries,countries_tags,brands,packaging,labels_tags,labels_hierarchy,cities_tags,quantity,ingredients_from_palm_oil_n,image_url,link,emb_codes_tags,states_tags,creator,created_t,last_modified_t,last_modified_by,editors_tags,nova_groups,lang,purchase_places,nutrition_data_per,no_nutrition_data")
Single<State> getFullProductByBarcodeSingle(@Path("barcode") String barcode);
@GET("cgi/product_jqm2.pl")
Single<State> saveProductSingle(@Query("code") String code,
@QueryMap Map<String, String> parameters,
@Query("comment") String comment);
@GET("api/v0/product/{barcode}.json?fields=image_small_url,product_name,brands,quantity,image_url,nutrition_grade_fr,code")
Call<State> getShortProductByBarcode(@Path("barcode") String barcode);
@GET("cgi/search.pl?search_simple=1&json=1&action=process&fields=image_small_url,product_name,brands,quantity,code,nutrition_grade_fr")
Call<Search> searchProductByName(@Query("search_terms") String name, @Query("page") int page);
@FormUrlEncoded
@POST("/cgi/session.pl")
Call<ResponseBody> signIn(@Field("user_id") String login, @Field("password") String password, @Field(".submit") String submit);
@POST("/cgi/product_jqm2.pl")
Call<State> saveProduct(@Body SendProduct product);
/**
* waiting https://github.com/openfoodfacts/openfoodfacts-server/issues/510 to use saveProduct(SendProduct)
*/
@Deprecated
@GET("/cgi/product_jqm2.pl")
Call<State> saveProduct(@Query("code") String code,
@Query("lang") String lang,
@Query("product_name") String name,
@Query("brands") String brands,
@Query("quantity") String quantity,
@Query("user_id") String login,
@Query("password") String password,
@Query("comment") String comment);
/**
* This method is used to upload those products which
* does not contain Name of the product.
* here name query is not present to make sure if the product is already present
* then the server would not assume to delete it.
*/
@Deprecated
@GET("/cgi/product_jqm2.pl")
Call<State> saveProductWithoutName(@Query("code") String code,
@Query("lang") String lang,
@Query("brands") String brands,
@Query("quantity") String quantity,
@Query("user_id") String login,
@Query("password") String password,
@Query("comment") String comment);
/**
* This method is used to upload those products which
* does not contain Brands of the product.
* here Brands query is not present to make sure if the product is already present
* then the server would not assume to delete it.
*/
@Deprecated
@GET("/cgi/product_jqm2.pl")
Call<State> saveProductWithoutBrands(@Query("code") String code,
@Query("lang") String lang,
@Query("product_name") String name,
@Query("quantity") String quantity,
@Query("user_id") String login,
@Query("password") String password,
@Query("comment") String comment);
/**
* This method is used to upload those products which
* does not contain Quantity of the product.
* here Quantity query is not present to make sure if the product is already present
* then the server would not assume to delete it.
*/
@Deprecated
@GET("/cgi/product_jqm2.pl")
Call<State> saveProductWithoutQuantity(@Query("code") String code,
@Query("lang") String lang,
@Query("product_name") String name,
@Query("brands") String brands,
@Query("user_id") String login,
@Query("password") String password,
@Query("comment") String comment);
/**
* This method is used to upload those products which
* does not contain Name and Brands of the product.
* here Name and Brands query is not present to make sure if the product is already present
* then the server would not assume to delete it.
*/
@Deprecated
@GET("/cgi/product_jqm2.pl")
Call<State> saveProductWithoutNameAndBrands(@Query("code") String code,
@Query("lang") String lang,
@Query("quantity") String quantity,
@Query("user_id") String login,
@Query("password") String password,
@Query("comment") String comment);
/**
* This method is used to upload those products which
* does not contain Name and Quantity of the product.
* here Name and Quantity query is not present to make sure if the product is already present
* then the server would not assume to delete it.
*/
@Deprecated
@GET("/cgi/product_jqm2.pl")
Call<State> saveProductWithoutNameAndQuantity(@Query("code") String code,
@Query("lang") String lang,
@Query("brands") String brands,
@Query("user_id") String login,
@Query("password") String password,
@Query("comment") String comment);
/**
* This method is used to upload those products which
* does not contain Brands and Quantity of the product.
* here Brands and Quantity query is not present to make sure if the product is already present
* then the server would not assume to delete it.
*/
@Deprecated
@GET("/cgi/product_jqm2.pl")
Call<State> saveProductWithoutBrandsAndQuantity(@Query("code") String code,
@Query("lang") String lang,
@Query("product_name") String name,
@Query("user_id") String login,
@Query("password") String password,
@Query("comment") String comment);
/**
* This method is used to upload those products which
* does not contain Brands, Name and Quantity of the product.
* here Brands, Name and Quantity query is not present to make sure if the product is already present
* then the server would not assume to delete it.
*/
@Deprecated
@GET("/cgi/product_jqm2.pl")
Call<State> saveProductWithoutNameBrandsAndQuantity(@Query("code") String code,
@Query("lang") String lang,
@Query("user_id") String login,
@Query("password") String password,
@Query("comment") String comment);
@Multipart
@POST("/cgi/product_image_upload.pl")
Call<JsonNode> saveImage(@PartMap Map<String, RequestBody> fields);
@Multipart
@POST("/cgi/product_image_upload.pl")
Single<JsonNode> saveImageSingle(@PartMap Map<String, RequestBody> fields);
@GET("/cgi/product_image_crop.pl")
Single<JsonNode> editImageSingle(@Query("code") String code,
@QueryMap Map<String, String> fields);
@GET("/cgi/ingredients.pl?process_image=1&ocr_engine=google_cloud_vision")
Single<JsonNode> getIngredients(@Query("code") String code,
@Query("id") String id);
@GET("cgi/suggest.pl?tagtype=emb_codes")
Single<ArrayList<String>> getEMBCodeSuggestions(@Query("term") String term);
@GET("/cgi/suggest.pl?tagtype=periods_after_opening")
Single<ArrayList<String>> getPeriodAfterOpeningSuggestions(@Query("term") String term);
@GET("brand/{brand}/{page}.json")
Call<Search> getProductByBrands(@Path("brand") String brand, @Path("page") int page);
@GET("additive/{additive}/{page}.json")
Call<Search> getProductsByAdditive(@Path("additive") String additive, @Path("page") int page);
@GET("country/{country}/{page}.json")
Call<Search> getProductsByCountry(@Path("country") String country, @Path("page") int page);
@GET("store/{store}/{page}.json")
Call<Search> getProductByStores(@Path("store") String store, @Path("page") int page);
@GET("packaging/{packaging}/{page}.json")
Call<Search> getProductByPackaging(@Path("packaging") String packaging, @Path("page") int page);
@GET("label/{label}/{page}.json")
Call<Search> getProductByLabel(@Path("label") String label, @Path("page") int page);
@GET("category/{category}/{page}.json?fields=product_name,brands,quantity,image_small_url,nutrition_grade_fr,code")
Call<Search> getProductByCategory(@Path("category") String category, @Path("page") int page);
@GET("contributor/{Contributor}/{page}.json")
Call<Search> searchProductsByContributor(@Path("Contributor") String Contributor, @Path("page") int page);
@GET("language/{language}.json")
Call<Search> byLanguage(@Path("language") String language);
@GET("label/{label}.json")
Call<Search> byLabel(@Path("label") String label);
@GET("category/{category}.json")
Call<Search> byCategory(@Path("category") String category);
@GET("state/{state}.json")
Call<Search> byState(@Path("state") String state);
@GET("packaging/{packaging}.json")
Call<Search> byPackaging(@Path("packaging") String packaging);
@GET("brand/{brand}.json")
Call<Search> byBrand(@Path("brand") String brand);
@GET("purchase-place/{purchasePlace}.json")
Call<Search> byPurchasePlace(@Path("purchasePlace") String purchasePlace);
@GET("store/{store}.json")
Call<Search> byStore(@Path("store") String store);
@GET("country/{country}.json")
Call<Search> byCountry(@Path("country") String country);
@GET("trace/{trace}.json")
Call<Search> byTrace(@Path("trace") String trace);
@GET("packager-code/{PackagerCode}.json")
Call<Search> byPackagerCode(@Path("PackagerCode") String PackagerCode);
@GET("city/{City}.json")
Call<Search> byCity(@Path("City") String City);
@GET("nutrition-grade/{NutritionGrade}.json")
Call<Search> byNutritionGrade(@Path("NutritionGrade") String NutritionGrade);
@GET("nutrient-level/{NutrientLevel}.json")
Call<Search> byNutrientLevel(@Path("NutrientLevel") String NutrientLevel);
@GET("contributor/{Contributor}.json")
Call<Search> byContributor(@Path("Contributor") String Contributor);
@GET("contributor/{Contributor}/state/to-be-completed/{page}.json")
Call<Search> getToBeCompletedProductsByContributor(@Path("Contributor") String Contributor, @Path("page") int page);
@GET("/photographer/{Contributor}/{page}.json")
Call<Search> getPicturesContributedProducts(@Path("Contributor") String Contributor, @Path("page") int page);
@GET("photographer/{Photographer}.json")
Call<Search> byPhotographer(@Path("Photographer") String Photographer);
@GET("photographer/{Contributor}/state/to-be-completed/{page}.json")
Call<Search> getPicturesContributedIncompleteProducts(@Path("Contributor") String Contributor, @Path("page") int page);
@GET("informer/{Informer}.json")
Call<Search> byInformer(@Path("Informer") String Informer);
@GET("informer/{Contributor}/{page}.json")
Call<Search> getInfoAddedProducts(@Path("Contributor") String Contributor, @Path("page") int page);
@GET("informer/{Contributor}/state/to-be-completed/{page}.json")
Call<Search> getInfoAddedIncompleteProducts(@Path("Contributor") String Contributor, @Path("page") int page);
@GET("last-edit-date/{LastEditDate}.json")
Call<Search> byLastEditDate(@Path("LastEditDate") String LastEditDate);
@GET("entry-dates/{EntryDates}.json")
Call<Search> byEntryDates(@Path("EntryDates") String EntryDates);
@GET("unknown-nutrient/{UnknownNutrient}.json")
Call<Search> byUnknownNutrient(@Path("UnknownNutrient") String UnknownNutrient);
@GET("additive/{Additive}.json")
Call<Search> byAdditive(@Path("Additive") String Additive);
@GET("code/{Code}.json")
Call<Search> byCode(@Path("Code") String Code);
@GET("packager-codes.json")
Single<TagsWrapper> getTags();
@GET("state/{State}/{page}.json")
Call<Search> getProductsByState(@Path("State") String state, @Path("page") int page);
/**
* Open Beauty Facts experimental and specific APIs
*/
@GET("period-after-opening/{PeriodAfterOpening}.json")
Call<Search> byPeriodAfterOpening(@Path("PeriodAfterOpening") String PeriodAfterOpening);
@GET("ingredient/{ingredient}.json")
Call<Search> byIngredient(@Path("ingredient") String ingredient);
/**
* This method gives a list of incomplete products
*/
@GET("state/to-be-completed/{page}.json")
Call<Search> getIncompleteProducts(@Path("page") int page);
}
| 1 | 65,770 | @huzaifaiftikhar Changed the endpoint as suggested by Stephane in the latest commit. | openfoodfacts-openfoodfacts-androidapp | java |
@@ -21,10 +21,14 @@ type Value struct {
Uint64 uint64
Float64 float64
String string
- Bytes []byte
- // TODO See how segmentio/stats handles this type, it's much smaller.
- // TODO Lazy value type?
+ // Note: this type could be made smaller by using a
+ // core.Number to represent four of these fields, e.g.,
+ // struct {
+ // Type ValueType
+ // String string
+ // Number Number
+ // }
}
const ( | 1 | package core
import (
"fmt"
"unsafe"
)
type Key string
type KeyValue struct {
Key Key
Value Value
}
type ValueType int
type Value struct {
Type ValueType
Bool bool
Int64 int64
Uint64 uint64
Float64 float64
String string
Bytes []byte
// TODO See how segmentio/stats handles this type, it's much smaller.
// TODO Lazy value type?
}
const (
INVALID ValueType = iota
BOOL
INT32
INT64
UINT32
UINT64
FLOAT32
FLOAT64
STRING
BYTES
)
func (k Key) Bool(v bool) KeyValue {
return KeyValue{
Key: k,
Value: Value{
Type: BOOL,
Bool: v,
},
}
}
func (k Key) Int64(v int64) KeyValue {
return KeyValue{
Key: k,
Value: Value{
Type: INT64,
Int64: v,
},
}
}
func (k Key) Uint64(v uint64) KeyValue {
return KeyValue{
Key: k,
Value: Value{
Type: UINT64,
Uint64: v,
},
}
}
func (k Key) Float64(v float64) KeyValue {
return KeyValue{
Key: k,
Value: Value{
Type: FLOAT64,
Float64: v,
},
}
}
func (k Key) Int32(v int32) KeyValue {
return KeyValue{
Key: k,
Value: Value{
Type: INT32,
Int64: int64(v),
},
}
}
func (k Key) Uint32(v uint32) KeyValue {
return KeyValue{
Key: k,
Value: Value{
Type: UINT32,
Uint64: uint64(v),
},
}
}
func (k Key) Float32(v float32) KeyValue {
return KeyValue{
Key: k,
Value: Value{
Type: FLOAT32,
Float64: float64(v),
},
}
}
func (k Key) String(v string) KeyValue {
return KeyValue{
Key: k,
Value: Value{
Type: STRING,
String: v,
},
}
}
func (k Key) Bytes(v []byte) KeyValue {
return KeyValue{
Key: k,
Value: Value{
Type: BYTES,
Bytes: v,
},
}
}
func (k Key) Int(v int) KeyValue {
if unsafe.Sizeof(v) == 4 {
return k.Int32(int32(v))
}
return k.Int64(int64(v))
}
func (k Key) Uint(v uint) KeyValue {
if unsafe.Sizeof(v) == 4 {
return k.Uint32(uint32(v))
}
return k.Uint64(uint64(v))
}
func (k Key) Defined() bool {
return len(k) != 0
}
// TODO make this a lazy one-time conversion.
func (v Value) Emit() string {
switch v.Type {
case BOOL:
return fmt.Sprint(v.Bool)
case INT32, INT64:
return fmt.Sprint(v.Int64)
case UINT32, UINT64:
return fmt.Sprint(v.Uint64)
case FLOAT32, FLOAT64:
return fmt.Sprint(v.Float64)
case STRING:
return v.String
case BYTES:
return string(v.Bytes)
}
return "unknown"
}
| 1 | 10,259 | There's no core.Number yet. ;) | open-telemetry-opentelemetry-go | go |
@@ -24,6 +24,18 @@ import (
"github.com/spf13/cobra"
)
+var (
+ snapshotrevertHelpText = `
+Usage: mayactl snapshot revert [options]
+
+$ mayactl snapshot revert --volname <vol> --snapname <snap>
+
+This command rolls back the volume data to the specified snapshot.
+Once the roll back to snapshot is successful, all the data changes made after the snapshot was taken will be post.
+This command should be used cautiously and only when there is an issue with the current state of the data.
+`
+)
+
/*type CmdSnaphotCreateOptions struct {
volName string
snapName string | 1 | /*
Copyright 2017 The OpenEBS Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package snapshot
import (
"fmt"
"github.com/openebs/maya/pkg/client/mapiserver"
"github.com/openebs/maya/pkg/util"
"github.com/spf13/cobra"
)
/*type CmdSnaphotCreateOptions struct {
volName string
snapName string
}*/
// NewCmdSnapshotRevert reverts a snapshot of OpenEBS Volume
func NewCmdSnapshotRevert() *cobra.Command {
options := CmdSnaphotCreateOptions{}
cmd := &cobra.Command{
Use: "revert",
Short: "Reverts to specific snapshot of a Volume",
Long: "Reverts to specific snapshot of a Volume",
Run: func(cmd *cobra.Command, args []string) {
util.CheckErr(options.Validate(cmd), util.Fatal)
util.CheckErr(options.RunSnapshotRevert(cmd), util.Fatal)
},
}
cmd.Flags().StringVarP(&options.volName, "volname", "n", options.volName,
"unique volume name.")
cmd.MarkPersistentFlagRequired("volname")
cmd.MarkPersistentFlagRequired("snapname")
cmd.Flags().StringVarP(&options.snapName, "snapname", "s", options.snapName,
"unique snapshot name")
return cmd
}
// RunSnapshotRevert does tasks related to mayaserver.
func (c *CmdSnaphotCreateOptions) RunSnapshotRevert(cmd *cobra.Command) error {
fmt.Println("Executing volume snapshot revert ...")
resp := mapiserver.RevertSnapshot(c.volName, c.snapName)
if resp != nil {
return fmt.Errorf("Error: %v", resp)
}
fmt.Printf("Reverting to snapshot [%s] of volume [%s]\n", c.snapName, c.volName)
return nil
}
| 1 | 8,200 | ..., ...will be posted. | openebs-maya | go |
@@ -14,7 +14,7 @@ func (f *Filecoin) ShowBlock(ctx context.Context, ref cid.Cid) (*types.Block, er
sRef := ref.String()
- if err := f.RunCmdJSONWithStdin(ctx, nil, &out, "go-filecoin", "show", "block", sRef); err != nil {
+ if err := f.RunCmdJSONWithStdin(ctx, nil, &out, "go-filecoin", "show", "header", sRef); err != nil {
return nil, err
}
| 1 | package fast
import (
"context"
"github.com/ipfs/go-cid"
"github.com/filecoin-project/go-filecoin/types"
)
// ShowBlock runs the `show block` command against the filecoin process
func (f *Filecoin) ShowBlock(ctx context.Context, ref cid.Cid) (*types.Block, error) {
var out types.Block
sRef := ref.String()
if err := f.RunCmdJSONWithStdin(ctx, nil, &out, "go-filecoin", "show", "block", sRef); err != nil {
return nil, err
}
return &out, nil
}
| 1 | 20,748 | Can you update this function to be `ShowHeader`? There is only one use of it at the moment in `tools/fast/series/get_head_block_height.go`. | filecoin-project-venus | go |
@@ -25,6 +25,7 @@ CONFIG_PATH = BASE_PATH / 'config.yml'
OPEN_DATA_URL = "https://open.quiltdata.com"
PACKAGE_NAME_FORMAT = r"([\w-]+/[\w-]+)(?:/(.+))?$"
+DISABLE_TQDM = os.getenv('QUILT_USE_TQDM', '').lower() != 'true'
## CONFIG_TEMPLATE
# Must contain every permitted config key, as well as their default values (which can be 'null'/None). | 1 | import re
from collections import OrderedDict
from collections.abc import Mapping, Sequence, Set
import datetime
import json
import os
import pathlib
from urllib.parse import parse_qs, quote, unquote, urlencode, urlparse, urlunparse
from urllib.request import pathname2url, url2pathname
import warnings
# Third-Party
import yaml
from appdirs import user_cache_dir, user_data_dir
import requests
APP_NAME = "Quilt"
APP_AUTHOR = "QuiltData"
BASE_DIR = user_data_dir(APP_NAME, APP_AUTHOR)
BASE_PATH = pathlib.Path(BASE_DIR)
CACHE_PATH = pathlib.Path(user_cache_dir(APP_NAME, APP_AUTHOR)) / "v0"
TEMPFILE_DIR_PATH = BASE_PATH / "tempfiles"
CONFIG_PATH = BASE_PATH / 'config.yml'
OPEN_DATA_URL = "https://open.quiltdata.com"
PACKAGE_NAME_FORMAT = r"([\w-]+/[\w-]+)(?:/(.+))?$"
## CONFIG_TEMPLATE
# Must contain every permitted config key, as well as their default values (which can be 'null'/None).
# Comments are retained and added to local config, unless overridden by autoconfig via `api.config(<url>)`
CONFIG_TEMPLATE = """
# Quilt3 configuration file
# navigator_url: <url string, default: null>
#
# Used for autoconfiguration
# navigator_url: https://example.com
navigator_url:
# default_local_registry: <url string, default: local appdirs>
# default target registry for operations like install and build
default_local_registry: "{}"
# default_remote_registry: <url string, default: null>
# default target for operations like push and browse
default_remote_registry:
# default_install_location: <url string, default: null>
# default filesystem target for the install operation
default_install_location:
# Identity service URL
registryUrl:
# Disable anonymous usage metrics
telemetry_disabled: false
# S3 Proxy
s3Proxy:
# API Gateway endpoint (e.g., for search)
apiGatewayEndpoint:
# Binary API Gateway endpoint (e.g., for preview)
binaryApiGatewayEndpoint:
""".format(BASE_PATH.as_uri() + '/packages')
class QuiltException(Exception):
def __init__(self, message, **kwargs):
# We use NewError("Prefix: " + str(error)) a lot.
# To be consistent across Python 2.7 and 3.x:
# 1) This `super` call must exist, or 2.7 will have no text for str(error)
# 2) This `super` call must have only one argument (the message) or str(error) will be a repr of args
super(QuiltException, self).__init__(message)
self.message = message
for k, v in kwargs.items():
setattr(self, k, v)
class PhysicalKey(object):
__slots__ = ['bucket', 'path', 'version_id']
def __init__(self, bucket, path, version_id):
"""
For internal use only; call from_path or from_url instead.
"""
assert bucket is None or isinstance(bucket, str)
assert isinstance(path, str)
assert version_id is None or isinstance(version_id, str)
if bucket is None:
assert path is not None, "Local keys must have a path"
assert version_id is None, "Local keys cannot have a version ID"
if os.name == 'nt':
assert '\\' not in path, "Paths must use / as a separator"
else:
assert not path.startswith('/'), "S3 paths must not start with '/'"
self.bucket = bucket
self.path = path
self.version_id = version_id
@classmethod
def from_url(cls, url):
parsed = urlparse(url)
if parsed.scheme == 's3':
if not parsed.netloc:
raise ValueError("Missing bucket")
bucket = parsed.netloc
assert not parsed.path or parsed.path.startswith('/')
path = unquote(parsed.path)[1:]
# Parse the version ID the way the Java SDK does:
# https://github.com/aws/aws-sdk-java/blob/master/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3URI.java#L192
query = parse_qs(parsed.query)
version_id = query.pop('versionId', [None])[0]
if query:
raise ValueError(f"Unexpected S3 query string: {parsed.query!r}")
return cls(bucket, path, version_id)
elif parsed.scheme == 'file':
if parsed.netloc not in ('', 'localhost'):
raise ValueError("Unexpected hostname")
if not parsed.path:
raise ValueError("Missing path")
if not parsed.path.startswith('/'):
raise ValueError("Relative paths are not allowed")
if parsed.query:
raise ValueError("Unexpected query")
path = url2pathname(parsed.path)
if parsed.path.endswith('/') and not path.endswith(os.path.sep):
# On Windows, url2pathname loses the trailing `/`.
path += os.path.sep
return cls.from_path(path)
else:
raise ValueError(f"Unexpected scheme: {parsed.scheme!r}")
@classmethod
def from_path(cls, path):
path = os.fspath(path)
new_path = os.path.realpath(path)
# Use '/' as the path separator.
if os.path.sep != '/':
new_path = new_path.replace(os.path.sep, '/')
# Add back a trailing '/' if the original path has it.
if (path.endswith(os.path.sep) or
(os.path.altsep is not None and path.endswith(os.path.altsep))):
new_path += '/'
return cls(None, new_path, None)
def is_local(self):
return self.bucket is None
def join(self, rel_path):
if self.version_id is not None:
raise ValueError('Cannot append paths to URLs with a version ID')
if os.name == 'nt' and '\\' in rel_path:
raise ValueError("Paths must use / as a separator")
if self.path:
new_path = self.path.rstrip('/') + '/' + rel_path.lstrip('/')
else:
new_path = rel_path.lstrip('/')
return PhysicalKey(self.bucket, new_path, None)
def basename(self):
return self.path.rsplit('/', 1)[-1]
def __eq__(self, other):
return (
isinstance(other, self.__class__) and
self.bucket == other.bucket and
self.path == other.path and
self.version_id == other.version_id
)
def __repr__(self):
return f'{self.__class__.__name__}({self.bucket!r}, {self.path!r}, {self.version_id!r})'
def __str__(self):
if self.bucket is None:
return urlunparse(('file', '', pathname2url(self.path.replace('/', os.path.sep)), None, None, None))
else:
if self.version_id is None:
params = {}
else:
params = {'versionId': self.version_id}
return urlunparse(('s3', self.bucket, quote(self.path), None, urlencode(params), None))
def fix_url(url):
"""Convert non-URL paths to file:// URLs"""
# If it has a scheme, we assume it's a URL.
# On Windows, we ignore schemes that look like drive letters, e.g. C:/users/foo
if not url:
raise ValueError("Empty URL")
url = str(url)
parsed = urlparse(url)
if parsed.scheme and not os.path.splitdrive(url)[0]:
return url
# `expanduser()` expands any leading "~" or "~user" path components, as a user convenience
# `resolve()` _tries_ to make the URI absolute - but doesn't guarantee anything.
# In particular, on Windows, non-existent files won't be resolved.
# `absolute()` makes the URI absolute, though it can still contain '..'
fixed_url = pathlib.Path(url).expanduser().resolve().absolute().as_uri()
# pathlib likes to remove trailing slashes, so add it back if needed.
if url[-1:] in (os.sep, os.altsep) and not fixed_url.endswith('/'):
fixed_url += '/'
return fixed_url
def extract_file_extension(file_path_or_url):
"""
Extract the file extension if it exists.
Args:
file_path_or_url: The path to the file. Type can can be anything that pathlib.Path understands.
Returns:
File extension without the period, i.e. ("txt" not ".txt"). None if the path does not have an extension.
"""
p = pathlib.Path(file_path_or_url)
if len(p.suffix) > 0:
return p.suffix[1:]
else:
return None
def read_yaml(yaml_stream):
try:
if isinstance(yaml_stream, pathlib.PosixPath):
with yaml_stream.open(mode='r') as stream:
return yaml.safe_load(stream)
return yaml.safe_load(yaml_stream)
except yaml.YAMLError as error:
raise QuiltException(str(error), original_error=error)
def write_yaml(data, yaml_path, keep_backup=False):
"""Write `data` to `yaml_path`
:param data: Any yaml-serializable data
:param yaml_path: Destination. Can be a string or pathlib path.
:param keep_backup: If set, a timestamped backup will be kept in the same dir.
"""
path = pathlib.Path(yaml_path)
now = str(datetime.datetime.now())
# XXX unicode colon for Windows/NTFS -- looks prettier, but could be confusing. We could use '_' instead.
if os.name == 'nt':
now = now.replace(':', '\ua789')
backup_path = path.with_name(path.name + '.backup.' + now)
try:
if path.exists():
path.rename(backup_path)
if not path.parent.exists():
path.parent.mkdir(parents=True)
with path.open('w') as config_file:
yaml.dump(data, config_file)
except Exception: #! intentionally wide catch -- reraised immediately.
if backup_path.exists():
if path.exists():
path.unlink()
backup_path.rename(path)
raise
if backup_path.exists() and not keep_backup:
backup_path.unlink()
def validate_url(url):
"""A URL must have scheme and host, at minimum."""
parsed_url = urlparse(url)
# require scheme and host at minimum, like config_path'http://foo'
if not all((parsed_url.scheme, parsed_url.netloc)):
raise QuiltException("Invalid URL -- Requires at least scheme and host: {}".format(url))
try:
parsed_url.port
except ValueError:
raise QuiltException("Invalid URL -- Port must be a number: {}".format(url))
# Although displaying the config may seem not to warrant a class, it's pretty important
# for good UX. A lot of points were considered in making this -- retaining order,
# user's usage in an interpreted environment like Jupyter, and keeping the displayed
# information concise. Given the limitations of the other options, making a class with
# custom repr panned out to be the best (and shortest) option.
class QuiltConfig(OrderedDict):
def __init__(self, filepath, *args, **kwargs):
self.filepath = pathlib.Path(filepath)
super(QuiltConfig, self).__init__(*args, **kwargs)
def __setitem__(self, key, value):
# Per chat in #engineering 4-5-19, strip navigator_url of trailing slash.
# Ideally, we should do that kind of thing in one cohesive spot.
# This is a good spot.
if key == 'navigator_url' and value:
if not isinstance(value, str):
raise ValueError("Expected a string for config key {!r}, but got {!r}"
.format(key, value))
value = value.strip().rstrip('/')
# Similar activity, moved from api.config() to here.
if isinstance(key, str) and key.endswith('_url'):
if value:
validate_url(value)
super().__setitem__(key, value)
# TODO: Make an _html_repr_ for nicer Notebook display
def __repr__(self):
return "<{} at {!r} {}>".format(type(self).__name__, str(self.filepath), json.dumps(self, indent=4))
def parse_sub_package_name(name):
"""
Extract package name and optional sub-package path as tuple.
"""
m = re.match(PACKAGE_NAME_FORMAT, name)
if m:
return tuple(m.groups())
def validate_package_name(name):
""" Verify that a package name is two alphanumeric strings separated by a slash."""
parts = parse_sub_package_name(name)
if not parts or parts[1]:
raise QuiltException(f"Invalid package name: {name}.")
def get_package_registry(path=None):
""" Returns the package registry root for a given path """
if path is None:
path = get_from_config('default_local_registry')
return path.rstrip('/') + '/.quilt'
def configure_from_url(catalog_url):
""" Read configuration settings from a Quilt catalog """
config_template = read_yaml(CONFIG_TEMPLATE)
# Clean up and validate catalog url
catalog_url = catalog_url.rstrip('/')
validate_url(catalog_url)
# Get the new config
config_url = catalog_url + '/config.json'
response = requests.get(config_url)
if not response.ok:
message = "An HTTP Error ({code}) occurred: {reason}"
raise QuiltException(
message.format(code=response.status_code, reason=response.reason),
response=response
)
# QuiltConfig may perform some validation and value scrubbing.
new_config = QuiltConfig('', response.json())
# 'navigator_url' needs to be renamed, the term is outdated.
if not new_config.get('navigator_url'):
new_config['navigator_url'] = catalog_url
# Use our template + their configured values, keeping our comments.
for key, value in new_config.items():
if not key in config_template:
continue
config_template[key] = value
write_yaml(config_template, CONFIG_PATH, keep_backup=True)
return config_template
def config_exists():
"""
Returns True if a config file (config.yml) is installed.
"""
return CONFIG_PATH.exists()
def user_is_configured_to_custom_stack():
"""Look at the users stack to see if they have configured to their own stack. There is currently no way to
distinguish between someone who has not configured their stack and someone who has intentionally configured
their stack to use open.quiltdata.com"""
configured_nav_url = get_from_config("navigator_url")
return configured_nav_url is not None and configured_nav_url != OPEN_DATA_URL
def configure_from_default():
"""
Try to configure to the default (public) Quilt stack.
If reading from the public stack fails, warn the user
and save an empty template.
"""
try:
local_config = configure_from_url(OPEN_DATA_URL)
except requests.exceptions.ConnectionError:
msg = f"Failed to connect to {OPEN_DATA_URL}."
msg += "Some features will not work without a"
msg += "valid configuration."
warnings.warn(msg)
config_template = read_yaml(CONFIG_TEMPLATE)
write_yaml(config_template, CONFIG_PATH, keep_backup=True)
local_config = config_template
return local_config
def load_config():
"""
Read the local config using defaults from CONFIG_TEMPLATE.
"""
local_config = read_yaml(CONFIG_TEMPLATE)
if CONFIG_PATH.exists():
local_config.update(read_yaml(CONFIG_PATH))
return local_config
def get_from_config(key):
return load_config().get(key)
def get_install_location():
loc = get_from_config('default_install_location')
if loc is None:
loc = get_from_config('default_local_registry').rstrip('/')
return loc
def set_config_value(key, value):
# Use local configuration (or defaults)
local_config = load_config()
local_config[key] = value
write_yaml(local_config, CONFIG_PATH)
def quiltignore_filter(paths, ignore, url_scheme):
"""Given a list of paths, filter out the paths which are captured by the
given ignore rules.
Args:
paths (list): a list or iterable of paths
ignore (path): a path to the file defining ignore rules, in Unix shell
style wildcard format
url_scheme (str): the URL scheme, only the "file" scheme is currently
supported
"""
ignore_rules = ignore.read_text('utf-8').split("\n")
ignore_rules = ['*/' + rule for rule in ignore_rules if rule]
if url_scheme == 'file':
from fnmatch import fnmatch
files, dirs = set(), set()
for path in paths:
if path.is_file():
files.add(path)
else:
dirs.add(path)
filtered_dirs = dirs.copy()
for ignore_rule in ignore_rules:
for pkg_dir in filtered_dirs.copy():
# copy git behavior --- git matches paths and directories equivalently.
# e.g. both foo and foo/ will match the ignore rule "foo"
# but only foo/ will match the ignore rule "foo/"
if fnmatch(pkg_dir.as_posix() + "/", ignore_rule) or fnmatch(pkg_dir.as_posix(), ignore_rule):
files = set(n for n in files if pkg_dir not in n.parents)
dirs = dirs - {pkg_dir}
files = set(n for n in files if not fnmatch(n, ignore_rule))
return files.union(dirs)
else:
raise NotImplementedError
def validate_key(key):
"""
Verify that a file path or S3 path does not contain any '.' or '..' separators or files.
"""
if key is None or key == '':
raise QuiltException(
f"Invalid key {key!r}. A package entry key cannot be empty."
)
for part in key.split('/'):
if part in ('', '.', '..'):
raise QuiltException(
f"Invalid key {key!r}. "
f"A package entry key cannot contain a file or folder named '.' or '..' in its path."
)
def catalog_s3_url(catalog_url, s3_url):
"""
Generate a URL to the Quilt catalog page for an object in S3
"""
if s3_url is None:
return catalog_url
pk = PhysicalKey.from_url(s3_url)
if pk.is_local():
raise QuiltException("Not an S3 URL")
url = f"{catalog_url}/b/{quote(pk.bucket)}"
if pk.path:
url += f"/tree/{quote(pk.path)}"
# Ignore version_id if path is empty (e.g., s3://<bucket>)
if pk.version_id is not None:
params = {'version': pk.version_id}
url += f"?{urlencode(params)}"
return url
def catalog_package_url(catalog_url, bucket, package_name, package_timestamp="latest"):
"""
Generate a URL to the Quilt catalog page of a package. By default will go to the latest version of the package,
but the user can pass in the appropriate timestamp to go to a different version.
Note: There is currently no good way to generate the URL given a specific tophash
"""
assert bucket is not None, "The bucket parameter must not be None"
assert package_name is not None, "The package_name parameter must not be None"
validate_package_name(package_name)
return f"{catalog_url}/b/{bucket}/packages/{package_name}/tree/{package_timestamp}"
| 1 | 18,420 | @akarve, this disables `tqdm` by default, is it intended? Also name `QUILT_USE_TQDM` might be too specific, IMHO `QUILT_INTERACTIVE` or `QUILT_PROGRESS_BARS` or something might be better. | quiltdata-quilt | py |
@@ -46,7 +46,7 @@ func testENIAckTimeout(t *testing.T, attachmentType string) {
taskEngineState := dockerstate.NewTaskEngineState()
- expiresAt := time.Now().Add(time.Duration(waitTimeoutMillis) * time.Millisecond)
+ expiresAt := time.Now().Add(time.Millisecond * waitTimeoutMillis)
err := addENIAttachmentToState(attachmentType, attachmentArn, taskArn, randomMAC, expiresAt, taskEngineState)
assert.NoError(t, err)
assert.Len(t, taskEngineState.(*dockerstate.DockerTaskEngineState).AllENIAttachments(), 1) | 1 | // +build unit
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package handler
import (
"testing"
"time"
apieni "github.com/aws/amazon-ecs-agent/agent/api/eni"
"github.com/aws/amazon-ecs-agent/agent/engine/dockerstate"
"github.com/aws/amazon-ecs-agent/agent/statemanager"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
)
const (
attachmentArn = "attachmentarn"
)
// TestTaskENIAckTimeout tests acknowledge timeout for a task eni before submit the state change
func TestTaskENIAckTimeout(t *testing.T) {
testENIAckTimeout(t, apieni.ENIAttachmentTypeTaskENI)
}
// TestInstanceENIAckTimeout tests acknowledge timeout for an instance level eni before submit the state change
func TestInstanceENIAckTimeout(t *testing.T) {
testENIAckTimeout(t, apieni.ENIAttachmentTypeInstanceENI)
}
func testENIAckTimeout(t *testing.T, attachmentType string) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
taskEngineState := dockerstate.NewTaskEngineState()
expiresAt := time.Now().Add(time.Duration(waitTimeoutMillis) * time.Millisecond)
err := addENIAttachmentToState(attachmentType, attachmentArn, taskArn, randomMAC, expiresAt, taskEngineState)
assert.NoError(t, err)
assert.Len(t, taskEngineState.(*dockerstate.DockerTaskEngineState).AllENIAttachments(), 1)
for {
time.Sleep(time.Millisecond * waitTimeoutMillis)
if len(taskEngineState.(*dockerstate.DockerTaskEngineState).AllENIAttachments()) == 0 {
break
}
}
}
// TestTaskENIAckWithinTimeout tests the eni state change was reported before the timeout, for a task eni
func TestTaskENIAckWithinTimeout(t *testing.T) {
testENIAckWithinTimeout(t, apieni.ENIAttachmentTypeTaskENI)
}
// TestInstanceENIAckWithinTimeout tests the eni state change was reported before the timeout, for an instance eni
func TestInstanceENIAckWithinTimeout(t *testing.T) {
testENIAckWithinTimeout(t, apieni.ENIAttachmentTypeInstanceENI)
}
func testENIAckWithinTimeout(t *testing.T, attachmentType string) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
taskEngineState := dockerstate.NewTaskEngineState()
expiresAt := time.Now().Add(time.Duration(waitTimeoutMillis) * time.Millisecond)
err := addENIAttachmentToState(attachmentType, attachmentArn, taskArn, randomMAC, expiresAt, taskEngineState)
assert.NoError(t, err)
assert.Len(t, taskEngineState.(*dockerstate.DockerTaskEngineState).AllENIAttachments(), 1)
eniAttachment, ok := taskEngineState.(*dockerstate.DockerTaskEngineState).ENIByMac(randomMAC)
assert.True(t, ok)
eniAttachment.SetSentStatus()
time.Sleep(time.Millisecond * waitTimeoutMillis)
assert.Len(t, taskEngineState.(*dockerstate.DockerTaskEngineState).AllENIAttachments(), 1)
}
// TestHandleENIAttachmentTaskENI tests handling a new task eni
func TestHandleENIAttachmentTaskENI(t *testing.T) {
testHandleENIAttachment(t, apieni.ENIAttachmentTypeTaskENI, taskArn)
}
// TestHandleENIAttachmentInstanceENI tests handling a new instance eni
func TestHandleENIAttachmentInstanceENI(t *testing.T) {
testHandleENIAttachment(t, apieni.ENIAttachmentTypeInstanceENI, "")
}
func testHandleENIAttachment(t *testing.T, attachmentType, taskArn string) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
taskEngineState := dockerstate.NewTaskEngineState()
expiresAt := time.Now().Add(time.Duration(waitTimeoutMillis) * time.Millisecond)
stateManager := statemanager.NewNoopStateManager()
err := handleENIAttachment(attachmentType, attachmentArn, taskArn, randomMAC, expiresAt, taskEngineState, stateManager)
assert.NoError(t, err)
assert.Len(t, taskEngineState.(*dockerstate.DockerTaskEngineState).AllENIAttachments(), 1)
eniAttachment, ok := taskEngineState.(*dockerstate.DockerTaskEngineState).ENIByMac(randomMAC)
assert.True(t, ok)
eniAttachment.SetSentStatus()
time.Sleep(time.Millisecond * waitTimeoutMillis)
assert.Len(t, taskEngineState.(*dockerstate.DockerTaskEngineState).AllENIAttachments(), 1)
}
| 1 | 23,430 | unrelated but just changing for consistency with code below it | aws-amazon-ecs-agent | go |
@@ -78,12 +78,8 @@ export function renderComponent(component, opts, mountAll, isChild) {
component.props = previousProps;
component.state = previousState;
component.context = previousContext;
- if (opts!==FORCE_RENDER
- && component.shouldComponentUpdate
- && component.shouldComponentUpdate(props, state, context) === false) {
- skip = true;
- }
- else if (component.componentWillUpdate) {
+ skip = opts!==FORCE_RENDER && component.shouldComponentUpdate && component.shouldComponentUpdate(props, state, context) === false;
+ if (component.componentWillUpdate) {
component.componentWillUpdate(props, state, context);
}
component.props = props; | 1 | import { SYNC_RENDER, NO_RENDER, FORCE_RENDER, ASYNC_RENDER, ATTR_KEY } from '../constants';
import options from '../options';
import { extend } from '../util';
import { enqueueRender } from '../render-queue';
import { getNodeProps } from './index';
import { diff, mounts, diffLevel, flushMounts, recollectNodeTree, removeChildren } from './diff';
import { createComponent, collectComponent } from './component-recycler';
import { removeNode } from '../dom';
/** Set a component's `props` (generally derived from JSX attributes).
* @param {Object} props
* @param {Object} [opts]
* @param {boolean} [opts.renderSync=false] If `true` and {@link options.syncComponentUpdates} is `true`, triggers synchronous rendering.
* @param {boolean} [opts.render=true] If `false`, no render will be triggered.
*/
export function setComponentProps(component, props, opts, context, mountAll) {
if (component._disable) return;
component._disable = true;
if ((component.__ref = props.ref)) delete props.ref;
if ((component.__key = props.key)) delete props.key;
if (!component.base || mountAll) {
if (component.componentWillMount) component.componentWillMount();
}
else if (component.componentWillReceiveProps) {
component.componentWillReceiveProps(props, context);
}
if (context && context!==component.context) {
if (!component.prevContext) component.prevContext = component.context;
component.context = context;
}
if (!component.prevProps) component.prevProps = component.props;
component.props = props;
component._disable = false;
if (opts!==NO_RENDER) {
if (opts===SYNC_RENDER || options.syncComponentUpdates!==false || !component.base) {
renderComponent(component, SYNC_RENDER, mountAll);
}
else {
enqueueRender(component);
}
}
if (component.__ref) component.__ref(component);
}
/** Render a Component, triggering necessary lifecycle events and taking High-Order Components into account.
* @param {Component} component
* @param {Object} [opts]
* @param {boolean} [opts.build=false] If `true`, component will build and store a DOM node if not already associated with one.
* @private
*/
export function renderComponent(component, opts, mountAll, isChild) {
if (component._disable) return;
let props = component.props,
state = component.state,
context = component.context,
previousProps = component.prevProps || props,
previousState = component.prevState || state,
previousContext = component.prevContext || context,
isUpdate = component.base,
nextBase = component.nextBase,
initialBase = isUpdate || nextBase,
initialChildComponent = component._component,
skip = false,
rendered, inst, cbase;
// if updating
if (isUpdate) {
component.props = previousProps;
component.state = previousState;
component.context = previousContext;
if (opts!==FORCE_RENDER
&& component.shouldComponentUpdate
&& component.shouldComponentUpdate(props, state, context) === false) {
skip = true;
}
else if (component.componentWillUpdate) {
component.componentWillUpdate(props, state, context);
}
component.props = props;
component.state = state;
component.context = context;
}
component.prevProps = component.prevState = component.prevContext = component.nextBase = null;
component._dirty = false;
if (!skip) {
rendered = component.render(props, state, context);
// context to pass to the child, can be updated via (grand-)parent component
if (component.getChildContext) {
context = extend(extend({}, context), component.getChildContext());
}
let childComponent = rendered && rendered.nodeName,
toUnmount, base;
if (typeof childComponent==='function') {
// set up high order component link
let childProps = getNodeProps(rendered);
inst = initialChildComponent;
if (inst && inst.constructor===childComponent && childProps.key==inst.__key) {
setComponentProps(inst, childProps, SYNC_RENDER, context, false);
}
else {
toUnmount = inst;
component._component = inst = createComponent(childComponent, childProps, context);
inst.nextBase = inst.nextBase || nextBase;
inst._parentComponent = component;
setComponentProps(inst, childProps, NO_RENDER, context, false);
renderComponent(inst, SYNC_RENDER, mountAll, true);
}
base = inst.base;
}
else {
cbase = initialBase;
// destroy high order component link
toUnmount = initialChildComponent;
if (toUnmount) {
cbase = component._component = null;
}
if (initialBase || opts===SYNC_RENDER) {
if (cbase) cbase._component = null;
base = diff(cbase, rendered, context, mountAll || !isUpdate, initialBase && initialBase.parentNode, true);
}
}
if (initialBase && base!==initialBase && inst!==initialChildComponent) {
let baseParent = initialBase.parentNode;
if (baseParent && base!==baseParent) {
baseParent.replaceChild(base, initialBase);
if (!toUnmount) {
initialBase._component = null;
recollectNodeTree(initialBase, false);
}
}
}
if (toUnmount) {
unmountComponent(toUnmount);
}
component.base = base;
if (base && !isChild) {
let componentRef = component,
t = component;
while ((t=t._parentComponent)) {
(componentRef = t).base = base;
}
base._component = componentRef;
base._componentConstructor = componentRef.constructor;
}
}
if (!isUpdate || mountAll) {
mounts.unshift(component);
}
else if (!skip) {
// Ensure that pending componentDidMount() hooks of child components
// are called before the componentDidUpdate() hook in the parent.
flushMounts();
if (component.componentDidUpdate) {
component.componentDidUpdate(previousProps, previousState, previousContext);
}
if (options.afterUpdate) options.afterUpdate(component);
}
if (component._renderCallbacks!=null) {
while (component._renderCallbacks.length) component._renderCallbacks.pop().call(component);
}
if (!diffLevel && !isChild) flushMounts();
}
/** Apply the Component referenced by a VNode to the DOM.
* @param {Element} dom The DOM node to mutate
* @param {VNode} vnode A Component-referencing VNode
* @returns {Element} dom The created/mutated element
* @private
*/
export function buildComponentFromVNode(dom, vnode, context, mountAll) {
let c = dom && dom._component,
originalComponent = c,
oldDom = dom,
isDirectOwner = c && dom._componentConstructor===vnode.nodeName,
isOwner = isDirectOwner,
props = getNodeProps(vnode);
while (c && !isOwner && (c=c._parentComponent)) {
isOwner = c.constructor===vnode.nodeName;
}
if (c && isOwner && (!mountAll || c._component)) {
setComponentProps(c, props, ASYNC_RENDER, context, mountAll);
dom = c.base;
}
else {
if (originalComponent && !isDirectOwner) {
unmountComponent(originalComponent);
dom = oldDom = null;
}
c = createComponent(vnode.nodeName, props, context);
if (dom && !c.nextBase) {
c.nextBase = dom;
// passing dom/oldDom as nextBase will recycle it if unused, so bypass recycling on L229:
oldDom = null;
}
setComponentProps(c, props, SYNC_RENDER, context, mountAll);
dom = c.base;
if (oldDom && dom!==oldDom) {
oldDom._component = null;
recollectNodeTree(oldDom, false);
}
}
return dom;
}
/** Remove a component from the DOM and recycle it.
* @param {Element} dom A DOM node from which to unmount the given Component
* @param {Component} component The Component instance to unmount
* @private
*/
export function unmountComponent(component) {
if (options.beforeUnmount) options.beforeUnmount(component);
let base = component.base;
component._disable = true;
if (component.componentWillUnmount) component.componentWillUnmount();
component.base = null;
// recursively tear down & recollect high-order component children:
let inner = component._component;
if (inner) {
unmountComponent(inner);
}
else if (base) {
if (base[ATTR_KEY] && base[ATTR_KEY].ref) base[ATTR_KEY].ref(null);
component.nextBase = base;
removeNode(base);
collectComponent(component);
removeChildren(base);
}
if (component.__ref) component.__ref(null);
}
| 1 | 10,828 | This will call `componentWillUpdate()` for mounts because the else clause is removed. It should only be called for updates. | preactjs-preact | js |
@@ -56,6 +56,12 @@ PERMISSIONS_INHERITANCE_TREE = {
'group': ['write', 'read']
},
},
+ 'history': {
+ 'read': {
+ 'bucket': ['write', 'read'],
+ 'history': ['write', 'read']
+ },
+ },
'collection': {
'write': {
'bucket': ['write'], | 1 | import re
from pyramid.security import IAuthorizationPolicy
from zope.interface import implementer
from kinto.core import authorization as core_authorization
# Vocab really matters when you deal with permissions. Let's do a quick recap
# of the terms used here:
#
# Object URI:
# An unique identifier for an object.
# for instance, /buckets/blog/collections/articles/records/article1
#
# Object:
# A common denomination of an object (e.g. "collection" or "record")
#
# Unbound permission:
# A permission not bound to an object (e.g. "create")
#
# Bound permission:
# A permission bound to an object (e.g. "collection:create")
# Dictionary which list all permissions a given permission enables.
PERMISSIONS_INHERITANCE_TREE = {
'': { # Granted via settings only.
'bucket:create': {},
'write': {},
'read': {},
},
'bucket': {
'write': {
'bucket': ['write']
},
'read': {
'bucket': ['write', 'read'],
},
'read:attributes': {
'bucket': ['write', 'read', 'collection:create', 'group:create']
},
'group:create': {
'bucket': ['write', 'group:create']
},
'collection:create': {
'bucket': ['write', 'collection:create']
},
},
'group': {
'write': {
'bucket': ['write'],
'group': ['write']
},
'read': {
'bucket': ['write', 'read'],
'group': ['write', 'read']
},
},
'collection': {
'write': {
'bucket': ['write'],
'collection': ['write'],
},
'read': {
'bucket': ['write', 'read'],
'collection': ['write', 'read'],
},
'read:attributes': {
'bucket': ['write', 'read'],
'collection': ['write', 'read', 'record:create'],
},
'record:create': {
'bucket': ['write'],
'collection': ['write', 'record:create']
},
},
'record': {
'write': {
'bucket': ['write'],
'collection': ['write'],
'record': ['write']
},
'read': {
'bucket': ['write', 'read'],
'collection': ['write', 'read'],
'record': ['write', 'read']
},
}
}
def _resource_endpoint(object_uri):
"""Determine the resource name and whether it is the plural endpoint from
the specified `object_uri`. Returns `(None, None)` for the root URL plural
endpoint.
"""
url_patterns = [
('record', r'/buckets/(.+)/collections/(.+)/records/(.+)?'),
('collection', r'/buckets/(.+)/collections/(.+)?'),
('group', r'/buckets/(.+)/groups/(.+)?'),
('bucket', r'/buckets/(.+)?'),
('', r'/(buckets)') # Root buckets list.
]
for resource_name, pattern in url_patterns:
m = re.match(pattern, object_uri)
if m:
plural = '/' in m.groups()[-1]
return resource_name, plural
raise ValueError("%r is not a resource." % object_uri)
def _relative_object_uri(resource_name, object_uri):
"""Returns object_uri
"""
obj_parts = object_uri.split('/')
PARTS_LENGTH = {
'': 1,
'bucket': 3,
'collection': 5,
'group': 5,
'record': 7
}
length = PARTS_LENGTH[resource_name]
parent_uri = '/'.join(obj_parts[:length])
if length > len(obj_parts):
error_msg = 'Cannot get URL of resource %r from parent %r.'
raise ValueError(error_msg % (resource_name, parent_uri))
return parent_uri
def _inherited_permissions(object_uri, permission):
"""Build the list of all permissions that can grant access to the given
object URI and permission.
>>> _inherited_permissions('/buckets/blog/collections/article', 'read')
[('/buckets/blog/collections/article', 'write'),
('/buckets/blog/collections/article', 'read'),
('/buckets/blog', 'write'),
('/buckets/blog', 'read')]
"""
try:
resource_name, plural = _resource_endpoint(object_uri)
except ValueError:
return [] # URL that are not resources have no inherited perms.
object_perms_tree = PERMISSIONS_INHERITANCE_TREE[resource_name]
# When requesting permissions for a single object, we check if they are any
# specific inherited permissions for the attributes.
attributes_permission = '%s:attributes' % permission if not plural else permission
inherited_perms = object_perms_tree.get(attributes_permission, object_perms_tree[permission])
granters = set()
for related_resource_name, implicit_permissions in inherited_perms.items():
for permission in implicit_permissions:
related_uri = _relative_object_uri(related_resource_name, object_uri)
granters.add((related_uri, permission))
# Sort by ascending URLs.
return sorted(granters, key=lambda uri_perm: len(uri_perm[0]), reverse=True)
@implementer(IAuthorizationPolicy)
class AuthorizationPolicy(core_authorization.AuthorizationPolicy):
def get_bound_permissions(self, *args, **kwargs):
return _inherited_permissions(*args, **kwargs)
class RouteFactory(core_authorization.RouteFactory):
pass
| 1 | 10,263 | We should add write inheritance too. | Kinto-kinto | py |
@@ -12,6 +12,9 @@ from localstack.constants import DEFAULT_SERVICE_PORTS, LOCALHOST, PATH_USER_REQ
TRUE_VALUES = ('1', 'true')
+# java options to Lambda
+
+JAVA_OPTS = os.environ.get('JAVA_OPTS', '').strip()
# randomly inject faults to Kinesis
KINESIS_ERROR_PROBABILITY = float(os.environ.get('KINESIS_ERROR_PROBABILITY', '').strip() or 0.0) | 1 | import re
import os
import socket
import logging
import platform
import tempfile
import subprocess
from os.path import expanduser
import six
from boto3 import Session
from localstack.constants import DEFAULT_SERVICE_PORTS, LOCALHOST, PATH_USER_REQUEST, DEFAULT_PORT_WEB_UI
TRUE_VALUES = ('1', 'true')
# randomly inject faults to Kinesis
KINESIS_ERROR_PROBABILITY = float(os.environ.get('KINESIS_ERROR_PROBABILITY', '').strip() or 0.0)
# randomly inject faults to DynamoDB
DYNAMODB_ERROR_PROBABILITY = float(os.environ.get('DYNAMODB_ERROR_PROBABILITY', '').strip() or 0.0)
# expose services on a specific host internally
HOSTNAME = os.environ.get('HOSTNAME', '').strip() or LOCALHOST
# expose services on a specific host externally
HOSTNAME_EXTERNAL = os.environ.get('HOSTNAME_EXTERNAL', '').strip() or LOCALHOST
# expose SQS on a specific port externally
SQS_PORT_EXTERNAL = int(os.environ.get('SQS_PORT_EXTERNAL') or 0)
# name of the host under which the LocalStack services are available
LOCALSTACK_HOSTNAME = os.environ.get('LOCALSTACK_HOSTNAME', '').strip() or HOSTNAME
# whether to remotely copy the lambda or locally mount a volume
LAMBDA_REMOTE_DOCKER = os.environ.get('LAMBDA_REMOTE_DOCKER', '').lower().strip() in TRUE_VALUES
# network that the docker lambda container will be joining
LAMBDA_DOCKER_NETWORK = os.environ.get('LAMBDA_DOCKER_NETWORK', '').strip()
# folder for temporary files and data
TMP_FOLDER = os.path.join(tempfile.gettempdir(), 'localstack')
# fix for Mac OS, to be able to mount /var/folders in Docker
if TMP_FOLDER.startswith('/var/folders/') and os.path.exists('/private%s' % TMP_FOLDER):
TMP_FOLDER = '/private%s' % TMP_FOLDER
# temporary folder of the host (required when running in Docker). Fall back to local tmp folder if not set
HOST_TMP_FOLDER = os.environ.get('HOST_TMP_FOLDER', TMP_FOLDER)
# directory for persisting data
DATA_DIR = os.environ.get('DATA_DIR', '').strip()
# whether to use SSL encryption for the services
USE_SSL = os.environ.get('USE_SSL', '').strip() not in ('0', 'false', '')
# default encoding used to convert strings to byte arrays (mainly for Python 3 compatibility)
DEFAULT_ENCODING = 'utf-8'
# path to local Docker UNIX domain socket
DOCKER_SOCK = os.environ.get('DOCKER_SOCK', '').strip() or '/var/run/docker.sock'
# additional flags to pass to "docker run" when starting the stack in Docker
DOCKER_FLAGS = os.environ.get('DOCKER_FLAGS', '').strip()
# command used to run Docker containers (e.g., set to "sudo docker" to run as sudo)
DOCKER_CMD = os.environ.get('DOCKER_CMD', '').strip() or 'docker'
# port of Web UI
PORT_WEB_UI = int(os.environ.get('PORT_WEB_UI', '').strip() or DEFAULT_PORT_WEB_UI)
# IP of the docker bridge used to enable access between containers
DOCKER_BRIDGE_IP = os.environ.get('DOCKER_BRIDGE_IP', '').strip()
# CORS settings
EXTRA_CORS_ALLOWED_HEADERS = os.environ.get('EXTRA_CORS_ALLOWED_HEADERS', '').strip()
EXTRA_CORS_EXPOSE_HEADERS = os.environ.get('EXTRA_CORS_EXPOSE_HEADERS', '').strip()
def has_docker():
try:
with open(os.devnull, 'w') as devnull:
subprocess.check_output('docker ps', stderr=devnull, shell=True)
return True
except Exception:
return False
def is_linux():
try:
out = subprocess.check_output('uname -a', shell=True)
out = out.decode('utf-8') if isinstance(out, six.binary_type) else out
return 'Linux' in out
except subprocess.CalledProcessError:
return False
# whether to use Lambda functions in a Docker container
LAMBDA_EXECUTOR = os.environ.get('LAMBDA_EXECUTOR', '').strip()
if not LAMBDA_EXECUTOR:
LAMBDA_EXECUTOR = 'docker'
if not has_docker():
LAMBDA_EXECUTOR = 'local'
# Fallback URL to use when a non-existing Lambda is invoked. If this matches
# `dynamodb://<table_name>`, then the invocation is recorded in the corresponding
# DynamoDB table. If this matches `http(s)://...`, then the Lambda invocation is
# forwarded as a POST request to that URL.
LAMBDA_FALLBACK_URL = os.environ.get('LAMBDA_FALLBACK_URL', '').strip()
# list of environment variable names used for configuration.
# Make sure to keep this in sync with the above!
# Note: do *not* include DATA_DIR in this list, as it is treated separately
CONFIG_ENV_VARS = ['SERVICES', 'HOSTNAME', 'HOSTNAME_EXTERNAL', 'LOCALSTACK_HOSTNAME', 'LAMBDA_FALLBACK_URL',
'LAMBDA_EXECUTOR', 'LAMBDA_REMOTE_DOCKER', 'LAMBDA_DOCKER_NETWORK', 'USE_SSL', 'LOCALSTACK_API_KEY', 'DEBUG',
'KINESIS_ERROR_PROBABILITY', 'DYNAMODB_ERROR_PROBABILITY', 'PORT_WEB_UI', 'START_WEB', 'DOCKER_BRIDGE_IP']
for key, value in six.iteritems(DEFAULT_SERVICE_PORTS):
clean_key = key.upper().replace('-', '_')
CONFIG_ENV_VARS += [clean_key + '_BACKEND', clean_key + '_PORT', clean_key + '_PORT_EXTERNAL']
# create variable aliases prefixed with LOCALSTACK_ (except LOCALSTACK_HOSTNAME)
CONFIG_ENV_VARS += ['LOCALSTACK_' + v for v in CONFIG_ENV_VARS]
def ping(host):
""" Returns True if host responds to a ping request """
is_windows = platform.system().lower() == 'windows'
ping_opts = '-n 1' if is_windows else '-c 1'
args = 'ping %s %s' % (ping_opts, host)
return subprocess.call(args, shell=not is_windows, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
def in_docker():
""" Returns True if running in a docker container, else False """
if not os.path.exists('/proc/1/cgroup'):
return False
with open('/proc/1/cgroup', 'rt') as ifh:
return 'docker' in ifh.read()
is_in_docker = in_docker()
# determine IP of Docker bridge
if not DOCKER_BRIDGE_IP:
DOCKER_BRIDGE_IP = '172.17.0.1'
if is_in_docker:
candidates = (DOCKER_BRIDGE_IP, '172.18.0.1')
for ip in candidates:
if ping(ip):
DOCKER_BRIDGE_IP = ip
break
# determine route to Docker host from container
try:
DOCKER_HOST_FROM_CONTAINER = DOCKER_BRIDGE_IP
if not is_in_docker:
DOCKER_HOST_FROM_CONTAINER = socket.gethostbyname('host.docker.internal')
# update LOCALSTACK_HOSTNAME if host.docker.internal is available
if is_in_docker and LOCALSTACK_HOSTNAME == DOCKER_BRIDGE_IP:
LOCALSTACK_HOSTNAME = DOCKER_HOST_FROM_CONTAINER
except socket.error:
pass
# make sure we default to LAMBDA_REMOTE_DOCKER=true if running in Docker
if is_in_docker and not os.environ.get('LAMBDA_REMOTE_DOCKER', '').strip():
LAMBDA_REMOTE_DOCKER = True
# print a warning if we're not running in Docker but using Docker based LAMBDA_EXECUTOR
if not is_in_docker and 'docker' in LAMBDA_EXECUTOR and not is_linux():
print(('!WARNING! - Running outside of Docker with LAMBDA_EXECUTOR=%s can lead to '
'problems on your OS. The environment variable $LOCALSTACK_HOSTNAME may not '
'be properly set in your Lambdas.') % LAMBDA_EXECUTOR)
# local config file path in home directory
CONFIG_FILE_PATH = os.path.join(expanduser('~'), '.localstack')
# create folders
for folder in [DATA_DIR, TMP_FOLDER]:
if folder and not os.path.exists(folder):
try:
os.makedirs(folder)
except Exception:
# this can happen due to a race condition when starting
# multiple processes in parallel. Should be safe to ignore
pass
# set variables no_proxy, i.e., run internal service calls directly
no_proxy = ','.join(set((LOCALSTACK_HOSTNAME, HOSTNAME, LOCALHOST, '127.0.0.1', '[::1]')))
if os.environ.get('no_proxy'):
os.environ['no_proxy'] += ',' + no_proxy
elif os.environ.get('NO_PROXY'):
os.environ['NO_PROXY'] += ',' + no_proxy
else:
os.environ['no_proxy'] = no_proxy
# additional CLI commands, can be set by plugins
CLI_COMMANDS = {}
# set of valid regions
VALID_REGIONS = set(Session().get_available_regions('sns'))
def parse_service_ports():
""" Parses the environment variable $SERVICE_PORTS with a comma-separated list of services
and (optional) ports they should run on: 'service1:port1,service2,service3:port3' """
service_ports = os.environ.get('SERVICES', '').strip()
if not service_ports:
return DEFAULT_SERVICE_PORTS
result = {}
for service_port in re.split(r'\s*,\s*', service_ports):
parts = re.split(r'[:=]', service_port)
service = parts[0]
key_upper = service.upper().replace('-', '_')
port_env_name = '%s_PORT' % key_upper
# (1) set default port number
port_number = DEFAULT_SERVICE_PORTS.get(service)
# (2) set port number from <SERVICE>_PORT environment, if present
if os.environ.get(port_env_name):
port_number = os.environ.get(port_env_name)
# (3) set port number from <service>:<port> portion in $SERVICES, if present
if len(parts) > 1:
port_number = int(parts[-1])
# (4) try to parse as int, fall back to 0 (invalid port)
try:
port_number = int(port_number)
except Exception:
port_number = 0
result[service] = port_number
return result
def populate_configs(service_ports=None):
global SERVICE_PORTS
SERVICE_PORTS = service_ports or parse_service_ports()
globs = globals()
# define service ports and URLs as environment variables
for key, value in six.iteritems(DEFAULT_SERVICE_PORTS):
key_upper = key.upper().replace('-', '_')
# define PORT_* variables with actual service ports as per configuration
port_var_name = 'PORT_%s' % key_upper
port_number = SERVICE_PORTS.get(key, 0)
globs[port_var_name] = port_number
url = 'http%s://%s:%s' % ('s' if USE_SSL else '', LOCALSTACK_HOSTNAME, port_number)
# define TEST_*_URL variables with mock service endpoints
url_key = 'TEST_%s_URL' % key_upper
globs[url_key] = url
# expose HOST_*_URL variables as environment variables
os.environ[url_key] = url
# expose LOCALSTACK_HOSTNAME as env. variable
os.environ['LOCALSTACK_HOSTNAME'] = LOCALSTACK_HOSTNAME
def service_port(service_key):
return SERVICE_PORTS.get(service_key, 0)
# initialize config values
populate_configs()
# set log level
if os.environ.get('DEBUG', '').lower() in TRUE_VALUES:
logging.getLogger('').setLevel(logging.DEBUG)
logging.getLogger('localstack').setLevel(logging.DEBUG)
# whether to bundle multiple APIs into a single process, where possible
BUNDLE_API_PROCESSES = True
# whether to use a CPU/memory profiler when running the integration tests
USE_PROFILER = os.environ.get('USE_PROFILER', '').lower() in TRUE_VALUES
# set URL pattern of inbound API gateway
INBOUND_GATEWAY_URL_PATTERN = ('%s/restapis/{api_id}/{stage_name}/%s{path}' %
(TEST_APIGATEWAY_URL, PATH_USER_REQUEST)) # noqa
| 1 | 10,137 | Please rename this to `LAMBDA_JAVA_OPTS`, and add a short description to the README. | localstack-localstack | py |
@@ -25,6 +25,8 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
+ "github.com/google/uuid"
+
"github.com/pipe-cd/pipe/pkg/app/api/analysisresultstore"
"github.com/pipe-cd/pipe/pkg/app/api/applicationlivestatestore"
"github.com/pipe-cd/pipe/pkg/app/api/commandstore" | 1 | // Copyright 2020 The PipeCD Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package grpcapi
import (
"context"
"encoding/json"
"errors"
"time"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/pipe-cd/pipe/pkg/app/api/analysisresultstore"
"github.com/pipe-cd/pipe/pkg/app/api/applicationlivestatestore"
"github.com/pipe-cd/pipe/pkg/app/api/commandstore"
"github.com/pipe-cd/pipe/pkg/app/api/service/pipedservice"
"github.com/pipe-cd/pipe/pkg/app/api/stagelogstore"
"github.com/pipe-cd/pipe/pkg/cache"
"github.com/pipe-cd/pipe/pkg/cache/memorycache"
"github.com/pipe-cd/pipe/pkg/datastore"
"github.com/pipe-cd/pipe/pkg/filestore"
"github.com/pipe-cd/pipe/pkg/model"
"github.com/pipe-cd/pipe/pkg/rpc/rpcauth"
)
// PipedAPI implements the behaviors for the gRPC definitions of PipedAPI.
type PipedAPI struct {
applicationStore datastore.ApplicationStore
deploymentStore datastore.DeploymentStore
environmentStore datastore.EnvironmentStore
pipedStore datastore.PipedStore
projectStore datastore.ProjectStore
eventStore datastore.EventStore
stageLogStore stagelogstore.Store
applicationLiveStateStore applicationlivestatestore.Store
analysisResultStore analysisresultstore.Store
commandStore commandstore.Store
commandOutputPutter commandOutputPutter
appPipedCache cache.Cache
deploymentPipedCache cache.Cache
envProjectCache cache.Cache
pipedStatCache cache.Cache
webBaseURL string
logger *zap.Logger
}
// NewPipedAPI creates a new PipedAPI instance.
func NewPipedAPI(ctx context.Context, ds datastore.DataStore, sls stagelogstore.Store, alss applicationlivestatestore.Store, las analysisresultstore.Store, cs commandstore.Store, hc cache.Cache, cop commandOutputPutter, webBaseURL string, logger *zap.Logger) *PipedAPI {
a := &PipedAPI{
applicationStore: datastore.NewApplicationStore(ds),
deploymentStore: datastore.NewDeploymentStore(ds),
environmentStore: datastore.NewEnvironmentStore(ds),
pipedStore: datastore.NewPipedStore(ds),
projectStore: datastore.NewProjectStore(ds),
eventStore: datastore.NewEventStore(ds),
stageLogStore: sls,
applicationLiveStateStore: alss,
analysisResultStore: las,
commandStore: cs,
commandOutputPutter: cop,
appPipedCache: memorycache.NewTTLCache(ctx, 24*time.Hour, 3*time.Hour),
deploymentPipedCache: memorycache.NewTTLCache(ctx, 24*time.Hour, 3*time.Hour),
envProjectCache: memorycache.NewTTLCache(ctx, 24*time.Hour, 3*time.Hour),
pipedStatCache: hc,
webBaseURL: webBaseURL,
logger: logger.Named("piped-api"),
}
return a
}
// Register registers all handling of this service into the specified gRPC server.
func (a *PipedAPI) Register(server *grpc.Server) {
pipedservice.RegisterPipedServiceServer(server, a)
}
// Ping is periodically sent to report its realtime status/stats to control-plane.
// The received stats will be pushed to the metrics collector.
// Note: This rpc is deprecated, use ReportStat instead.
func (a *PipedAPI) Ping(ctx context.Context, req *pipedservice.PingRequest) (*pipedservice.PingResponse, error) {
return &pipedservice.PingResponse{}, nil
// return nil, status.Error(codes.Unimplemented, "")
}
// ReportStat is periodically sent to report its realtime status/stats to control-plane.
// The received stats will be pushed to the metrics collector.
func (a *PipedAPI) ReportStat(ctx context.Context, req *pipedservice.ReportStatRequest) (*pipedservice.ReportStatResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
now := time.Now().Unix()
val, err := json.Marshal(model.PipedStat{PipedId: pipedID, Metrics: req.PipedStats, Timestamp: now})
if err != nil {
a.logger.Error("failed to store the reported piped stat",
zap.String("piped-id", pipedID),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to encode the reported piped stat")
}
if err := a.pipedStatCache.Put(pipedID, val); err != nil {
a.logger.Error("failed to store the reported piped stat",
zap.String("piped-id", pipedID),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to store the reported piped stat")
}
return &pipedservice.ReportStatResponse{}, nil
}
// ReportPipedMeta is sent by piped while starting up to report its metadata
// such as configured cloud providers.
func (a *PipedAPI) ReportPipedMeta(ctx context.Context, req *pipedservice.ReportPipedMetaRequest) (*pipedservice.ReportPipedMetaResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
now := time.Now().Unix()
connStatus := model.Piped_ONLINE
if err = a.pipedStore.UpdatePiped(ctx, pipedID, datastore.PipedMetadataUpdater(req.CloudProviders, req.Repositories, connStatus, req.SecretEncryption, req.Version, now)); err != nil {
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.InvalidArgument, "piped is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "invalid value for update")
default:
a.logger.Error("failed to update the piped metadata",
zap.String("piped-id", pipedID),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to update the piped metadata")
}
}
piped, err := getPiped(ctx, a.pipedStore, pipedID, a.logger)
if err != nil {
return nil, err
}
return &pipedservice.ReportPipedMetaResponse{
Name: piped.Name,
WebBaseUrl: a.webBaseURL,
}, nil
}
// GetEnvironment finds and returns the environment for the specified ID.
func (a *PipedAPI) GetEnvironment(ctx context.Context, req *pipedservice.GetEnvironmentRequest) (*pipedservice.GetEnvironmentResponse, error) {
projectID, _, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateEnvBelongsToProject(ctx, req.Id, projectID); err != nil {
return nil, err
}
env, err := a.environmentStore.GetEnvironment(ctx, req.Id)
if errors.Is(err, datastore.ErrNotFound) {
return nil, status.Error(codes.NotFound, "environment is not found")
}
if err != nil {
a.logger.Error("failed to get environment", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to get environment")
}
return &pipedservice.GetEnvironmentResponse{
Environment: env,
}, nil
}
// ListApplications returns a list of registered applications
// that should be managed by the requested piped.
// Disabled applications should not be included in the response.
// Piped uses this RPC to fetch and sync the application configuration into its local database.
func (a *PipedAPI) ListApplications(ctx context.Context, req *pipedservice.ListApplicationsRequest) (*pipedservice.ListApplicationsResponse, error) {
projectID, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
opts := datastore.ListOptions{
Filters: []datastore.ListFilter{
{
Field: "ProjectId",
Operator: datastore.OperatorEqual,
Value: projectID,
},
{
Field: "PipedId",
Operator: datastore.OperatorEqual,
Value: pipedID,
},
{
Field: "Disabled",
Operator: datastore.OperatorEqual,
Value: false,
},
},
}
// TODO: Support pagination in ListApplications
apps, _, err := a.applicationStore.ListApplications(ctx, opts)
if err != nil {
a.logger.Error("failed to fetch applications", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to fetch applications")
}
return &pipedservice.ListApplicationsResponse{
Applications: apps,
}, nil
}
// ReportApplicationSyncState is used to update the sync status of an application.
func (a *PipedAPI) ReportApplicationSyncState(ctx context.Context, req *pipedservice.ReportApplicationSyncStateRequest) (*pipedservice.ReportApplicationSyncStateResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateAppBelongsToPiped(ctx, req.ApplicationId, pipedID); err != nil {
return nil, err
}
err = a.applicationStore.PutApplicationSyncState(ctx, req.ApplicationId, req.State)
if err != nil {
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.InvalidArgument, "application is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "invalid value for update")
default:
a.logger.Error("failed to update application sync state",
zap.String("application-id", req.ApplicationId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to update the application sync state")
}
}
return &pipedservice.ReportApplicationSyncStateResponse{}, nil
}
// ReportApplicationDeployingStatus is used to report whether the specified application is deploying or not.
func (a *PipedAPI) ReportApplicationDeployingStatus(ctx context.Context, req *pipedservice.ReportApplicationDeployingStatusRequest) (*pipedservice.ReportApplicationDeployingStatusResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateAppBelongsToPiped(ctx, req.ApplicationId, pipedID); err != nil {
return nil, err
}
err = a.applicationStore.UpdateApplication(ctx, req.ApplicationId, func(app *model.Application) error {
app.Deploying = req.Deploying
return nil
})
if err == nil {
return &pipedservice.ReportApplicationDeployingStatusResponse{}, nil
}
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.InvalidArgument, "application is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "invalid value for update")
default:
a.logger.Error("failed to update deploying status of application",
zap.String("application-id", req.ApplicationId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to update deploying status of application")
}
}
// ReportApplicationMostRecentDeployment is used to update the basic information about
// the most recent deployment of a specific application.
func (a *PipedAPI) ReportApplicationMostRecentDeployment(ctx context.Context, req *pipedservice.ReportApplicationMostRecentDeploymentRequest) (*pipedservice.ReportApplicationMostRecentDeploymentResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateAppBelongsToPiped(ctx, req.ApplicationId, pipedID); err != nil {
return nil, err
}
err = a.applicationStore.PutApplicationMostRecentDeployment(ctx, req.ApplicationId, req.Status, req.Deployment)
if err != nil {
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.InvalidArgument, "application is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "invalid value for update")
default:
a.logger.Error("failed to update application completed deployment",
zap.String("application-id", req.ApplicationId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to update the application completed deployment")
}
}
return &pipedservice.ReportApplicationMostRecentDeploymentResponse{}, nil
}
// GetApplicationMostRecentDeployment returns the most recent deployment of the given application.
func (a *PipedAPI) GetApplicationMostRecentDeployment(ctx context.Context, req *pipedservice.GetApplicationMostRecentDeploymentRequest) (*pipedservice.GetApplicationMostRecentDeploymentResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateAppBelongsToPiped(ctx, req.ApplicationId, pipedID); err != nil {
return nil, err
}
app, err := a.applicationStore.GetApplication(ctx, req.ApplicationId)
if errors.Is(err, datastore.ErrNotFound) {
return nil, status.Error(codes.NotFound, "application is not found")
}
if err != nil {
a.logger.Error("failed to get application", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to get application")
}
if req.Status == model.DeploymentStatus_DEPLOYMENT_SUCCESS && app.MostRecentlySuccessfulDeployment != nil {
return &pipedservice.GetApplicationMostRecentDeploymentResponse{Deployment: app.MostRecentlySuccessfulDeployment}, nil
}
if req.Status == model.DeploymentStatus_DEPLOYMENT_PENDING && app.MostRecentlyTriggeredDeployment != nil {
return &pipedservice.GetApplicationMostRecentDeploymentResponse{Deployment: app.MostRecentlyTriggeredDeployment}, nil
}
return nil, status.Error(codes.NotFound, "deployment is not found")
}
func (a *PipedAPI) GetDeployment(ctx context.Context, req *pipedservice.GetDeploymentRequest) (*pipedservice.GetDeploymentResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
deployment, err := getDeployment(ctx, a.deploymentStore, req.Id, a.logger)
if err != nil {
return nil, err
}
if deployment.PipedId != pipedID {
return nil, status.Error(codes.PermissionDenied, "requested deployment doesn't belong to the piped")
}
return &pipedservice.GetDeploymentResponse{
Deployment: deployment,
}, nil
}
// ListNotCompletedDeployments returns a list of not completed deployments
// which are managed by this piped.
// DeploymentController component uses this RPC to spawns/syncs its local deployment executors.
func (a *PipedAPI) ListNotCompletedDeployments(ctx context.Context, req *pipedservice.ListNotCompletedDeploymentsRequest) (*pipedservice.ListNotCompletedDeploymentsResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
opts := datastore.ListOptions{
Filters: []datastore.ListFilter{
{
Field: "PipedId",
Operator: datastore.OperatorEqual,
Value: pipedID,
},
// TODO: Change to simple conditional clause without using OR clause for portability
// Note: firestore does not support OR operator.
// See more: https://firebase.google.com/docs/firestore/query-data/queries?hl=en
{
Field: "Status",
Operator: datastore.OperatorIn,
Value: model.GetNotCompletedDeploymentStatuses(),
},
},
}
deployments, cursor, err := a.deploymentStore.ListDeployments(ctx, opts)
if err != nil {
a.logger.Error("failed to fetch deployments", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to fetch deployments")
}
return &pipedservice.ListNotCompletedDeploymentsResponse{
Deployments: deployments,
Cursor: cursor,
}, nil
}
// CreateDeployment creates/triggers a new deployment for an application
// that is managed by this piped.
// This will be used by DeploymentTrigger component.
func (a *PipedAPI) CreateDeployment(ctx context.Context, req *pipedservice.CreateDeploymentRequest) (*pipedservice.CreateDeploymentResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateAppBelongsToPiped(ctx, req.Deployment.ApplicationId, pipedID); err != nil {
return nil, err
}
err = a.deploymentStore.AddDeployment(ctx, req.Deployment)
if errors.Is(err, datastore.ErrAlreadyExists) {
return nil, status.Error(codes.AlreadyExists, "deployment already exists")
}
if err != nil {
a.logger.Error("failed to create deployment", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to create deployment")
}
return &pipedservice.CreateDeploymentResponse{}, nil
}
// ReportDeploymentPlanned used by piped to update the status
// of a specific deployment to PLANNED.
func (a *PipedAPI) ReportDeploymentPlanned(ctx context.Context, req *pipedservice.ReportDeploymentPlannedRequest) (*pipedservice.ReportDeploymentPlannedResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateDeploymentBelongsToPiped(ctx, req.DeploymentId, pipedID); err != nil {
return nil, err
}
updater := datastore.DeploymentToPlannedUpdater(req.Summary, req.StatusReason, req.RunningCommitHash, req.Version, req.Stages)
err = a.deploymentStore.UpdateDeployment(ctx, req.DeploymentId, updater)
if err != nil {
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.InvalidArgument, "deployment is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "invalid value for update")
default:
a.logger.Error("failed to update deployment to be planned",
zap.String("deployment-id", req.DeploymentId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to update deployment to be planned")
}
}
return &pipedservice.ReportDeploymentPlannedResponse{}, nil
}
// ReportDeploymentStatusChanged is used to update the status
// of a specific deployment to RUNNING or ROLLING_BACK.
func (a *PipedAPI) ReportDeploymentStatusChanged(ctx context.Context, req *pipedservice.ReportDeploymentStatusChangedRequest) (*pipedservice.ReportDeploymentStatusChangedResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateDeploymentBelongsToPiped(ctx, req.DeploymentId, pipedID); err != nil {
return nil, err
}
updater := datastore.DeploymentStatusUpdater(req.Status, req.StatusReason)
err = a.deploymentStore.UpdateDeployment(ctx, req.DeploymentId, updater)
if err != nil {
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.InvalidArgument, "deployment is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "invalid value for update")
default:
a.logger.Error("failed to update deployment status",
zap.String("deployment-id", req.DeploymentId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to update deployment status")
}
}
return &pipedservice.ReportDeploymentStatusChangedResponse{}, nil
}
// ReportDeploymentCompleted used by piped to update the status
// of a specific deployment to SUCCESS | FAILURE | CANCELLED.
func (a *PipedAPI) ReportDeploymentCompleted(ctx context.Context, req *pipedservice.ReportDeploymentCompletedRequest) (*pipedservice.ReportDeploymentCompletedResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateDeploymentBelongsToPiped(ctx, req.DeploymentId, pipedID); err != nil {
return nil, err
}
updater := datastore.DeploymentToCompletedUpdater(req.Status, req.StageStatuses, req.StatusReason, req.CompletedAt)
err = a.deploymentStore.UpdateDeployment(ctx, req.DeploymentId, updater)
if err != nil {
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.InvalidArgument, "deployment is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "invalid value for update")
default:
a.logger.Error("failed to update deployment to be completed",
zap.String("deployment-id", req.DeploymentId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to update deployment to be completed")
}
}
return &pipedservice.ReportDeploymentCompletedResponse{}, nil
}
// SaveDeploymentMetadata used by piped to persist the metadata of a specific deployment.
func (a *PipedAPI) SaveDeploymentMetadata(ctx context.Context, req *pipedservice.SaveDeploymentMetadataRequest) (*pipedservice.SaveDeploymentMetadataResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateDeploymentBelongsToPiped(ctx, req.DeploymentId, pipedID); err != nil {
return nil, err
}
err = a.deploymentStore.PutDeploymentMetadata(ctx, req.DeploymentId, req.Metadata)
if errors.Is(err, datastore.ErrNotFound) {
return nil, status.Error(codes.InvalidArgument, "deployment is not found")
}
if err != nil {
a.logger.Error("failed to save deployment metadata",
zap.String("deployment-id", req.DeploymentId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to save deployment metadata")
}
return &pipedservice.SaveDeploymentMetadataResponse{}, nil
}
// SaveStageMetadata used by piped to persist the metadata
// of a specific stage of a deployment.
func (a *PipedAPI) SaveStageMetadata(ctx context.Context, req *pipedservice.SaveStageMetadataRequest) (*pipedservice.SaveStageMetadataResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateDeploymentBelongsToPiped(ctx, req.DeploymentId, pipedID); err != nil {
return nil, err
}
err = a.deploymentStore.PutDeploymentStageMetadata(ctx, req.DeploymentId, req.StageId, req.Metadata)
if err != nil {
switch errors.Unwrap(err) {
case datastore.ErrNotFound:
return nil, status.Error(codes.InvalidArgument, "deployment is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "invalid value for update")
default:
a.logger.Error("failed to save deployment stage metadata",
zap.String("deployment-id", req.DeploymentId),
zap.String("stage-id", req.StageId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to save deployment stage metadata")
}
}
return &pipedservice.SaveStageMetadataResponse{}, nil
}
// ReportStageLogs is sent by piped to save the log of a pipeline stage.
func (a *PipedAPI) ReportStageLogs(ctx context.Context, req *pipedservice.ReportStageLogsRequest) (*pipedservice.ReportStageLogsResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateDeploymentBelongsToPiped(ctx, req.DeploymentId, pipedID); err != nil {
return nil, err
}
err = a.stageLogStore.AppendLogs(ctx, req.DeploymentId, req.StageId, req.RetriedCount, req.Blocks)
if errors.Is(err, stagelogstore.ErrAlreadyCompleted) {
return nil, status.Error(codes.FailedPrecondition, "could not append the logs because the stage was already completed")
}
if err != nil {
a.logger.Error("failed to append logs", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to append logs")
}
return &pipedservice.ReportStageLogsResponse{}, nil
}
// ReportStageLogsFromLastCheckpoint is used to save the full logs from the most recently saved point.
func (a *PipedAPI) ReportStageLogsFromLastCheckpoint(ctx context.Context, req *pipedservice.ReportStageLogsFromLastCheckpointRequest) (*pipedservice.ReportStageLogsFromLastCheckpointResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateDeploymentBelongsToPiped(ctx, req.DeploymentId, pipedID); err != nil {
return nil, err
}
err = a.stageLogStore.AppendLogsFromLastCheckpoint(ctx, req.DeploymentId, req.StageId, req.RetriedCount, req.Blocks, req.Completed)
if errors.Is(err, stagelogstore.ErrAlreadyCompleted) {
return nil, status.Error(codes.FailedPrecondition, "could not append the logs because the stage was already completed")
}
if err != nil {
a.logger.Error("failed to append logs", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to append logs")
}
return &pipedservice.ReportStageLogsFromLastCheckpointResponse{}, nil
}
// ReportStageStatusChanged used by piped to update the status
// of a specific stage of a deployment.
func (a *PipedAPI) ReportStageStatusChanged(ctx context.Context, req *pipedservice.ReportStageStatusChangedRequest) (*pipedservice.ReportStageStatusChangedResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateDeploymentBelongsToPiped(ctx, req.DeploymentId, pipedID); err != nil {
return nil, err
}
updater := datastore.StageStatusChangedUpdater(req.StageId, req.Status, req.StatusReason, req.Requires, req.Visible, req.RetriedCount, req.CompletedAt)
err = a.deploymentStore.UpdateDeployment(ctx, req.DeploymentId, updater)
if err != nil {
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.InvalidArgument, "deployment is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "invalid value for update")
default:
a.logger.Error("failed to update stage status",
zap.String("deployment-id", req.DeploymentId),
zap.String("stage-id", req.StageId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to update stage status")
}
}
return &pipedservice.ReportStageStatusChangedResponse{}, nil
}
// ListUnhandledCommands is periodically called by piped to obtain the commands
// that should be handled.
// Whenever an user makes an interaction from WebUI (cancel/approve/retry/sync)
// a new command with a unique identifier will be generated an saved into the datastore.
// Piped uses this RPC to list all still-not-handled commands to handle them,
// then report back the result to server.
// On other side, the web will periodically check the command status and feedback the result to user.
// In the future, we may need a solution to remove all old-handled commands from datastore for space.
func (a *PipedAPI) ListUnhandledCommands(ctx context.Context, req *pipedservice.ListUnhandledCommandsRequest) (*pipedservice.ListUnhandledCommandsResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
cmds, err := a.commandStore.ListUnhandledCommands(ctx, pipedID)
if err != nil {
a.logger.Error("failed to fetch unhandled commands", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to unhandled commands")
}
return &pipedservice.ListUnhandledCommandsResponse{
Commands: cmds,
}, nil
}
// ReportCommandHandled is called by piped to mark a specific command as handled.
// The request payload will contain the handle status as well as any additional result data.
// The handle result should be updated to both datastore and cache (for reading from web).
func (a *PipedAPI) ReportCommandHandled(ctx context.Context, req *pipedservice.ReportCommandHandledRequest) (*pipedservice.ReportCommandHandledResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
cmd, err := a.getCommand(ctx, req.CommandId)
if err != nil {
return nil, err
}
if pipedID != cmd.PipedId {
return nil, status.Error(codes.PermissionDenied, "The current piped does not have requested command")
}
if len(req.Output) > 0 {
if err := a.commandOutputPutter.Put(ctx, req.CommandId, req.Output); err != nil {
a.logger.Error("failed to store output of command",
zap.String("command_id", req.CommandId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "Failed to store output of command")
}
}
err = a.commandStore.UpdateCommandHandled(ctx, req.CommandId, req.Status, req.Metadata, req.HandledAt)
if err != nil {
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.NotFound, "command is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "invalid value for update")
default:
a.logger.Error("failed to update command",
zap.String("command-id", req.CommandId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "failed to update command")
}
}
return &pipedservice.ReportCommandHandledResponse{}, nil
}
func (a *PipedAPI) getCommand(ctx context.Context, pipedID string) (*model.Command, error) {
cmd, err := a.commandStore.GetCommand(ctx, pipedID)
if errors.Is(err, datastore.ErrNotFound) {
return nil, status.Error(codes.NotFound, "command is not found")
}
if err != nil {
return nil, status.Error(codes.Internal, "failed to get command")
}
return cmd, nil
}
// ReportApplicationLiveState is periodically sent to correct full state of an application.
// For kubernetes application, this contains a full tree of its kubernetes resources.
// The tree data should be written into filestore immediately and then the state in cache should be refreshsed too.
func (a *PipedAPI) ReportApplicationLiveState(ctx context.Context, req *pipedservice.ReportApplicationLiveStateRequest) (*pipedservice.ReportApplicationLiveStateResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateAppBelongsToPiped(ctx, req.Snapshot.ApplicationId, pipedID); err != nil {
return nil, err
}
if err := a.applicationLiveStateStore.PutStateSnapshot(ctx, req.Snapshot); err != nil {
return nil, status.Error(codes.Internal, "failed to report application live state")
}
return &pipedservice.ReportApplicationLiveStateResponse{}, nil
}
// ReportApplicationLiveStateEvents is sent by piped to submit one or multiple events
// about the changes of application state.
// Control plane uses the received events to update the state of application-resource-tree.
// We want to start by a simple solution at this initial stage of development,
// so the API server just handles as below:
// - loads the releated application-resource-tree from filestore
// - checks and builds new state for the application-resource-tree
// - updates new state into fielstore and cache (cache data is for reading while handling web requests)
// In the future, we may want to redesign the behavior of this RPC by using pubsub/queue pattern.
// After receiving the events, all of them will be publish into a queue immediately,
// and then another Handler service will pick them inorder to apply to build new state.
// By that way we can control the traffic to the datastore in a better way.
func (a *PipedAPI) ReportApplicationLiveStateEvents(ctx context.Context, req *pipedservice.ReportApplicationLiveStateEventsRequest) (*pipedservice.ReportApplicationLiveStateEventsResponse, error) {
a.applicationLiveStateStore.PatchKubernetesApplicationLiveState(ctx, req.KubernetesEvents)
// TODO: Patch Terraform application live state
// TODO: Patch Cloud Run application live state
// TODO: Patch Lambda application live state
return &pipedservice.ReportApplicationLiveStateEventsResponse{}, nil
}
// GetLatestEvent returns the latest event that meets the given conditions.
func (a *PipedAPI) GetLatestEvent(ctx context.Context, req *pipedservice.GetLatestEventRequest) (*pipedservice.GetLatestEventResponse, error) {
projectID, _, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
// Try to fetch the most recently registered event that has the given parameters.
opts := datastore.ListOptions{
Limit: 1,
Filters: []datastore.ListFilter{
{
Field: "ProjectId",
Operator: datastore.OperatorEqual,
Value: projectID,
},
{
Field: "Name",
Operator: datastore.OperatorEqual,
Value: req.Name,
},
{
Field: "EventKey",
Operator: datastore.OperatorEqual,
Value: model.MakeEventKey(req.Name, req.Labels),
},
},
Orders: []datastore.Order{
{
Field: "CreatedAt",
Direction: datastore.Desc,
},
{
Field: "Id",
Direction: datastore.Asc,
},
},
}
events, err := a.eventStore.ListEvents(ctx, opts)
if err != nil {
a.logger.Error("failed to list events", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to list event")
}
if len(events) == 0 {
return nil, status.Error(codes.NotFound, "no events found")
}
return &pipedservice.GetLatestEventResponse{
Event: events[0],
}, nil
}
// ListEvents returns a list of Events inside the given range.
func (a *PipedAPI) ListEvents(ctx context.Context, req *pipedservice.ListEventsRequest) (*pipedservice.ListEventsResponse, error) {
projectID, _, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
// Build options based on the request.
opts := datastore.ListOptions{
Filters: []datastore.ListFilter{
{
Field: "ProjectId",
Operator: datastore.OperatorEqual,
Value: projectID,
},
},
}
if req.From > 0 {
opts.Filters = append(opts.Filters, datastore.ListFilter{
Field: "CreatedAt",
Operator: datastore.OperatorGreaterThanOrEqual,
Value: req.From,
})
}
if req.To > 0 {
opts.Filters = append(opts.Filters, datastore.ListFilter{
Field: "CreatedAt",
Operator: datastore.OperatorLessThan,
Value: req.To,
})
}
switch req.Order {
case pipedservice.ListOrder_ASC:
opts.Orders = []datastore.Order{
{
Field: "CreatedAt",
Direction: datastore.Asc,
},
{
Field: "Id",
Direction: datastore.Asc,
},
}
case pipedservice.ListOrder_DESC:
opts.Orders = []datastore.Order{
{
Field: "CreatedAt",
Direction: datastore.Desc,
},
{
Field: "Id",
Direction: datastore.Asc,
},
}
}
events, err := a.eventStore.ListEvents(ctx, opts)
if err != nil {
a.logger.Error("failed to list events", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to list events")
}
return &pipedservice.ListEventsResponse{
Events: events,
}, nil
}
func (a *PipedAPI) ReportEventsHandled(ctx context.Context, req *pipedservice.ReportEventsHandledRequest) (*pipedservice.ReportEventsHandledResponse, error) {
_, _, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
for _, id := range req.EventIds {
if err := a.eventStore.MarkEventHandled(ctx, id); err != nil {
switch err {
case datastore.ErrNotFound:
return nil, status.Errorf(codes.NotFound, "event %q is not found", id)
default:
a.logger.Error("failed to mark event as handled",
zap.String("event-id", id),
zap.Error(err),
)
return nil, status.Errorf(codes.Internal, "failed to mark event %q as handled", id)
}
}
}
return &pipedservice.ReportEventsHandledResponse{}, nil
}
func (a *PipedAPI) GetLatestAnalysisResult(ctx context.Context, req *pipedservice.GetLatestAnalysisResultRequest) (*pipedservice.GetLatestAnalysisResultResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateAppBelongsToPiped(ctx, req.ApplicationId, pipedID); err != nil {
return nil, err
}
result, err := a.analysisResultStore.GetLatestAnalysisResult(ctx, req.ApplicationId)
if errors.Is(err, filestore.ErrNotFound) {
return nil, status.Error(codes.NotFound, "the most recent analysis result is not found")
}
if err != nil {
a.logger.Error("failed to get the most recent analysis result", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to get the most recent analysis result")
}
return &pipedservice.GetLatestAnalysisResultResponse{
AnalysisResult: result,
}, nil
}
func (a *PipedAPI) PutLatestAnalysisResult(ctx context.Context, req *pipedservice.PutLatestAnalysisResultRequest) (*pipedservice.PutLatestAnalysisResultResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
if err := a.validateAppBelongsToPiped(ctx, req.ApplicationId, pipedID); err != nil {
return nil, err
}
err = a.analysisResultStore.PutLatestAnalysisResult(ctx, req.ApplicationId, req.AnalysisResult)
if err != nil {
a.logger.Error("failed to put the most recent analysis result", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to put the most recent analysis result")
}
return &pipedservice.PutLatestAnalysisResultResponse{}, nil
}
func (a *PipedAPI) GetDesiredVersion(ctx context.Context, _ *pipedservice.GetDesiredVersionRequest) (*pipedservice.GetDesiredVersionResponse, error) {
_, pipedID, _, err := rpcauth.ExtractPipedToken(ctx)
if err != nil {
return nil, err
}
piped, err := getPiped(ctx, a.pipedStore, pipedID, a.logger)
if err != nil {
return nil, err
}
return &pipedservice.GetDesiredVersionResponse{
Version: piped.DesiredVersion,
}, nil
}
func (a *PipedAPI) UpdateApplicationConfigurations(ctx context.Context, req *pipedservice.UpdateApplicationConfigurationsRequest) (*pipedservice.UpdateApplicationConfigurationsResponse, error) {
// TODO: Update the given application configurations
return nil, status.Errorf(codes.Unimplemented, "UpdateApplicationConfigurations is not implemented yet")
}
func (a *PipedAPI) ReportUnregisteredApplicationConfigurations(ctx context.Context, req *pipedservice.ReportUnregisteredApplicationConfigurationsRequest) (*pipedservice.ReportUnregisteredApplicationConfigurationsResponse, error) {
// TODO: Make the unused application configurations cache up-to-date
return nil, status.Errorf(codes.Unimplemented, "ReportUnregisteredApplicationConfigurations is not implemented yet")
}
// validateAppBelongsToPiped checks if the given application belongs to the given piped.
// It gives back an error unless the application belongs to the piped.
func (a *PipedAPI) validateAppBelongsToPiped(ctx context.Context, appID, pipedID string) error {
pid, err := a.appPipedCache.Get(appID)
if err == nil {
if pid != pipedID {
return status.Error(codes.PermissionDenied, "requested application doesn't belong to the piped")
}
return nil
}
app, err := a.applicationStore.GetApplication(ctx, appID)
if errors.Is(err, datastore.ErrNotFound) {
return status.Error(codes.NotFound, "the application is not found")
}
if err != nil {
a.logger.Error("failed to get application", zap.Error(err))
return status.Error(codes.Internal, "failed to get application")
}
a.appPipedCache.Put(appID, app.PipedId)
if app.PipedId != pipedID {
return status.Error(codes.PermissionDenied, "requested application doesn't belong to the piped")
}
return nil
}
// validateDeploymentBelongsToPiped checks if the given deployment belongs to the given piped.
// It gives back an error unless the deployment belongs to the piped.
func (a *PipedAPI) validateDeploymentBelongsToPiped(ctx context.Context, deploymentID, pipedID string) error {
pid, err := a.deploymentPipedCache.Get(deploymentID)
if err == nil {
if pid != pipedID {
return status.Error(codes.PermissionDenied, "requested deployment doesn't belong to the piped")
}
return nil
}
deployment, err := a.deploymentStore.GetDeployment(ctx, deploymentID)
if errors.Is(err, datastore.ErrNotFound) {
return status.Error(codes.NotFound, "the deployment is not found")
}
if err != nil {
a.logger.Error("failed to get deployment", zap.Error(err))
return status.Error(codes.Internal, "failed to get deployment")
}
a.deploymentPipedCache.Put(deploymentID, deployment.PipedId)
if deployment.PipedId != pipedID {
return status.Error(codes.PermissionDenied, "requested deployment doesn't belong to the piped")
}
return nil
}
// validateEnvBelongsToProject checks if the given environment belongs to the given project.
// It gives back an error unless the environment belongs to the project.
func (a *PipedAPI) validateEnvBelongsToProject(ctx context.Context, envID, projectID string) error {
pid, err := a.envProjectCache.Get(envID)
if err == nil {
if pid != projectID {
return status.Error(codes.PermissionDenied, "requested environment doesn't belong to the project")
}
return nil
}
env, err := a.environmentStore.GetEnvironment(ctx, envID)
if errors.Is(err, datastore.ErrNotFound) {
return status.Error(codes.NotFound, "the environment is not found")
}
if err != nil {
a.logger.Error("failed to get environment", zap.Error(err))
return status.Error(codes.Internal, "failed to get environment")
}
a.envProjectCache.Put(envID, env.ProjectId)
if env.ProjectId != projectID {
return status.Error(codes.PermissionDenied, "requested environment doesn't belong to the project")
}
return nil
}
| 1 | 22,586 | Should be in the same import group. | pipe-cd-pipe | go |
@@ -119,7 +119,8 @@ class _TLSMsgListField(PacketListField):
remain, ret = s[:l], s[l:]
if remain == b"":
- if pkt.tls_session.tls_version > 0x0200 and pkt.type == 23:
+ if ((pkt.tls_session.tls_version or 0x0303 > 0x0200) and
+ hasattr(pkt, "type") and pkt.type == 23):
return ret, [TLSApplicationData(data=b"")]
else:
return ret, [Raw(load=b"")] | 1 | ## This file is part of Scapy
## Copyright (C) 2007, 2008, 2009 Arnaud Ebalard
## 2015, 2016, 2017 Maxence Tury
## This program is published under a GPLv2 license
"""
Common TLS fields & bindings.
This module covers the record layer, along with the ChangeCipherSpec, Alert and
ApplicationData submessages. For the Handshake type, see tls_handshake.py.
See the TLS class documentation for more information.
"""
import struct, traceback
from scapy.config import conf
from scapy.error import log_runtime
from scapy.fields import *
from scapy.compat import *
from scapy.packet import *
from scapy.layers.inet import TCP
from scapy.layers.tls.session import _GenericTLSSessionInheritance
from scapy.layers.tls.handshake import (_tls_handshake_cls, _TLSHandshake,
TLS13ServerHello)
from scapy.layers.tls.basefields import (_TLSVersionField, _tls_version,
_TLSIVField, _TLSMACField,
_TLSPadField, _TLSPadLenField,
_TLSLengthField, _tls_type)
from scapy.layers.tls.crypto.pkcs1 import randstring, pkcs_i2osp
from scapy.layers.tls.crypto.compression import Comp_NULL
from scapy.layers.tls.crypto.cipher_aead import AEADTagError
if conf.crypto_valid_advanced:
from scapy.layers.tls.crypto.cipher_aead import Cipher_CHACHA20_POLY1305
from scapy.layers.tls.crypto.cipher_stream import Cipher_NULL
from scapy.layers.tls.crypto.ciphers import CipherError
from scapy.layers.tls.crypto.h_mac import HMACError
###############################################################################
### TLS Record Protocol ###
###############################################################################
class _TLSEncryptedContent(Raw):
"""
When the content of a TLS record (more precisely, a TLSCiphertext) could
not be deciphered, we use this class to represent the encrypted data.
The MAC will still be parsed from the whole message, even though it could
not been verified. When present (depending on cipher type and protocol
version), the nonce_explicit, IV and/or padding will also be parsed.
"""
name = "Encrypted Content"
class _TLSMsgListField(PacketListField):
"""
This is the actual content of the TLS record. As a TLS record may pack
multiple sublayer messages (notably, several handshake messages),
we inherit from PacketListField.
"""
def __init__(self, name, default, length_from=None):
if not length_from:
length_from = self._get_length
super(_TLSMsgListField, self).__init__(name, default, cls=None,
length_from=length_from)
def _get_length(self, pkt):
if pkt.deciphered_len is None:
return pkt.len
return pkt.deciphered_len
def m2i(self, pkt, m):
"""
Try to parse one of the TLS subprotocols (ccs, alert, handshake or
application_data). This is used inside a loop managed by .getfield().
"""
cls = Raw
if pkt.type == 22:
if len(m) >= 1:
msgtype = orb(m[0])
cls = _tls_handshake_cls.get(msgtype, Raw)
elif pkt.type == 20:
cls = TLSChangeCipherSpec
elif pkt.type == 21:
cls = TLSAlert
elif pkt.type == 23:
cls = TLSApplicationData
if cls is Raw:
return Raw(m)
else:
try:
return cls(m, tls_session=pkt.tls_session)
except:
if conf.debug_dissector:
traceback.print_exc()
return Raw(m)
def getfield(self, pkt, s):
"""
If the decryption of the content did not fail with a CipherError,
we begin a loop on the clear content in order to get as much messages
as possible, of the type advertised in the record header. This is
notably important for several TLS handshake implementations, which
may for instance pack a server_hello, a certificate, a
server_key_exchange and a server_hello_done, all in one record.
Each parsed message may update the TLS context throught their method
.post_dissection_tls_session_update().
If the decryption failed with a CipherError, presumably because we
missed the session keys, we signal it by returning a
_TLSEncryptedContent packet which simply contains the ciphered data.
"""
l = self.length_from(pkt)
lst = []
ret = b""
remain = s
if l is not None:
remain, ret = s[:l], s[l:]
if remain == b"":
if pkt.tls_session.tls_version > 0x0200 and pkt.type == 23:
return ret, [TLSApplicationData(data=b"")]
else:
return ret, [Raw(load=b"")]
if False in six.itervalues(pkt.tls_session.rcs.cipher.ready):
return ret, _TLSEncryptedContent(remain)
else:
while remain:
raw_msg = remain
p = self.m2i(pkt, remain)
if Padding in p:
pad = p[Padding]
remain = pad.load
del(pad.underlayer.payload)
if len(remain) != 0:
raw_msg = raw_msg[:-len(remain)]
else:
remain = b""
if isinstance(p, _GenericTLSSessionInheritance):
if not p.tls_session.frozen:
p.post_dissection_tls_session_update(raw_msg)
lst.append(p)
return remain + ret, lst
def i2m(self, pkt, p):
"""
Update the context with information from the built packet.
If no type was given at the record layer, we try to infer it.
"""
cur = b""
if isinstance(p, _GenericTLSSessionInheritance):
if pkt.type is None:
if isinstance(p, TLSChangeCipherSpec):
pkt.type = 20
elif isinstance(p, TLSAlert):
pkt.type = 21
elif isinstance(p, _TLSHandshake):
pkt.type = 22
elif isinstance(p, TLSApplicationData):
pkt.type = 23
p.tls_session = pkt.tls_session
if not pkt.tls_session.frozen:
cur = p.str_stateful()
p.post_build_tls_session_update(cur)
else:
cur = raw(p)
else:
pkt.type = 23
cur = raw(p)
return cur
def addfield(self, pkt, s, val):
"""
Reconstruct the header because the TLS type may have been updated.
Then, append the content.
"""
res = b""
for p in val:
res += self.i2m(pkt, p)
if (isinstance(pkt, _GenericTLSSessionInheritance) and
pkt.tls_session.tls_version >= 0x0304 and
not isinstance(pkt, TLS13ServerHello)):
return s + res
if not pkt.type:
pkt.type = 0
hdr = struct.pack("!B", pkt.type) + s[1:5]
return hdr + res
class TLS(_GenericTLSSessionInheritance):
"""
The generic TLS Record message, based on section 6.2 of RFC 5246.
When reading a TLS message, we try to parse as much as we can.
In .pre_dissect(), according to the type of the current cipher algorithm
(self.tls_session.rcs.cipher.type), we extract the 'iv', 'mac', 'pad' and
'padlen'. Some of these fields may remain blank: for instance, when using
a stream cipher, there is no IV nor any padding. The 'len' should always
hold the length of the ciphered message; for the plaintext version, you
should rely on the additional 'deciphered_len' attribute.
XXX Fix 'deciphered_len' which should not be defined when failing with
AEAD decryption. This is related to the 'decryption_success' below.
Also, follow this behaviour in record_sslv2.py and record_tls13.py
Once we have isolated the ciphered message aggregate (which should be one
or several TLS messages of the same type), we try to decipher it. Either we
succeed and store the clear data in 'msg', or we graciously fail with a
CipherError and store the ciphered data in 'msg'.
Unless the user manually provides the session secrets through the passing
of a 'tls_session', obviously the ciphered messages will not be deciphered.
Indeed, the need for a proper context may also present itself when trying
to parse clear handshake messages.
For instance, suppose you sniffed the beginning of a DHE-RSA negotiation:
t1 = TLS(<client_hello>)
t2 = TLS(<server_hello | certificate | server_key_exchange>)
t3 = TLS(<server_hello | certificate | server_key_exchange>,
tls_session=t1.tls_session)
(Note that to do things properly, here 't1.tls_session' should actually be
't1.tls_session.mirror()'. See session.py for explanations.)
As no context was passed to t2, neither was any client_random. Hence Scapy
will not be able to verify the signature of the server_key_exchange inside
t2. However, it should be able to do so for t3, thanks to the tls_session.
The consequence of not having a complete TLS context is even more obvious
when trying to parse ciphered content, as we decribed before.
Thus, in order to parse TLS-protected communications with Scapy:
_either Scapy reads every message from one side of the TLS connection and
builds every message from the other side (as such, it should know the
secrets needed for the generation of the pre_master_secret), while passing
the same tls_session context (this is how our automaton.py mostly works);
_or, if Scapy did not build any TLS message, it has to create a TLS context
and feed it with secrets retrieved by whatever technique. Note that the
knowing the private key of the server certificate will not be sufficient
if a PFS ciphersuite was used. However, if you got a master_secret somehow,
use it with tls_session.(w|r)cs.derive_keys() and leave the rest to Scapy.
When building a TLS message with str_stateful, we expect the tls_session to
have the right parameters for ciphering. Else, .post_build() might fail.
"""
__slots__ = ["deciphered_len"]
name = "TLS"
fields_desc = [ ByteEnumField("type", None, _tls_type),
_TLSVersionField("version", None, _tls_version),
_TLSLengthField("len", None),
_TLSIVField("iv", None),
_TLSMsgListField("msg", []),
_TLSMACField("mac", None),
_TLSPadField("pad", None),
_TLSPadLenField("padlen", None) ]
def __init__(self, *args, **kargs):
self.deciphered_len = kargs.get("deciphered_len", None)
super(TLS, self).__init__(*args, **kargs)
@classmethod
def dispatch_hook(cls, _pkt=None, *args, **kargs):
"""
If the TLS class was called on raw SSLv2 data, we want to return an
SSLv2 record instance. We acknowledge the risk of SSLv2 packets with a
msglen of 0x1403, 0x1503, 0x1603 or 0x1703 which will never be casted
as SSLv2 records but TLS ones instead, but hey, we can't be held
responsible for low-minded extensibility choices.
"""
if _pkt and len(_pkt) >= 2:
byte0 = orb(_pkt[0])
byte1 = orb(_pkt[1])
if (byte0 not in _tls_type) or (byte1 != 3):
from scapy.layers.tls.record_sslv2 import SSLv2
return SSLv2
else:
s = kargs.get("tls_session", None)
if s and s.tls_version >= 0x0304:
if s.rcs and not isinstance(s.rcs.cipher, Cipher_NULL):
from scapy.layers.tls.record_tls13 import TLS13
return TLS13
return TLS
### Parsing methods
def _tls_auth_decrypt(self, hdr, s):
"""
Provided with the record header and AEAD-ciphered data, return the
sliced and clear tuple (nonce, TLSCompressed.fragment, mac). Note that
we still return the slicing of the original input in case of decryption
failure. Also, if the integrity check fails, a warning will be issued,
but we still return the sliced (unauthenticated) plaintext.
"""
try:
read_seq_num = struct.pack("!Q", self.tls_session.rcs.seq_num)
self.tls_session.rcs.seq_num += 1
# self.type and self.version have not been parsed yet,
# this is why we need to look into the provided hdr.
add_data = read_seq_num + chb(hdr[0]) + hdr[1:3]
# Last two bytes of add_data are appended by the return function
return self.tls_session.rcs.cipher.auth_decrypt(add_data, s,
read_seq_num)
except CipherError as e:
return e.args
except AEADTagError as e:
pkt_info = self.firstlayer().summary()
log_runtime.info("TLS: record integrity check failed [%s]", pkt_info)
return e.args
def _tls_decrypt(self, s):
"""
Provided with stream- or block-ciphered data, return the clear version.
The cipher should have been updated with the right IV early on,
which should not be at the beginning of the input.
In case of decryption failure, a CipherError will be raised with
the slicing of the original input as first argument.
"""
return self.tls_session.rcs.cipher.decrypt(s)
def _tls_hmac_verify(self, hdr, msg, mac):
"""
Provided with the record header, the TLSCompressed.fragment and the
HMAC, return True if the HMAC is correct. If we could not compute the
HMAC because the key was missing, there is no sense in verifying
anything, thus we also return True.
Meant to be used with a block cipher or a stream cipher.
It would fail with an AEAD cipher, because rcs.hmac would be None.
See RFC 5246, section 6.2.3.
"""
read_seq_num = struct.pack("!Q", self.tls_session.rcs.seq_num)
self.tls_session.rcs.seq_num += 1
mac_len = self.tls_session.rcs.mac_len
if mac_len == 0: # should be TLS_NULL_WITH_NULL_NULL
return True
if len(mac) != mac_len:
return False
alg = self.tls_session.rcs.hmac
version = struct.unpack("!H", hdr[1:3])[0]
try:
if version > 0x300:
h = alg.digest(read_seq_num + hdr + msg)
elif version == 0x300:
h = alg.digest_sslv3(read_seq_num + hdr[0] + hdr[3:5] + msg)
else:
raise Exception("Unrecognized version.")
except HMACError:
h = mac
return h == mac
def _tls_decompress(self, s):
"""
Provided with the TLSCompressed.fragment,
return the TLSPlaintext.fragment.
"""
alg = self.tls_session.rcs.compression
return alg.decompress(s)
def pre_dissect(self, s):
"""
Decrypt, verify and decompress the message,
i.e. apply the previous methods according to the reading cipher type.
If the decryption was successful, 'len' will be the length of the
TLSPlaintext.fragment. Else, it should be the length of the
_TLSEncryptedContent.
"""
if len(s) < 5:
raise Exception("Invalid record: header is too short.")
msglen = struct.unpack('!H', s[3:5])[0]
hdr, efrag, r = s[:5], s[5:5+msglen], s[msglen+5:]
iv = mac = pad = b""
self.padlen = None
decryption_success = False
cipher_type = self.tls_session.rcs.cipher.type
if cipher_type == 'block':
version = struct.unpack("!H", s[1:3])[0]
# Decrypt
try:
if version >= 0x0302:
# Explicit IV for TLS 1.1 and 1.2
block_size = self.tls_session.rcs.cipher.block_size
iv, efrag = efrag[:block_size], efrag[block_size:]
self.tls_session.rcs.cipher.iv = iv
pfrag = self._tls_decrypt(efrag)
else:
# Implicit IV for SSLv3 and TLS 1.0
pfrag = self._tls_decrypt(efrag)
except CipherError as e:
# This will end up dissected as _TLSEncryptedContent.
cfrag = e.args[0]
else:
decryption_success = True
# Excerpt below better corresponds to TLS 1.1 IV definition,
# but the result is the same as with TLS 1.2 anyway.
# This leading *IV* has been decrypted by _tls_decrypt with a
# random IV, hence it does not correspond to anything.
# What actually matters is that we got the first encrypted block
# in order to decrypt the second block (first data block).
#if version >= 0x0302:
# block_size = self.tls_session.rcs.cipher.block_size
# iv, pfrag = pfrag[:block_size], pfrag[block_size:]
# l = struct.unpack('!H', hdr[3:5])[0]
# hdr = hdr[:3] + struct.pack('!H', l-block_size)
# Extract padding ('pad' actually includes the trailing padlen)
padlen = orb(pfrag[-1]) + 1
mfrag, pad = pfrag[:-padlen], pfrag[-padlen:]
self.padlen = padlen
# Extract MAC
l = self.tls_session.rcs.mac_len
if l != 0:
cfrag, mac = mfrag[:-l], mfrag[-l:]
else:
cfrag, mac = mfrag, b""
# Verify integrity
chdr = hdr[:3] + struct.pack('!H', len(cfrag))
is_mac_ok = self._tls_hmac_verify(chdr, cfrag, mac)
if not is_mac_ok:
pkt_info = self.firstlayer().summary()
log_runtime.info("TLS: record integrity check failed [%s]", pkt_info)
elif cipher_type == 'stream':
# Decrypt
try:
pfrag = self._tls_decrypt(efrag)
except CipherError as e:
# This will end up dissected as _TLSEncryptedContent.
cfrag = e.args[0]
else:
decryption_success = True
mfrag = pfrag
# Extract MAC
l = self.tls_session.rcs.mac_len
if l != 0:
cfrag, mac = mfrag[:-l], mfrag[-l:]
else:
cfrag, mac = mfrag, b""
# Verify integrity
chdr = hdr[:3] + struct.pack('!H', len(cfrag))
is_mac_ok = self._tls_hmac_verify(chdr, cfrag, mac)
if not is_mac_ok:
pkt_info = self.firstlayer().summary()
log_runtime.info("TLS: record integrity check failed [%s]", pkt_info)
elif cipher_type == 'aead':
# Authenticated encryption
# crypto/cipher_aead.py prints a warning for integrity failure
if (conf.crypto_valid_advanced and
isinstance(self.tls_session.rcs.cipher, Cipher_CHACHA20_POLY1305)):
iv = b""
cfrag, mac = self._tls_auth_decrypt(hdr, efrag)
else:
iv, cfrag, mac = self._tls_auth_decrypt(hdr, efrag)
decryption_success = True # see XXX above
frag = self._tls_decompress(cfrag)
if (decryption_success and
not isinstance(self.tls_session.rcs.cipher, Cipher_NULL)):
self.deciphered_len = len(frag)
else:
self.deciphered_len = None
reconstructed_body = iv + frag + mac + pad
return hdr + reconstructed_body + r
def post_dissect(self, s):
"""
Commit the pending r/w state if it has been triggered (e.g. by an
underlying TLSChangeCipherSpec or a SSLv2ClientMasterKey). We update
nothing if the prcs was not set, as this probably means that we're
working out-of-context (and we need to keep the default rcs).
"""
if self.tls_session.triggered_prcs_commit:
if self.tls_session.prcs is not None:
self.tls_session.rcs = self.tls_session.prcs
self.tls_session.prcs = None
self.tls_session.triggered_prcs_commit = False
if self.tls_session.triggered_pwcs_commit:
if self.tls_session.pwcs is not None:
self.tls_session.wcs = self.tls_session.pwcs
self.tls_session.pwcs = None
self.tls_session.triggered_pwcs_commit = False
return s
def do_dissect_payload(self, s):
"""
Try to dissect the following data as a TLS message.
Note that overloading .guess_payload_class() would not be enough,
as the TLS session to be used would get lost.
"""
if s:
try:
p = TLS(s, _internal=1, _underlayer=self,
tls_session = self.tls_session)
except KeyboardInterrupt:
raise
except:
p = conf.raw_layer(s, _internal=1, _underlayer=self)
self.add_payload(p)
### Building methods
def _tls_compress(self, s):
"""
Provided with the TLSPlaintext.fragment,
return the TLSCompressed.fragment.
"""
alg = self.tls_session.wcs.compression
return alg.compress(s)
def _tls_auth_encrypt(self, s):
"""
Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole
GenericAEADCipher. Also, the additional data is computed right here.
"""
write_seq_num = struct.pack("!Q", self.tls_session.wcs.seq_num)
self.tls_session.wcs.seq_num += 1
add_data = (write_seq_num +
pkcs_i2osp(self.type, 1) +
pkcs_i2osp(self.version, 2) +
pkcs_i2osp(len(s), 2))
return self.tls_session.wcs.cipher.auth_encrypt(s, add_data,
write_seq_num)
def _tls_hmac_add(self, hdr, msg):
"""
Provided with the record header (concatenation of the TLSCompressed
type, version and length fields) and the TLSCompressed.fragment,
return the concatenation of the TLSCompressed.fragment and the HMAC.
Meant to be used with a block cipher or a stream cipher.
It would fail with an AEAD cipher, because wcs.hmac would be None.
See RFC 5246, section 6.2.3.
"""
write_seq_num = struct.pack("!Q", self.tls_session.wcs.seq_num)
self.tls_session.wcs.seq_num += 1
alg = self.tls_session.wcs.hmac
version = struct.unpack("!H", hdr[1:3])[0]
if version > 0x300:
h = alg.digest(write_seq_num + hdr + msg)
elif version == 0x300:
h = alg.digest_sslv3(write_seq_num + hdr[0] + hdr[3:5] + msg)
else:
raise Exception("Unrecognized version.")
return msg + h
def _tls_pad(self, s):
"""
Provided with the concatenation of the TLSCompressed.fragment and the
HMAC, append the right padding and return it as a whole.
This is the TLS-style padding: while SSL allowed for random padding,
TLS (misguidedly) specifies the repetition of the same byte all over,
and this byte must be equal to len(<entire padding>) - 1.
Meant to be used with a block cipher only.
"""
padding = b""
block_size = self.tls_session.wcs.cipher.block_size
padlen = block_size - ((len(s) + 1) % block_size)
if padlen == block_size:
padlen = 0
pad_pattern = chb(padlen)
padding = pad_pattern * (padlen + 1)
return s + padding
def _tls_encrypt(self, s):
"""
Return the stream- or block-ciphered version of the concatenated input.
In case of GenericBlockCipher, no IV has been specifically prepended to
the output, so this might not be the whole TLSCiphertext.fragment yet.
"""
return self.tls_session.wcs.cipher.encrypt(s)
def post_build(self, pkt, pay):
"""
Apply the previous methods according to the writing cipher type.
"""
# Compute the length of TLSPlaintext fragment
hdr, frag = pkt[:5], pkt[5:]
l = len(frag)
hdr = hdr[:3] + struct.pack("!H", l)
# Compression
cfrag = self._tls_compress(frag)
l = len(cfrag) # Update the length as a result of compression
hdr = hdr[:3] + struct.pack("!H", l)
cipher_type = self.tls_session.wcs.cipher.type
if cipher_type == 'block':
# Integrity
mfrag = self._tls_hmac_add(hdr, cfrag)
# Excerpt below better corresponds to TLS 1.1 IV definition,
# but the result is the same as with TLS 1.2 anyway.
#if self.version >= 0x0302:
# l = self.tls_session.wcs.cipher.block_size
# iv = randstring(l)
# mfrag = iv + mfrag
# Add padding
pfrag = self._tls_pad(mfrag)
# Encryption
if self.version >= 0x0302:
# Explicit IV for TLS 1.1 and 1.2
l = self.tls_session.wcs.cipher.block_size
iv = randstring(l)
self.tls_session.wcs.cipher.iv = iv
efrag = self._tls_encrypt(pfrag)
efrag = iv + efrag
else:
# Implicit IV for SSLv3 and TLS 1.0
efrag = self._tls_encrypt(pfrag)
elif cipher_type == "stream":
# Integrity
mfrag = self._tls_hmac_add(hdr, cfrag)
# Encryption
efrag = self._tls_encrypt(mfrag)
elif cipher_type == "aead":
# Authenticated encryption (with nonce_explicit as header)
efrag = self._tls_auth_encrypt(cfrag)
if self.len is not None:
# The user gave us a 'len', let's respect this ultimately
hdr = hdr[:3] + struct.pack("!H", self.len)
else:
# Update header with the length of TLSCiphertext.fragment
hdr = hdr[:3] + struct.pack("!H", len(efrag))
# Now we commit the pending write state if it has been triggered (e.g.
# by an underlying TLSChangeCipherSpec or a SSLv2ClientMasterKey). We
# update nothing if the pwcs was not set. This probably means that
# we're working out-of-context (and we need to keep the default wcs).
if self.tls_session.triggered_pwcs_commit:
if self.tls_session.pwcs is not None:
self.tls_session.wcs = self.tls_session.pwcs
self.tls_session.pwcs = None
self.tls_session.triggered_pwcs_commit = False
return hdr + efrag + pay
###############################################################################
### TLS ChangeCipherSpec ###
###############################################################################
_tls_changecipherspec_type = { 1: "change_cipher_spec" }
class TLSChangeCipherSpec(_GenericTLSSessionInheritance):
"""
Note that, as they are not handshake messages, the ccs messages do not get
appended to the list of messages whose integrity gets verified through the
Finished messages.
"""
name = "TLS ChangeCipherSpec"
fields_desc = [ ByteEnumField("msgtype", 1, _tls_changecipherspec_type) ]
def post_dissection_tls_session_update(self, msg_str):
self.tls_session.triggered_prcs_commit = True
def post_build_tls_session_update(self, msg_str):
# Unlike for dissection case, we cannot commit pending write
# state as current write state. We need to delay this after
# the ChangeCipherSpec message has indeed been sent
self.tls_session.triggered_pwcs_commit = True
###############################################################################
### TLS Alert ###
###############################################################################
_tls_alert_level = { 1: "warning", 2: "fatal"}
_tls_alert_description = {
0: "close_notify", 10: "unexpected_message",
20: "bad_record_mac", 21: "decryption_failed",
22: "record_overflow", 30: "decompression_failure",
40: "handshake_failure", 41: "no_certificate_RESERVED",
42: "bad_certificate", 43: "unsupported_certificate",
44: "certificate_revoked", 45: "certificate_expired",
46: "certificate_unknown", 47: "illegal_parameter",
48: "unknown_ca", 49: "access_denied",
50: "decode_error", 51: "decrypt_error",
60: "export_restriction_RESERVED", 70: "protocol_version",
71: "insufficient_security", 80: "internal_error",
90: "user_canceled", 100: "no_renegotiation",
110: "unsupported_extension", 111: "certificate_unobtainable",
112: "unrecognized_name", 113: "bad_certificate_status_response",
114: "bad_certificate_hash_value", 115: "unknown_psk_identity" }
class TLSAlert(_GenericTLSSessionInheritance):
name = "TLS Alert"
fields_desc = [ ByteEnumField("level", None, _tls_alert_level),
ByteEnumField("descr", None, _tls_alert_description) ]
def post_dissection_tls_session_update(self, msg_str):
pass
def post_build_tls_session_update(self, msg_str):
pass
###############################################################################
### TLS Application Data ###
###############################################################################
class TLSApplicationData(_GenericTLSSessionInheritance):
name = "TLS Application Data"
fields_desc = [ StrField("data", "") ]
def post_dissection_tls_session_update(self, msg_str):
pass
def post_build_tls_session_update(self, msg_str):
pass
###############################################################################
### Bindings ###
###############################################################################
bind_bottom_up(TCP, TLS, {"dport": 443})
bind_bottom_up(TCP, TLS, {"sport": 443})
| 1 | 11,541 | Operator precedence is very confusing here. Care to add parentheses? ` ((version or 0x0303) >= 0x0200)` Same below. | secdev-scapy | py |
@@ -45,7 +45,8 @@ import java.nio.file.Path;
import static com.github.javaparser.ParseStart.*;
import static com.github.javaparser.Problem.PROBLEM_BY_BEGIN_POSITION;
import static com.github.javaparser.Providers.*;
-import static com.github.javaparser.utils.Utils.assertNotNull;
+import static com.github.javaparser.utils.Utils.assertNotNull;import org.apache.log4j.Logger;
+
/**
* Parse Java source code and creates Abstract Syntax Trees. | 1 | /*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2016 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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.
*/
package com.github.javaparser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.modules.ModuleDeclaration;
import com.github.javaparser.ast.modules.ModuleDirective;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Path;
import static com.github.javaparser.ParseStart.*;
import static com.github.javaparser.Problem.PROBLEM_BY_BEGIN_POSITION;
import static com.github.javaparser.Providers.*;
import static com.github.javaparser.utils.Utils.assertNotNull;
/**
* Parse Java source code and creates Abstract Syntax Trees.
*
* @author Júlio Vilmar Gesser
* @see StaticJavaParser
*/
public final class JavaParser {
private final ParserConfiguration configuration;
private GeneratedJavaParser astParser = null;
/**
* Instantiate the parser with default configuration. Note that parsing can also be done with the static methods {@link StaticJavaParser}.
* Creating an instance will reduce setup time between parsing files.
*/
public JavaParser() {
this(new ParserConfiguration());
}
/**
* Instantiate the parser. Note that parsing can also be done with the static methods {@link StaticJavaParser}.
* Creating an instance will reduce setup time between parsing files.
*/
public JavaParser(ParserConfiguration configuration) {
this.configuration = configuration;
}
/**
* @return The configuration for this parser.
*/
public ParserConfiguration getParserConfiguration() {
return this.configuration;
}
private GeneratedJavaParser getParserForProvider(Provider provider) {
if (astParser == null) {
astParser = new GeneratedJavaParser(provider);
} else {
astParser.reset(provider);
}
astParser.setTabSize(configuration.getTabSize());
astParser.setStoreTokens(configuration.isStoreTokens());
return astParser;
}
/**
* Parses source code.
* It takes the source code from a Provider.
* The start indicates what can be found in the source code (compilation unit, block, import...)
*
* @param start refer to the constants in ParseStart to see what can be parsed.
* @param provider refer to Providers to see how you can read source. The provider will be closed after parsing.
* @param <N> the subclass of Node that is the result of parsing in the start.
* @return the parse result, a collection of encountered problems, and some extra data.
*/
public <N extends Node> ParseResult<N> parse(ParseStart<N> start, Provider provider) {
assertNotNull(start);
assertNotNull(provider);
for (PreProcessor preProcessor : configuration.getPreProcessors()) {
provider = preProcessor.process(provider);
}
final GeneratedJavaParser parser = getParserForProvider(provider);
try {
N resultNode = start.parse(parser);
ParseResult<N> result = new ParseResult<>(resultNode, parser.problems, parser.getCommentsCollection());
configuration.getPostProcessors().forEach(postProcessor ->
postProcessor.process(result, configuration));
result.getProblems().sort(PROBLEM_BY_BEGIN_POSITION);
return result;
} catch (Exception e) {
final String message = e.getMessage() == null ? "Unknown error" : e.getMessage();
parser.problems.add(new Problem(message, null, e));
return new ParseResult<>(null, parser.problems, parser.getCommentsCollection());
} finally {
try {
provider.close();
} catch (IOException e) {
// Since we're done parsing and have our result, we don't care about any errors.
}
}
}
/**
* Parses the Java code contained in the {@link InputStream} and returns a
* {@link CompilationUnit} that represents it.
*
* @param in {@link InputStream} containing Java source code. It will be closed after parsing.
* @param encoding encoding of the source code
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<CompilationUnit> parse(final InputStream in, Charset encoding) {
return parse(COMPILATION_UNIT, provider(in, encoding));
}
/**
* Parses the Java code contained in the {@link InputStream} and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param in {@link InputStream} containing Java source code. It will be closed after parsing.
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<CompilationUnit> parse(final InputStream in) {
return parse(in, configuration.getCharacterEncoding());
}
/**
* Parses the Java code contained in a {@link File} and returns a
* {@link CompilationUnit} that represents it.
*
* @param file {@link File} containing Java source code. It will be closed after parsing.
* @param encoding encoding of the source code
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @throws FileNotFoundException the file was not found
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public ParseResult<CompilationUnit> parse(final File file, final Charset encoding) throws FileNotFoundException {
ParseResult<CompilationUnit> result = parse(COMPILATION_UNIT, provider(file, encoding));
result.getResult().ifPresent(cu -> cu.setStorage(file.toPath()));
return result;
}
/**
* Parses the Java code contained in a {@link File} and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param file {@link File} containing Java source code. It will be closed after parsing.
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @throws FileNotFoundException the file was not found
*/
public ParseResult<CompilationUnit> parse(final File file) throws FileNotFoundException {
ParseResult<CompilationUnit> result = parse(COMPILATION_UNIT, provider(file, configuration.getCharacterEncoding()));
result.getResult().ifPresent(cu -> cu.setStorage(file.toPath()));
return result;
}
/**
* Parses the Java code contained in a file and returns a
* {@link CompilationUnit} that represents it.
*
* @param path path to a file containing Java source code
* @param encoding encoding of the source code
* @return CompilationUnit representing the Java source code
* @throws IOException the path could not be accessed
* @throws ParseProblemException if the source code has parser errors
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public ParseResult<CompilationUnit> parse(final Path path, final Charset encoding) throws IOException {
ParseResult<CompilationUnit> result = parse(COMPILATION_UNIT, provider(path, encoding));
result.getResult().ifPresent(cu -> cu.setStorage(path));
return result;
}
/**
* Parses the Java code contained in a file and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param path path to a file containing Java source code
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @throws IOException the path could not be accessed
*/
public ParseResult<CompilationUnit> parse(final Path path) throws IOException {
ParseResult<CompilationUnit> result = parse(COMPILATION_UNIT, provider(path, configuration.getCharacterEncoding()));
result.getResult().ifPresent(cu -> cu.setStorage(path));
return result;
}
/**
* Parses the Java code contained in a resource and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param path path to a resource containing Java source code. As resource is accessed through a class loader, a
* leading "/" is not allowed in pathToResource
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @throws IOException the path could not be accessed
*/
public ParseResult<CompilationUnit> parseResource(final String path) throws IOException {
return parse(COMPILATION_UNIT, resourceProvider(path, configuration.getCharacterEncoding()));
}
/**
* Parses the Java code contained in a resource and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param path path to a resource containing Java source code. As resource is accessed through a class loader, a
* leading "/" is not allowed in pathToResource
* @param encoding encoding of the source code
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @throws IOException the path could not be accessed
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public ParseResult<CompilationUnit> parseResource(final String path, Charset encoding) throws IOException {
return parse(COMPILATION_UNIT, resourceProvider(path, encoding));
}
/**
* Parses the Java code contained in a resource and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param classLoader the classLoader that is asked to load the resource
* @param path path to a resource containing Java source code. As resource is accessed through a class loader, a
* leading "/" is not allowed in pathToResource
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @throws IOException the path could not be accessed
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public ParseResult<CompilationUnit> parseResource(final ClassLoader classLoader, final String path, Charset encoding) throws IOException {
return parse(COMPILATION_UNIT, resourceProvider(classLoader, path, encoding));
}
/**
* Parses Java code from a Reader and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param reader the reader containing Java source code. It will be closed after parsing.
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<CompilationUnit> parse(final Reader reader) {
return parse(COMPILATION_UNIT, provider(reader));
}
/**
* Parses the Java code contained in code and returns a
* {@link CompilationUnit} that represents it.
*
* @param code Java source code
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<CompilationUnit> parse(String code) {
return parse(COMPILATION_UNIT, provider(code));
}
/**
* Parses the Java block contained in a {@link String} and returns a
* {@link BlockStmt} that represents it.
*
* @param blockStatement {@link String} containing Java block code
* @return BlockStmt representing the Java block
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<BlockStmt> parseBlock(final String blockStatement) {
return parse(BLOCK, provider(blockStatement));
}
/**
* Parses the Java statement contained in a {@link String} and returns a
* {@link Statement} that represents it.
*
* @param statement {@link String} containing Java statement code
* @return Statement representing the Java statement
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<Statement> parseStatement(final String statement) {
return parse(STATEMENT, provider(statement));
}
/**
* Parses the Java import contained in a {@link String} and returns a
* {@link ImportDeclaration} that represents it.
*
* @param importDeclaration {@link String} containing Java import code
* @return ImportDeclaration representing the Java import declaration
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<ImportDeclaration> parseImport(final String importDeclaration) {
return parse(IMPORT_DECLARATION, provider(importDeclaration));
}
/**
* Parses the Java expression contained in a {@link String} and returns a
* {@link Expression} that represents it.
*
* @param expression {@link String} containing Java expression
* @return Expression representing the Java expression
* @throws ParseProblemException if the source code has parser errors
*/
@SuppressWarnings("unchecked")
public <T extends Expression> ParseResult<T> parseExpression(final String expression) {
return (ParseResult<T>) parse(EXPRESSION, provider(expression));
}
/**
* Parses the Java annotation contained in a {@link String} and returns a
* {@link AnnotationExpr} that represents it.
*
* @param annotation {@link String} containing Java annotation
* @return AnnotationExpr representing the Java annotation
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<AnnotationExpr> parseAnnotation(final String annotation) {
return parse(ANNOTATION, provider(annotation));
}
/**
* Parses the Java annotation body declaration(e.g fields or methods) contained in a
* {@link String} and returns a {@link BodyDeclaration} that represents it.
*
* @param body {@link String} containing Java body declaration
* @return BodyDeclaration representing the Java annotation
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<BodyDeclaration<?>> parseAnnotationBodyDeclaration(final String body) {
return parse(ANNOTATION_BODY, provider(body));
}
/**
* Parses a Java class or interface body declaration(e.g fields or methods) and returns a
* {@link BodyDeclaration} that represents it.
*
* @param body the body of a class or interface
* @return BodyDeclaration representing the Java interface body
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<BodyDeclaration<?>> parseBodyDeclaration(String body) {
return parse(CLASS_BODY, provider(body));
}
/**
* Parses a Java class or interface type name and returns a {@link ClassOrInterfaceType} that represents it.
*
* @param type the type name like a.b.c.X or Y
* @return ClassOrInterfaceType representing the type
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<ClassOrInterfaceType> parseClassOrInterfaceType(String type) {
return parse(CLASS_OR_INTERFACE_TYPE, provider(type));
}
/**
* Parses a Java type name and returns a {@link Type} that represents it.
*
* @param type the type name like a.b.c.X, Y, or int
* @return ClassOrInterfaceType representing the type
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<Type> parseType(String type) {
return parse(TYPE, provider(type));
}
/**
* Parses a variable declaration expression and returns a {@link com.github.javaparser.ast.expr.VariableDeclarationExpr}
* that represents it.
*
* @param declaration a variable declaration like <code>int x=2;</code>
* @return VariableDeclarationExpr representing the type
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<VariableDeclarationExpr> parseVariableDeclarationExpr(String declaration) {
return parse(VARIABLE_DECLARATION_EXPR, provider(declaration));
}
/**
* Parses the this(...) and super(...) statements that may occur at the start of a constructor.
*
* @param statement a statement like super("hello");
* @return the AST for the statement.
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<ExplicitConstructorInvocationStmt> parseExplicitConstructorInvocationStmt(String statement) {
return parse(EXPLICIT_CONSTRUCTOR_INVOCATION_STMT, provider(statement));
}
/**
* Parses a qualified name (one that can have "."s in it) and returns it as a Name.
*
* @param qualifiedName a name like "com.laamella.parameter_source"
* @return the AST for the name
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<Name> parseName(String qualifiedName) {
return parse(NAME, provider(qualifiedName));
}
/**
* Parses a simple name (one that can NOT have "."s in it) and returns it as a SimpleName.
*
* @param name a name like "parameter_source"
* @return the AST for the name
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<SimpleName> parseSimpleName(String name) {
return parse(SIMPLE_NAME, provider(name));
}
/**
* Parses a single parameter (a type and a name) and returns it as a Parameter.
*
* @param parameter a parameter like "int[] x"
* @return the AST for the parameter
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<Parameter> parseParameter(String parameter) {
return parse(PARAMETER, provider(parameter));
}
/**
* Parses a package declaration and returns it as a PackageDeclaration.
*
* @param packageDeclaration a declaration like "package com.microsoft.java;"
* @return the AST for the parameter
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<PackageDeclaration> parsePackageDeclaration(String packageDeclaration) {
return parse(PACKAGE_DECLARATION, provider(packageDeclaration));
}
/**
* Parses a type declaration and returns it as a TypeDeclaration.
*
* @param typeDeclaration a declaration like "class X {}"
* @return the AST for the type declaration
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<TypeDeclaration<?>> parseTypeDeclaration(String typeDeclaration) {
return parse(TYPE_DECLARATION, provider(typeDeclaration));
}
/**
* Parses a module declaration and returns it as a ModuleDeclaration.
*
* @param moduleDeclaration a declaration like "module X {}"
* @return the AST for the module declaration
* @throws ParseProblemException if the source code has parser errors
* @see ModuleDeclaration
*/
public ParseResult<ModuleDeclaration> parseModuleDeclaration(String moduleDeclaration) {
return parse(MODULE_DECLARATION, provider(moduleDeclaration));
}
/**
* Parses a module directive and returns it as a ModuleDirective.
*
* @param moduleDirective a directive like "opens C;"
* @return the AST for the module directive
* @throws ParseProblemException if the source code has parser errors
* @see ModuleDirective
*/
public ParseResult<ModuleDirective> parseModuleDirective(String moduleDirective) {
return parse(MODULE_DIRECTIVE, provider(moduleDirective));
}
/**
* Parses a type parameter and returns it as a TypeParameter
*
* @param typeParameter a parameter like "T extends Serializable"
* @return the AST for the type parameter
* @throws ParseProblemException if the source code has parser errors
*/
public ParseResult<TypeParameter> parseTypeParameter(String typeParameter) {
return parse(TYPE_PARAMETER, provider(typeParameter));
}
}
| 1 | 13,479 | javaparser-core has no dependencies and it should stay that way. So no log4j. And even then there would have been a preference for slf4j. | javaparser-javaparser | java |
@@ -86,6 +86,16 @@ public class FileUtil implements java.io.Serializable {
private static final Logger logger = Logger.getLogger(FileUtil.class.getCanonicalName());
private static final String[] TABULAR_DATA_FORMAT_SET = {"POR", "SAV", "DTA", "RDA"};
+ // The list of formats for which we need to re-test, if we want to attempt
+ // to ingest the file again:
+ // Example: We have added support for Stata-13+; the new ingest plugin is called
+ // when the file type is detected as "application/x-stata-1[345]". But the
+ // previously uploaded, but not ingested stata files are in the database
+ // typed as "application/x-stata". So we want to run the new-and-improved
+ // DTA check that will re-identify the specific DTA flavor.
+ // If similar cases are introduced in the future, the affected formats will
+ // need to be added to the list.
+ private static final String[] TABULAR_DATA_FORMATS_RETEST = {"DTA"};
private static Map<String, String> STATISTICAL_FILE_EXTENSION = new HashMap<String, String>();
| 1 | /*
Copyright (C) 2005-2012, by the President and Fellows of Harvard College.
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.
Dataverse Network - A web application to share, preserve and analyze research data.
Developed at the Institute for Quantitative Social Science, Harvard University.
Version 3.0.
*/
package edu.harvard.iq.dataverse.util;
import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.DataFile.ChecksumType;
import edu.harvard.iq.dataverse.DataFileServiceBean;
import edu.harvard.iq.dataverse.DatasetVersion;
import edu.harvard.iq.dataverse.FileMetadata;
import edu.harvard.iq.dataverse.TermsOfUseAndAccess;
import edu.harvard.iq.dataverse.dataaccess.ImageThumbConverter;
import edu.harvard.iq.dataverse.dataset.DatasetThumbnail;
import edu.harvard.iq.dataverse.datasetutility.FileExceedsMaxSizeException;
import static edu.harvard.iq.dataverse.datasetutility.FileSizeChecker.bytesToHumanReadable;
import edu.harvard.iq.dataverse.ingest.IngestReport;
import edu.harvard.iq.dataverse.ingest.IngestServiceShapefileHelper;
import edu.harvard.iq.dataverse.ingest.IngestableDataChecker;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ResourceBundle;
import java.util.MissingResourceException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.MimetypesFileTypeMap;
import javax.ejb.EJBException;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* a 4.0 implementation of the DVN FileUtil;
* it provides some of the functionality from the 3.6 implementation,
* but the old code is ported creatively on the method-by-method basis.
*
* @author Leonid Andreev
*/
public class FileUtil implements java.io.Serializable {
private static final Logger logger = Logger.getLogger(FileUtil.class.getCanonicalName());
private static final String[] TABULAR_DATA_FORMAT_SET = {"POR", "SAV", "DTA", "RDA"};
private static Map<String, String> STATISTICAL_FILE_EXTENSION = new HashMap<String, String>();
/*
* The following are Stata, SAS and SPSS syntax/control cards:
* These are recognized as text files (because they are!) so
* we check all the uploaded "text/plain" files for these extensions, and
* assign the following types when they are matched;
* Note that these types are only used in the metadata displayed on the
* dataset page. We don't support ingest on control cards.
* -- L.A. 4.0 Oct. 2014
*/
static {
STATISTICAL_FILE_EXTENSION.put("do", "application/x-stata-syntax");
STATISTICAL_FILE_EXTENSION.put("sas", "application/x-sas-syntax");
STATISTICAL_FILE_EXTENSION.put("sps", "application/x-spss-syntax");
STATISTICAL_FILE_EXTENSION.put("csv", "text/csv");
STATISTICAL_FILE_EXTENSION.put("tsv", "text/tsv");
}
private static MimetypesFileTypeMap MIME_TYPE_MAP = new MimetypesFileTypeMap();
public static final String MIME_TYPE_STATA = "application/x-stata";
public static final String MIME_TYPE_STATA13 = "application/x-stata-13";
public static final String MIME_TYPE_STATA14 = "application/x-stata-14";
public static final String MIME_TYPE_STATA15 = "application/x-stata-15";
public static final String MIME_TYPE_RDATA = "application/x-rlang-transport";
public static final String MIME_TYPE_CSV = "text/csv";
public static final String MIME_TYPE_CSV_ALT = "text/comma-separated-values";
public static final String MIME_TYPE_TSV = "text/tsv";
public static final String MIME_TYPE_TSV_ALT = "text/tab-separated-values";
public static final String MIME_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public static final String MIME_TYPE_SPSS_SAV = "application/x-spss-sav";
public static final String MIME_TYPE_SPSS_POR = "application/x-spss-por";
public static final String MIME_TYPE_FITS = "application/fits";
public static final String MIME_TYPE_ZIP = "application/zip";
public static final String MIME_TYPE_FITSIMAGE = "image/fits";
// SHAPE file type:
// this is the only supported file type in the GEO DATA class:
public static final String MIME_TYPE_GEO_SHAPE = "application/zipped-shapefile";
public static final String MIME_TYPE_UNDETERMINED_DEFAULT = "application/octet-stream";
public static final String MIME_TYPE_UNDETERMINED_BINARY = "application/binary";
public static final String SAVED_ORIGINAL_FILENAME_EXTENSION = "orig";
public static final String MIME_TYPE_INGESTED_FILE = "text/tab-separated-values";
/**
* This string can be prepended to a Base64-encoded representation of a PNG
* file in order to imbed an image directly into an HTML page using the
* "img" tag. See also https://en.wikipedia.org/wiki/Data_URI_scheme
*/
public static String DATA_URI_SCHEME = "data:image/png;base64,";
public FileUtil() {
}
public static void copyFile(File inputFile, File outputFile) throws IOException {
FileChannel in = null;
WritableByteChannel out = null;
try {
in = new FileInputStream(inputFile).getChannel();
out = new FileOutputStream(outputFile).getChannel();
long bytesPerIteration = 50000;
long start = 0;
while ( start < in.size() ) {
in.transferTo(start, bytesPerIteration, out);
start += bytesPerIteration;
}
} finally {
if (in != null) { in.close(); }
if (out != null) { out.close(); }
}
}
public static String getFileExtension(String fileName){
String ext = null;
if ( fileName.lastIndexOf(".") != -1){
ext = (fileName.substring( fileName.lastIndexOf(".") + 1 )).toLowerCase();
}
return ext;
}
public static String replaceExtension(String originalName) {
return replaceExtension(originalName, "tab");
}
public static String replaceExtension(String originalName, String newExtension) {
int extensionIndex = originalName.lastIndexOf(".");
if (extensionIndex != -1 ) {
return originalName.substring(0, extensionIndex) + "."+newExtension ;
} else {
return originalName +"."+newExtension ;
}
}
public static String getUserFriendlyFileType(DataFile dataFile) {
String fileType = dataFile.getContentType();
if (fileType != null) {
if (fileType.equalsIgnoreCase(ShapefileHandler.SHAPEFILE_FILE_TYPE)){
return ShapefileHandler.SHAPEFILE_FILE_TYPE_FRIENDLY_NAME;
}
if (fileType.contains(";")) {
fileType = fileType.substring(0, fileType.indexOf(";"));
}
try {
return ResourceBundle.getBundle("MimeTypeDisplay").getString(fileType);
} catch (MissingResourceException e) {
return fileType;
}
}
return fileType;
}
public static String getFacetFileType(DataFile dataFile) {
String fileType = dataFile.getContentType();
if (fileType != null) {
if (fileType.contains(";")) {
fileType = fileType.substring(0, fileType.indexOf(";"));
}
try {
return ResourceBundle.getBundle("MimeTypeFacets").getString(fileType);
} catch (MissingResourceException e) {
// if there's no defined "facet-friendly" form of this mime type
// we'll truncate the available type by "/", e.g., all the
// unknown image/* types will become "image"; many other, quite
// different types will all become "application" this way -
// but it is probably still better than to tag them all as
// "uknown".
// -- L.A. 4.0 alpha 1
return fileType.split("/")[0];
}
}
return "unknown";
}
public static String getUserFriendlyOriginalType(DataFile dataFile) {
String fileType = dataFile.getOriginalFileFormat();
if (fileType != null && !fileType.equals("")) {
if (fileType.contains(";")) {
fileType = fileType.substring(0, fileType.indexOf(";"));
}
try {
return ResourceBundle.getBundle("MimeTypeDisplay").getString(fileType);
} catch (MissingResourceException e) {
return fileType;
}
}
return "UNKNOWN";
}
/**
* Returns a content type string for a FileObject
*
*/
private static String determineContentType(File fileObject) {
if (fileObject==null){
return null;
}
String contentType;
try {
contentType = determineFileType(fileObject, fileObject.getName());
} catch (Exception ex) {
logger.warning("FileUtil.determineFileType failed for file with name: " + fileObject.getName());
contentType = null;
}
if ((contentType==null)||(contentType.equals(""))){
contentType = MIME_TYPE_UNDETERMINED_DEFAULT;
}
return contentType;
}
public static String determineFileType(File f, String fileName) throws IOException{
String fileType = null;
String fileExtension = getFileExtension(fileName);
// step 1:
// Apply our custom methods to try and recognize data files that can be
// converted to tabular data, or can be parsed for extra metadata
// (such as FITS).
logger.fine("Attempting to identify potential tabular data files;");
IngestableDataChecker tabChk = new IngestableDataChecker(TABULAR_DATA_FORMAT_SET);
fileType = tabChk.detectTabularDataFormat(f);
logger.fine("determineFileType: tabular data checker found "+fileType);
// step 2: If not found, check if graphml or FITS
if (fileType==null) {
if (isGraphMLFile(f)) {
fileType = "text/xml-graphml";
} else // Check for FITS:
// our check is fairly weak (it appears to be hard to really
// really recognize a FITS file without reading the entire
// stream...), so in version 3.* we used to nsist on *both*
// the ".fits" extension and the header check;
// in 4.0, we'll accept either the extension, or the valid
// magic header:
if (isFITSFile(f) || (fileExtension != null
&& fileExtension.equalsIgnoreCase("fits"))) {
fileType = "application/fits";
}
}
// step 3: check the mime type of this file with Jhove
if (fileType == null){
JhoveFileType jw = new JhoveFileType();
String mimeType = jw.getFileMimeType(f);
if (mimeType != null) {
fileType = mimeType;
}
}
// step 4:
// Additional processing; if we haven't gotten much useful information
// back from Jhove, we'll try and make an educated guess based on
// the file extension:
if ( fileExtension != null) {
logger.fine("fileExtension="+fileExtension);
if (fileType == null || fileType.startsWith("text/plain") || "application/octet-stream".equals(fileType)) {
if (fileType != null && fileType.startsWith("text/plain") && STATISTICAL_FILE_EXTENSION.containsKey(fileExtension)) {
fileType = STATISTICAL_FILE_EXTENSION.get(fileExtension);
} else {
fileType = determineFileTypeByExtension(fileName);
}
logger.fine("mime type recognized by extension: "+fileType);
}
} else {
logger.fine("fileExtension is null");
}
// step 5:
// if this is a compressed file - zip or gzip - we'll check the
// file(s) inside the compressed stream and see if it's one of our
// recognized formats that we want to support compressed:
if ("application/x-gzip".equals(fileType)) {
logger.fine("we'll run additional checks on this gzipped file.");
// We want to be able to support gzipped FITS files, same way as
// if they were just regular FITS files:
FileInputStream gzippedIn = new FileInputStream(f);
// (new FileInputStream() can throw a "filen not found" exception;
// however, if we've made it this far, it really means that the
// file does exist and can be opened)
InputStream uncompressedIn = null;
try {
uncompressedIn = new GZIPInputStream(gzippedIn);
if (isFITSFile(uncompressedIn)) {
fileType = "application/fits-gzipped";
}
} catch (IOException ioex) {
if (uncompressedIn != null) {
try {uncompressedIn.close();} catch (IOException e) {}
}
}
}
if ("application/zip".equals(fileType)) {
// Is this a zipped Shapefile?
// Check for shapefile extensions as described here: http://en.wikipedia.org/wiki/Shapefile
//logger.info("Checking for shapefile");
ShapefileHandler shp_handler = new ShapefileHandler(new FileInputStream(f));
if (shp_handler.containsShapefile()){
// logger.info("------- shapefile FOUND ----------");
fileType = ShapefileHandler.SHAPEFILE_FILE_TYPE; //"application/zipped-shapefile";
}
}
logger.fine("returning fileType "+fileType);
return fileType;
}
public static String determineFileTypeByExtension(String fileName) {
logger.fine("Type by extension, for "+fileName+": "+MIME_TYPE_MAP.getContentType(fileName));
return MIME_TYPE_MAP.getContentType(fileName);
}
/*
* Custom method for identifying FITS files:
* TODO:
* the existing check for the "magic header" is very weak (see below);
* it should probably be replaced by attempting to parse and read at
* least the primary HDU, using the NOM fits parser.
* -- L.A. 4.0 alpha
*/
private static boolean isFITSFile(File file) {
BufferedInputStream ins = null;
try {
ins = new BufferedInputStream(new FileInputStream(file));
return isFITSFile(ins);
} catch (IOException ex) {
}
return false;
}
private static boolean isFITSFile(InputStream ins) {
boolean isFITS = false;
// number of header bytes read for identification:
int magicWordLength = 6;
String magicWord = "SIMPLE";
try {
byte[] b = new byte[magicWordLength];
logger.fine("attempting to read "+magicWordLength+" bytes from the FITS format candidate stream.");
if (ins.read(b, 0, magicWordLength) != magicWordLength) {
throw new IOException();
}
if (magicWord.equals(new String(b))) {
logger.fine("yes, this is FITS file!");
isFITS = true;
}
} catch (IOException ex) {
isFITS = false;
} finally {
if (ins != null) {
try {
ins.close();
} catch (Exception e) {
}
}
}
return isFITS;
}
private static boolean isGraphMLFile(File file) {
boolean isGraphML = false;
logger.fine("begin isGraphMLFile()");
try{
FileReader fileReader = new FileReader(file);
javax.xml.stream.XMLInputFactory xmlif = javax.xml.stream.XMLInputFactory.newInstance();
xmlif.setProperty("javax.xml.stream.isCoalescing", java.lang.Boolean.TRUE);
XMLStreamReader xmlr = xmlif.createXMLStreamReader(fileReader);
for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
if (event == XMLStreamConstants.START_ELEMENT) {
if (xmlr.getLocalName().equals("graphml")) {
String schema = xmlr.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation");
logger.fine("schema = "+schema);
if (schema!=null && schema.contains("http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd")){
logger.fine("graphML is true");
isGraphML = true;
}
}
break;
}
}
} catch(XMLStreamException e) {
logger.fine("XML error - this is not a valid graphML file.");
isGraphML = false;
} catch(IOException e) {
throw new EJBException(e);
}
logger.fine("end isGraphML()");
return isGraphML;
}
// from MD5Checksum.java
public static String CalculateCheckSum(String datafile, ChecksumType checksumType) {
FileInputStream fis = null;
try {
fis = new FileInputStream(datafile);
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
return CalculateChecksum(fis, checksumType);
}
// from MD5Checksum.java
public static String CalculateChecksum(InputStream in, ChecksumType checksumType) {
MessageDigest md = null;
try {
// Use "SHA-1" (toString) rather than "SHA1", for example.
md = MessageDigest.getInstance(checksumType.toString());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
byte[] dataBytes = new byte[1024];
int nread;
try {
while ((nread = in.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
try {
in.close();
} catch (Exception e) {
}
}
byte[] mdbytes = md.digest();
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
public static String generateOriginalExtension(String fileType) {
if (fileType.equalsIgnoreCase("application/x-spss-sav")) {
return ".sav";
} else if (fileType.equalsIgnoreCase("application/x-spss-por")) {
return ".por";
} else if (fileType.equalsIgnoreCase("application/x-stata")) {
return ".dta";
} else if (fileType.equalsIgnoreCase( "application/x-rlang-transport")) {
return ".RData";
} else if (fileType.equalsIgnoreCase("text/csv")) {
return ".csv";
} else if (fileType.equalsIgnoreCase( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
return ".xlsx";
}
return "";
}
public static List<DataFile> createDataFiles(DatasetVersion version, InputStream inputStream, String fileName, String suppliedContentType, SystemConfig systemConfig) throws IOException {
List<DataFile> datafiles = new ArrayList<>();
String warningMessage = null;
// save the file, in the temporary location for now:
Path tempFile = null;
Long fileSizeLimit = systemConfig.getMaxFileUploadSize();
if (getFilesTempDirectory() != null) {
tempFile = Files.createTempFile(Paths.get(getFilesTempDirectory()), "tmp", "upload");
// "temporary" location is the key here; this is why we are not using
// the DataStore framework for this - the assumption is that
// temp files will always be stored on the local filesystem.
// -- L.A. Jul. 2014
logger.fine("Will attempt to save the file as: " + tempFile.toString());
Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
// A file size check, before we do anything else:
// (note that "no size limit set" = "unlimited")
// (also note, that if this is a zip file, we'll be checking
// the size limit for each of the individual unpacked files)
Long fileSize = tempFile.toFile().length();
if (fileSizeLimit != null && fileSize > fileSizeLimit) {
try {tempFile.toFile().delete();} catch (Exception ex) {}
throw new IOException (MessageFormat.format(BundleUtil.getStringFromBundle("file.addreplace.error.file_exceeds_limit"), bytesToHumanReadable(fileSize), bytesToHumanReadable(fileSizeLimit)));
}
} else {
throw new IOException ("Temp directory is not configured.");
}
logger.fine("mime type supplied: "+suppliedContentType);
// Let's try our own utilities (Jhove, etc.) to determine the file type
// of the uploaded file. (We may already have a mime type supplied for this
// file - maybe the type that the browser recognized on upload; or, if
// it's a harvest, maybe the remote server has already given us the type
// for this file... with our own type utility we may or may not do better
// than the type supplied:
// -- L.A.
String recognizedType = null;
String finalType = null;
try {
recognizedType = determineFileType(tempFile.toFile(), fileName);
logger.fine("File utility recognized the file as " + recognizedType);
if (recognizedType != null && !recognizedType.equals("")) {
// is it any better than the type that was supplied to us,
// if any?
// This is not as trivial a task as one might expect...
// We may need a list of "good" mime types, that should always
// be chosen over other choices available. Maybe it should
// even be a weighed list... as in, "application/foo" should
// be chosen over "application/foo-with-bells-and-whistles".
// For now the logic will be as follows:
//
// 1. If the contentType supplied (by the browser, most likely)
// is some form of "unknown", we always discard it in favor of
// whatever our own utilities have determined;
// 2. We should NEVER trust the browser when it comes to the
// following "ingestable" types: Stata, SPSS, R;
// 2a. We are willing to TRUST the browser when it comes to
// the CSV and XSLX ingestable types.
// 3. We should ALWAYS trust our utilities when it comes to
// ingestable types.
if (suppliedContentType == null
|| suppliedContentType.equals("")
|| suppliedContentType.equalsIgnoreCase(MIME_TYPE_UNDETERMINED_DEFAULT)
|| suppliedContentType.equalsIgnoreCase(MIME_TYPE_UNDETERMINED_BINARY)
|| (canIngestAsTabular(suppliedContentType)
&& !suppliedContentType.equalsIgnoreCase(MIME_TYPE_CSV)
&& !suppliedContentType.equalsIgnoreCase(MIME_TYPE_CSV_ALT)
&& !suppliedContentType.equalsIgnoreCase(MIME_TYPE_XLSX))
|| canIngestAsTabular(recognizedType)
|| recognizedType.equals("application/fits-gzipped")
|| recognizedType.equalsIgnoreCase(ShapefileHandler.SHAPEFILE_FILE_TYPE)
|| recognizedType.equals(MIME_TYPE_ZIP)) {
finalType = recognizedType;
}
}
} catch (Exception ex) {
logger.warning("Failed to run the file utility mime type check on file " + fileName);
}
if (finalType == null) {
finalType = (suppliedContentType == null || suppliedContentType.equals(""))
? MIME_TYPE_UNDETERMINED_DEFAULT
: suppliedContentType;
}
// A few special cases:
// if this is a gzipped FITS file, we'll uncompress it, and ingest it as
// a regular FITS file:
if (finalType.equals("application/fits-gzipped")) {
InputStream uncompressedIn = null;
String finalFileName = fileName;
// if the file name had the ".gz" extension, remove it,
// since we are going to uncompress it:
if (fileName != null && fileName.matches(".*\\.gz$")) {
finalFileName = fileName.replaceAll("\\.gz$", "");
}
DataFile datafile = null;
try {
uncompressedIn = new GZIPInputStream(new FileInputStream(tempFile.toFile()));
File unZippedTempFile = saveInputStreamInTempFile(uncompressedIn, fileSizeLimit);
datafile = createSingleDataFile(version, unZippedTempFile, finalFileName, MIME_TYPE_UNDETERMINED_DEFAULT, systemConfig.getFileFixityChecksumAlgorithm());
} catch (IOException | FileExceedsMaxSizeException ioex) {
datafile = null;
} finally {
if (uncompressedIn != null) {
try {uncompressedIn.close();} catch (IOException e) {}
}
}
// If we were able to produce an uncompressed file, we'll use it
// to create and return a final DataFile; if not, we're not going
// to do anything - and then a new DataFile will be created further
// down, from the original, uncompressed file.
if (datafile != null) {
// remove the compressed temp file:
try {
tempFile.toFile().delete();
} catch (SecurityException ex) {
// (this is very non-fatal)
logger.warning("Failed to delete temporary file "+tempFile.toString());
}
datafiles.add(datafile);
return datafiles;
}
// If it's a ZIP file, we are going to unpack it and create multiple
// DataFile objects from its contents:
} else if (finalType.equals("application/zip")) {
ZipInputStream unZippedIn = null;
ZipEntry zipEntry = null;
int fileNumberLimit = systemConfig.getZipUploadFilesLimit();
try {
Charset charset = null;
/*
TODO: (?)
We may want to investigate somehow letting the user specify
the charset for the filenames in the zip file...
- otherwise, ZipInputStream bails out if it encounteres a file
name that's not valid in the current charest (i.e., UTF-8, in
our case). It would be a bit trickier than what we're doing for
SPSS tabular ingests - with the lang. encoding pulldown menu -
because this encoding needs to be specified *before* we upload and
attempt to unzip the file.
-- L.A. 4.0 beta12
logger.info("default charset is "+Charset.defaultCharset().name());
if (Charset.isSupported("US-ASCII")) {
logger.info("charset US-ASCII is supported.");
charset = Charset.forName("US-ASCII");
if (charset != null) {
logger.info("was able to obtain charset for US-ASCII");
}
}
*/
if (charset != null) {
unZippedIn = new ZipInputStream(new FileInputStream(tempFile.toFile()), charset);
} else {
unZippedIn = new ZipInputStream(new FileInputStream(tempFile.toFile()));
}
while (true) {
try {
zipEntry = unZippedIn.getNextEntry();
} catch (IllegalArgumentException iaex) {
// Note:
// ZipInputStream documentation doesn't even mention that
// getNextEntry() throws an IllegalArgumentException!
// but that's what happens if the file name of the next
// entry is not valid in the current CharSet.
// -- L.A.
warningMessage = "Failed to unpack Zip file. (Unknown Character Set used in a file name?) Saving the file as is.";
logger.warning(warningMessage);
throw new IOException();
}
if (zipEntry == null) {
break;
}
// Note that some zip entries may be directories - we
// simply skip them:
if (!zipEntry.isDirectory()) {
if (datafiles.size() > fileNumberLimit) {
logger.warning("Zip upload - too many files.");
warningMessage = "The number of files in the zip archive is over the limit (" + fileNumberLimit +
"); please upload a zip archive with fewer files, if you want them to be ingested " +
"as individual DataFiles.";
throw new IOException();
}
String fileEntryName = zipEntry.getName();
logger.fine("ZipEntry, file: "+fileEntryName);
if (fileEntryName != null && !fileEntryName.equals("")) {
String shortName = fileEntryName.replaceFirst("^.*[\\/]", "");
// Check if it's a "fake" file - a zip archive entry
// created for a MacOS X filesystem element: (these
// start with "._")
if (!shortName.startsWith("._") && !shortName.startsWith(".DS_Store") && !"".equals(shortName)) {
// OK, this seems like an OK file entry - we'll try
// to read it and create a DataFile with it:
File unZippedTempFile = saveInputStreamInTempFile(unZippedIn, fileSizeLimit);
DataFile datafile = createSingleDataFile(version, unZippedTempFile, shortName, MIME_TYPE_UNDETERMINED_DEFAULT, systemConfig.getFileFixityChecksumAlgorithm(), false);
if (!fileEntryName.equals(shortName)) {
// If the filename looks like a hierarchical folder name (i.e., contains slashes and backslashes),
// we'll extract the directory name, then a) strip the leading and trailing slashes;
// and b) replace all the back slashes with regular ones and b) replace any multiple
// slashes with a single slash:
String directoryName = fileEntryName.replaceFirst("[\\/][\\/]*[^\\/]*$", "").replaceFirst("^[\\/]*", "").replaceAll("[\\/][\\/]*", "/");
if (!"".equals(directoryName)) {
logger.fine("setting the directory label to " + directoryName);
datafile.getFileMetadata().setDirectoryLabel(directoryName);
}
}
if (datafile != null) {
// We have created this datafile with the mime type "unknown";
// Now that we have it saved in a temporary location,
// let's try and determine its real type:
String tempFileName = getFilesTempDirectory() + "/" + datafile.getStorageIdentifier();
try {
recognizedType = determineFileType(new File(tempFileName), shortName);
logger.fine("File utility recognized unzipped file as " + recognizedType);
if (recognizedType != null && !recognizedType.equals("")) {
datafile.setContentType(recognizedType);
}
} catch (Exception ex) {
logger.warning("Failed to run the file utility mime type check on file " + fileName);
}
datafiles.add(datafile);
}
}
}
}
unZippedIn.closeEntry();
}
} catch (IOException ioex) {
// just clear the datafiles list and let
// ingest default to creating a single DataFile out
// of the unzipped file.
logger.warning("Unzipping failed; rolling back to saving the file as is.");
if (warningMessage == null) {
warningMessage = "Failed to unzip the file. Saving the file as is.";
}
datafiles.clear();
} catch (FileExceedsMaxSizeException femsx) {
logger.warning("One of the unzipped files exceeds the size limit; resorting to saving the file as is. " + femsx.getMessage());
warningMessage = femsx.getMessage() + "; saving the zip file as is, unzipped.";
datafiles.clear();
} finally {
if (unZippedIn != null) {
try {unZippedIn.close();} catch (Exception zEx) {}
}
}
if (datafiles.size() > 0) {
// link the data files to the dataset/version:
// (except we no longer want to do this! -- 4.6)
/*Iterator<DataFile> itf = datafiles.iterator();
while (itf.hasNext()) {
DataFile datafile = itf.next();
datafile.setOwner(version.getDataset());
if (version.getFileMetadatas() == null) {
version.setFileMetadatas(new ArrayList());
}
version.getFileMetadatas().add(datafile.getFileMetadata());
datafile.getFileMetadata().setDatasetVersion(version);
version.getDataset().getFiles().add(datafile);
} */
// remove the uploaded zip file:
try {
Files.delete(tempFile);
} catch (IOException ioex) {
// do nothing - it's just a temp file.
logger.warning("Could not remove temp file "+tempFile.getFileName().toString());
}
// and return:
return datafiles;
}
} else if (finalType.equalsIgnoreCase(ShapefileHandler.SHAPEFILE_FILE_TYPE)) {
// Shape files may have to be split into multiple files,
// one zip archive per each complete set of shape files:
//File rezipFolder = new File(this.getFilesTempDirectory());
File rezipFolder = getShapefileUnzipTempDirectory();
IngestServiceShapefileHelper shpIngestHelper;
shpIngestHelper = new IngestServiceShapefileHelper(tempFile.toFile(), rezipFolder);
boolean didProcessWork = shpIngestHelper.processFile();
if (!(didProcessWork)){
logger.severe("Processing of zipped shapefile failed.");
return null;
}
try {
for (File finalFile : shpIngestHelper.getFinalRezippedFiles()) {
FileInputStream finalFileInputStream = new FileInputStream(finalFile);
finalType = determineContentType(finalFile);
if (finalType == null) {
logger.warning("Content type is null; but should default to 'MIME_TYPE_UNDETERMINED_DEFAULT'");
continue;
}
File unZippedShapeTempFile = saveInputStreamInTempFile(finalFileInputStream, fileSizeLimit);
DataFile new_datafile = createSingleDataFile(version, unZippedShapeTempFile, finalFile.getName(), finalType, systemConfig.getFileFixityChecksumAlgorithm());
if (new_datafile != null) {
datafiles.add(new_datafile);
} else {
logger.severe("Could not add part of rezipped shapefile. new_datafile was null: " + finalFile.getName());
}
finalFileInputStream.close();
}
} catch (FileExceedsMaxSizeException femsx) {
logger.severe("One of the unzipped shape files exceeded the size limit; giving up. " + femsx.getMessage());
datafiles.clear();
}
// Delete the temp directory used for unzipping
//logger.fine("Delete temp shapefile unzip directory: " + rezipFolder.getAbsolutePath());
//FileUtils.deleteDirectory(rezipFolder);
//// Delete rezipped files
//for (File finalFile : shpIngestHelper.getFinalRezippedFiles()){
// if (finalFile.isFile()){
// finalFile.delete();
// }
//}
if (datafiles.size() > 0) {
return datafiles;
}else{
logger.severe("No files added from directory of rezipped shapefiles");
}
return null;
}
// Finally, if none of the special cases above were applicable (or
// if we were unable to unpack an uploaded file, etc.), we'll just
// create and return a single DataFile:
DataFile datafile = createSingleDataFile(version, tempFile.toFile(), fileName, finalType, systemConfig.getFileFixityChecksumAlgorithm());
if (datafile != null && tempFile.toFile() != null) {
if (warningMessage != null) {
createIngestFailureReport(datafile, warningMessage);
datafile.SetIngestProblem();
}
datafiles.add(datafile);
return datafiles;
}
return null;
} // end createDataFiles
private static File saveInputStreamInTempFile(InputStream inputStream, Long fileSizeLimit) throws IOException, FileExceedsMaxSizeException {
Path tempFile = Files.createTempFile(Paths.get(getFilesTempDirectory()), "tmp", "upload");
if (inputStream != null && tempFile != null) {
Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
// size check:
// (note that "no size limit set" = "unlimited")
Long fileSize = tempFile.toFile().length();
if (fileSizeLimit != null && fileSize > fileSizeLimit) {
try {tempFile.toFile().delete();} catch (Exception ex) {}
throw new FileExceedsMaxSizeException (MessageFormat.format(BundleUtil.getStringFromBundle("file.addreplace.error.file_exceeds_limit"), bytesToHumanReadable(fileSize), bytesToHumanReadable(fileSizeLimit)));
}
return tempFile.toFile();
}
throw new IOException("Failed to save uploaded file.");
}
/*
* This method creates a DataFile;
* The bytes from the suppplied InputStream have already been saved in the temporary location.
* This method should only be called by the upper-level methods that handle
* file upload and creation for individual use cases - a single file upload,
* an upload of a zip archive that needs to be unpacked and turned into
* individual files, etc., and once the file name and mime type have already
* been figured out.
*/
private static DataFile createSingleDataFile(DatasetVersion version, File tempFile, String fileName, String contentType, DataFile.ChecksumType checksumType) {
return createSingleDataFile(version, tempFile, fileName, contentType, checksumType, false);
}
private static DataFile createSingleDataFile(DatasetVersion version, File tempFile, String fileName, String contentType, DataFile.ChecksumType checksumType, boolean addToDataset) {
if (tempFile == null) {
return null;
}
DataFile datafile = new DataFile(contentType);
datafile.setModificationTime(new Timestamp(new Date().getTime()));
/**
* @todo Think more about when permissions on files are modified.
* Obviously, here at create time files have some sort of permissions,
* even if these permissions are *implied*, by ViewUnpublishedDataset at
* the dataset level, for example.
*/
datafile.setPermissionModificationTime(new Timestamp(new Date().getTime()));
FileMetadata fmd = new FileMetadata();
// TODO: add directoryLabel?
fmd.setLabel(fileName);
if (addToDataset) {
datafile.setOwner(version.getDataset());
}
fmd.setDataFile(datafile);
datafile.getFileMetadatas().add(fmd);
if (addToDataset) {
if (version.getFileMetadatas() == null) {
version.setFileMetadatas(new ArrayList<>());
}
version.getFileMetadatas().add(fmd);
fmd.setDatasetVersion(version);
version.getDataset().getFiles().add(datafile);
}
generateStorageIdentifier(datafile);
if (!tempFile.renameTo(new File(getFilesTempDirectory() + "/" + datafile.getStorageIdentifier()))) {
return null;
}
try {
// We persist "SHA1" rather than "SHA-1".
datafile.setChecksumType(checksumType);
datafile.setChecksumValue(CalculateCheckSum(getFilesTempDirectory() + "/" + datafile.getStorageIdentifier(), datafile.getChecksumType()));
} catch (Exception cksumEx) {
logger.warning("Could not calculate " + checksumType + " signature for the new file " + fileName);
}
return datafile;
}
/**
For the restructuring of zipped shapefiles, create a timestamped directory.
This directory is deleted after successful restructuring.
Naming convention: getFilesTempDirectory() + "shp_" + "yyyy-MM-dd-hh-mm-ss-SSS"
*/
private static File getShapefileUnzipTempDirectory(){
String tempDirectory = getFilesTempDirectory();
if (tempDirectory == null){
logger.severe("Failed to retrieve tempDirectory, null was returned" );
return null;
}
String datestampedFileName = "shp_" + new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSS").format(new Date());
String datestampedFolderName = tempDirectory + "/" + datestampedFileName;
File datestampedFolder = new File(datestampedFolderName);
if (!datestampedFolder.isDirectory()) {
/* Note that "createDirectories()" must be used - not
* "createDirectory()", to make sure all the parent
* directories that may not yet exist are created as well.
*/
try {
Files.createDirectories(Paths.get(datestampedFolderName));
} catch (IOException ex) {
logger.severe("Failed to create temp. directory to unzip shapefile: " + datestampedFolderName );
return null;
}
}
return datestampedFolder;
}
public static boolean canIngestAsTabular(DataFile dataFile) {
String mimeType = dataFile.getContentType();
return canIngestAsTabular(mimeType);
}
public static boolean canIngestAsTabular(String mimeType) {
/*
* In the final 4.0 we'll be doing real-time checks, going through the
* available plugins and verifying the lists of mime types that they
* can handle. In 4.0 beta, the ingest plugins are still built into the
* main code base, so we can just go through a hard-coded list of mime
* types. -- L.A.
*/
if (mimeType == null) {
return false;
}
switch (mimeType) {
case MIME_TYPE_STATA:
case MIME_TYPE_STATA13:
case MIME_TYPE_STATA14:
case MIME_TYPE_STATA15:
case MIME_TYPE_RDATA:
case MIME_TYPE_CSV:
case MIME_TYPE_CSV_ALT:
case MIME_TYPE_TSV:
case MIME_TYPE_TSV_ALT:
case MIME_TYPE_XLSX:
case MIME_TYPE_SPSS_SAV:
case MIME_TYPE_SPSS_POR:
return true;
default:
return false;
}
}
public static String getFilesTempDirectory() {
String filesRootDirectory = System.getProperty("dataverse.files.directory");
if (filesRootDirectory == null || filesRootDirectory.equals("")) {
filesRootDirectory = "/tmp/files";
}
String filesTempDirectory = filesRootDirectory + "/temp";
if (!Files.exists(Paths.get(filesTempDirectory))) {
/* Note that "createDirectories()" must be used - not
* "createDirectory()", to make sure all the parent
* directories that may not yet exist are created as well.
*/
try {
Files.createDirectories(Paths.get(filesTempDirectory));
} catch (IOException ex) {
logger.severe("Failed to create filesTempDirectory: " + filesTempDirectory );
return null;
}
}
return filesTempDirectory;
}
public static void generateStorageIdentifier(DataFile dataFile) {
dataFile.setStorageIdentifier(generateStorageIdentifier());
}
public static String generateStorageIdentifier() {
UUID uid = UUID.randomUUID();
logger.log(Level.FINE, "UUID value: {0}", uid.toString());
// last 6 bytes, of the random UUID, in hex:
String hexRandom = uid.toString().substring(24);
logger.log(Level.FINE, "UUID (last 6 bytes, 12 hex digits): {0}", hexRandom);
String hexTimestamp = Long.toHexString(new Date().getTime());
logger.log(Level.FINE, "(not UUID) timestamp in hex: {0}", hexTimestamp);
String storageIdentifier = hexTimestamp + "-" + hexRandom;
logger.log(Level.FINE, "timestamp/UUID hybrid: {0}", storageIdentifier);
return storageIdentifier;
}
public static void createIngestFailureReport(DataFile dataFile, String message) {
createIngestReport(dataFile, IngestReport.INGEST_STATUS_FAILURE, message);
}
private static void createIngestReport (DataFile dataFile, int status, String message) {
IngestReport errorReport = new IngestReport();
if (status == IngestReport.INGEST_STATUS_FAILURE) {
errorReport.setFailure();
errorReport.setReport(message);
errorReport.setDataFile(dataFile);
dataFile.setIngestReport(errorReport);
}
}
public enum FileCitationExtension {
ENDNOTE("-endnote.xml"),
RIS(".ris"),
BIBTEX(".bib");
private final String text;
private FileCitationExtension(final String text) {
this.text = text;
}
}
public static String getCiteDataFileFilename(FileMetadata fileMetadata, FileCitationExtension fileCitationExtension) {
if (fileMetadata == null) {
logger.info("In getCitationBibtex but FileMetadata is null!");
return null;
}
if (fileCitationExtension == null) {
logger.info("In getCitationBibtex but fileCitationExtension is null!");
return null;
}
if (fileMetadata.getLabel().endsWith("tab")) {
return fileMetadata.getLabel().replaceAll("\\.tab$", fileCitationExtension.text);
} else {
return fileMetadata.getLabel() + fileCitationExtension.text;
}
}
/**
* @todo Consider returning not only the boolean but the human readable
* reason why the popup is required, which could be used in the GUI to
* elaborate on the text "This file cannot be downloaded publicly."
*/
public static boolean isDownloadPopupRequired(DatasetVersion datasetVersion) {
// Each of these conditions is sufficient reason to have to
// present the user with the popup:
if (datasetVersion == null) {
logger.fine("Download popup required because datasetVersion is null.");
return false;
}
//0. if version is draft then Popup "not required"
if (!datasetVersion.isReleased()) {
logger.fine("Download popup required because datasetVersion has not been released.");
return false;
}
// 1. License and Terms of Use:
if (datasetVersion.getTermsOfUseAndAccess() != null) {
if (!TermsOfUseAndAccess.License.CC0.equals(datasetVersion.getTermsOfUseAndAccess().getLicense())
&& !(datasetVersion.getTermsOfUseAndAccess().getTermsOfUse() == null
|| datasetVersion.getTermsOfUseAndAccess().getTermsOfUse().equals(""))) {
logger.fine("Download popup required because of license or terms of use.");
return true;
}
// 2. Terms of Access:
if (!(datasetVersion.getTermsOfUseAndAccess().getTermsOfAccess() == null) && !datasetVersion.getTermsOfUseAndAccess().getTermsOfAccess().equals("")) {
logger.fine("Download popup required because of terms of access.");
return true;
}
}
// 3. Guest Book:
if (datasetVersion.getDataset() != null && datasetVersion.getDataset().getGuestbook() != null && datasetVersion.getDataset().getGuestbook().isEnabled() && datasetVersion.getDataset().getGuestbook().getDataverse() != null) {
logger.fine("Download popup required because of guestbook.");
return true;
}
logger.fine("Download popup is not required.");
return false;
}
public static boolean isRequestAccessPopupRequired(DatasetVersion datasetVersion){
// Each of these conditions is sufficient reason to have to
// present the user with the popup:
if (datasetVersion == null) {
logger.fine("Download popup required because datasetVersion is null.");
return false;
}
//0. if version is draft then Popup "not required"
if (!datasetVersion.isReleased()) {
logger.fine("Download popup required because datasetVersion has not been released.");
return false;
}
// 1. License and Terms of Use:
if (datasetVersion.getTermsOfUseAndAccess() != null) {
if (!TermsOfUseAndAccess.License.CC0.equals(datasetVersion.getTermsOfUseAndAccess().getLicense())
&& !(datasetVersion.getTermsOfUseAndAccess().getTermsOfUse() == null
|| datasetVersion.getTermsOfUseAndAccess().getTermsOfUse().equals(""))) {
logger.fine("Download popup required because of license or terms of use.");
return true;
}
// 2. Terms of Access:
if (!(datasetVersion.getTermsOfUseAndAccess().getTermsOfAccess() == null) && !datasetVersion.getTermsOfUseAndAccess().getTermsOfAccess().equals("")) {
logger.fine("Download popup required because of terms of access.");
return true;
}
}
logger.fine("Download popup is not required.");
return false;
}
/**
* Provide download URL if no Terms of Use, no guestbook, and not
* restricted.
*/
public static boolean isPubliclyDownloadable(FileMetadata fileMetadata) {
if (fileMetadata == null) {
return false;
}
if (fileMetadata.isRestricted()) {
String msg = "Not publicly downloadable because the file is restricted.";
logger.fine(msg);
return false;
}
boolean popupReasons = isDownloadPopupRequired(fileMetadata.getDatasetVersion());
if (popupReasons == true) {
/**
* @todo The user clicking publish may have a bad "Dude, where did
* the file Download URL go" experience in the following scenario:
*
* - The user creates a dataset and uploads a file.
*
* - The user sets Terms of Use, which means a Download URL should
* not be displayed.
*
* - While the dataset is in draft, the Download URL is displayed
* due to the rule "Download popup required because datasetVersion
* has not been released."
*
* - Once the dataset is published the Download URL disappears due
* to the rule "Download popup required because of license or terms
* of use."
*
* In short, the Download URL disappears on publish in the scenario
* above, which is weird. We should probably attempt to see into the
* future to when the dataset is published to see if the file will
* be publicly downloadable or not.
*/
return false;
}
return true;
}
/**
* This is what the UI displays for "Download URL" on the file landing page
* (DOIs rather than file IDs.
*/
public static String getPublicDownloadUrl(String dataverseSiteUrl, String persistentId) {
String path = "/api/access/datafile/:persistentId?persistentId=" + persistentId;
return dataverseSiteUrl + path;
}
/**
* The FileDownloadServiceBean operates on file IDs, not DOIs.
*/
public static String getFileDownloadUrlPath(String downloadType, Long fileId, boolean gbRecordsWritten) {
String fileDownloadUrl = "/api/access/datafile/" + fileId;
if (downloadType != null && downloadType.equals("bundle")) {
fileDownloadUrl = "/api/access/datafile/bundle/" + fileId;
}
if (downloadType != null && downloadType.equals("original")) {
fileDownloadUrl = "/api/access/datafile/" + fileId + "?format=original";
}
if (downloadType != null && downloadType.equals("RData")) {
fileDownloadUrl = "/api/access/datafile/" + fileId + "?format=RData";
}
if (downloadType != null && downloadType.equals("var")) {
fileDownloadUrl = "/api/access/datafile/" + fileId + "/metadata";
}
if (downloadType != null && downloadType.equals("tab")) {
fileDownloadUrl = "/api/access/datafile/" + fileId + "?format=tab";
}
if (gbRecordsWritten) {
if (downloadType != null && (downloadType.equals("original") || downloadType.equals("RData") || downloadType.equals("tab"))) {
fileDownloadUrl += "&gbrecs=true";
} else {
fileDownloadUrl += "?gbrecs=true";
}
}
logger.fine("Returning file download url: " + fileDownloadUrl);
return fileDownloadUrl;
}
public static File inputStreamToFile(InputStream inputStream) throws IOException {
if (inputStream == null) {
logger.info("In inputStreamToFile but inputStream was null! Returning null rather than a File.");
return null;
}
File file = File.createTempFile(UUID.randomUUID().toString(), UUID.randomUUID().toString());
OutputStream outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
return file;
}
/*
* This method tells you if thumbnail generation is *supported*
* on this type of file. i.e., if true, it does not guarantee that a thumbnail
* can/will be generated; but it means that we can try.
*/
public static boolean isThumbnailSupported (DataFile file) {
if (file == null) {
return false;
}
if (file.isHarvested() || "".equals(file.getStorageIdentifier())) {
return false;
}
String contentType = file.getContentType();
// Some browsers (Chrome?) seem to identify FITS files as mime
// type "image/fits" on upload; this is both incorrect (the official
// mime type for FITS is "application/fits", and problematic: then
// the file is identified as an image, and the page will attempt to
// generate a preview - which of course is going to fail...
if (MIME_TYPE_FITSIMAGE.equalsIgnoreCase(contentType)) {
return false;
}
// besides most image/* types, we can generate thumbnails for
// pdf and "world map" files:
return (contentType != null &&
(contentType.startsWith("image/") ||
contentType.equalsIgnoreCase("application/pdf") ||
(file.isTabularData() && file.hasGeospatialTag()) ||
contentType.equalsIgnoreCase(MIME_TYPE_GEO_SHAPE)));
}
/*
* The method below appears to be unnecessary;
* it duplicates the method generateImageThumbnailFromFileAsBase64() from ImageThumbConverter;
* plus it creates an unnecessary temp file copy of the source file.
public static String rescaleImage(File file) throws IOException {
if (file == null) {
logger.info("file was null!!");
return null;
}
File tmpFile = File.createTempFile("tempFileToRescale", ".tmp");
BufferedImage fullSizeImage = ImageIO.read(file);
if (fullSizeImage == null) {
logger.info("fullSizeImage was null!");
return null;
}
int width = fullSizeImage.getWidth();
int height = fullSizeImage.getHeight();
FileChannel src = new FileInputStream(file).getChannel();
FileChannel dest = new FileOutputStream(tmpFile).getChannel();
dest.transferFrom(src, 0, src.size());
String pathToResizedFile = ImageThumbConverter.rescaleImage(fullSizeImage, width, height, ImageThumbConverter.DEFAULT_CARDIMAGE_SIZE, tmpFile.getAbsolutePath());
File resizedFile = new File(pathToResizedFile);
return ImageThumbConverter.getImageAsBase64FromFile(resizedFile);
}
*/
public static DatasetThumbnail getThumbnail(DataFile file) {
String imageSourceBase64 = ImageThumbConverter.getImageThumbnailAsBase64(file, ImageThumbConverter.DEFAULT_THUMBNAIL_SIZE);
DatasetThumbnail defaultDatasetThumbnail = new DatasetThumbnail(imageSourceBase64, file);
return defaultDatasetThumbnail;
}
public static boolean isPackageFile(DataFile dataFile) {
return DataFileServiceBean.MIME_TYPE_PACKAGE_FILE.equalsIgnoreCase(dataFile.getContentType());
}
}
| 1 | 38,271 | Why not just retest all? it's not expensive (I think). | IQSS-dataverse | java |
@@ -17,8 +17,8 @@
package mock_ecr
import (
- ecr0 "github.com/aws/amazon-ecs-agent/agent/ecr"
- ecr "github.com/aws/amazon-ecs-agent/agent/ecr/model/ecr"
+ ecr "github.com/aws/amazon-ecs-agent/agent/ecr"
+ ecr0 "github.com/aws/amazon-ecs-agent/agent/ecr/model/ecr"
gomock "github.com/golang/mock/gomock"
)
| 1 | // Copyright 2015-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
// Automatically generated by MockGen. DO NOT EDIT!
// Source: github.com/aws/amazon-ecs-agent/agent/ecr (interfaces: ECRSDK,ECRFactory,ECRClient)
package mock_ecr
import (
ecr0 "github.com/aws/amazon-ecs-agent/agent/ecr"
ecr "github.com/aws/amazon-ecs-agent/agent/ecr/model/ecr"
gomock "github.com/golang/mock/gomock"
)
// Mock of ECRSDK interface
type MockECRSDK struct {
ctrl *gomock.Controller
recorder *_MockECRSDKRecorder
}
// Recorder for MockECRSDK (not exported)
type _MockECRSDKRecorder struct {
mock *MockECRSDK
}
func NewMockECRSDK(ctrl *gomock.Controller) *MockECRSDK {
mock := &MockECRSDK{ctrl: ctrl}
mock.recorder = &_MockECRSDKRecorder{mock}
return mock
}
func (_m *MockECRSDK) EXPECT() *_MockECRSDKRecorder {
return _m.recorder
}
func (_m *MockECRSDK) GetAuthorizationToken(_param0 *ecr.GetAuthorizationTokenInput) (*ecr.GetAuthorizationTokenOutput, error) {
ret := _m.ctrl.Call(_m, "GetAuthorizationToken", _param0)
ret0, _ := ret[0].(*ecr.GetAuthorizationTokenOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockECRSDKRecorder) GetAuthorizationToken(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "GetAuthorizationToken", arg0)
}
// Mock of ECRFactory interface
type MockECRFactory struct {
ctrl *gomock.Controller
recorder *_MockECRFactoryRecorder
}
// Recorder for MockECRFactory (not exported)
type _MockECRFactoryRecorder struct {
mock *MockECRFactory
}
func NewMockECRFactory(ctrl *gomock.Controller) *MockECRFactory {
mock := &MockECRFactory{ctrl: ctrl}
mock.recorder = &_MockECRFactoryRecorder{mock}
return mock
}
func (_m *MockECRFactory) EXPECT() *_MockECRFactoryRecorder {
return _m.recorder
}
func (_m *MockECRFactory) GetClient(_param0 string, _param1 string) ecr0.ECRClient {
ret := _m.ctrl.Call(_m, "GetClient", _param0, _param1)
ret0, _ := ret[0].(ecr0.ECRClient)
return ret0
}
func (_mr *_MockECRFactoryRecorder) GetClient(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "GetClient", arg0, arg1)
}
// Mock of ECRClient interface
type MockECRClient struct {
ctrl *gomock.Controller
recorder *_MockECRClientRecorder
}
// Recorder for MockECRClient (not exported)
type _MockECRClientRecorder struct {
mock *MockECRClient
}
func NewMockECRClient(ctrl *gomock.Controller) *MockECRClient {
mock := &MockECRClient{ctrl: ctrl}
mock.recorder = &_MockECRClientRecorder{mock}
return mock
}
func (_m *MockECRClient) EXPECT() *_MockECRClientRecorder {
return _m.recorder
}
func (_m *MockECRClient) GetAuthorizationToken(_param0 string) (*ecr.AuthorizationData, error) {
ret := _m.ctrl.Call(_m, "GetAuthorizationToken", _param0)
ret0, _ := ret[0].(*ecr.AuthorizationData)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockECRClientRecorder) GetAuthorizationToken(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "GetAuthorizationToken", arg0)
}
func (_m *MockECRClient) IsTokenValid(_param0 *ecr.AuthorizationData) bool {
ret := _m.ctrl.Call(_m, "IsTokenValid", _param0)
ret0, _ := ret[0].(bool)
return ret0
}
func (_mr *_MockECRClientRecorder) IsTokenValid(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "IsTokenValid", arg0)
}
| 1 | 16,191 | ecr and ecr0 aren't deterministically named here. This change will just cause confusion in the git history. Could you either: a) fix this and make it deterministic b) regenerate the mock until it doesn't flip definitions for ecr and ecr0 | aws-amazon-ecs-agent | go |
@@ -112,12 +112,13 @@ module Travis
'cdbs qpdf texinfo libssh2-1-dev devscripts '\
"#{optional_apt_pkgs}", retry: true
- r_filename = "R-#{r_version}-$(lsb_release -cs).xz"
- r_url = "https://travis-ci.rstudio.org/#{r_filename}"
+ r_filename = "r-#{r_version}_1_amd64.deb"
+ os_version = "$(lsb_release -ds | perl -a -e '$F[1] =~ tr/[.]//d; print $F[1]')"
+ r_url = "https://cdn.rstudio.com/r/ubuntu-#{os_version}/pkgs/#{r_filename}"
sh.cmd "curl -fLo /tmp/#{r_filename} #{r_url}", retry: true
- sh.cmd "tar xJf /tmp/#{r_filename} -C ~"
- sh.export 'PATH', "${TRAVIS_HOME}/R-bin/bin:$PATH", echo: false
- sh.export 'LD_LIBRARY_PATH', "${TRAVIS_HOME}/R-bin/lib:$LD_LIBRARY_PATH", echo: false
+ sh.cmd "sudo apt-get install gdebi-core"
+ sh.cmd "sudo gdebi r-#{r_version}_1_amd64.deb"
+ sh.export 'PATH', "/opt/R/#{r_version}/bin:$PATH", echo: false
sh.rm "/tmp/#{r_filename}"
sh.cmd "sudo mkdir -p /usr/local/lib/R/site-library $R_LIBS_USER" | 1 | # Maintained by:
# Jim Hester @jimhester [email protected]
# Jeroen Ooms @jeroen [email protected]
#
module Travis
module Build
class Script
class R < Script
DEFAULTS = {
# Basic config options
cran: 'https://cloud.r-project.org',
repos: {},
warnings_are_errors: true,
# Dependencies (installed in this order)
apt_packages: [],
brew_packages: [],
r_binary_packages: [],
r_packages: [],
bioc_packages: [],
r_github_packages: [],
# Build/test options
r_build_args: '',
r_check_args: '--as-cran',
# Heavy dependencies
pandoc: true,
latex: true,
fortran: true,
pandoc_version: '2.2',
# Bioconductor
bioc: 'https://bioconductor.org/biocLite.R',
bioc_required: false,
bioc_check: false,
bioc_use_devel: false,
disable_homebrew: false,
use_devtools: false,
r: 'release'
}
def initialize(data)
# TODO: Is there a way to avoid explicitly naming arguments here?
super
@remotes_installed = false
@devtools_installed = false
@bioc_installed = false
end
def export
super
sh.export 'TRAVIS_R_VERSION', r_version, echo: false
sh.export 'TRAVIS_R_VERSION_STRING', config[:r].to_s, echo: false
sh.export 'R_LIBS_USER', '~/R/Library', echo: false
sh.export 'R_LIBS_SITE', '/usr/local/lib/R/site-library:/usr/lib/R/site-library', echo: false
sh.export '_R_CHECK_CRAN_INCOMING_', 'false', echo: false
sh.export 'NOT_CRAN', 'true', echo: false
end
def configure
super
sh.echo 'R for Travis-CI is not officially supported, '\
'but is community maintained.', ansi: :green
sh.echo 'Please file any issues at https://travis-ci.community/c/languages/r'
sh.echo 'and mention @jeroen and @jimhester in the issue'
sh.fold 'R-install' do
sh.with_options({ assert: true, echo: true, timing: true }) do
sh.echo 'Installing R', ansi: :yellow
case config[:os]
when 'linux'
# This key is added implicitly by the marutter PPA below
#sh.cmd 'apt-key adv --keyserver ha.pool.sks-keyservers.net '\
#'--recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9', sudo: true
# Add marutter's c2d4u plus ppa dependencies as listed on launchpad
if r_version_less_than('3.5.0')
sh.cmd 'sudo add-apt-repository -y "ppa:marutter/rrutter"'
sh.cmd 'sudo add-apt-repository -y "ppa:marutter/c2d4u"'
elsif r_version_less_than('4.0.0')
sh.cmd 'sudo add-apt-repository -y "ppa:marutter/rrutter3.5"'
sh.cmd 'sudo add-apt-repository -y "ppa:marutter/c2d4u3.5"'
else
sh.cmd 'sudo add-apt-repository -y "ppa:marutter/rrutter4.0"'
sh.cmd 'sudo add-apt-repository -y "ppa:c2d4u.team/c2d4u4.0+"'
end
# Extra PPAs that do not depend on R version
sh.cmd 'sudo add-apt-repository -y "ppa:ubuntugis/ppa"'
sh.cmd 'sudo add-apt-repository -y "ppa:cran/travis"'
# Both c2d4u and c2d4u3.5 depend on this ppa for ffmpeg
sh.if "$(lsb_release -cs) = 'trusty'" do
sh.cmd 'sudo add-apt-repository -y "ppa:kirillshkrogalev/ffmpeg-next"'
end
# Update after adding all repositories. Retry several
# times to work around flaky connection to Launchpad PPAs.
sh.cmd 'travis_apt_get_update', retry: true
# Install precompiled R
# Install only the dependencies for an R development environment except for
# libpcre3-dev or r-base-core because they will be included in
# the R binary tarball.
# Dependencies queried with `apt-cache depends -i r-base-dev`.
# qpdf and texinfo are also needed for --as-cran # checks:
# https://stat.ethz.ch/pipermail/r-help//2012-September/335676.html
optional_apt_pkgs = ""
optional_apt_pkgs << "gfortran" if config[:fortran]
sh.cmd 'sudo apt-get install -y --no-install-recommends '\
'build-essential gcc g++ libblas-dev liblapack-dev '\
'libncurses5-dev libreadline-dev libjpeg-dev '\
'libpcre3-dev libpng-dev zlib1g-dev libbz2-dev liblzma-dev libicu-dev '\
'cdbs qpdf texinfo libssh2-1-dev devscripts '\
"#{optional_apt_pkgs}", retry: true
r_filename = "R-#{r_version}-$(lsb_release -cs).xz"
r_url = "https://travis-ci.rstudio.org/#{r_filename}"
sh.cmd "curl -fLo /tmp/#{r_filename} #{r_url}", retry: true
sh.cmd "tar xJf /tmp/#{r_filename} -C ~"
sh.export 'PATH', "${TRAVIS_HOME}/R-bin/bin:$PATH", echo: false
sh.export 'LD_LIBRARY_PATH', "${TRAVIS_HOME}/R-bin/lib:$LD_LIBRARY_PATH", echo: false
sh.rm "/tmp/#{r_filename}"
sh.cmd "sudo mkdir -p /usr/local/lib/R/site-library $R_LIBS_USER"
sh.cmd 'sudo chmod 2777 /usr/local/lib/R /usr/local/lib/R/site-library $R_LIBS_USER'
when 'osx'
# We want to update, but we don't need the 800+ lines of
# output.
unless config[:disable_homebrew]
sh.cmd 'brew update >/dev/null', retry: true
sh.cmd 'brew install checkbashisms || true'
end
# R-devel builds available at mac.r-project.org
if r_version == 'devel'
r_url = "https://mac.r-project.org/high-sierra/R-devel/R-devel.pkg"
# The latest release is the only one available in /bin/macosx
elsif r_version == r_latest
r_url = "#{repos[:CRAN]}/bin/macosx/R-latest.pkg"
# 3.2.5 was never built for OS X so
# we need to use 3.2.4-revised, which is the same codebase
# https://stat.ethz.ch/pipermail/r-devel/2016-May/072642.html
elsif r_version == '3.2.5'
r_url = "#{repos[:CRAN]}/bin/macosx/old/R-3.2.4-revised.pkg"
# the old archive has moved after 3.4.0
elsif r_version_less_than('3.4.0')
r_url = "#{repos[:CRAN]}/bin/macosx/old/R-#{r_version}.pkg"
else
r_url = "#{repos[:CRAN]}/bin/macosx/el-capitan/base/R-#{r_version}.pkg"
end
# Install from latest CRAN binary build for OS X
sh.cmd "curl -fLo /tmp/R.pkg #{r_url}", retry: true
sh.echo 'Installing OS X binary package for R'
sh.cmd 'sudo installer -pkg "/tmp/R.pkg" -target /'
sh.rm '/tmp/R.pkg'
setup_fortran_osx if config[:fortran]
else
sh.failure "Operating system not supported: #{config[:os]}"
end
# Set repos in ~/.Rprofile
repos_str = repos.collect {|k,v| "#{k} = \"#{v}\""}.join(", ")
options_repos = "options(repos = c(#{repos_str}))"
sh.cmd %Q{echo '#{options_repos}' > ~/.Rprofile.site}
sh.export 'R_PROFILE', "~/.Rprofile.site", echo: false
# PDF manual requires latex
if config[:latex]
setup_latex
else
config[:r_check_args] = config[:r_check_args] + " --no-manual"
config[:r_build_args] = config[:r_build_args] + " --no-manual"
end
setup_bioc if needs_bioc?
setup_pandoc if config[:pandoc]
# Removes preinstalled homebrew
disable_homebrew if config[:disable_homebrew]
end
end
end
def announce
super
sh.fold 'R-session-info' do
sh.echo 'R session information', ansi: :yellow
sh.cmd 'Rscript -e \'sessionInfo()\''
end
end
def install
super
sh.if '! -e DESCRIPTION' do
sh.failure "No DESCRIPTION file found, user must supply their own install and script steps"
end
sh.fold "R-dependencies" do
sh.echo 'Installing package dependencies', ansi: :yellow
# Install any declared packages
apt_install config[:apt_packages]
brew_install config[:brew_packages]
r_binary_install config[:r_binary_packages]
r_install config[:r_packages]
r_install config[:bioc_packages]
r_github_install config[:r_github_packages]
# Install dependencies for the package we're testing.
install_deps
end
if @devtools_installed
sh.fold 'R-installed-versions' do
sh.echo 'Installed package versions', ansi: :yellow
sh.cmd 'Rscript -e \'devtools::session_info(installed.packages()[, "Package"])\''
end
end
end
def script
# Build the package
sh.if '! -e DESCRIPTION' do
sh.failure "No DESCRIPTION file found, user must supply their own install and script steps"
end
tarball_script =
'$version = $1 if (/^Version:\s(\S+)/);'\
'$package = $1 if (/^Package:\s*(\S+)/);'\
'END { print "${package}_$version.tar.gz" }'\
sh.export 'PKG_TARBALL', "$(perl -ne '#{tarball_script}' DESCRIPTION)", echo: false
sh.fold 'R-build' do
sh.echo 'Building package', ansi: :yellow
sh.echo "Building with: R CMD build ${R_BUILD_ARGS}"
sh.cmd "R CMD build #{config[:r_build_args]} .",
assert: true
end
# Check the package
sh.fold 'R-check' do
sh.echo 'Checking package', ansi: :yellow
# Test the package
sh.echo 'Checking with: R CMD check "${PKG_TARBALL}" '\
"#{config[:r_check_args]}"
sh.cmd "R CMD check \"${PKG_TARBALL}\" #{config[:r_check_args]}; "\
"CHECK_RET=$?", assert: false
end
export_rcheck_dir
if config[:bioc_check]
# BiocCheck the package
sh.fold 'Bioc-check' do
sh.echo 'Checking with: BiocCheck( "${PKG_TARBALL}" ) '
sh.cmd 'Rscript -e "BiocCheck::BiocCheck(\"${PKG_TARBALL}\", \'quit-with-status\'=TRUE)"'
end
end
if @devtools_installed
# Output check summary
sh.cmd 'Rscript -e "message(devtools::check_failures(path = \"${RCHECK_DIR}\"))"', echo: false
end
# Build fails if R CMD check fails
sh.if '$CHECK_RET -ne 0' do
dump_error_logs
sh.failure 'R CMD check failed'
end
# Turn warnings into errors, if requested.
if config[:warnings_are_errors]
sh.cmd 'grep -q -R "WARNING" "${RCHECK_DIR}/00check.log"', echo: false, assert: false
sh.if '$? -eq 0' do
dump_error_logs
sh.failure "Found warnings, treating as errors (as requested)."
end
end
end
def setup_cache
if data.cache?(:packages)
sh.fold 'package cache' do
sh.echo 'Setting up package cache', ansi: :yellow
directory_cache.add '$R_LIBS_USER'
end
end
end
def cache_slug
super << '--R-' << r_version
end
def use_directory_cache?
super || data.cache?(:packages)
end
private
def needs_bioc?
config[:bioc_required] || !config[:bioc_packages].empty?
end
def packages_as_arg(packages)
packages = Array(packages)
quoted_pkgs = packages.collect{|p| "\"#{p}\""}
"c(#{quoted_pkgs.join(', ')})"
end
def as_r_boolean(bool)
bool ? "TRUE" : "FALSE"
end
def r_install(packages)
return if packages.empty?
packages = Array(packages)
sh.echo "Installing R packages: #{packages.join(', ')}"
pkg_arg = packages_as_arg(packages)
install_script =
"install.packages(#{pkg_arg});"\
"if (!all(#{pkg_arg} %in% installed.packages())) {"\
' q(status = 1, save = "no")'\
'}'
sh.cmd "Rscript -e '#{install_script}'"
end
def r_github_install(packages)
return if packages.empty?
packages = Array(packages)
setup_remotes
setup_devtools if config[:use_devtools]
sh.echo "Installing R packages from GitHub: #{packages.join(', ')}"
pkg_arg = packages_as_arg(packages)
install_script = "remotes::install_github(#{pkg_arg})"
sh.cmd "Rscript -e '#{install_script}'"
end
def r_binary_install(packages)
return if packages.empty?
packages = Array(packages)
if config[:os] == 'linux'
if config[:dist] == 'precise'
sh.echo "R binary packages not supported for 'dist: precise', "\
' falling back to source install'
return r_install packages
end
sh.echo "Installing *binary* R packages: #{packages.join(', ')}"
apt_install packages.collect{|p| "r-cran-#{p.downcase}"}
else
sh.echo "R binary packages not supported on #{config[:os]}, "\
'falling back to source install'
r_install packages
end
end
def apt_install(packages)
return if packages.empty?
packages = Array(packages)
return unless (config[:os] == 'linux')
pkg_arg = packages.join(' ')
sh.echo "Installing apt packages: #{packages.join(', ')}"
sh.cmd "sudo apt-get install -y #{pkg_arg}", retry: true
end
def brew_install(packages)
return if packages.empty?
packages = Array(packages)
return unless (config[:os] == 'osx')
pkg_arg = packages.join(' ')
sh.echo "Installing brew packages: #{packages.join(', ')}"
sh.cmd "brew install #{pkg_arg}", retry: true
end
def install_deps
setup_remotes
setup_devtools if config[:use_devtools]
install_script =
'deps <- remotes::dev_package_deps(dependencies = NA);'\
'remotes::install_deps(dependencies = TRUE);'\
'if (!all(deps$package %in% installed.packages())) {'\
' message("missing: ", paste(setdiff(deps$package, installed.packages()), collapse=", "));'\
' q(status = 1, save = "no")'\
'}'
sh.cmd "Rscript -e '#{install_script}'"
end
def export_rcheck_dir
# Simply strip the tarball name until the last _ and add '.Rcheck',
# relevant R code # https://github.com/wch/r-source/blob/840a972338042b14aa5855cc431b2d0decf68234/src/library/tools/R/check.R#L4608-L4615
sh.export 'RCHECK_DIR', "$(expr \"$PKG_TARBALL\" : '\\(.*\\)_').Rcheck", echo: false
end
def dump_error_logs
dump_log("fail")
dump_log("log")
dump_log("out")
end
def dump_log(type)
sh.fold "#{type} logs" do
sh.echo "R CMD check #{type} logs", ansi: :yellow
cmd =
'for name in '\
"$(find \"${RCHECK_DIR}\" -type f -name \"*#{type}\");"\
'do '\
'echo ">>> Filename: ${name} <<<";'\
'cat ${name};'\
'done'
sh.cmd cmd
end
end
def setup_bioc
unless @bioc_installed
sh.fold 'Bioconductor' do
sh.echo 'Installing Bioconductor', ansi: :yellow
bioc_install_script =
if r_version_less_than("3.5.0")
"source(\"#{config[:bioc]}\");"\
'tryCatch('\
" useDevel(#{as_r_boolean(config[:bioc_use_devel])}),"\
' error=function(e) {if (!grepl("already in use", e$message)) {e}}'\
' );'\
'cat(append = TRUE, file = "~/.Rprofile.site", "options(repos = BiocInstaller::biocinstallRepos());")'
else
'if (!requireNamespace("BiocManager", quietly=TRUE))'\
' install.packages("BiocManager");'\
"if (#{as_r_boolean(config[:bioc_use_devel])})"\
' BiocManager::install(version = "devel", ask = FALSE);'\
'cat(append = TRUE, file = "~/.Rprofile.site", "options(repos = BiocManager::repositories());")'
end
sh.cmd "Rscript -e '#{bioc_install_script}'", retry: true
bioc_install_bioccheck =
if r_version_less_than("3.5.0")
'BiocInstaller::biocLite("BiocCheck")'
else
'BiocManager::install("BiocCheck")'
end
if config[:bioc_check]
sh.cmd "Rscript -e '#{bioc_install_bioccheck}'"
end
end
end
@bioc_installed = true
end
def setup_remotes
unless @remotes_installed
case config[:os]
when 'linux'
# We can't use remotes binaries because R versions < 3.5 are not
# compatible with R versions >= 3.5
r_install ['remotes']
else
remotes_check = '!requireNamespace("remotes", quietly = TRUE)'
remotes_install = 'install.packages("remotes")'
sh.cmd "Rscript -e 'if (#{remotes_check}) #{remotes_install}'",
retry: true
end
end
@remotes_installed = true
end
def setup_devtools
unless @devtools_installed
case config[:os]
when 'linux'
# We can't use devtools binaries because R versions < 3.5 are not
# compatible with R versions >= 3.5
r_install ['devtools']
else
devtools_check = '!requireNamespace("devtools", quietly = TRUE)'
devtools_install = 'install.packages("devtools")'
sh.cmd "Rscript -e 'if (#{devtools_check}) #{devtools_install}'",
retry: true
end
end
@devtools_installed = true
end
def setup_latex
case config[:os]
when 'linux'
texlive_filename = 'texlive.tar.gz'
texlive_url = 'https://github.com/jimhester/ubuntu-bin/releases/download/latest/texlive.tar.gz'
sh.cmd "curl -fLo /tmp/#{texlive_filename} #{texlive_url}", retry: true
sh.cmd "tar xzf /tmp/#{texlive_filename} -C ~"
sh.export 'PATH', "${TRAVIS_HOME}/texlive/bin/x86_64-linux:$PATH"
sh.cmd 'tlmgr update --self', assert: false
when 'osx'
# We use basictex due to disk space constraints.
mactex = 'BasicTeX.pkg'
# TODO: Confirm that this will route us to the nearest mirror.
sh.cmd "curl -fLo \"/tmp/#{mactex}\" --retry 3 http://mirror.ctan.org/systems/mac/mactex/"\
"#{mactex}"
sh.echo 'Installing OS X binary package for MacTeX'
sh.cmd "sudo installer -pkg \"/tmp/#{mactex}\" -target /"
sh.rm "/tmp/#{mactex}"
sh.export 'PATH', '/usr/texbin:/Library/TeX/texbin:$PATH'
sh.cmd 'sudo tlmgr update --self', assert: false
# Install common packages
sh.cmd 'sudo tlmgr install inconsolata upquote '\
'courier courier-scaled helvetic', assert: false
end
end
def setup_pandoc
case config[:os]
when 'linux'
pandoc_filename = "pandoc-#{config[:pandoc_version]}-1-amd64.deb"
pandoc_url = "https://github.com/jgm/pandoc/releases/download/#{config[:pandoc_version]}/"\
"#{pandoc_filename}"
# Download and install pandoc
sh.cmd "curl -fLo /tmp/#{pandoc_filename} #{pandoc_url}"
sh.cmd "sudo dpkg -i /tmp/#{pandoc_filename}"
# Fix any missing dependencies
sh.cmd "sudo apt-get install -f"
# Cleanup
sh.rm "/tmp/#{pandoc_filename}"
when 'osx'
# Change OS name if requested version is less than 1.19.2.2
# Name change was introduced in v2.0 of pandoc.
# c.f. "Build Infrastructure Improvements" section of
# https://github.com/jgm/pandoc/releases/tag/2.0
# Lastly, the last binary for macOS before 2.0 is 1.19.2.1
os_short_name = version_check_less_than("#{config[:pandoc_version]}", "1.19.2.2") ? "macOS" : "osx"
pandoc_filename = "pandoc-#{config[:pandoc_version]}-#{os_short_name}.pkg"
pandoc_url = "https://github.com/jgm/pandoc/releases/download/#{config[:pandoc_version]}/"\
"#{pandoc_filename}"
# Download and install pandoc
sh.cmd "curl -fLo /tmp/#{pandoc_filename} #{pandoc_url}"
sh.cmd "sudo installer -pkg \"/tmp/#{pandoc_filename}\" -target /"
# Cleanup
sh.rm "/tmp/#{pandoc_filename}"
end
end
# Install gfortran libraries the precompiled binaries are linked to
def setup_fortran_osx
return unless (config[:os] == 'osx')
if r_version_less_than('3.4')
sh.cmd 'curl -fLo /tmp/gfortran.tar.bz2 http://r.research.att.com/libs/gfortran-4.8.2-darwin13.tar.bz2', retry: true
sh.cmd 'sudo tar fvxz /tmp/gfortran.tar.bz2 -C /'
sh.rm '/tmp/gfortran.tar.bz2'
elsif r_version_less_than('3.7')
sh.cmd "curl -fLo /tmp/gfortran61.dmg #{repos[:CRAN]}/contrib/extra/macOS/gfortran-6.1-ElCapitan.dmg", retry: true
sh.cmd 'sudo hdiutil attach /tmp/gfortran61.dmg -mountpoint /Volumes/gfortran'
sh.cmd 'sudo installer -pkg "/Volumes/gfortran/gfortran-6.1-ElCapitan/gfortran.pkg" -target /'
sh.cmd 'sudo hdiutil detach /Volumes/gfortran'
sh.rm '/tmp/gfortran61.dmg'
else
sh.cmd "curl -fLo /tmp/gfortran82.dmg https://github.com/fxcoudert/gfortran-for-macOS/releases/download/8.2/gfortran-8.2-Mojave.dmg", retry: true
sh.cmd 'sudo hdiutil attach /tmp/gfortran82.dmg -mountpoint /Volumes/gfortran'
sh.cmd 'sudo installer -pkg "/Volumes/gfortran/gfortran-8.2-Mojave/gfortran.pkg" -target /'
sh.cmd 'sudo hdiutil detach /Volumes/gfortran'
sh.rm '/tmp/gfortran82.dmg'
end
end
# Uninstalls the preinstalled homebrew
# See FAQ: https://docs.brew.sh/FAQ#how-do-i-uninstall-homebrew
def disable_homebrew
return unless (config[:os] == 'osx')
sh.cmd "curl -fsSOL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh"
sh.cmd "sudo /bin/bash uninstall.sh --force"
sh.cmd "rm uninstall.sh"
sh.cmd "hash -r"
sh.cmd "git config --global --unset protocol.version || true"
end
# Abstract out version check
def version_check_less_than(version_str_new, version_str_old)
Gem::Version.new(version_str_old) < Gem::Version.new(version_str_new)
end
def r_version
@r_version ||= normalized_r_version
end
def r_version_less_than(str)
return if normalized_r_version == 'devel' # always false (devel is highest version)
version_check_less_than(str, normalized_r_version)
end
def normalized_r_version(v=Array(config[:r]).first.to_s)
case v
when 'release' then '4.0.0'
when 'oldrel' then '3.6.3'
when '3.0' then '3.0.3'
when '3.1' then '3.1.3'
when '3.2' then '3.2.5'
when '3.3' then '3.3.3'
when '3.4' then '3.4.4'
when '3.5' then '3.5.3'
when '3.6' then '3.6.3'
when '4.0' then '4.0.0'
when 'bioc-devel'
config[:bioc_required] = true
config[:bioc_use_devel] = true
config[:r] = 'release'
normalized_r_version('release')
when 'bioc-release'
config[:bioc_required] = true
config[:bioc_use_devel] = false
config[:r] = 'release'
normalized_r_version('release')
else v
end
end
def r_latest
normalized_r_version('release')
end
def repos
@repos ||= normalized_repos
end
# If CRAN is not set in repos set it with cran
def normalized_repos
v = config[:repos]
if not v.has_key?(:CRAN)
v[:CRAN] = config[:cran]
end
# If the version is less than 3.2 we need to use http repositories
if r_version_less_than('3.2')
v.each {|_, url| url.sub!(/^https:/, "http:")}
config[:bioc].sub!(/^https:/, "http:")
end
v
end
end
end
end
end
| 1 | 17,518 | This looks like bash... does this work in ruby? Or is the idea to inject the entire script into the subsequent commands? | travis-ci-travis-build | rb |
@@ -54,7 +54,7 @@ namespace OpenTelemetry.Context.Propagation
return SpanContext.Blank;
}
- var traceparent = traceparentCollection.First();
+ var traceparent = traceparentCollection?.First();
var traceparentParsed = this.TryExtractTraceparent(traceparent, out var traceId, out var spanId, out var traceoptions);
if (!traceparentParsed) | 1 | // <copyright file="TraceContextFormat.cs" company="OpenTelemetry Authors">
// Copyright 2018, OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace OpenTelemetry.Context.Propagation
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using OpenTelemetry.Abstractions.Context.Propagation;
using OpenTelemetry.Trace;
/// <summary>
/// W3C trace context text wire protocol formatter. See https://github.com/w3c/distributed-tracing/.
/// </summary>
public class TraceContextFormat : ITextFormat
{
private static readonly int VersionLength = "00".Length;
private static readonly int VersionPrefixIdLength = "00-".Length;
private static readonly int TraceIdLength = "0af7651916cd43dd8448eb211c80319c".Length;
private static readonly int VersionAndTraceIdLength = "00-0af7651916cd43dd8448eb211c80319c-".Length;
private static readonly int SpanIdLength = "00f067aa0ba902b7".Length;
private static readonly int VersionAndTraceIdAndSpanIdLength = "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-".Length;
private static readonly int OptionsLength = "00".Length;
private static readonly int TraceparentLengthV0 = "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-00".Length;
/// <inheritdoc/>
public ISet<string> Fields => new HashSet<string> { "tracestate", "traceparent" };
/// <inheritdoc/>
public SpanContext Extract<T>(T carrier, Func<T, string, IEnumerable<string>> getter)
{
try
{
var traceparentCollection = getter(carrier, "traceparent");
var tracestateCollection = getter(carrier, "tracestate");
if (traceparentCollection != null && traceparentCollection.Count() > 1)
{
// multiple traceparent are not allowed
return SpanContext.Blank;
}
var traceparent = traceparentCollection.First();
var traceparentParsed = this.TryExtractTraceparent(traceparent, out var traceId, out var spanId, out var traceoptions);
if (!traceparentParsed)
{
return SpanContext.Blank;
}
var tracestate = Tracestate.Empty;
if (tracestateCollection != null)
{
this.TryExtractTracestate(tracestateCollection.ToArray(), out tracestate);
}
return SpanContext.Create(traceId, spanId, traceoptions, tracestate);
}
catch (Exception)
{
// TODO: logging
}
// in case of exception indicate to upstream that there is no parseable context from the top
return SpanContext.Blank;
}
/// <inheritdoc/>
public void Inject<T>(SpanContext spanContext, T carrier, Action<T, string, string> setter)
{
var traceparent = string.Concat("00-", spanContext.TraceId.ToHexString(), "-", spanContext.SpanId.ToHexString());
traceparent = string.Concat(traceparent, (spanContext.TraceOptions & ActivityTraceFlags.Recorded) != 0 ? "-01" : "-00");
setter(carrier, "traceparent", traceparent);
string tracestateStr = spanContext.Tracestate.ToString();
if (tracestateStr.Length > 0)
{
setter(carrier, "tracestate", tracestateStr);
}
}
private bool TryExtractTraceparent(string traceparent, out ActivityTraceId traceId, out ActivitySpanId spanId, out ActivityTraceFlags traceoptions)
{
// from https://github.com/w3c/distributed-tracing/blob/master/trace_context/HTTP_HEADER_FORMAT.md
// traceparent: 00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-01
traceId = default;
spanId = default;
traceoptions = default;
var bestAttempt = false;
if (string.IsNullOrWhiteSpace(traceparent) || traceparent.Length < TraceparentLengthV0)
{
return false;
}
// if version does not end with delimiter
if (traceparent[VersionPrefixIdLength - 1] != '-')
{
return false;
}
// or version is not a hex (will throw)
var version0 = this.HexCharToByte(traceparent[0]);
var version1 = this.HexCharToByte(traceparent[1]);
if (version0 == 0xf && version1 == 0xf)
{
return false;
}
if (version0 > 0)
{
// expected version is 00
// for higher versions - best attempt parsing of trace id, span id, etc.
bestAttempt = true;
}
if (traceparent[VersionAndTraceIdLength - 1] != '-')
{
return false;
}
try
{
traceId = ActivityTraceId.CreateFromString(traceparent.AsSpan().Slice(VersionPrefixIdLength, TraceIdLength));
}
catch (ArgumentOutOfRangeException)
{
// it's ok to still parse tracestate
return false;
}
if (traceparent[VersionAndTraceIdAndSpanIdLength - 1] != '-')
{
return false;
}
try
{
spanId = ActivitySpanId.CreateFromString(traceparent.AsSpan().Slice(VersionAndTraceIdLength, SpanIdLength));
}
catch (ArgumentOutOfRangeException)
{
// it's ok to still parse tracestate
return false;
}
byte options0;
byte options1;
try
{
options0 = this.HexCharToByte(traceparent[VersionAndTraceIdAndSpanIdLength]);
options1 = this.HexCharToByte(traceparent[VersionAndTraceIdAndSpanIdLength + 1]);
}
catch (ArgumentOutOfRangeException)
{
// it's ok to still parse tracestate
return false;
}
if ((options1 & 1) == 1)
{
traceoptions |= ActivityTraceFlags.Recorded;
}
if ((!bestAttempt) && (traceparent.Length != VersionAndTraceIdAndSpanIdLength + OptionsLength))
{
return false;
}
if (bestAttempt)
{
if ((traceparent.Length > TraceparentLengthV0) && (traceparent[TraceparentLengthV0] != '-'))
{
return false;
}
}
return true;
}
private byte HexCharToByte(char c)
{
if ((c >= '0') && (c <= '9'))
{
return (byte)(c - '0');
}
if ((c >= 'a') && (c <= 'f'))
{
return (byte)(c - 'a' + 10);
}
if ((c >= 'A') && (c <= 'F'))
{
return (byte)(c - 'A' + 10);
}
throw new ArgumentOutOfRangeException(nameof(c), $"Invalid character: {c}.");
}
private bool TryExtractTracestate(string[] tracestateCollection, out Tracestate tracestateResult)
{
tracestateResult = Tracestate.Empty;
var tracestateBuilder = Tracestate.Builder;
try
{
var names = new HashSet<string>();
if (tracestateCollection != null)
{
// Iterate in reverse order because when call builder set the elements is added in the
// front of the list.
for (int i = tracestateCollection.Length - 1; i >= 0; i--)
{
if (!TracestateUtils.TryExtractTracestate(tracestateCollection[i], tracestateBuilder))
{
return false;
}
}
}
tracestateResult = tracestateBuilder.Build();
return true;
}
catch (Exception)
{
// failure to parse tracestate should not disregard traceparent
// TODO: logging
}
return false;
}
}
}
| 1 | 12,149 | I don't understand why this change is in this PR? | open-telemetry-opentelemetry-dotnet | .cs |
@@ -1,5 +1,8 @@
# frozen_string_literal: true
module Blacklight::FacetsHelperBehavior
+ extend Deprecation
+ self.deprecation_horizon = 'blacklight 8.0'
+
include Blacklight::Facet
## | 1 | # frozen_string_literal: true
module Blacklight::FacetsHelperBehavior
include Blacklight::Facet
##
# Check if any of the given fields have values
#
# @param [Array<String>] fields
# @return [Boolean]
def has_facet_values? fields = facet_field_names, response = nil
unless response
Deprecation.warn(self, 'Calling has_facet_values? without passing the ' \
'second argument (response) is deprecated and will be removed in Blacklight ' \
'8.0.0')
response = @response
end
facets_from_request(fields, response).any? { |display_facet| should_render_facet?(display_facet) }
end
##
# Render a collection of facet fields.
# @see #render_facet_limit
#
# @param [Array<String>] fields
# @param [Hash] options
# @options options [Blacklight::Solr::Response] :response the Solr response object
# @return String
def render_facet_partials fields = nil, options = {}
unless fields
Deprecation.warn(self, 'Calling render_facet_partials without passing the ' \
'first argument (fields) is deprecated and will be removed in Blacklight ' \
'8.0.0')
fields = facet_field_names
end
response = options.delete(:response)
unless response
Deprecation.warn(self, 'Calling render_facet_partials without passing the ' \
'response keyword is deprecated and will be removed in Blacklight ' \
'8.0.0')
response = @response
end
safe_join(facets_from_request(fields, response).map do |display_facet|
render_facet_limit(display_facet, options)
end.compact, "\n")
end
##
# Renders a single section for facet limit with a specified
# solr field used for faceting. Can be over-ridden for custom
# display on a per-facet basis.
#
# @param [Blacklight::Solr::Response::Facets::FacetField] display_facet
# @param [Hash] options parameters to use for rendering the facet limit partial
# @option options [String] :partial partial to render
# @option options [String] :layout partial layout to render
# @option options [Hash] :locals locals to pass to the partial
# @return [String]
def render_facet_limit(display_facet, options = {})
field_config = facet_configuration_for_field(display_facet.name)
return unless should_render_facet?(display_facet, field_config)
options = options.dup
options[:partial] ||= facet_partial_name(display_facet)
options[:layout] ||= "facet_layout" unless options.key?(:layout)
options[:locals] ||= {}
options[:locals][:field_name] ||= display_facet.name
options[:locals][:facet_field] ||= field_config
options[:locals][:display_facet] ||= display_facet
render(options)
end
##
# Renders the list of values
# removes any elements where render_facet_item returns a nil value. This enables an application
# to filter undesireable facet items so they don't appear in the UI
def render_facet_limit_list(paginator, facet_field, wrapping_element = :li)
safe_join(paginator.items.map { |item| render_facet_item(facet_field, item) }.compact.map { |item| content_tag(wrapping_element, item) })
end
##
# Renders a single facet item
def render_facet_item(facet_field, item)
if facet_in_params?(facet_field, item.value)
render_selected_facet_value(facet_field, item)
else
render_facet_value(facet_field, item)
end
end
##
# Determine if Blacklight should render the display_facet or not
#
# By default, only render facets with items.
#
# @param [Blacklight::Solr::Response::Facets::FacetField] display_facet
# @param [Blacklight::Configuration::FacetField] facet_config
# @return [Boolean]
def should_render_facet? display_facet, facet_config = nil
return false if display_facet.items.blank?
# display when show is nil or true
facet_config ||= facet_configuration_for_field(display_facet.name)
should_render_field?(facet_config, display_facet)
end
##
# Determine whether a facet should be rendered as collapsed or not.
# - if the facet is 'active', don't collapse
# - if the facet is configured to collapse (the default), collapse
# - if the facet is configured not to collapse, don't collapse
#
# @param [Blacklight::Configuration::FacetField] facet_field
# @return [Boolean]
def should_collapse_facet? facet_field
!facet_field_in_params?(facet_field.key) && facet_field.collapse
end
##
# The name of the partial to use to render a facet field.
# uses the value of the "partial" field if set in the facet configuration
# otherwise uses "facet_pivot" if this facet is a pivot facet
# defaults to 'facet_limit'
#
# @return [String]
def facet_partial_name(display_facet = nil)
config = facet_configuration_for_field(display_facet.name)
name = config.try(:partial)
name ||= "facet_pivot" if config.pivot
name || "facet_limit"
end
##
# Standard display of a facet value in a list. Used in both _facets sidebar
# partial and catalog/facet expanded list. Will output facet value name as
# a link to add that to your restrictions, with count in parens.
#
# @param [Blacklight::Solr::Response::Facets::FacetField] facet_field
# @param [Blacklight::Solr::Response::Facets::FacetItem] item
# @param [Hash] options
# @option options [Boolean] :suppress_link display the facet, but don't link to it
# @return [String]
def render_facet_value(facet_field, item, options = {})
path = path_for_facet(facet_field, item)
content_tag(:span, class: "facet-label") do
link_to_unless(options[:suppress_link],
facet_display_value(facet_field, item),
path,
class: "facet-select")
end + render_facet_count(item.hits)
end
##
# Where should this facet link to?
# @param [Blacklight::Solr::Response::Facets::FacetField] facet_field
# @param [String] item
# @return [String]
def path_for_facet(facet_field, item, path_options = {})
facet_config = facet_configuration_for_field(facet_field)
if facet_config.url_method
send(facet_config.url_method, facet_field, item)
else
search_action_path(search_state.add_facet_params_and_redirect(facet_field, item).merge(path_options))
end
end
##
# Standard display of a SELECTED facet value (e.g. without a link and with a remove button)
# @see #render_facet_value
# @param [Blacklight::Solr::Response::Facets::FacetField] facet_field
# @param [String] item
def render_selected_facet_value(facet_field, item)
remove_href = search_action_path(search_state.remove_facet_params(facet_field, item))
content_tag(:span, class: "facet-label") do
content_tag(:span, facet_display_value(facet_field, item), class: "selected") +
# remove link
link_to(remove_href, class: "remove") do
content_tag(:span, '✖', class: "remove-icon") +
content_tag(:span, '[remove]', class: 'sr-only')
end
end + render_facet_count(item.hits, classes: ["selected"])
end
##
# Renders a count value for facet limits. Can be over-ridden locally
# to change style. And can be called by plugins to get consistent display.
#
# @param [Integer] num number of facet results
# @param [Hash] options
# @option options [Array<String>] an array of classes to add to count span.
# @return [String]
def render_facet_count(num, options = {})
classes = (options[:classes] || []) << "facet-count"
content_tag("span", t('blacklight.search.facets.count', number: number_with_delimiter(num)), class: classes)
end
##
# Are any facet restrictions for a field in the query parameters?
#
# @param [String] field
# @return [Boolean]
def facet_field_in_params? field
facet_params(field).present?
end
##
# Check if the query parameters have the given facet field with the
# given value.
#
# @param [String] field
# @param [String] item facet value
# @return [Boolean]
def facet_in_params?(field, item)
value = facet_value_for_facet_item(item)
(facet_params(field) || []).include? value
end
##
# Get the values of the facet set in the blacklight query string
def facet_params field
config = facet_configuration_for_field(field)
params[:f][config.key] if params[:f]
end
##
# Get the displayable version of a facet's value
#
# @param [Object] field
# @param [String] item value
# @return [String]
def facet_display_value field, item
facet_config = facet_configuration_for_field(field)
value = if item.respond_to? :label
item.label
else
facet_value_for_facet_item(item)
end
if facet_config.helper_method
send facet_config.helper_method, value
elsif facet_config.query && facet_config.query[value]
facet_config.query[value][:label]
elsif facet_config.date
localization_options = facet_config.date == true ? {} : facet_config.date
l(Time.zone.parse(value), localization_options)
else
value
end
end
def facet_field_id facet_field
"facet-#{facet_field.key.parameterize}"
end
private
def facet_value_for_facet_item item
if item.respond_to? :value
item.value
else
item
end
end
end
| 1 | 8,686 | It's a little hard to tell from the diff, but as a result of this PR, the only non-deprecated helpers are: - `has_facet_values?` (probably not long for this world) - `render_facet_partials` (perhaps part of a future component) - `render_facet_limit` (possibly obsolete once components get traction) - `facet_field_in_params` (a little tricky to deprecate at the moment) - `facet_field_presenter` | projectblacklight-blacklight | rb |
@@ -44,8 +44,15 @@ PersonObject.prototype.description = function() {
PersonObject.prototype.toString = function() {
return this.name;
};
-Object.setPrototypeOf(PersonObject, Realm.Object);
-Object.setPrototypeOf(PersonObject.prototype, Realm.Object.prototype);
+
+// Object.setPrototypeOf doesn't work on JSC on Android. The code below achieves the same thing.
+//Object.setPrototypeOf(PersonObject, Realm.Object);
+//Object.setPrototypeOf(PersonObject.prototype, Realm.Object.prototype);
+
+PersonObject.__proto__ = Realm.Object.__proto__;
+PersonObject.prototype.__proto__ = Realm.Object.prototype.__proto__;
+
+
exports.PersonObject = PersonObject;
exports.PersonList = { | 1 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm 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.
//
////////////////////////////////////////////////////////////////////////////
'use strict';
const Realm = require('realm');
exports.TestObject = {
name: 'TestObject',
properties: {
doubleCol: 'double',
}
};
function PersonObject() {}
PersonObject.schema = {
name: 'PersonObject',
properties: {
name: 'string',
age: 'double',
married: {type: 'bool', default: false},
children: {type: 'list', objectType: 'PersonObject'},
parents: {type: 'linkingObjects', objectType: 'PersonObject', property: 'children'},
}
};
PersonObject.prototype.description = function() {
return this.name + ' ' + this.age;
};
PersonObject.prototype.toString = function() {
return this.name;
};
Object.setPrototypeOf(PersonObject, Realm.Object);
Object.setPrototypeOf(PersonObject.prototype, Realm.Object.prototype);
exports.PersonObject = PersonObject;
exports.PersonList = {
name: 'PersonList',
properties: {
list: {type: 'list', objectType: 'PersonObject'},
}
};
exports.BasicTypes = {
name: 'BasicTypesObject',
properties: {
boolCol: 'bool',
intCol: 'int',
floatCol: 'float',
doubleCol: 'double',
stringCol: 'string',
dateCol: 'date',
dataCol: 'data',
}
};
exports.NullableBasicTypes = {
name: 'NullableBasicTypesObject',
properties: {
boolCol: {type: 'bool', optional: true},
intCol: {type: 'int', optional: true},
floatCol: {type: 'float', optional: true},
doubleCol: {type: 'double', optional: true},
stringCol: {type: 'string', optional: true},
dateCol: {type: 'date', optional: true},
dataCol: {type: 'data', optional: true},
}
};
exports.IndexedTypes = {
name: 'IndexedTypesObject',
properties: {
boolCol: {type: 'bool', indexed: true},
intCol: {type: 'int', indexed: true},
stringCol: {type: 'string', indexed: true},
dateCol: {type: 'date', indexed: true},
}
};
exports.LinkTypes = {
name: 'LinkTypesObject',
properties: {
objectCol: 'TestObject',
objectCol1: {type: 'object', objectType: 'TestObject'},
arrayCol: {type: 'list', objectType: 'TestObject'},
}
};
exports.IntPrimary = {
name: 'IntPrimaryObject',
primaryKey: 'primaryCol',
properties: {
primaryCol: 'int',
valueCol: 'string',
}
};
exports.StringPrimary = {
name: 'StringPrimaryObject',
primaryKey: 'primaryCol',
properties: {
primaryCol: 'string',
valueCol: 'int',
}
};
exports.AllTypes = {
name: 'AllTypesObject',
primaryKey: 'primaryCol',
properties: {
primaryCol: 'string',
boolCol: 'bool',
intCol: 'int',
floatCol: 'float',
doubleCol: 'double',
stringCol: 'string',
dateCol: 'date',
dataCol: 'data',
objectCol: 'TestObject',
arrayCol: {type: 'list', objectType: 'TestObject'},
linkingObjectsCol: {type: 'linkingObjects', objectType: 'LinkToAllTypesObject', property: 'allTypesCol'},
}
};
exports.LinkToAllTypes = {
name: 'LinkToAllTypesObject',
properties: {
allTypesCol: 'AllTypesObject',
}
}
exports.DefaultValues = {
name: 'DefaultValuesObject',
properties: {
boolCol: {type: 'bool', default: true},
intCol: {type: 'int', default: -1},
floatCol: {type: 'float', default: -1.1},
doubleCol: {type: 'double', default: -1.11},
stringCol: {type: 'string', default: 'defaultString'},
dateCol: {type: 'date', default: new Date(1.111)},
dataCol: {type: 'data', default: new ArrayBuffer(1)},
objectCol: {type: 'TestObject', default: {doubleCol: 1}},
nullObjectCol: {type: 'TestObject', default: null},
arrayCol: {type: 'list', objectType: 'TestObject', default: [{doubleCol: 2}]},
}
};
exports.QueryObject = {
name: 'QueryObject',
properties: [
{name: 'bool1', type: 'bool'},
{name: 'bool2', type: 'bool'},
{name: 'int1', type: 'int'},
{name: 'int2', type: 'int'},
{name: 'float1', type: 'float'},
{name: 'float2', type: 'float'},
{name: 'double1', type: 'double'},
{name: 'double2', type: 'double'},
{name: 'string1', type: 'string'},
{name: 'string2', type: 'string'},
]
};
exports.NullQueryObject = {
name: 'NullQueryObject',
properties: [
{name: 'bool1', type: 'bool'},
{name: 'bool2', type: 'bool'},
{name: 'int1', type: 'int'},
{name: 'int2', type: 'int'},
{name: 'float1', type: 'float'},
{name: 'float2', type: 'float'},
{name: 'double1', type: 'double'},
{name: 'double2', type: 'double'},
{name: 'string1', type: 'string'},
{name: 'string2', type: 'string'},
]
};
exports.DateObject = {
name: 'Date',
properties: {
currentDate: 'date',
nullDate: { type: 'date', optional: true }
}
};
exports.LinkingObjectsObject = {
name: 'LinkingObjectsObject',
properties: {
value: 'int',
links: {type: 'list', objectType: 'LinkingObjectsObject'},
linkingObjects: {type: 'linkingObjects', objectType: 'LinkingObjectsObject', property: 'links'}
}
}
| 1 | 16,236 | The right-hand part shouldn't use `__proto__`. Should be just `PersonObject.__proto__ = Realm.Object`. | realm-realm-js | js |
@@ -233,6 +233,14 @@ func (m *taskManagerImpl) CreateTasks(request *CreateTasksRequest) (*CreateTasks
}
func (m *taskManagerImpl) GetTasks(request *GetTasksRequest) (*GetTasksResponse, error) {
+ if request.MinTaskID >= request.MaxTaskID {
+ panic(fmt.Sprintf(
+ "taskManagerImpl encountered MinTaskID >= MaxTaskID: %v vs %v",
+ request.MinTaskID,
+ request.MaxTaskID,
+ ))
+ }
+
internalResp, err := m.taskStore.GetTasks(request)
if err != nil {
return nil, err | 1 | // The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package persistence
import (
"fmt"
"time"
enumspb "go.temporal.io/api/enums/v1"
"go.temporal.io/api/serviceerror"
persistencespb "go.temporal.io/server/api/persistence/v1"
"go.temporal.io/server/common/persistence/serialization"
"go.temporal.io/server/common/primitives/timestamp"
)
const (
initialRangeID = 1 // Id of the first range of a new task queue
stickyTaskQueueTTL = 24 * time.Hour
)
type taskManagerImpl struct {
taskStore TaskStore
serializer serialization.Serializer
}
// NewTaskManager creates a new instance of TaskManager
func NewTaskManager(store TaskStore) TaskManager {
return &taskManagerImpl{
taskStore: store,
serializer: serialization.NewSerializer(),
}
}
func (m *taskManagerImpl) Close() {
m.taskStore.Close()
}
func (m *taskManagerImpl) GetName() string {
return m.taskStore.GetName()
}
func (m *taskManagerImpl) LeaseTaskQueue(request *LeaseTaskQueueRequest) (*LeaseTaskQueueResponse, error) {
if len(request.TaskQueue) == 0 {
return nil, serviceerror.NewUnavailable(fmt.Sprintf("LeaseTaskQueue requires non empty task queue"))
}
taskQueue, err := m.taskStore.GetTaskQueue(&InternalGetTaskQueueRequest{
NamespaceID: request.NamespaceID,
TaskQueue: request.TaskQueue,
TaskType: request.TaskType,
})
switch err.(type) {
case nil:
// If request.RangeID is > 0, we are trying to renew an existing lease on the task queue.
// If request.RangeID=0, we are trying to steal the task queue from its current owner.
if request.RangeID > 0 && request.RangeID != taskQueue.RangeID {
return nil, &ConditionFailedError{
Msg: fmt.Sprintf("LeaseTaskQueue: renew failed: taskQueue:%v, taskQueueType:%v, haveRangeID:%v, gotRangeID:%v",
request.TaskQueue, request.TaskType, request.RangeID, taskQueue.RangeID),
}
}
taskQueueInfo, err := m.serializer.TaskQueueInfoFromBlob(taskQueue.TaskQueueInfo)
if err != nil {
return nil, serviceerror.NewUnavailable(fmt.Sprintf("LeaseTaskQueue operation failed during serialization. TaskQueue: %v, TaskType: %v, Error: %v", request.TaskQueue, request.TaskType, err))
}
taskQueueInfo.LastUpdateTime = timestamp.TimeNowPtrUtc()
taskQueueInfoBlob, err := m.serializer.TaskQueueInfoToBlob(taskQueueInfo, enumspb.ENCODING_TYPE_PROTO3)
if err != nil {
return nil, err
}
err = m.taskStore.ExtendLease(&InternalExtendLeaseRequest{
NamespaceID: request.NamespaceID,
TaskQueue: request.TaskQueue,
TaskType: request.TaskType,
RangeID: taskQueue.RangeID,
TaskQueueInfo: taskQueueInfoBlob,
})
if err != nil {
return nil, err
}
return &LeaseTaskQueueResponse{
TaskQueueInfo: &PersistedTaskQueueInfo{
Data: taskQueueInfo,
RangeID: taskQueue.RangeID + 1,
},
}, nil
case *serviceerror.NotFound:
// First time task queue is used
taskQueueInfo := &persistencespb.TaskQueueInfo{
NamespaceId: request.NamespaceID,
Name: request.TaskQueue,
TaskType: request.TaskType,
Kind: request.TaskQueueKind,
AckLevel: 0,
ExpiryTime: nil,
LastUpdateTime: timestamp.TimeNowPtrUtc(),
}
taskQueueInfoBlob, err := m.serializer.TaskQueueInfoToBlob(taskQueueInfo, enumspb.ENCODING_TYPE_PROTO3)
if err != nil {
return nil, err
}
if err := m.taskStore.CreateTaskQueue(&InternalCreateTaskQueueRequest{
NamespaceID: request.NamespaceID,
TaskQueue: request.TaskQueue,
TaskType: request.TaskType,
RangeID: initialRangeID,
TaskQueueInfo: taskQueueInfoBlob,
}); err != nil {
return nil, err
}
// return newly created TaskQueueInfo
return &LeaseTaskQueueResponse{
TaskQueueInfo: &PersistedTaskQueueInfo{
Data: taskQueueInfo,
RangeID: initialRangeID,
},
}, nil
default:
// failed
return nil, err
}
}
func (m *taskManagerImpl) UpdateTaskQueue(request *UpdateTaskQueueRequest) (*UpdateTaskQueueResponse, error) {
taskQueueInfo := request.TaskQueueInfo
taskQueueInfo.LastUpdateTime = timestamp.TimeNowPtrUtc()
if taskQueueInfo.GetKind() == enumspb.TASK_QUEUE_KIND_STICKY {
taskQueueInfo.ExpiryTime = timestamp.TimePtr(time.Now().UTC().Add(stickyTaskQueueTTL))
}
taskQueueInfoBlob, err := m.serializer.TaskQueueInfoToBlob(taskQueueInfo, enumspb.ENCODING_TYPE_PROTO3)
if err != nil {
return nil, err
}
internalRequest := &InternalUpdateTaskQueueRequest{
NamespaceID: request.TaskQueueInfo.GetNamespaceId(),
TaskQueue: request.TaskQueueInfo.GetName(),
TaskType: request.TaskQueueInfo.GetTaskType(),
TaskQueueKind: request.TaskQueueInfo.GetKind(),
RangeID: request.RangeID,
ExpiryTime: taskQueueInfo.ExpiryTime,
TaskQueueInfo: taskQueueInfoBlob,
}
return m.taskStore.UpdateTaskQueue(internalRequest)
}
func (m *taskManagerImpl) ListTaskQueue(request *ListTaskQueueRequest) (*ListTaskQueueResponse, error) {
internalResp, err := m.taskStore.ListTaskQueue(request)
if err != nil {
return nil, err
}
taskQueues := make([]*PersistedTaskQueueInfo, len(internalResp.Items))
for i, item := range internalResp.Items {
tqi, err := m.serializer.TaskQueueInfoFromBlob(item.TaskQueue)
if err != nil {
return nil, err
}
taskQueues[i] = &PersistedTaskQueueInfo{
Data: tqi,
RangeID: item.RangeID,
}
}
return &ListTaskQueueResponse{
Items: taskQueues,
NextPageToken: internalResp.NextPageToken,
}, nil
}
func (m *taskManagerImpl) DeleteTaskQueue(request *DeleteTaskQueueRequest) error {
return m.taskStore.DeleteTaskQueue(request)
}
func (m *taskManagerImpl) CreateTasks(request *CreateTasksRequest) (*CreateTasksResponse, error) {
taskQueueInfo := request.TaskQueueInfo.Data
taskQueueInfo.LastUpdateTime = timestamp.TimeNowPtrUtc()
taskQueueInfoBlob, err := m.serializer.TaskQueueInfoToBlob(taskQueueInfo, enumspb.ENCODING_TYPE_PROTO3)
if err != nil {
return nil, err
}
tasks := make([]*InternalCreateTask, len(request.Tasks))
for i, task := range request.Tasks {
taskBlob, err := m.serializer.TaskInfoToBlob(task, enumspb.ENCODING_TYPE_PROTO3)
if err != nil {
return nil, serviceerror.NewUnavailable(fmt.Sprintf("CreateTasks operation failed during serialization. Error : %v", err))
}
tasks[i] = &InternalCreateTask{
TaskId: task.GetTaskId(),
ExpiryTime: task.Data.ExpiryTime,
Task: taskBlob,
}
}
internalRequest := &InternalCreateTasksRequest{
NamespaceID: request.TaskQueueInfo.Data.GetNamespaceId(),
TaskQueue: request.TaskQueueInfo.Data.GetName(),
TaskType: request.TaskQueueInfo.Data.GetTaskType(),
RangeID: request.TaskQueueInfo.RangeID,
TaskQueueInfo: taskQueueInfoBlob,
Tasks: tasks,
}
return m.taskStore.CreateTasks(internalRequest)
}
func (m *taskManagerImpl) GetTasks(request *GetTasksRequest) (*GetTasksResponse, error) {
internalResp, err := m.taskStore.GetTasks(request)
if err != nil {
return nil, err
}
tasks := make([]*persistencespb.AllocatedTaskInfo, len(internalResp.Tasks))
for i, taskBlob := range internalResp.Tasks {
task, err := m.serializer.TaskInfoFromBlob(taskBlob)
if err != nil {
return nil, serviceerror.NewUnavailable(fmt.Sprintf("GetTasks failed to deserialize task: %s", err.Error()))
}
tasks[i] = task
}
return &GetTasksResponse{
Tasks: tasks,
}, nil
}
func (m *taskManagerImpl) CompleteTask(request *CompleteTaskRequest) error {
return m.taskStore.CompleteTask(request)
}
func (m *taskManagerImpl) CompleteTasksLessThan(request *CompleteTasksLessThanRequest) (int, error) {
return m.taskStore.CompleteTasksLessThan(request)
}
| 1 | 13,553 | the == case might be legit, or not? If there is no task written since last read, but we trigger a new read, would the min == max? Or should the upper layer handle that case? | temporalio-temporal | go |
@@ -971,7 +971,7 @@ void* ponyint_pool_realloc_size(size_t old_size, size_t new_size, void* p)
new_p = pool_alloc_size(new_adj_size);
}
- memcpy(new_p, p, new_size);
+ memcpy(new_p, p, old_size);
if(old_index < POOL_COUNT)
ponyint_pool_free(old_index, p); | 1 | #define PONY_WANT_ATOMIC_DEFS
#include "pool.h"
#include "alloc.h"
#include "../ds/fun.h"
#include "../sched/cpu.h"
#include "ponyassert.h"
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <platform.h>
#include <pony/detail/atomics.h>
#ifdef USE_VALGRIND
#include <valgrind/valgrind.h>
#include <valgrind/helgrind.h>
#endif
/// Allocations this size and above are aligned on this size. This is needed
/// so that the pagemap for the heap is aligned.
#define POOL_ALIGN_INDEX (POOL_ALIGN_BITS - POOL_MIN_BITS)
#define POOL_ALIGN_MASK (POOL_ALIGN - 1)
/// When we mmap, pull at least this many bytes.
#ifdef PLATFORM_IS_ILP32
# define POOL_MMAP (16 * 1024 * 1024) // 16 MB
#else
# ifdef PLATFORM_IS_WINDOWS
# define POOL_MMAP (16 * 1024 * 1024) // 16 MB
# else
# define POOL_MMAP (128 * 1024 * 1024) // 128 MB
# endif
#endif
/// An item on a per-size thread-local free list.
typedef struct pool_item_t
{
struct pool_item_t* next;
} pool_item_t;
/// A per-size thread-local free list header.
typedef struct pool_local_t
{
pool_item_t* pool;
size_t length;
char* start;
char* end;
} pool_local_t;
/// A free list on a per-size global list of free lists.
typedef struct pool_central_t
{
pool_item_t* next;
uintptr_t length;
struct pool_central_t* central;
} pool_central_t;
PONY_ABA_PROTECTED_PTR_DECLARE(pool_central_t)
/// A per-size global list of free lists header.
typedef struct pool_global_t
{
size_t size;
size_t count;
#ifdef PLATFORM_IS_X86
PONY_ATOMIC_ABA_PROTECTED_PTR(pool_central_t) central;
#else
PONY_ATOMIC(pool_central_t*) central;
#endif
} pool_global_t;
/// An item on an either thread-local or global list of free blocks.
typedef struct pool_block_t
{
struct pool_block_t* prev;
union
{
struct pool_block_t* next;
PONY_ATOMIC(struct pool_block_t*) global;
};
size_t size;
PONY_ATOMIC(bool) acquired;
} pool_block_t;
/// A thread local list of free blocks header.
typedef struct pool_block_header_t
{
pool_block_t* head;
size_t total_size;
size_t largest_size;
} pool_block_header_t;
static pool_global_t pool_global[POOL_COUNT] =
{
{POOL_MIN << 0, POOL_MAX / (POOL_MIN << 0), {{NULL, 0}}},
{POOL_MIN << 1, POOL_MAX / (POOL_MIN << 1), {{NULL, 0}}},
{POOL_MIN << 2, POOL_MAX / (POOL_MIN << 2), {{NULL, 0}}},
{POOL_MIN << 3, POOL_MAX / (POOL_MIN << 3), {{NULL, 0}}},
{POOL_MIN << 4, POOL_MAX / (POOL_MIN << 4), {{NULL, 0}}},
{POOL_MIN << 5, POOL_MAX / (POOL_MIN << 5), {{NULL, 0}}},
{POOL_MIN << 6, POOL_MAX / (POOL_MIN << 6), {{NULL, 0}}},
{POOL_MIN << 7, POOL_MAX / (POOL_MIN << 7), {{NULL, 0}}},
{POOL_MIN << 8, POOL_MAX / (POOL_MIN << 8), {{NULL, 0}}},
{POOL_MIN << 9, POOL_MAX / (POOL_MIN << 9), {{NULL, 0}}},
{POOL_MIN << 10, POOL_MAX / (POOL_MIN << 10), {{NULL, 0}}},
{POOL_MIN << 11, POOL_MAX / (POOL_MIN << 11), {{NULL, 0}}},
{POOL_MIN << 12, POOL_MAX / (POOL_MIN << 12), {{NULL, 0}}},
{POOL_MIN << 13, POOL_MAX / (POOL_MIN << 13), {{NULL, 0}}},
{POOL_MIN << 14, POOL_MAX / (POOL_MIN << 14), {{NULL, 0}}},
{POOL_MIN << 15, POOL_MAX / (POOL_MIN << 15), {{NULL, 0}}},
};
static pool_block_t pool_block_global;
static PONY_ATOMIC(size_t) in_pool_block_global;
static __pony_thread_local pool_local_t pool_local[POOL_COUNT];
static __pony_thread_local pool_block_header_t pool_block_header;
#ifdef USE_POOLTRACK
#include "../ds/stack.h"
#include "../sched/cpu.h"
#define POOL_TRACK_FREE ((void*)0)
#define POOL_TRACK_ALLOC ((void*)1)
#define POOL_TRACK_PUSH ((void*)2)
#define POOL_TRACK_PULL ((void*)3)
#define POOL_TRACK_PUSH_LIST ((void*)4)
#define POOL_TRACK_PULL_LIST ((void*)5)
#define POOL_TRACK_MAX_THREADS 64
DECLARE_STACK(pool_track, pool_track_t, void);
DEFINE_STACK(pool_track, pool_track_t, void);
typedef struct
{
bool init;
bool internal;
int thread_id;
pool_track_t* stack;
} pool_track_info_t;
static __pony_thread_local pool_track_info_t track;
static PONY_ATOMIC(int) track_global_thread_id;
static pool_track_info_t* track_global_info[POOL_TRACK_MAX_THREADS];
static void pool_event_print(int thread, void* op, size_t event, size_t tsc,
void* addr, size_t size)
{
if(op == POOL_TRACK_ALLOC)
printf("%d ALLOC "__zu" ("__zu"): %p, "__zu"\n",
thread, event, tsc, addr, size);
else if(op == POOL_TRACK_FREE)
printf("%d FREE "__zu" ("__zu"): %p, "__zu"\n",
thread, event, tsc, addr, size);
else if(op == POOL_TRACK_PUSH)
printf("%d PUSH "__zu" ("__zu"): %p, "__zu"\n",
thread, event, tsc, addr, size);
else if(op == POOL_TRACK_PULL)
printf("%d PULL "__zu" ("__zu"): %p, "__zu"\n",
thread, event, tsc, addr, size);
else if(op == POOL_TRACK_PUSH_LIST)
printf("%d PUSH LIST "__zu" ("__zu"): "__zu", "__zu"\n",
thread, event, tsc, (size_t)addr, size);
else if(op == POOL_TRACK_PULL_LIST)
printf("%d PULL LIST "__zu" ("__zu"): "__zu", "__zu"\n",
thread, event, tsc, (size_t)addr, size);
}
static void pool_track(int thread_filter, void* addr_filter, int op_filter,
size_t event_filter)
{
for(int i = 0; i < POOL_TRACK_MAX_THREADS; i++)
{
if((thread_filter != -1) && (thread_filter != i))
continue;
pool_track_info_t* track = track_global_info[i];
if(track == NULL)
continue;
Stack* t = (Stack*)track->stack;
size_t event = 0;
int state = 0;
void* op;
void* addr;
size_t size;
size_t tsc;
while(t != NULL)
{
for(int j = t->index - 1; j >= 0; j--)
{
switch(state)
{
case 0:
tsc = (size_t)t->data[j];
state = 1;
break;
case 1:
size = (size_t)t->data[j];
state = 2;
break;
case 2:
addr = t->data[j];
state = 3;
break;
case 3:
{
bool print = true;
op = t->data[j];
state = 0;
if((op_filter != -1) && (op_filter != (int)op))
print = false;
if((event_filter != (size_t)-1) && (event_filter != event))
print = false;
if((addr_filter != NULL) &&
((addr > addr_filter) || ((addr + size) <= addr_filter)))
{
print = false;
}
if(print)
{
pool_event_print(i, op, event, tsc, addr, size);
if(event_filter != (size_t)-1)
return;
}
event++;
break;
}
default: {}
}
}
t = t->prev;
}
}
}
static void track_init()
{
if(track.init)
return;
track.init = true;
track.thread_id = atomic_fetch_add_explicit(&track_global_thread_id, 1,
memory_order_relaxed);
track_global_info[track.thread_id] = &track;
// Force the symbol to be linked.
pool_track(track.thread_id, NULL, -1, 0);
}
static void track_alloc(void* p, size_t size)
{
track_init();
if(track.internal)
return;
track.internal = true;
track.stack = pool_track_push(track.stack, POOL_TRACK_ALLOC);
track.stack = pool_track_push(track.stack, p);
track.stack = pool_track_push(track.stack, (void*)size);
track.stack = pool_track_push(track.stack, (void*)ponyint_cpu_tick());
track.internal = false;
}
static void track_free(void* p, size_t size)
{
track_init();
pony_assert(!track.internal);
track.internal = true;
track.stack = pool_track_push(track.stack, POOL_TRACK_FREE);
track.stack = pool_track_push(track.stack, p);
track.stack = pool_track_push(track.stack, (void*)size);
track.stack = pool_track_push(track.stack, (void*)ponyint_cpu_tick());
track.internal = false;
}
static void track_push(pool_item_t* p, size_t length, size_t size)
{
track_init();
pony_assert(!track.internal);
track.internal = true;
uint64_t tsc = ponyint_cpu_tick();
track.stack = pool_track_push(track.stack, POOL_TRACK_PUSH_LIST);
track.stack = pool_track_push(track.stack, (void*)length);
track.stack = pool_track_push(track.stack, (void*)size);
track.stack = pool_track_push(track.stack, (void*)tsc);
while(p != NULL)
{
track.stack = pool_track_push(track.stack, POOL_TRACK_PUSH);
track.stack = pool_track_push(track.stack, p);
track.stack = pool_track_push(track.stack, (void*)size);
track.stack = pool_track_push(track.stack, (void*)tsc);
p = p->next;
}
track.internal = false;
}
static void track_pull(pool_item_t* p, size_t length, size_t size)
{
track_init();
pony_assert(!track.internal);
track.internal = true;
uint64_t tsc = ponyint_cpu_tick();
track.stack = pool_track_push(track.stack, POOL_TRACK_PULL_LIST);
track.stack = pool_track_push(track.stack, (void*)length);
track.stack = pool_track_push(track.stack, (void*)size);
track.stack = pool_track_push(track.stack, (void*)tsc);
while(p != NULL)
{
track.stack = pool_track_push(track.stack, POOL_TRACK_PULL);
track.stack = pool_track_push(track.stack, p);
track.stack = pool_track_push(track.stack, (void*)size);
track.stack = pool_track_push(track.stack, (void*)tsc);
p = p->next;
}
track.internal = false;
}
#define TRACK_ALLOC(PTR, SIZE) track_alloc(PTR, SIZE)
#define TRACK_FREE(PTR, SIZE) track_free(PTR, SIZE)
#define TRACK_PUSH(PTR, LEN, SIZE) track_push(PTR, LEN, SIZE)
#define TRACK_PULL(PTR, LEN, SIZE) track_pull(PTR, LEN, SIZE)
#define TRACK_EXTERNAL() (!track.internal)
#else
#define TRACK_ALLOC(PTR, SIZE)
#define TRACK_FREE(PTR, SIZE)
#define TRACK_PUSH(PTR, LEN, SIZE)
#define TRACK_PULL(PTR, LEN, SIZE)
#define TRACK_EXTERNAL() (true)
#endif
static void pool_block_remove(pool_block_t* block)
{
if(block->prev != NULL)
block->prev->next = block->next;
else
pool_block_header.head = block->next;
if(block->next != NULL)
block->next->prev = block->prev;
}
static void pool_block_insert(pool_block_t* block)
{
pool_block_t* next = pool_block_header.head;
pool_block_t* prev = NULL;
while(next != NULL)
{
if(block->size <= next->size)
break;
prev = next;
next = next->next;
}
block->prev = prev;
block->next = next;
if(prev != NULL)
prev->next = block;
else
pool_block_header.head = block;
if(next != NULL)
next->prev = block;
}
static void pool_block_push(pool_block_t* block)
{
atomic_store_explicit(&block->acquired, false, memory_order_relaxed);
atomic_fetch_add_explicit(&in_pool_block_global, 1, memory_order_acquire);
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_AFTER(&in_pool_block_global);
#endif
while(true)
{
pool_block_t* pos = atomic_load_explicit(&pool_block_global.global,
memory_order_acquire);
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_AFTER(&pool_block_global.global);
#endif
// Find an insertion position. The list is sorted and stays sorted after an
// insertion.
pool_block_t* prev = &pool_block_global;
while((pos != NULL) && (block->size > pos->size))
{
prev = pos;
pos = atomic_load_explicit(&pos->global, memory_order_acquire);
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_AFTER(&pos->global);
#endif
}
if(atomic_exchange_explicit(&prev->acquired, true, memory_order_acquire))
continue;
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_AFTER(&prev->acquired);
#endif
pool_block_t* check_pos = atomic_load_explicit(&prev->global,
memory_order_relaxed);
if(pos != check_pos)
{
atomic_store_explicit(&prev->acquired, false, memory_order_relaxed);
continue;
}
atomic_store_explicit(&block->global, pos, memory_order_relaxed);
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_BEFORE(&prev->global);
#endif
atomic_store_explicit(&prev->global, block, memory_order_release);
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_BEFORE(&prev->acquired);
#endif
atomic_store_explicit(&prev->acquired, false, memory_order_release);
break;
}
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_BEFORE(&in_pool_block_global);
#endif
atomic_fetch_sub_explicit(&in_pool_block_global, 1, memory_order_release);
}
static pool_block_t* pool_block_pull( size_t size)
{
pool_block_t* block = atomic_load_explicit(&pool_block_global.global,
memory_order_relaxed);
if(block == NULL)
return NULL;
atomic_fetch_add_explicit(&in_pool_block_global, 1, memory_order_acquire);
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_AFTER(&in_pool_block_global);
#endif
while(true)
{
block = atomic_load_explicit(&pool_block_global.global,
memory_order_relaxed);
if(block == NULL)
{
atomic_fetch_sub_explicit(&in_pool_block_global, 1, memory_order_relaxed);
return NULL;
}
atomic_thread_fence(memory_order_acquire);
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_AFTER(&pool_block_global.global);
#endif
pool_block_t* prev = &pool_block_global;
// Find a big enough block. The list is sorted.
while((block != NULL) && (size > block->size))
{
prev = block;
block = atomic_load_explicit(&block->global, memory_order_acquire);
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_AFTER(&block->global);
#endif
}
// No suitable block.
if(block == NULL)
{
atomic_fetch_sub_explicit(&in_pool_block_global, 1, memory_order_relaxed);
return NULL;
}
if(atomic_exchange_explicit(&prev->acquired, true, memory_order_acquire))
continue;
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_AFTER(&prev->acquired);
#endif
pool_block_t* check_block = atomic_load_explicit(&prev->global,
memory_order_relaxed);
if((block != check_block) ||
atomic_exchange_explicit(&block->acquired, true, memory_order_relaxed))
{
atomic_store_explicit(&prev->acquired, false, memory_order_relaxed);
continue;
}
atomic_thread_fence(memory_order_acquire);
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_AFTER(&block->acquired);
#endif
pool_block_t* next = atomic_load_explicit(&block->global,
memory_order_relaxed);
atomic_store_explicit(&prev->global, next, memory_order_relaxed);
// Don't release block.
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_BEFORE(&prev->acquired);
#endif
atomic_store_explicit(&prev->acquired, false, memory_order_release);
break;
}
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_BEFORE(&in_pool_block_global);
#endif
atomic_fetch_sub_explicit(&in_pool_block_global, 1, memory_order_release);
// We can't modify block until we're sure no other thread will try to read
// from it (e.g. to check if it can be popped from the global list). To do
// this, we wait until nobody is trying to either push or pull.
while(atomic_load_explicit(&in_pool_block_global, memory_order_relaxed) != 0)
ponyint_cpu_relax();
atomic_thread_fence(memory_order_acquire);
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_AFTER(&in_pool_block_global);
#endif
pony_assert(size <= block->size);
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_BEFORE_FORGET_ALL(&block->global);
ANNOTATE_HAPPENS_BEFORE_FORGET_ALL(&block->acquired);
#endif
return block;
}
static void* pool_block_get(size_t size)
{
if(pool_block_header.largest_size >= size)
{
pool_block_t* block = pool_block_header.head;
while(block != NULL)
{
if(block->size > size)
{
// Use size bytes from the end of the block. This allows us to keep the
// block info inside the block instead of using another data structure.
size_t rem = block->size - size;
block->size = rem;
pool_block_header.total_size -= size;
if((block->prev != NULL) && (block->prev->size > block->size))
{
// If we are now smaller than the previous block, move us forward in
// the list.
if(block->next == NULL)
pool_block_header.largest_size = block->prev->size;
pool_block_remove(block);
pool_block_insert(block);
} else if(block->next == NULL) {
pool_block_header.largest_size = rem;
}
return (char*)block + rem;
} else if(block->size == size) {
if(block->next == NULL)
{
pool_block_header.largest_size =
(block->prev == NULL) ? 0 : block->prev->size;
}
// Remove the block from the list.
pool_block_remove(block);
// Return the block pointer itself.
pool_block_header.total_size -= size;
return block;
}
block = block->next;
}
// If we didn't find any suitable block, something has gone really wrong.
pony_assert(false);
}
pool_block_t* block = pool_block_pull(size);
if(block == NULL)
return NULL;
if(size == block->size)
return block;
size_t rem = block->size - size;
block->size = rem;
pool_block_insert(block);
pool_block_header.total_size += rem;
if(pool_block_header.largest_size < rem)
pool_block_header.largest_size = rem;
return (char*)block + rem;
}
static void* pool_alloc_pages(size_t size)
{
void* p = pool_block_get(size);
if(p != NULL)
return p;
// We have no free blocks big enough.
if(size >= POOL_MMAP)
return ponyint_virt_alloc(size);
pool_block_t* block = (pool_block_t*)ponyint_virt_alloc(POOL_MMAP);
size_t rem = POOL_MMAP - size;
block->size = rem;
block->next = NULL;
block->prev = NULL;
pool_block_insert(block);
pool_block_header.total_size += rem;
if(pool_block_header.largest_size < rem)
pool_block_header.largest_size = rem;
return (char*)block + rem;
}
static void pool_free_pages(void* p, size_t size)
{
if(pool_block_header.total_size >= POOL_MMAP)
{
// TODO: ???
}
pool_block_t* block = (pool_block_t*)p;
block->prev = NULL;
block->next = NULL;
block->size = size;
pool_block_insert(block);
pool_block_header.total_size += size;
if(pool_block_header.largest_size < size)
pool_block_header.largest_size = size;
}
static void pool_push(pool_local_t* thread, pool_global_t* global)
{
pool_central_t* p = (pool_central_t*)thread->pool;
p->length = thread->length;
thread->pool = NULL;
thread->length = 0;
pony_assert((p->length > 0) && (p->length <= global->count));
TRACK_PUSH((pool_item_t*)p, p->length, global->size);
pool_central_t* top;
#ifdef PLATFORM_IS_X86
PONY_ABA_PROTECTED_PTR(pool_central_t) cmp;
PONY_ABA_PROTECTED_PTR(pool_central_t) xchg;
cmp.object = global->central.object;
cmp.counter = global->central.counter;
xchg.object = p;
#else
top = atomic_load_explicit(&global->central, memory_order_relaxed);
#endif
do
{
#ifdef PLATFORM_IS_X86
top = cmp.object;
xchg.counter = cmp.counter + 1;
#endif
p->central = top;
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_BEFORE(&global->central);
#endif
}
#ifdef PLATFORM_IS_X86
while(!bigatomic_compare_exchange_weak_explicit(&global->central, &cmp,
xchg, memory_order_release, memory_order_relaxed));
#else
while(!atomic_compare_exchange_weak_explicit(&global->central, &top, p,
memory_order_release, memory_order_relaxed));
#endif
}
static pool_item_t* pool_pull(pool_local_t* thread, pool_global_t* global)
{
pool_central_t* top;
#ifdef PLATFORM_IS_X86
PONY_ABA_PROTECTED_PTR(pool_central_t) cmp;
PONY_ABA_PROTECTED_PTR(pool_central_t) xchg;
cmp.object = global->central.object;
cmp.counter = global->central.counter;
#else
top = atomic_load_explicit(&global->central, memory_order_relaxed);
#endif
pool_central_t* next;
do
{
#ifdef PLATFORM_IS_X86
top = cmp.object;
#endif
if(top == NULL)
return NULL;
atomic_thread_fence(memory_order_acquire);
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_AFTER(&global->central);
#endif
next = top->central;
#ifdef PLATFORM_IS_X86
xchg.object = next;
xchg.counter = cmp.counter + 1;
#endif
}
#ifdef PLATFORM_IS_X86
while(!bigatomic_compare_exchange_weak_explicit(&global->central, &cmp,
xchg, memory_order_acquire, memory_order_relaxed));
#else
while(!atomic_compare_exchange_weak_explicit(&global->central, &top, next,
memory_order_acquire, memory_order_relaxed));
#endif
// We need to synchronise twice on global->central to make sure we see every
// previous write to the memory we're going to use before we use it.
#ifdef USE_VALGRIND
ANNOTATE_HAPPENS_AFTER(&global->central);
#endif
pool_item_t* p = (pool_item_t*)top;
pony_assert((top->length > 0) && (top->length <= global->count));
TRACK_PULL(p, top->length, global->size);
thread->pool = p->next;
thread->length = top->length - 1;
return p;
}
static void* pool_get(pool_local_t* pool, size_t index)
{
// Try per-size thread-local free list first.
pool_local_t* thread = &pool[index];
pool_global_t* global = &pool_global[index];
pool_item_t* p = thread->pool;
if(p != NULL)
{
thread->pool = p->next;
thread->length--;
return p;
}
if(TRACK_EXTERNAL())
{
// Try to get a new free list from the per-size global list of free lists.
p = pool_pull(thread, global);
if(p != NULL)
return p;
}
if(global->size < POOL_ALIGN)
{
// Check our per-size thread-local free block.
if(thread->start < thread->end)
{
void* p = thread->start;
thread->start += global->size;
return p;
}
// Use the pool allocator to get a block POOL_ALIGN bytes in size
// and treat it as a free block.
char* mem = (char*)pool_get(pool, POOL_ALIGN_INDEX);
thread->start = mem + global->size;
thread->end = mem + POOL_ALIGN;
return mem;
}
// Pull size bytes from the list of free blocks. Don't use a size-specific
// free block.
return pool_alloc_pages(global->size);
}
void* ponyint_pool_alloc(size_t index)
{
#ifdef USE_VALGRIND
VALGRIND_DISABLE_ERROR_REPORTING;
#endif
pool_local_t* pool = pool_local;
void* p = pool_get(pool, index);
TRACK_ALLOC(p, POOL_MIN << index);
#ifdef USE_VALGRIND
VALGRIND_ENABLE_ERROR_REPORTING;
VALGRIND_HG_CLEAN_MEMORY(p, ponyint_pool_size(index));
VALGRIND_MALLOCLIKE_BLOCK(p, ponyint_pool_size(index), 0, 0);
#endif
return p;
}
void ponyint_pool_free(size_t index, void* p)
{
#ifdef USE_VALGRIND
VALGRIND_HG_CLEAN_MEMORY(p, ponyint_pool_size(index));
VALGRIND_DISABLE_ERROR_REPORTING;
#endif
pony_assert(index < POOL_COUNT);
TRACK_FREE(p, POOL_MIN << index);
pool_local_t* thread = &pool_local[index];
pool_global_t* global = &pool_global[index];
if(thread->length == global->count)
pool_push(thread, global);
pony_assert(thread->length < global->count);
pool_item_t* lp = (pool_item_t*)p;
lp->next = thread->pool;
thread->pool = lp;
thread->length++;
#ifdef USE_VALGRIND
VALGRIND_ENABLE_ERROR_REPORTING;
VALGRIND_FREELIKE_BLOCK(p, 0);
#endif
}
static void* pool_alloc_size(size_t size)
{
#ifdef USE_VALGRIND
VALGRIND_DISABLE_ERROR_REPORTING;
#endif
void* p = pool_alloc_pages(size);
TRACK_ALLOC(p, size);
#ifdef USE_VALGRIND
VALGRIND_ENABLE_ERROR_REPORTING;
VALGRIND_HG_CLEAN_MEMORY(p, size);
VALGRIND_MALLOCLIKE_BLOCK(p, size, 0, 0);
#endif
return p;
}
void* ponyint_pool_alloc_size(size_t size)
{
size_t index = ponyint_pool_index(size);
if(index < POOL_COUNT)
return ponyint_pool_alloc(index);
size = ponyint_pool_adjust_size(size);
void* p = pool_alloc_size(size);
return p;
}
static void pool_free_size(size_t size, void* p)
{
#ifdef USE_VALGRIND
VALGRIND_HG_CLEAN_MEMORY(p, size);
VALGRIND_DISABLE_ERROR_REPORTING;
#endif
TRACK_FREE(p, size);
pool_free_pages(p, size);
#ifdef USE_VALGRIND
VALGRIND_ENABLE_ERROR_REPORTING;
VALGRIND_FREELIKE_BLOCK(p, 0);
#endif
}
void ponyint_pool_free_size(size_t size, void* p)
{
size_t index = ponyint_pool_index(size);
if(index < POOL_COUNT)
return ponyint_pool_free(index, p);
size = ponyint_pool_adjust_size(size);
pool_free_size(size, p);
}
void* ponyint_pool_realloc_size(size_t old_size, size_t new_size, void* p)
{
// Can only reuse the old pointer if the old index/adjusted size is equal to
// the new one, not greater.
if(p == NULL)
return ponyint_pool_alloc_size(new_size);
size_t old_index = ponyint_pool_index(old_size);
size_t new_index = ponyint_pool_index(new_size);
size_t old_adj_size = 0;
void* new_p;
if(new_index < POOL_COUNT)
{
if(old_index == new_index)
return p;
new_p = ponyint_pool_alloc(new_index);
} else {
size_t new_adj_size = ponyint_pool_adjust_size(new_size);
if(old_index >= POOL_COUNT)
{
old_adj_size = ponyint_pool_adjust_size(old_size);
if(old_adj_size == new_adj_size)
return p;
}
new_p = pool_alloc_size(new_adj_size);
}
memcpy(new_p, p, new_size);
if(old_index < POOL_COUNT)
ponyint_pool_free(old_index, p);
else
pool_free_size(old_adj_size, p);
return new_p;
}
void ponyint_pool_thread_cleanup()
{
for(size_t index = 0; index < POOL_COUNT; index++)
{
pool_local_t* thread = &pool_local[index];
pool_global_t* global = &pool_global[index];
while(thread->start < thread->end)
{
if(thread->length == global->count)
pool_push(thread, global);
pool_item_t* item = (pool_item_t*)thread->start;
thread->start += global->size;
item->next = thread->pool;
thread->pool = item;
thread->length++;
}
if(thread->length > 0)
pool_push(thread, global);
}
pool_block_t* block = pool_block_header.head;
while(block != NULL)
{
pool_block_t* next = block->next;
pool_block_remove(block);
pool_block_push(block);
block = next;
}
pool_block_header.total_size = 0;
pool_block_header.largest_size = 0;
}
size_t ponyint_pool_index(size_t size)
{
#ifdef PLATFORM_IS_ILP32
#define BITS (32 - POOL_MIN_BITS)
#else
#define BITS (64 - POOL_MIN_BITS)
#endif
// The condition is in that order for better branch prediction: non-zero pool
// indices are more likely than zero pool indices.
if(size > POOL_MIN)
return (size_t)BITS - __pony_clzl(size) - (!(size & (size - 1)));
return 0;
}
size_t ponyint_pool_size(size_t index)
{
return (size_t)1 << (POOL_MIN_BITS + index);
}
size_t ponyint_pool_adjust_size(size_t size)
{
if((size & POOL_ALIGN_MASK) != 0)
size = (size & ~POOL_ALIGN_MASK) + POOL_ALIGN;
return size;
}
| 1 | 11,097 | Good catch! But is it guaranteed that `old_size < new_size` here? If not, wouldn't we want to take `min(old_size, new_size)` as the copy length? | ponylang-ponyc | c |
@@ -109,6 +109,7 @@ namespace pwiz.Skyline.ToolsUI
return OverwriteOrInParallel(_parent, toolCollectionName, toolCollectionVersion, reportList, foundVersion, newCollectionName);
}
+ // ReSharper disable once MemberHidesStaticFromOuterClass
public string InstallProgram(ProgramPathContainer programPathContainer,
ICollection<ToolPackage> packages,
string pathToInstallScript) | 1 | /*
* Original author: Daniel Broudy <daniel.broudy .at. gmail.com>,
* MacCoss Lab, Department of Genome Sciences, UW
*
* Copyright 2013 University of Washington - Seattle, WA
*
* 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.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows.Forms;
using Newtonsoft.Json;
using pwiz.Skyline.Alerts;
using pwiz.Skyline.Controls;
using pwiz.Skyline.Model.Databinding;
using pwiz.Skyline.Model.DocSettings;
using pwiz.Skyline.Model.Tools;
using pwiz.Skyline.Properties;
using pwiz.Skyline.Util.Extensions;
namespace pwiz.Skyline.ToolsUI
{
public static class ToolInstallUI
{
public delegate string InstallProgram(ProgramPathContainer pathContainer,
ICollection<ToolPackage> toolPackages,
string pathToPackageInstallScrip);
public static void InstallZipFromFile(Control parent, InstallProgram install)
{
using (var dlg = new OpenFileDialog
{
Filter = TextUtil.FileDialogFiltersAll(TextUtil.FileDialogFilter(
Resources.ConfigureToolsDlg_AddFromFile_Zip_Files, ToolDescription.EXT_INSTALL)),
Multiselect = false
})
{
if (dlg.ShowDialog(parent) == DialogResult.OK)
InstallZipTool(parent, dlg.FileName, install);
}
}
public static void InstallZipFromWeb(Control parent, InstallProgram install)
{
try
{
IList<ToolStoreItem> toolStoreItems = null;
using (var dlg = new LongWaitDlg { Message = Resources.ConfigureToolsDlg_AddFromWeb_Contacting_the_server })
{
dlg.PerformWork(parent, 1000, () =>
{
toolStoreItems = ToolStoreUtil.ToolStoreClient.GetToolStoreItems();
});
}
if (toolStoreItems == null || toolStoreItems.Count == 0)
{
MessageDlg.Show(parent, Resources.ConfigureToolsDlg_AddFromWeb_Unknown_error_connecting_to_the_tool_store);
}
using (var dlg = new ToolStoreDlg(ToolStoreUtil.ToolStoreClient, toolStoreItems))
{
if (dlg.ShowDialog(parent) == DialogResult.OK)
InstallZipTool(parent, dlg.DownloadPath, install);
}
}
catch (TargetInvocationException x)
{
if (x.InnerException is ToolExecutionException || x.InnerException is WebException)
MessageDlg.Show(parent, String.Format(Resources.ConfigureToolsDlg_GetZipFromWeb_Error_connecting_to_the_Tool_Store___0_, x.Message));
else if (x.InnerException is JsonReaderException)
MessageDlg.Show(parent, Resources.ToolInstallUI_InstallZipFromWeb_The_server_returned_an_invalid_response__It_might_be_down_for_maintenance__Please_check_the_Tool_Store_on_the_skyline_ms_website_);
else
throw;
}
}
public class InstallZipToolHelper : IUnpackZipToolSupport
{
private readonly Control _parent;
public InstallZipToolHelper(Control parent, InstallProgram installProgram)
{
_parent = parent;
_installProgram = installProgram;
}
private InstallProgram _installProgram { get; set; }
public bool? ShouldOverwrite(string toolCollectionName,
string toolCollectionVersion,
List<ReportOrViewSpec> reportList,
string foundVersion,
string newCollectionName)
{
return OverwriteOrInParallel(_parent, toolCollectionName, toolCollectionVersion, reportList, foundVersion, newCollectionName);
}
public string InstallProgram(ProgramPathContainer programPathContainer,
ICollection<ToolPackage> packages,
string pathToInstallScript)
{
return _installProgram(programPathContainer, packages, pathToInstallScript);
}
public bool? ShouldOverwriteAnnotations(List<AnnotationDef> annotations)
{
return OverwriteAnnotations(_parent, annotations);
}
}
/// <summary>
/// Copy a zip file's contents to the tools folder and loop through its .properties
/// files adding the tools to the tools menu.
/// </summary>
/// <param name="parent">Parent window for alerts and forms</param>
/// <param name="fullpath">The full path to the zipped folder containing the tools</param>
/// <param name="install">Installation function</param>
public static void InstallZipTool(Control parent, string fullpath, InstallProgram install)
{
ToolInstaller.UnzipToolReturnAccumulator result = null;
var toolListStart = ToolList.CopyTools(Settings.Default.ToolList);
Exception xFailure = null;
try
{
result = ToolInstaller.UnpackZipTool(fullpath, new InstallZipToolHelper(parent, install));
}
catch (ToolExecutionException x)
{
MessageDlg.ShowException(parent, x);
}
catch (Exception x)
{
xFailure = x;
}
if (xFailure != null)
{
MessageDlg.ShowWithException(parent, TextUtil.LineSeparate(String.Format(Resources.ConfigureToolsDlg_UnpackZipTool_Failed_attempting_to_extract_the_tool_from__0_, Path.GetFileName(fullpath)), xFailure.Message), xFailure);
}
if (result != null)
{
foreach (var message in result.MessagesThrown)
{
MessageDlg.Show(parent, message);
}
}
else
{
// If result is Null, then we want to discard changes made to the ToolsList
Settings.Default.ToolList = toolListStart;
}
}
public enum RelativeVersion
{
upgrade,
reinstall,
olderversion,
unknown
}
public static bool? OverwriteOrInParallel(Control parent,
string toolCollectionName,
string toolCollectionVersion,
List<ReportOrViewSpec> reportList,
string foundVersion,
string newCollectionName)
{
string message;
string buttonText;
if (toolCollectionName != null)
{
RelativeVersion relativeVersion = DetermineRelativeVersion(toolCollectionVersion, foundVersion);
string toolMessage;
switch (relativeVersion)
{
case RelativeVersion.upgrade:
toolMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_currently_installed_, String.Empty,
String.Format(Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_upgrade_to__0__or_install_in_parallel_, foundVersion));
buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Upgrade;
break;
case RelativeVersion.olderversion:
toolMessage =
TextUtil.LineSeparate(
String.Format(Resources.ConfigureToolsDlg_OverwriteOrInParallel_This_is_an_older_installation_v_0__of_the_tool__1_, foundVersion, @"{0}"),
String.Empty,
String.Format(Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_with_the_older_version__0__or_install_in_parallel_,
foundVersion));
buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite;
break;
case RelativeVersion.reinstall:
toolMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_already_installed_,
String.Empty,
Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_reinstall_or_install_in_parallel_);
buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Reinstall;
break;
default:
toolMessage =
TextUtil.LineSeparate(
Resources.ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_in_conflict_with_the_new_installation,
String.Empty,
Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_or_install_in_parallel_);
buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite; // Or update?
break;
}
message = String.Format(toolMessage, toolCollectionName);
}
else //Warn about overwritng report.
{
List<string> reportTitles = reportList.Select(sp => sp.GetKey()).ToList();
string reportMultiMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_This_installation_would_modify_the_following_reports, String.Empty,
@"{0}", String.Empty);
string reportSingleMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_This_installation_would_modify_the_report_titled__0_, String.Empty);
string reportMessage = reportList.Count == 1 ? reportSingleMessage : reportMultiMessage;
string question = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_or_install_in_parallel_;
buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite;
string reportMessageFormat = TextUtil.LineSeparate(reportMessage, question);
message = String.Format(reportMessageFormat, TextUtil.LineSeparate(reportTitles));
}
DialogResult result = MultiButtonMsgDlg.Show(
parent, message, buttonText, Resources.ConfigureToolsDlg_OverwriteOrInParallel_In_Parallel, true);
switch (result)
{
case DialogResult.Cancel:
return null;
case DialogResult.Yes:
return true;
case DialogResult.No:
return false;
}
return false;
}
public static RelativeVersion DetermineRelativeVersion(string versionToCompare, string foundVersion)
{
if (!String.IsNullOrEmpty(foundVersion) && !String.IsNullOrEmpty(versionToCompare))
{
Version current = new Version(versionToCompare);
Version found = new Version(foundVersion);
if (current > found) //Installing an olderversion.
{
return RelativeVersion.olderversion;
}
else if (current == found) // Installing the same version.
{
return RelativeVersion.reinstall;
}
else if (found > current)
{
return RelativeVersion.upgrade;
}
}
return RelativeVersion.unknown;
}
public static bool? OverwriteAnnotations(Control parent, List<AnnotationDef> annotations)
{
List<string> annotationTitles = annotations.Select(annotation => annotation.GetKey()).ToList();
string annotationMultiMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteAnnotations_Annotations_with_the_following_names_already_exist_, String.Empty,
@"{0}", String.Empty);
string annotationSingleMessage =
TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteAnnotations_An_annotation_with_the_following_name_already_exists_, String.Empty, @"{0}", String.Empty);
string annotationMessage = annotations.Count == 1 ? annotationSingleMessage : annotationMultiMessage;
string question = Resources.ConfigureToolsDlg_OverwriteAnnotations_Do_you_want_to_overwrite_or_keep_the_existing_annotations_;
string messageFormat = TextUtil.LineSeparate(annotationMessage, question);
DialogResult result = MultiButtonMsgDlg.Show(
parent,
String.Format(messageFormat, TextUtil.LineSeparate(annotationTitles)),
Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite,
Resources.ConfigureToolsDlg_OverwriteAnnotations_Keep_Existing, true);
switch (result)
{
case DialogResult.Cancel:
return null;
case DialogResult.Yes:
return true;
case DialogResult.No:
return false;
}
return false;
}
}
}
| 1 | 14,330 | This is the only one that worries me a bit. It would be good if Brendan signed off on it. | ProteoWizard-pwiz | .cs |
@@ -57,6 +57,8 @@ public abstract class OptionalArrayMethodView implements ApiMethodView {
public abstract boolean isLongrunningOperation();
+ public abstract boolean hasLongrunningReturnValue();
+
public static Builder newBuilder() {
return new AutoValue_OptionalArrayMethodView.Builder();
} | 1 | /* Copyright 2016 Google 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.
*/
package com.google.api.codegen.viewmodel;
import com.google.api.codegen.config.GrpcStreamingConfig.GrpcStreamingType;
import com.google.auto.value.AutoValue;
import java.util.List;
@AutoValue
public abstract class OptionalArrayMethodView implements ApiMethodView {
public abstract ClientMethodType type();
public abstract String apiClassName();
public abstract String apiVariableName();
public abstract String apiModuleName();
public abstract InitCodeView initCode();
public abstract ApiMethodDocView doc();
public abstract String name();
public abstract String requestTypeName();
public abstract String key();
public abstract String grpcMethodName();
public abstract GrpcStreamingType grpcStreamingType();
public abstract List<DynamicLangDefaultableParamView> methodParams();
public abstract List<RequestObjectParamView> requiredRequestObjectParams();
public abstract List<RequestObjectParamView> optionalRequestObjectParams();
public abstract List<RequestObjectParamView> optionalRequestObjectParamsNoPageToken();
public abstract boolean hasReturnValue();
public abstract String stubName();
public abstract boolean isLongrunningOperation();
public static Builder newBuilder() {
return new AutoValue_OptionalArrayMethodView.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder type(ClientMethodType val);
public abstract Builder apiClassName(String val);
public abstract Builder apiVariableName(String val);
public abstract Builder apiModuleName(String val);
public abstract Builder initCode(InitCodeView val);
public abstract Builder doc(ApiMethodDocView val);
public abstract Builder name(String val);
public abstract Builder requestTypeName(String val);
public abstract Builder key(String val);
public abstract Builder grpcMethodName(String val);
public abstract Builder grpcStreamingType(GrpcStreamingType val);
public abstract Builder methodParams(List<DynamicLangDefaultableParamView> val);
public abstract Builder requiredRequestObjectParams(List<RequestObjectParamView> val);
public abstract Builder optionalRequestObjectParams(List<RequestObjectParamView> val);
public abstract Builder optionalRequestObjectParamsNoPageToken(
List<RequestObjectParamView> val);
public abstract Builder hasReturnValue(boolean val);
public abstract Builder stubName(String val);
public abstract Builder isLongrunningOperation(boolean val);
public abstract OptionalArrayMethodView build();
}
}
| 1 | 20,448 | `LongRunningOperationDetailView` already has `isEmptyOperation`. | googleapis-gapic-generator | java |
@@ -471,6 +471,9 @@ class RemoteConnection(object):
request.add_header('Accept', 'application/json')
request.add_header('Content-Type', 'application/json;charset=UTF-8')
+ base64string = base64.b64encode('%s:%s' % (parsed_url.username, parsed_url.password))
+ request.add_header("Authorization", "Basic %s" % base64string)
+
if password_manager:
opener = url_request.build_opener(url_request.HTTPRedirectHandler(),
HttpErrorHandler(), | 1 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
import socket
import string
import base64
try:
import http.client as httplib
from urllib import request as url_request
from urllib import parse
except ImportError: # above is available in py3+, below is py2.7
import httplib as httplib
import urllib2 as url_request
import urlparse as parse
from selenium.webdriver.common import utils as common_utils
from .command import Command
from .errorhandler import ErrorCode
from . import utils
LOGGER = logging.getLogger(__name__)
class Request(url_request.Request):
"""
Extends the url_request.Request to support all HTTP request types.
"""
def __init__(self, url, data=None, method=None):
"""
Initialise a new HTTP request.
:Args:
- url - String for the URL to send the request to.
- data - Data to send with the request.
"""
if method is None:
method = data is not None and 'POST' or 'GET'
elif method != 'POST' and method != 'PUT':
data = None
self._method = method
url_request.Request.__init__(self, url, data=data)
def get_method(self):
"""
Returns the HTTP method used by this request.
"""
return self._method
class Response(object):
"""
Represents an HTTP response.
"""
def __init__(self, fp, code, headers, url):
"""
Initialise a new Response.
:Args:
- fp - The response body file object.
- code - The HTTP status code returned by the server.
- headers - A dictionary of headers returned by the server.
- url - URL of the retrieved resource represented by this Response.
"""
self.fp = fp
self.read = fp.read
self.code = code
self.headers = headers
self.url = url
def close(self):
"""
Close the response body file object.
"""
self.read = None
self.fp = None
def info(self):
"""
Returns the response headers.
"""
return self.headers
def geturl(self):
"""
Returns the URL for the resource returned in this response.
"""
return self.url
class HttpErrorHandler(url_request.HTTPDefaultErrorHandler):
"""
A custom HTTP error handler.
Used to return Response objects instead of raising an HTTPError exception.
"""
def http_error_default(self, req, fp, code, msg, headers):
"""
Default HTTP error handler.
:Args:
- req - The original Request object.
- fp - The response body file object.
- code - The HTTP status code returned by the server.
- msg - The HTTP status message returned by the server.
- headers - The response headers.
:Returns:
A new Response object.
"""
return Response(fp, code, headers, req.get_full_url())
class RemoteConnection(object):
"""A connection with the Remote WebDriver server.
Communicates with the server using the WebDriver wire protocol:
https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol"""
_timeout = socket._GLOBAL_DEFAULT_TIMEOUT
@classmethod
def get_timeout(cls):
"""
:Returns:
Timeout value in seconds for all http requests made to the Remote Connection
"""
return None if cls._timeout == socket._GLOBAL_DEFAULT_TIMEOUT else cls._timeout
@classmethod
def set_timeout(cls, timeout):
"""
Override the default timeout
:Args:
- timeout - timeout value for http requests in seconds
"""
cls._timeout = timeout
@classmethod
def reset_timeout(cls):
"""
Reset the http request timeout to socket._GLOBAL_DEFAULT_TIMEOUT
"""
cls._timeout = socket._GLOBAL_DEFAULT_TIMEOUT
def __init__(self, remote_server_addr, keep_alive=False, resolve_ip=True):
# Attempt to resolve the hostname and get an IP address.
self.keep_alive = keep_alive
parsed_url = parse.urlparse(remote_server_addr)
addr = parsed_url.hostname
if parsed_url.hostname and resolve_ip:
port = parsed_url.port or None
if parsed_url.scheme == "https":
ip = parsed_url.hostname
else:
ip = common_utils.find_connectable_ip(parsed_url.hostname,
port=port)
if ip:
netloc = ip
addr = netloc
if parsed_url.port:
netloc = common_utils.join_host_port(netloc,
parsed_url.port)
if parsed_url.username:
auth = parsed_url.username
if parsed_url.password:
auth += ':%s' % parsed_url.password
netloc = '%s@%s' % (auth, netloc)
remote_server_addr = parse.urlunparse(
(parsed_url.scheme, netloc, parsed_url.path,
parsed_url.params, parsed_url.query, parsed_url.fragment))
else:
LOGGER.info('Could not get IP address for host: %s' %
parsed_url.hostname)
self._url = remote_server_addr
if keep_alive:
self._conn = httplib.HTTPConnection(
str(addr), str(parsed_url.port), timeout=self._timeout)
self._commands = {
Command.STATUS: ('GET', '/status'),
Command.NEW_SESSION: ('POST', '/session'),
Command.GET_ALL_SESSIONS: ('GET', '/sessions'),
Command.QUIT: ('DELETE', '/session/$sessionId'),
Command.GET_CURRENT_WINDOW_HANDLE:
('GET', '/session/$sessionId/window_handle'),
Command.GET_WINDOW_HANDLES:
('GET', '/session/$sessionId/window_handles'),
Command.GET: ('POST', '/session/$sessionId/url'),
Command.GO_FORWARD: ('POST', '/session/$sessionId/forward'),
Command.GO_BACK: ('POST', '/session/$sessionId/back'),
Command.REFRESH: ('POST', '/session/$sessionId/refresh'),
Command.EXECUTE_SCRIPT: ('POST', '/session/$sessionId/execute'),
Command.GET_CURRENT_URL: ('GET', '/session/$sessionId/url'),
Command.GET_TITLE: ('GET', '/session/$sessionId/title'),
Command.GET_PAGE_SOURCE: ('GET', '/session/$sessionId/source'),
Command.SCREENSHOT: ('GET', '/session/$sessionId/screenshot'),
Command.ELEMENT_SCREENSHOT: ('GET', '/session/$sessionId/element/$id/screenshot'),
Command.FIND_ELEMENT: ('POST', '/session/$sessionId/element'),
Command.FIND_ELEMENTS: ('POST', '/session/$sessionId/elements'),
Command.W3C_GET_ACTIVE_ELEMENT: ('GET', '/session/$sessionId/element/active'),
Command.GET_ACTIVE_ELEMENT:
('POST', '/session/$sessionId/element/active'),
Command.FIND_CHILD_ELEMENT:
('POST', '/session/$sessionId/element/$id/element'),
Command.FIND_CHILD_ELEMENTS:
('POST', '/session/$sessionId/element/$id/elements'),
Command.CLICK_ELEMENT: ('POST', '/session/$sessionId/element/$id/click'),
Command.CLEAR_ELEMENT: ('POST', '/session/$sessionId/element/$id/clear'),
Command.SUBMIT_ELEMENT: ('POST', '/session/$sessionId/element/$id/submit'),
Command.GET_ELEMENT_TEXT: ('GET', '/session/$sessionId/element/$id/text'),
Command.SEND_KEYS_TO_ELEMENT:
('POST', '/session/$sessionId/element/$id/value'),
Command.SEND_KEYS_TO_ACTIVE_ELEMENT:
('POST', '/session/$sessionId/keys'),
Command.UPLOAD_FILE: ('POST', "/session/$sessionId/file"),
Command.GET_ELEMENT_VALUE:
('GET', '/session/$sessionId/element/$id/value'),
Command.GET_ELEMENT_TAG_NAME:
('GET', '/session/$sessionId/element/$id/name'),
Command.IS_ELEMENT_SELECTED:
('GET', '/session/$sessionId/element/$id/selected'),
Command.SET_ELEMENT_SELECTED:
('POST', '/session/$sessionId/element/$id/selected'),
Command.IS_ELEMENT_ENABLED:
('GET', '/session/$sessionId/element/$id/enabled'),
Command.IS_ELEMENT_DISPLAYED:
('GET', '/session/$sessionId/element/$id/displayed'),
Command.GET_ELEMENT_LOCATION:
('GET', '/session/$sessionId/element/$id/location'),
Command.GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW:
('GET', '/session/$sessionId/element/$id/location_in_view'),
Command.GET_ELEMENT_SIZE:
('GET', '/session/$sessionId/element/$id/size'),
Command.GET_ELEMENT_RECT:
('GET', '/session/$sessionId/element/$id/rect'),
Command.GET_ELEMENT_ATTRIBUTE:
('GET', '/session/$sessionId/element/$id/attribute/$name'),
Command.GET_ELEMENT_PROPERTY:
('GET', '/session/$sessionId/element/$id/property/$name'),
Command.ELEMENT_EQUALS:
('GET', '/session/$sessionId/element/$id/equals/$other'),
Command.GET_ALL_COOKIES: ('GET', '/session/$sessionId/cookie'),
Command.ADD_COOKIE: ('POST', '/session/$sessionId/cookie'),
Command.DELETE_ALL_COOKIES:
('DELETE', '/session/$sessionId/cookie'),
Command.DELETE_COOKIE:
('DELETE', '/session/$sessionId/cookie/$name'),
Command.SWITCH_TO_FRAME: ('POST', '/session/$sessionId/frame'),
Command.SWITCH_TO_PARENT_FRAME: ('POST', '/session/$sessionId/frame/parent'),
Command.SWITCH_TO_WINDOW: ('POST', '/session/$sessionId/window'),
Command.CLOSE: ('DELETE', '/session/$sessionId/window'),
Command.GET_ELEMENT_VALUE_OF_CSS_PROPERTY:
('GET', '/session/$sessionId/element/$id/css/$propertyName'),
Command.IMPLICIT_WAIT:
('POST', '/session/$sessionId/timeouts/implicit_wait'),
Command.EXECUTE_ASYNC_SCRIPT: ('POST', '/session/$sessionId/execute_async'),
Command.SET_SCRIPT_TIMEOUT:
('POST', '/session/$sessionId/timeouts/async_script'),
Command.SET_TIMEOUTS:
('POST', '/session/$sessionId/timeouts'),
Command.DISMISS_ALERT:
('POST', '/session/$sessionId/dismiss_alert'),
Command.ACCEPT_ALERT:
('POST', '/session/$sessionId/accept_alert'),
Command.SET_ALERT_VALUE:
('POST', '/session/$sessionId/alert_text'),
Command.GET_ALERT_TEXT:
('GET', '/session/$sessionId/alert_text'),
Command.SET_ALERT_CREDENTIALS:
('POST', '/session/$sessionId/alert/credentials'),
Command.CLICK:
('POST', '/session/$sessionId/click'),
Command.DOUBLE_CLICK:
('POST', '/session/$sessionId/doubleclick'),
Command.MOUSE_DOWN:
('POST', '/session/$sessionId/buttondown'),
Command.MOUSE_UP:
('POST', '/session/$sessionId/buttonup'),
Command.MOVE_TO:
('POST', '/session/$sessionId/moveto'),
Command.GET_WINDOW_SIZE:
('GET', '/session/$sessionId/window/$windowHandle/size'),
Command.W3C_GET_WINDOW_SIZE:
('GET', '/session/$sessionId/window/size'),
Command.SET_WINDOW_SIZE:
('POST', '/session/$sessionId/window/$windowHandle/size'),
Command.W3C_SET_WINDOW_SIZE:
('POST', '/session/$sessionId/window/size'),
Command.GET_WINDOW_POSITION:
('GET', '/session/$sessionId/window/$windowHandle/position'),
Command.SET_WINDOW_POSITION:
('POST', '/session/$sessionId/window/$windowHandle/position'),
Command.W3C_GET_WINDOW_POSITION:
('GET', '/session/$sessionId/window/position'),
Command.W3C_SET_WINDOW_POSITION:
('POST', '/session/$sessionId/window/position'),
Command.MAXIMIZE_WINDOW:
('POST', '/session/$sessionId/window/$windowHandle/maximize'),
Command.W3C_MAXIMIZE_WINDOW:
('POST', '/session/$sessionId/window/maximize'),
Command.SET_SCREEN_ORIENTATION:
('POST', '/session/$sessionId/orientation'),
Command.GET_SCREEN_ORIENTATION:
('GET', '/session/$sessionId/orientation'),
Command.SINGLE_TAP:
('POST', '/session/$sessionId/touch/click'),
Command.TOUCH_DOWN:
('POST', '/session/$sessionId/touch/down'),
Command.TOUCH_UP:
('POST', '/session/$sessionId/touch/up'),
Command.TOUCH_MOVE:
('POST', '/session/$sessionId/touch/move'),
Command.TOUCH_SCROLL:
('POST', '/session/$sessionId/touch/scroll'),
Command.DOUBLE_TAP:
('POST', '/session/$sessionId/touch/doubleclick'),
Command.LONG_PRESS:
('POST', '/session/$sessionId/touch/longclick'),
Command.FLICK:
('POST', '/session/$sessionId/touch/flick'),
Command.EXECUTE_SQL:
('POST', '/session/$sessionId/execute_sql'),
Command.GET_LOCATION:
('GET', '/session/$sessionId/location'),
Command.SET_LOCATION:
('POST', '/session/$sessionId/location'),
Command.GET_APP_CACHE:
('GET', '/session/$sessionId/application_cache'),
Command.GET_APP_CACHE_STATUS:
('GET', '/session/$sessionId/application_cache/status'),
Command.CLEAR_APP_CACHE:
('DELETE', '/session/$sessionId/application_cache/clear'),
Command.GET_NETWORK_CONNECTION:
('GET', '/session/$sessionId/network_connection'),
Command.SET_NETWORK_CONNECTION:
('POST', '/session/$sessionId/network_connection'),
Command.GET_LOCAL_STORAGE_ITEM:
('GET', '/session/$sessionId/local_storage/key/$key'),
Command.REMOVE_LOCAL_STORAGE_ITEM:
('DELETE', '/session/$sessionId/local_storage/key/$key'),
Command.GET_LOCAL_STORAGE_KEYS:
('GET', '/session/$sessionId/local_storage'),
Command.SET_LOCAL_STORAGE_ITEM:
('POST', '/session/$sessionId/local_storage'),
Command.CLEAR_LOCAL_STORAGE:
('DELETE', '/session/$sessionId/local_storage'),
Command.GET_LOCAL_STORAGE_SIZE:
('GET', '/session/$sessionId/local_storage/size'),
Command.GET_SESSION_STORAGE_ITEM:
('GET', '/session/$sessionId/session_storage/key/$key'),
Command.REMOVE_SESSION_STORAGE_ITEM:
('DELETE', '/session/$sessionId/session_storage/key/$key'),
Command.GET_SESSION_STORAGE_KEYS:
('GET', '/session/$sessionId/session_storage'),
Command.SET_SESSION_STORAGE_ITEM:
('POST', '/session/$sessionId/session_storage'),
Command.CLEAR_SESSION_STORAGE:
('DELETE', '/session/$sessionId/session_storage'),
Command.GET_SESSION_STORAGE_SIZE:
('GET', '/session/$sessionId/session_storage/size'),
Command.GET_LOG:
('POST', '/session/$sessionId/log'),
Command.GET_AVAILABLE_LOG_TYPES:
('GET', '/session/$sessionId/log/types'),
Command.CURRENT_CONTEXT_HANDLE:
('GET', '/session/$sessionId/context'),
Command.CONTEXT_HANDLES:
('GET', '/session/$sessionId/contexts'),
Command.SWITCH_TO_CONTEXT:
('POST', '/session/$sessionId/context'),
}
def execute(self, command, params):
"""
Send a command to the remote server.
Any path subtitutions required for the URL mapped to the command should be
included in the command parameters.
:Args:
- command - A string specifying the command to execute.
- params - A dictionary of named parameters to send with the command as
its JSON payload.
"""
command_info = self._commands[command]
assert command_info is not None, 'Unrecognised command %s' % command
data = utils.dump_json(params)
path = string.Template(command_info[1]).substitute(params)
url = '%s%s' % (self._url, path)
return self._request(command_info[0], url, body=data)
def _request(self, method, url, body=None):
"""
Send an HTTP request to the remote server.
:Args:
- method - A string for the HTTP method to send the request with.
- url - A string for the URL to send the request to.
- body - A string for request body. Ignored unless method is POST or PUT.
:Returns:
A dictionary with the server's parsed JSON response.
"""
LOGGER.debug('%s %s %s' % (method, url, body))
parsed_url = parse.urlparse(url)
if self.keep_alive:
headers = {"Connection": 'keep-alive', method: parsed_url.path,
"User-Agent": "Python http auth",
"Content-type": "application/json;charset=\"UTF-8\"",
"Accept": "application/json"}
if parsed_url.username:
auth = base64.standard_b64encode(('%s:%s' % (
parsed_url.username,
parsed_url.password)).encode('ascii')).decode('ascii').replace('\n', '')
headers["Authorization"] = "Basic %s" % auth
if body and method != 'POST' and method != 'PUT':
body = None
try:
self._conn.request(method, parsed_url.path, body, headers)
resp = self._conn.getresponse()
except (httplib.HTTPException, socket.error):
self._conn.close()
raise
statuscode = resp.status
else:
password_manager = None
if parsed_url.username:
netloc = parsed_url.hostname
if parsed_url.port:
netloc += ":%s" % parsed_url.port
cleaned_url = parse.urlunparse((
parsed_url.scheme,
netloc,
parsed_url.path,
parsed_url.params,
parsed_url.query,
parsed_url.fragment))
password_manager = url_request.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None,
"%s://%s" % (parsed_url.scheme, netloc),
parsed_url.username,
parsed_url.password)
request = Request(cleaned_url, data=body.encode('utf-8'), method=method)
else:
request = Request(url, data=body.encode('utf-8'), method=method)
request.add_header('Accept', 'application/json')
request.add_header('Content-Type', 'application/json;charset=UTF-8')
if password_manager:
opener = url_request.build_opener(url_request.HTTPRedirectHandler(),
HttpErrorHandler(),
url_request.HTTPBasicAuthHandler(password_manager))
else:
opener = url_request.build_opener(url_request.HTTPRedirectHandler(),
HttpErrorHandler())
resp = opener.open(request, timeout=self._timeout)
statuscode = resp.code
if not hasattr(resp, 'getheader'):
if hasattr(resp.headers, 'getheader'):
resp.getheader = lambda x: resp.headers.getheader(x)
elif hasattr(resp.headers, 'get'):
resp.getheader = lambda x: resp.headers.get(x)
data = resp.read()
try:
if 300 <= statuscode < 304:
return self._request('GET', resp.getheader('location'))
body = data.decode('utf-8').replace('\x00', '').strip()
if 399 < statuscode <= 500:
return {'status': statuscode, 'value': body}
content_type = []
if resp.getheader('Content-Type') is not None:
content_type = resp.getheader('Content-Type').split(';')
if not any([x.startswith('image/png') for x in content_type]):
try:
data = utils.load_json(body.strip())
except ValueError:
if 199 < statuscode < 300:
status = ErrorCode.SUCCESS
else:
status = ErrorCode.UNKNOWN_ERROR
return {'status': status, 'value': body.strip()}
assert type(data) is dict, (
'Invalid server response body: %s' % body)
# Some of the drivers incorrectly return a response
# with no 'value' field when they should return null.
if 'value' not in data:
data['value'] = None
return data
else:
data = {'status': 0, 'value': body.strip()}
return data
finally:
LOGGER.debug("Finished Request")
resp.close()
| 1 | 14,022 | This will always add the authorization header to the request object. Is this the right scope for these two lines? If username/password are not defined, it will encode 'Basic :' | SeleniumHQ-selenium | js |
@@ -15,12 +15,7 @@ class Theme < ActiveRecord::Base
validates :title, presence: {message: _("can't be blank")}
- # EVALUATE CLASS AND INSTANCE METHODS BELOW
- #
- # What do they do? do they do it efficiently, and do we need them?
-
-
-
+ scope :updated_at_desc, -> { self.all.order(updated_at: 'DESC') }
##
# returns the title of the theme
# | 1 | class Theme < ActiveRecord::Base
##
# Associations
has_and_belongs_to_many :questions, join_table: "questions_themes"
has_and_belongs_to_many :guidances, join_table: "themes_in_guidance"
##
# Possibly needed for active_admin
# -relies on protected_attributes gem as syntax depricated in rails 4.2
attr_accessible :guidance_ids , :as => [:default, :admin]
attr_accessible :question_ids, :as => [:default, :admin]
attr_accessible :description, :title, :locale , :as => [:default, :admin]
validates :title, presence: {message: _("can't be blank")}
# EVALUATE CLASS AND INSTANCE METHODS BELOW
#
# What do they do? do they do it efficiently, and do we need them?
##
# returns the title of the theme
#
# @return [String] title of the theme
def to_s
title
end
end
| 1 | 17,203 | Don't think a scope adds much value for us here. Also, for future reference, you don't need to use the `self.all` it is implied. Could just be: `scope :updated_at_desc, -> { order(updated_at: :desc) }` No need to change this one now though, it works. | DMPRoadmap-roadmap | rb |
@@ -10,7 +10,7 @@ module Faker
end
return if digits < 1
- return 0 if digits == 1
+ return Base.rand(0..9).round if digits == 1
# Ensure the first digit is not zero
([non_zero_digit] + generate(digits - 1)).join.to_i | 1 | # frozen_string_literal: true
module Faker
class Number < Base
class << self
def number(legacy_digits = NOT_GIVEN, digits: 10)
if legacy_digits != NOT_GIVEN
warn_with_uplevel 'Passing `digits` with the 1st argument of `Number.number` is deprecated. Use keyword argument like `Number.number(digits: ...)` instead.', uplevel: 1
digits = legacy_digits
end
return if digits < 1
return 0 if digits == 1
# Ensure the first digit is not zero
([non_zero_digit] + generate(digits - 1)).join.to_i
end
def leading_zero_number(legacy_digits = NOT_GIVEN, digits: 10)
if legacy_digits != NOT_GIVEN
warn_with_uplevel 'Passing `digits` with the 1st argument of `Number.leading_zero_number` is deprecated. Use keyword argument like `Number.leading_zero_number(digits: ...)` instead.', uplevel: 1
digits = legacy_digits
end
'0' + (2..digits).collect { digit }.join
end
def decimal_part(legacy_digits = NOT_GIVEN, digits: 10)
if legacy_digits != NOT_GIVEN
warn_with_uplevel 'Passing `digits` with the 1st argument of `Number.decimal_part` is deprecated. Use keyword argument like `Number.decimal_part(digits: ...)` instead.', uplevel: 1
digits = legacy_digits
end
num = ''
if digits > 1
num = non_zero_digit
digits -= 1
end
leading_zero_number(digits: digits) + num.to_s
end
def decimal(legacy_l_digits = NOT_GIVEN, legacy_r_digits = NOT_GIVEN, l_digits: 5, r_digits: 2)
if legacy_l_digits != NOT_GIVEN
warn_with_uplevel 'Passing `l_digits` with the 1st argument of `Number.decimal` is deprecated. Use keyword argument like `Number.decimal(l_digits: ...)` instead.', uplevel: 1
l_digits = legacy_l_digits
end
if legacy_r_digits != NOT_GIVEN
warn_with_uplevel 'Passing `r_digits` with the 2nd argument of `Number.decimal` is deprecated. Use keyword argument like `Number.decimal(r_digits: ...)` instead.', uplevel: 1
r_digits = legacy_r_digits
end
l_d = number(digits: l_digits)
r_d = if r_digits == 1
generate(r_digits)
else
# Ensure the last digit is not zero
# so it does not get truncated on converting to float
generate(r_digits - 1).join + non_zero_digit.to_s
end
"#{l_d}.#{r_d}".to_f
end
def non_zero_digit
rand(1..9)
end
def digit
rand(10)
end
def hexadecimal(legacy_digits = NOT_GIVEN, digits: 6)
if legacy_digits != NOT_GIVEN
warn_with_uplevel 'Passing `digits` with the 1st argument of `Number.hexadecimal` is deprecated. Use keyword argument like `Number.hexadecimal(digits: ...)` instead.', uplevel: 1
digits = legacy_digits
end
hex = ''
digits.times { hex += rand(15).to_s(16) }
hex
end
def normal(legacy_mean = NOT_GIVEN, legacy_standard_deviation = NOT_GIVEN, mean: 1, standard_deviation: 1)
if legacy_mean != NOT_GIVEN
warn_with_uplevel 'Passing `mean` with the 1st argument of `Number.normal` is deprecated. Use keyword argument like `Number.normal(mean: ...)` instead.', uplevel: 1
mean = legacy_mean
end
if legacy_standard_deviation != NOT_GIVEN
warn_with_uplevel 'Passing `standard_deviation` with the 2nd argument of `Number.normal` is deprecated. Use keyword argument like `Number.normal(standard_deviation: ...)` instead.', uplevel: 1
standard_deviation = legacy_standard_deviation
end
theta = 2 * Math::PI * rand
rho = Math.sqrt(-2 * Math.log(1 - rand))
scale = standard_deviation * rho
mean + scale * Math.cos(theta)
end
def between(legacy_from = NOT_GIVEN, legacy_to = NOT_GIVEN, from: 1.00, to: 5000.00)
if legacy_from != NOT_GIVEN
warn_with_uplevel 'Passing `from` with the 1st argument of `Number.between` is deprecated. Use keyword argument like `Number.between(from: ...)` instead.', uplevel: 1
from = legacy_from
end
if legacy_to != NOT_GIVEN
warn_with_uplevel 'Passing `to` with the 2nd argument of `Number.between` is deprecated. Use keyword argument like `Number.between(to: ...)` instead.', uplevel: 1
to = legacy_to
end
Faker::Base.rand_in_range(from, to)
end
def within(legacy_range = NOT_GIVEN, range: 1.00..5000.00)
if legacy_range != NOT_GIVEN
warn_with_uplevel 'Passing `range` with the 1st argument of `Number.within` is deprecated. Use keyword argument like `Number.within(range: ...)` instead.', uplevel: 1
range = legacy_range
end
between(from: range.min, to: range.max)
end
def positive(legacy_from = NOT_GIVEN, legacy_to = NOT_GIVEN, from: 1.00, to: 5000.00)
if legacy_from != NOT_GIVEN
warn_with_uplevel 'Passing `from` with the 1st argument of `Number.positive` is deprecated. Use keyword argument like `Number.positive(from: ...)` instead.', uplevel: 1
from = legacy_from
end
if legacy_to != NOT_GIVEN
warn_with_uplevel 'Passing `to` with the 2nd argument of `Number.positive` is deprecated. Use keyword argument like `Number.positive(to: ...)` instead.', uplevel: 1
to = legacy_to
end
random_number = between(from: from, to: to)
greater_than_zero(random_number)
end
def negative(legacy_from = NOT_GIVEN, legacy_to = NOT_GIVEN, from: -5000.00, to: -1.00)
if legacy_from != NOT_GIVEN
warn_with_uplevel 'Passing `from` with the 1st argument of `Number.negative` is deprecated. Use keyword argument like `Number.negative(from: ...)` instead.', uplevel: 1
from = legacy_from
end
if legacy_to != NOT_GIVEN
warn_with_uplevel 'Passing `to` with the 2nd argument of `Number.negative` is deprecated. Use keyword argument like `Number.negative(to: ...)` instead.', uplevel: 1
to = legacy_to
end
random_number = between(from: from, to: to)
less_than_zero(random_number)
end
private
def generate(count)
return [] if count.zero?
Array.new(count) { digit }
end
def greater_than_zero(number)
should_be(number, :>)
end
def less_than_zero(number)
should_be(number, :<)
end
def should_be(number, method_to_compare)
if number.send(method_to_compare, 0)
number
else
number * -1
end
end
end
end
end
| 1 | 9,323 | I believe `Base.` is unnecessary in this case, as the class already extends `Base`. | faker-ruby-faker | rb |
@@ -76,12 +76,13 @@ import ServerConnections from '../ServerConnections';
return '';
}
- function getImageUrl(item, width) {
+ function getImageUrl(item, size) {
const apiClient = ServerConnections.getApiClient(item.ServerId);
let itemId;
const options = {
- maxWidth: width,
+ fillWidth: size,
+ fillHeight: size,
type: 'Primary'
};
| 1 | /* eslint-disable indent */
/**
* Module for display list view.
* @module components/listview/listview
*/
import itemHelper from '../itemHelper';
import mediaInfo from '../mediainfo/mediainfo';
import indicators from '../indicators/indicators';
import layoutManager from '../layoutManager';
import globalize from '../../scripts/globalize';
import datetime from '../../scripts/datetime';
import cardBuilder from '../cardbuilder/cardBuilder';
import './listview.css';
import '../../elements/emby-ratingbutton/emby-ratingbutton';
import '../../elements/emby-playstatebutton/emby-playstatebutton';
import ServerConnections from '../ServerConnections';
function getIndex(item, options) {
if (options.index === 'disc') {
return item.ParentIndexNumber == null ? '' : globalize.translate('ValueDiscNumber', item.ParentIndexNumber);
}
const sortBy = (options.sortBy || '').toLowerCase();
let code;
let name;
if (sortBy.indexOf('sortname') === 0) {
if (item.Type === 'Episode') {
return '';
}
// SortName
name = (item.SortName || item.Name || '?')[0].toUpperCase();
code = name.charCodeAt(0);
if (code < 65 || code > 90) {
return '#';
}
return name.toUpperCase();
}
if (sortBy.indexOf('officialrating') === 0) {
return item.OfficialRating || globalize.translate('Unrated');
}
if (sortBy.indexOf('communityrating') === 0) {
if (item.CommunityRating == null) {
return globalize.translate('Unrated');
}
return Math.floor(item.CommunityRating);
}
if (sortBy.indexOf('criticrating') === 0) {
if (item.CriticRating == null) {
return globalize.translate('Unrated');
}
return Math.floor(item.CriticRating);
}
if (sortBy.indexOf('albumartist') === 0) {
// SortName
if (!item.AlbumArtist) {
return '';
}
name = item.AlbumArtist[0].toUpperCase();
code = name.charCodeAt(0);
if (code < 65 || code > 90) {
return '#';
}
return name.toUpperCase();
}
return '';
}
function getImageUrl(item, width) {
const apiClient = ServerConnections.getApiClient(item.ServerId);
let itemId;
const options = {
maxWidth: width,
type: 'Primary'
};
if (item.ImageTags && item.ImageTags.Primary) {
options.tag = item.ImageTags.Primary;
itemId = item.Id;
} else if (item.AlbumId && item.AlbumPrimaryImageTag) {
options.tag = item.AlbumPrimaryImageTag;
itemId = item.AlbumId;
} else if (item.SeriesId && item.SeriesPrimaryImageTag) {
options.tag = item.SeriesPrimaryImageTag;
itemId = item.SeriesId;
} else if (item.ParentPrimaryImageTag) {
options.tag = item.ParentPrimaryImageTag;
itemId = item.ParentPrimaryImageItemId;
}
if (itemId) {
return apiClient.getScaledImageUrl(itemId, options);
}
return null;
}
function getChannelImageUrl(item, width) {
const apiClient = ServerConnections.getApiClient(item.ServerId);
const options = {
maxWidth: width,
type: 'Primary'
};
if (item.ChannelId && item.ChannelPrimaryImageTag) {
options.tag = item.ChannelPrimaryImageTag;
}
if (item.ChannelId) {
return apiClient.getScaledImageUrl(item.ChannelId, options);
}
}
function getTextLinesHtml(textlines, isLargeStyle) {
let html = '';
const largeTitleTagName = layoutManager.tv ? 'h2' : 'div';
for (const [i, text] of textlines.entries()) {
if (!text) {
continue;
}
if (i === 0) {
if (isLargeStyle) {
html += `<${largeTitleTagName} class="listItemBodyText">`;
} else {
html += '<div class="listItemBodyText">';
}
} else {
html += '<div class="secondary listItemBodyText">';
}
html += (textlines[i] || ' ');
if (i === 0 && isLargeStyle) {
html += `</${largeTitleTagName}>`;
} else {
html += '</div>';
}
}
return html;
}
function getRightButtonsHtml(options) {
let html = '';
for (let i = 0, length = options.rightButtons.length; i < length; i++) {
const button = options.rightButtons[i];
html += `<button is="paper-icon-button-light" class="listItemButton itemAction" data-action="custom" data-customaction="${button.id}" title="${button.title}"><span class="material-icons ${button.icon}"></span></button>`;
}
return html;
}
function getId(item) {
return item.Id;
}
export function getListViewHtml(options) {
const items = options.items;
let groupTitle = '';
const action = options.action || 'link';
const isLargeStyle = options.imageSize === 'large';
const enableOverview = options.enableOverview;
const clickEntireItem = layoutManager.tv ? true : false;
const outerTagName = clickEntireItem ? 'button' : 'div';
const enableSideMediaInfo = options.enableSideMediaInfo != null ? options.enableSideMediaInfo : true;
let outerHtml = '';
const enableContentWrapper = options.enableOverview && !layoutManager.tv;
const containerAlbumArtistIds = (options.containerAlbumArtists || []).map(getId);
for (let i = 0, length = items.length; i < length; i++) {
const item = items[i];
let html = '';
if (options.showIndex) {
const itemGroupTitle = getIndex(item, options);
if (itemGroupTitle !== groupTitle) {
if (html) {
html += '</div>';
}
if (i === 0) {
html += '<h2 class="listGroupHeader listGroupHeader-first">';
} else {
html += '<h2 class="listGroupHeader">';
}
html += itemGroupTitle;
html += '</h2>';
html += '<div>';
groupTitle = itemGroupTitle;
}
}
let cssClass = 'listItem';
if (options.border || (options.highlight !== false && !layoutManager.tv)) {
cssClass += ' listItem-border';
}
if (clickEntireItem) {
cssClass += ' itemAction listItem-button';
}
if (layoutManager.tv) {
cssClass += ' listItem-focusscale';
}
let downloadWidth = 80;
if (isLargeStyle) {
cssClass += ' listItem-largeImage';
downloadWidth = 500;
}
const playlistItemId = item.PlaylistItemId ? (` data-playlistitemid="${item.PlaylistItemId}"`) : '';
const positionTicksData = item.UserData && item.UserData.PlaybackPositionTicks ? (` data-positionticks="${item.UserData.PlaybackPositionTicks}"`) : '';
const collectionIdData = options.collectionId ? (` data-collectionid="${options.collectionId}"`) : '';
const playlistIdData = options.playlistId ? (` data-playlistid="${options.playlistId}"`) : '';
const mediaTypeData = item.MediaType ? (` data-mediatype="${item.MediaType}"`) : '';
const collectionTypeData = item.CollectionType ? (` data-collectiontype="${item.CollectionType}"`) : '';
const channelIdData = item.ChannelId ? (` data-channelid="${item.ChannelId}"`) : '';
if (enableContentWrapper) {
cssClass += ' listItem-withContentWrapper';
}
html += `<${outerTagName} class="${cssClass}"${playlistItemId} data-action="${action}" data-isfolder="${item.IsFolder}" data-id="${item.Id}" data-serverid="${item.ServerId}" data-type="${item.Type}"${mediaTypeData}${collectionTypeData}${channelIdData}${positionTicksData}${collectionIdData}${playlistIdData}>`;
if (enableContentWrapper) {
html += '<div class="listItem-content">';
}
if (!clickEntireItem && options.dragHandle) {
html += '<span class="listViewDragHandle material-icons listItemIcon listItemIcon-transparent drag_handle"></span>';
}
if (options.image !== false) {
const imgUrl = options.imageSource === 'channel' ? getChannelImageUrl(item, downloadWidth) : getImageUrl(item, downloadWidth);
let imageClass = isLargeStyle ? 'listItemImage listItemImage-large' : 'listItemImage';
if (isLargeStyle && layoutManager.tv) {
imageClass += ' listItemImage-large-tv';
}
const playOnImageClick = options.imagePlayButton && !layoutManager.tv;
if (!clickEntireItem) {
imageClass += ' itemAction';
}
const imageAction = playOnImageClick ? 'link' : action;
if (imgUrl) {
html += '<div data-action="' + imageAction + '" class="' + imageClass + ' lazy" data-src="' + imgUrl + '" item-icon>';
} else {
html += '<div class="' + imageClass + ' cardImageContainer ' + cardBuilder.getDefaultBackgroundClass(item.Name) + '">' + cardBuilder.getDefaultText(item, options);
}
let indicatorsHtml = '';
indicatorsHtml += indicators.getPlayedIndicatorHtml(item);
if (indicatorsHtml) {
html += `<div class="indicators listItemIndicators">${indicatorsHtml}</div>`;
}
if (playOnImageClick) {
html += '<button is="paper-icon-button-light" class="listItemImageButton itemAction" data-action="resume"><span class="material-icons listItemImageButton-icon play_arrow"></span></button>';
}
const progressHtml = indicators.getProgressBarHtml(item, {
containerClass: 'listItemProgressBar'
});
if (progressHtml) {
html += progressHtml;
}
html += '</div>';
}
if (options.showIndexNumberLeft) {
html += '<div class="listItem-indexnumberleft">';
html += (item.IndexNumber || ' ');
html += '</div>';
}
const textlines = [];
if (options.showProgramDateTime) {
textlines.push(datetime.toLocaleString(datetime.parseISO8601Date(item.StartDate), {
weekday: 'long',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit'
}));
}
if (options.showProgramTime) {
textlines.push(datetime.getDisplayTime(datetime.parseISO8601Date(item.StartDate)));
}
if (options.showChannel) {
if (item.ChannelName) {
textlines.push(item.ChannelName);
}
}
let parentTitle = null;
if (options.showParentTitle) {
if (item.Type === 'Episode') {
parentTitle = item.SeriesName;
} else if (item.IsSeries || (item.EpisodeTitle && item.Name)) {
parentTitle = item.Name;
}
}
let displayName = itemHelper.getDisplayName(item, {
includeParentInfo: options.includeParentInfoInTitle
});
if (options.showIndexNumber && item.IndexNumber != null) {
displayName = `${item.IndexNumber}. ${displayName}`;
}
if (options.showParentTitle && options.parentTitleWithTitle) {
if (displayName) {
if (parentTitle) {
parentTitle += ' - ';
}
parentTitle = (parentTitle || '') + displayName;
}
textlines.push(parentTitle || '');
} else if (options.showParentTitle) {
textlines.push(parentTitle || '');
}
if (displayName && !options.parentTitleWithTitle) {
textlines.push(displayName);
}
if (item.IsFolder) {
if (options.artist !== false) {
if (item.AlbumArtist && item.Type === 'MusicAlbum') {
textlines.push(item.AlbumArtist);
}
}
} else {
if (options.artist) {
const artistItems = item.ArtistItems;
if (artistItems && item.Type !== 'MusicAlbum') {
textlines.push(artistItems.map(a => {
return a.Name;
}).join(', '));
}
}
}
if (item.Type === 'TvChannel') {
if (item.CurrentProgram) {
textlines.push(itemHelper.getDisplayName(item.CurrentProgram));
}
}
cssClass = 'listItemBody';
if (!clickEntireItem) {
cssClass += ' itemAction';
}
if (options.image === false) {
cssClass += ' listItemBody-noleftpadding';
}
html += `<div class="${cssClass}">`;
html += getTextLinesHtml(textlines, isLargeStyle);
if (options.mediaInfo !== false) {
if (!enableSideMediaInfo) {
const mediaInfoClass = 'secondary listItemMediaInfo listItemBodyText';
html += `<div class="${mediaInfoClass}">`;
html += mediaInfo.getPrimaryMediaInfoHtml(item, {
episodeTitle: false,
originalAirDate: false,
subtitles: false
});
html += '</div>';
}
}
if (enableOverview && item.Overview) {
html += '<div class="secondary listItem-overview listItemBodyText">';
html += item.Overview;
html += '</div>';
}
html += '</div>';
if (options.mediaInfo !== false) {
if (enableSideMediaInfo) {
html += '<div class="secondary listItemMediaInfo">';
html += mediaInfo.getPrimaryMediaInfoHtml(item, {
year: false,
container: false,
episodeTitle: false,
criticRating: false,
endsAt: false
});
html += '</div>';
}
}
if (!options.recordButton && (item.Type === 'Timer' || item.Type === 'Program')) {
html += indicators.getTimerIndicator(item).replace('indicatorIcon', 'indicatorIcon listItemAside');
}
html += '<div class="listViewUserDataButtons">';
if (!clickEntireItem) {
if (options.addToListButton) {
html += '<button is="paper-icon-button-light" class="listItemButton itemAction" data-action="addtoplaylist"><span class="material-icons playlist_add"></span></button>';
}
if (options.infoButton) {
html += '<button is="paper-icon-button-light" class="listItemButton itemAction" data-action="link"><span class="material-icons info_outline"></span></button>';
}
if (options.rightButtons) {
html += getRightButtonsHtml(options);
}
if (options.enableUserDataButtons !== false) {
const userData = item.UserData || {};
const likes = userData.Likes == null ? '' : userData.Likes;
if (itemHelper.canMarkPlayed(item) && options.enablePlayedButton !== false) {
html += '<button is="emby-playstatebutton" type="button" class="listItemButton paper-icon-button-light" data-id="' + item.Id + '" data-serverid="' + item.ServerId + '" data-itemtype="' + item.Type + '" data-played="' + (userData.Played) + '"><span class="material-icons check"></span></button>';
}
if (itemHelper.canRate(item) && options.enableRatingButton !== false) {
html += '<button is="emby-ratingbutton" type="button" class="listItemButton paper-icon-button-light" data-id="' + item.Id + '" data-serverid="' + item.ServerId + '" data-itemtype="' + item.Type + '" data-likes="' + likes + '" data-isfavorite="' + (userData.IsFavorite) + '"><span class="material-icons favorite"></span></button>';
}
}
if (options.moreButton !== false) {
html += '<button is="paper-icon-button-light" class="listItemButton itemAction" data-action="menu"><span class="material-icons more_vert"></span></button>';
}
}
html += '</div>';
if (enableContentWrapper) {
html += '</div>';
if (enableOverview && item.Overview) {
html += '<div class="listItem-bottomoverview secondary">';
html += item.Overview;
html += '</div>';
}
}
html += `</${outerTagName}>`;
outerHtml += html;
}
return outerHtml;
}
/* eslint-enable indent */
export default {
getListViewHtml: getListViewHtml
};
| 1 | 18,889 | Couldn't this result in images being scaled too small when the width is less than the height assuming the width is still what is being passed here? | jellyfin-jellyfin-web | js |
@@ -13,7 +13,8 @@ var reportsInstance = {},
localize = require('../../../api/utils/localization.js'),
common = require('../../../api/utils/common.js'),
log = require('../../../api/utils/log')('reports:reports'),
- versionInfo = require('../../../frontend/express/version.info');
+ versionInfo = require('../../../frontend/express/version.info'),
+ offlineMode = plugins.getConfig("api").offline_mode;
versionInfo.page = (!versionInfo.title) ? "https://count.ly" : null;
versionInfo.title = versionInfo.title || "Countly"; | 1 | var reportsInstance = {},
async = require("async"),
moment = require('moment-timezone'),
ejs = require("ejs"),
fs = require('fs'),
path = require('path'),
request = require('request'),
crypto = require('crypto'),
mail = require("../../../api/parts/mgmt/mail"),
fetch = require("../../../api/parts/data/fetch"),
plugins = require("../../pluginManager"),
countlyCommon = require('../../../api/lib/countly.common.js'),
localize = require('../../../api/utils/localization.js'),
common = require('../../../api/utils/common.js'),
log = require('../../../api/utils/log')('reports:reports'),
versionInfo = require('../../../frontend/express/version.info');
versionInfo.page = (!versionInfo.title) ? "https://count.ly" : null;
versionInfo.title = versionInfo.title || "Countly";
var metrics = {
"analytics": {
"total_sessions": true,
"total_users": true,
"new_users": true,
"total_time": true,
"avg_time": true,
},
"revenue": {
"paying_users": true,
"purchases_c": true,
"purchases_s": true,
},
"push": {
"messaging_users": true,
"push_sent": true,
"push_open": true,
"push_action": true,
},
"crash": {
"unique_crashes": true,
"total_crashes": true,
"fatal_crashes": true,
"non_fatal_crashes": true
},
"events": {},
"views": {}
};
(function(reports) {
let _periodObj = null;
reports.sendReport = function(db, id, callback) {
reports.loadReport(db, id, function(err, report) {
if (err) {
return callback(err, null);
}
reports.getReport(db, report, function(err2, ob) {
if (!err2) {
reports.send(ob.report, ob.message, function() {
if (callback) {
callback(err2, ob.message);
}
});
}
else if (callback) {
callback(err2, ob.message);
}
});
});
};
reports.loadReport = function(db, id, callback) {
db.collection('reports').findOne({_id: db.ObjectID(id)}, function(err, report) {
if (callback) {
callback(err, report);
}
});
};
reports.getReport = function(db, report, callback, cache) {
/**
* find Member
* @param {func} cb - callback function
*/
function findMember(cb) {
db.collection('members').findOne({_id: db.ObjectID(report.user)}, function(err1, member) {
if (!err1 && member) {
return cb(null, member);
}
db.collection('members').findOne({global_admin: true}, function(err2, globalAdmin) {
if (!err2 && globalAdmin) {
log.d("Report user not found. Updating it to the global admin.");
report.user = globalAdmin._id;
return cb(null, globalAdmin);
}
return cb(err2);
});
});
}
/**
* process to get news from countly offical site
* @param {func} cb - callback function
*/
function processUniverse(cb) {
if (versionInfo.title.indexOf("Countly") > -1) {
var options = {
uri: 'http://count.ly/email-news.txt',
method: 'GET',
timeout: 1000
};
request(options, function(error, response, body) {
if (!error) {
try {
var arr = JSON.parse(body);
report.universe = arr[Math.floor(Math.random() * arr.length)];
}
catch (ex) {
console.log(ex);
}
}
cb(null);
});
}
else {
cb(null);
}
}
cache = cache || {};
var reportType = report.report_type || "core";
if (report) {
var parallelTasks = [
findMember.bind(null),
processUniverse.bind(null)
];
async.parallel(parallelTasks, function(err, data) {
/**
* iterate app
* @param {string} app_id - id of app record in db.
* @param {func} done - callback function
*/
function appIterator(app_id, done) {
/**
* metricIterator curry function
* @param {obj} params - params injected in inner func
* @return {func} metricIterator - function for iterartion
*/
function metricIteratorCurryFunc(params) {
/**
* fetch metric iterator
* @param {array} metric - martric array
* @param {*} done2 - callback function
*/
function metricIterator(metric, done2) {
if (metric.indexOf("events") === 0) {
var parts = metric.split(".");
var event = null;
//replace with app's iap_key
if (parts[1] === "purchases") {
event = common.dot(params.app, 'plugins.revenue.iap_events');
event = event && event.length ? event : null;
}
else if (parts[1] === "[CLY]_push_sent" || parts[1] === "[CLY]_push_open" || parts[1] === "[CLY]_push_action") {
if ((params.app.gcm && Object.keys(params.app.gcm).length) || (params.app.apn && Object.keys(params.app.apn).length)) {
event = parts[1];
}
}
else {
event = parts[1];
}
if (event) {
if (Array.isArray(event)) {
fetch.getMergedEventData(params, event, {db: db}, function(output) {
done2(null, {metric: parts[1], data: output});
});
}
else {
var collectionName = "events" + crypto.createHash('sha1').update(event + app_id).digest('hex');
fetch.getTimeObjForEvents(collectionName, params, {db: db}, function(output) {
done2(null, {metric: parts[1], data: output});
});
}
}
else {
done2(null, null);
}
}
else {
if (metric === "crashdata") {
fetch.getTimeObj(metric, params, {db: db, unique: "cru"}, function(output) {
done2(null, {metric: metric, data: output});
});
}
else {
fetch.getTimeObj(metric, params, {db: db}, function(output) {
fetch.getTotalUsersObj(metric, params, function(dbTotalUsersObj) {
output.correction = fetch.formatTotalUsersObj(dbTotalUsersObj);
output.prev_correction = fetch.formatTotalUsersObj(dbTotalUsersObj, true);
done2(null, {metric: metric, data: output});
});
});
}
}
}
return metricIterator;
}
var params2 = {qstring: {period: report.period}};
if (!cache[app_id] || !cache[app_id][report.period]) {
db.collection('apps').findOne({_id: db.ObjectID(app_id)}, function(err_apps, app) {
if (err_apps) {
console.log(err_apps);
}
if (app) {
params2.app_id = app._id;
params2.app_cc = app.country;
params2.app_name = app.name;
params2.appTimezone = app.timezone;
params2.app = app;
db.collection('events').findOne({_id: params2.app_id}, function(err_events, events) {
if (err_events) {
console.log(err_events);
}
events = events || {};
events.list = events.list || [];
const metricIterator = metricIteratorCurryFunc(params2);
async.map(metricsToCollections(report.metrics, events.list), metricIterator, function(err1, results) {
if (err1) {
console.log(err1);
}
app.results = {};
for (var i = 0; i < results.length; i++) {
if (results[i] && results[i].metric) {
app.results[results[i].metric] = results[i].data;
}
}
if (!cache[app_id]) {
cache[app_id] = {};
}
cache[app_id][report.period] = JSON.parse(JSON.stringify(app));
done(null, app);
});
});
}
else {
done(null, null);
}
});
}
else {
done(null, JSON.parse(JSON.stringify(cache[app_id][report.period])));
}
}
if (err || !data[0]) {
return callback("Report user not found.", {report: report});
}
var member = data[0];
var lang = member.lang || 'en';
if (lang.toLowerCase() === "zh") {
moment.locale("zh-cn");
}
else {
moment.locale(lang.toLowerCase());
}
if (reportType !== "core") {
var params = {
db: db,
report: report,
member: member,
moment: moment
};
if (!plugins.isPluginEnabled(reportType)) {
return callback("No data to report", {report: report});
}
plugins.dispatch("/email/report", { params: params }, function() {
if (!params.report || !params.report.data) {
return callback("No data to report", {report: report});
}
return callback(null, report.data);
});
}
else if (reportType === "core" && report.apps) {
report.apps = sortBy(report.apps, member.appSortList || []);
if (report.frequency === "daily") {
var endDate = new Date();
endDate.setDate(endDate.getDate() - 1);
endDate.setHours(23, 59);
report.end = endDate.getTime();
report.start = report.end - 24 * 60 * 59 * 1000;
var startDate = new Date(report.start);
var monthName = moment.localeData().monthsShort(moment([0, startDate.getMonth()]), "");
report.date = startDate.getDate() + " " + monthName;
report.period = "yesterday";
}
else if (report.frequency === "weekly") {
endDate = new Date();
endDate.setHours(23, 59);
report.end = endDate.getTime();
report.start = report.end - 7 * 24 * 60 * 59 * 1000;
report.period = "7days";
startDate = new Date(report.start);
monthName = moment.localeData().monthsShort(moment([0, startDate.getMonth()]), "");
report.date = startDate.getDate() + " " + monthName;
monthName = moment.localeData().monthsShort(moment([0, endDate.getMonth()]), "");
report.date += " - " + endDate.getDate() + " " + monthName;
}
else if (report.frequency === "monthly") {
endDate = new Date();
endDate.setHours(23, 59);
report.end = endDate.getTime();
report.start = report.end - parseInt(moment(endDate).subtract(1, 'months').daysInMonth()) * 24 * 60 * 60 * 1000;
report.period = [report.start, report.end];
startDate = new Date(report.start);
monthName = moment.localeData().monthsShort(moment([0, startDate.getMonth()]), "");
report.date = startDate.getDate() + " " + monthName;
monthName = moment.localeData().monthsShort(moment([0, endDate.getMonth()]), "");
report.date += " - " + endDate.getDate() + " " + monthName;
}
async.map(report.apps, appIterator, function(err2, results) {
if (err2) {
return callback(err2);
}
report.total_new = 0;
var total = 0;
for (var i = 0; i < results.length; i++) {
if (results[i] && results[i].results) {
countlyCommon.setPeriod(report.period);
countlyCommon.setTimezone(results[i].timezone);
for (var j in results[i].results) {
if (j === "users") {
results[i].results[j] = getSessionData(
results[i].results[j] || {},
(results[i].results[j] && results[i].results[j].correction) ? results[i].results[j].correction : {},
(results[i].results[j] && results[i].results[j].prev_correction) ? results[i].results[j].prev_correction : {}
);
if (results[i].results[j].total_sessions.total > 0) {
results[i].display = true;
}
total += results[i].results[j].total_sessions.total;
report.total_new += results[i].results[j].new_users.total;
results[i].results.analytics = results[i].results[j];
delete results[i].results[j];
let iap_events = common.dot(results[i], 'plugins.revenue.iap_events');
if (iap_events && iap_events.length) {
if (!results[i].results.revenue) {
results[i].results.revenue = {};
}
results[i].results.revenue.paying_users = results[i].results.analytics.paying_users;
}
delete results[i].results.analytics.paying_users;
if ((results[i].gcm && Object.keys(results[i].gcm).length) || (results[i].apn && Object.keys(results[i].apn).length)) {
if (!results[i].results.push) {
results[i].results.push = {};
}
results[i].results.push.messaging_users = results[i].results.analytics.messaging_users;
}
delete results[i].results.analytics.messaging_users;
}
else if (j === "crashdata") {
results[i].results.crash = getCrashData(results[i].results[j] || {});
delete results[i].results[j];
}
else if (j === "[CLY]_push_sent" || j === "[CLY]_push_open" || j === "[CLY]_push_action") {
if (!results[i].results.push) {
results[i].results.push = {};
}
results[i].results.push[j.replace("[CLY]_", "")] = getEventData(results[i].results[j] || {});
delete results[i].results[j];
}
else if (j === "purchases") {
if (!results[i].results.revenue) {
results[i].results.revenue = {};
}
var revenueData = getRevenueData(results[i].results[j] || {});
results[i].results.revenue[j + "_c"] = revenueData.c;
results[i].results.revenue[j + "_s"] = revenueData.s;
delete results[i].results[j];
}
else {
if (!results[i].results.events) {
results[i].results.events = {};
}
results[i].results.events[j] = getEventData(results[i].results[j] || {});
delete results[i].results[j];
}
}
}
}
if (total > 0) {
report.apps = results;
report.mailTemplate = "/templates/email.html";
process();
}
else if (callback) {
return callback("No data to report", {report: report});
}
});
}
else {
return callback("Report not found", {report: report});
}
/**
* process email sending
*/
function process() {
mail.lookup(function(err0, host) {
if (err0) {
if (callback) {
return callback(err0, {});
}
}
var dir = path.resolve(__dirname, '../frontend/public');
fs.readFile(dir + report.mailTemplate, 'utf8', function(err1, template) {
if (err1) {
if (callback) {
callback(err1, {report: report});
}
}
else {
member.lang = member.lang || "en";
localize.getProperties(member.lang, function(err2, props) {
if (err2) {
if (callback) {
return callback(err2, {report: report});
}
}
else {
props["reports.report"] = localize.format(props["reports.report"], versionInfo.title);
props["reports.your"] = localize.format(props["reports.your"], props["reports." + report.frequency], report.date);
report.properties = props;
var allowedMetrics = {};
for (var i in report.metrics) {
if (metrics[i]) {
for (var j in metrics[i]) {
allowedMetrics[j] = true;
}
}
}
var message = ejs.render(template, {"apps": report.apps, "host": host, "report": report, "version": versionInfo, "properties": props, metrics: allowedMetrics});
report.subject = versionInfo.title + ': ' + localize.format(
(
(report.frequency === "weekly") ? report.properties["reports.subject-week"] :
((report.frequency === "monthly") ? report.properties["reports.subject-month"] : report.properties["reports.subject-day"])
), report.total_new);
if (callback) {
return callback(err2, {"apps": report.apps, "host": host, "report": report, "version": versionInfo, "properties": props, message: message});
}
}
});
}
});
});
}
});
}
else if (callback) {
return callback("Report not found", {report: report});
}
};
reports.send = function(report, message, callback) {
if (report.emails) {
for (var i = 0; i < report.emails.length; i++) {
var msg = {
to: report.emails[i],
from: versionInfo.title,
subject: report.subject,
html: message
};
if (mail.sendPoolMail) {
mail.sendPoolMail(msg);
}
else {
mail.sendMail(msg);
}
}
}
callback();
};
/**
* set metrics in collection
* @param {object} metricsObj - metrics data
* @param {object} events - event data
* @return {object} collections - collections names
*/
function metricsToCollections(metricsObj, events) {
var collections = {users: true};
for (let i in metricsObj) {
if (metricsObj[i]) {
if (i === "analytics") {
collections.users = true;
}
else if (i === "crash" && plugins.isPluginEnabled("crashes")) {
collections.crashdata = true;
}
else if (i === "push") {
collections["events.[CLY]_push_sent"] = true;
collections["events.[CLY]_push_action"] = true;
}
else if (i === "revenue") {
collections["events.purchases"] = true;
}
else if (i === "events") {
for (let j = 0; j < events.length; j++) {
if (events[j].indexOf("[CLY]_") === -1) {
collections["events." + events[j]] = true;
}
}
}
}
}
return Object.keys(collections);
}
/**
* get session data
* @param {object} _sessionDb - session original data
* @param {object} totalUserOverrideObj - user data
* @param {object} previousTotalUserOverrideObj - user data for previous period
* @return {object} dataArr - session statstics contains serveral metrics.
*/
function getSessionData(_sessionDb, totalUserOverrideObj, previousTotalUserOverrideObj) {
//Update the current period object in case selected date is changed
_periodObj = countlyCommon.periodObj;
var dataArr = {},
tmp_x,
tmp_y,
currentTotal = 0,
previousTotal = 0,
currentPayingTotal = 0,
previousPayingTotal = 0,
currentMsgEnabledTotal = 0,
previousMsgEnabledTotal = 0,
currentNew = 0,
previousNew = 0,
currentUnique = 0,
previousUnique = 0,
currentDuration = 0,
previousDuration = 0,
currentEvents = 0,
previousEvents = 0,
isEstimate = false;
if (_periodObj.isSpecialPeriod) {
isEstimate = true;
for (let i = 0; i < (_periodObj.uniquePeriodArr.length); i++) {
tmp_x = countlyCommon.getDescendantProp(_sessionDb, _periodObj.uniquePeriodArr[i]);
tmp_x = clearSessionObject(tmp_x);
currentUnique += tmp_x.u;
currentPayingTotal += tmp_x.p;
currentMsgEnabledTotal += tmp_x.m;
}
var tmpUniqObj,
tmpCurrentUniq = 0,
tmpCurrentPaying = 0,
tmpCurrentMsgEnabled = 0;
for (let i = 0; i < (_periodObj.uniquePeriodCheckArr.length); i++) {
tmpUniqObj = countlyCommon.getDescendantProp(_sessionDb, _periodObj.uniquePeriodCheckArr[i]);
tmpUniqObj = clearSessionObject(tmpUniqObj);
tmpCurrentUniq += tmpUniqObj.u;
tmpCurrentPaying += tmpUniqObj.p;
tmpCurrentMsgEnabled += tmpUniqObj.m;
}
//console.log(currentPayingTotal + " " + tmpCurrentPaying)
if (currentUnique > tmpCurrentUniq) {
currentUnique = tmpCurrentUniq;
}
if (currentPayingTotal > tmpCurrentPaying) {
currentPayingTotal = tmpCurrentPaying;
}
if (currentMsgEnabledTotal > tmpCurrentMsgEnabled) {
currentMsgEnabledTotal = tmpCurrentMsgEnabled;
}
for (let i = 0; i < (_periodObj.previousUniquePeriodArr.length); i++) {
tmp_y = countlyCommon.getDescendantProp(_sessionDb, _periodObj.previousUniquePeriodArr[i]);
tmp_y = clearSessionObject(tmp_y);
previousUnique += tmp_y.u;
previousPayingTotal += tmp_y.p;
previousMsgEnabledTotal += tmp_y.m;
}
var tmpUniqObj2,
tmpPreviousUniq = 0,
tmpPreviousPaying = 0;
for (let i = 0; i < (_periodObj.previousUniquePeriodCheckArr.length); i++) {
tmpUniqObj2 = countlyCommon.getDescendantProp(_sessionDb, _periodObj.previousUniquePeriodCheckArr[i]);
tmpUniqObj2 = clearSessionObject(tmpUniqObj2);
tmpPreviousUniq += tmpUniqObj2.u;
tmpPreviousPaying += tmpUniqObj2.p;
}
if (previousUnique > tmpPreviousUniq) {
previousUnique = tmpPreviousUniq;
}
if (previousPayingTotal > tmpPreviousPaying) {
previousPayingTotal = tmpPreviousPaying;
}
if (currentMsgEnabledTotal > tmpCurrentMsgEnabled) {
currentMsgEnabledTotal = tmpCurrentMsgEnabled;
}
for (let i = 0; i < (_periodObj.currentPeriodArr.length); i++) {
tmp_x = countlyCommon.getDescendantProp(_sessionDb, _periodObj.currentPeriodArr[i]);
tmp_y = countlyCommon.getDescendantProp(_sessionDb, _periodObj.previousPeriodArr[i]);
tmp_x = clearSessionObject(tmp_x);
tmp_y = clearSessionObject(tmp_y);
currentTotal += tmp_x.t;
previousTotal += tmp_y.t;
currentNew += tmp_x.n;
previousNew += tmp_y.n;
currentDuration += tmp_x.d;
previousDuration += tmp_y.d;
currentEvents += tmp_x.e;
previousEvents += tmp_y.e;
}
}
else {
tmp_x = countlyCommon.getDescendantProp(_sessionDb, _periodObj.activePeriod);
tmp_y = countlyCommon.getDescendantProp(_sessionDb, _periodObj.previousPeriod);
tmp_x = clearSessionObject(tmp_x);
tmp_y = clearSessionObject(tmp_y);
currentTotal = tmp_x.t;
previousTotal = tmp_y.t;
currentNew = tmp_x.n;
previousNew = tmp_y.n;
currentUnique = tmp_x.u;
previousUnique = tmp_y.u;
currentDuration = tmp_x.d;
previousDuration = tmp_y.d;
currentEvents = tmp_x.e;
previousEvents = tmp_y.e;
currentPayingTotal = tmp_x.p;
previousPayingTotal = tmp_y.p;
currentMsgEnabledTotal = tmp_x.m;
previousMsgEnabledTotal = tmp_y.m;
}
currentUnique = (totalUserOverrideObj && totalUserOverrideObj.users) ? totalUserOverrideObj.users : currentUnique;
previousUnique = (previousTotalUserOverrideObj && previousTotalUserOverrideObj.users) ? previousTotalUserOverrideObj.users : previousUnique;
if (currentUnique < currentNew) {
if (totalUserOverrideObj && totalUserOverrideObj.users) {
currentNew = currentUnique;
}
else {
currentUnique = currentNew;
}
}
if (currentUnique > currentTotal) {
currentUnique = currentTotal;
}
var sessionDuration = (currentDuration / 60),
previousSessionDuration = (previousDuration / 60),
previousDurationPerUser = (previousTotal === 0) ? 0 : previousSessionDuration / previousTotal,
durationPerUser = (currentTotal === 0) ? 0 : (sessionDuration / currentTotal),
previousEventsPerUser = (previousUnique === 0) ? 0 : previousEvents / previousUnique,
eventsPerUser = (currentUnique === 0) ? 0 : (currentEvents / currentUnique),
changeTotal = countlyCommon.getPercentChange(previousTotal, currentTotal),
changeDuration = countlyCommon.getPercentChange(previousDuration, currentDuration),
changeDurationPerUser = countlyCommon.getPercentChange(previousDurationPerUser, durationPerUser),
changeNew = countlyCommon.getPercentChange(previousNew, currentNew),
changeUnique = countlyCommon.getPercentChange(previousUnique, currentUnique),
changeReturning = countlyCommon.getPercentChange((previousUnique - previousNew), (currentUnique - currentNew)),
changeEvents = countlyCommon.getPercentChange(previousEvents, currentEvents),
changeEventsPerUser = countlyCommon.getPercentChange(previousEventsPerUser, eventsPerUser),
changePaying = countlyCommon.getPercentChange(previousPayingTotal, currentPayingTotal),
changeMsgEnabled = countlyCommon.getPercentChange(previousMsgEnabledTotal, currentMsgEnabledTotal);
var timeSpentString = (sessionDuration.toFixed(1)) + " min";
if (sessionDuration >= 142560) {
timeSpentString = (sessionDuration / 525600).toFixed(1) + " years";
}
else if (sessionDuration >= 1440) {
timeSpentString = (sessionDuration / 1440).toFixed(1) + " days";
}
else if (sessionDuration >= 60) {
timeSpentString = (sessionDuration / 60).toFixed(1) + " hours";
}
//var timeSpentString = countlyCommon.timeString(sessionDuration);
dataArr =
{
"total_sessions": {
"total": currentTotal,
"change": changeTotal.percent,
"trend": changeTotal.trend
},
"paying_users": {
"total": currentPayingTotal,
"prev-total": previousPayingTotal,
"change": changePaying.percent,
"trend": changePaying.trend,
"isEstimate": isEstimate
},
"total_users": {
"total": currentUnique,
"prev-total": previousUnique,
"change": changeUnique.percent,
"trend": changeUnique.trend,
"isEstimate": isEstimate
},
"messaging_users": {
"total": currentMsgEnabledTotal,
"prev-total": previousMsgEnabledTotal,
"change": changeMsgEnabled.percent,
"trend": changeMsgEnabled.trend,
"isEstimate": isEstimate
},
"new_users": {
"total": currentNew,
"change": changeNew.percent,
"trend": changeNew.trend
},
"returning_users": {
"total": (currentUnique - currentNew),
"change": changeReturning.percent,
"trend": changeReturning.trend
},
"total_time": {
"total": timeSpentString,
"change": changeDuration.percent,
"trend": changeDuration.trend
},
"avg_time": {
"total": countlyCommon.timeString(durationPerUser),
"change": changeDurationPerUser.percent,
"trend": changeDurationPerUser.trend
},
"total_requests": {
"total": currentEvents,
"change": changeEvents.percent,
"trend": changeEvents.trend
},
"avg_requests": {
"total": eventsPerUser.toFixed(1),
"change": changeEventsPerUser.percent,
"trend": changeEventsPerUser.trend
}
};
return dataArr;
}
/**
* get crash data
* @param {object} _crashTimeline - timeline object
* @return {object} dataArr - crash data with several dimension statistics
*/
function getCrashData(_crashTimeline) {
//Update the current period object in case selected date is changed
_periodObj = countlyCommon.periodObj;
var dataArr = {},
tmp_x,
tmp_y,
currentTotal = 0,
previousTotal = 0,
currentUnique = 0,
previousUnique = 0,
currentNonfatal = 0,
previousNonfatal = 0,
currentFatal = 0,
previousFatal = 0,
currentResolved = 0,
previousResolved = 0;
if (_periodObj.isSpecialPeriod) {
for (let i = 0; i < (_periodObj.currentPeriodArr.length); i++) {
tmp_x = countlyCommon.getDescendantProp(_crashTimeline, _periodObj.currentPeriodArr[i]);
tmp_x = clearCrashObject(tmp_x);
currentUnique += tmp_x.cru;
currentTotal += tmp_x.cr;
currentNonfatal += tmp_x.crnf;
currentFatal += tmp_x.crf;
currentResolved += tmp_x.crru;
}
for (let i = 0; i < (_periodObj.previousPeriodArr.length); i++) {
tmp_y = countlyCommon.getDescendantProp(_crashTimeline, _periodObj.previousPeriodArr[i]);
tmp_y = clearCrashObject(tmp_y);
previousUnique += tmp_y.cru;
previousTotal += tmp_y.cr;
previousNonfatal += tmp_y.crnf;
previousFatal += tmp_y.crf;
previousResolved += tmp_y.crru;
}
}
else {
tmp_x = countlyCommon.getDescendantProp(_crashTimeline, _periodObj.activePeriod);
tmp_y = countlyCommon.getDescendantProp(_crashTimeline, _periodObj.previousPeriod);
tmp_x = clearCrashObject(tmp_x);
tmp_y = clearCrashObject(tmp_y);
currentTotal = tmp_x.cr;
previousTotal = tmp_y.cr;
currentNonfatal = tmp_x.crnf;
previousNonfatal = tmp_y.crnf;
currentUnique = tmp_x.cru;
previousUnique = tmp_y.cru;
currentFatal = tmp_x.crf;
previousFatal = tmp_y.crf;
currentResolved = tmp_x.crru;
previousResolved = tmp_y.crru;
}
var changeTotal = countlyCommon.getPercentChange(previousTotal, currentTotal),
changeNonfatal = countlyCommon.getPercentChange(previousNonfatal, currentNonfatal),
changeUnique = countlyCommon.getPercentChange(previousUnique, currentUnique),
changeFatal = countlyCommon.getPercentChange(previousFatal, currentFatal),
changeResolved = countlyCommon.getPercentChange(previousResolved, currentResolved);
dataArr =
{
"total_crashes": {
"total": currentTotal,
"change": changeTotal.percent,
"trend": changeTotal.trend,
"isEstimate": false
},
"unique_crashes": {
"total": currentUnique,
"prev-total": previousUnique,
"change": changeUnique.percent,
"trend": changeUnique.trend,
"isEstimate": false
},
"non_fatal_crashes": {
"total": currentNonfatal,
"prev-total": previousNonfatal,
"change": changeNonfatal.percent,
"trend": changeNonfatal.trend,
"isEstimate": false
},
"fatal_crashes": {
"total": currentFatal,
"change": changeFatal.percent,
"trend": changeFatal.trend,
"isEstimate": false
},
"resolved_upgrades": {
"total": currentResolved,
"change": changeResolved.percent,
"trend": changeResolved.trend,
"isEstimate": false
}
};
return dataArr;
}
/**
* get event data
* @param {object} eventDb - original event data
* @return {number} - return event calc data
*/
function getEventData(eventDb) {
_periodObj = countlyCommon.periodObj;
if (!eventDb) {
return {
total: 0,
change: 'NA',
trend: 'u',
sparkline: '0,0'
};
}
var currentTotal = 0,
previousTotal = 0;
if (_periodObj.isSpecialPeriod) {
for (var i = 0; i < (_periodObj.currentPeriodArr.length); i++) {
currentTotal += eventCount(eventDb, _periodObj.currentPeriodArr[i]);
previousTotal += eventCount(eventDb, _periodObj.previousPeriodArr[i]);
}
}
else {
currentTotal = eventCount(eventDb, _periodObj.activePeriod);
previousTotal = eventCount(eventDb, _periodObj.previousPeriod);
}
var changeTotal = countlyCommon.getPercentChange(previousTotal, currentTotal);
return {
"total": currentTotal,
"change": changeTotal.percent,
"trend": changeTotal.trend
};
}
/**
* get revenue chart data
* @param {object} eventDb - event data
* @return {object} - return revenu data chart object
*/
function getRevenueData(eventDb) {
_periodObj = countlyCommon.periodObj;
if (!eventDb) {
return {
c: {
total: 0,
change: 'NA',
trend: 'u',
sparkline: '0,0'
},
s: {
total: 0,
change: 'NA',
trend: 'u',
sparkline: '0,0'
}
};
}
var total = {
c: 0,
pc: 0,
s: 0,
ps: 0
};
if (_periodObj.isSpecialPeriod) {
for (var i = 0; i < (_periodObj.currentPeriodArr.length); i++) {
let tmpObj = countlyCommon.getDescendantProp(eventDb, _periodObj.currentPeriodArr[i]);
total.c += (tmpObj && tmpObj.c) ? tmpObj.c : 0;
total.s += (tmpObj && tmpObj.s) ? tmpObj.s : 0;
let tmpObj2 = countlyCommon.getDescendantProp(eventDb, _periodObj.previousPeriodArr[i]);
total.pc += (tmpObj2 && tmpObj2.c) ? tmpObj2.c : 0;
total.ps += (tmpObj2 && tmpObj2.s) ? tmpObj2.s : 0;
}
}
else {
let tmpObj = countlyCommon.getDescendantProp(eventDb, _periodObj.activePeriod);
total.c = (tmpObj && tmpObj.c) ? tmpObj.c : 0;
total.s = (tmpObj && tmpObj.s) ? tmpObj.s : 0;
let tmpObj2 = countlyCommon.getDescendantProp(eventDb, _periodObj.previousPeriod);
total.pc = (tmpObj2 && tmpObj2.c) ? tmpObj2.c : 0;
total.ps = (tmpObj2 && tmpObj2.s) ? tmpObj2.s : 0;
}
var changeTotalCount = countlyCommon.getPercentChange(total.pc, total.c);
var changeTotalSum = countlyCommon.getPercentChange(total.ps, total.s);
return {
c: {
"total": total.c,
"change": changeTotalCount.percent,
"trend": changeTotalCount.trend
},
s: {
"total": total.s.toFixed(2),
"change": changeTotalSum.percent,
"trend": changeTotalSum.trend
}
};
}
/**
* get event count
* @param {object} eventDb - event data
* @param {string/array} period - period defined by countly
* @return {number} - return event count
*/
function eventCount(eventDb, period) {
var tmpObj = countlyCommon.getDescendantProp(eventDb, period);
return (tmpObj && tmpObj.c) ? tmpObj.c : 0;
}
/**
* clear session object data format, will set properties to 0 if not exisit
* @param {object} obj - db object
* @return {object} obj - cleared object
*/
function clearCrashObject(obj) {
if (obj) {
if (!obj.cr) {
obj.cr = 0;
}
if (!obj.cru) {
obj.cru = 0;
}
if (!obj.crnf) {
obj.crnf = 0;
}
if (!obj.crf) {
obj.crf = 0;
}
if (!obj.crru) {
obj.crru = 0;
}
}
else {
obj = {"cr": 0, "cru": 0, "crnf": 0, "crf": 0, "crru": 0};
}
return obj;
}
/**
* clear session object data format, will set properties to 0 if not exisit
* @param {object} obj - db object
* @return {object} obj - cleared object
*/
function clearSessionObject(obj) {
if (obj) {
if (!obj.t) {
obj.t = 0;
}
if (!obj.n) {
obj.n = 0;
}
if (!obj.u) {
obj.u = 0;
}
if (!obj.d) {
obj.d = 0;
}
if (!obj.e) {
obj.e = 0;
}
if (!obj.p) {
obj.p = 0;
}
if (!obj.m) {
obj.m = 0;
}
}
else {
obj = {"t": 0, "n": 0, "u": 0, "d": 0, "e": 0, "p": 0, "m": 0};
}
return obj;
}
/**
* sort first array base on second array, and render the rest of elements by original relative sequence.
* @param {object} arrayToSort - array need to sort
* @param {object} sortList - array for reference.
* @return {object} retArr - return sorted array
*/
function sortBy(arrayToSort, sortList) {
if (!sortList.length) {
return arrayToSort;
}
var tmpArr = [],
retArr = [];
for (let i = 0; i < arrayToSort.length; i++) {
var objId = arrayToSort[i];
if (sortList.indexOf(objId) !== -1) {
tmpArr[sortList.indexOf(objId)] = arrayToSort[i];
}
}
for (let i = 0; i < tmpArr.length; i++) {
if (tmpArr[i]) {
retArr[retArr.length] = tmpArr[i];
}
}
for (let i = 0; i < arrayToSort.length; i++) {
if (retArr.indexOf(arrayToSort[i]) === -1) {
retArr[retArr.length] = arrayToSort[i];
}
}
return retArr;
}
}(reportsInstance));
module.exports = reportsInstance; | 1 | 13,380 | Here also, let's not cache value on top of file, but use `plugins.getConfig("api").offline_mode` directly where it is needed | Countly-countly-server | js |
@@ -78,10 +78,15 @@ class LibraryCardsController extends AbstractBase
// Connect to the ILS for login drivers:
$catalog = $this->getILS();
+ $config = $this->getConfig();
+ $shibboleth = isset($config->Catalog->shibboleth_library_cards) &&
+ $config->Catalog->shibboleth_library_cards &&
+ ($this->getAuthManager()->getAuthMethod() == 'Shibboleth');
return $this->createViewModel(
[
'libraryCards' => $user->getLibraryCards(),
- 'multipleTargets' => $catalog->checkCapability('getLoginDrivers')
+ 'multipleTargets' => $catalog->checkCapability('getLoginDrivers'),
+ 'shibboleth' => $shibboleth,
]
);
} | 1 | <?php
/**
* LibraryCards Controller
*
* PHP version 7
*
* Copyright (C) Villanova University 2010.
* Copyright (C) The National Library of Finland 2015-2019.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Controller
* @author Demian Katz <[email protected]>
* @author Ere Maijala <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/
namespace VuFind\Controller;
use VuFind\Exception\ILS as ILSException;
/**
* Controller for the library card functionality.
*
* @category VuFind
* @package Controller
* @author Demian Katz <[email protected]>
* @author Ere Maijala <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/
class LibraryCardsController extends AbstractBase
{
/**
* Send user's library cards to the view
*
* @return mixed
*/
public function homeAction()
{
if (!($user = $this->getUser())) {
return $this->forceLogin();
}
// Check for "delete card" request; parameter may be in GET or POST depending
// on calling context.
$deleteId = $this->params()->fromPost(
'delete', $this->params()->fromQuery('delete')
);
if ($deleteId) {
// If the user already confirmed the operation, perform the delete now;
// otherwise prompt for confirmation:
$confirm = $this->params()->fromPost(
'confirm', $this->params()->fromQuery('confirm')
);
if ($confirm) {
$success = $this->performDeleteLibraryCard($deleteId);
if ($success !== true) {
return $success;
}
} else {
return $this->confirmDeleteLibraryCard($deleteId);
}
}
// Connect to the ILS for login drivers:
$catalog = $this->getILS();
return $this->createViewModel(
[
'libraryCards' => $user->getLibraryCards(),
'multipleTargets' => $catalog->checkCapability('getLoginDrivers')
]
);
}
/**
* Send user's library card to the edit view
*
* @return mixed
*/
public function editCardAction()
{
// User must be logged in to edit library cards:
$user = $this->getUser();
if ($user == false) {
return $this->forceLogin();
}
// Process email authentication:
if ($this->params()->fromQuery('auth_method') === 'Email'
&& ($hash = $this->params()->fromQuery('hash'))
) {
return $this->processEmailLink($user, $hash);
}
// Process form submission:
if ($this->formWasSubmitted('submit')) {
if ($redirect = $this->processEditLibraryCard($user)) {
return $redirect;
}
}
$id = $this->params()->fromRoute('id', $this->params()->fromQuery('id'));
$card = $user->getLibraryCard($id == 'NEW' ? null : $id);
$target = null;
$username = $card->cat_username;
$loginSettings = $this->getILSLoginSettings();
// Split target and username if multiple login targets are available:
if ($loginSettings['targets'] && strstr($username, '.')) {
list($target, $username) = explode('.', $username, 2);
}
$cardName = $this->params()->fromPost('card_name', $card->card_name);
$username = $this->params()->fromPost('username', $username);
$target = $this->params()->fromPost('target', $target);
// Send the card to the view:
return $this->createViewModel(
[
'card' => $card,
'cardName' => $cardName,
'target' => $target ?: $loginSettings['defaultTarget'],
'username' => $username,
'targets' => $loginSettings['targets'],
'defaultTarget' => $loginSettings['defaultTarget'],
'loginMethod' => $loginSettings['loginMethod'],
'loginMethods' => $loginSettings['loginMethods'],
]
);
}
/**
* Creates a confirmation box to delete or not delete the current list
*
* @return mixed
*/
public function deleteCardAction()
{
// User must be logged in to edit library cards:
$user = $this->getUser();
if ($user == false) {
return $this->forceLogin();
}
// Get requested library card ID:
$cardID = $this->params()
->fromPost('cardID', $this->params()->fromQuery('cardID'));
// Have we confirmed this?
$confirm = $this->params()->fromPost(
'confirm', $this->params()->fromQuery('confirm')
);
if ($confirm) {
$user->deleteLibraryCard($cardID);
// Success Message
$this->flashMessenger()->addMessage('Library Card Deleted', 'success');
// Redirect to MyResearch library cards
return $this->redirect()->toRoute('librarycards-home');
}
// If we got this far, we must display a confirmation message:
return $this->confirm(
'confirm_delete_library_card_brief',
$this->url()->fromRoute('librarycards-deletecard'),
$this->url()->fromRoute('librarycards-home'),
'confirm_delete_library_card_text', ['cardID' => $cardID]
);
}
/**
* When redirecting after selecting a library card, adjust the URL to make
* sure it will work correctly.
*
* @param string $url URL to adjust
*
* @return string
*/
protected function adjustCardRedirectUrl($url)
{
// If there is pagination in the URL, reset it to page 1, since the
// new card may have a different number of pages of data:
return preg_replace('/([&?]page)=[0-9]+/', '$1=1', $url);
}
/**
* Activates a library card
*
* @return \Laminas\Http\Response
*/
public function selectCardAction()
{
$user = $this->getUser();
if ($user == false) {
return $this->forceLogin();
}
$cardID = $this->params()->fromQuery('cardID');
if (null === $cardID) {
return $this->redirect()->toRoute('myresearch-home');
}
$user->activateLibraryCard($cardID);
// Connect to the ILS and check that the credentials are correct:
try {
$catalog = $this->getILS();
$patron = $catalog->patronLogin(
$user->cat_username,
$user->getCatPassword()
);
if (!$patron) {
$this->flashMessenger()
->addMessage('authentication_error_invalid', 'error');
}
} catch (ILSException $e) {
$this->flashMessenger()
->addMessage('authentication_error_technical', 'error');
}
$this->setFollowupUrlToReferer();
if ($url = $this->getFollowupUrl()) {
$this->clearFollowupUrl();
return $this->redirect()->toUrl($this->adjustCardRedirectUrl($url));
}
return $this->redirect()->toRoute('myresearch-home');
}
/**
* Process the "edit library card" submission.
*
* @param \VuFind\Db\Row\User $user Logged in user
*
* @return object|bool Response object if redirect is
* needed, false if form needs to be redisplayed.
*/
protected function processEditLibraryCard($user)
{
$cardName = $this->params()->fromPost('card_name', '');
$target = $this->params()->fromPost('target', '');
$username = $this->params()->fromPost('username', '');
$password = $this->params()->fromPost('password', '');
$id = $this->params()->fromRoute('id', $this->params()->fromQuery('id'));
if (!$username) {
$this->flashMessenger()
->addMessage('authentication_error_blank', 'error');
return false;
}
if ($target) {
$username = "$target.$username";
}
// Check the credentials if the username is changed or a new password is
// entered:
$card = $user->getLibraryCard($id == 'NEW' ? null : $id);
if ($card->cat_username !== $username || trim($password)) {
// Connect to the ILS and check that the credentials are correct:
$loginMethod = $this->getILSLoginMethod($target);
$catalog = $this->getILS();
try {
$patron = $catalog->patronLogin($username, $password);
} catch (ILSException $e) {
$this->flashMessenger()->addErrorMessage('ils_connection_failed');
return false;
}
if ('password' === $loginMethod && !$patron) {
$this->flashMessenger()
->addMessage('authentication_error_invalid', 'error');
return false;
}
if ('email' === $loginMethod) {
if ($patron) {
$info = $patron;
$info['cardID'] = $id;
$info['cardName'] = $cardName;
$emailAuthenticator = $this->serviceLocator
->get(\VuFind\Auth\EmailAuthenticator::class);
$emailAuthenticator->sendAuthenticationLink(
$info['email'],
$info,
['auth_method' => 'Email'],
'editLibraryCard'
);
}
// Don't reveal the result
$this->flashMessenger()->addSuccessMessage('email_login_link_sent');
return $this->redirect()->toRoute('librarycards-home');
}
}
try {
$user->saveLibraryCard(
$id == 'NEW' ? null : $id, $cardName, $username, $password
);
} catch (\VuFind\Exception\LibraryCard $e) {
$this->flashMessenger()->addMessage($e->getMessage(), 'error');
return false;
}
return $this->redirect()->toRoute('librarycards-home');
}
/**
* Process library card addition via an email link
*
* @param User $user User object
* @param string $hash Hash
*
* @return \Laminas\Http\Response Response object
*/
protected function processEmailLink($user, $hash)
{
$emailAuthenticator = $this->serviceLocator
->get(\VuFind\Auth\EmailAuthenticator::class);
try {
$info = $emailAuthenticator->authenticate($hash);
$user->saveLibraryCard(
'NEW' === $info['cardID'] ? null : $info['cardID'],
$info['cardName'],
$info['cat_username'],
' '
);
} catch (\VuFind\Exception\Auth $e) {
$this->flashMessenger()->addErrorMessage($e->getMessage());
} catch (\VuFind\Exception\LibraryCard $e) {
$this->flashMessenger()->addErrorMessage($e->getMessage());
}
return $this->redirect()->toRoute('librarycards-home');
}
}
| 1 | 30,711 | You can combine the two checks into a single `!empty()` check. | vufind-org-vufind | php |
@@ -599,6 +599,10 @@ func validateOptions(o *Options) error {
return fmt.Errorf("lame duck grace period (%v) should be strictly lower than lame duck duration (%v)",
o.LameDuckGracePeriod, o.LameDuckDuration)
}
+ if int64(o.MaxPayload) > o.MaxPending {
+ return fmt.Errorf("max_payload (%v) cannot be higher than max_pending (%v)",
+ o.MaxPayload, o.MaxPending)
+ }
// Check that the trust configuration is correct.
if err := validateTrustedOperators(o); err != nil {
return err | 1 | // Copyright 2012-2020 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
"regexp"
// Allow dynamic profiling.
_ "net/http/pprof"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nats-io/jwt/v2"
"github.com/nats-io/nkeys"
"github.com/nats-io/nuid"
"github.com/nats-io/nats-server/v2/logger"
)
const (
// Interval for the first PING for non client connections.
firstPingInterval = time.Second
// This is for the first ping for client connections.
firstClientPingInterval = 2 * time.Second
)
// Info is the information sent to clients, routes, gateways, and leaf nodes,
// to help them understand information about this server.
type Info struct {
ID string `json:"server_id"`
Name string `json:"server_name"`
Version string `json:"version"`
Proto int `json:"proto"`
GitCommit string `json:"git_commit,omitempty"`
GoVersion string `json:"go"`
Host string `json:"host"`
Port int `json:"port"`
Headers bool `json:"headers"`
AuthRequired bool `json:"auth_required,omitempty"`
TLSRequired bool `json:"tls_required,omitempty"`
TLSVerify bool `json:"tls_verify,omitempty"`
TLSAvailable bool `json:"tls_available,omitempty"`
MaxPayload int32 `json:"max_payload"`
JetStream bool `json:"jetstream,omitempty"`
IP string `json:"ip,omitempty"`
CID uint64 `json:"client_id,omitempty"`
ClientIP string `json:"client_ip,omitempty"`
Nonce string `json:"nonce,omitempty"`
Cluster string `json:"cluster,omitempty"`
Dynamic bool `json:"cluster_dynamic,omitempty"`
Domain string `json:"domain,omitempty"`
ClientConnectURLs []string `json:"connect_urls,omitempty"` // Contains URLs a client can connect to.
WSConnectURLs []string `json:"ws_connect_urls,omitempty"` // Contains URLs a ws client can connect to.
LameDuckMode bool `json:"ldm,omitempty"`
// Route Specific
Import *SubjectPermission `json:"import,omitempty"`
Export *SubjectPermission `json:"export,omitempty"`
LNOC bool `json:"lnoc,omitempty"`
InfoOnConnect bool `json:"info_on_connect,omitempty"` // When true the server will respond to CONNECT with an INFO
ConnectInfo bool `json:"connect_info,omitempty"` // When true this is the server INFO response to CONNECT
// Gateways Specific
Gateway string `json:"gateway,omitempty"` // Name of the origin Gateway (sent by gateway's INFO)
GatewayURLs []string `json:"gateway_urls,omitempty"` // Gateway URLs in the originating cluster (sent by gateway's INFO)
GatewayURL string `json:"gateway_url,omitempty"` // Gateway URL on that server (sent by route's INFO)
GatewayCmd byte `json:"gateway_cmd,omitempty"` // Command code for the receiving server to know what to do
GatewayCmdPayload []byte `json:"gateway_cmd_payload,omitempty"` // Command payload when needed
GatewayNRP bool `json:"gateway_nrp,omitempty"` // Uses new $GNR. prefix for mapped replies
// LeafNode Specific
LeafNodeURLs []string `json:"leafnode_urls,omitempty"` // LeafNode URLs that the server can reconnect to.
RemoteAccount string `json:"remote_account,omitempty"` // Lets the other side know the remote account that they bind to.
}
// Server is our main struct.
type Server struct {
gcid uint64
stats
mu sync.Mutex
kp nkeys.KeyPair
prand *rand.Rand
info Info
configFile string
optsMu sync.RWMutex
opts *Options
running bool
shutdown bool
reloading bool
listener net.Listener
listenerErr error
gacc *Account
sys *internal
js *jetStream
accounts sync.Map
tmpAccounts sync.Map // Temporarily stores accounts that are being built
activeAccounts int32
accResolver AccountResolver
clients map[uint64]*client
routes map[uint64]*client
routesByHash sync.Map
remotes map[string]*client
leafs map[uint64]*client
users map[string]*User
nkeys map[string]*NkeyUser
totalClients uint64
closed *closedRingBuffer
done chan bool
start time.Time
http net.Listener
httpHandler http.Handler
httpBasePath string
profiler net.Listener
httpReqStats map[string]uint64
routeListener net.Listener
routeListenerErr error
routeInfo Info
routeInfoJSON []byte
routeResolver netResolver
routesToSelf map[string]struct{}
leafNodeListener net.Listener
leafNodeListenerErr error
leafNodeInfo Info
leafNodeInfoJSON []byte
leafURLsMap refCountedUrlSet
leafNodeOpts struct {
resolver netResolver
dialTimeout time.Duration
}
leafRemoteCfgs []*leafNodeCfg
leafRemoteAccounts sync.Map
quitCh chan struct{}
shutdownComplete chan struct{}
// Tracking Go routines
grMu sync.Mutex
grTmpClients map[uint64]*client
grRunning bool
grWG sync.WaitGroup // to wait on various go routines
cproto int64 // number of clients supporting async INFO
configTime time.Time // last time config was loaded
logging struct {
sync.RWMutex
logger Logger
trace int32
debug int32
traceSysAcc int32
}
clientConnectURLs []string
// Used internally for quick look-ups.
clientConnectURLsMap refCountedUrlSet
lastCURLsUpdate int64
// For Gateways
gatewayListener net.Listener // Accept listener
gatewayListenerErr error
gateway *srvGateway
// Used by tests to check that http.Servers do
// not set any timeout.
monitoringServer *http.Server
profilingServer *http.Server
// LameDuck mode
ldm bool
ldmCh chan bool
// Trusted public operator keys.
trustedKeys []string
// map of trusted keys to operator setting StrictSigningKeyUsage
strictSigningKeyUsage map[string]struct{}
// We use this to minimize mem copies for requests to monitoring
// endpoint /varz (when it comes from http).
varzMu sync.Mutex
varz *Varz
// This is set during a config reload if we detect that we have
// added/removed routes. The monitoring code then check that
// to know if it should update the cluster's URLs array.
varzUpdateRouteURLs bool
// Keeps a sublist of of subscriptions attached to leafnode connections
// for the $GNR.*.*.*.> subject so that a server can send back a mapped
// gateway reply.
gwLeafSubs *Sublist
// Used for expiration of mapped GW replies
gwrm struct {
w int32
ch chan time.Duration
m sync.Map
}
// For eventIDs
eventIds *nuid.NUID
// Websocket structure
websocket srvWebsocket
// MQTT structure
mqtt srvMQTT
// OCSP monitoring
ocsps []*OCSPMonitor
// exporting account name the importer experienced issues with
incompleteAccExporterMap sync.Map
// Holds cluster name under different lock for mapping
cnMu sync.RWMutex
cn string
// For registering raft nodes with the server.
rnMu sync.RWMutex
raftNodes map[string]RaftNode
// For mapping from a raft node name back to a server name and cluster. Node has to be in the same domain.
nodeToInfo sync.Map
// For out of resources to not log errors too fast.
rerrMu sync.Mutex
rerrLast time.Time
// If there is a system account configured, to still support the $G account,
// the server will create a fake user and add it to the list of users.
// Keep track of what that user name is for config reload purposes.
sysAccOnlyNoAuthUser string
}
// For tracking JS nodes.
type nodeInfo struct {
name string
cluster string
domain string
id string
offline bool
js bool
}
// Make sure all are 64bits for atomic use
type stats struct {
inMsgs int64
outMsgs int64
inBytes int64
outBytes int64
slowConsumers int64
}
// New will setup a new server struct after parsing the options.
// DEPRECATED: Use NewServer(opts)
func New(opts *Options) *Server {
s, _ := NewServer(opts)
return s
}
// NewServer will setup a new server struct after parsing the options.
// Could return an error if options can not be validated.
func NewServer(opts *Options) (*Server, error) {
setBaselineOptions(opts)
// Process TLS options, including whether we require client certificates.
tlsReq := opts.TLSConfig != nil
verify := (tlsReq && opts.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert)
// Created server's nkey identity.
kp, _ := nkeys.CreateServer()
pub, _ := kp.PublicKey()
serverName := pub
if opts.ServerName != _EMPTY_ {
serverName = opts.ServerName
}
httpBasePath := normalizeBasePath(opts.HTTPBasePath)
// Validate some options. This is here because we cannot assume that
// server will always be started with configuration parsing (that could
// report issues). Its options can be (incorrectly) set by hand when
// server is embedded. If there is an error, return nil.
if err := validateOptions(opts); err != nil {
return nil, err
}
info := Info{
ID: pub,
Version: VERSION,
Proto: PROTO,
GitCommit: gitCommit,
GoVersion: runtime.Version(),
Name: serverName,
Host: opts.Host,
Port: opts.Port,
AuthRequired: false,
TLSRequired: tlsReq && !opts.AllowNonTLS,
TLSVerify: verify,
MaxPayload: opts.MaxPayload,
JetStream: opts.JetStream,
Headers: !opts.NoHeaderSupport,
Cluster: opts.Cluster.Name,
Domain: opts.JetStreamDomain,
}
if tlsReq && !info.TLSRequired {
info.TLSAvailable = true
}
now := time.Now().UTC()
s := &Server{
kp: kp,
configFile: opts.ConfigFile,
info: info,
prand: rand.New(rand.NewSource(time.Now().UnixNano())),
opts: opts,
done: make(chan bool, 1),
start: now,
configTime: now,
gwLeafSubs: NewSublistWithCache(),
httpBasePath: httpBasePath,
eventIds: nuid.New(),
routesToSelf: make(map[string]struct{}),
httpReqStats: make(map[string]uint64), // Used to track HTTP requests
}
// Trusted root operator keys.
if !s.processTrustedKeys() {
return nil, fmt.Errorf("Error processing trusted operator keys")
}
// If we have solicited leafnodes but no clustering and no clustername.
// However we may need a stable clustername so use the server name.
if len(opts.LeafNode.Remotes) > 0 && opts.Cluster.Port == 0 && opts.Cluster.Name == _EMPTY_ {
opts.Cluster.Name = opts.ServerName
}
if opts.Cluster.Name != _EMPTY_ {
// Also place into mapping cn with cnMu lock.
s.cnMu.Lock()
s.cn = opts.Cluster.Name
s.cnMu.Unlock()
}
s.mu.Lock()
defer s.mu.Unlock()
// Place ourselves in some lookup maps.
ourNode := string(getHash(serverName))
s.nodeToInfo.Store(ourNode, nodeInfo{serverName, opts.Cluster.Name, opts.JetStreamDomain, info.ID, false, opts.JetStream})
s.routeResolver = opts.Cluster.resolver
if s.routeResolver == nil {
s.routeResolver = net.DefaultResolver
}
// Used internally for quick look-ups.
s.clientConnectURLsMap = make(refCountedUrlSet)
s.websocket.connectURLsMap = make(refCountedUrlSet)
s.leafURLsMap = make(refCountedUrlSet)
// Ensure that non-exported options (used in tests) are properly set.
s.setLeafNodeNonExportedOptions()
// Setup OCSP Stapling. This will abort server from starting if there
// are no valid staples and OCSP policy is to Always or MustStaple.
if err := s.enableOCSP(); err != nil {
return nil, err
}
// Call this even if there is no gateway defined. It will
// initialize the structure so we don't have to check for
// it to be nil or not in various places in the code.
if err := s.newGateway(opts); err != nil {
return nil, err
}
// If we have a cluster definition but do not have a cluster name, create one.
if opts.Cluster.Port != 0 && opts.Cluster.Name == _EMPTY_ {
s.info.Cluster = nuid.Next()
} else if opts.Cluster.Name != _EMPTY_ {
// Likewise here if we have a cluster name set.
s.info.Cluster = opts.Cluster.Name
}
// This is normally done in the AcceptLoop, once the
// listener has been created (possibly with random port),
// but since some tests may expect the INFO to be properly
// set after New(), let's do it now.
s.setInfoHostPort()
// For tracking clients
s.clients = make(map[uint64]*client)
// For tracking closed clients.
s.closed = newClosedRingBuffer(opts.MaxClosedClients)
// For tracking connections that are not yet registered
// in s.routes, but for which readLoop has started.
s.grTmpClients = make(map[uint64]*client)
// For tracking routes and their remote ids
s.routes = make(map[uint64]*client)
s.remotes = make(map[string]*client)
// For tracking leaf nodes.
s.leafs = make(map[uint64]*client)
// Used to kick out all go routines possibly waiting on server
// to shutdown.
s.quitCh = make(chan struct{})
// Closed when Shutdown() is complete. Allows WaitForShutdown() to block
// waiting for complete shutdown.
s.shutdownComplete = make(chan struct{})
// Check for configured account resolvers.
if err := s.configureResolver(); err != nil {
return nil, err
}
// If there is an URL account resolver, do basic test to see if anyone is home.
if ar := opts.AccountResolver; ar != nil {
if ur, ok := ar.(*URLAccResolver); ok {
if _, err := ur.Fetch(""); err != nil {
return nil, err
}
}
}
// For other resolver:
// In operator mode, when the account resolver depends on an external system and
// the system account can't fetched, inject a temporary one.
if ar := s.accResolver; len(opts.TrustedOperators) == 1 && ar != nil &&
opts.SystemAccount != _EMPTY_ && opts.SystemAccount != DEFAULT_SYSTEM_ACCOUNT {
if _, ok := ar.(*MemAccResolver); !ok {
s.mu.Unlock()
var a *Account
// perform direct lookup to avoid warning trace
if _, err := fetchAccount(ar, s.opts.SystemAccount); err == nil {
a, _ = s.fetchAccount(s.opts.SystemAccount)
}
s.mu.Lock()
if a == nil {
sac := NewAccount(s.opts.SystemAccount)
sac.Issuer = opts.TrustedOperators[0].Issuer
sac.signingKeys = map[string]jwt.Scope{}
sac.signingKeys[s.opts.SystemAccount] = nil
s.registerAccountNoLock(sac)
}
}
}
// For tracking accounts
if err := s.configureAccounts(); err != nil {
return nil, err
}
// Used to setup Authorization.
s.configureAuthorization()
// Start signal handler
s.handleSignals()
return s, nil
}
// clusterName returns our cluster name which could be dynamic.
func (s *Server) ClusterName() string {
s.mu.Lock()
cn := s.info.Cluster
s.mu.Unlock()
return cn
}
// Grabs cluster name with cluster name specific lock.
func (s *Server) cachedClusterName() string {
s.cnMu.RLock()
cn := s.cn
s.cnMu.RUnlock()
return cn
}
// setClusterName will update the cluster name for this server.
func (s *Server) setClusterName(name string) {
s.mu.Lock()
var resetCh chan struct{}
if s.sys != nil && s.info.Cluster != name {
// can't hold the lock as go routine reading it may be waiting for lock as well
resetCh = s.sys.resetCh
}
s.info.Cluster = name
s.routeInfo.Cluster = name
// Regenerate the info byte array
s.generateRouteInfoJSON()
// Need to close solicited leaf nodes. The close has to be done outside of the server lock.
var leafs []*client
for _, c := range s.leafs {
c.mu.Lock()
if c.leaf != nil && c.leaf.remote != nil {
leafs = append(leafs, c)
}
c.mu.Unlock()
}
s.mu.Unlock()
// Also place into mapping cn with cnMu lock.
s.cnMu.Lock()
s.cn = name
s.cnMu.Unlock()
for _, l := range leafs {
l.closeConnection(ClusterNameConflict)
}
if resetCh != nil {
resetCh <- struct{}{}
}
s.Noticef("Cluster name updated to %s", name)
}
// Return whether the cluster name is dynamic.
func (s *Server) isClusterNameDynamic() bool {
return s.getOpts().Cluster.Name == _EMPTY_
}
// ClientURL returns the URL used to connect clients. Helpful in testing
// when we designate a random client port (-1).
func (s *Server) ClientURL() string {
// FIXME(dlc) - should we add in user and pass if defined single?
opts := s.getOpts()
scheme := "nats://"
if opts.TLSConfig != nil {
scheme = "tls://"
}
return fmt.Sprintf("%s%s:%d", scheme, opts.Host, opts.Port)
}
func validateCluster(o *Options) error {
if err := validatePinnedCerts(o.Cluster.TLSPinnedCerts); err != nil {
return fmt.Errorf("cluster: %v", err)
}
// Check that cluster name if defined matches any gateway name.
if o.Gateway.Name != "" && o.Gateway.Name != o.Cluster.Name {
if o.Cluster.Name != "" {
return ErrClusterNameConfigConflict
}
// Set this here so we do not consider it dynamic.
o.Cluster.Name = o.Gateway.Name
}
return nil
}
func validatePinnedCerts(pinned PinnedCertSet) error {
re := regexp.MustCompile("^[a-f0-9]{64}$")
for certId := range pinned {
entry := strings.ToLower(certId)
if !re.MatchString(entry) {
return fmt.Errorf("error parsing 'pinned_certs' key %s does not look like lower case hex-encoded sha256 of DER encoded SubjectPublicKeyInfo", entry)
}
}
return nil
}
func validateOptions(o *Options) error {
if o.LameDuckDuration > 0 && o.LameDuckGracePeriod >= o.LameDuckDuration {
return fmt.Errorf("lame duck grace period (%v) should be strictly lower than lame duck duration (%v)",
o.LameDuckGracePeriod, o.LameDuckDuration)
}
// Check that the trust configuration is correct.
if err := validateTrustedOperators(o); err != nil {
return err
}
// Check on leaf nodes which will require a system
// account when gateways are also configured.
if err := validateLeafNode(o); err != nil {
return err
}
// Check that authentication is properly configured.
if err := validateAuth(o); err != nil {
return err
}
// Check that gateway is properly configured. Returns no error
// if there is no gateway defined.
if err := validateGatewayOptions(o); err != nil {
return err
}
// Check that cluster name if defined matches any gateway name.
if err := validateCluster(o); err != nil {
return err
}
if err := validateMQTTOptions(o); err != nil {
return err
}
if err := validateJetStreamOptions(o); err != nil {
return err
}
// Finally check websocket options.
return validateWebsocketOptions(o)
}
func (s *Server) getOpts() *Options {
s.optsMu.RLock()
opts := s.opts
s.optsMu.RUnlock()
return opts
}
func (s *Server) setOpts(opts *Options) {
s.optsMu.Lock()
s.opts = opts
s.optsMu.Unlock()
}
func (s *Server) globalAccount() *Account {
s.mu.Lock()
gacc := s.gacc
s.mu.Unlock()
return gacc
}
// Used to setup Accounts.
// Lock is held upon entry.
func (s *Server) configureAccounts() error {
// Create the global account.
if s.gacc == nil {
s.gacc = NewAccount(globalAccountName)
s.registerAccountNoLock(s.gacc)
}
opts := s.opts
// Check opts and walk through them. We need to copy them here
// so that we do not keep a real one sitting in the options.
for _, acc := range s.opts.Accounts {
var a *Account
if acc.Name == globalAccountName {
a = s.gacc
} else {
a = acc.shallowCopy()
}
if acc.hasMappings() {
// For now just move and wipe from opts.Accounts version.
a.mappings = acc.mappings
acc.mappings = nil
// We use this for selecting between multiple weighted destinations.
a.prand = rand.New(rand.NewSource(time.Now().UnixNano()))
}
acc.sl = nil
acc.clients = nil
s.registerAccountNoLock(a)
// If we see an account defined using $SYS we will make sure that is set as system account.
if acc.Name == DEFAULT_SYSTEM_ACCOUNT && opts.SystemAccount == _EMPTY_ {
s.opts.SystemAccount = DEFAULT_SYSTEM_ACCOUNT
}
}
// Now that we have this we need to remap any referenced accounts in
// import or export maps to the new ones.
swapApproved := func(ea *exportAuth) {
for sub, a := range ea.approved {
var acc *Account
if v, ok := s.accounts.Load(a.Name); ok {
acc = v.(*Account)
}
ea.approved[sub] = acc
}
}
var numAccounts int
s.accounts.Range(func(k, v interface{}) bool {
numAccounts++
acc := v.(*Account)
// Exports
for _, se := range acc.exports.streams {
if se != nil {
swapApproved(&se.exportAuth)
}
}
for _, se := range acc.exports.services {
if se != nil {
// Swap over the bound account for service exports.
if se.acc != nil {
if v, ok := s.accounts.Load(se.acc.Name); ok {
se.acc = v.(*Account)
}
}
swapApproved(&se.exportAuth)
}
}
// Imports
for _, si := range acc.imports.streams {
if v, ok := s.accounts.Load(si.acc.Name); ok {
si.acc = v.(*Account)
}
}
for _, si := range acc.imports.services {
if v, ok := s.accounts.Load(si.acc.Name); ok {
si.acc = v.(*Account)
si.se = si.acc.getServiceExport(si.to)
}
}
// Make sure the subs are running, but only if not reloading.
if len(acc.imports.services) > 0 && acc.ic == nil && !s.reloading {
acc.ic = s.createInternalAccountClient()
acc.ic.acc = acc
acc.addAllServiceImportSubs()
}
acc.updated = time.Now().UTC()
return true
})
// Set the system account if it was configured.
// Otherwise create a default one.
if opts.SystemAccount != _EMPTY_ {
// Lock may be acquired in lookupAccount, so release to call lookupAccount.
s.mu.Unlock()
acc, err := s.lookupAccount(opts.SystemAccount)
s.mu.Lock()
if err == nil && s.sys != nil && acc != s.sys.account {
// sys.account.clients (including internal client)/respmap/etc... are transferred separately
s.sys.account = acc
s.mu.Unlock()
// acquires server lock separately
s.addSystemAccountExports(acc)
s.mu.Lock()
}
if err != nil {
return fmt.Errorf("error resolving system account: %v", err)
}
// If we have defined a system account here check to see if its just us and the $G account.
// We would do this to add user/pass to the system account. If this is the case add in
// no-auth-user for $G.
if numAccounts == 2 && s.opts.NoAuthUser == _EMPTY_ {
// If we come here from config reload, let's not recreate the fake user name otherwise
// it will cause currently clients to be disconnected.
uname := s.sysAccOnlyNoAuthUser
if uname == _EMPTY_ {
// Create a unique name so we do not collide.
var b [8]byte
rn := rand.Int63()
for i, l := 0, rn; i < len(b); i++ {
b[i] = digits[l%base]
l /= base
}
uname = fmt.Sprintf("nats-%s", b[:])
s.sysAccOnlyNoAuthUser = uname
}
s.opts.Users = append(s.opts.Users, &User{Username: uname, Password: uname[6:], Account: s.gacc})
s.opts.NoAuthUser = uname
}
}
return nil
}
// Setup the account resolver. For memory resolver, make sure the JWTs are
// properly formed but do not enforce expiration etc.
func (s *Server) configureResolver() error {
opts := s.getOpts()
s.accResolver = opts.AccountResolver
if opts.AccountResolver != nil {
// For URL resolver, set the TLSConfig if specified.
if opts.AccountResolverTLSConfig != nil {
if ar, ok := opts.AccountResolver.(*URLAccResolver); ok {
if t, ok := ar.c.Transport.(*http.Transport); ok {
t.CloseIdleConnections()
t.TLSClientConfig = opts.AccountResolverTLSConfig.Clone()
}
}
}
if len(opts.resolverPreloads) > 0 {
if s.accResolver.IsReadOnly() {
return fmt.Errorf("resolver preloads only available for writeable resolver types MEM/DIR/CACHE_DIR")
}
for k, v := range opts.resolverPreloads {
_, err := jwt.DecodeAccountClaims(v)
if err != nil {
return fmt.Errorf("preload account error for %q: %v", k, err)
}
s.accResolver.Store(k, v)
}
}
}
return nil
}
// This will check preloads for validation issues.
func (s *Server) checkResolvePreloads() {
opts := s.getOpts()
// We can just check the read-only opts versions here, that way we do not need
// to grab server lock or access s.accResolver.
for k, v := range opts.resolverPreloads {
claims, err := jwt.DecodeAccountClaims(v)
if err != nil {
s.Errorf("Preloaded account [%s] not valid", k)
continue
}
// Check if it is expired.
vr := jwt.CreateValidationResults()
claims.Validate(vr)
if vr.IsBlocking(true) {
s.Warnf("Account [%s] has validation issues:", k)
for _, v := range vr.Issues {
s.Warnf(" - %s", v.Description)
}
}
}
}
func (s *Server) generateRouteInfoJSON() {
b, _ := json.Marshal(s.routeInfo)
pcs := [][]byte{[]byte("INFO"), b, []byte(CR_LF)}
s.routeInfoJSON = bytes.Join(pcs, []byte(" "))
}
// Determines if we are in pre NATS 2.0 setup with no accounts.
func (s *Server) globalAccountOnly() bool {
var hasOthers bool
if s.trustedKeys != nil {
return false
}
s.mu.Lock()
s.accounts.Range(func(k, v interface{}) bool {
acc := v.(*Account)
// Ignore global and system
if acc == s.gacc || (s.sys != nil && acc == s.sys.account) {
return true
}
hasOthers = true
return false
})
s.mu.Unlock()
return !hasOthers
}
// Determines if this server is in standalone mode, meaning no routes or gateways.
func (s *Server) standAloneMode() bool {
opts := s.getOpts()
return opts.Cluster.Port == 0 && opts.Gateway.Port == 0
}
func (s *Server) configuredRoutes() int {
return len(s.getOpts().Routes)
}
// activePeers is used in bootstrapping raft groups like the JetStream meta controller.
func (s *Server) ActivePeers() (peers []string) {
s.nodeToInfo.Range(func(k, v interface{}) bool {
si := v.(nodeInfo)
if !si.offline {
peers = append(peers, k.(string))
}
return true
})
return peers
}
// isTrustedIssuer will check that the issuer is a trusted public key.
// This is used to make sure an account was signed by a trusted operator.
func (s *Server) isTrustedIssuer(issuer string) bool {
s.mu.Lock()
defer s.mu.Unlock()
// If we are not running in trusted mode and there is no issuer, that is ok.
if s.trustedKeys == nil && issuer == "" {
return true
}
for _, tk := range s.trustedKeys {
if tk == issuer {
return true
}
}
return false
}
// processTrustedKeys will process binary stamped and
// options-based trusted nkeys. Returns success.
func (s *Server) processTrustedKeys() bool {
s.strictSigningKeyUsage = map[string]struct{}{}
if trustedKeys != "" && !s.initStampedTrustedKeys() {
return false
} else if s.opts.TrustedKeys != nil {
for _, key := range s.opts.TrustedKeys {
if !nkeys.IsValidPublicOperatorKey(key) {
return false
}
}
s.trustedKeys = append([]string(nil), s.opts.TrustedKeys...)
for _, claim := range s.opts.TrustedOperators {
if !claim.StrictSigningKeyUsage {
continue
}
for _, key := range claim.SigningKeys {
s.strictSigningKeyUsage[key] = struct{}{}
}
}
}
return true
}
// checkTrustedKeyString will check that the string is a valid array
// of public operator nkeys.
func checkTrustedKeyString(keys string) []string {
tks := strings.Fields(keys)
if len(tks) == 0 {
return nil
}
// Walk all the keys and make sure they are valid.
for _, key := range tks {
if !nkeys.IsValidPublicOperatorKey(key) {
return nil
}
}
return tks
}
// initStampedTrustedKeys will check the stamped trusted keys
// and will set the server field 'trustedKeys'. Returns whether
// it succeeded or not.
func (s *Server) initStampedTrustedKeys() bool {
// Check to see if we have an override in options, which will cause us to fail.
if len(s.opts.TrustedKeys) > 0 {
return false
}
tks := checkTrustedKeyString(trustedKeys)
if len(tks) == 0 {
return false
}
s.trustedKeys = tks
return true
}
// PrintAndDie is exported for access in other packages.
func PrintAndDie(msg string) {
fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
}
// PrintServerAndExit will print our version and exit.
func PrintServerAndExit() {
fmt.Printf("nats-server: v%s\n", VERSION)
os.Exit(0)
}
// ProcessCommandLineArgs takes the command line arguments
// validating and setting flags for handling in case any
// sub command was present.
func ProcessCommandLineArgs(cmd *flag.FlagSet) (showVersion bool, showHelp bool, err error) {
if len(cmd.Args()) > 0 {
arg := cmd.Args()[0]
switch strings.ToLower(arg) {
case "version":
return true, false, nil
case "help":
return false, true, nil
default:
return false, false, fmt.Errorf("unrecognized command: %q", arg)
}
}
return false, false, nil
}
// Public version.
func (s *Server) Running() bool {
return s.isRunning()
}
// Protected check on running state
func (s *Server) isRunning() bool {
s.mu.Lock()
running := s.running
s.mu.Unlock()
return running
}
func (s *Server) logPid() error {
pidStr := strconv.Itoa(os.Getpid())
return ioutil.WriteFile(s.getOpts().PidFile, []byte(pidStr), 0660)
}
// NewAccountsAllowed returns whether or not new accounts can be created on the fly.
func (s *Server) NewAccountsAllowed() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.opts.AllowNewAccounts
}
// numReservedAccounts will return the number of reserved accounts configured in the server.
// Currently this is 1, one for the global default account.
func (s *Server) numReservedAccounts() int {
return 1
}
// NumActiveAccounts reports number of active accounts on this server.
func (s *Server) NumActiveAccounts() int32 {
return atomic.LoadInt32(&s.activeAccounts)
}
// incActiveAccounts() just adds one under lock.
func (s *Server) incActiveAccounts() {
atomic.AddInt32(&s.activeAccounts, 1)
}
// decActiveAccounts() just subtracts one under lock.
func (s *Server) decActiveAccounts() {
atomic.AddInt32(&s.activeAccounts, -1)
}
// This should be used for testing only. Will be slow since we have to
// range over all accounts in the sync.Map to count.
func (s *Server) numAccounts() int {
count := 0
s.mu.Lock()
s.accounts.Range(func(k, v interface{}) bool {
count++
return true
})
s.mu.Unlock()
return count
}
// NumLoadedAccounts returns the number of loaded accounts.
func (s *Server) NumLoadedAccounts() int {
return s.numAccounts()
}
// LookupOrRegisterAccount will return the given account if known or create a new entry.
func (s *Server) LookupOrRegisterAccount(name string) (account *Account, isNew bool) {
s.mu.Lock()
defer s.mu.Unlock()
if v, ok := s.accounts.Load(name); ok {
return v.(*Account), false
}
acc := NewAccount(name)
s.registerAccountNoLock(acc)
return acc, true
}
// RegisterAccount will register an account. The account must be new
// or this call will fail.
func (s *Server) RegisterAccount(name string) (*Account, error) {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.accounts.Load(name); ok {
return nil, ErrAccountExists
}
acc := NewAccount(name)
s.registerAccountNoLock(acc)
return acc, nil
}
// SetSystemAccount will set the internal system account.
// If root operators are present it will also check validity.
func (s *Server) SetSystemAccount(accName string) error {
// Lookup from sync.Map first.
if v, ok := s.accounts.Load(accName); ok {
return s.setSystemAccount(v.(*Account))
}
// If we are here we do not have local knowledge of this account.
// Do this one by hand to return more useful error.
ac, jwt, err := s.fetchAccountClaims(accName)
if err != nil {
return err
}
acc := s.buildInternalAccount(ac)
acc.claimJWT = jwt
// Due to race, we need to make sure that we are not
// registering twice.
if racc := s.registerAccount(acc); racc != nil {
return nil
}
return s.setSystemAccount(acc)
}
// SystemAccount returns the system account if set.
func (s *Server) SystemAccount() *Account {
var sacc *Account
s.mu.Lock()
if s.sys != nil {
sacc = s.sys.account
}
s.mu.Unlock()
return sacc
}
// GlobalAccount returns the global account.
// Default clients will use the global account.
func (s *Server) GlobalAccount() *Account {
s.mu.Lock()
defer s.mu.Unlock()
return s.gacc
}
// SetDefaultSystemAccount will create a default system account if one is not present.
func (s *Server) SetDefaultSystemAccount() error {
if _, isNew := s.LookupOrRegisterAccount(DEFAULT_SYSTEM_ACCOUNT); !isNew {
return nil
}
s.Debugf("Created system account: %q", DEFAULT_SYSTEM_ACCOUNT)
return s.SetSystemAccount(DEFAULT_SYSTEM_ACCOUNT)
}
// For internal sends.
const internalSendQLen = 256 * 1024
// Assign a system account. Should only be called once.
// This sets up a server to send and receive messages from
// inside the server itself.
func (s *Server) setSystemAccount(acc *Account) error {
if acc == nil {
return ErrMissingAccount
}
// Don't try to fix this here.
if acc.IsExpired() {
return ErrAccountExpired
}
// If we are running with trusted keys for an operator
// make sure we check the account is legit.
if !s.isTrustedIssuer(acc.Issuer) {
return ErrAccountValidation
}
s.mu.Lock()
if s.sys != nil {
s.mu.Unlock()
return ErrAccountExists
}
// This is here in an attempt to quiet the race detector and not have to place
// locks on fast path for inbound messages and checking service imports.
acc.mu.Lock()
if acc.imports.services == nil {
acc.imports.services = make(map[string]*serviceImport)
}
acc.mu.Unlock()
s.sys = &internal{
account: acc,
client: s.createInternalSystemClient(),
seq: 1,
sid: 1,
servers: make(map[string]*serverUpdate),
replies: make(map[string]msgHandler),
sendq: make(chan *pubMsg, internalSendQLen),
resetCh: make(chan struct{}),
sq: s.newSendQ(),
statsz: eventsHBInterval,
orphMax: 5 * eventsHBInterval,
chkOrph: 3 * eventsHBInterval,
}
s.sys.wg.Add(1)
s.mu.Unlock()
// Register with the account.
s.sys.client.registerWithAccount(acc)
s.addSystemAccountExports(acc)
// Start our internal loop to serialize outbound messages.
// We do our own wg here since we will stop first during shutdown.
go s.internalSendLoop(&s.sys.wg)
// Start up our general subscriptions
s.initEventTracking()
// Track for dead remote servers.
s.wrapChk(s.startRemoteServerSweepTimer)()
// Send out statsz updates periodically.
s.wrapChk(s.startStatszTimer)()
// If we have existing accounts make sure we enable account tracking.
s.mu.Lock()
s.accounts.Range(func(k, v interface{}) bool {
acc := v.(*Account)
s.enableAccountTracking(acc)
return true
})
s.mu.Unlock()
return nil
}
// Creates an internal system client.
func (s *Server) createInternalSystemClient() *client {
return s.createInternalClient(SYSTEM)
}
// Creates an internal jetstream client.
func (s *Server) createInternalJetStreamClient() *client {
return s.createInternalClient(JETSTREAM)
}
// Creates an internal client for Account.
func (s *Server) createInternalAccountClient() *client {
return s.createInternalClient(ACCOUNT)
}
// Internal clients. kind should be SYSTEM or JETSTREAM
func (s *Server) createInternalClient(kind int) *client {
if kind != SYSTEM && kind != JETSTREAM && kind != ACCOUNT {
return nil
}
now := time.Now().UTC()
c := &client{srv: s, kind: kind, opts: internalOpts, msubs: -1, mpay: -1, start: now, last: now}
c.initClient()
c.echo = false
c.headers = true
c.flags.set(noReconnect)
return c
}
// Determine if accounts should track subscriptions for
// efficient propagation.
// Lock should be held on entry.
func (s *Server) shouldTrackSubscriptions() bool {
return (s.opts.Cluster.Port != 0 || s.opts.Gateway.Port != 0)
}
// Invokes registerAccountNoLock under the protection of the server lock.
// That is, server lock is acquired/released in this function.
// See registerAccountNoLock for comment on returned value.
func (s *Server) registerAccount(acc *Account) *Account {
s.mu.Lock()
racc := s.registerAccountNoLock(acc)
s.mu.Unlock()
return racc
}
// Helper to set the sublist based on preferences.
func (s *Server) setAccountSublist(acc *Account) {
if acc != nil && acc.sl == nil {
opts := s.getOpts()
if opts != nil && opts.NoSublistCache {
acc.sl = NewSublistNoCache()
} else {
acc.sl = NewSublistWithCache()
}
}
}
// Registers an account in the server.
// Due to some locking considerations, we may end-up trying
// to register the same account twice. This function will
// then return the already registered account.
// Lock should be held on entry.
func (s *Server) registerAccountNoLock(acc *Account) *Account {
// We are under the server lock. Lookup from map, if present
// return existing account.
if a, _ := s.accounts.Load(acc.Name); a != nil {
s.tmpAccounts.Delete(acc.Name)
return a.(*Account)
}
// Finish account setup and store.
s.setAccountSublist(acc)
acc.mu.Lock()
if acc.clients == nil {
acc.clients = make(map[*client]struct{})
}
// If we are capable of routing we will track subscription
// information for efficient interest propagation.
// During config reload, it is possible that account was
// already created (global account), so use locking and
// make sure we create only if needed.
// TODO(dlc)- Double check that we need this for GWs.
if acc.rm == nil && s.opts != nil && s.shouldTrackSubscriptions() {
acc.rm = make(map[string]int32)
acc.lqws = make(map[string]int32)
}
acc.srv = s
acc.updated = time.Now().UTC()
acc.mu.Unlock()
s.accounts.Store(acc.Name, acc)
s.tmpAccounts.Delete(acc.Name)
s.enableAccountTracking(acc)
return nil
}
// lookupAccount is a function to return the account structure
// associated with an account name.
// Lock MUST NOT be held upon entry.
func (s *Server) lookupAccount(name string) (*Account, error) {
var acc *Account
if v, ok := s.accounts.Load(name); ok {
acc = v.(*Account)
}
if acc != nil {
// If we are expired and we have a resolver, then
// return the latest information from the resolver.
if acc.IsExpired() {
s.Debugf("Requested account [%s] has expired", name)
if s.AccountResolver() != nil {
if err := s.updateAccount(acc); err != nil {
// This error could mask expired, so just return expired here.
return nil, ErrAccountExpired
}
} else {
return nil, ErrAccountExpired
}
}
return acc, nil
}
// If we have a resolver see if it can fetch the account.
if s.AccountResolver() == nil {
return nil, ErrMissingAccount
}
return s.fetchAccount(name)
}
// LookupAccount is a public function to return the account structure
// associated with name.
func (s *Server) LookupAccount(name string) (*Account, error) {
return s.lookupAccount(name)
}
// This will fetch new claims and if found update the account with new claims.
// Lock MUST NOT be held upon entry.
func (s *Server) updateAccount(acc *Account) error {
// TODO(dlc) - Make configurable
if !acc.incomplete && time.Since(acc.updated) < time.Second {
s.Debugf("Requested account update for [%s] ignored, too soon", acc.Name)
return ErrAccountResolverUpdateTooSoon
}
claimJWT, err := s.fetchRawAccountClaims(acc.Name)
if err != nil {
return err
}
return s.updateAccountWithClaimJWT(acc, claimJWT)
}
// updateAccountWithClaimJWT will check and apply the claim update.
// Lock MUST NOT be held upon entry.
func (s *Server) updateAccountWithClaimJWT(acc *Account, claimJWT string) error {
if acc == nil {
return ErrMissingAccount
}
acc.mu.RLock()
sameClaim := acc.claimJWT != "" && acc.claimJWT == claimJWT && !acc.incomplete
acc.mu.RUnlock()
if sameClaim {
s.Debugf("Requested account update for [%s], same claims detected", acc.Name)
return nil
}
accClaims, _, err := s.verifyAccountClaims(claimJWT)
if err == nil && accClaims != nil {
acc.mu.Lock()
if acc.Issuer == "" {
acc.Issuer = accClaims.Issuer
}
if acc.Name != accClaims.Subject {
acc.mu.Unlock()
return ErrAccountValidation
}
acc.mu.Unlock()
s.UpdateAccountClaims(acc, accClaims)
acc.mu.Lock()
// needs to be set after update completed.
// This causes concurrent calls to return with sameClaim=true if the change is effective.
acc.claimJWT = claimJWT
acc.mu.Unlock()
return nil
}
return err
}
// fetchRawAccountClaims will grab raw account claims iff we have a resolver.
// Lock is NOT held upon entry.
func (s *Server) fetchRawAccountClaims(name string) (string, error) {
accResolver := s.AccountResolver()
if accResolver == nil {
return _EMPTY_, ErrNoAccountResolver
}
// Need to do actual Fetch
start := time.Now()
claimJWT, err := fetchAccount(accResolver, name)
fetchTime := time.Since(start)
if fetchTime > time.Second {
s.Warnf("Account [%s] fetch took %v", name, fetchTime)
} else {
s.Debugf("Account [%s] fetch took %v", name, fetchTime)
}
if err != nil {
s.Warnf("Account fetch failed: %v", err)
return "", err
}
return claimJWT, nil
}
// fetchAccountClaims will attempt to fetch new claims if a resolver is present.
// Lock is NOT held upon entry.
func (s *Server) fetchAccountClaims(name string) (*jwt.AccountClaims, string, error) {
claimJWT, err := s.fetchRawAccountClaims(name)
if err != nil {
return nil, _EMPTY_, err
}
var claim *jwt.AccountClaims
claim, claimJWT, err = s.verifyAccountClaims(claimJWT)
if claim != nil && claim.Subject != name {
return nil, _EMPTY_, ErrAccountValidation
}
return claim, claimJWT, err
}
// verifyAccountClaims will decode and validate any account claims.
func (s *Server) verifyAccountClaims(claimJWT string) (*jwt.AccountClaims, string, error) {
accClaims, err := jwt.DecodeAccountClaims(claimJWT)
if err != nil {
return nil, _EMPTY_, err
}
if !s.isTrustedIssuer(accClaims.Issuer) {
return nil, _EMPTY_, ErrAccountValidation
}
vr := jwt.CreateValidationResults()
accClaims.Validate(vr)
if vr.IsBlocking(true) {
return nil, _EMPTY_, ErrAccountValidation
}
return accClaims, claimJWT, nil
}
// This will fetch an account from a resolver if defined.
// Lock is NOT held upon entry.
func (s *Server) fetchAccount(name string) (*Account, error) {
accClaims, claimJWT, err := s.fetchAccountClaims(name)
if accClaims == nil {
return nil, err
}
acc := s.buildInternalAccount(accClaims)
acc.claimJWT = claimJWT
// Due to possible race, if registerAccount() returns a non
// nil account, it means the same account was already
// registered and we should use this one.
if racc := s.registerAccount(acc); racc != nil {
// Update with the new claims in case they are new.
if err = s.updateAccountWithClaimJWT(racc, claimJWT); err != nil {
return nil, err
}
return racc, nil
}
// The sub imports may have been setup but will not have had their
// subscriptions properly setup. Do that here.
if len(acc.imports.services) > 0 {
if acc.ic == nil {
acc.ic = s.createInternalAccountClient()
acc.ic.acc = acc
}
acc.addAllServiceImportSubs()
}
return acc, nil
}
// Start up the server, this will block.
// Start via a Go routine if needed.
func (s *Server) Start() {
s.Noticef("Starting nats-server")
gc := gitCommit
if gc == "" {
gc = "not set"
}
// Snapshot server options.
opts := s.getOpts()
s.Noticef(" Version: %s", VERSION)
s.Noticef(" Git: [%s]", gc)
s.Debugf(" Go build: %s", s.info.GoVersion)
s.Noticef(" Name: %s", s.info.Name)
if opts.JetStream {
s.Noticef(" Node: %s", getHash(s.info.Name))
}
s.Noticef(" ID: %s", s.info.ID)
defer s.Noticef("Server is ready")
// Check for insecure configurations.
s.checkAuthforWarnings()
// Avoid RACE between Start() and Shutdown()
s.mu.Lock()
s.running = true
s.mu.Unlock()
s.grMu.Lock()
s.grRunning = true
s.grMu.Unlock()
if opts.ConfigFile != _EMPTY_ {
s.Noticef("Using configuration file: %s", opts.ConfigFile)
}
hasOperators := len(opts.TrustedOperators) > 0
if hasOperators {
s.Noticef("Trusted Operators")
}
for _, opc := range opts.TrustedOperators {
s.Noticef(" System : %q", opc.Audience)
s.Noticef(" Operator: %q", opc.Name)
s.Noticef(" Issued : %v", time.Unix(opc.IssuedAt, 0))
s.Noticef(" Expires : %v", time.Unix(opc.Expires, 0))
}
if hasOperators && opts.SystemAccount == _EMPTY_ {
s.Warnf("Trusted Operators should utilize a System Account")
}
// If we have a memory resolver, check the accounts here for validation exceptions.
// This allows them to be logged right away vs when they are accessed via a client.
if hasOperators && len(opts.resolverPreloads) > 0 {
s.checkResolvePreloads()
}
// Log the pid to a file
if opts.PidFile != _EMPTY_ {
if err := s.logPid(); err != nil {
s.Fatalf("Could not write pidfile: %v", err)
return
}
}
// Setup system account which will start the eventing stack.
if sa := opts.SystemAccount; sa != _EMPTY_ {
if err := s.SetSystemAccount(sa); err != nil {
s.Fatalf("Can't set system account: %v", err)
return
}
} else if !opts.NoSystemAccount {
// We will create a default system account here.
s.SetDefaultSystemAccount()
}
// start up resolver machinery
if ar := s.AccountResolver(); ar != nil {
if err := ar.Start(s); err != nil {
s.Fatalf("Could not start resolver: %v", err)
return
}
// In operator mode, when the account resolver depends on an external system and
// the system account is the bootstrapping account, start fetching it
if len(opts.TrustedOperators) == 1 && opts.SystemAccount != _EMPTY_ && opts.SystemAccount != DEFAULT_SYSTEM_ACCOUNT {
_, isMemResolver := ar.(*MemAccResolver)
if v, ok := s.accounts.Load(s.opts.SystemAccount); !isMemResolver && ok && v.(*Account).claimJWT == "" {
s.Noticef("Using bootstrapping system account")
s.startGoRoutine(func() {
defer s.grWG.Done()
t := time.NewTicker(time.Second)
defer t.Stop()
for {
select {
case <-s.quitCh:
return
case <-t.C:
if _, err := fetchAccount(ar, s.opts.SystemAccount); err != nil {
continue
}
if _, err := s.fetchAccount(s.opts.SystemAccount); err != nil {
continue
}
s.Noticef("System account fetched and updated")
return
}
}
})
}
}
}
// Start expiration of mapped GW replies, regardless if
// this server is configured with gateway or not.
s.startGWReplyMapExpiration()
// Check if JetStream has been enabled. This needs to be after
// the system account setup above. JetStream will create its
// own system account if one is not present.
if opts.JetStream {
// Make sure someone is not trying to enable on the system account.
if sa := s.SystemAccount(); sa != nil && sa.jsLimits != nil {
s.Fatalf("Not allowed to enable JetStream on the system account")
}
cfg := &JetStreamConfig{
StoreDir: opts.StoreDir,
MaxMemory: opts.JetStreamMaxMemory,
MaxStore: opts.JetStreamMaxStore,
Domain: opts.JetStreamDomain,
}
if err := s.EnableJetStream(cfg); err != nil {
s.Fatalf("Can't start JetStream: %v", err)
return
}
} else {
// Check to see if any configured accounts have JetStream enabled.
s.accounts.Range(func(k, v interface{}) bool {
acc := v.(*Account)
acc.mu.RLock()
hasJs := acc.jsLimits != nil
acc.mu.RUnlock()
if hasJs {
s.checkJetStreamExports()
acc.enableAllJetStreamServiceImportsAndMappings()
}
return true
})
}
// Start OCSP Stapling monitoring for TLS certificates if enabled.
s.startOCSPMonitoring()
// Start monitoring if needed.
if err := s.StartMonitoring(); err != nil {
s.Fatalf("Can't start monitoring: %v", err)
return
}
// Start up gateway if needed. Do this before starting the routes, because
// we want to resolve the gateway host:port so that this information can
// be sent to other routes.
if opts.Gateway.Port != 0 {
s.startGateways()
}
// Start websocket server if needed. Do this before starting the routes, and
// leaf node because we want to resolve the gateway host:port so that this
// information can be sent to other routes.
if opts.Websocket.Port != 0 {
s.startWebsocketServer()
}
// Start up listen if we want to accept leaf node connections.
if opts.LeafNode.Port != 0 {
// Will resolve or assign the advertise address for the leafnode listener.
// We need that in StartRouting().
s.startLeafNodeAcceptLoop()
}
// Solicit remote servers for leaf node connections.
if len(opts.LeafNode.Remotes) > 0 {
s.solicitLeafNodeRemotes(opts.LeafNode.Remotes)
}
// TODO (ik): I wanted to refactor this by starting the client
// accept loop first, that is, it would resolve listen spec
// in place, but start the accept-for-loop in a different go
// routine. This would get rid of the synchronization between
// this function and StartRouting, which I also would have wanted
// to refactor, but both AcceptLoop() and StartRouting() have
// been exported and not sure if that would break users using them.
// We could mark them as deprecated and remove in a release or two...
// The Routing routine needs to wait for the client listen
// port to be opened and potential ephemeral port selected.
clientListenReady := make(chan struct{})
// MQTT
if opts.MQTT.Port != 0 {
s.startMQTT()
}
// Start up routing as well if needed.
if opts.Cluster.Port != 0 {
s.startGoRoutine(func() {
s.StartRouting(clientListenReady)
})
}
// Pprof http endpoint for the profiler.
if opts.ProfPort != 0 {
s.StartProfiler()
}
if opts.PortsFileDir != _EMPTY_ {
s.logPorts()
}
// Wait for clients.
s.AcceptLoop(clientListenReady)
}
// Shutdown will shutdown the server instance by kicking out the AcceptLoop
// and closing all associated clients.
func (s *Server) Shutdown() {
if s == nil {
return
}
// Transfer off any raft nodes that we are a leader by shutting them all down.
s.shutdownRaftNodes()
// This is for clustered JetStream and ephemeral consumers.
// No-op if not clustered or not running JetStream.
s.migrateEphemerals()
// Shutdown the eventing system as needed.
// This is done first to send out any messages for
// account status. We will also clean up any
// eventing items associated with accounts.
s.shutdownEventing()
s.mu.Lock()
// Prevent issues with multiple calls.
if s.shutdown {
s.mu.Unlock()
return
}
s.Noticef("Initiating Shutdown...")
accRes := s.accResolver
opts := s.getOpts()
s.shutdown = true
s.running = false
s.grMu.Lock()
s.grRunning = false
s.grMu.Unlock()
s.mu.Unlock()
if accRes != nil {
accRes.Close()
}
// Now check jetstream.
s.shutdownJetStream()
s.mu.Lock()
conns := make(map[uint64]*client)
// Copy off the clients
for i, c := range s.clients {
conns[i] = c
}
// Copy off the connections that are not yet registered
// in s.routes, but for which the readLoop has started
s.grMu.Lock()
for i, c := range s.grTmpClients {
conns[i] = c
}
s.grMu.Unlock()
// Copy off the routes
for i, r := range s.routes {
conns[i] = r
}
// Copy off the gateways
s.getAllGatewayConnections(conns)
// Copy off the leaf nodes
for i, c := range s.leafs {
conns[i] = c
}
// Number of done channel responses we expect.
doneExpected := 0
// Kick client AcceptLoop()
if s.listener != nil {
doneExpected++
s.listener.Close()
s.listener = nil
}
// Kick websocket server
if s.websocket.server != nil {
doneExpected++
s.websocket.server.Close()
s.websocket.server = nil
s.websocket.listener = nil
}
// Kick MQTT accept loop
if s.mqtt.listener != nil {
doneExpected++
s.mqtt.listener.Close()
s.mqtt.listener = nil
}
// Kick leafnodes AcceptLoop()
if s.leafNodeListener != nil {
doneExpected++
s.leafNodeListener.Close()
s.leafNodeListener = nil
}
// Kick route AcceptLoop()
if s.routeListener != nil {
doneExpected++
s.routeListener.Close()
s.routeListener = nil
}
// Kick Gateway AcceptLoop()
if s.gatewayListener != nil {
doneExpected++
s.gatewayListener.Close()
s.gatewayListener = nil
}
// Kick HTTP monitoring if its running
if s.http != nil {
doneExpected++
s.http.Close()
s.http = nil
}
// Kick Profiling if its running
if s.profiler != nil {
doneExpected++
s.profiler.Close()
}
s.mu.Unlock()
// Release go routines that wait on that channel
close(s.quitCh)
// Close client and route connections
for _, c := range conns {
c.setNoReconnect()
c.closeConnection(ServerShutdown)
}
// Block until the accept loops exit
for doneExpected > 0 {
<-s.done
doneExpected--
}
// Wait for go routines to be done.
s.grWG.Wait()
if opts.PortsFileDir != _EMPTY_ {
s.deletePortsFile(opts.PortsFileDir)
}
s.Noticef("Server Exiting..")
// Close logger if applicable. It allows tests on Windows
// to be able to do proper cleanup (delete log file).
s.logging.RLock()
log := s.logging.logger
s.logging.RUnlock()
if log != nil {
if l, ok := log.(*logger.Logger); ok {
l.Close()
}
}
// Notify that the shutdown is complete
close(s.shutdownComplete)
}
// WaitForShutdown will block until the server has been fully shutdown.
func (s *Server) WaitForShutdown() {
<-s.shutdownComplete
}
// AcceptLoop is exported for easier testing.
func (s *Server) AcceptLoop(clr chan struct{}) {
// If we were to exit before the listener is setup properly,
// make sure we close the channel.
defer func() {
if clr != nil {
close(clr)
}
}()
// Snapshot server options.
opts := s.getOpts()
// Setup state that can enable shutdown
s.mu.Lock()
if s.shutdown {
s.mu.Unlock()
return
}
hp := net.JoinHostPort(opts.Host, strconv.Itoa(opts.Port))
l, e := natsListen("tcp", hp)
s.listenerErr = e
if e != nil {
s.mu.Unlock()
s.Fatalf("Error listening on port: %s, %q", hp, e)
return
}
s.Noticef("Listening for client connections on %s",
net.JoinHostPort(opts.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
// Alert of TLS enabled.
if opts.TLSConfig != nil {
s.Noticef("TLS required for client connections")
}
// If server was started with RANDOM_PORT (-1), opts.Port would be equal
// to 0 at the beginning this function. So we need to get the actual port
if opts.Port == 0 {
// Write resolved port back to options.
opts.Port = l.Addr().(*net.TCPAddr).Port
}
// Now that port has been set (if it was set to RANDOM), set the
// server's info Host/Port with either values from Options or
// ClientAdvertise.
if err := s.setInfoHostPort(); err != nil {
s.Fatalf("Error setting server INFO with ClientAdvertise value of %s, err=%v", s.opts.ClientAdvertise, err)
l.Close()
s.mu.Unlock()
return
}
// Keep track of client connect URLs. We may need them later.
s.clientConnectURLs = s.getClientConnectURLs()
s.listener = l
go s.acceptConnections(l, "Client", func(conn net.Conn) { s.createClient(conn) },
func(_ error) bool {
if s.isLameDuckMode() {
// Signal that we are not accepting new clients
s.ldmCh <- true
// Now wait for the Shutdown...
<-s.quitCh
return true
}
return false
})
s.mu.Unlock()
// Let the caller know that we are ready
close(clr)
clr = nil
}
func (s *Server) acceptConnections(l net.Listener, acceptName string, createFunc func(conn net.Conn), errFunc func(err error) bool) {
tmpDelay := ACCEPT_MIN_SLEEP
for {
conn, err := l.Accept()
if err != nil {
if errFunc != nil && errFunc(err) {
return
}
if tmpDelay = s.acceptError(acceptName, err, tmpDelay); tmpDelay < 0 {
break
}
continue
}
tmpDelay = ACCEPT_MIN_SLEEP
if !s.startGoRoutine(func() {
createFunc(conn)
s.grWG.Done()
}) {
conn.Close()
}
}
s.Debugf(acceptName + " accept loop exiting..")
s.done <- true
}
// This function sets the server's info Host/Port based on server Options.
// Note that this function may be called during config reload, this is why
// Host/Port may be reset to original Options if the ClientAdvertise option
// is not set (since it may have previously been).
func (s *Server) setInfoHostPort() error {
// When this function is called, opts.Port is set to the actual listen
// port (if option was originally set to RANDOM), even during a config
// reload. So use of s.opts.Port is safe.
if s.opts.ClientAdvertise != _EMPTY_ {
h, p, err := parseHostPort(s.opts.ClientAdvertise, s.opts.Port)
if err != nil {
return err
}
s.info.Host = h
s.info.Port = p
} else {
s.info.Host = s.opts.Host
s.info.Port = s.opts.Port
}
return nil
}
// StartProfiler is called to enable dynamic profiling.
func (s *Server) StartProfiler() {
// Snapshot server options.
opts := s.getOpts()
port := opts.ProfPort
// Check for Random Port
if port == -1 {
port = 0
}
s.mu.Lock()
if s.shutdown {
s.mu.Unlock()
return
}
hp := net.JoinHostPort(opts.Host, strconv.Itoa(port))
l, err := net.Listen("tcp", hp)
if err != nil {
s.mu.Unlock()
s.Fatalf("error starting profiler: %s", err)
return
}
s.Noticef("profiling port: %d", l.Addr().(*net.TCPAddr).Port)
srv := &http.Server{
Addr: hp,
Handler: http.DefaultServeMux,
MaxHeaderBytes: 1 << 20,
}
s.profiler = l
s.profilingServer = srv
// Enable blocking profile
runtime.SetBlockProfileRate(1)
go func() {
// if this errors out, it's probably because the server is being shutdown
err := srv.Serve(l)
if err != nil {
s.mu.Lock()
shutdown := s.shutdown
s.mu.Unlock()
if !shutdown {
s.Fatalf("error starting profiler: %s", err)
}
}
srv.Close()
s.done <- true
}()
s.mu.Unlock()
}
// StartHTTPMonitoring will enable the HTTP monitoring port.
// DEPRECATED: Should use StartMonitoring.
func (s *Server) StartHTTPMonitoring() {
s.startMonitoring(false)
}
// StartHTTPSMonitoring will enable the HTTPS monitoring port.
// DEPRECATED: Should use StartMonitoring.
func (s *Server) StartHTTPSMonitoring() {
s.startMonitoring(true)
}
// StartMonitoring starts the HTTP or HTTPs server if needed.
func (s *Server) StartMonitoring() error {
// Snapshot server options.
opts := s.getOpts()
// Specifying both HTTP and HTTPS ports is a misconfiguration
if opts.HTTPPort != 0 && opts.HTTPSPort != 0 {
return fmt.Errorf("can't specify both HTTP (%v) and HTTPs (%v) ports", opts.HTTPPort, opts.HTTPSPort)
}
var err error
if opts.HTTPPort != 0 {
err = s.startMonitoring(false)
} else if opts.HTTPSPort != 0 {
if opts.TLSConfig == nil {
return fmt.Errorf("TLS cert and key required for HTTPS")
}
err = s.startMonitoring(true)
}
return err
}
// HTTP endpoints
const (
RootPath = "/"
VarzPath = "/varz"
ConnzPath = "/connz"
RoutezPath = "/routez"
GatewayzPath = "/gatewayz"
LeafzPath = "/leafz"
SubszPath = "/subsz"
StackszPath = "/stacksz"
AccountzPath = "/accountz"
JszPath = "/jsz"
)
func (s *Server) basePath(p string) string {
return path.Join(s.httpBasePath, p)
}
// Start the monitoring server
func (s *Server) startMonitoring(secure bool) error {
// Snapshot server options.
opts := s.getOpts()
var (
hp string
err error
httpListener net.Listener
port int
)
monitorProtocol := "http"
if secure {
monitorProtocol += "s"
port = opts.HTTPSPort
if port == -1 {
port = 0
}
hp = net.JoinHostPort(opts.HTTPHost, strconv.Itoa(port))
config := opts.TLSConfig.Clone()
config.ClientAuth = tls.NoClientCert
httpListener, err = tls.Listen("tcp", hp, config)
} else {
port = opts.HTTPPort
if port == -1 {
port = 0
}
hp = net.JoinHostPort(opts.HTTPHost, strconv.Itoa(port))
httpListener, err = net.Listen("tcp", hp)
}
if err != nil {
return fmt.Errorf("can't listen to the monitor port: %v", err)
}
s.Noticef("Starting %s monitor on %s", monitorProtocol,
net.JoinHostPort(opts.HTTPHost, strconv.Itoa(httpListener.Addr().(*net.TCPAddr).Port)))
mux := http.NewServeMux()
// Root
mux.HandleFunc(s.basePath(RootPath), s.HandleRoot)
// Varz
mux.HandleFunc(s.basePath(VarzPath), s.HandleVarz)
// Connz
mux.HandleFunc(s.basePath(ConnzPath), s.HandleConnz)
// Routez
mux.HandleFunc(s.basePath(RoutezPath), s.HandleRoutez)
// Gatewayz
mux.HandleFunc(s.basePath(GatewayzPath), s.HandleGatewayz)
// Leafz
mux.HandleFunc(s.basePath(LeafzPath), s.HandleLeafz)
// Subz
mux.HandleFunc(s.basePath(SubszPath), s.HandleSubsz)
// Subz alias for backwards compatibility
mux.HandleFunc(s.basePath("/subscriptionsz"), s.HandleSubsz)
// Stacksz
mux.HandleFunc(s.basePath(StackszPath), s.HandleStacksz)
// Accountz
mux.HandleFunc(s.basePath(AccountzPath), s.HandleAccountz)
// Jsz
mux.HandleFunc(s.basePath(JszPath), s.HandleJsz)
// Do not set a WriteTimeout because it could cause cURL/browser
// to return empty response or unable to display page if the
// server needs more time to build the response.
srv := &http.Server{
Addr: hp,
Handler: mux,
MaxHeaderBytes: 1 << 20,
}
s.mu.Lock()
if s.shutdown {
httpListener.Close()
s.mu.Unlock()
return nil
}
s.http = httpListener
s.httpHandler = mux
s.monitoringServer = srv
s.mu.Unlock()
go func() {
if err := srv.Serve(httpListener); err != nil {
s.mu.Lock()
shutdown := s.shutdown
s.mu.Unlock()
if !shutdown {
s.Fatalf("Error starting monitor on %q: %v", hp, err)
}
}
srv.Close()
srv.Handler = nil
s.mu.Lock()
s.httpHandler = nil
s.mu.Unlock()
s.done <- true
}()
return nil
}
// HTTPHandler returns the http.Handler object used to handle monitoring
// endpoints. It will return nil if the server is not configured for
// monitoring, or if the server has not been started yet (Server.Start()).
func (s *Server) HTTPHandler() http.Handler {
s.mu.Lock()
defer s.mu.Unlock()
return s.httpHandler
}
// Perform a conditional deep copy due to reference nature of [Client|WS]ConnectURLs.
// If updates are made to Info, this function should be consulted and updated.
// Assume lock is held.
func (s *Server) copyInfo() Info {
info := s.info
if len(info.ClientConnectURLs) > 0 {
info.ClientConnectURLs = append([]string(nil), s.info.ClientConnectURLs...)
}
if len(info.WSConnectURLs) > 0 {
info.WSConnectURLs = append([]string(nil), s.info.WSConnectURLs...)
}
return info
}
// tlsMixConn is used when we can receive both TLS and non-TLS connections on same port.
type tlsMixConn struct {
net.Conn
pre *bytes.Buffer
}
// Read for our mixed multi-reader.
func (c *tlsMixConn) Read(b []byte) (int, error) {
if c.pre != nil {
n, err := c.pre.Read(b)
if c.pre.Len() == 0 {
c.pre = nil
}
return n, err
}
return c.Conn.Read(b)
}
func (s *Server) createClient(conn net.Conn) *client {
// Snapshot server options.
opts := s.getOpts()
maxPay := int32(opts.MaxPayload)
maxSubs := int32(opts.MaxSubs)
// For system, maxSubs of 0 means unlimited, so re-adjust here.
if maxSubs == 0 {
maxSubs = -1
}
now := time.Now().UTC()
c := &client{srv: s, nc: conn, opts: defaultOpts, mpay: maxPay, msubs: maxSubs, start: now, last: now}
c.registerWithAccount(s.globalAccount())
var info Info
var authRequired bool
s.mu.Lock()
// Grab JSON info string
info = s.copyInfo()
if s.nonceRequired() {
// Nonce handling
var raw [nonceLen]byte
nonce := raw[:]
s.generateNonce(nonce)
info.Nonce = string(nonce)
}
c.nonce = []byte(info.Nonce)
authRequired = info.AuthRequired
s.totalClients++
s.mu.Unlock()
// Grab lock
c.mu.Lock()
if authRequired {
c.flags.set(expectConnect)
}
// Initialize
c.initClient()
c.Debugf("Client connection created")
// Send our information.
// Need to be sent in place since writeLoop cannot be started until
// TLS handshake is done (if applicable).
c.sendProtoNow(c.generateClientInfoJSON(info))
// Unlock to register
c.mu.Unlock()
// Register with the server.
s.mu.Lock()
// If server is not running, Shutdown() may have already gathered the
// list of connections to close. It won't contain this one, so we need
// to bail out now otherwise the readLoop started down there would not
// be interrupted. Skip also if in lame duck mode.
if !s.running || s.ldm {
// There are some tests that create a server but don't start it,
// and use "async" clients and perform the parsing manually. Such
// clients would branch here (since server is not running). However,
// when a server was really running and has been shutdown, we must
// close this connection.
if s.shutdown {
conn.Close()
}
s.mu.Unlock()
return c
}
// If there is a max connections specified, check that adding
// this new client would not push us over the max
if opts.MaxConn > 0 && len(s.clients) >= opts.MaxConn {
s.mu.Unlock()
c.maxConnExceeded()
return nil
}
s.clients[c.cid] = c
tlsRequired := info.TLSRequired
s.mu.Unlock()
// Re-Grab lock
c.mu.Lock()
// Connection could have been closed while sending the INFO proto.
isClosed := c.isClosed()
var pre []byte
// If we have both TLS and non-TLS allowed we need to see which
// one the client wants.
if !isClosed && opts.TLSConfig != nil && opts.AllowNonTLS {
pre = make([]byte, 4)
c.nc.SetReadDeadline(time.Now().Add(secondsToDuration(opts.TLSTimeout)))
n, _ := io.ReadFull(c.nc, pre[:])
c.nc.SetReadDeadline(time.Time{})
pre = pre[:n]
if n > 0 && pre[0] == 0x16 {
tlsRequired = true
} else {
tlsRequired = false
}
}
// Check for TLS
if !isClosed && tlsRequired {
// If we have a prebuffer create a multi-reader.
if len(pre) > 0 {
c.nc = &tlsMixConn{c.nc, bytes.NewBuffer(pre)}
// Clear pre so it is not parsed.
pre = nil
}
// Performs server-side TLS handshake.
if err := c.doTLSServerHandshake(_EMPTY_, opts.TLSConfig, opts.TLSTimeout, opts.TLSPinnedCerts); err != nil {
c.mu.Unlock()
return nil
}
}
// If connection is marked as closed, bail out.
if isClosed {
c.mu.Unlock()
// Connection could have been closed due to TLS timeout or while trying
// to send the INFO protocol. We need to call closeConnection() to make
// sure that proper cleanup is done.
c.closeConnection(WriteError)
return nil
}
// Check for Auth. We schedule this timer after the TLS handshake to avoid
// the race where the timer fires during the handshake and causes the
// server to write bad data to the socket. See issue #432.
if authRequired {
c.setAuthTimer(secondsToDuration(opts.AuthTimeout))
}
// Do final client initialization
// Set the Ping timer. Will be reset once connect was received.
c.setPingTimer()
// Spin up the read loop.
s.startGoRoutine(func() { c.readLoop(pre) })
// Spin up the write loop.
s.startGoRoutine(func() { c.writeLoop() })
if tlsRequired {
c.Debugf("TLS handshake complete")
cs := c.nc.(*tls.Conn).ConnectionState()
c.Debugf("TLS version %s, cipher suite %s", tlsVersion(cs.Version), tlsCipher(cs.CipherSuite))
}
c.mu.Unlock()
return c
}
// This will save off a closed client in a ring buffer such that
// /connz can inspect. Useful for debugging, etc.
func (s *Server) saveClosedClient(c *client, nc net.Conn, reason ClosedState) {
now := time.Now().UTC()
s.accountDisconnectEvent(c, now, reason.String())
c.mu.Lock()
cc := &closedClient{}
cc.fill(c, nc, now)
cc.Stop = &now
cc.Reason = reason.String()
// Do subs, do not place by default in main ConnInfo
if len(c.subs) > 0 {
cc.subs = make([]SubDetail, 0, len(c.subs))
for _, sub := range c.subs {
cc.subs = append(cc.subs, newSubDetail(sub))
}
}
// Hold user as well.
cc.user = c.opts.Username
// Hold account name if not the global account.
if c.acc != nil && c.acc.Name != globalAccountName {
cc.acc = c.acc.Name
}
cc.JWT = c.opts.JWT
cc.IssuerKey = issuerForClient(c)
cc.Tags = c.tags
cc.NameTag = c.nameTag
c.mu.Unlock()
// Place in the ring buffer
s.mu.Lock()
if s.closed != nil {
s.closed.append(cc)
}
s.mu.Unlock()
}
// Adds to the list of client and websocket clients connect URLs.
// If there was a change, an INFO protocol is sent to registered clients
// that support async INFO protocols.
func (s *Server) addConnectURLsAndSendINFOToClients(curls, wsurls []string) {
s.updateServerINFOAndSendINFOToClients(curls, wsurls, true)
}
// Removes from the list of client and websocket clients connect URLs.
// If there was a change, an INFO protocol is sent to registered clients
// that support async INFO protocols.
func (s *Server) removeConnectURLsAndSendINFOToClients(curls, wsurls []string) {
s.updateServerINFOAndSendINFOToClients(curls, wsurls, false)
}
// Updates the list of client and websocket clients connect URLs and if any change
// sends an async INFO update to clients that support it.
func (s *Server) updateServerINFOAndSendINFOToClients(curls, wsurls []string, add bool) {
s.mu.Lock()
defer s.mu.Unlock()
remove := !add
// Will return true if we need alter the server's Info object.
updateMap := func(urls []string, m refCountedUrlSet) bool {
wasUpdated := false
for _, url := range urls {
if add && m.addUrl(url) {
wasUpdated = true
} else if remove && m.removeUrl(url) {
wasUpdated = true
}
}
return wasUpdated
}
cliUpdated := updateMap(curls, s.clientConnectURLsMap)
wsUpdated := updateMap(wsurls, s.websocket.connectURLsMap)
updateInfo := func(infoURLs *[]string, urls []string, m refCountedUrlSet) {
// Recreate the info's slice from the map
*infoURLs = (*infoURLs)[:0]
// Add this server client connect ULRs first...
*infoURLs = append(*infoURLs, urls...)
// Then the ones from the map
for url := range m {
*infoURLs = append(*infoURLs, url)
}
}
if cliUpdated {
updateInfo(&s.info.ClientConnectURLs, s.clientConnectURLs, s.clientConnectURLsMap)
}
if wsUpdated {
updateInfo(&s.info.WSConnectURLs, s.websocket.connectURLs, s.websocket.connectURLsMap)
}
if cliUpdated || wsUpdated {
// Update the time of this update
s.lastCURLsUpdate = time.Now().UnixNano()
// Send to all registered clients that support async INFO protocols.
s.sendAsyncInfoToClients(cliUpdated, wsUpdated)
}
}
// Handle closing down a connection when the handshake has timedout.
func tlsTimeout(c *client, conn *tls.Conn) {
c.mu.Lock()
closed := c.isClosed()
c.mu.Unlock()
// Check if already closed
if closed {
return
}
cs := conn.ConnectionState()
if !cs.HandshakeComplete {
c.Errorf("TLS handshake timeout")
c.sendErr("Secure Connection - TLS Required")
c.closeConnection(TLSHandshakeError)
}
}
// Seems silly we have to write these
func tlsVersion(ver uint16) string {
switch ver {
case tls.VersionTLS10:
return "1.0"
case tls.VersionTLS11:
return "1.1"
case tls.VersionTLS12:
return "1.2"
case tls.VersionTLS13:
return "1.3"
}
return fmt.Sprintf("Unknown [0x%x]", ver)
}
// We use hex here so we don't need multiple versions
func tlsCipher(cs uint16) string {
name, present := cipherMapByID[cs]
if present {
return name
}
return fmt.Sprintf("Unknown [0x%x]", cs)
}
// Remove a client or route from our internal accounting.
func (s *Server) removeClient(c *client) {
// kind is immutable, so can check without lock
switch c.kind {
case CLIENT:
c.mu.Lock()
cid := c.cid
updateProtoInfoCount := false
if c.kind == CLIENT && c.opts.Protocol >= ClientProtoInfo {
updateProtoInfoCount = true
}
c.mu.Unlock()
s.mu.Lock()
delete(s.clients, cid)
if updateProtoInfoCount {
s.cproto--
}
s.mu.Unlock()
case ROUTER:
s.removeRoute(c)
case GATEWAY:
s.removeRemoteGatewayConnection(c)
case LEAF:
s.removeLeafNodeConnection(c)
}
}
func (s *Server) removeFromTempClients(cid uint64) {
s.grMu.Lock()
delete(s.grTmpClients, cid)
s.grMu.Unlock()
}
func (s *Server) addToTempClients(cid uint64, c *client) bool {
added := false
s.grMu.Lock()
if s.grRunning {
s.grTmpClients[cid] = c
added = true
}
s.grMu.Unlock()
return added
}
/////////////////////////////////////////////////////////////////
// These are some helpers for accounting in functional tests.
/////////////////////////////////////////////////////////////////
// NumRoutes will report the number of registered routes.
func (s *Server) NumRoutes() int {
s.mu.Lock()
nr := len(s.routes)
s.mu.Unlock()
return nr
}
// NumRemotes will report number of registered remotes.
func (s *Server) NumRemotes() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.remotes)
}
// NumLeafNodes will report number of leaf node connections.
func (s *Server) NumLeafNodes() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.leafs)
}
// NumClients will report the number of registered clients.
func (s *Server) NumClients() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.clients)
}
// GetClient will return the client associated with cid.
func (s *Server) GetClient(cid uint64) *client {
return s.getClient(cid)
}
// getClient will return the client associated with cid.
func (s *Server) getClient(cid uint64) *client {
s.mu.Lock()
defer s.mu.Unlock()
return s.clients[cid]
}
// GetLeafNode returns the leafnode associated with the cid.
func (s *Server) GetLeafNode(cid uint64) *client {
s.mu.Lock()
defer s.mu.Unlock()
return s.leafs[cid]
}
// NumSubscriptions will report how many subscriptions are active.
func (s *Server) NumSubscriptions() uint32 {
s.mu.Lock()
defer s.mu.Unlock()
return s.numSubscriptions()
}
// numSubscriptions will report how many subscriptions are active.
// Lock should be held.
func (s *Server) numSubscriptions() uint32 {
var subs int
s.accounts.Range(func(k, v interface{}) bool {
acc := v.(*Account)
if acc.sl != nil {
subs += acc.TotalSubs()
}
return true
})
return uint32(subs)
}
// NumSlowConsumers will report the number of slow consumers.
func (s *Server) NumSlowConsumers() int64 {
return atomic.LoadInt64(&s.slowConsumers)
}
// ConfigTime will report the last time the server configuration was loaded.
func (s *Server) ConfigTime() time.Time {
s.mu.Lock()
defer s.mu.Unlock()
return s.configTime
}
// Addr will return the net.Addr object for the current listener.
func (s *Server) Addr() net.Addr {
s.mu.Lock()
defer s.mu.Unlock()
if s.listener == nil {
return nil
}
return s.listener.Addr()
}
// MonitorAddr will return the net.Addr object for the monitoring listener.
func (s *Server) MonitorAddr() *net.TCPAddr {
s.mu.Lock()
defer s.mu.Unlock()
if s.http == nil {
return nil
}
return s.http.Addr().(*net.TCPAddr)
}
// ClusterAddr returns the net.Addr object for the route listener.
func (s *Server) ClusterAddr() *net.TCPAddr {
s.mu.Lock()
defer s.mu.Unlock()
if s.routeListener == nil {
return nil
}
return s.routeListener.Addr().(*net.TCPAddr)
}
// ProfilerAddr returns the net.Addr object for the profiler listener.
func (s *Server) ProfilerAddr() *net.TCPAddr {
s.mu.Lock()
defer s.mu.Unlock()
if s.profiler == nil {
return nil
}
return s.profiler.Addr().(*net.TCPAddr)
}
func (s *Server) readyForConnections(d time.Duration) error {
// Snapshot server options.
opts := s.getOpts()
type info struct {
ok bool
err error
}
chk := make(map[string]info)
end := time.Now().Add(d)
for time.Now().Before(end) {
s.mu.Lock()
chk["server"] = info{ok: s.listener != nil, err: s.listenerErr}
chk["route"] = info{ok: (opts.Cluster.Port == 0 || s.routeListener != nil), err: s.routeListenerErr}
chk["gateway"] = info{ok: (opts.Gateway.Name == "" || s.gatewayListener != nil), err: s.gatewayListenerErr}
chk["leafNode"] = info{ok: (opts.LeafNode.Port == 0 || s.leafNodeListener != nil), err: s.leafNodeListenerErr}
chk["websocket"] = info{ok: (opts.Websocket.Port == 0 || s.websocket.listener != nil), err: s.websocket.listenerErr}
chk["mqtt"] = info{ok: (opts.MQTT.Port == 0 || s.mqtt.listener != nil), err: s.mqtt.listenerErr}
s.mu.Unlock()
var numOK int
for _, inf := range chk {
if inf.ok {
numOK++
}
}
if numOK == len(chk) {
return nil
}
time.Sleep(25 * time.Millisecond)
}
failed := make([]string, 0, len(chk))
for name, inf := range chk {
if inf.ok && inf.err != nil {
failed = append(failed, fmt.Sprintf("%s(ok, but %s)", name, inf.err))
}
if !inf.ok && inf.err == nil {
failed = append(failed, name)
}
if !inf.ok && inf.err != nil {
failed = append(failed, fmt.Sprintf("%s(%s)", name, inf.err))
}
}
return fmt.Errorf(
"failed to be ready for connections after %s: %s",
d, strings.Join(failed, ", "),
)
}
// ReadyForConnections returns `true` if the server is ready to accept clients
// and, if routing is enabled, route connections. If after the duration
// `dur` the server is still not ready, returns `false`.
func (s *Server) ReadyForConnections(dur time.Duration) bool {
return s.readyForConnections(dur) == nil
}
// Quick utility to function to tell if the server supports headers.
func (s *Server) supportsHeaders() bool {
if s == nil {
return false
}
return !(s.getOpts().NoHeaderSupport)
}
// ID returns the server's ID
func (s *Server) ID() string {
return s.info.ID
}
// NodeName returns the node name for this server.
func (s *Server) NodeName() string {
return string(getHash(s.info.Name))
}
// Name returns the server's name. This will be the same as the ID if it was not set.
func (s *Server) Name() string {
return s.info.Name
}
func (s *Server) String() string {
return s.info.Name
}
func (s *Server) startGoRoutine(f func()) bool {
var started bool
s.grMu.Lock()
if s.grRunning {
s.grWG.Add(1)
go f()
started = true
}
s.grMu.Unlock()
return started
}
func (s *Server) numClosedConns() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.closed.len()
}
func (s *Server) totalClosedConns() uint64 {
s.mu.Lock()
defer s.mu.Unlock()
return s.closed.totalConns()
}
func (s *Server) closedClients() []*closedClient {
s.mu.Lock()
defer s.mu.Unlock()
return s.closed.closedClients()
}
// getClientConnectURLs returns suitable URLs for clients to connect to the listen
// port based on the server options' Host and Port. If the Host corresponds to
// "any" interfaces, this call returns the list of resolved IP addresses.
// If ClientAdvertise is set, returns the client advertise host and port.
// The server lock is assumed held on entry.
func (s *Server) getClientConnectURLs() []string {
// Snapshot server options.
opts := s.getOpts()
// Ignore error here since we know that if there is client advertise, the
// parseHostPort is correct because we did it right before calling this
// function in Server.New().
urls, _ := s.getConnectURLs(opts.ClientAdvertise, opts.Host, opts.Port)
return urls
}
// Generic version that will return an array of URLs based on the given
// advertise, host and port values.
func (s *Server) getConnectURLs(advertise, host string, port int) ([]string, error) {
urls := make([]string, 0, 1)
// short circuit if advertise is set
if advertise != "" {
h, p, err := parseHostPort(advertise, port)
if err != nil {
return nil, err
}
urls = append(urls, net.JoinHostPort(h, strconv.Itoa(p)))
} else {
sPort := strconv.Itoa(port)
_, ips, err := s.getNonLocalIPsIfHostIsIPAny(host, true)
for _, ip := range ips {
urls = append(urls, net.JoinHostPort(ip, sPort))
}
if err != nil || len(urls) == 0 {
// We are here if s.opts.Host is not "0.0.0.0" nor "::", or if for some
// reason we could not add any URL in the loop above.
// We had a case where a Windows VM was hosed and would have err == nil
// and not add any address in the array in the loop above, and we
// ended-up returning 0.0.0.0, which is problematic for Windows clients.
// Check for 0.0.0.0 or :: specifically, and ignore if that's the case.
if host == "0.0.0.0" || host == "::" {
s.Errorf("Address %q can not be resolved properly", host)
} else {
urls = append(urls, net.JoinHostPort(host, sPort))
}
}
}
return urls, nil
}
// Returns an array of non local IPs if the provided host is
// 0.0.0.0 or ::. It returns the first resolved if `all` is
// false.
// The boolean indicate if the provided host was 0.0.0.0 (or ::)
// so that if the returned array is empty caller can decide
// what to do next.
func (s *Server) getNonLocalIPsIfHostIsIPAny(host string, all bool) (bool, []string, error) {
ip := net.ParseIP(host)
// If this is not an IP, we are done
if ip == nil {
return false, nil, nil
}
// If this is not 0.0.0.0 or :: we have nothing to do.
if !ip.IsUnspecified() {
return false, nil, nil
}
s.Debugf("Get non local IPs for %q", host)
var ips []string
ifaces, _ := net.Interfaces()
for _, i := range ifaces {
addrs, _ := i.Addrs()
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
ipStr := ip.String()
// Skip non global unicast addresses
if !ip.IsGlobalUnicast() || ip.IsUnspecified() {
ip = nil
continue
}
s.Debugf(" ip=%s", ipStr)
ips = append(ips, ipStr)
if !all {
break
}
}
}
return true, ips, nil
}
// if the ip is not specified, attempt to resolve it
func resolveHostPorts(addr net.Listener) []string {
hostPorts := make([]string, 0)
hp := addr.Addr().(*net.TCPAddr)
port := strconv.Itoa(hp.Port)
if hp.IP.IsUnspecified() {
var ip net.IP
ifaces, _ := net.Interfaces()
for _, i := range ifaces {
addrs, _ := i.Addrs()
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
hostPorts = append(hostPorts, net.JoinHostPort(ip.String(), port))
case *net.IPAddr:
ip = v.IP
hostPorts = append(hostPorts, net.JoinHostPort(ip.String(), port))
default:
continue
}
}
}
} else {
hostPorts = append(hostPorts, net.JoinHostPort(hp.IP.String(), port))
}
return hostPorts
}
// format the address of a net.Listener with a protocol
func formatURL(protocol string, addr net.Listener) []string {
hostports := resolveHostPorts(addr)
for i, hp := range hostports {
hostports[i] = fmt.Sprintf("%s://%s", protocol, hp)
}
return hostports
}
// Ports describes URLs that the server can be contacted in
type Ports struct {
Nats []string `json:"nats,omitempty"`
Monitoring []string `json:"monitoring,omitempty"`
Cluster []string `json:"cluster,omitempty"`
Profile []string `json:"profile,omitempty"`
WebSocket []string `json:"websocket,omitempty"`
}
// PortsInfo attempts to resolve all the ports. If after maxWait the ports are not
// resolved, it returns nil. Otherwise it returns a Ports struct
// describing ports where the server can be contacted
func (s *Server) PortsInfo(maxWait time.Duration) *Ports {
if s.readyForListeners(maxWait) {
opts := s.getOpts()
s.mu.Lock()
tls := s.info.TLSRequired
listener := s.listener
httpListener := s.http
clusterListener := s.routeListener
profileListener := s.profiler
wsListener := s.websocket.listener
wss := s.websocket.tls
s.mu.Unlock()
ports := Ports{}
if listener != nil {
natsProto := "nats"
if tls {
natsProto = "tls"
}
ports.Nats = formatURL(natsProto, listener)
}
if httpListener != nil {
monProto := "http"
if opts.HTTPSPort != 0 {
monProto = "https"
}
ports.Monitoring = formatURL(monProto, httpListener)
}
if clusterListener != nil {
clusterProto := "nats"
if opts.Cluster.TLSConfig != nil {
clusterProto = "tls"
}
ports.Cluster = formatURL(clusterProto, clusterListener)
}
if profileListener != nil {
ports.Profile = formatURL("http", profileListener)
}
if wsListener != nil {
protocol := wsSchemePrefix
if wss {
protocol = wsSchemePrefixTLS
}
ports.WebSocket = formatURL(protocol, wsListener)
}
return &ports
}
return nil
}
// Returns the portsFile. If a non-empty dirHint is provided, the dirHint
// path is used instead of the server option value
func (s *Server) portFile(dirHint string) string {
dirname := s.getOpts().PortsFileDir
if dirHint != "" {
dirname = dirHint
}
if dirname == _EMPTY_ {
return _EMPTY_
}
return filepath.Join(dirname, fmt.Sprintf("%s_%d.ports", filepath.Base(os.Args[0]), os.Getpid()))
}
// Delete the ports file. If a non-empty dirHint is provided, the dirHint
// path is used instead of the server option value
func (s *Server) deletePortsFile(hintDir string) {
portsFile := s.portFile(hintDir)
if portsFile != "" {
if err := os.Remove(portsFile); err != nil {
s.Errorf("Error cleaning up ports file %s: %v", portsFile, err)
}
}
}
// Writes a file with a serialized Ports to the specified ports_file_dir.
// The name of the file is `exename_pid.ports`, typically nats-server_pid.ports.
// if ports file is not set, this function has no effect
func (s *Server) logPorts() {
opts := s.getOpts()
portsFile := s.portFile(opts.PortsFileDir)
if portsFile != _EMPTY_ {
go func() {
info := s.PortsInfo(5 * time.Second)
if info == nil {
s.Errorf("Unable to resolve the ports in the specified time")
return
}
data, err := json.Marshal(info)
if err != nil {
s.Errorf("Error marshaling ports file: %v", err)
return
}
if err := ioutil.WriteFile(portsFile, data, 0666); err != nil {
s.Errorf("Error writing ports file (%s): %v", portsFile, err)
return
}
}()
}
}
// waits until a calculated list of listeners is resolved or a timeout
func (s *Server) readyForListeners(dur time.Duration) bool {
end := time.Now().Add(dur)
for time.Now().Before(end) {
s.mu.Lock()
listeners := s.serviceListeners()
s.mu.Unlock()
if len(listeners) == 0 {
return false
}
ok := true
for _, l := range listeners {
if l == nil {
ok = false
break
}
}
if ok {
return true
}
select {
case <-s.quitCh:
return false
case <-time.After(25 * time.Millisecond):
// continue - unable to select from quit - we are still running
}
}
return false
}
// returns a list of listeners that are intended for the process
// if the entry is nil, the interface is yet to be resolved
func (s *Server) serviceListeners() []net.Listener {
listeners := make([]net.Listener, 0)
opts := s.getOpts()
listeners = append(listeners, s.listener)
if opts.Cluster.Port != 0 {
listeners = append(listeners, s.routeListener)
}
if opts.HTTPPort != 0 || opts.HTTPSPort != 0 {
listeners = append(listeners, s.http)
}
if opts.ProfPort != 0 {
listeners = append(listeners, s.profiler)
}
if opts.Websocket.Port != 0 {
listeners = append(listeners, s.websocket.listener)
}
return listeners
}
// Returns true if in lame duck mode.
func (s *Server) isLameDuckMode() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.ldm
}
// This function will close the client listener then close the clients
// at some interval to avoid a reconnecting storm.
func (s *Server) lameDuckMode() {
s.mu.Lock()
// Check if there is actually anything to do
if s.shutdown || s.ldm || s.listener == nil {
s.mu.Unlock()
return
}
s.Noticef("Entering lame duck mode, stop accepting new clients")
s.ldm = true
expected := 1
s.listener.Close()
s.listener = nil
if s.websocket.server != nil {
expected++
s.websocket.server.Close()
s.websocket.server = nil
s.websocket.listener = nil
}
s.ldmCh = make(chan bool, expected)
opts := s.getOpts()
gp := opts.LameDuckGracePeriod
// For tests, we want the grace period to be in some cases bigger
// than the ldm duration, so to by-pass the validateOptions() check,
// we use negative number and flip it here.
if gp < 0 {
gp *= -1
}
s.mu.Unlock()
// If we are running any raftNodes transfer leaders.
if hadTransfers := s.transferRaftLeaders(); hadTransfers {
// They will tranfer leadership quickly, but wait here for a second.
select {
case <-time.After(time.Second):
case <-s.quitCh:
return
}
}
// Wait for accept loops to be done to make sure that no new
// client can connect
for i := 0; i < expected; i++ {
<-s.ldmCh
}
s.mu.Lock()
// Need to recheck few things
if s.shutdown || len(s.clients) == 0 {
s.mu.Unlock()
// If there is no client, we need to call Shutdown() to complete
// the LDMode. If server has been shutdown while lock was released,
// calling Shutdown() should be no-op.
s.Shutdown()
return
}
dur := int64(opts.LameDuckDuration)
dur -= int64(gp)
if dur <= 0 {
dur = int64(time.Second)
}
numClients := int64(len(s.clients))
batch := 1
// Sleep interval between each client connection close.
si := dur / numClients
if si < 1 {
// Should not happen (except in test with very small LD duration), but
// if there are too many clients, batch the number of close and
// use a tiny sleep interval that will result in yield likely.
si = 1
batch = int(numClients / dur)
} else if si > int64(time.Second) {
// Conversely, there is no need to sleep too long between clients
// and spread say 10 clients for the 2min duration. Sleeping no
// more than 1sec.
si = int64(time.Second)
}
// Now capture all clients
clients := make([]*client, 0, len(s.clients))
for _, client := range s.clients {
clients = append(clients, client)
}
// Now that we know that no new client can be accepted,
// send INFO to routes and clients to notify this state.
s.sendLDMToRoutes()
s.sendLDMToClients()
s.mu.Unlock()
t := time.NewTimer(gp)
// Delay start of closing of client connections in case
// we have several servers that we want to signal to enter LD mode
// and not have their client reconnect to each other.
select {
case <-t.C:
s.Noticef("Closing existing clients")
case <-s.quitCh:
t.Stop()
return
}
for i, client := range clients {
client.closeConnection(ServerShutdown)
if i == len(clients)-1 {
break
}
if batch == 1 || i%batch == 0 {
// We pick a random interval which will be at least si/2
v := rand.Int63n(si)
if v < si/2 {
v = si / 2
}
t.Reset(time.Duration(v))
// Sleep for given interval or bail out if kicked by Shutdown().
select {
case <-t.C:
case <-s.quitCh:
t.Stop()
return
}
}
}
s.Shutdown()
}
// Send an INFO update to routes with the indication that this server is in LDM mode.
// Server lock is held on entry.
func (s *Server) sendLDMToRoutes() {
s.routeInfo.LameDuckMode = true
s.generateRouteInfoJSON()
for _, r := range s.routes {
r.mu.Lock()
r.enqueueProto(s.routeInfoJSON)
r.mu.Unlock()
}
// Clear now so that we notify only once, should we have to send other INFOs.
s.routeInfo.LameDuckMode = false
}
// Send an INFO update to clients with the indication that this server is in
// LDM mode and with only URLs of other nodes.
// Server lock is held on entry.
func (s *Server) sendLDMToClients() {
s.info.LameDuckMode = true
// Clear this so that if there are further updates, we don't send our URLs.
s.clientConnectURLs = s.clientConnectURLs[:0]
if s.websocket.connectURLs != nil {
s.websocket.connectURLs = s.websocket.connectURLs[:0]
}
// Reset content first.
s.info.ClientConnectURLs = s.info.ClientConnectURLs[:0]
s.info.WSConnectURLs = s.info.WSConnectURLs[:0]
// Only add the other nodes if we are allowed to.
if !s.getOpts().Cluster.NoAdvertise {
for url := range s.clientConnectURLsMap {
s.info.ClientConnectURLs = append(s.info.ClientConnectURLs, url)
}
for url := range s.websocket.connectURLsMap {
s.info.WSConnectURLs = append(s.info.WSConnectURLs, url)
}
}
// Send to all registered clients that support async INFO protocols.
s.sendAsyncInfoToClients(true, true)
// We now clear the info.LameDuckMode flag so that if there are
// cluster updates and we send the INFO, we don't have the boolean
// set which would cause multiple LDM notifications to clients.
s.info.LameDuckMode = false
}
// If given error is a net.Error and is temporary, sleeps for the given
// delay and double it, but cap it to ACCEPT_MAX_SLEEP. The sleep is
// interrupted if the server is shutdown.
// An error message is displayed depending on the type of error.
// Returns the new (or unchanged) delay, or a negative value if the
// server has been or is being shutdown.
func (s *Server) acceptError(acceptName string, err error, tmpDelay time.Duration) time.Duration {
if !s.isRunning() {
return -1
}
if ne, ok := err.(net.Error); ok && ne.Temporary() {
s.Errorf("Temporary %s Accept Error(%v), sleeping %dms", acceptName, ne, tmpDelay/time.Millisecond)
select {
case <-time.After(tmpDelay):
case <-s.quitCh:
return -1
}
tmpDelay *= 2
if tmpDelay > ACCEPT_MAX_SLEEP {
tmpDelay = ACCEPT_MAX_SLEEP
}
} else {
s.Errorf("%s Accept error: %v", acceptName, err)
}
return tmpDelay
}
var errNoIPAvail = errors.New("no IP available")
func (s *Server) getRandomIP(resolver netResolver, url string, excludedAddresses map[string]struct{}) (string, error) {
host, port, err := net.SplitHostPort(url)
if err != nil {
return "", err
}
// If already an IP, skip.
if net.ParseIP(host) != nil {
return url, nil
}
ips, err := resolver.LookupHost(context.Background(), host)
if err != nil {
return "", fmt.Errorf("lookup for host %q: %v", host, err)
}
if len(excludedAddresses) > 0 {
for i := 0; i < len(ips); i++ {
ip := ips[i]
addr := net.JoinHostPort(ip, port)
if _, excluded := excludedAddresses[addr]; excluded {
if len(ips) == 1 {
ips = nil
break
}
ips[i] = ips[len(ips)-1]
ips = ips[:len(ips)-1]
i--
}
}
if len(ips) == 0 {
return "", errNoIPAvail
}
}
var address string
if len(ips) == 0 {
s.Warnf("Unable to get IP for %s, will try with %s: %v", host, url, err)
address = url
} else {
var ip string
if len(ips) == 1 {
ip = ips[0]
} else {
ip = ips[rand.Int31n(int32(len(ips)))]
}
// add the port
address = net.JoinHostPort(ip, port)
}
return address, nil
}
// Returns true for the first attempt and depending on the nature
// of the attempt (first connect or a reconnect), when the number
// of attempts is equal to the configured report attempts.
func (s *Server) shouldReportConnectErr(firstConnect bool, attempts int) bool {
opts := s.getOpts()
if firstConnect {
if attempts == 1 || attempts%opts.ConnectErrorReports == 0 {
return true
}
return false
}
if attempts == 1 || attempts%opts.ReconnectErrorReports == 0 {
return true
}
return false
}
// Invoked for route, leaf and gateway connections. Set the very first
// PING to a lower interval to capture the initial RTT.
// After that the PING interval will be set to the user defined value.
// Client lock should be held.
func (s *Server) setFirstPingTimer(c *client) {
opts := s.getOpts()
d := opts.PingInterval
if !opts.DisableShortFirstPing {
if c.kind != CLIENT {
if d > firstPingInterval {
d = firstPingInterval
}
if c.kind == GATEWAY {
d = adjustPingIntervalForGateway(d)
}
} else if d > firstClientPingInterval {
d = firstClientPingInterval
}
}
// We randomize the first one by an offset up to 20%, e.g. 2m ~= max 24s.
addDelay := rand.Int63n(int64(d / 5))
d += time.Duration(addDelay)
c.ping.tmr = time.AfterFunc(d, c.processPingTimer)
}
func (s *Server) updateRemoteSubscription(acc *Account, sub *subscription, delta int32) {
s.updateRouteSubscriptionMap(acc, sub, delta)
if s.gateway.enabled {
s.gatewayUpdateSubInterest(acc.Name, sub, delta)
}
s.updateLeafNodes(acc, sub, delta)
}
| 1 | 13,814 | Should we add a warning for anything over say 8M? Just suggesting that is not recommended? | nats-io-nats-server | go |
@@ -9,11 +9,9 @@ import (
"sync"
keybase1 "github.com/keybase/client/go/protocol"
-
- "golang.org/x/net/context"
)
-func checkMDPerms(ctx context.Context, codec Codec, kbpki KBPKI,
+func checkMDPerms(codec Codec, currentUID keybase1.UID,
mergedMasterHead *RootMetadataSigned, checkWrite bool,
newMd *RootMetadataSigned) (bool, error) {
if mergedMasterHead == nil { | 1 | // Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"fmt"
"sync"
keybase1 "github.com/keybase/client/go/protocol"
"golang.org/x/net/context"
)
func checkMDPerms(ctx context.Context, codec Codec, kbpki KBPKI,
mergedMasterHead *RootMetadataSigned, checkWrite bool,
newMd *RootMetadataSigned) (bool, error) {
if mergedMasterHead == nil {
// TODO: the real mdserver will actually reverse
// lookup the folder handle and check that the UID is
// listed.
return true, nil
}
_, user, err := kbpki.GetCurrentUserInfo(ctx)
if err != nil {
return false, err
}
h, err := mergedMasterHead.MD.MakeBareTlfHandle()
if err != nil {
return false, err
}
isWriter := h.IsWriter(user)
isReader := h.IsReader(user)
if checkWrite {
// if this is a reader, are they acting within their
// restrictions?
if !isWriter && isReader && newMd != nil {
return newMd.MD.IsValidRekeyRequest(
codec, &mergedMasterHead.MD, user)
}
return isWriter, nil
}
return isWriter || isReader, nil
}
// Helper to aid in enforcement that only specified public keys can
// access TLF metadata. mergedMasterHead can be nil, in which case
// true is returned.
func isReader(ctx context.Context, codec Codec, kbpki KBPKI,
mergedMasterHead *RootMetadataSigned) (bool, error) {
return checkMDPerms(
ctx, codec, kbpki, mergedMasterHead, false, nil)
}
// Helper to aid in enforcement that only specified public keys can
// access TLF metadata. mergedMasterHead can be nil, in which case
// true is returned.
func isWriterOrValidRekey(ctx context.Context, codec Codec, kbpki KBPKI,
mergedMasterHead *RootMetadataSigned,
newMd *RootMetadataSigned) (bool, error) {
return checkMDPerms(
ctx, codec, kbpki, mergedMasterHead, true, newMd)
}
// mdServerLocalTruncateLockManager manages the truncate locks for a
// set of TLFs. Note that it is not goroutine-safe.
type mdServerLocalTruncateLockManager struct {
// TLF ID -> device KID.
locksDb map[TlfID]keybase1.KID
}
func newMDServerLocalTruncatedLockManager() mdServerLocalTruncateLockManager {
return mdServerLocalTruncateLockManager{
locksDb: make(map[TlfID]keybase1.KID),
}
}
func (m mdServerLocalTruncateLockManager) truncateLock(
deviceKID keybase1.KID, id TlfID) (bool, error) {
lockKID, ok := m.locksDb[id]
if !ok {
m.locksDb[id] = deviceKID
return true, nil
}
if lockKID == deviceKID {
// idempotent
return true, nil
}
// Locked by someone else.
return false, MDServerErrorLocked{}
}
func (m mdServerLocalTruncateLockManager) truncateUnlock(
deviceKID keybase1.KID, id TlfID) (bool, error) {
lockKID, ok := m.locksDb[id]
if !ok {
// Already unlocked.
return true, nil
}
if lockKID == deviceKID {
delete(m.locksDb, id)
return true, nil
}
// Locked by someone else.
return false, MDServerErrorLocked{}
}
// mdServerLocalUpdateManager manages the observers for a set of TLFs
// referenced by multiple mdServerLocal instances sharing the same
// data. It is goroutine-safe.
type mdServerLocalUpdateManager struct {
// Protects observers and sessionHeads.
lock sync.Mutex
observers map[TlfID]map[mdServerLocal]chan<- error
sessionHeads map[TlfID]mdServerLocal
}
func newMDServerLocalUpdateManager() *mdServerLocalUpdateManager {
return &mdServerLocalUpdateManager{
observers: make(map[TlfID]map[mdServerLocal]chan<- error),
sessionHeads: make(map[TlfID]mdServerLocal),
}
}
func (m *mdServerLocalUpdateManager) setHead(id TlfID, server mdServerLocal) {
m.lock.Lock()
defer m.lock.Unlock()
m.sessionHeads[id] = server
// now fire all the observers that aren't from this session
for k, v := range m.observers[id] {
if k != server {
v <- nil
close(v)
delete(m.observers[id], k)
}
}
if len(m.observers[id]) == 0 {
delete(m.observers, id)
}
}
func (m *mdServerLocalUpdateManager) registerForUpdate(
id TlfID, currHead, currMergedHeadRev MetadataRevision,
server mdServerLocal) <-chan error {
m.lock.Lock()
defer m.lock.Unlock()
c := make(chan error, 1)
if currMergedHeadRev > currHead && server != m.sessionHeads[id] {
c <- nil
close(c)
return c
}
if _, ok := m.observers[id]; !ok {
m.observers[id] = make(map[mdServerLocal]chan<- error)
}
// Otherwise, this is a legit observer. This assumes that each
// client will be using a unique instance of MDServerLocal.
if _, ok := m.observers[id][server]; ok {
// If the local node registers something twice, it indicates a
// fatal bug. Note that in the real MDServer implementation,
// we should allow this, in order to make the RPC properly
// idempotent.
panic(fmt.Errorf("Attempted double-registration for MDServerLocal %v",
server))
}
m.observers[id][server] = c
return c
}
| 1 | 11,856 | Looks like there are no callers left of this function. | keybase-kbfs | go |
@@ -267,7 +267,7 @@ func logProgress(ctx context.Context, label BuildLabel) {
// If the command times out the returned error will be a context.DeadlineExceeded error.
// If showOutput is true then output will be printed to stderr as well as returned.
// It returns the stdout only, combined stdout and stderr and any error that occurred.
-func ExecWithTimeout(target *BuildTarget, dir string, env []string, timeout time.Duration, defaultTimeout cli.Duration, showOutput bool, argv []string) ([]byte, []byte, error) {
+func ExecWithTimeout(target *BuildTarget, dir string, env []string, timeout time.Duration, defaultTimeout cli.Duration, showOutput, attachStdin bool, argv []string) ([]byte, []byte, error) {
if timeout == 0 {
if defaultTimeout == 0 {
timeout = 10 * time.Minute | 1 | package core
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha1"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"time"
"cli"
)
// RepoRoot is the root of the Please repository
var RepoRoot string
// initialWorkingDir is the directory we began in. Early on we chdir() to the repo root but for
// some things we need to remember this.
var initialWorkingDir string
// initialPackage is the initial subdir of the working directory, ie. what package did we start in.
// This is similar but not identical to initialWorkingDir.
var initialPackage string
// usingBazelWorkspace is true if we detected a Bazel WORKSPACE file to find our repo root.
var usingBazelWorkspace bool
// DirPermissions are the default permission bits we apply to directories.
const DirPermissions = os.ModeDir | 0775
// FindRepoRoot returns the root directory of the current repo and sets the initial working dir.
// It returns true if the repo root was found.
func FindRepoRoot() bool {
initialWorkingDir, _ = os.Getwd()
RepoRoot, initialPackage = getRepoRoot(ConfigFileName, false)
return RepoRoot != ""
}
// MustFindRepoRoot returns the root directory of the current repo and sets the initial working dir.
// It dies on failure, although will fall back to looking for a Bazel WORKSPACE file first.
func MustFindRepoRoot() string {
if RepoRoot != "" {
return RepoRoot
}
if !FindRepoRoot() {
RepoRoot, initialPackage = getRepoRoot("WORKSPACE", true)
log.Warning("No .plzconfig file found to define the repo root.")
log.Warning("Falling back to Bazel WORKSPACE at %s", path.Join(RepoRoot, "WORKSPACE"))
usingBazelWorkspace = true
}
return RepoRoot
}
// InitialPackage returns a label corresponding to the initial package we started in.
func InitialPackage() []BuildLabel {
// It's possible to start off in directories that aren't legal package names, because
// our package naming is stricter than directory naming requirements.
// In that case move up until we find somewhere we can run from.
dir := initialPackage
for dir != "." {
if label, err := TryNewBuildLabel(dir, "test"); err == nil {
label.Name = "..."
return []BuildLabel{label}
}
dir = filepath.Dir(dir)
}
return WholeGraph
}
// getRepoRoot returns the root directory of the current repo and the initial package.
func getRepoRoot(filename string, die bool) (string, string) {
dir, err := os.Getwd()
if err != nil {
log.Fatalf("Couldn't determine working directory: %s", err)
}
// Walk up directories looking for a .plzconfig file, which we use to identify the root.
initial := dir
for dir != "" {
if PathExists(path.Join(dir, filename)) {
return dir, strings.TrimLeft(initial[len(dir):], "/")
}
dir, _ = path.Split(dir)
dir = strings.TrimRight(dir, "/")
}
if die {
log.Fatalf("Couldn't locate the repo root. Are you sure you're inside a plz repo?")
}
return "", ""
}
// StartedAtRepoRoot returns true if the build was initiated from the repo root.
// Used to provide slightly nicer output in some places.
func StartedAtRepoRoot() bool {
return RepoRoot == initialWorkingDir
}
// PathExists returns true if the given path exists, as a file or a directory.
func PathExists(filename string) bool {
_, err := os.Stat(filename)
return err == nil
}
// FileExists returns true if the given path exists and is a file.
func FileExists(filename string) bool {
info, err := os.Stat(filename)
return err == nil && !info.IsDir()
}
// CopyFile copies a file from 'from' to 'to', with an attempt to perform a copy & rename
// to avoid chaos if anything goes wrong partway.
func CopyFile(from string, to string, mode os.FileMode) error {
fromFile, err := os.Open(from)
if err != nil {
return err
}
defer fromFile.Close()
return WriteFile(fromFile, to, mode)
}
// WriteFile writes data from a reader to the file named 'to', with an attempt to perform
// a copy & rename to avoid chaos if anything goes wrong partway.
func WriteFile(fromFile io.Reader, to string, mode os.FileMode) error {
if err := os.RemoveAll(to); err != nil {
return err
}
dir, file := path.Split(to)
if err := os.MkdirAll(dir, DirPermissions); err != nil {
return err
}
tempFile, err := ioutil.TempFile(dir, file)
if err != nil {
return err
}
if _, err := io.Copy(tempFile, fromFile); err != nil {
return err
}
if err := tempFile.Close(); err != nil {
return err
}
// OK, now file is written; adjust permissions appropriately.
if mode == 0 {
mode = 0664
}
if err := os.Chmod(tempFile.Name(), mode); err != nil {
return err
}
// And move it to its final destination.
return os.Rename(tempFile.Name(), to)
}
// RecursiveCopyFile copies either a single file or a directory.
// If 'link' is true then we'll hardlink files instead of copying them.
// If 'fallback' is true then we'll fall back to a copy if linking fails.
func RecursiveCopyFile(from string, to string, mode os.FileMode, link, fallback bool) error {
if info, err := os.Stat(from); err == nil && info.IsDir() {
return filepath.Walk(from, func(name string, info os.FileInfo, err error) error {
dest := path.Join(to, name[len(from):])
if err != nil {
return err
} else if info.IsDir() {
return os.MkdirAll(dest, DirPermissions)
} else if (info.Mode() & os.ModeSymlink) != 0 {
fi, err := os.Stat(name)
if err != nil {
return err
}
if fi.IsDir() {
return RecursiveCopyFile(name+"/", dest+"/", mode, link, fallback)
}
// 0 indicates inheriting the existing mode bits.
if mode == 0 {
mode = info.Mode()
}
return copyOrLinkFile(name, dest, mode, link, fallback)
}
return copyOrLinkFile(name, dest, mode, link, fallback)
})
}
return copyOrLinkFile(from, to, mode, link, fallback)
}
// Either copies or hardlinks a file based on the link argument.
// Falls back to a copy if link fails and fallback is true.
func copyOrLinkFile(from, to string, mode os.FileMode, link, fallback bool) error {
if link {
if err := os.Link(from, to); err == nil || !fallback {
return err
}
}
return CopyFile(from, to, mode)
}
// IsSameFile returns true if two filenames describe the same underlying file (i.e. inode)
func IsSameFile(a, b string) bool {
i1, err1 := getInode(a)
i2, err2 := getInode(b)
return err1 == nil && err2 == nil && i1 == i2
}
// getInode returns the inode of a file.
func getInode(filename string) (uint64, error) {
fi, err := os.Stat(filename)
if err != nil {
return 0, err
}
s, ok := fi.Sys().(*syscall.Stat_t)
if !ok {
return 0, fmt.Errorf("Not a syscall.Stat_t")
}
return s.Ino, nil
}
// safeBuffer is an io.Writer that ensures that only one thread writes to it at a time.
// This is important because we potentially have both stdout and stderr writing to the same
// buffer, and os.exec only guarantees goroutine-safety if both are the same writer, which in
// our case they're not (but are both ultimately causing writes to the same buffer)
type safeBuffer struct {
sync.Mutex
buf bytes.Buffer
}
func (sb *safeBuffer) Write(b []byte) (int, error) {
sb.Lock()
defer sb.Unlock()
return sb.buf.Write(b)
}
func (sb *safeBuffer) Bytes() []byte {
return sb.buf.Bytes()
}
func (sb *safeBuffer) String() string {
return sb.buf.String()
}
// logProgress logs a message once a minute until the given context has expired.
// Used to provide some notion of progress while waiting for external commands.
func logProgress(ctx context.Context, label BuildLabel) {
t := time.NewTicker(1 * time.Minute)
defer t.Stop()
for i := 1; i < 1000000; i++ {
select {
case <-ctx.Done():
return
case <-t.C:
if i == 1 {
log.Notice("%s still running after 1 minute", label)
} else {
log.Notice("%s still running after %d minutes", label, i)
}
}
}
}
// ExecWithTimeout runs an external command with a timeout.
// If the command times out the returned error will be a context.DeadlineExceeded error.
// If showOutput is true then output will be printed to stderr as well as returned.
// It returns the stdout only, combined stdout and stderr and any error that occurred.
func ExecWithTimeout(target *BuildTarget, dir string, env []string, timeout time.Duration, defaultTimeout cli.Duration, showOutput bool, argv []string) ([]byte, []byte, error) {
if timeout == 0 {
if defaultTimeout == 0 {
timeout = 10 * time.Minute
} else {
timeout = time.Duration(defaultTimeout)
}
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
cmd := ExecCommand(argv[0], argv[1:]...)
cmd.Dir = dir
cmd.Env = env
var out bytes.Buffer
var outerr safeBuffer
if showOutput {
cmd.Stdout = io.MultiWriter(os.Stderr, &out, &outerr)
cmd.Stderr = io.MultiWriter(os.Stderr, &outerr)
} else {
cmd.Stdout = io.MultiWriter(&out, &outerr)
cmd.Stderr = &outerr
}
if target != nil {
go logProgress(ctx, target.Label)
}
// Start the command, wait for the timeout & then kill it.
// We deliberately don't use CommandContext because it will only send SIGKILL which
// child processes can't handle themselves.
err := cmd.Start()
if err != nil {
return nil, nil, err
}
ch := make(chan error)
go runCommand(cmd, ch)
select {
case err = <-ch:
// Do nothing.
case <-time.After(timeout):
// Send a relatively gentle signal that it can catch.
if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
log.Notice("Failed to kill subprocess: %s", err)
}
time.Sleep(10 * time.Millisecond)
// Send a more forceful signal.
cmd.Process.Kill()
err = fmt.Errorf("Timeout exceeded: %s", outerr.String())
}
return out.Bytes(), outerr.Bytes(), err
}
// runCommand runs a command and signals on the given channel when it's done.
func runCommand(cmd *exec.Cmd, ch chan error) {
ch <- cmd.Wait()
}
// ExecWithTimeoutShell runs an external command within a Bash shell.
// Other arguments are as ExecWithTimeout.
// Note that the command is deliberately a single string.
func ExecWithTimeoutShell(target *BuildTarget, dir string, env []string, timeout time.Duration, defaultTimeout cli.Duration, showOutput bool, cmd string, sandbox bool) ([]byte, []byte, error) {
c := append([]string{"bash", "-u", "-o", "pipefail", "-c"}, cmd)
// Runtime check is a little ugly, but we know this only works on Linux right now.
if sandbox && runtime.GOOS == "linux" {
tool, err := LookPath(State.Config.Build.PleaseSandboxTool, State.Config.Build.Path)
if err != nil {
return nil, nil, err
}
c = append([]string{tool}, c...)
}
return ExecWithTimeout(target, dir, env, timeout, defaultTimeout, showOutput, c)
}
// ExecWithTimeoutSimple runs an external command with a timeout.
// It's a simpler version of ExecWithTimeout that gives less control.
func ExecWithTimeoutSimple(timeout cli.Duration, cmd ...string) ([]byte, error) {
_, out, err := ExecWithTimeout(nil, "", nil, time.Duration(timeout), timeout, false, cmd)
return out, err
}
// A SourcePair represents a source file with its source and temporary locations.
// This isn't typically used much by callers; it's just useful to have a single type for channels.
type SourcePair struct{ Src, Tmp string }
// IterSources returns all the sources for a function, allowing for sources that are other rules
// and rules that require transitive dependencies.
// Yielded values are pairs of the original source location and its temporary location for this rule.
func IterSources(graph *BuildGraph, target *BuildTarget) <-chan SourcePair {
ch := make(chan SourcePair)
done := map[BuildLabel]bool{}
donePaths := map[string]bool{}
tmpDir := target.TmpDir()
var inner func(dependency *BuildTarget)
inner = func(dependency *BuildTarget) {
sources := dependency.AllSources()
if target == dependency {
// This is the current build rule, so link its sources.
for _, source := range sources {
for _, providedSource := range recursivelyProvideSource(graph, target, source) {
fullPaths := providedSource.FullPaths(graph)
for i, sourcePath := range providedSource.Paths(graph) {
tmpPath := path.Join(tmpDir, sourcePath)
ch <- SourcePair{fullPaths[i], tmpPath}
donePaths[tmpPath] = true
}
}
}
} else {
// This is a dependency of the rule, so link its outputs.
outDir := dependency.OutDir()
for _, dep := range dependency.Outputs() {
depPath := path.Join(outDir, dep)
tmpPath := path.Join(tmpDir, dependency.Label.PackageName, dep)
if !donePaths[tmpPath] {
ch <- SourcePair{depPath, tmpPath}
donePaths[tmpPath] = true
}
}
// Mark any label-type outputs as done.
for _, out := range dependency.DeclaredOutputs() {
if LooksLikeABuildLabel(out) {
label := ParseBuildLabel(out, target.Label.PackageName)
done[label] = true
}
}
}
// All the sources of this rule now count as done.
for _, source := range sources {
if label := source.Label(); label != nil && dependency.IsSourceOnlyDep(*label) {
done[*label] = true
}
}
done[dependency.Label] = true
if target == dependency || (target.NeedsTransitiveDependencies && !dependency.OutputIsComplete) {
for _, dep := range dependency.BuildDependencies() {
for _, dep2 := range recursivelyProvideFor(graph, target, dependency, dep.Label) {
if !done[dep2] && !dependency.IsTool(dep2) {
inner(graph.TargetOrDie(dep2))
}
}
}
} else {
for _, dep := range dependency.ExportedDependencies() {
for _, dep2 := range recursivelyProvideFor(graph, target, dependency, dep) {
if !done[dep2] {
inner(graph.TargetOrDie(dep2))
}
}
}
}
}
go func() {
inner(target)
close(ch)
}()
return ch
}
// recursivelyProvideFor recursively applies ProvideFor to a target.
func recursivelyProvideFor(graph *BuildGraph, target, dependency *BuildTarget, dep BuildLabel) []BuildLabel {
depTarget := graph.TargetOrDie(dep)
ret := depTarget.ProvideFor(dependency)
if len(ret) == 1 && ret[0] == dep {
// Dependency doesn't have a require/provide directly on this guy, up to the top-level
// target. We have to check the dep first to keep things consistent with what targets
// have actually been built.
ret = depTarget.ProvideFor(target)
if len(ret) == 1 && ret[0] == dep {
return ret
}
}
ret2 := make([]BuildLabel, 0, len(ret))
for _, r := range ret {
if r == dep {
ret2 = append(ret2, r) // Providing itself, don't recurse
} else {
ret2 = append(ret2, recursivelyProvideFor(graph, target, dependency, r)...)
}
}
return ret2
}
// recursivelyProvideSource is similar to recursivelyProvideFor but operates on a BuildInput.
func recursivelyProvideSource(graph *BuildGraph, target *BuildTarget, src BuildInput) []BuildInput {
if label := src.nonOutputLabel(); label != nil {
dep := graph.TargetOrDie(*label)
provided := recursivelyProvideFor(graph, target, target, dep.Label)
ret := make([]BuildInput, len(provided))
for i, p := range provided {
ret[i] = p
}
return ret
}
return []BuildInput{src}
}
// IterRuntimeFiles yields all the runtime files for a rule (outputs & data files), similar to above.
func IterRuntimeFiles(graph *BuildGraph, target *BuildTarget, absoluteOuts bool) <-chan SourcePair {
done := map[string]bool{}
ch := make(chan SourcePair)
makeOut := func(out string) string {
if absoluteOuts {
return path.Join(RepoRoot, target.TestDir(), out)
}
return out
}
pushOut := func(src, out string) {
out = makeOut(out)
if !done[out] {
ch <- SourcePair{src, out}
done[out] = true
}
}
var inner func(*BuildTarget)
inner = func(target *BuildTarget) {
outDir := target.OutDir()
for _, out := range target.Outputs() {
pushOut(path.Join(outDir, out), out)
}
for _, data := range target.Data {
fullPaths := data.FullPaths(graph)
for i, dataPath := range data.Paths(graph) {
pushOut(fullPaths[i], dataPath)
}
if label := data.Label(); label != nil {
for _, dep := range graph.TargetOrDie(*label).ExportedDependencies() {
inner(graph.TargetOrDie(dep))
}
}
}
for _, dep := range target.ExportedDependencies() {
inner(graph.TargetOrDie(dep))
}
}
go func() {
inner(target)
close(ch)
}()
return ch
}
// IterInputPaths yields all the transitive input files for a rule (sources & data files), similar to above (again).
func IterInputPaths(graph *BuildGraph, target *BuildTarget) <-chan string {
// Use a couple of maps to protect us from dep-graph loops and to stop parsing the same target
// multiple times. We also only want to push files to the channel that it has not already seen.
donePaths := map[string]bool{}
doneTargets := map[*BuildTarget]bool{}
ch := make(chan string)
var inner func(*BuildTarget)
inner = func(target *BuildTarget) {
if !doneTargets[target] {
// First yield all the sources of the target only ever pushing declared paths to
// the channel to prevent us outputting any intermediate files.
for _, source := range target.AllSources() {
// If the label is nil add any input paths contained here.
if label := source.nonOutputLabel(); label == nil {
for _, sourcePath := range source.FullPaths(graph) {
if !donePaths[sourcePath] {
ch <- sourcePath
donePaths[sourcePath] = true
}
}
// Otherwise we should recurse for this build label (and gather its sources)
} else {
inner(graph.TargetOrDie(*label))
}
}
// Now yield all the data deps of this rule.
for _, data := range target.Data {
// If the label is nil add any input paths contained here.
if label := data.Label(); label == nil {
for _, sourcePath := range data.FullPaths(graph) {
if !donePaths[sourcePath] {
ch <- sourcePath
donePaths[sourcePath] = true
}
}
// Otherwise we should recurse for this build label (and gather its sources)
} else {
inner(graph.TargetOrDie(*label))
}
}
// Finally recurse for all the deps of this rule.
for _, dep := range target.Dependencies() {
inner(dep)
}
doneTargets[target] = true
}
}
go func() {
inner(target)
close(ch)
}()
return ch
}
// PrepareSource symlinks a single source file for a build rule.
func PrepareSource(sourcePath string, tmpPath string) error {
dir := path.Dir(tmpPath)
if !PathExists(dir) {
if err := os.MkdirAll(dir, DirPermissions); err != nil {
return err
}
}
if !PathExists(sourcePath) {
return fmt.Errorf("Source file %s doesn't exist", sourcePath)
}
return RecursiveCopyFile(sourcePath, tmpPath, 0, true, true)
}
// PrepareSourcePair prepares a source file for a build.
func PrepareSourcePair(pair SourcePair) error {
if path.IsAbs(pair.Src) {
return PrepareSource(pair.Src, pair.Tmp)
}
return PrepareSource(path.Join(RepoRoot, pair.Src), pair.Tmp)
}
// CollapseHash combines our usual four-part hash into one by XOR'ing them together.
// This helps keep things short in places where sometimes we get complaints about filenames being
// too long (this is most noticeable on e.g. Ubuntu with an encrypted home directory, but
// not an entire encrypted disk) and where we don't especially care about breaking out the
// individual parts of hashes, which is important for many parts of the system.
func CollapseHash(key []byte) []byte {
short := [sha1.Size]byte{}
// We store the rule hash twice, if it's repeated we must make sure not to xor it
// against itself.
if bytes.Equal(key[0:sha1.Size], key[sha1.Size:2*sha1.Size]) {
for i := 0; i < sha1.Size; i++ {
short[i] = key[i] ^ key[i+2*sha1.Size] ^ key[i+3*sha1.Size]
}
} else {
for i := 0; i < sha1.Size; i++ {
short[i] = key[i] ^ key[i+sha1.Size] ^ key[i+2*sha1.Size] ^ key[i+3*sha1.Size]
}
}
return short[:]
}
// LookPath does roughly the same as exec.LookPath, i.e. looks for the named file on the path.
// The main difference is that it looks based on our config which isn't necessarily the same
// as the external environment variable.
func LookPath(filename string, paths []string) (string, error) {
for _, p := range paths {
for _, p2 := range strings.Split(p, ":") {
p3 := path.Join(p2, filename)
if _, err := os.Stat(p3); err == nil {
return p3, nil
}
}
}
return "", fmt.Errorf("%s not found in PATH %s", filename, strings.Join(paths, ":"))
}
// AsyncDeleteDir deletes a directory asynchronously.
// First it renames the directory to something temporary and then forks to delete it.
// The rename is done synchronously but the actual deletion is async (after fork) so
// you don't have to wait for large directories to be removed.
// Conversely there is obviously no guarantee about at what point it will actually cease to
// be on disk any more.
func AsyncDeleteDir(dir string) error {
rm, err := exec.LookPath("rm")
if err != nil {
return err
} else if !PathExists(dir) {
return nil // not an error, just don't need to do anything.
}
newDir, err := moveDir(dir)
if err != nil {
return err
}
// Note that we can't fork() directly and continue running Go code, but ForkExec() works okay.
// Hence why we're using rm rather than fork() + os.RemoveAll.
_, err = syscall.ForkExec(rm, []string{rm, "-rf", newDir}, nil)
return err
}
// moveDir moves a directory to a new location and returns that new location.
func moveDir(dir string) (string, error) {
b := make([]byte, 16)
rand.Read(b)
name := path.Join(path.Dir(dir), ".plz_clean_"+hex.EncodeToString(b))
log.Notice("Moving %s to %s", dir, name)
return name, os.Rename(dir, name)
}
// ContainsString returns true if the given slice contains an individual string.
func ContainsString(needle string, haystack []string) bool {
for _, straw := range haystack {
if needle == straw {
return true
}
}
return false
}
| 1 | 8,071 | Should there still be a ` bool` trailing `showOutput`? | thought-machine-please | go |
@@ -24,6 +24,7 @@ import (
"sync"
"github.com/ghodss/yaml"
+ "github.com/pingcap/chaos-mesh/api/v1alpha1"
ctrl "sigs.k8s.io/controller-runtime"
| 1 | // Copyright 2019 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
"crypto/sha256"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"github.com/ghodss/yaml"
ctrl "sigs.k8s.io/controller-runtime"
corev1 "k8s.io/api/core/v1"
)
var log = ctrl.Log.WithName("inject-webhook")
var (
// ErrMissingName ..
ErrMissingName = fmt.Errorf(`name field is required for an injection config`)
)
const (
annotationNamespaceDefault = "admission-webhook.pingcap.com"
defaultVersion = "latest"
)
// ExecAction describes a "run in container" action.
type ExecAction struct {
// Command is the command line to execute inside the container, the working directory for the
// command is root ('/') in the container's filesystem. The command is simply exec'd, it is
// not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use
// a shell, you need to explicitly call out to that shell.
// Exit status of 0 is treated as live/healthy and non-zero is unhealthy.
// +optional
Command []string `json:"command,omitempty"`
}
// InjectionConfig is a specific instance of a injected config, for a given annotation
type InjectionConfig struct {
Name string `json:"name"`
Containers []corev1.Container `json:"containers"`
Volumes []corev1.Volume `json:"volumes"`
Environment []corev1.EnvVar `json:"env"`
VolumeMounts []corev1.VolumeMount `json:"volumeMounts"`
HostAliases []corev1.HostAlias `json:"hostAliases"`
InitContainers []corev1.Container `json:"initContainers"`
ShareProcessNamespace bool `json:"shareProcessNamespace"`
version string
// PostStart is called after a container is created first.
// If the handler fails, the containers will failed.
// Key defines for the name of deployment container.
// Value defines for the Commands for stating container.
// +optional
PostStart map[string]ExecAction `json:"postStart,omitempty"`
}
// FullName returns the full identifier of this sidecar - both the Name, and the Version(), formatted like
// "${.Name}:${.Version}"
func (c *InjectionConfig) FullName() string {
return canonicalizeConfigName(c.Name, c.Version())
}
func canonicalizeConfigName(name, version string) string {
return strings.ToLower(fmt.Sprintf("%s:%s", name, version))
}
// Version returns the parsed version of this injection config. If no version is specified,
// "latest" is returned. The version is extracted from the request annotation, i.e.
// admission-webhook.pingcap.com/request: my-sidecar:1.2, where "1.2" is the version.
func (c *InjectionConfig) Version() string {
if c.version == "" {
return defaultVersion
}
return c.version
}
// Config is a struct indicating how a given injection should be configured
type Config struct {
sync.RWMutex
AnnotationNamespace string `yaml:"annotationNamespace"`
Injections map[string]*InjectionConfig `yaml:"injections"`
}
// LoadConfigDirectory loads all configs in a directory and returns the Config
func LoadConfigDirectory(path string) (*Config, error) {
cfg := &Config{
Injections: map[string]*InjectionConfig{},
}
glob := filepath.Join(path, "*.yaml")
matches, err := filepath.Glob(glob)
if err != nil {
return cfg, err
}
for _, p := range matches {
c, err := LoadInjectionConfigFromFilePath(p)
if err != nil {
log.Error(err, "Error reading injection config", "from", p)
return cfg, err
}
cfg.Injections[c.FullName()] = c
}
if cfg.AnnotationNamespace == "" {
cfg.AnnotationNamespace = annotationNamespaceDefault
}
log.V(2).Info("Loaded injection configs", "len", len(cfg.Injections), "from", glob)
return cfg, nil
}
func (c *Config) RequestAnnotationKey() string {
return c.AnnotationNamespace + "/request"
}
func (c *Config) StatusAnnotationKey() string {
return c.AnnotationNamespace + "/status"
}
func (c *Config) RequestInitAnnotationKey() string {
return c.AnnotationNamespace + "/init-request"
}
// GetRequestedConfig returns the InjectionConfig given a requested key
func (c *Config) GetRequestedConfig(key string) (*InjectionConfig, error) {
c.RLock()
defer c.RUnlock()
name, version, err := configNameFields(key)
if err != nil {
return nil, err
}
fullKey := canonicalizeConfigName(name, version)
i, ok := c.Injections[fullKey]
if !ok {
return nil, fmt.Errorf("no injection config found for annotation %s", fullKey)
}
return i, nil
}
// LoadInjectionConfigFromFilePath returns a InjectionConfig given a yaml file on disk
func LoadInjectionConfigFromFilePath(configFile string) (*InjectionConfig, error) {
f, err := os.Open(configFile)
if err != nil {
return nil, fmt.Errorf("error loading injection config from file %s: %s", configFile, err.Error())
}
defer f.Close()
log.V(3).Info("Loading injection config", "file", configFile)
return LoadInjectionConfig(f)
}
// LoadInjectionConfig takes an io.Reader and parses out an injectionconfig
func LoadInjectionConfig(reader io.Reader) (*InjectionConfig, error) {
data, err := ioutil.ReadAll(reader)
if err != nil {
return nil, err
}
var cfg InjectionConfig
if err := yaml.Unmarshal(data, &cfg); err != nil {
return nil, err
}
if cfg.Name == "" {
return nil, ErrMissingName
}
// we need to split the Name field apart into a Name and Version component
cfg.Name, cfg.version, err = configNameFields(cfg.Name)
if err != nil {
return nil, err
}
log.V(3).Info("Loaded injection configx", "name", cfg.Name, "sha256sum", sha256.Sum256(data))
return &cfg, nil
}
// given a name of a config, extract the name and version. Format is "name[:version]" where :version
// is optional, and is assumed to be "latest" if omitted.
func configNameFields(shortName string) (name, version string, err error) {
substrings := strings.Split(shortName, ":")
switch len(substrings) {
case 1:
return substrings[0], defaultVersion, nil
case 2:
if substrings[1] == "" {
return substrings[0], defaultVersion, nil
}
return substrings[0], substrings[1], nil
default:
return "", "", fmt.Errorf(`not a valid name or name:version format`)
}
}
// ReplaceInjectionConfigs will take a list of new InjectionConfigs, and replace the current configuration with them.
// this blocks waiting on being able to update the configs in place.
func (c *Config) ReplaceInjectionConfigs(replacementConfigs []*InjectionConfig) {
c.Lock()
defer c.Unlock()
c.Injections = map[string]*InjectionConfig{}
for _, r := range replacementConfigs {
c.Injections[r.FullName()] = r
}
}
| 1 | 12,574 | Did we can change to v1 | chaos-mesh-chaos-mesh | go |
@@ -43,6 +43,9 @@ export function diff(parentDom, newVNode, oldVNode, context, isSvg, excessDomChi
try {
outer: if (oldVNode.type===Fragment || newType===Fragment) {
+ // Passing the ancestorComponent here is needed for catchErrorInComponent to properly traverse upwards through fragments
+ // to find a parent Suspense
+ c = { _ancestorComponent: ancestorComponent };
diffChildren(parentDom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, c, oldDom);
// Mark dom as empty in case `_children` is any empty array. If it isn't | 1 | import { EMPTY_OBJ, EMPTY_ARR } from '../constants';
import { Component, enqueueRender } from '../component';
import { coerceToVNode, Fragment } from '../create-element';
import { diffChildren } from './children';
import { diffProps } from './props';
import { assign, removeNode } from '../util';
import options from '../options';
/**
* Diff two virtual nodes and apply proper changes to the DOM
* @param {import('../internal').PreactElement} parentDom The parent of the DOM element
* @param {import('../internal').VNode | null} newVNode The new virtual node
* @param {import('../internal').VNode | null} oldVNode The old virtual node
* @param {object} context The current context object
* @param {boolean} isSvg Whether or not this element is an SVG node
* @param {Array<import('../internal').PreactElement>} excessDomChildren
* @param {Array<import('../internal').Component>} mounts A list of newly
* mounted components
* @param {import('../internal').Component | null} ancestorComponent The direct
* parent component
* @param {Element | Text} oldDom The current attached DOM
* element any new dom elements should be placed around. Likely `null` on first
* render (except when hydrating). Can be a sibling DOM element when diffing
* Fragments that have siblings. In most cases, it starts out as `oldChildren[0]._dom`.
*/
export function diff(parentDom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent, force, oldDom) {
// If the previous type doesn't match the new type we drop the whole subtree
if (oldVNode==null || newVNode==null || oldVNode.type!==newVNode.type || oldVNode.key!==newVNode.key) {
if (oldVNode!=null) unmount(oldVNode, ancestorComponent);
if (newVNode==null) return null;
oldVNode = EMPTY_OBJ;
}
// When passing through createElement it assigns the object
// ref on _self, to prevent JSON Injection we check if this attribute
// is equal.
if (newVNode._self!==newVNode) return null;
if (options.diff) options.diff(newVNode);
let c, p, isNew = false, oldProps, oldState, snapshot,
newType = newVNode.type, clearProcessingException;
try {
outer: if (oldVNode.type===Fragment || newType===Fragment) {
diffChildren(parentDom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, c, oldDom);
// Mark dom as empty in case `_children` is any empty array. If it isn't
// we'll set `dom` to the correct value just a few lines later.
if (newVNode._children.length && newVNode._children[0]!=null) {
newVNode._dom = newVNode._children[0]._dom;
// If the last child is a Fragment, use _lastDomChild, else use _dom
// We have no guarantee that the last child rendered something into the
// dom, so we iterate backwards to find the last child with a dom node.
for (let i = newVNode._children.length; i--;) {
p = newVNode._children[i];
newVNode._lastDomChild = p && (p._lastDomChild || p._dom);
if (newVNode._lastDomChild) break;
}
}
}
else if (typeof newType==='function') {
// Necessary for createContext api. Setting this property will pass
// the context value as `this.context` just for this component.
let cxType = newType.contextType;
let provider = cxType && context[cxType._id];
let cctx = cxType != null ? (provider ? provider.props.value : cxType._defaultValue) : context;
// Get component and set it to `c`
if (oldVNode._component) {
c = newVNode._component = oldVNode._component;
clearProcessingException = c._processingException = c._pendingError;
newVNode._dom = oldVNode._dom;
}
else {
// Instantiate the new component
if (newType.prototype && newType.prototype.render) {
newVNode._component = c = new newType(newVNode.props, cctx); // eslint-disable-line new-cap
}
else {
newVNode._component = c = new Component(newVNode.props, cctx);
c.constructor = newType;
c.render = doRender;
}
c._ancestorComponent = ancestorComponent;
if (provider) provider.sub(c);
c.props = newVNode.props;
if (!c.state) c.state = {};
c.context = cctx;
c._context = context;
isNew = c._dirty = true;
c._renderCallbacks = [];
}
c._vnode = newVNode;
// Invoke getDerivedStateFromProps
if (c._nextState==null) {
c._nextState = c.state;
}
if (newType.getDerivedStateFromProps!=null) {
assign(c._nextState==c.state ? (c._nextState = assign({}, c._nextState)) : c._nextState, newType.getDerivedStateFromProps(newVNode.props, c._nextState));
}
// Invoke pre-render lifecycle methods
if (isNew) {
if (newType.getDerivedStateFromProps==null && c.componentWillMount!=null) c.componentWillMount();
if (c.componentDidMount!=null) mounts.push(c);
}
else {
if (newType.getDerivedStateFromProps==null && force==null && c.componentWillReceiveProps!=null) {
c.componentWillReceiveProps(newVNode.props, cctx);
}
if (!force && c.shouldComponentUpdate!=null && c.shouldComponentUpdate(newVNode.props, c._nextState, cctx)===false) {
c.props = newVNode.props;
c.state = c._nextState;
c._dirty = false;
newVNode._lastDomChild = oldVNode._lastDomChild;
break outer;
}
if (c.componentWillUpdate!=null) {
c.componentWillUpdate(newVNode.props, c._nextState, cctx);
}
}
oldProps = c.props;
oldState = c.state;
c.context = cctx;
c.props = newVNode.props;
c.state = c._nextState;
if (options.render) options.render(newVNode);
let prev = c._prevVNode || null;
c._dirty = false;
let vnode = c._prevVNode = coerceToVNode(c.render(c.props, c.state, c.context));
if (c.getChildContext!=null) {
context = assign(assign({}, context), c.getChildContext());
}
if (!isNew && c.getSnapshotBeforeUpdate!=null) {
snapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);
}
c._depth = ancestorComponent ? (ancestorComponent._depth || 0) + 1 : 0;
c.base = newVNode._dom = diff(parentDom, vnode, prev, context, isSvg, excessDomChildren, mounts, c, null, oldDom);
if (vnode!=null) {
// If this component returns a Fragment (or another component that
// returns a Fragment), then _lastDomChild will be non-null,
// informing `diffChildren` to diff this component's VNode like a Fragemnt
newVNode._lastDomChild = vnode._lastDomChild;
}
c._parentDom = parentDom;
if (newVNode.ref) applyRef(newVNode.ref, c, ancestorComponent);
while (p=c._renderCallbacks.pop()) p.call(c);
// Don't call componentDidUpdate on mount or when we bailed out via
// `shouldComponentUpdate`
if (!isNew && oldProps!=null && c.componentDidUpdate!=null) {
c.componentDidUpdate(oldProps, oldState, snapshot);
}
}
else {
newVNode._dom = diffElementNodes(oldVNode._dom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent);
if (newVNode.ref && (oldVNode.ref !== newVNode.ref)) {
applyRef(newVNode.ref, newVNode._dom, ancestorComponent);
}
}
if (clearProcessingException) {
c._pendingError = c._processingException = null;
}
if (options.diffed) options.diffed(newVNode);
}
catch (e) {
catchErrorInComponent(e, ancestorComponent);
}
return newVNode._dom;
}
export function commitRoot(mounts, root) {
let c;
while ((c = mounts.pop())) {
try {
c.componentDidMount();
}
catch (e) {
catchErrorInComponent(e, c._ancestorComponent);
}
}
if (options.commit) options.commit(root);
}
/**
* Diff two virtual nodes representing DOM element
* @param {import('../internal').PreactElement} dom The DOM element representing
* the virtual nodes being diffed
* @param {import('../internal').VNode} newVNode The new virtual node
* @param {import('../internal').VNode} oldVNode The old virtual node
* @param {object} context The current context object
* @param {boolean} isSvg Whether or not this DOM node is an SVG node
* @param {*} excessDomChildren
* @param {Array<import('../internal').Component>} mounts An array of newly
* mounted components
* @param {import('../internal').Component} ancestorComponent The parent
* component to the ones being diffed
* @returns {import('../internal').PreactElement}
*/
function diffElementNodes(dom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent) {
let originalDom = dom;
// Tracks entering and exiting SVG namespace when descending through the tree.
isSvg = newVNode.type==='svg' || isSvg;
if (dom==null && excessDomChildren!=null) {
for (let i=0; i<excessDomChildren.length; i++) {
const child = excessDomChildren[i];
if (child!=null && (newVNode.type===null ? child.nodeType===3 : child.localName===newVNode.type)) {
dom = child;
excessDomChildren[i] = null;
break;
}
}
}
if (dom==null) {
dom = newVNode.type===null ? document.createTextNode(newVNode.text) : isSvg ? document.createElementNS('http://www.w3.org/2000/svg', newVNode.type) : document.createElement(newVNode.type);
// we created a new parent, so none of the previously attached children can be reused:
excessDomChildren = null;
}
if (newVNode.type===null) {
if ((originalDom==null || dom===originalDom) && newVNode.text!==oldVNode.text) {
dom.data = newVNode.text;
}
}
else {
if (excessDomChildren!=null && dom.childNodes!=null) {
excessDomChildren = EMPTY_ARR.slice.call(dom.childNodes);
}
if (newVNode!==oldVNode) {
let oldProps = oldVNode.props;
let newProps = newVNode.props;
// if we're hydrating, use the element's attributes as its current props:
if (oldProps==null) {
oldProps = {};
if (excessDomChildren!=null) {
let name;
for (let i=0; i<dom.attributes.length; i++) {
name = dom.attributes[i].name;
oldProps[name=='class' && newProps.className ? 'className' : name] = dom.attributes[i].value;
}
}
}
let oldHtml = oldProps.dangerouslySetInnerHTML;
let newHtml = newProps.dangerouslySetInnerHTML;
if (newHtml || oldHtml) {
// Avoid re-applying the same '__html' if it did not changed between re-render
if (!newHtml || !oldHtml || newHtml.__html!=oldHtml.__html) {
dom.innerHTML = newHtml && newHtml.__html || '';
}
}
if (newProps.multiple) {
dom.multiple = newProps.multiple;
}
diffChildren(dom, newVNode, oldVNode, context, newVNode.type==='foreignObject' ? false : isSvg, excessDomChildren, mounts, ancestorComponent, EMPTY_OBJ);
diffProps(dom, newProps, oldProps, isSvg);
}
}
return dom;
}
/**
* Invoke or update a ref, depending on whether it is a function or object ref.
* @param {object|function} [ref=null]
* @param {any} [value]
*/
export function applyRef(ref, value, ancestorComponent) {
try {
if (typeof ref=='function') ref(value);
else ref.current = value;
}
catch (e) {
catchErrorInComponent(e, ancestorComponent);
}
}
/**
* Unmount a virtual node from the tree and apply DOM changes
* @param {import('../internal').VNode} vnode The virtual node to unmount
* @param {import('../internal').Component} ancestorComponent The parent
* component to this virtual node
* @param {boolean} [skipRemove] Flag that indicates that a parent node of the
* current element is already detached from the DOM.
*/
export function unmount(vnode, ancestorComponent, skipRemove) {
let r;
if (options.unmount) options.unmount(vnode);
if (r = vnode.ref) {
applyRef(r, null, ancestorComponent);
}
let dom;
if (!skipRemove && vnode._lastDomChild==null) {
skipRemove = (dom = vnode._dom)!=null;
}
vnode._dom = vnode._lastDomChild = null;
if ((r = vnode._component)!=null) {
if (r.componentWillUnmount) {
try {
r.componentWillUnmount();
}
catch (e) {
catchErrorInComponent(e, ancestorComponent);
}
}
r.base = r._parentDom = null;
if (r = r._prevVNode) unmount(r, ancestorComponent, skipRemove);
}
else if (r = vnode._children) {
for (let i = 0; i < r.length; i++) {
if (r[i]) unmount(r[i], ancestorComponent, skipRemove);
}
}
if (dom!=null) removeNode(dom);
}
/** The `.render()` method for a PFC backing instance. */
function doRender(props, state, context) {
return this.constructor(props, context);
}
/**
* Find the closest error boundary to a thrown error and call it
* @param {object} error The thrown value
* @param {import('../internal').Component} component The first ancestor
* component check for error boundary behaviors
*/
function catchErrorInComponent(error, component) {
for (; component; component = component._ancestorComponent) {
if (!component._processingException) {
try {
if (component.constructor.getDerivedStateFromError!=null) {
component.setState(component.constructor.getDerivedStateFromError(error));
}
else if (component.componentDidCatch!=null) {
component.componentDidCatch(error);
}
else {
continue;
}
return enqueueRender(component._pendingError = component);
}
catch (e) {
error = e;
}
}
}
throw error;
}
| 1 | 13,281 | Can you please double check that this won't break anything? | preactjs-preact | js |
@@ -124,6 +124,7 @@ namespace Nethermind.Runner.JsonRpc
string.Empty,
new IpcSocketsHandler(socket),
RpcEndpoint.IPC,
+ null,
_jsonRpcProcessor,
_jsonRpcService,
_jsonRpcLocalStats, | 1 | using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Nethermind.Api;
using Nethermind.Config;
using Nethermind.JsonRpc;
using Nethermind.JsonRpc.Modules;
using Nethermind.JsonRpc.WebSockets;
using Nethermind.Logging;
using Nethermind.Serialization.Json;
using Nethermind.Sockets;
using Newtonsoft.Json;
namespace Nethermind.Runner.JsonRpc
{
public class JsonRpcIpcRunner : IDisposable
{
private readonly ILogger _logger;
private readonly IJsonRpcLocalStats _jsonRpcLocalStats;
private readonly IJsonSerializer _jsonSerializer;
private readonly IFileSystem _fileSystem;
private readonly IJsonRpcProcessor _jsonRpcProcessor;
private readonly IJsonRpcService _jsonRpcService;
private readonly IJsonRpcConfig _jsonRpcConfig;
private string _path;
private Socket _server;
private readonly ManualResetEvent _resetEvent = new(false);
public JsonRpcIpcRunner(
IJsonRpcProcessor jsonRpcProcessor,
IJsonRpcService jsonRpcService,
IConfigProvider configurationProvider,
ILogManager logManager,
IJsonRpcLocalStats jsonRpcLocalStats,
IJsonSerializer jsonSerializer,
IFileSystem fileSystem)
{
_jsonRpcConfig = configurationProvider.GetConfig<IJsonRpcConfig>();
_jsonRpcProcessor = jsonRpcProcessor;
_jsonRpcService = jsonRpcService;
_logger = logManager.GetClassLogger();
_jsonRpcLocalStats = jsonRpcLocalStats;
_jsonSerializer = jsonSerializer;
_fileSystem = fileSystem;
}
public void Start(CancellationToken cancellationToken)
{
_path = _jsonRpcConfig.IpcUnixDomainSocketPath;
if (!string.IsNullOrEmpty(_path))
{
_logger.Info($"Starting IPC JSON RPC service over '{_path}'");
Task.Factory.StartNew(_ => StartServer(_path), cancellationToken, TaskCreationOptions.LongRunning);
}
}
private void StartServer(string path)
{
try
{
DeleteSocketFileIfExists(path);
var endPoint = new UnixDomainSocketEndPoint(path);
_server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
_server.Bind(endPoint);
_server.Listen(0);
while (true)
{
_resetEvent.Reset();
_logger.Info("Waiting for a IPC connection...");
_server.BeginAccept(AcceptCallback, null);
_resetEvent.WaitOne();
}
}
catch (IOException exc) when (exc.InnerException != null && exc.InnerException is SocketException se && se.SocketErrorCode == SocketError.ConnectionReset)
{
LogDebug("Client disconnected.");
}
catch (SocketException exc) when (exc.SocketErrorCode == SocketError.ConnectionReset)
{
LogDebug("Client disconnected.");
}
catch (SocketException exc)
{
_logger.Error($"Error ({exc.ErrorCode}) when starting IPC server over '{_path}' path.", exc);
}
catch (Exception exc)
{
_logger.Error($"Error when starting IPC server over '{ _path}' path.", exc);
}
finally
{
Dispose();
}
}
private async void AcceptCallback(IAsyncResult ar)
{
JsonRpcSocketsClient socketsClient = null;
try
{
Socket socket = _server.EndAccept(ar);
socket.ReceiveTimeout = _jsonRpcConfig.Timeout;
socket.SendTimeout = _jsonRpcConfig.Timeout;
_resetEvent.Set();
socketsClient = new JsonRpcSocketsClient(
string.Empty,
new IpcSocketsHandler(socket),
RpcEndpoint.IPC,
_jsonRpcProcessor,
_jsonRpcService,
_jsonRpcLocalStats,
_jsonSerializer);
await socketsClient.ReceiveAsync();
}
catch (IOException exc) when (exc.InnerException != null && exc.InnerException is SocketException se && se.SocketErrorCode == SocketError.ConnectionReset)
{
LogDebug("Client disconnected.");
}
catch (SocketException exc) when (exc.SocketErrorCode == SocketError.ConnectionReset)
{
LogDebug("Client disconnected.");
}
catch (SocketException exc)
{
_logger.Warn($"Error {exc.ErrorCode}:{exc.Message}");
}
catch (Exception exc)
{
_logger.Error("Error when handling IPC communication with a client.", exc);
}
finally
{
socketsClient?.Dispose();
}
}
private void DeleteSocketFileIfExists(string path)
{
try
{
if (_fileSystem.File.Exists(path))
{
_fileSystem.File.Delete(path);
}
}
catch (Exception exc)
{
_logger.Warn($"Cannot delete UNIX socket file:{path}. {exc.Message}");
}
}
public void Dispose()
{
_server?.Dispose();
DeleteSocketFileIfExists(_path);
if (_logger.IsInfo) _logger.Info("IPC JSON RPC service stopped");
}
private void LogDebug(string msg)
{
if (_logger.IsDebug) _logger.Debug(msg);
}
}
}
| 1 | 26,341 | optionals, shouldn't need to be stated explicitly | NethermindEth-nethermind | .cs |
@@ -7,13 +7,15 @@ import (
// VersionNumber is a version number as int
type VersionNumber int
-// gquicVersion0 is the "base" for gQUIC versions
-// e.g. version 39 is gquicVersion + 0x39
-const gquicVersion0 = 0x51303300
+// gQUIC version range as defined in the wiki: https://github.com/quicwg/base-drafts/wiki/QUIC-Versions
+const (
+ gquicVersion0 = 0x51303030
+ maxGquicVersion = 0x51303439
+)
// The version numbers, making grepping easier
const (
- Version37 VersionNumber = gquicVersion0 + 0x37 + iota
+ Version37 VersionNumber = gquicVersion0 + 3*0x100 + 0x7 + iota
Version38
Version39
VersionTLS VersionNumber = 101 | 1 | package protocol
import (
"fmt"
)
// VersionNumber is a version number as int
type VersionNumber int
// gquicVersion0 is the "base" for gQUIC versions
// e.g. version 39 is gquicVersion + 0x39
const gquicVersion0 = 0x51303300
// The version numbers, making grepping easier
const (
Version37 VersionNumber = gquicVersion0 + 0x37 + iota
Version38
Version39
VersionTLS VersionNumber = 101
VersionWhatever VersionNumber = 0 // for when the version doesn't matter
VersionUnsupported VersionNumber = -1
VersionUnknown VersionNumber = -2
)
// SupportedVersions lists the versions that the server supports
// must be in sorted descending order
var SupportedVersions = []VersionNumber{
Version39,
Version38,
Version37,
}
// UsesTLS says if this QUIC version uses TLS 1.3 for the handshake
func (vn VersionNumber) UsesTLS() bool {
return vn == VersionTLS
}
func (vn VersionNumber) String() string {
switch vn {
case VersionWhatever:
return "whatever"
case VersionUnsupported:
return "unsupported"
case VersionUnknown:
return "unknown"
case VersionTLS:
return "TLS dev version (WIP)"
default:
if vn > gquicVersion0 && vn <= gquicVersion0+0x99 {
return fmt.Sprintf("gQUIC %x", uint32(vn-gquicVersion0))
}
return fmt.Sprintf("%d", vn)
}
}
// ToAltSvc returns the representation of the version for the H2 Alt-Svc parameters
func (vn VersionNumber) ToAltSvc() string {
if vn > gquicVersion0 && vn <= gquicVersion0+0x99 {
return fmt.Sprintf("%x", uint32(vn-gquicVersion0))
}
return fmt.Sprintf("%d", vn)
}
// IsSupportedVersion returns true if the server supports this version
func IsSupportedVersion(supported []VersionNumber, v VersionNumber) bool {
for _, t := range supported {
if t == v {
return true
}
}
return false
}
// ChooseSupportedVersion finds the best version in the overlap of ours and theirs
// ours is a slice of versions that we support, sorted by our preference (descending)
// theirs is a slice of versions offered by the peer. The order does not matter
// if no suitable version is found, it returns VersionUnsupported
func ChooseSupportedVersion(ours, theirs []VersionNumber) VersionNumber {
for _, ourVer := range ours {
for _, theirVer := range theirs {
if ourVer == theirVer {
return ourVer
}
}
}
return VersionUnsupported
}
| 1 | 6,923 | That seems quite low - why not just 0x5130ffff? | lucas-clemente-quic-go | go |
@@ -76,7 +76,8 @@ class Net(Gen):
self.repr=net
self.parsed,self.netmask = self._parse_net(net)
-
+ def __str__(self):
+ return self.repr
def __iter__(self):
for d in xrange(*self.parsed[3]): | 1 | ## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <[email protected]>
## This program is published under a GPLv2 license
"""
Generators and packet meta classes.
"""
###############
## Generators ##
################
import re,random,socket
import types
class Gen(object):
__slots__ = []
def __iter__(self):
return iter([])
class SetGen(Gen):
def __init__(self, values, _iterpacket=1):
self._iterpacket=_iterpacket
if isinstance(values, (list, BasePacketList)):
self.values = list(values)
elif (type(values) is tuple) and (2 <= len(values) <= 3) and \
all(type(i) is int for i in values):
# We use values[1] + 1 as stop value for xrange to maintain
# the behavior of using tuples as field `values`
self.values = [xrange(*((values[0], values[1] + 1) + values[2:]))]
else:
self.values = [values]
def transf(self, element):
return element
def __iter__(self):
for i in self.values:
if (isinstance(i, Gen) and
(self._iterpacket or not isinstance(i,BasePacket))) or (
isinstance(i, (xrange, types.GeneratorType))):
for j in i:
yield j
else:
yield i
def __repr__(self):
return "<SetGen %r>" % self.values
class Net(Gen):
"""Generate a list of IPs from a network address or a name"""
name = "ip"
ipaddress = re.compile(r"^(\*|[0-2]?[0-9]?[0-9](-[0-2]?[0-9]?[0-9])?)\.(\*|[0-2]?[0-9]?[0-9](-[0-2]?[0-9]?[0-9])?)\.(\*|[0-2]?[0-9]?[0-9](-[0-2]?[0-9]?[0-9])?)\.(\*|[0-2]?[0-9]?[0-9](-[0-2]?[0-9]?[0-9])?)(/[0-3]?[0-9])?$")
@staticmethod
def _parse_digit(a,netmask):
netmask = min(8,max(netmask,0))
if a == "*":
a = (0,256)
elif a.find("-") >= 0:
x,y = map(int,a.split("-"))
if x > y:
y = x
a = (x & (0xffL<<netmask) , max(y, (x | (0xffL>>(8-netmask))))+1)
else:
a = (int(a) & (0xffL<<netmask),(int(a) | (0xffL>>(8-netmask)))+1)
return a
@classmethod
def _parse_net(cls, net):
tmp=net.split('/')+["32"]
if not cls.ipaddress.match(net):
tmp[0]=socket.gethostbyname(tmp[0])
netmask = int(tmp[1])
return map(lambda x,y: cls._parse_digit(x,y), tmp[0].split("."), map(lambda x,nm=netmask: x-nm, (8,16,24,32))),netmask
def __init__(self, net):
self.repr=net
self.parsed,self.netmask = self._parse_net(net)
def __iter__(self):
for d in xrange(*self.parsed[3]):
for c in xrange(*self.parsed[2]):
for b in xrange(*self.parsed[1]):
for a in xrange(*self.parsed[0]):
yield "%i.%i.%i.%i" % (a,b,c,d)
def choice(self):
ip = []
for v in self.parsed:
ip.append(str(random.randint(v[0],v[1]-1)))
return ".".join(ip)
def __repr__(self):
return "Net(%r)" % self.repr
def __eq__(self, other):
if hasattr(other, "parsed"):
p2 = other.parsed
else:
p2,nm2 = self._parse_net(other)
return self.parsed == p2
def __contains__(self, other):
if hasattr(other, "parsed"):
p2 = other.parsed
else:
p2,nm2 = self._parse_net(other)
for (a1,b1),(a2,b2) in zip(self.parsed,p2):
if a1 > a2 or b1 < b2:
return False
return True
def __rcontains__(self, other):
return self in self.__class__(other)
class OID(Gen):
name = "OID"
def __init__(self, oid):
self.oid = oid
self.cmpt = []
fmt = []
for i in oid.split("."):
if "-" in i:
fmt.append("%i")
self.cmpt.append(tuple(map(int, i.split("-"))))
else:
fmt.append(i)
self.fmt = ".".join(fmt)
def __repr__(self):
return "OID(%r)" % self.oid
def __iter__(self):
ii = [k[0] for k in self.cmpt]
while 1:
yield self.fmt % tuple(ii)
i = 0
while 1:
if i >= len(ii):
raise StopIteration
if ii[i] < self.cmpt[i][1]:
ii[i]+=1
break
else:
ii[i] = self.cmpt[i][0]
i += 1
######################################
## Packet abstract and base classes ##
######################################
class Packet_metaclass(type):
def __new__(cls, name, bases, dct):
if "fields_desc" in dct: # perform resolution of references to other packets
current_fld = dct["fields_desc"]
resolved_fld = []
for f in current_fld:
if isinstance(f, Packet_metaclass): # reference to another fields_desc
for f2 in f.fields_desc:
resolved_fld.append(f2)
else:
resolved_fld.append(f)
else: # look for a field_desc in parent classes
resolved_fld = None
for b in bases:
if hasattr(b,"fields_desc"):
resolved_fld = b.fields_desc
break
if resolved_fld: # perform default value replacements
final_fld = []
for f in resolved_fld:
if f.name in dct:
f = f.copy()
f.default = dct[f.name]
del(dct[f.name])
final_fld.append(f)
dct["fields_desc"] = final_fld
if "__slots__" not in dct:
dct["__slots__"] = []
for attr in ["name", "overload_fields"]:
try:
dct["_%s" % attr] = dct.pop(attr)
except KeyError:
pass
newcls = super(Packet_metaclass, cls).__new__(cls, name, bases, dct)
newcls.__all_slots__ = set(
attr
for cls in newcls.__mro__ if hasattr(cls, "__slots__")
for attr in cls.__slots__
)
if hasattr(newcls, "aliastypes"):
newcls.aliastypes = [newcls] + newcls.aliastypes
else:
newcls.aliastypes = [newcls]
if hasattr(newcls,"register_variant"):
newcls.register_variant()
for f in newcls.fields_desc:
if hasattr(f, "register_owner"):
f.register_owner(newcls)
from scapy import config
config.conf.layers.register(newcls)
return newcls
def __getattr__(self, attr):
for k in self.fields_desc:
if k.name == attr:
return k
raise AttributeError(attr)
def __call__(cls, *args, **kargs):
if "dispatch_hook" in cls.__dict__:
try:
cls = cls.dispatch_hook(*args, **kargs)
except:
from scapy import config
if config.conf.debug_dissector:
raise
cls = config.conf.raw_layer
i = cls.__new__(cls, cls.__name__, cls.__bases__, cls.__dict__)
i.__init__(*args, **kargs)
return i
class Field_metaclass(type):
def __new__(cls, name, bases, dct):
if "__slots__" not in dct:
dct["__slots__"] = []
newcls = super(Field_metaclass, cls).__new__(cls, name, bases, dct)
return newcls
class NewDefaultValues(Packet_metaclass):
"""NewDefaultValues is deprecated (not needed anymore)
remove this:
__metaclass__ = NewDefaultValues
and it should still work.
"""
def __new__(cls, name, bases, dct):
from scapy.error import log_loading
import traceback
try:
for tb in traceback.extract_stack()+[("??",-1,None,"")]:
f,l,_,line = tb
if line.startswith("class"):
break
except:
f,l="??",-1
raise
log_loading.warning("Deprecated (no more needed) use of NewDefaultValues (%s l. %i)." % (f,l))
return super(NewDefaultValues, cls).__new__(cls, name, bases, dct)
class BasePacket(Gen):
__slots__ = []
#############################
## Packet list base class ##
#############################
class BasePacketList(object):
__slots__ = []
| 1 | 9,265 | Why is this needed ? | secdev-scapy | py |
@@ -77,6 +77,14 @@ module Bolt
File.exist?(path) ? read_yaml_hash(path, file_name) : {}
end
+ def first_runs_free
+ Bolt::Config.user_path + '.first_runs_free'
+ end
+
+ def first_run?
+ Bolt::Config.user_path && !File.exist?(first_runs_free)
+ end
+
# Accepts a path with either 'plans' or 'tasks' in it and determines
# the name of the module
def module_name(path) | 1 | # frozen_string_literal: true
module Bolt
module Util
class << self
# Gets input for an argument.
def get_arg_input(value)
if value.start_with?('@')
file = value.sub(/^@/, '')
read_arg_file(file)
elsif value == '-'
$stdin.read
else
value
end
end
# Reads a file passed as an argument to a command.
def read_arg_file(file)
File.read(File.expand_path(file))
rescue StandardError => e
raise Bolt::FileError.new("Error attempting to read #{file}: #{e}", file)
end
def read_json_file(path, filename)
require 'json'
logger = Bolt::Logger.logger(self)
path = File.expand_path(path)
content = JSON.parse(File.read(path))
logger.trace("Loaded #{filename} from #{path}")
content
rescue Errno::ENOENT
raise Bolt::FileError.new("Could not read #{filename} file at #{path}", path)
rescue JSON::ParserError => e
msg = "Unable to parse #{filename} file at #{path} as JSON: #{e.message}"
raise Bolt::FileError.new(msg, path)
rescue IOError, SystemCallError => e
raise Bolt::FileError.new("Could not read #{filename} file at #{path}\n#{e.message}",
path)
end
def read_optional_json_file(path, file_name)
File.exist?(path) && !File.zero?(path) ? read_yaml_hash(path, file_name) : {}
end
def read_yaml_hash(path, file_name)
require 'yaml'
logger = Bolt::Logger.logger(self)
path = File.expand_path(path)
content = File.open(path, "r:UTF-8") { |f| YAML.safe_load(f.read) } || {}
unless content.is_a?(Hash)
raise Bolt::FileError.new(
"Invalid content for #{file_name} file at #{path}\nContent should be a Hash or empty, "\
"not #{content.class}",
path
)
end
logger.trace("Loaded #{file_name} from #{path}")
content
rescue Errno::ENOENT
raise Bolt::FileError.new("Could not read #{file_name} file at #{path}", path)
rescue Psych::SyntaxError => e
raise Bolt::FileError.new("Could not parse #{file_name} file at #{path}, line #{e.line}, "\
"column #{e.column}\n#{e.problem}",
path)
rescue Psych::Exception => e
raise Bolt::FileError.new("Could not parse #{file_name} file at #{path}\n#{e.message}",
path)
rescue IOError, SystemCallError => e
raise Bolt::FileError.new("Could not read #{file_name} file at #{path}\n#{e.message}",
path)
end
def read_optional_yaml_hash(path, file_name)
File.exist?(path) ? read_yaml_hash(path, file_name) : {}
end
# Accepts a path with either 'plans' or 'tasks' in it and determines
# the name of the module
def module_name(path)
# Remove extra dots and slashes
path = Pathname.new(path).cleanpath.to_s
fs = File::SEPARATOR
regex = Regexp.new("#{fs}plans#{fs}|#{fs}tasks#{fs}")
# Only accept paths with '/plans/' or '/tasks/'
unless path.match?(regex)
msg = "Could not determine module from #{path}. "\
"The path must include 'plans' or 'tasks' directory"
raise Bolt::Error.new(msg, 'bolt/modulepath-error')
end
# Split the path on the first instance of /plans/ or /tasks/
parts = path.split(regex, 2)
# Module name is the last entry before 'plans' or 'tasks'
modulename = parts[0].split(fs)[-1]
filename = File.basename(path).split('.')[0]
# Remove "/init.*" if filename is init or just remove the file
# extension
if filename == 'init'
parts[1].chomp!(File.basename(path))
else
parts[1].chomp!(File.extname(path))
end
# The plan or task name is the rest of the path
[modulename, parts[1].split(fs)].flatten.join('::')
end
def to_code(string)
case string
when Bolt::PAL::YamlPlan::DoubleQuotedString
string.value.inspect
when Bolt::PAL::YamlPlan::BareString
if string.value.start_with?('$')
string.value.to_s
else
"'#{string.value}'"
end
when Bolt::PAL::YamlPlan::EvaluableString, Bolt::PAL::YamlPlan::CodeLiteral
string.value.to_s
when String
"'#{string}'"
when Hash
formatted = String.new("{")
string.each do |k, v|
formatted << "#{to_code(k)} => #{to_code(v)}, "
end
formatted.chomp!(", ")
formatted << "}"
formatted
when Array
formatted = String.new("[")
formatted << string.map { |str| to_code(str) }.join(', ')
formatted << "]"
formatted
else
string
end
end
def deep_merge(hash1, hash2)
recursive_merge = proc do |_key, h1, h2|
if h1.is_a?(Hash) && h2.is_a?(Hash)
h1.merge(h2, &recursive_merge)
else
h2
end
end
hash1.merge(hash2, &recursive_merge)
end
# Accepts a Data object and returns a copy with all hash keys
# modified by block. use &:to_s to stringify keys or &:to_sym to symbolize them
def walk_keys(data, &block)
case data
when Hash
data.each_with_object({}) do |(k, v), acc|
v = walk_keys(v, &block)
acc[yield(k)] = v
end
when Array
data.map { |v| walk_keys(v, &block) }
else
data
end
end
# Accepts a Data object and returns a copy with all hash and array values
# Arrays and hashes including the initial object are modified before
# their descendants are.
def walk_vals(data, skip_top = false, &block)
data = yield(data) unless skip_top
case data
when Hash
data.transform_values { |v| walk_vals(v, &block) }
when Array
data.map { |v| walk_vals(v, &block) }
else
data
end
end
# Accepts a Data object and returns a copy with all hash and array values
# modified by the given block. Descendants are modified before their
# parents.
def postwalk_vals(data, skip_top = false, &block)
new_data = case data
when Hash
data.transform_values { |v| postwalk_vals(v, &block) }
when Array
data.map { |v| postwalk_vals(v, &block) }
else
data
end
if skip_top
new_data
else
yield(new_data)
end
end
# Performs a deep_clone, using an identical copy if the cloned structure contains multiple
# references to the same object and prevents endless recursion.
# Credit to Jan Molic via https://github.com/rubyworks/facets/blob/master/LICENSE.txt
def deep_clone(obj, cloned = {})
return cloned[obj.object_id] if cloned.include?(obj.object_id)
# The `defined?` method will not reliably find the Java::JavaLang::CloneNotSupportedException constant
# presumably due to some sort of optimization that short-cuts doing a bunch of Java introspection.
# Java::JavaLang::<...> IS defining the constant (via const_missing or const_get magic perhaps) so
# it is safe to reference it in the error_types array when a JRuby interpreter is evaluating the code
# (detected by RUBY_PLATFORM == `java`). SO instead of conditionally adding the CloneNotSupportedException
# constant to the error_types array based on `defined?` detecting the Java::JavaLang constant it is added
# based on detecting a JRuby interpreter.
# TypeError handles unclonable Ruby ojbects (TrueClass, Fixnum, ...)
# CloneNotSupportedException handles uncloneable Java objects (JRuby only)
error_types = [TypeError]
error_types << Java::JavaLang::CloneNotSupportedException if RUBY_PLATFORM == 'java'
begin
# We can't recurse on frozen objects to populate them with cloned
# data. Instead we store the freeze-state of the original object,
# deep_clone, then set the cloned object to frozen if the original
# object was frozen
frozen = obj.frozen?
cl = begin
obj.clone(freeze: false)
# Some datatypes, such as FalseClass, can't be unfrozen. These
# aren't the types we recurse on, so we can leave them frozen
rescue ArgumentError => e
if e.message =~ /can't unfreeze/
obj.clone
else
raise e
end
end
rescue *error_types
cloned[obj.object_id] = obj
obj
else
cloned[obj.object_id] = cl
cloned[cl.object_id] = cl
case cl
when Hash
obj.each { |k, v| cl[k] = deep_clone(v, cloned) }
when Array
cl.collect! { |v| deep_clone(v, cloned) }
when Struct
obj.each_pair { |k, v| cl[k] = deep_clone(v, cloned) }
end
cl.instance_variables.each do |var|
v = cl.instance_variable_get(var)
v_cl = deep_clone(v, cloned)
cl.instance_variable_set(var, v_cl)
end
cl.freeze if frozen
cl
end
end
# This is stubbed for testing validate_file
def file_stat(path)
File.stat(File.expand_path(path))
end
def snake_name_to_class_name(snake_name)
snake_name.split('_').map(&:capitalize).join
end
def class_name_to_file_name(cls_name)
# Note this turns Bolt::CLI -> 'bolt/cli' not 'bolt/c_l_i'
# this won't handle Bolt::Inventory2Foo
cls_name.gsub(/([a-z])([A-Z])/, '\1_\2').gsub('::', '/').downcase
end
def validate_file(type, path, allow_dir = false)
stat = file_stat(path)
if !stat.readable?
raise Bolt::FileError.new("The #{type} '#{path}' is unreadable", path)
elsif !stat.file? && (!allow_dir || !stat.directory?)
expected = allow_dir ? 'file or directory' : 'file'
raise Bolt::FileError.new("The #{type} '#{path}' is not a #{expected}", path)
elsif stat.directory?
Dir.foreach(path) do |file|
next if %w[. ..].include?(file)
validate_file(type, File.join(path, file), allow_dir)
end
end
rescue Errno::ENOENT
raise Bolt::FileError.new("The #{type} '#{path}' does not exist", path)
end
# Returns true if windows false if not.
def windows?
!!File::ALT_SEPARATOR
end
# Returns true if running in PowerShell.
def powershell?
!!ENV['PSModulePath']
end
# Accept hash and return hash with top level keys of type "String" converted to symbols.
def symbolize_top_level_keys(hsh)
hsh.each_with_object({}) { |(k, v), h| k.is_a?(String) ? h[k.to_sym] = v : h[k] = v }
end
# Recursively searches a data structure for plugin references
def references?(input)
case input
when Hash
input.key?('_plugin') || input.values.any? { |v| references?(v) }
when Array
input.any? { |v| references?(v) }
else
false
end
end
def unix_basename(path)
raise Bolt::ValidationError, "path must be a String, received #{path.class} #{path}" unless path.is_a?(String)
path.split('/').last
end
def windows_basename(path)
raise Bolt::ValidationError, "path must be a String, received #{path.class} #{path}" unless path.is_a?(String)
path.split(%r{[/\\]}).last
end
# Prompts yes or no, returning true for yes and false for no.
#
def prompt_yes_no(prompt, outputter)
choices = {
'y' => true,
'yes' => true,
'n' => false,
'no' => false
}
loop do
outputter.print_prompt("#{prompt} ([y]es/[n]o) ")
response = $stdin.gets.to_s.downcase.chomp
if choices.key?(response)
return choices[response]
else
outputter.print_prompt_error("Invalid response, must pick [y]es or [n]o")
end
end
end
end
end
end
| 1 | 18,001 | `Bolt::Config.user_path` returns `nil` if there's no homedir, so this will still error in that case. | puppetlabs-bolt | rb |
@@ -113,6 +113,9 @@ func (a networkAction) String() string {
if a.t() == ignore || a.t() == disconnect {
return fmt.Sprintf("%v: %5v", a.t().String(), a.Err)
}
+ if a.Tag == protocol.ProposalPayloadTag {
+ return fmt.Sprintf("%v: %2v: %5v", a.t().String(), a.Tag, a.CompoundMessage.Proposal.value())
+ }
return fmt.Sprintf("%v: %2v", a.t().String(), a.Tag)
}
| 1 | // Copyright (C) 2019 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package agreement
import (
"context"
"fmt"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/logging/logspec"
"github.com/algorand/go-algorand/logging/telemetryspec"
"github.com/algorand/go-algorand/protocol"
)
//go:generate stringer -type=actionType
type actionType int
const (
noop actionType = iota
// network
ignore
broadcast
relay
disconnect
broadcastVotes
// crypto
verifyVote
verifyPayload
verifyBundle
// ledger
ensure
// time
rezero
// logical
attest
assemble
repropose
// disk
checkpoint
)
type action interface {
t() actionType
persistent() bool
do(context.Context, *Service)
String() string
}
type nonpersistent struct{}
func (nonpersistent) persistent() bool {
return false
}
type noopAction struct {
nonpersistent
}
func (a noopAction) t() actionType {
return noop
}
func (a noopAction) do(context.Context, *Service) {}
func (a noopAction) String() string {
return a.t().String()
}
type networkAction struct {
nonpersistent
// ignore, broadcast, broadcastVotes, relay, disconnect
T actionType
Tag protocol.Tag
h MessageHandle // this is cleared to correctly handle ephemeral network state on recovery
UnauthenticatedVote unauthenticatedVote
UnauthenticatedBundle unauthenticatedBundle
CompoundMessage compoundMessage
UnauthenticatedVotes []unauthenticatedVote
Err serializableError
}
func (a networkAction) t() actionType {
return a.T
}
func (a networkAction) String() string {
if a.t() == ignore || a.t() == disconnect {
return fmt.Sprintf("%v: %5v", a.t().String(), a.Err)
}
return fmt.Sprintf("%v: %2v", a.t().String(), a.Tag)
}
func (a networkAction) do(ctx context.Context, s *Service) {
if a.T == broadcastVotes {
tag := protocol.AgreementVoteTag
for i, uv := range a.UnauthenticatedVotes {
data := protocol.Encode(uv)
sendErr := s.Network.Broadcast(tag, data)
if sendErr != nil {
s.log.Warnf("Network was unable to queue votes for broadcast(%v). %d / %d votes for round %d period %d step %d were dropped.",
sendErr,
len(a.UnauthenticatedVotes)-i, len(a.UnauthenticatedVotes),
uv.R.Round,
uv.R.Period,
uv.R.Step)
break
}
if ctx.Err() != nil {
break
}
}
return
}
var data []byte
switch a.Tag {
case protocol.AgreementVoteTag:
data = protocol.Encode(a.UnauthenticatedVote)
case protocol.VoteBundleTag:
data = protocol.Encode(a.UnauthenticatedBundle)
case protocol.ProposalPayloadTag:
msg := a.CompoundMessage
payload := transmittedPayload{
unauthenticatedProposal: msg.Proposal,
PriorVote: msg.Vote,
}
data = protocol.Encode(payload)
}
switch a.T {
case broadcast:
s.Network.Broadcast(a.Tag, data)
case relay:
s.Network.Relay(a.h, a.Tag, data)
case disconnect:
s.Network.Disconnect(a.h)
case ignore:
// pass
}
}
type cryptoAction struct {
nonpersistent
// verify{Vote,Payload,Bundle}
T actionType
M message
Proposal proposalValue // TODO deprecate
Round round
Period period
Pinned bool
TaskIndex int
}
func (a cryptoAction) t() actionType {
return a.T
}
func (a cryptoAction) String() string {
return a.t().String()
}
func (a cryptoAction) do(ctx context.Context, s *Service) {
switch a.T {
case verifyVote:
s.demux.verifyVote(ctx, a.M, a.TaskIndex, a.Round, a.Period)
case verifyPayload:
s.demux.verifyPayload(ctx, a.M, a.Round, a.Period, a.Pinned)
case verifyBundle:
s.demux.verifyBundle(ctx, a.M, a.Round, a.Period)
}
}
type ensureAction struct {
nonpersistent
Payload proposal
PayloadOk bool
Certificate Certificate
}
func (a ensureAction) t() actionType {
return ensure
}
func (a ensureAction) String() string {
return fmt.Sprintf("%v: %.5v", a.t().String(), a.Payload.Digest().String())
}
func (a ensureAction) do(ctx context.Context, s *Service) {
logEvent := logspec.AgreementEvent{
Hash: a.Certificate.Proposal.BlockDigest.String(),
Round: uint64(a.Certificate.Round),
Period: uint64(a.Certificate.Period),
Sender: a.Certificate.Proposal.OriginalProposer.String(),
}
if a.Payload.ve != nil {
logEvent.Type = logspec.RoundConcluded
s.log.with(logEvent).Infof("committed round %v with pre-validated block %v", a.Certificate.Round, a.Certificate.Proposal)
s.log.EventWithDetails(telemetryspec.Agreement, telemetryspec.BlockAcceptedEvent, telemetryspec.BlockAcceptedEventDetails{
Address: a.Certificate.Proposal.OriginalProposer.String(),
Hash: a.Certificate.Proposal.BlockDigest.String(),
Round: uint64(a.Certificate.Round),
})
s.Ledger.EnsureValidatedBlock(a.Payload.ve, a.Certificate)
} else {
block := a.Payload.Block
if !a.PayloadOk {
logEvent.Type = logspec.RoundWaiting
s.log.with(logEvent).Infof("round %v concluded without block for %v; waiting on ledger", a.Certificate.Round, a.Certificate.Proposal)
s.Ledger.EnsureDigest(a.Certificate, s.quit, s.voteVerifier)
} else {
logEvent.Type = logspec.RoundConcluded
s.log.with(logEvent).Infof("committed round %v with block %v", a.Certificate.Round, a.Certificate.Proposal)
s.log.EventWithDetails(telemetryspec.Agreement, telemetryspec.BlockAcceptedEvent, telemetryspec.BlockAcceptedEventDetails{
Address: a.Certificate.Proposal.OriginalProposer.String(),
Hash: a.Certificate.Proposal.BlockDigest.String(),
Round: uint64(a.Certificate.Round),
})
s.Ledger.EnsureBlock(block, a.Certificate)
}
}
logEventStart := logEvent
logEventStart.Type = logspec.RoundStart
s.log.with(logEventStart).Infof("finished round %v", a.Certificate.Round)
s.tracer.timeR().StartRound(a.Certificate.Round + 1)
s.tracer.timeR().RecStep(0, propose, bottom)
}
type rezeroAction struct {
nonpersistent
Round round
}
func (a rezeroAction) t() actionType {
return rezero
}
func (a rezeroAction) String() string {
return a.t().String()
}
func (a rezeroAction) do(ctx context.Context, s *Service) {
s.Clock = s.Clock.Zero()
}
type pseudonodeAction struct {
// assemble, repropose, attest
T actionType
Round round
Period period
Step step
Proposal proposalValue
}
func (a pseudonodeAction) t() actionType {
return a.T
}
func (a pseudonodeAction) String() string {
return fmt.Sprintf("%v %3v-%2v-%2v: %.5v", a.t().String(), a.Round, a.Period, a.Step, a.Proposal.BlockDigest.String())
}
func (a pseudonodeAction) persistent() bool {
return a.T == attest
}
func (a pseudonodeAction) do(ctx context.Context, s *Service) {
// making proposals and/or voting are opportunistic actions. If we're unable to generate the proposals/votes
// due some internal reason, we should just drop that; the protocol would recover by using other proposers and/or
// will go to the next period.
switch a.T {
// loopback
case assemble:
events, err := s.loopback.MakeProposals(ctx, a.Round, a.Period)
switch err {
case nil:
s.demux.prioritize(events)
case errPseudonodeNoProposals:
// no participation keys, do nothing.
default:
logging.Base().Errorf("pseudonode.MakeProposals call failed %v", err)
}
case repropose:
logEvent := logspec.AgreementEvent{
Type: logspec.VoteAttest,
Round: uint64(a.Round),
Period: uint64(a.Period),
Step: uint64(propose),
Hash: a.Proposal.BlockDigest.String(),
}
s.log.with(logEvent).Infof("repropose to %v at (%v, %v, %v)", a.Proposal, a.Round, a.Period, propose)
// create a channel that would get closed when we're done storing the persistence information to disk.
// ( or will let us know if we failed ! )
persistStateDone := make(chan error)
close(persistStateDone)
events, err := s.loopback.MakeVotes(ctx, a.Round, a.Period, propose, a.Proposal, persistStateDone)
switch err {
case nil:
// no error.
s.demux.prioritize(events)
case errPseudonodeNoVotes:
// do nothing
default:
// otherwise,
logging.Base().Errorf("pseudonode.MakeVotes call failed for reproposal(%v) %v", a.T, err)
}
case attest:
logEvent := logspec.AgreementEvent{
Type: logspec.VoteAttest,
Round: uint64(a.Round),
Period: uint64(a.Period),
Step: uint64(a.Step),
Hash: a.Proposal.BlockDigest.String(),
}
s.log.with(logEvent).Infof("attested to %v at (%v, %v, %v)", a.Proposal, a.Round, a.Period, a.Step)
// create a channel that would get closed when we're done storing the persistence information to disk.
// ( or will let us know if we failed ! )
persistStateDone := make(chan error)
voteEvents, err := s.loopback.MakeVotes(ctx, a.Round, a.Period, a.Step, a.Proposal, persistStateDone)
switch err {
case nil:
// no error.
persistCompleteEvents := s.persistState(persistStateDone)
// we want to place there two one after the other. That way, the second would not get executed up until the first one is complete.
s.demux.prioritize(persistCompleteEvents)
s.demux.prioritize(voteEvents)
default:
// otherwise,
logging.Base().Errorf("pseudonode.MakeVotes call failed(%v) %v", a.T, err)
fallthrough // just so that we would close the channel.
case errPseudonodeNoVotes:
// do nothing; we're closing the channel just to avoid leaving open channels, but it's not
// really do anything at this point.
close(persistStateDone)
}
}
}
func ignoreAction(e messageEvent, err serializableError) action {
return networkAction{T: ignore, Err: err, h: e.Input.MessageHandle}
}
func disconnectAction(e messageEvent, err serializableError) action {
return networkAction{T: disconnect, Err: err, h: e.Input.MessageHandle}
}
func broadcastAction(tag protocol.Tag, o interface{}) action {
a := networkAction{T: broadcast, Tag: tag}
// TODO would be good to have compiler check this (and related) type switch
// by specializing one method per type
switch tag {
case protocol.AgreementVoteTag:
a.UnauthenticatedVote = o.(unauthenticatedVote)
case protocol.VoteBundleTag:
a.UnauthenticatedBundle = o.(unauthenticatedBundle)
case protocol.ProposalPayloadTag:
a.CompoundMessage = o.(compoundMessage)
}
return a
}
func relayAction(e messageEvent, tag protocol.Tag, o interface{}) action {
a := networkAction{T: relay, h: e.Input.MessageHandle, Tag: tag}
// TODO would be good to have compiler check this (and related) type switch
// by specializing one method per type
switch tag {
case protocol.AgreementVoteTag:
a.UnauthenticatedVote = o.(unauthenticatedVote)
case protocol.VoteBundleTag:
a.UnauthenticatedBundle = o.(unauthenticatedBundle)
case protocol.ProposalPayloadTag:
a.CompoundMessage = o.(compoundMessage)
}
return a
}
func verifyBundleAction(e messageEvent, r round, p period) action {
return cryptoAction{T: verifyBundle, M: e.Input, Round: r, Period: p}
}
func verifyVoteAction(e messageEvent, r round, p period, taskIndex int) action {
return cryptoAction{T: verifyVote, M: e.Input, Round: r, Period: p, TaskIndex: taskIndex}
}
func verifyPayloadAction(e messageEvent, r round, p period, pinned bool) action {
return cryptoAction{T: verifyPayload, M: e.Input, Round: r, Period: p, Pinned: pinned}
}
func zeroAction(t actionType) action {
switch t {
case noop:
return noopAction{}
case ignore, broadcast, relay, disconnect, broadcastVotes:
return networkAction{}
case verifyVote, verifyPayload, verifyBundle:
return cryptoAction{}
case ensure:
return ensureAction{}
case rezero:
return rezeroAction{}
case attest, assemble, repropose:
return pseudonodeAction{}
case checkpoint:
return checkpointAction{}
default:
err := fmt.Errorf("bad action type: %v", t)
panic(err)
}
}
type checkpointAction struct {
Round round
Period period
Step step
Err serializableError
done chan error // an output channel to let the pseudonode that we're done processing. We don't want to serialize that, since it's not needed in recovery/autopsy
}
func (c checkpointAction) t() actionType {
return checkpoint
}
func (c checkpointAction) persistent() bool {
return false
}
func (c checkpointAction) do(ctx context.Context, s *Service) {
logEvent := logspec.AgreementEvent{
Type: logspec.Persisted,
Round: uint64(c.Round),
Period: uint64(c.Period),
Step: uint64(c.Step),
}
if c.Err == nil {
s.log.with(logEvent).Infof("checkpoint at (%v, %v, %v)", c.Round, c.Period, c.Step)
} else {
s.log.with(logEvent).Errorf("checkpoint at (%v, %v, %v) failed : %v", c.Round, c.Period, c.Step, c.Err)
if c.done != nil {
c.done <- c.Err
}
}
if c.done != nil {
close(c.done)
} else {
// c.done == nil
// we don't expect this to happen in recovery
s.log.with(logEvent).Errorf("checkpoint action for (%v, %v, %v) reached with nil completion channel", c.Round, c.Period, c.Step)
}
return
}
func (c checkpointAction) String() string {
return c.t().String()
}
| 1 | 35,987 | nit: use %s for strings and %v for objects. | algorand-go-algorand | go |
@@ -8,16 +8,6 @@ class TTemplateParamClass extends TClassString
*/
public $param_name;
- /**
- * @var string
- */
- public $as;
-
- /**
- * @var ?TNamedObject
- */
- public $as_type;
-
/**
* @var string
*/ | 1 | <?php
namespace Psalm\Type\Atomic;
class TTemplateParamClass extends TClassString
{
/**
* @var string
*/
public $param_name;
/**
* @var string
*/
public $as;
/**
* @var ?TNamedObject
*/
public $as_type;
/**
* @var string
*/
public $defining_class;
public function __construct(
string $param_name,
string $as,
?TNamedObject $as_type,
string $defining_class
) {
$this->param_name = $param_name;
$this->as = $as;
$this->as_type = $as_type;
$this->defining_class = $defining_class;
}
public function getKey(bool $include_extra = true): string
{
return 'class-string<' . $this->param_name . '>';
}
public function __toString(): string
{
return 'class-string<' . $this->param_name . '>';
}
public function getId(bool $nested = false): string
{
return 'class-string<' . $this->param_name . ':' . $this->defining_class . ' as ' . $this->as . '>';
}
public function getAssertionString(): string
{
return 'class-string<' . $this->param_name . '>';
}
/**
* @param array<string> $aliased_classes
*/
public function toPhpString(
?string $namespace,
array $aliased_classes,
?string $this_class,
int $php_major_version,
int $php_minor_version
): ?string {
return 'string';
}
public function canBeFullyExpressedInPhp(): bool
{
return false;
}
/**
* @param array<string> $aliased_classes
*
*/
public function toNamespacedString(
?string $namespace,
array $aliased_classes,
?string $this_class,
bool $use_phpdoc_format
): string {
return $this->param_name . '::class';
}
public function getChildNodes() : array
{
return $this->as_type ? [$this->as_type] : [];
}
}
| 1 | 9,166 | Same as before, the properties already exists in parent | vimeo-psalm | php |
@@ -25,11 +25,11 @@ if __name__ == "__main__":
copy_file(os.path.join(source, "lib_lightgbm.dll"), os.path.join(windows_folder_path, "lib_lightgbm.dll"))
copy_file(os.path.join(source, "lightgbm.exe"), os.path.join(windows_folder_path, "lightgbm.exe"))
version = open(os.path.join(current_dir, os.path.pardir, 'VERSION.txt')).read().strip().replace('rc', '-rc')
- nuget_str = r"""<?xml version="1.0"?>
+ nuget_str = f"""<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd">
<metadata>
<id>LightGBM</id>
- <version>%s</version>
+ <version>{version, datetime.datetime.now().year}</version>
<authors>Guolin Ke</authors>
<owners>Guolin Ke</owners>
<licenseUrl>https://github.com/microsoft/LightGBM/blob/master/LICENSE</licenseUrl> | 1 | # coding: utf-8
"""Script for generating files with NuGet package metadata."""
import datetime
import os
import sys
from distutils.file_util import copy_file
if __name__ == "__main__":
source = sys.argv[1]
current_dir = os.path.abspath(os.path.dirname(__file__))
linux_folder_path = os.path.join(current_dir, "runtimes", "linux-x64", "native")
if not os.path.exists(linux_folder_path):
os.makedirs(linux_folder_path)
osx_folder_path = os.path.join(current_dir, "runtimes", "osx-x64", "native")
if not os.path.exists(osx_folder_path):
os.makedirs(osx_folder_path)
windows_folder_path = os.path.join(current_dir, "runtimes", "win-x64", "native")
if not os.path.exists(windows_folder_path):
os.makedirs(windows_folder_path)
build_folder_path = os.path.join(current_dir, "build")
if not os.path.exists(build_folder_path):
os.makedirs(build_folder_path)
copy_file(os.path.join(source, "lib_lightgbm.so"), os.path.join(linux_folder_path, "lib_lightgbm.so"))
copy_file(os.path.join(source, "lib_lightgbm.dylib"), os.path.join(osx_folder_path, "lib_lightgbm.dylib"))
copy_file(os.path.join(source, "lib_lightgbm.dll"), os.path.join(windows_folder_path, "lib_lightgbm.dll"))
copy_file(os.path.join(source, "lightgbm.exe"), os.path.join(windows_folder_path, "lightgbm.exe"))
version = open(os.path.join(current_dir, os.path.pardir, 'VERSION.txt')).read().strip().replace('rc', '-rc')
nuget_str = r"""<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd">
<metadata>
<id>LightGBM</id>
<version>%s</version>
<authors>Guolin Ke</authors>
<owners>Guolin Ke</owners>
<licenseUrl>https://github.com/microsoft/LightGBM/blob/master/LICENSE</licenseUrl>
<projectUrl>https://github.com/microsoft/LightGBM</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>A fast, distributed, high performance gradient boosting framework</description>
<copyright>Copyright %d @ Microsoft</copyright>
<tags>machine-learning data-mining distributed native boosting gbdt</tags>
<dependencies> </dependencies>
</metadata>
<files>
<file src="build\**" target="build"/>
<file src="runtimes\**" target="runtimes"/>
</files>
</package>
""" % (version, datetime.datetime.now().year)
prop_str = r"""
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Condition="Exists('packages.config') OR
Exists('$(MSBuildProjectName).packages.config') OR
Exists('packages.$(MSBuildProjectName).config')">
<Content Include="$(MSBuildThisFileDirectory)/../runtimes/win-x64/native/*.dll"
Condition="'$(PlatformTarget)' == 'x64'">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Visible>false</Visible>
</Content>
<Content Include="$(MSBuildThisFileDirectory)/../runtimes/win-x64/native/*.exe"
Condition="'$(PlatformTarget)' == 'x64'">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Visible>false</Visible>
</Content>
</ItemGroup>
</Project>
"""
target_str = r"""
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<EnableLightGBMUnsupportedPlatformTargetCheck Condition="'$(EnableLightGBMUnsupportedPlatformTargetCheck)' == ''">true</EnableLightGBMUnsupportedPlatformTargetCheck>
</PropertyGroup>
<Target Name="_LightGBMCheckForUnsupportedPlatformTarget"
Condition="'$(EnableLightGBMUnsupportedPlatformTargetCheck)' == 'true'"
AfterTargets="_CheckForInvalidConfigurationAndPlatform">
<Error Condition="'$(PlatformTarget)' != 'x64' AND
('$(OutputType)' == 'Exe' OR '$(OutputType)'=='WinExe') AND
!('$(TargetFrameworkIdentifier)' == '.NETCoreApp' AND '$(PlatformTarget)' == '')"
Text="LightGBM currently supports 'x64' processor architectures. Please ensure your application is targeting 'x64'." />
</Target>
</Project>
"""
with open(os.path.join(current_dir, "LightGBM.nuspec"), "w") as nuget_file:
nuget_file.write(nuget_str)
with open(os.path.join(current_dir, "build", "LightGBM.props"), "w") as prop_file:
prop_file.write(prop_str)
with open(os.path.join(current_dir, "build", "LightGBM.targets"), "w") as target_file:
target_file.write(target_str)
| 1 | 30,029 | This fix is not quite correct. The `%s` should be replaced with `version` and the `%d` on line 39 should be replaced with `datetime.datetime.now().year`. | microsoft-LightGBM | cpp |
@@ -274,7 +274,7 @@ static int pause_device(sd_bus_message *msg, void *userdata,
goto error;
}
- if (major == DRM_MAJOR) {
+ if (major == DRM_MAJOR && strcmp(type, "gone") != 0) {
assert(session->has_drm);
session->base.active = false;
wlr_signal_emit_safe(&session->base.session_signal, session); | 1 | #define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <unistd.h>
#include <wayland-server.h>
#include <wlr/backend/session/interface.h>
#include <wlr/config.h>
#include <wlr/util/log.h>
#include "util/signal.h"
#if WLR_HAS_SYSTEMD
#include <systemd/sd-bus.h>
#include <systemd/sd-login.h>
#elif WLR_HAS_ELOGIND
#include <elogind/sd-bus.h>
#include <elogind/sd-login.h>
#endif
enum { DRM_MAJOR = 226 };
const struct session_impl session_logind;
struct logind_session {
struct wlr_session base;
sd_bus *bus;
struct wl_event_source *event;
char *id;
char *path;
// specifies whether a drm device was taken
// if so, the session will be (de)activated with the drm fd,
// otherwise with the dbus PropertiesChanged on "active" signal
bool has_drm;
};
static struct logind_session *logind_session_from_session(
struct wlr_session *base) {
assert(base->impl == &session_logind);
return (struct logind_session *)base;
}
static int logind_take_device(struct wlr_session *base, const char *path) {
struct logind_session *session = logind_session_from_session(base);
int fd = -1;
int ret;
sd_bus_message *msg = NULL;
sd_bus_error error = SD_BUS_ERROR_NULL;
struct stat st;
if (stat(path, &st) < 0) {
wlr_log(WLR_ERROR, "Failed to stat '%s'", path);
return -1;
}
if (major(st.st_rdev) == DRM_MAJOR) {
session->has_drm = true;
}
ret = sd_bus_call_method(session->bus, "org.freedesktop.login1",
session->path, "org.freedesktop.login1.Session", "TakeDevice",
&error, &msg, "uu", major(st.st_rdev), minor(st.st_rdev));
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to take device '%s': %s", path,
error.message);
goto out;
}
int paused = 0;
ret = sd_bus_message_read(msg, "hb", &fd, &paused);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to parse D-Bus response for '%s': %s",
path, strerror(-ret));
goto out;
}
// The original fd seems to be closed when the message is freed
// so we just clone it.
fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
if (fd < 0) {
wlr_log(WLR_ERROR, "Failed to clone file descriptor for '%s': %s",
path, strerror(errno));
goto out;
}
out:
sd_bus_error_free(&error);
sd_bus_message_unref(msg);
return fd;
}
static void logind_release_device(struct wlr_session *base, int fd) {
struct logind_session *session = logind_session_from_session(base);
struct stat st;
if (fstat(fd, &st) < 0) {
wlr_log(WLR_ERROR, "Failed to stat device '%d': %s", fd,
strerror(errno));
return;
}
sd_bus_message *msg = NULL;
sd_bus_error error = SD_BUS_ERROR_NULL;
int ret = sd_bus_call_method(session->bus, "org.freedesktop.login1",
session->path, "org.freedesktop.login1.Session", "ReleaseDevice",
&error, &msg, "uu", major(st.st_rdev), minor(st.st_rdev));
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to release device '%d': %s", fd,
error.message);
}
sd_bus_error_free(&error);
sd_bus_message_unref(msg);
close(fd);
}
static bool logind_change_vt(struct wlr_session *base, unsigned vt) {
struct logind_session *session = logind_session_from_session(base);
// Only seat0 has VTs associated with it
if (strcmp(session->base.seat, "seat0") != 0) {
return true;
}
int ret;
sd_bus_message *msg = NULL;
sd_bus_error error = SD_BUS_ERROR_NULL;
ret = sd_bus_call_method(session->bus, "org.freedesktop.login1",
"/org/freedesktop/login1/seat/self", "org.freedesktop.login1.Seat", "SwitchTo",
&error, &msg, "u", (uint32_t)vt);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to change to vt '%d'", vt);
}
sd_bus_error_free(&error);
sd_bus_message_unref(msg);
return ret >= 0;
}
static bool find_session_path(struct logind_session *session) {
int ret;
sd_bus_message *msg = NULL;
sd_bus_error error = SD_BUS_ERROR_NULL;
ret = sd_bus_call_method(session->bus, "org.freedesktop.login1",
"/org/freedesktop/login1", "org.freedesktop.login1.Manager",
"GetSession", &error, &msg, "s", session->id);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to get session path: %s", error.message);
goto out;
}
const char *path;
ret = sd_bus_message_read(msg, "o", &path);
if (ret < 0) {
wlr_log(WLR_ERROR, "Could not parse session path: %s", error.message);
goto out;
}
session->path = strdup(path);
out:
sd_bus_error_free(&error);
sd_bus_message_unref(msg);
return ret >= 0;
}
static bool session_activate(struct logind_session *session) {
int ret;
sd_bus_message *msg = NULL;
sd_bus_error error = SD_BUS_ERROR_NULL;
ret = sd_bus_call_method(session->bus, "org.freedesktop.login1",
session->path, "org.freedesktop.login1.Session", "Activate",
&error, &msg, "");
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to activate session: %s", error.message);
}
sd_bus_error_free(&error);
sd_bus_message_unref(msg);
return ret >= 0;
}
static bool take_control(struct logind_session *session) {
int ret;
sd_bus_message *msg = NULL;
sd_bus_error error = SD_BUS_ERROR_NULL;
ret = sd_bus_call_method(session->bus, "org.freedesktop.login1",
session->path, "org.freedesktop.login1.Session", "TakeControl",
&error, &msg, "b", false);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to take control of session: %s",
error.message);
}
sd_bus_error_free(&error);
sd_bus_message_unref(msg);
return ret >= 0;
}
static void release_control(struct logind_session *session) {
int ret;
sd_bus_message *msg = NULL;
sd_bus_error error = SD_BUS_ERROR_NULL;
ret = sd_bus_call_method(session->bus, "org.freedesktop.login1",
session->path, "org.freedesktop.login1.Session", "ReleaseControl",
&error, &msg, "");
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to release control of session: %s",
error.message);
}
sd_bus_error_free(&error);
sd_bus_message_unref(msg);
}
static void logind_session_destroy(struct wlr_session *base) {
struct logind_session *session = logind_session_from_session(base);
release_control(session);
wl_event_source_remove(session->event);
sd_bus_unref(session->bus);
free(session->id);
free(session->path);
free(session);
}
static int session_removed(sd_bus_message *msg, void *userdata,
sd_bus_error *ret_error) {
wlr_log(WLR_INFO, "SessionRemoved signal received");
return 0;
}
static struct wlr_device *find_device(struct wlr_session *session,
dev_t devnum) {
struct wlr_device *dev;
wl_list_for_each(dev, &session->devices, link) {
if (dev->dev == devnum) {
return dev;
}
}
wlr_log(WLR_ERROR, "Tried to use dev_t %lu not opened by session",
(unsigned long)devnum);
assert(0);
}
static int pause_device(sd_bus_message *msg, void *userdata,
sd_bus_error *ret_error) {
struct logind_session *session = userdata;
int ret;
uint32_t major, minor;
const char *type;
ret = sd_bus_message_read(msg, "uus", &major, &minor, &type);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to parse D-Bus response for PauseDevice: %s",
strerror(-ret));
goto error;
}
if (major == DRM_MAJOR) {
assert(session->has_drm);
session->base.active = false;
wlr_signal_emit_safe(&session->base.session_signal, session);
}
if (strcmp(type, "pause") == 0) {
ret = sd_bus_call_method(session->bus, "org.freedesktop.login1",
session->path, "org.freedesktop.login1.Session", "PauseDeviceComplete",
ret_error, &msg, "uu", major, minor);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to send PauseDeviceComplete signal: %s",
strerror(-ret));
}
}
error:
return 0;
}
static int resume_device(sd_bus_message *msg, void *userdata,
sd_bus_error *ret_error) {
struct logind_session *session = userdata;
int ret;
int fd;
uint32_t major, minor;
ret = sd_bus_message_read(msg, "uuh", &major, &minor, &fd);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to parse D-Bus response for ResumeDevice: %s",
strerror(-ret));
goto error;
}
if (major == DRM_MAJOR) {
struct wlr_device *dev = find_device(&session->base, makedev(major, minor));
close(dev->fd);
if (fcntl(fd, F_DUPFD_CLOEXEC, dev->fd) < 0) {
wlr_log_errno(WLR_ERROR, "Failed to duplicate file descriptor");
goto error;
}
if (!session->base.active) {
session->base.active = true;
wlr_signal_emit_safe(&session->base.session_signal, session);
}
}
error:
return 0;
}
static int properties_changed(sd_bus_message *msg, void *userdata,
sd_bus_error *ret_error) {
struct logind_session *session = userdata;
int ret = 0;
// if we have a drm fd we don't depend on this
if (session->has_drm) {
return 0;
}
// PropertiesChanged arg 1: interface
const char *interface;
ret = sd_bus_message_read_basic(msg, 's', &interface); // skip path
if (ret < 0) {
goto error;
}
if (strcmp(interface, "org.freedesktop.login1.Session") != 0) {
// not interesting for us; ignore
wlr_log(WLR_DEBUG, "ignoring PropertiesChanged from %s", interface);
return 0;
}
// PropertiesChanged arg 2: changed properties with values
ret = sd_bus_message_enter_container(msg, 'a', "{sv}");
if (ret < 0) {
goto error;
}
const char *s;
while ((ret = sd_bus_message_enter_container(msg, 'e', "sv")) > 0) {
ret = sd_bus_message_read_basic(msg, 's', &s);
if (ret < 0) {
goto error;
}
if (strcmp(s, "Active") == 0) {
int ret;
ret = sd_bus_message_enter_container(msg, 'v', "b");
if (ret < 0) {
goto error;
}
bool active;
ret = sd_bus_message_read_basic(msg, 'b', &active);
if (ret < 0) {
goto error;
}
if (session->base.active != active) {
session->base.active = active;
wlr_signal_emit_safe(&session->base.session_signal, session);
}
return 0;
} else {
sd_bus_message_skip(msg, "{sv}");
}
ret = sd_bus_message_exit_container(msg);
if (ret < 0) {
goto error;
}
}
if (ret < 0) {
goto error;
}
ret = sd_bus_message_exit_container(msg);
if (ret < 0) {
goto error;
}
// PropertiesChanged arg 3: changed properties without values
sd_bus_message_enter_container(msg, 'a', "s");
while ((ret = sd_bus_message_read_basic(msg, 's', &s)) > 0) {
if (strcmp(s, "Active") == 0) {
sd_bus_error error = SD_BUS_ERROR_NULL;
bool active;
ret = sd_bus_get_property_trivial(session->bus,
"org.freedesktop.login1", session->path,
"org.freedesktop.login1.Session", "Active", &error,
'b', &active);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to get 'Active' property: %s",
error.message);
return 0;
}
if (session->base.active != active) {
session->base.active = active;
wlr_signal_emit_safe(&session->base.session_signal, session);
}
return 0;
}
}
if (ret < 0) {
goto error;
}
return 0;
error:
wlr_log(WLR_ERROR, "Failed to parse D-Bus PropertiesChanged: %s",
strerror(-ret));
return 0;
}
static bool add_signal_matches(struct logind_session *session) {
int ret;
char str[256];
const char fmt[] = "type='signal',"
"sender='org.freedesktop.login1',"
"interface='org.freedesktop.login1.%s',"
"member='%s',"
"path='%s'";
snprintf(str, sizeof(str), fmt, "Manager", "SessionRemoved",
"/org/freedesktop/login1");
ret = sd_bus_add_match(session->bus, NULL, str, session_removed, session);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to add D-Bus match: %s", strerror(-ret));
return false;
}
snprintf(str, sizeof(str), fmt, "Session", "PauseDevice", session->path);
ret = sd_bus_add_match(session->bus, NULL, str, pause_device, session);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to add D-Bus match: %s", strerror(-ret));
return false;
}
snprintf(str, sizeof(str), fmt, "Session", "ResumeDevice", session->path);
ret = sd_bus_add_match(session->bus, NULL, str, resume_device, session);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to add D-Bus match: %s", strerror(-ret));
return false;
}
ret = sd_bus_match_signal(session->bus, NULL, "org.freedesktop.login1",
session->path, "org.freedesktop.DBus.Properties", "PropertiesChanged",
properties_changed, session);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to add D-Bus match: %s", strerror(-ret));
return false;
}
return true;
}
static int dbus_event(int fd, uint32_t mask, void *data) {
sd_bus *bus = data;
while (sd_bus_process(bus, NULL) > 0) {
// Do nothing.
}
return 1;
}
static bool contains_str(const char *needle, const char **haystack) {
for (int i = 0; haystack[i]; i++) {
if (strcmp(haystack[i], needle) == 0) {
return true;
}
}
return false;
}
static bool get_greeter_session(char **session_id) {
char *class = NULL;
char **user_sessions = NULL;
int user_session_count = sd_uid_get_sessions(getuid(), 1, &user_sessions);
if (user_session_count < 0) {
wlr_log(WLR_ERROR, "Failed to get sessions");
goto out;
}
if (user_session_count == 0) {
wlr_log(WLR_ERROR, "User has no sessions");
goto out;
}
for (int i = 0; i < user_session_count; ++i) {
int ret = sd_session_get_class(user_sessions[i], &class);
if (ret < 0) {
continue;
}
if (strcmp(class, "greeter") == 0) {
*session_id = strdup(user_sessions[i]);
goto out;
}
}
out:
free(class);
for (int i = 0; i < user_session_count; ++i) {
free(user_sessions[i]);
}
free(user_sessions);
return *session_id != NULL;
}
static bool get_display_session(char **session_id) {
assert(session_id != NULL);
int ret;
// If there's a session active for the current process then just use that
ret = sd_pid_get_session(getpid(), session_id);
if (ret == 0) {
return true;
}
char *type = NULL;
char *state = NULL;
// Find any active sessions for the user if the process isn't part of an
// active session itself
ret = sd_uid_get_display(getuid(), session_id);
if (ret < 0 && ret != -ENODATA) {
wlr_log(WLR_ERROR, "Failed to get display: %s", strerror(-ret));
goto error;
}
if (ret != 0 && !get_greeter_session(session_id)) {
wlr_log(WLR_ERROR, "Couldn't find an active session or a greeter session");
goto error;
}
assert(*session_id != NULL);
// Check that the available session is graphical
ret = sd_session_get_type(*session_id, &type);
if (ret < 0) {
wlr_log(WLR_ERROR, "Couldn't get a type for session '%s': %s",
*session_id, strerror(-ret));
goto error;
}
const char *graphical_session_types[] = {"wayland", "x11", "mir", NULL};
if (!contains_str(type, graphical_session_types)) {
wlr_log(WLR_ERROR, "Session '%s' isn't a graphical session (type: '%s')",
*session_id, type);
goto error;
}
// Check that the session is active
ret = sd_session_get_state(*session_id, &state);
if (ret < 0) {
wlr_log(WLR_ERROR, "Couldn't get state for session '%s': %s",
*session_id, strerror(-ret));
goto error;
}
const char *active_states[] = {"active", "online", NULL};
if (!contains_str(state, active_states)) {
wlr_log(WLR_ERROR, "Session '%s' is not active", *session_id);
goto error;
}
free(type);
free(state);
return true;
error:
free(type);
free(state);
free(*session_id);
*session_id = NULL;
return false;
}
static struct wlr_session *logind_session_create(struct wl_display *disp) {
int ret;
struct logind_session *session = calloc(1, sizeof(*session));
if (!session) {
wlr_log(WLR_ERROR, "Allocation failed: %s", strerror(errno));
return NULL;
}
if (!get_display_session(&session->id)) {
goto error;
}
char *seat;
ret = sd_session_get_seat(session->id, &seat);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to get seat id: %s", strerror(-ret));
goto error;
}
snprintf(session->base.seat, sizeof(session->base.seat), "%s", seat);
if (strcmp(seat, "seat0") == 0) {
ret = sd_session_get_vt(session->id, &session->base.vtnr);
if (ret < 0) {
wlr_log(WLR_ERROR, "Session not running in virtual terminal");
goto error;
}
}
free(seat);
ret = sd_bus_default_system(&session->bus);
if (ret < 0) {
wlr_log(WLR_ERROR, "Failed to open D-Bus connection: %s", strerror(-ret));
goto error;
}
if (!find_session_path(session)) {
sd_bus_unref(session->bus);
goto error;
}
if (!add_signal_matches(session)) {
goto error_bus;
}
struct wl_event_loop *event_loop = wl_display_get_event_loop(disp);
session->event = wl_event_loop_add_fd(event_loop, sd_bus_get_fd(session->bus),
WL_EVENT_READABLE, dbus_event, session->bus);
if (!session_activate(session)) {
goto error_bus;
}
if (!take_control(session)) {
goto error_bus;
}
wlr_log(WLR_INFO, "Successfully loaded logind session");
session->base.impl = &session_logind;
return &session->base;
error_bus:
sd_bus_unref(session->bus);
free(session->path);
error:
free(session->id);
return NULL;
}
const struct session_impl session_logind = {
.create = logind_session_create,
.destroy = logind_session_destroy,
.open = logind_take_device,
.close = logind_release_device,
.change_vt = logind_change_vt,
};
| 1 | 13,837 | Maybe we should only set active = false if `strcmp(type, "pause") == 0`? | swaywm-wlroots | c |
@@ -37,6 +37,12 @@ module Selenium
def bridge_class
Bridge
end
+
+ def print_page(**options)
+ options[:page_ranges] &&= Array(options[:page_ranges])
+
+ bridge.print_page(options)
+ end
end # Driver
end # Firefox
end # WebDriver | 1 | # frozen_string_literal: true
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
module Selenium
module WebDriver
module Firefox
#
# Driver implementation for Firefox using GeckoDriver.
# @api private
#
class Driver < WebDriver::Driver
include DriverExtensions::HasAddons
include DriverExtensions::HasWebStorage
def browser
:firefox
end
def bridge_class
Bridge
end
end # Driver
end # Firefox
end # WebDriver
end # Selenium
| 1 | 18,368 | Same here. and all others. | SeleniumHQ-selenium | js |
@@ -18,6 +18,8 @@ import (
"github.com/keybase/kbfs/libfs"
"github.com/keybase/kbfs/libfuse"
"github.com/keybase/kbfs/libkbfs"
+
+ _ "github.com/songgao/stacktraces/on/SIGUSR2"
)
var runtimeDir = flag.String("runtime-dir", os.Getenv("KEYBASE_RUNTIME_DIR"), "runtime directory") | 1 | // Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
// Keybase file system
package main
import (
"flag"
"fmt"
"os"
"bazil.org/fuse"
"github.com/keybase/client/go/logger"
"github.com/keybase/kbfs/env"
"github.com/keybase/kbfs/libfs"
"github.com/keybase/kbfs/libfuse"
"github.com/keybase/kbfs/libkbfs"
)
var runtimeDir = flag.String("runtime-dir", os.Getenv("KEYBASE_RUNTIME_DIR"), "runtime directory")
var label = flag.String("label", os.Getenv("KEYBASE_LABEL"), "label to help identify if running as a service")
var mountType = flag.String("mount-type", defaultMountType, "mount type: default, force, none")
var version = flag.Bool("version", false, "Print version")
const usageFormatStr = `Usage:
kbfsfuse -version
To run against remote KBFS servers:
kbfsfuse
[-runtime-dir=path/to/dir] [-label=label] [-mount-type=force]
%s
%s/path/to/mountpoint
To run in a local testing environment:
kbfsfuse
[-runtime-dir=path/to/dir] [-label=label] [-mount-type=force]
%s
%s/path/to/mountpoint
Defaults:
%s
`
func getUsageString(ctx libkbfs.Context) string {
remoteUsageStr := libkbfs.GetRemoteUsageString()
localUsageStr := libkbfs.GetLocalUsageString()
platformUsageStr := libfuse.GetPlatformUsageString()
defaultUsageStr := libkbfs.GetDefaultsUsageString(ctx)
return fmt.Sprintf(usageFormatStr,
remoteUsageStr, platformUsageStr,
localUsageStr, platformUsageStr, defaultUsageStr)
}
func start() *libfs.Error {
ctx := env.NewContext()
kbfsParams := libkbfs.AddFlags(flag.CommandLine, ctx)
platformParams := libfuse.AddPlatformFlags(flag.CommandLine)
flag.Parse()
if *version {
fmt.Printf("%s\n", libkbfs.VersionString())
return nil
}
if len(flag.Args()) < 1 {
fmt.Print(getUsageString(ctx))
return libfs.InitError("no mount specified")
}
if len(flag.Args()) > 1 {
fmt.Print(getUsageString(ctx))
return libfs.InitError("extra arguments specified (flags go before the first argument)")
}
if kbfsParams.Debug {
fuseLog := logger.NewWithCallDepth("FUSE", 1)
fuseLog.Configure("", true, "")
fuse.Debug = libfuse.MakeFuseDebugFn(
fuseLog, false /* superVerbose */)
}
mountpoint := flag.Arg(0)
var mounter libfuse.Mounter
if *mountType == "force" {
mounter = libfuse.NewForceMounter(mountpoint, *platformParams)
} else if *mountType == "none" {
mounter = libfuse.NewNoopMounter()
} else {
mounter = libfuse.NewDefaultMounter(mountpoint, *platformParams)
}
options := libfuse.StartOptions{
KbfsParams: *kbfsParams,
PlatformParams: *platformParams,
RuntimeDir: *runtimeDir,
Label: *label,
}
return libfuse.Start(mounter, options, ctx)
}
func main() {
err := start()
if err != nil {
fmt.Fprintf(os.Stderr, "kbfsfuse error: (%d) %s\n", err.Code, err.Message)
os.Exit(err.Code)
}
os.Exit(0)
}
| 1 | 16,883 | Intentionally committed? I'm not against it, we already have a way to get goroutines without killing the process: `/keybase/.kbfs_profiles/goroutine`. | keybase-kbfs | go |
@@ -113,9 +113,10 @@ RTPSParticipant* RTPSDomain::createParticipant(
PParam.builtin.initialPeersList.push_back(local);
}
- GuidPrefix_t guidP(PParam.prefix);
+ // Generate a new GuidPrefix_t
+
+ GuidPrefix_t guidP;
- if (guidP == c_GuidPrefix_Unknown)
{
// Make a new participant GuidPrefix_t up
int pid = System::GetPID(); | 1 | // Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/*
* RTPSDomain.cpp
*
*/
#include <fastrtps/rtps/RTPSDomain.h>
#include <fastrtps/rtps/participant/RTPSParticipant.h>
#include "participant/RTPSParticipantImpl.h"
#include <fastrtps/log/Log.h>
#include <fastrtps/transport/UDPv4Transport.h>
#include <fastrtps/transport/UDPv6Transport.h>
#include <fastrtps/transport/test_UDPv4Transport.h>
#include <fastrtps/utils/IPFinder.h>
#include <fastrtps/utils/IPLocator.h>
#include <fastrtps/utils/eClock.h>
#include <fastrtps/utils/System.h>
#include <fastrtps/utils/md5.h>
#include <fastrtps/rtps/writer/RTPSWriter.h>
#include <fastrtps/rtps/reader/RTPSReader.h>
namespace eprosima {
namespace fastrtps{
namespace rtps {
std::mutex RTPSDomain::m_mutex;
std::atomic<uint32_t> RTPSDomain::m_maxRTPSParticipantID(1);
std::vector<RTPSDomain::t_p_RTPSParticipant> RTPSDomain::m_RTPSParticipants;
std::set<uint32_t> RTPSDomain::m_RTPSParticipantIDs;
void RTPSDomain::stopAll()
{
std::lock_guard<std::mutex> guard(m_mutex);
logInfo(RTPS_PARTICIPANT,"DELETING ALL ENDPOINTS IN THIS DOMAIN");
while(m_RTPSParticipants.size()>0)
{
RTPSDomain::removeRTPSParticipant_nts(m_RTPSParticipants.begin());
}
logInfo(RTPS_PARTICIPANT,"RTPSParticipants deleted correctly ");
eClock::my_sleep(100);
}
RTPSParticipant* RTPSDomain::createParticipant(
const RTPSParticipantAttributes& attrs,
RTPSParticipantListener* listen)
{
std::lock_guard<std::mutex> guard(m_mutex);
logInfo(RTPS_PARTICIPANT,"");
RTPSParticipantAttributes PParam = attrs;
if(PParam.builtin.discovery_config.leaseDuration < c_TimeInfinite && PParam.builtin.discovery_config.leaseDuration <= PParam.builtin.discovery_config.leaseDuration_announcementperiod) //TODO CHeckear si puedo ser infinito
{
logError(RTPS_PARTICIPANT,"RTPSParticipant Attributes: LeaseDuration should be >= leaseDuration announcement period");
return nullptr;
}
uint32_t ID;
if(PParam.participantID < 0)
{
ID = getNewId();
while(m_RTPSParticipantIDs.insert(ID).second == false)
{
ID = getNewId();
}
}
else
{
ID = PParam.participantID;
if(m_RTPSParticipantIDs.insert(ID).second == false)
{
logError(RTPS_PARTICIPANT,"RTPSParticipant with the same ID already exists");
return nullptr;
}
}
if(!PParam.defaultUnicastLocatorList.isValid())
{
logError(RTPS_PARTICIPANT,"Default Unicast Locator List contains invalid Locator");
return nullptr;
}
if(!PParam.defaultMulticastLocatorList.isValid())
{
logError(RTPS_PARTICIPANT,"Default Multicast Locator List contains invalid Locator");
return nullptr;
}
PParam.participantID = ID;
LocatorList_t loc;
IPFinder::getIP4Address(&loc);
if (loc.empty() && PParam.builtin.initialPeersList.empty())
{
Locator_t local;
IPLocator::setIPv4(local, 127, 0, 0, 1);
PParam.builtin.initialPeersList.push_back(local);
}
GuidPrefix_t guidP(PParam.prefix);
if (guidP == c_GuidPrefix_Unknown)
{
// Make a new participant GuidPrefix_t up
int pid = System::GetPID();
guidP.value[0] = c_VendorId_eProsima[0];
guidP.value[1] = c_VendorId_eProsima[1];
if (loc.size() > 0)
{
MD5 md5;
for (auto& l : loc)
{
md5.update(l.address, sizeof(l.address));
}
md5.finalize();
uint16_t hostid = 0;
for (size_t i = 0; i < sizeof(md5.digest); i += 2)
{
hostid ^= ((md5.digest[i] << 8) | md5.digest[i + 1]);
}
guidP.value[2] = octet(hostid);
guidP.value[3] = octet(hostid >> 8);
}
else
{
guidP.value[2] = 127;
guidP.value[3] = 1;
}
guidP.value[4] = octet(pid);
guidP.value[5] = octet(pid >> 8);
guidP.value[6] = octet(pid >> 16);
guidP.value[7] = octet(pid >> 24);
guidP.value[8] = octet(ID);
guidP.value[9] = octet(ID >> 8);
guidP.value[10] = octet(ID >> 16);
guidP.value[11] = octet(ID >> 24);
}
RTPSParticipant* p = new RTPSParticipant(nullptr);
RTPSParticipantImpl* pimpl = new RTPSParticipantImpl(PParam,guidP,p,listen);
#if HAVE_SECURITY
// Check security was correctly initialized
if (!pimpl->is_security_initialized())
{
logError(RTPS_PARTICIPANT, "Cannot create participant due to security initialization error");
delete pimpl;
return nullptr;
}
#endif
// Check there is at least one transport registered.
if(!pimpl->networkFactoryHasRegisteredTransports())
{
logError(RTPS_PARTICIPANT,"Cannot create participant, because there is any transport");
delete pimpl;
return nullptr;
}
m_RTPSParticipants.push_back(t_p_RTPSParticipant(p,pimpl));
return p;
}
bool RTPSDomain::removeRTPSParticipant(RTPSParticipant* p)
{
if(p!=nullptr)
{
std::lock_guard<std::mutex> guard(m_mutex);
for(auto it = m_RTPSParticipants.begin();it!= m_RTPSParticipants.end();++it)
{
if(it->second->getGuid().guidPrefix == p->getGuid().guidPrefix)
{
removeRTPSParticipant_nts(it);
return true;
}
}
}
logError(RTPS_PARTICIPANT,"RTPSParticipant not valid or not recognized");
return false;
}
void RTPSDomain::removeRTPSParticipant_nts(std::vector<RTPSDomain::t_p_RTPSParticipant>::iterator it)
{
m_RTPSParticipantIDs.erase(m_RTPSParticipantIDs.find(it->second->getRTPSParticipantID()));
delete(it->second);
m_RTPSParticipants.erase(it);
}
RTPSWriter* RTPSDomain::createRTPSWriter(
RTPSParticipant* p,
WriterAttributes& watt,
WriterHistory* hist,
WriterListener* listen)
{
std::lock_guard<std::mutex> guard(m_mutex);
for(auto it= m_RTPSParticipants.begin();it!=m_RTPSParticipants.end();++it)
{
if(it->first->getGuid().guidPrefix == p->getGuid().guidPrefix)
{
RTPSWriter* writ;
if(it->second->createWriter(&writ,watt,hist,listen))
{
return writ;
}
return nullptr;
}
}
return nullptr;
}
bool RTPSDomain::removeRTPSWriter(RTPSWriter* writer)
{
if(writer!=nullptr)
{
std::lock_guard<std::mutex> guard(m_mutex);
for(auto it= m_RTPSParticipants.begin();it!=m_RTPSParticipants.end();++it)
{
if(it->first->getGuid().guidPrefix == writer->getGuid().guidPrefix)
{
return it->second->deleteUserEndpoint((Endpoint*)writer);
}
}
}
return false;
}
RTPSReader* RTPSDomain::createRTPSReader(
RTPSParticipant* p,
ReaderAttributes& ratt,
ReaderHistory* rhist,
ReaderListener* rlisten)
{
std::lock_guard<std::mutex> guard(m_mutex);
for(auto it= m_RTPSParticipants.begin();it!=m_RTPSParticipants.end();++it)
{
if(it->first->getGuid().guidPrefix == p->getGuid().guidPrefix)
{
RTPSReader* reader;
if(it->second->createReader(&reader,ratt,rhist,rlisten))
{
return reader;
}
return nullptr;
}
}
return nullptr;
}
bool RTPSDomain::removeRTPSReader(RTPSReader* reader)
{
if(reader != nullptr)
{
std::lock_guard<std::mutex> guard(m_mutex);
for(auto it= m_RTPSParticipants.begin();it!=m_RTPSParticipants.end();++it)
{
if(it->first->getGuid().guidPrefix == reader->getGuid().guidPrefix)
{
return it->second->deleteUserEndpoint((Endpoint*)reader);
}
}
}
return false;
}
} /* namespace rtps */
} /* namespace fastrtps */
} /* namespace eprosima */
| 1 | 15,877 | I think this blank line may be removed | eProsima-Fast-DDS | cpp |
@@ -272,12 +272,17 @@ class BookmarkManager(UrlMarkManager):
elif len(parts) == 1:
self.marks[parts[0]] = ''
- def add(self, url, title):
+ def add(self, url, title, toggle=False):
"""Add a new bookmark.
+ Return True if the bookmark was added, and False if it was
+ removed (which only happens if toggle is True).
+
Args:
url: The url to add as bookmark.
title: The title for the new bookmark.
+ toggle: remove the bookmark instead of raising an error if it
+ already exists.
"""
if not url.isValid():
errstr = urlutils.get_errstring(url) | 1 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2016 Florian Bruhin (The Compiler) <[email protected]>
# Copyright 2015-2016 Antoni Boucher <[email protected]>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Managers for bookmarks and quickmarks.
Note we violate our general QUrl rule by storing url strings in the marks
OrderedDict. This is because we read them from a file at start and write them
to a file on shutdown, so it makes sense to keep them as strings here.
"""
import os
import os.path
import functools
import collections
from PyQt5.QtCore import pyqtSignal, QUrl, QObject
from qutebrowser.utils import (message, usertypes, qtutils, urlutils,
standarddir, objreg)
from qutebrowser.commands import cmdutils
from qutebrowser.misc import lineparser
class Error(Exception):
"""Base class for all errors in this module."""
pass
class InvalidUrlError(Error):
"""Exception emitted when a URL is invalid."""
pass
class DoesNotExistError(Error):
"""Exception emitted when a given URL does not exist."""
pass
class AlreadyExistsError(Error):
"""Exception emitted when a given URL does already exist."""
pass
class UrlMarkManager(QObject):
"""Base class for BookmarkManager and QuickmarkManager.
Attributes:
marks: An OrderedDict of all quickmarks/bookmarks.
_lineparser: The LineParser used for the marks, or None
(when qutebrowser is started with -c '').
Signals:
changed: Emitted when anything changed.
added: Emitted when a new quickmark/bookmark was added.
removed: Emitted when an existing quickmark/bookmark was removed.
"""
changed = pyqtSignal()
added = pyqtSignal(str, str)
removed = pyqtSignal(str)
def __init__(self, parent=None):
"""Initialize and read quickmarks."""
super().__init__(parent)
self.marks = collections.OrderedDict()
self._lineparser = None
if standarddir.config() is None:
return
self._init_lineparser()
for line in self._lineparser:
if not line.strip():
# Ignore empty or whitespace-only lines.
continue
self._parse_line(line)
self._init_savemanager(objreg.get('save-manager'))
def _init_lineparser(self):
raise NotImplementedError
def _parse_line(self, line):
raise NotImplementedError
def _init_savemanager(self, _save_manager):
raise NotImplementedError
def save(self):
"""Save the marks to disk."""
if self._lineparser is not None:
self._lineparser.data = [' '.join(tpl)
for tpl in self.marks.items()]
self._lineparser.save()
def delete(self, key):
"""Delete a quickmark/bookmark.
Args:
key: The key to delete (name for quickmarks, URL for bookmarks.)
"""
del self.marks[key]
self.changed.emit()
self.removed.emit(key)
class QuickmarkManager(UrlMarkManager):
"""Manager for quickmarks.
The primary key for quickmarks is their *name*, this means:
- self.marks maps names to URLs.
- changed gets emitted with the name as first argument and the URL as
second argument.
- removed gets emitted with the name as argument.
"""
def _init_lineparser(self):
self._lineparser = lineparser.LineParser(
standarddir.config(), 'quickmarks', parent=self)
def _init_savemanager(self, save_manager):
filename = os.path.join(standarddir.config(), 'quickmarks')
save_manager.add_saveable('quickmark-manager', self.save, self.changed,
filename=filename)
def _parse_line(self, line):
try:
key, url = line.rsplit(maxsplit=1)
except ValueError:
message.error('current', "Invalid quickmark '{}'".format(line))
else:
self.marks[key] = url
def prompt_save(self, win_id, url):
"""Prompt for a new quickmark name to be added and add it.
Args:
win_id: The current window ID.
url: The quickmark url as a QUrl.
"""
if not url.isValid():
urlutils.invalid_url_error(win_id, url, "save quickmark")
return
urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
message.ask_async(
win_id, "Add quickmark:", usertypes.PromptMode.text,
functools.partial(self.quickmark_add, win_id, urlstr))
@cmdutils.register(instance='quickmark-manager')
@cmdutils.argument('win_id', win_id=True)
def quickmark_add(self, win_id, url, name):
"""Add a new quickmark.
You can view all saved quickmarks on the
link:qute://bookmarks[bookmarks page].
Args:
win_id: The window ID to display the errors in.
url: The url to add as quickmark.
name: The name for the new quickmark.
"""
# We don't raise cmdexc.CommandError here as this can be called async
# via prompt_save.
if not name:
message.error(win_id, "Can't set mark with empty name!")
return
if not url:
message.error(win_id, "Can't set mark with empty URL!")
return
def set_mark():
"""Really set the quickmark."""
self.marks[name] = url
self.changed.emit()
self.added.emit(name, url)
if name in self.marks:
message.confirm_async(
win_id, "Override existing quickmark?", set_mark, default=True)
else:
set_mark()
def get_by_qurl(self, url):
"""Look up a quickmark by QUrl, returning its name.
Takes O(n) time, where n is the number of quickmarks.
Use a name instead where possible.
"""
qtutils.ensure_valid(url)
urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
try:
index = list(self.marks.values()).index(urlstr)
key = list(self.marks.keys())[index]
except ValueError:
raise DoesNotExistError(
"Quickmark for '{}' not found!".format(urlstr))
return key
def get(self, name):
"""Get the URL of the quickmark named name as a QUrl."""
if name not in self.marks:
raise DoesNotExistError(
"Quickmark '{}' does not exist!".format(name))
urlstr = self.marks[name]
try:
url = urlutils.fuzzy_url(urlstr, do_search=False)
except urlutils.InvalidUrlError as e:
raise InvalidUrlError(
"Invalid URL for quickmark {}: {}".format(name, str(e)))
return url
class BookmarkManager(UrlMarkManager):
"""Manager for bookmarks.
The primary key for bookmarks is their *url*, this means:
- self.marks maps URLs to titles.
- changed gets emitted with the URL as first argument and the title as
second argument.
- removed gets emitted with the URL as argument.
"""
def _init_lineparser(self):
bookmarks_directory = os.path.join(standarddir.config(), 'bookmarks')
if not os.path.isdir(bookmarks_directory):
os.makedirs(bookmarks_directory)
bookmarks_subdir = os.path.join('bookmarks', 'urls')
self._lineparser = lineparser.LineParser(
standarddir.config(), bookmarks_subdir, parent=self)
def _init_savemanager(self, save_manager):
filename = os.path.join(standarddir.config(), 'bookmarks', 'urls')
save_manager.add_saveable('bookmark-manager', self.save, self.changed,
filename=filename)
def _parse_line(self, line):
parts = line.split(maxsplit=1)
if len(parts) == 2:
self.marks[parts[0]] = parts[1]
elif len(parts) == 1:
self.marks[parts[0]] = ''
def add(self, url, title):
"""Add a new bookmark.
Args:
url: The url to add as bookmark.
title: The title for the new bookmark.
"""
if not url.isValid():
errstr = urlutils.get_errstring(url)
raise InvalidUrlError(errstr)
urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
if urlstr in self.marks:
raise AlreadyExistsError("Bookmark already exists!")
else:
self.marks[urlstr] = title
self.changed.emit()
self.added.emit(title, urlstr)
| 1 | 15,363 | I think this should be a keyword-only argument, i.e. do `def add(self, url, title, *, toggle=False):` and adjust the caller to do `toggle=toggle`. | qutebrowser-qutebrowser | py |
@@ -630,6 +630,7 @@ EmmcSwitchBusWidth (
UINT8 Index;
UINT8 Value;
UINT8 CmdSet;
+ UINT32 DevStatus;
//
// Write Byte, the Value field is written into the byte pointed by Index. | 1 | /** @file
This file provides some helper functions which are specific for EMMC device.
Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
Copyright (c) 2015 - 2016, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "SdMmcPciHcDxe.h"
/**
Send command GO_IDLE_STATE (CMD0 with argument of 0x00000000) to the device to
make it go to Idle State.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.4 for details.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@retval EFI_SUCCESS The EMMC device is reset correctly.
@retval Others The device reset fails.
**/
EFI_STATUS
EmmcReset (
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot
)
{
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
EFI_STATUS Status;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_GO_IDLE_STATE;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeBc;
SdMmcCmdBlk.ResponseType = 0;
SdMmcCmdBlk.CommandArgument = 0;
gBS->Stall (1000);
Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL);
return Status;
}
/**
Send command SEND_OP_COND to the EMMC device to get the data of the OCR register.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.4 for details.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in, out] Argument On input, the argument of SEND_OP_COND is to send to the device.
On output, the argument is the value of OCR register.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcGetOcr (
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN OUT UINT32 *Argument
)
{
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
EFI_STATUS Status;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SEND_OP_COND;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeBcr;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR3;
SdMmcCmdBlk.CommandArgument = *Argument;
Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL);
if (!EFI_ERROR (Status)) {
//
// For details, refer to SD Host Controller Simplified Spec 3.0 Table 2-12.
//
*Argument = SdMmcStatusBlk.Resp0;
}
return Status;
}
/**
Broadcast command ALL_SEND_CID to the bus to ask all the EMMC devices to send the
data of their CID registers.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.4 for details.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcGetAllCid (
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot
)
{
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
EFI_STATUS Status;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_ALL_SEND_CID;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeBcr;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2;
SdMmcCmdBlk.CommandArgument = 0;
Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL);
return Status;
}
/**
Send command SET_RELATIVE_ADDR to the EMMC device to assign a Relative device
Address (RCA).
Refer to EMMC Electrical Standard Spec 5.1 Section 6.4 for details.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] Rca The relative device address to be assigned.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcSetRca (
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT16 Rca
)
{
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
EFI_STATUS Status;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SET_RELATIVE_ADDR;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16;
Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL);
return Status;
}
/**
Send command SEND_CSD to the EMMC device to get the data of the CSD register.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.10.4 for details.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] Rca The relative device address of selected device.
@param[out] Csd The buffer to store the content of the CSD register.
Note the caller should ignore the lowest byte of this
buffer as the content of this byte is meaningless even
if the operation succeeds.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcGetCsd (
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT16 Rca,
OUT EMMC_CSD *Csd
)
{
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
EFI_STATUS Status;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SEND_CSD;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2;
SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16;
Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL);
if (!EFI_ERROR (Status)) {
//
// For details, refer to SD Host Controller Simplified Spec 3.0 Table 2-12.
//
CopyMem (((UINT8 *)Csd) + 1, &SdMmcStatusBlk.Resp0, sizeof (EMMC_CSD) - 1);
}
return Status;
}
/**
Send command SELECT_DESELECT_CARD to the EMMC device to select/deselect it.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.10.4 for details.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] Rca The relative device address of selected device.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcSelect (
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT16 Rca
)
{
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
EFI_STATUS Status;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SELECT_DESELECT_CARD;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16;
Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL);
return Status;
}
/**
Send command SEND_EXT_CSD to the EMMC device to get the data of the EXT_CSD register.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.10.4 for details.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[out] ExtCsd The buffer to store the content of the EXT_CSD register.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcGetExtCsd (
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
OUT EMMC_EXT_CSD *ExtCsd
)
{
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
EFI_STATUS Status;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SEND_EXT_CSD;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
SdMmcCmdBlk.CommandArgument = 0x00000000;
Packet.InDataBuffer = ExtCsd;
Packet.InTransferLength = sizeof (EMMC_EXT_CSD);
Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL);
return Status;
}
/**
Send command SWITCH to the EMMC device to switch the mode of operation of the
selected Device or modifies the EXT_CSD registers.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.10.4 for details.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] Access The access mode of SWTICH command.
@param[in] Index The offset of the field to be access.
@param[in] Value The value to be set to the specified field of EXT_CSD register.
@param[in] CmdSet The value of CmdSet field of EXT_CSD register.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcSwitch (
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT8 Access,
IN UINT8 Index,
IN UINT8 Value,
IN UINT8 CmdSet
)
{
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
EFI_STATUS Status;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SWITCH;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1b;
SdMmcCmdBlk.CommandArgument = (Access << 24) | (Index << 16) | (Value << 8) | CmdSet;
Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL);
return Status;
}
/**
Send command SEND_STATUS to the addressed EMMC device to get its status register.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.10.4 for details.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] Rca The relative device address of addressed device.
@param[out] DevStatus The returned device status.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcSendStatus (
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT16 Rca,
OUT UINT32 *DevStatus
)
{
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
EFI_STATUS Status;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SEND_STATUS;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16;
Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL);
if (!EFI_ERROR (Status)) {
*DevStatus = SdMmcStatusBlk.Resp0;
}
return Status;
}
/**
Send command SEND_TUNING_BLOCK to the EMMC device for HS200 optimal sampling point
detection.
It may be sent up to 40 times until the host finishes the tuning procedure.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.6.8 for details.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] BusWidth The bus width to work.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcSendTuningBlk (
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT8 BusWidth
)
{
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
EFI_STATUS Status;
UINT8 TuningBlock[128];
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SEND_TUNING_BLOCK;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
SdMmcCmdBlk.CommandArgument = 0;
Packet.InDataBuffer = TuningBlock;
if (BusWidth == 8) {
Packet.InTransferLength = sizeof (TuningBlock);
} else {
Packet.InTransferLength = 64;
}
Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL);
return Status;
}
/**
Tunning the clock to get HS200 optimal sampling point.
Command SEND_TUNING_BLOCK may be sent up to 40 times until the host finishes the
tuning procedure.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.6.8 and SD Host Controller
Simplified Spec 3.0 Figure 2-29 for details.
@param[in] PciIo A pointer to the EFI_PCI_IO_PROTOCOL instance.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] BusWidth The bus width to work.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcTuningClkForHs200 (
IN EFI_PCI_IO_PROTOCOL *PciIo,
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT8 BusWidth
)
{
EFI_STATUS Status;
UINT8 HostCtrl2;
UINT8 Retry;
//
// Notify the host that the sampling clock tuning procedure starts.
//
HostCtrl2 = BIT6;
Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Ask the device to send a sequence of tuning blocks till the tuning procedure is done.
//
Retry = 0;
do {
Status = EmmcSendTuningBlk (PassThru, Slot, BusWidth);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "EmmcTuningClkForHs200: Send tuning block fails with %r\n", Status));
return Status;
}
Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, TRUE, sizeof (HostCtrl2), &HostCtrl2);
if (EFI_ERROR (Status)) {
return Status;
}
if ((HostCtrl2 & (BIT6 | BIT7)) == 0) {
break;
}
if ((HostCtrl2 & (BIT6 | BIT7)) == BIT7) {
return EFI_SUCCESS;
}
} while (++Retry < 40);
DEBUG ((DEBUG_ERROR, "EmmcTuningClkForHs200: Send tuning block fails at %d times with HostCtrl2 %02x\n", Retry, HostCtrl2));
//
// Abort the tuning procedure and reset the tuning circuit.
//
HostCtrl2 = (UINT8) ~(BIT6 | BIT7);
Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2);
if (EFI_ERROR (Status)) {
return Status;
}
return EFI_DEVICE_ERROR;
}
/**
Check the SWITCH operation status.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number on which command should be sent.
@param[in] Rca The relative device address.
@retval EFI_SUCCESS The SWITCH finished siccessfully.
@retval others The SWITCH failed.
**/
EFI_STATUS
EmmcCheckSwitchStatus (
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT16 Rca
)
{
EFI_STATUS Status;
UINT32 DevStatus;
Status = EmmcSendStatus (PassThru, Slot, Rca, &DevStatus);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "EmmcCheckSwitchStatus: Send status fails with %r\n", Status));
return Status;
}
//
// Check the switch operation is really successful or not.
//
if ((DevStatus & BIT7) != 0) {
DEBUG ((DEBUG_ERROR, "EmmcCheckSwitchStatus: The switch operation fails as DevStatus is 0x%08x\n", DevStatus));
return EFI_DEVICE_ERROR;
}
return EFI_SUCCESS;
}
/**
Switch the bus width to specified width.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.6.9 and SD Host Controller
Simplified Spec 3.0 Figure 3-7 for details.
@param[in] PciIo A pointer to the EFI_PCI_IO_PROTOCOL instance.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] Rca The relative device address to be assigned.
@param[in] IsDdr If TRUE, use dual data rate data simpling method. Otherwise
use single data rate data simpling method.
@param[in] BusWidth The bus width to be set, it could be 4 or 8.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcSwitchBusWidth (
IN EFI_PCI_IO_PROTOCOL *PciIo,
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT16 Rca,
IN BOOLEAN IsDdr,
IN UINT8 BusWidth
)
{
EFI_STATUS Status;
UINT8 Access;
UINT8 Index;
UINT8 Value;
UINT8 CmdSet;
//
// Write Byte, the Value field is written into the byte pointed by Index.
//
Access = 0x03;
Index = OFFSET_OF (EMMC_EXT_CSD, BusWidth);
if (BusWidth == 4) {
Value = 1;
} else if (BusWidth == 8) {
Value = 2;
} else {
return EFI_INVALID_PARAMETER;
}
if (IsDdr) {
Value += 4;
}
CmdSet = 0;
Status = EmmcSwitch (PassThru, Slot, Access, Index, Value, CmdSet);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "EmmcSwitchBusWidth: Switch to bus width %d fails with %r\n", BusWidth, Status));
return Status;
}
Status = EmmcCheckSwitchStatus (PassThru, Slot, Rca);
if (EFI_ERROR (Status)) {
return Status;
}
Status = SdMmcHcSetBusWidth (PciIo, Slot, BusWidth);
return Status;
}
/**
Switch the bus timing and clock frequency.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.6 and SD Host Controller
Simplified Spec 3.0 Figure 3-3 for details.
@param[in] PciIo A pointer to the EFI_PCI_IO_PROTOCOL instance.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] Rca The relative device address to be assigned.
@param[in] DriverStrength Driver strength to set for speed modes that support it.
@param[in] BusTiming The bus mode timing indicator.
@param[in] ClockFreq The max clock frequency to be set, the unit is MHz.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcSwitchBusTiming (
IN EFI_PCI_IO_PROTOCOL *PciIo,
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT16 Rca,
IN EDKII_SD_MMC_DRIVER_STRENGTH DriverStrength,
IN SD_MMC_BUS_MODE BusTiming,
IN UINT32 ClockFreq
)
{
EFI_STATUS Status;
UINT8 Access;
UINT8 Index;
UINT8 Value;
UINT8 CmdSet;
SD_MMC_HC_PRIVATE_DATA *Private;
UINT8 HostCtrl1;
BOOLEAN DelaySendStatus;
Private = SD_MMC_HC_PRIVATE_FROM_THIS (PassThru);
//
// Write Byte, the Value field is written into the byte pointed by Index.
//
Access = 0x03;
Index = OFFSET_OF (EMMC_EXT_CSD, HsTiming);
CmdSet = 0;
switch (BusTiming) {
case SdMmcMmcHs400:
Value = (UINT8)((DriverStrength.Emmc << 4) | 3);
break;
case SdMmcMmcHs200:
Value = (UINT8)((DriverStrength.Emmc << 4) | 2);
break;
case SdMmcMmcHsSdr:
case SdMmcMmcHsDdr:
Value = 1;
break;
case SdMmcMmcLegacy:
Value = 0;
break;
default:
DEBUG ((DEBUG_ERROR, "EmmcSwitchBusTiming: Unsupported BusTiming(%d)\n", BusTiming));
return EFI_INVALID_PARAMETER;
}
Status = EmmcSwitch (PassThru, Slot, Access, Index, Value, CmdSet);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "EmmcSwitchBusTiming: Switch to bus timing %d fails with %r\n", BusTiming, Status));
return Status;
}
if ((BusTiming == SdMmcMmcHsSdr) || (BusTiming == SdMmcMmcHsDdr)) {
HostCtrl1 = BIT2;
Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1);
if (EFI_ERROR (Status)) {
return Status;
}
} else {
HostCtrl1 = (UINT8) ~BIT2;
Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1);
if (EFI_ERROR (Status)) {
return Status;
}
}
Status = SdMmcHcUhsSignaling (Private->ControllerHandle, PciIo, Slot, BusTiming);
if (EFI_ERROR (Status)) {
return Status;
}
//
// For cases when we switch bus timing to higher mode from current we want to
// send SEND_STATUS at current, lower, frequency then the target frequency to avoid
// stability issues. It has been observed that some designs are unable to process the
// SEND_STATUS at higher frequency during switch to HS200 @200MHz irrespective of the number of retries
// and only running the clock tuning is able to make them work at target frequency.
//
// For cases when we are downgrading the frequency and current high frequency is invalid
// we have to first change the frequency to target frequency and then send the SEND_STATUS.
//
if (Private->Slot[Slot].CurrentFreq < (ClockFreq * 1000)) {
Status = EmmcCheckSwitchStatus (PassThru, Slot, Rca);
if (EFI_ERROR (Status)) {
return Status;
}
DelaySendStatus = FALSE;
} else {
DelaySendStatus = TRUE;
}
//
// Convert the clock freq unit from MHz to KHz.
//
Status = SdMmcHcClockSupply (Private, Slot, BusTiming, FALSE, ClockFreq * 1000);
if (EFI_ERROR (Status)) {
return Status;
}
if (DelaySendStatus) {
Status = EmmcCheckSwitchStatus (PassThru, Slot, Rca);
if (EFI_ERROR (Status)) {
return Status;
}
}
return Status;
}
/**
Switch to the High Speed timing according to request.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.6.8 and SD Host Controller
Simplified Spec 3.0 Figure 2-29 for details.
@param[in] PciIo A pointer to the EFI_PCI_IO_PROTOCOL instance.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] Rca The relative device address to be assigned.
@param[in] BusMode Pointer to SD_MMC_BUS_SETTINGS structure containing bus settings.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcSwitchToHighSpeed (
IN EFI_PCI_IO_PROTOCOL *PciIo,
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT16 Rca,
IN SD_MMC_BUS_SETTINGS *BusMode
)
{
EFI_STATUS Status;
BOOLEAN IsDdr;
if (((BusMode->BusTiming != SdMmcMmcHsSdr) && (BusMode->BusTiming != SdMmcMmcHsDdr) && (BusMode->BusTiming != SdMmcMmcLegacy)) ||
(BusMode->ClockFreq > 52))
{
return EFI_INVALID_PARAMETER;
}
if (BusMode->BusTiming == SdMmcMmcHsDdr) {
IsDdr = TRUE;
} else {
IsDdr = FALSE;
}
Status = EmmcSwitchBusWidth (PciIo, PassThru, Slot, Rca, IsDdr, BusMode->BusWidth);
if (EFI_ERROR (Status)) {
return Status;
}
return EmmcSwitchBusTiming (PciIo, PassThru, Slot, Rca, BusMode->DriverStrength, BusMode->BusTiming, BusMode->ClockFreq);
}
/**
Switch to the HS200 timing. This function assumes that eMMC bus is still in legacy mode.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.6.8 and SD Host Controller
Simplified Spec 3.0 Figure 2-29 for details.
@param[in] PciIo A pointer to the EFI_PCI_IO_PROTOCOL instance.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] Rca The relative device address to be assigned.
@param[in] BusMode Pointer to SD_MMC_BUS_SETTINGS structure containing bus settings.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcSwitchToHS200 (
IN EFI_PCI_IO_PROTOCOL *PciIo,
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT16 Rca,
IN SD_MMC_BUS_SETTINGS *BusMode
)
{
EFI_STATUS Status;
if ((BusMode->BusTiming != SdMmcMmcHs200) ||
((BusMode->BusWidth != 4) && (BusMode->BusWidth != 8)))
{
return EFI_INVALID_PARAMETER;
}
Status = EmmcSwitchBusWidth (PciIo, PassThru, Slot, Rca, FALSE, BusMode->BusWidth);
if (EFI_ERROR (Status)) {
return Status;
}
Status = EmmcSwitchBusTiming (PciIo, PassThru, Slot, Rca, BusMode->DriverStrength, BusMode->BusTiming, BusMode->ClockFreq);
if (EFI_ERROR (Status)) {
return Status;
}
Status = EmmcTuningClkForHs200 (PciIo, PassThru, Slot, BusMode->BusWidth);
return Status;
}
/**
Switch to the HS400 timing. This function assumes that eMMC bus is still in legacy mode.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.6.8 and SD Host Controller
Simplified Spec 3.0 Figure 2-29 for details.
@param[in] PciIo A pointer to the EFI_PCI_IO_PROTOCOL instance.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] Rca The relative device address to be assigned.
@param[in] BusMode Pointer to SD_MMC_BUS_SETTINGS structure containing bus settings.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcSwitchToHS400 (
IN EFI_PCI_IO_PROTOCOL *PciIo,
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT16 Rca,
IN SD_MMC_BUS_SETTINGS *BusMode
)
{
EFI_STATUS Status;
SD_MMC_BUS_SETTINGS Hs200BusMode;
UINT32 HsFreq;
if ((BusMode->BusTiming != SdMmcMmcHs400) ||
(BusMode->BusWidth != 8))
{
return EFI_INVALID_PARAMETER;
}
Hs200BusMode.BusTiming = SdMmcMmcHs200;
Hs200BusMode.BusWidth = BusMode->BusWidth;
Hs200BusMode.ClockFreq = BusMode->ClockFreq;
Hs200BusMode.DriverStrength = BusMode->DriverStrength;
Status = EmmcSwitchToHS200 (PciIo, PassThru, Slot, Rca, &Hs200BusMode);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Set to High Speed timing and set the clock frequency to a value less than or equal to 52MHz.
// This step is necessary to be able to switch Bus into 8 bit DDR mode which is unsupported in HS200.
//
HsFreq = BusMode->ClockFreq < 52 ? BusMode->ClockFreq : 52;
Status = EmmcSwitchBusTiming (PciIo, PassThru, Slot, Rca, BusMode->DriverStrength, SdMmcMmcHsSdr, HsFreq);
if (EFI_ERROR (Status)) {
return Status;
}
Status = EmmcSwitchBusWidth (PciIo, PassThru, Slot, Rca, TRUE, BusMode->BusWidth);
if (EFI_ERROR (Status)) {
return Status;
}
return EmmcSwitchBusTiming (PciIo, PassThru, Slot, Rca, BusMode->DriverStrength, BusMode->BusTiming, BusMode->ClockFreq);
}
/**
Check if passed BusTiming is supported in both controller and card.
@param[in] Private Pointer to controller private data
@param[in] SlotIndex Index of the slot in the controller
@param[in] ExtCsd Pointer to the card's extended CSD
@param[in] BusTiming Bus timing to check
@retval TRUE Both card and controller support given BusTiming
@retval FALSE Card or controller doesn't support given BusTiming
**/
BOOLEAN
EmmcIsBusTimingSupported (
IN SD_MMC_HC_PRIVATE_DATA *Private,
IN UINT8 SlotIndex,
IN EMMC_EXT_CSD *ExtCsd,
IN SD_MMC_BUS_MODE BusTiming
)
{
BOOLEAN Supported;
SD_MMC_HC_SLOT_CAP *Capabilities;
Capabilities = &Private->Capability[SlotIndex];
Supported = FALSE;
switch (BusTiming) {
case SdMmcMmcHs400:
if ((((ExtCsd->DeviceType & (BIT6 | BIT7)) != 0) && (Capabilities->Hs400 != 0)) && (Capabilities->BusWidth8 != 0)) {
Supported = TRUE;
}
break;
case SdMmcMmcHs200:
if ((((ExtCsd->DeviceType & (BIT4 | BIT5)) != 0) && (Capabilities->Sdr104 != 0))) {
Supported = TRUE;
}
break;
case SdMmcMmcHsDdr:
if ((((ExtCsd->DeviceType & (BIT2 | BIT3)) != 0) && (Capabilities->Ddr50 != 0))) {
Supported = TRUE;
}
break;
case SdMmcMmcHsSdr:
if ((((ExtCsd->DeviceType & BIT1) != 0) && (Capabilities->HighSpeed != 0))) {
Supported = TRUE;
}
break;
case SdMmcMmcLegacy:
if ((ExtCsd->DeviceType & BIT0) != 0) {
Supported = TRUE;
}
break;
default:
ASSERT (FALSE);
}
return Supported;
}
/**
Get the target bus timing to set on the link. This function
will try to select highest bus timing supported by card, controller
and the driver.
@param[in] Private Pointer to controller private data
@param[in] SlotIndex Index of the slot in the controller
@param[in] ExtCsd Pointer to the card's extended CSD
@return Bus timing value that should be set on link
**/
SD_MMC_BUS_MODE
EmmcGetTargetBusTiming (
IN SD_MMC_HC_PRIVATE_DATA *Private,
IN UINT8 SlotIndex,
IN EMMC_EXT_CSD *ExtCsd
)
{
SD_MMC_BUS_MODE BusTiming;
//
// We start with highest bus timing that this driver currently supports and
// return as soon as we find supported timing.
//
BusTiming = SdMmcMmcHs400;
while (BusTiming > SdMmcMmcLegacy) {
if (EmmcIsBusTimingSupported (Private, SlotIndex, ExtCsd, BusTiming)) {
break;
}
BusTiming--;
}
return BusTiming;
}
/**
Check if the passed bus width is supported by controller and card.
@param[in] Private Pointer to controller private data
@param[in] SlotIndex Index of the slot in the controller
@param[in] BusTiming Bus timing set on the link
@param[in] BusWidth Bus width to check
@retval TRUE Passed bus width is supported in current bus configuration
@retval FALSE Passed bus width is not supported in current bus configuration
**/
BOOLEAN
EmmcIsBusWidthSupported (
IN SD_MMC_HC_PRIVATE_DATA *Private,
IN UINT8 SlotIndex,
IN SD_MMC_BUS_MODE BusTiming,
IN UINT16 BusWidth
)
{
if ((BusWidth == 8) && (Private->Capability[SlotIndex].BusWidth8 != 0)) {
return TRUE;
} else if ((BusWidth == 4) && (BusTiming != SdMmcMmcHs400)) {
return TRUE;
} else if ((BusWidth == 1) && ((BusTiming == SdMmcMmcHsSdr) || (BusTiming == SdMmcMmcLegacy))) {
return TRUE;
}
return FALSE;
}
/**
Get the target bus width to be set on the bus.
@param[in] Private Pointer to controller private data
@param[in] SlotIndex Index of the slot in the controller
@param[in] ExtCsd Pointer to card's extended CSD
@param[in] BusTiming Bus timing set on the bus
@return Bus width to be set on the bus
**/
UINT8
EmmcGetTargetBusWidth (
IN SD_MMC_HC_PRIVATE_DATA *Private,
IN UINT8 SlotIndex,
IN EMMC_EXT_CSD *ExtCsd,
IN SD_MMC_BUS_MODE BusTiming
)
{
UINT8 BusWidth;
UINT8 PreferredBusWidth;
PreferredBusWidth = Private->Slot[SlotIndex].OperatingParameters.BusWidth;
if ((PreferredBusWidth != EDKII_SD_MMC_BUS_WIDTH_IGNORE) &&
EmmcIsBusWidthSupported (Private, SlotIndex, BusTiming, PreferredBusWidth))
{
BusWidth = PreferredBusWidth;
} else if (EmmcIsBusWidthSupported (Private, SlotIndex, BusTiming, 8)) {
BusWidth = 8;
} else if (EmmcIsBusWidthSupported (Private, SlotIndex, BusTiming, 4)) {
BusWidth = 4;
} else {
BusWidth = 1;
}
return BusWidth;
}
/**
Get the target clock frequency to be set on the bus.
@param[in] Private Pointer to controller private data
@param[in] SlotIndex Index of the slot in the controller
@param[in] ExtCsd Pointer to card's extended CSD
@param[in] BusTiming Bus timing to be set on the bus
@return Value of the clock frequency to be set on bus in MHz
**/
UINT32
EmmcGetTargetClockFreq (
IN SD_MMC_HC_PRIVATE_DATA *Private,
IN UINT8 SlotIndex,
IN EMMC_EXT_CSD *ExtCsd,
IN SD_MMC_BUS_MODE BusTiming
)
{
UINT32 PreferredClockFreq;
UINT32 MaxClockFreq;
PreferredClockFreq = Private->Slot[SlotIndex].OperatingParameters.ClockFreq;
switch (BusTiming) {
case SdMmcMmcHs400:
case SdMmcMmcHs200:
MaxClockFreq = 200;
break;
case SdMmcMmcHsSdr:
case SdMmcMmcHsDdr:
MaxClockFreq = 52;
break;
default:
MaxClockFreq = 26;
break;
}
if ((PreferredClockFreq != EDKII_SD_MMC_CLOCK_FREQ_IGNORE) && (PreferredClockFreq < MaxClockFreq)) {
return PreferredClockFreq;
} else {
return MaxClockFreq;
}
}
/**
Get the driver strength to be set on bus.
@param[in] Private Pointer to controller private data
@param[in] SlotIndex Index of the slot in the controller
@param[in] ExtCsd Pointer to card's extended CSD
@param[in] BusTiming Bus timing set on the bus
@return Value of the driver strength to be set on the bus
**/
EDKII_SD_MMC_DRIVER_STRENGTH
EmmcGetTargetDriverStrength (
IN SD_MMC_HC_PRIVATE_DATA *Private,
IN UINT8 SlotIndex,
IN EMMC_EXT_CSD *ExtCsd,
IN SD_MMC_BUS_MODE BusTiming
)
{
EDKII_SD_MMC_DRIVER_STRENGTH PreferredDriverStrength;
EDKII_SD_MMC_DRIVER_STRENGTH DriverStrength;
PreferredDriverStrength = Private->Slot[SlotIndex].OperatingParameters.DriverStrength;
DriverStrength.Emmc = EmmcDriverStrengthType0;
if ((PreferredDriverStrength.Emmc != EDKII_SD_MMC_DRIVER_STRENGTH_IGNORE) &&
(ExtCsd->DriverStrength & (BIT0 << PreferredDriverStrength.Emmc)))
{
DriverStrength.Emmc = PreferredDriverStrength.Emmc;
}
return DriverStrength;
}
/**
Get the target settings for the bus mode.
@param[in] Private Pointer to controller private data
@param[in] SlotIndex Index of the slot in the controller
@param[in] ExtCsd Pointer to card's extended CSD
@param[out] BusMode Target configuration of the bus
**/
VOID
EmmcGetTargetBusMode (
IN SD_MMC_HC_PRIVATE_DATA *Private,
IN UINT8 SlotIndex,
IN EMMC_EXT_CSD *ExtCsd,
OUT SD_MMC_BUS_SETTINGS *BusMode
)
{
BusMode->BusTiming = EmmcGetTargetBusTiming (Private, SlotIndex, ExtCsd);
BusMode->BusWidth = EmmcGetTargetBusWidth (Private, SlotIndex, ExtCsd, BusMode->BusTiming);
BusMode->ClockFreq = EmmcGetTargetClockFreq (Private, SlotIndex, ExtCsd, BusMode->BusTiming);
BusMode->DriverStrength = EmmcGetTargetDriverStrength (Private, SlotIndex, ExtCsd, BusMode->BusTiming);
}
/**
Switch the high speed timing according to request.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.6.8 and SD Host Controller
Simplified Spec 3.0 Figure 2-29 for details.
@param[in] PciIo A pointer to the EFI_PCI_IO_PROTOCOL instance.
@param[in] PassThru A pointer to the EFI_SD_MMC_PASS_THRU_PROTOCOL instance.
@param[in] Slot The slot number of the SD card to send the command to.
@param[in] Rca The relative device address to be assigned.
@retval EFI_SUCCESS The operation is done correctly.
@retval Others The operation fails.
**/
EFI_STATUS
EmmcSetBusMode (
IN EFI_PCI_IO_PROTOCOL *PciIo,
IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru,
IN UINT8 Slot,
IN UINT16 Rca
)
{
EFI_STATUS Status;
EMMC_CSD Csd;
EMMC_EXT_CSD ExtCsd;
SD_MMC_BUS_SETTINGS BusMode;
SD_MMC_HC_PRIVATE_DATA *Private;
Private = SD_MMC_HC_PRIVATE_FROM_THIS (PassThru);
Status = EmmcGetCsd (PassThru, Slot, Rca, &Csd);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "EmmcSetBusMode: GetCsd fails with %r\n", Status));
return Status;
}
Status = EmmcSelect (PassThru, Slot, Rca);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "EmmcSetBusMode: Select fails with %r\n", Status));
return Status;
}
ASSERT (Private->BaseClkFreq[Slot] != 0);
//
// Get Device_Type from EXT_CSD register.
//
Status = EmmcGetExtCsd (PassThru, Slot, &ExtCsd);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "EmmcSetBusMode: GetExtCsd fails with %r\n", Status));
return Status;
}
EmmcGetTargetBusMode (Private, Slot, &ExtCsd, &BusMode);
DEBUG ((
DEBUG_INFO,
"EmmcSetBusMode: Target bus mode: timing = %d, width = %d, clock freq = %d, driver strength = %d\n",
BusMode.BusTiming,
BusMode.BusWidth,
BusMode.ClockFreq,
BusMode.DriverStrength.Emmc
));
if (BusMode.BusTiming == SdMmcMmcHs400) {
Status = EmmcSwitchToHS400 (PciIo, PassThru, Slot, Rca, &BusMode);
} else if (BusMode.BusTiming == SdMmcMmcHs200) {
Status = EmmcSwitchToHS200 (PciIo, PassThru, Slot, Rca, &BusMode);
} else {
//
// Note that EmmcSwitchToHighSpeed is also called for SdMmcMmcLegacy
// bus timing. This is because even though we might not want to
// change the timing itself we still want to allow customization of
// bus parameters such as clock frequency and bus width.
//
Status = EmmcSwitchToHighSpeed (PciIo, PassThru, Slot, Rca, &BusMode);
}
DEBUG ((DEBUG_INFO, "EmmcSetBusMode: Switch to %a %r\n", (BusMode.BusTiming == SdMmcMmcHs400) ? "HS400" : ((BusMode.BusTiming == SdMmcMmcHs200) ? "HS200" : "HighSpeed"), Status));
return Status;
}
/**
Execute EMMC device identification procedure.
Refer to EMMC Electrical Standard Spec 5.1 Section 6.4 for details.
@param[in] Private A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
@param[in] Slot The slot number of the SD card to send the command to.
@retval EFI_SUCCESS There is a EMMC card.
@retval Others There is not a EMMC card.
**/
EFI_STATUS
EmmcIdentification (
IN SD_MMC_HC_PRIVATE_DATA *Private,
IN UINT8 Slot
)
{
EFI_STATUS Status;
EFI_PCI_IO_PROTOCOL *PciIo;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
UINT32 Ocr;
UINT16 Rca;
UINTN Retry;
PciIo = Private->PciIo;
PassThru = &Private->PassThru;
Status = EmmcReset (PassThru, Slot);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_VERBOSE, "EmmcIdentification: Executing Cmd0 fails with %r\n", Status));
return Status;
}
Ocr = 0;
Retry = 0;
do {
Status = EmmcGetOcr (PassThru, Slot, &Ocr);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_VERBOSE, "EmmcIdentification: Executing Cmd1 fails with %r\n", Status));
return Status;
}
Ocr |= BIT30;
if (Retry++ == 100) {
DEBUG ((DEBUG_VERBOSE, "EmmcIdentification: Executing Cmd1 fails too many times\n"));
return EFI_DEVICE_ERROR;
}
gBS->Stall (10 * 1000);
} while ((Ocr & BIT31) == 0);
Status = EmmcGetAllCid (PassThru, Slot);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_VERBOSE, "EmmcIdentification: Executing Cmd2 fails with %r\n", Status));
return Status;
}
//
// Slot starts from 0 and valid RCA starts from 1.
// Here we takes a simple formula to calculate the RCA.
// Don't support multiple devices on the slot, that is
// shared bus slot feature.
//
Rca = Slot + 1;
Status = EmmcSetRca (PassThru, Slot, Rca);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "EmmcIdentification: Executing Cmd3 fails with %r\n", Status));
return Status;
}
//
// Enter Data Tranfer Mode.
//
DEBUG ((DEBUG_INFO, "EmmcIdentification: Found a EMMC device at slot [%d], RCA [%d]\n", Slot, Rca));
Private->Slot[Slot].CardType = EmmcCardType;
Status = EmmcSetBusMode (PciIo, PassThru, Slot, Rca);
return Status;
}
| 1 | 17,685 | @aimanrosli23 Judging from the commit description, I do not know why this file got changed so much. Could you help to double confirm if you do not revert the changes brought by commits: SHA-1: 643623147a1feaddd734ddd84604e1d8e9dcebee * MdeModulePkg/SdMmcPciHcDxe: Send SEND_STATUS at lower frequency SHA-1: 49accdedf956f175041040e677163b7cbb746283 * MdeModulePkg/SdMmcPciHcDxe: Hook SwitchClockFreq after SD clock start | tianocore-edk2 | c |
@@ -0,0 +1,10 @@
+class CloudTag
+ TAGS_LIST = YAML.load File.read("#{Rails.root}/config/tags_list.yml")
+
+ class << self
+ def list
+ index = TAGS_LIST.length - Time.now.day
+ TAGS_LIST[index].sort { |a, b| a[0] <=> b[0] }
+ end
+ end
+end | 1 | 1 | 7,415 | How about YAML.load_file() | blackducksoftware-ohloh-ui | rb |
|
@@ -33,7 +33,9 @@ public class ContainerizationMetricsImpl implements ContainerizationMetrics {
private Meter podCompleted, podRequested, podScheduled, initContainerRunning,
appContainerStarting, podReady, podInitFailure, podAppFailure;
private Meter flowSubmitToExecutor, flowSubmitToContainer;
+ private Meter executionStopped, containerDispatchFail;
private Histogram timeToDispatch;
+ private boolean isInitialized = false;
@Inject
public ContainerizationMetricsImpl(MetricsManager metricsManager) { | 1 | /*
* Copyright 2021 LinkedIn Corp.
*
* 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.
*/
package azkaban.metrics;
import azkaban.utils.Props;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class implements ContainerMetrics and emit metrics for containerized executions
*/
public class ContainerizationMetricsImpl implements ContainerizationMetrics {
private static final Logger logger = LoggerFactory.getLogger(ContainerizationMetricsImpl.class);
private final MetricsManager metricsManager;
private Meter podCompleted, podRequested, podScheduled, initContainerRunning,
appContainerStarting, podReady, podInitFailure, podAppFailure;
private Meter flowSubmitToExecutor, flowSubmitToContainer;
private Histogram timeToDispatch;
@Inject
public ContainerizationMetricsImpl(MetricsManager metricsManager) {
this.metricsManager = metricsManager;
}
@Override
public void setUp() {
logger.info(String.format("Setting up container metrics."));
this.podCompleted = this.metricsManager.addMeter("Pod-Completed-Meter");
this.podRequested = this.metricsManager.addMeter("Pod-Requested-Meter");
this.podScheduled = this.metricsManager.addMeter("Pod-Scheduled-Meter");
this.initContainerRunning = this.metricsManager.addMeter("Init-Container-Running-Meter");
this.appContainerStarting = this.metricsManager.addMeter("App-Container-Starting-Meter");
this.podReady = this.metricsManager.addMeter("Pod-Ready-Meter");
this.podInitFailure = this.metricsManager.addMeter("Pod-Init-Failure-Meter");
this.podAppFailure = this.metricsManager.addMeter("Pod-App-Failure-Meter");
this.flowSubmitToExecutor = this.metricsManager.addMeter("Flow-Submit-To-Executor-Meter");
this.flowSubmitToContainer = this.metricsManager.addMeter("Flow-Submit-To-Container-Meter");
this.timeToDispatch = this.metricsManager.addHistogram("Time-To-Dispatch-Pod-Histogram");
}
@Override
public void startReporting(Props props) {
logger.info(String.format("Start reporting container metrics"));
this.metricsManager.startReporting("AZ-WEB", props);
}
/**
* Mark the occurrence of various pod statuses, defined by {@link azkaban.executor.container.watch.AzPodStatus}
*/
@Override
public void markPodCompleted() {
this.podCompleted.mark();
}
@Override
public void markPodRequested() {
this.podRequested.mark();
}
@Override
public void markPodScheduled() {
this.podScheduled.mark();
}
@Override
public void markInitContainerRunning() {
this.initContainerRunning.mark();
}
@Override
public void markAppContainerStarting() {
this.appContainerStarting.mark();
}
@Override
public void markPodReady() { this.podReady.mark(); }
@Override
public void markPodInitFailure() {
this.podInitFailure.mark();
}
@Override
public void markPodAppFailure() {
this.podAppFailure.mark();
}
@Override
public void addTimeToDispatch(final long time) { timeToDispatch.update(time); }
@Override
public void markFlowSubmitToExecutor() { flowSubmitToExecutor.mark(); }
@Override
public void markFlowSubmitToContainer() { flowSubmitToContainer.mark(); }
}
| 1 | 22,414 | Maybe make this `volatile` or atomic as this can be set/read from different threads? Also, separately you may want to check if some of the methods here need to be `synchronized`. | azkaban-azkaban | java |
@@ -974,6 +974,13 @@ drwrap_exit(void)
if (count != 0)
return;
+ drmgr_unregister_bb_app2app_event(drwrap_event_bb_app2app);
+ drmgr_unregister_bb_instrumentation_event(drwrap_event_bb_analysis);
+ drmgr_unregister_module_unload_event(drwrap_event_module_unload);
+ dr_unregister_delete_event(drwrap_fragment_delete);
+
+ drmgr_unregister_tls_field(tls_idx);
+
hashtable_delete(&replace_table);
hashtable_delete(&replace_native_table);
hashtable_delete(&wrap_table); | 1 | /* **********************************************************
* Copyright (c) 2010-2017 Google, Inc. All rights reserved.
* Copyright (c) 2008-2009 VMware, Inc. All rights reserved.
* **********************************************************/
/* drwrap: DynamoRIO Function Wrapping and Replacing Extension
* Derived from Dr. Memory: the memory debugger
*
* 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;
* version 2.1 of the License, and no later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/* DynamoRIO Function Wrapping and Replacing Extension
*/
#include "dr_api.h"
#include "drwrap.h"
#include "drmgr.h"
#include "hashtable.h"
#include "drvector.h"
#include "../ext_utils.h"
#include <string.h>
#include <stddef.h> /* offsetof */
#include <limits.h> /* USHRT_MAX */
/* currently using asserts on internal logic sanity checks (never on
* input from user)
*/
#ifdef DEBUG
# define ASSERT(x, msg) DR_ASSERT_MSG(x, msg)
# define DODEBUG(statement) do { statement } while (0)
#else
# define ASSERT(x, msg) /* nothing */
# define DODEBUG(statement)
#endif
#define EXCLUDE_CALLCONV(flags) ((flags) & ~(DRWRAP_CALLCONV_MASK))
#define EXTRACT_CALLCONV(flags) ((drwrap_callconv_t) ((flags) & (DRWRAP_CALLCONV_MASK)))
#ifdef WINDOWS
# define IF_WINDOWS(x) x
#else
# define IF_WINDOWS(x) /* nothing */
#endif
#ifdef DEBUG
static uint verbose = 0;
# define NOTIFY(level, ...) do { \
if (verbose >= (level)) { \
dr_fprintf(STDERR, __VA_ARGS__); \
} \
} while (0)
#else
# define NOTIFY(...) /* nothing */
#endif
#define ALIGNED(x, alignment) ((((ptr_uint_t)x) & ((alignment)-1)) == 0)
/* We rely on being able to clobber this register at call sites */
#ifdef ARM
# define CALL_POINT_SCRATCH_REG DR_REG_R12
#elif defined(X64)
# define CALL_POINT_SCRATCH_REG DR_REG_R11
#else
# define CALL_POINT_SCRATCH_REG DR_REG_NULL
#endif
/* protected by wrap_lock */
static drwrap_global_flags_t global_flags;
#ifdef WINDOWS
static int sysnum_NtContinue = -1;
#endif
/* in drwrap_asm.asm */
void
replace_native_xfer(void);
void
replace_native_rets(void);
void
replace_native_ret_imms(void);
void
replace_native_ret_imms_end(void);
#ifdef AARCHXX
byte *
get_cur_xsp(void);
#endif
/***************************************************************************
* REQUEST TRACKING
*/
/* There can only be one replacement for any target so we store just app_pc */
#define REPLACE_TABLE_HASH_BITS 6
/* i#1689: we store the decorated (LSB=1) pc (passed from client) in the table */
static hashtable_t replace_table;
/* Native replacements need to store the stack adjust and user data */
typedef struct _replace_native_t {
app_pc replacement;
bool at_entry;
uint stack_adjust;
void *user_data;
} replace_native_t;
#define REPLACE_NATIVE_TABLE_HASH_BITS 6
/* i#1689: we store the decorated (LSB=1) pc (passed from client) in the table */
static hashtable_t replace_native_table;
static void
replace_native_free(void *v)
{
replace_native_t *rn = (replace_native_t *) v;
dr_global_free(rn, sizeof(*rn));
}
/* For each target wrap address, we store a list of wrap requests */
typedef struct _wrap_entry_t {
app_pc func;
void (*pre_cb)(void *, OUT void **);
void (*post_cb)(void *, void *);
/* To support delayed removal. We don't set pre_cb and post_cb
* to NULL instead b/c we want to support re-wrapping.
*/
bool enabled;
drwrap_wrap_flags_t flags;
/* While it would probably be incorrect for the user to wrap the same function
* multiple times using differing calling conventions, it is possible. Therefore
* we propagate the callconv to the wrapcxt prior to each pre/post wrap callback.
*/
drwrap_callconv_t callconv;
void *user_data;
struct _wrap_entry_t *next;
} wrap_entry_t;
#define WRAP_TABLE_HASH_BITS 6
/* i#1689: we store the decorated (LSB=1) pc (passed from client) in the table */
static hashtable_t wrap_table;
/* We need recursive locking on the table to support drwrap_unwrap
* being called from a post event so we use this lock instead of
* hashtable_lock(&wrap_table)
*/
static void *wrap_lock;
static void
wrap_entry_free(void *v)
{
wrap_entry_t *e = (wrap_entry_t *) v;
wrap_entry_t *tmp;
ASSERT(e != NULL, "invalid hashtable deletion");
while (e != NULL) {
tmp = e;
e = e->next;
dr_global_free(tmp, sizeof(*tmp));
}
}
/* TLS. OK to be callback-shared: just more nesting. */
static int tls_idx;
/* We could dynamically allocate: for now assuming no truly recursive func */
#define MAX_WRAP_NESTING 64
/* When a wrapping is disabled, we lazily flush, b/c it's less costly to
* execute the already-instrumented pre and post points than to do a flush.
* Only after enough executions do we decide the flush is worthwhile.
*/
#define DISABLED_COUNT_FLUSH_THRESHOLD 1024
/* Lazy removal and flushing. Protected by wrap_lock. */
static uint disabled_count;
/* i#1713: per-thread state, similar to where_am_i_t */
typedef enum _drwrap_where_t {
DRWRAP_WHERE_OUTSIDE_CALLBACK,
DRWRAP_WHERE_PRE_FUNC,
DRWRAP_WHERE_POST_FUNC
} drwrap_where_t;
typedef struct _per_thread_t {
int wrap_level;
/* record which wrap routine */
app_pc last_wrap_func[MAX_WRAP_NESTING];
/* for no-frills we store wrap_entry_t */
wrap_entry_t *last_wrap_entry[MAX_WRAP_NESTING];
void *user_data_nofrills[MAX_WRAP_NESTING];
/* record app esp to handle tailcalls, etc. */
reg_t app_esp[MAX_WRAP_NESTING];
/* user_data for passing between pre and post cbs */
size_t user_data_count[MAX_WRAP_NESTING];
void **user_data[MAX_WRAP_NESTING];
void **user_data_pre_cb[MAX_WRAP_NESTING];
void **user_data_post_cb[MAX_WRAP_NESTING];
/* whether to skip */
bool skip[MAX_WRAP_NESTING];
#ifdef WINDOWS
/* did we see an exception while in a wrapped routine? */
bool hit_exception;
#endif
} per_thread_t;
/***************************************************************************
* UTILITIES
*/
/* XXX: should DR provide this variant of dr_safe_read? DrMem uses this too. */
bool
fast_safe_read(void *base, size_t size, void *out_buf)
{
#ifdef WINDOWS
/* For all of our uses, a failure is rare, so we do not want
* to pay the cost of the syscall (DrMemi#265).
*/
bool res = true;
DR_TRY_EXCEPT(dr_get_current_drcontext(), {
memcpy(out_buf, base, size);
}, { /* EXCEPT */
res = false;
});
return res;
#else
return dr_safe_read(base, size, out_buf, NULL);
#endif
}
/***************************************************************************
* WRAPPING INSTRUMENTATION TRACKING
*/
/* We need to know whether we've inserted instrumentation at the call site .
* The separate post_call_table tells us whether we've set up the return site
* for instrumentation.
*/
#define CALL_SITE_TABLE_HASH_BITS 10
/* i#1689: we store the aligned (LSB=0) pc here */
static hashtable_t call_site_table;
/* Hashtable so we can remember post-call pcs (since
* post-cti-instrumentation is not supported by DR).
* Synchronized externally to safeguard the externally-allocated payload,
* using an rwlock b/c read on every instruction.
*/
#define POST_CALL_TABLE_HASH_BITS 10
/* i#1689: we store the aligned (LSB=0) pc here */
static hashtable_t post_call_table;
static void *post_call_rwlock;
typedef struct _post_call_entry_t {
/* PR 454616: we need two flags in the post_call_table: one that
* says "please add instru for this callee" and one saying "all
* existing fragments have instru"
*/
bool existing_instrumented;
/* There seems to be no easy solution to correctly removing from
* the table without extra removals from our own non-consistency
* flushes: with delayed deletion we can easily have races, and if
* conservative we have performance problems where one tag's flush
* removes a whole buch of post-call, delayed deletion causes
* table removal after re-instrumentation, and then the next
* retaddr check causes another flush.
* Xref DrMemi#673, DRi#409, DrMemi#114, DrMemi#260.
*/
#define POST_CALL_PRIOR_BYTES_STORED 6 /* max normal call size */
byte prior[POST_CALL_PRIOR_BYTES_STORED];
} post_call_entry_t;
/* Support for external post-call caching */
typedef struct _post_call_notify_t {
void (*cb)(app_pc);
struct _post_call_notify_t *next;
} post_call_notify_t;
/* protected by post_call_rwlock */
post_call_notify_t *post_call_notify_list;
/* FIFO cache read w/o a lock (which we assume is fine b/c it's word-aligned
* and thus does not cross a cache line) and written under post_call_rwlock
*/
static uint postcall_cache_idx;
#define POSTCALL_CACHE_SIZE 8
static app_pc postcall_cache[POSTCALL_CACHE_SIZE];
static void
post_call_entry_free(void *v)
{
post_call_entry_t *e = (post_call_entry_t *) v;
ASSERT(e != NULL, "invalid hashtable deletion");
dr_global_free(e, sizeof(*e));
}
/* caller must hold write lock */
static post_call_entry_t *
post_call_entry_add(app_pc postcall, bool external)
{
post_call_entry_t *e = (post_call_entry_t *) dr_global_alloc(sizeof(*e));
ASSERT(dr_rwlock_self_owns_write_lock(post_call_rwlock), "must hold write lock");
e->existing_instrumented = false;
if (!fast_safe_read(postcall - POST_CALL_PRIOR_BYTES_STORED,
POST_CALL_PRIOR_BYTES_STORED, e->prior)) {
/* notify client somehow? we'll carry on and invalidate on next bb */
memset(e->prior, 0, sizeof(e->prior));
}
hashtable_add(&post_call_table, (void*)postcall, (void*)e);
if (!external && post_call_notify_list != NULL) {
post_call_notify_t *cb = post_call_notify_list;
while (cb != NULL) {
cb->cb(postcall);
cb = cb->next;
}
}
return e;
}
/* caller must hold post_call_rwlock read lock or write lock */
static bool
post_call_consistent(app_pc postcall, post_call_entry_t *e)
{
byte cur[POST_CALL_PRIOR_BYTES_STORED];
ASSERT(e != NULL, "invalid param");
/* i#673: to avoid all the problems w/ invalidating on delete, we instead
* invalidate on lookup. We store the prior 6 bytes which is the call
* instruction, which is what we care about. Note that it's ok for us
* to not be 100% accurate b/c we now use stored-esp on
* post-call and so make no assumptions about post-call sites.
*/
if (!fast_safe_read(postcall - POST_CALL_PRIOR_BYTES_STORED,
POST_CALL_PRIOR_BYTES_STORED, cur)) {
/* notify client somehow? */
return false;
}
return (memcmp(e->prior, cur, POST_CALL_PRIOR_BYTES_STORED) == 0);
}
#ifdef X86
static bool
post_call_lookup(app_pc pc)
{
bool res = false;
dr_rwlock_read_lock(post_call_rwlock);
res = (hashtable_lookup(&post_call_table, (void*)pc) != NULL);
dr_rwlock_read_unlock(post_call_rwlock);
return res;
}
#endif
/* marks as having instrumentation if it finds the entry */
static bool
post_call_lookup_for_instru(app_pc pc)
{
bool res = false;
post_call_entry_t *e;
dr_rwlock_read_lock(post_call_rwlock);
e = (post_call_entry_t *) hashtable_lookup(&post_call_table, (void*)pc);
if (e != NULL) {
res = post_call_consistent(pc, e);
if (!res) {
int i;
/* need the write lock */
dr_rwlock_read_unlock(post_call_rwlock);
e = NULL; /* no longer safe */
dr_rwlock_write_lock(post_call_rwlock);
/* might not be found now if racily removed: but that's fine */
hashtable_remove(&post_call_table, (void *)pc);
/* invalidate cache */
for (i = 0; i < POSTCALL_CACHE_SIZE; i++) {
if (pc == postcall_cache[i])
postcall_cache[i] = NULL;
}
dr_rwlock_write_unlock(post_call_rwlock);
return res;
} else {
e->existing_instrumented = true;
}
}
/* N.B.: we don't need DrMem i#559's storage of postcall points and
* check here to see if our postcall was flushed from underneath us,
* b/c we use invalidation on bb creation rather than deletion.
* So the postcall entry will be removed only if the code changed:
* and if it did, we don't want to re-add the entry or instru.
* In that case we'll miss the post-hook at the post-call point, but
* we'll execute it along w/ the next post-hook b/c of our stored esp.
* That seems sufficient.
*/
dr_rwlock_read_unlock(post_call_rwlock);
return res;
}
DR_EXPORT
bool
drwrap_register_post_call_notify(void (*cb)(app_pc pc))
{
post_call_notify_t *e;
if (cb == NULL)
return false;
e = dr_global_alloc(sizeof(*e));
e->cb = cb;
dr_rwlock_write_lock(post_call_rwlock);
e->next = post_call_notify_list;
post_call_notify_list = e;
dr_rwlock_write_unlock(post_call_rwlock);
return true;
}
DR_EXPORT
bool
drwrap_unregister_post_call_notify(void (*cb)(app_pc pc))
{
post_call_notify_t *e, *prev_e;
bool res;
if (cb == NULL)
return false;
dr_rwlock_write_lock(post_call_rwlock);
for (prev_e = NULL, e = post_call_notify_list; e != NULL; prev_e = e, e = e->next) {
if (e->cb == cb)
break;
}
if (e != NULL) {
if (prev_e == NULL)
post_call_notify_list = e->next;
else
prev_e->next = e->next;
dr_global_free(e, sizeof(*e));
res = true;
} else
res = false;
dr_rwlock_write_unlock(post_call_rwlock);
return res;
}
DR_EXPORT
bool
drwrap_mark_as_post_call(app_pc pc)
{
/* XXX: a tool adding a whole bunch of these would be better off acquiring
* the lock just once. Should we export lock+unlock routines?
*/
if (pc == NULL)
return false;
dr_rwlock_write_lock(post_call_rwlock);
post_call_entry_add(pc, true);
dr_rwlock_write_unlock(post_call_rwlock);
return true;
}
/***************************************************************************
* WRAPPING CONTEXT
*/
/* An opaque pointer we pass to callbacks and the user passes back for queries */
typedef struct _drwrap_context_t {
void *drcontext;
app_pc func;
dr_mcontext_t *mc;
app_pc retaddr;
bool mc_modified;
/* i#1713: client redirection request */
bool is_redirect_requested;
drwrap_callconv_t callconv;
drwrap_where_t where_am_i;
} drwrap_context_t;
static void
drwrap_context_init(void *drcontext, drwrap_context_t *wrapcxt, app_pc func,
dr_mcontext_t *mc, drwrap_where_t where, app_pc retaddr)
{
wrapcxt->drcontext = drcontext;
wrapcxt->func = func;
wrapcxt->mc = mc;
wrapcxt->retaddr = retaddr;
wrapcxt->mc_modified = false;
wrapcxt->is_redirect_requested = false;
wrapcxt->callconv = 0; /* must be set per wrap_entry_t for each pre/post callback */
wrapcxt->where_am_i = where;
}
DR_EXPORT
app_pc
drwrap_get_drcontext(void *wrapcxt_opaque)
{
drwrap_context_t *wrapcxt = (drwrap_context_t *) wrapcxt_opaque;
if (wrapcxt == NULL)
return NULL;
return wrapcxt->drcontext;
}
DR_EXPORT
app_pc
drwrap_get_func(void *wrapcxt_opaque)
{
drwrap_context_t *wrapcxt = (drwrap_context_t *) wrapcxt_opaque;
if (wrapcxt == NULL)
return NULL;
return wrapcxt->func;
}
DR_EXPORT
app_pc
drwrap_get_retaddr(void *wrapcxt_opaque)
{
drwrap_context_t *wrapcxt = (drwrap_context_t *) wrapcxt_opaque;
if (wrapcxt == NULL)
return NULL;
return wrapcxt->retaddr;
}
static dr_mcontext_t *
drwrap_get_mcontext_internal(drwrap_context_t *wrapcxt, dr_mcontext_flags_t flags)
{
dr_mcontext_t tmp;
flags &= DR_MC_ALL; /* throw away invalid flags */
/* lazily fill in info if more is requested than we have so far.
* unfortunately, dr_get_mcontext() clobbers what was there, so we
* can't just re-get whenever we see a new flag. the xmm/ymm regs
* are the bottleneck, so we just separate that out.
*/
if (!TESTALL(flags, wrapcxt->mc->flags)) {
dr_mcontext_flags_t old_flags = wrapcxt->mc->flags;
wrapcxt->mc->flags |= flags | DR_MC_INTEGER | DR_MC_CONTROL;
if (old_flags == 0) /* nothing to clobber */
dr_get_mcontext(wrapcxt->drcontext, wrapcxt->mc);
else {
ASSERT(TEST(DR_MC_MULTIMEDIA, flags) && !TEST(DR_MC_MULTIMEDIA, old_flags) &&
TESTALL(DR_MC_INTEGER|DR_MC_CONTROL, old_flags), "logic error");
/* the pre-ymm is smaller than ymm so we make a temp copy and then
* restore afterward. ugh, too many copies: but should be worth it
* for the typical case of not needing multimedia at all and thus
* having a faster dr_get_mcontext() call above
*/
memcpy(&tmp, wrapcxt->mc, offsetof(dr_mcontext_t, pc) + sizeof(tmp.pc));
dr_get_mcontext(wrapcxt->drcontext, wrapcxt->mc);
memcpy(wrapcxt->mc, &tmp, offsetof(dr_mcontext_t, pc) + sizeof(tmp.pc));
}
if (TEST(DRWRAP_FAST_CLEANCALLS, global_flags)) {
/* N.B: it's fine to have garbage in the xmm slots we didn't save
* (which is all but the x64 param ones) since we only redirect
* to start of callee where they're scratch or to retaddr on a
* skip where client should have retrieved param xmm (should happen
* automatically on get) and then filled in any xmm retvals.
*/
if (TEST(DR_MC_CONTROL, flags)) {
/* we need a sane eflags for redirect, but we also need to preserve
* trap flag or other flags so instead of zeroing we copy cur flags
* (xref i#806).
*/
#ifdef AARCHXX
wrapcxt->mc->xflags = 0; /*0 is fine for ARM */
#else
# ifdef WINDOWS
wrapcxt->mc->xflags = __readeflags();
# else
ptr_uint_t val;
__asm__ __volatile__("pushf"IF_X64_ELSE("q","l")"; pop"
IF_X64_ELSE("q","l")" %0" : "=m"(val));
wrapcxt->mc->xflags = val;
# endif
ASSERT(!TEST(EFLAGS_DF, wrapcxt->mc->xflags), "DF not cleared");
#endif
}
}
}
return wrapcxt->mc;
}
DR_EXPORT
dr_mcontext_t *
drwrap_get_mcontext_ex(void *wrapcxt_opaque, dr_mcontext_flags_t flags)
{
drwrap_context_t *wrapcxt = (drwrap_context_t *) wrapcxt_opaque;
if (wrapcxt == NULL)
return NULL;
return drwrap_get_mcontext_internal(wrapcxt, flags);
}
DR_EXPORT
dr_mcontext_t *
drwrap_get_mcontext(void *wrapcxt_opaque)
{
return drwrap_get_mcontext_ex(wrapcxt_opaque,
TEST(DRWRAP_FAST_CLEANCALLS, global_flags) ?
(DR_MC_INTEGER | DR_MC_CONTROL) : DR_MC_ALL);
}
DR_EXPORT
bool
drwrap_set_mcontext(void *wrapcxt_opaque)
{
drwrap_context_t *wrapcxt = (drwrap_context_t *) wrapcxt_opaque;
if (wrapcxt == NULL || wrapcxt->is_redirect_requested)
return false;
wrapcxt->mc_modified = true;
return true;
}
static inline reg_t *
drwrap_stack_arg_addr(drwrap_context_t *wrapcxt, uint arg, uint reg_arg_count,
uint stack_arg_offset)
{
return (reg_t *) (wrapcxt->mc->xsp +
(arg - reg_arg_count + stack_arg_offset) * sizeof(reg_t));
}
static inline reg_t *
drwrap_arg_addr(drwrap_context_t *wrapcxt, int arg)
{
if (wrapcxt == NULL || wrapcxt->mc == NULL)
return NULL;
if (wrapcxt->callconv != DRWRAP_CALLCONV_CDECL)
drwrap_get_mcontext_internal(wrapcxt, DR_MC_INTEGER); /* already have xsp */
switch (wrapcxt->callconv) {
#if defined(ARM)
case DRWRAP_CALLCONV_ARM:
switch (arg) {
case 0: return &wrapcxt->mc->r0;
case 1: return &wrapcxt->mc->r1;
case 2: return &wrapcxt->mc->r2;
case 3: return &wrapcxt->mc->r3;
default: return drwrap_stack_arg_addr(wrapcxt, arg, 4, 0);
}
#elif defined(AARCH64)
case DRWRAP_CALLCONV_AARCH64:
switch (arg) {
case 0: return &wrapcxt->mc->r0;
case 1: return &wrapcxt->mc->r1;
case 2: return &wrapcxt->mc->r2;
case 3: return &wrapcxt->mc->r3;
case 4: return &wrapcxt->mc->r4;
case 5: return &wrapcxt->mc->r5;
case 6: return &wrapcxt->mc->r6;
case 7: return &wrapcxt->mc->r7;
default: return drwrap_stack_arg_addr(wrapcxt, arg, 8, 0);
}
#else /* Intel x86 or x64 */
# ifdef X64 /* registers are platform-exclusive */
case DRWRAP_CALLCONV_AMD64:
switch (arg) {
case 0: return &wrapcxt->mc->rdi;
case 1: return &wrapcxt->mc->rsi;
case 2: return &wrapcxt->mc->rdx;
case 3: return &wrapcxt->mc->rcx;
case 4: return &wrapcxt->mc->r8;
case 5: return &wrapcxt->mc->r9;
default: return drwrap_stack_arg_addr(wrapcxt, arg, 6, 1/*retaddr*/);
}
case DRWRAP_CALLCONV_MICROSOFT_X64:
switch (arg) {
case 0: return &wrapcxt->mc->rcx;
case 1: return &wrapcxt->mc->rdx;
case 2: return &wrapcxt->mc->r8;
case 3: return &wrapcxt->mc->r9;
default: return drwrap_stack_arg_addr(wrapcxt, arg, 4,
1/*retaddr*/ + 4/*reserved*/);
}
# endif
case DRWRAP_CALLCONV_CDECL:
return drwrap_stack_arg_addr(wrapcxt, arg, 0, 1/*retaddr*/);
case DRWRAP_CALLCONV_FASTCALL:
switch (arg) {
case 0: return &wrapcxt->mc->xcx;
case 1: return &wrapcxt->mc->xdx;
default: return drwrap_stack_arg_addr(wrapcxt, arg, 2, 1/*retaddr*/);
}
case DRWRAP_CALLCONV_THISCALL:
if (arg == 0)
return &wrapcxt->mc->xcx;
else
return drwrap_stack_arg_addr(wrapcxt, arg, 1, 1/*retaddr*/);
#endif
default:
ASSERT(false, "unknown or unsupported calling convention");
return NULL;
}
}
DR_EXPORT
void *
drwrap_get_arg(void *wrapcxt_opaque, int arg)
{
drwrap_context_t *wrapcxt = (drwrap_context_t *) wrapcxt_opaque;
reg_t *addr = drwrap_arg_addr(wrapcxt, arg);
if (wrapcxt->where_am_i != DRWRAP_WHERE_PRE_FUNC)
return NULL; /* can only get args in pre */
if (addr == NULL)
return NULL;
else if (TEST(DRWRAP_SAFE_READ_ARGS, global_flags)) {
void *arg;
if (!fast_safe_read(addr, sizeof(arg), &arg))
return NULL;
return arg;
} else
return (void *) *addr;
}
DR_EXPORT
bool
drwrap_set_arg(void *wrapcxt_opaque, int arg, void *val)
{
drwrap_context_t *wrapcxt = (drwrap_context_t *) wrapcxt_opaque;
reg_t *addr = drwrap_arg_addr(wrapcxt, arg);
if (wrapcxt->where_am_i != DRWRAP_WHERE_PRE_FUNC)
return false; /* can only set args in pre */
if (addr == NULL)
return false;
else {
bool in_memory = true;
in_memory = !(addr >= (reg_t*)wrapcxt->mc && addr < (reg_t*)(wrapcxt->mc + 1));
if (!in_memory)
wrapcxt->mc_modified = true;
if (in_memory && TEST(DRWRAP_SAFE_READ_ARGS, global_flags)) {
if (!dr_safe_write((void *)addr, sizeof(val), val, NULL))
return false;
} else
*addr = (reg_t) val;
}
return true;
}
DR_EXPORT
void *
drwrap_get_retval(void *wrapcxt_opaque)
{
drwrap_context_t *wrapcxt = (drwrap_context_t *) wrapcxt_opaque;
if (wrapcxt->where_am_i != DRWRAP_WHERE_POST_FUNC)
return false; /* can only get retval in post */
if (wrapcxt == NULL || wrapcxt->mc == NULL)
return NULL;
/* ensure we have the info we need */
drwrap_get_mcontext_internal(wrapcxt_opaque, DR_MC_INTEGER);
return (void *) wrapcxt->mc->IF_X86_ELSE(xax, r0);
}
DR_EXPORT
bool
drwrap_set_retval(void *wrapcxt_opaque, void *val)
{
drwrap_context_t *wrapcxt = (drwrap_context_t *) wrapcxt_opaque;
per_thread_t *pt = (per_thread_t *) drmgr_get_tls_field(wrapcxt->drcontext, tls_idx);
if (wrapcxt == NULL || wrapcxt->mc == NULL)
return false;
/* ensure we have the info we need */
if (wrapcxt->where_am_i != DRWRAP_WHERE_POST_FUNC && !pt->skip[pt->wrap_level])
return false; /* can only set retval in post, or if skipping */
drwrap_get_mcontext_internal(wrapcxt_opaque, DR_MC_INTEGER);
wrapcxt->mc->IF_X86_ELSE(xax, r0) = (reg_t) val;
wrapcxt->mc_modified = true;
return true;
}
DR_EXPORT
bool
drwrap_skip_call(void *wrapcxt_opaque, void *retval, size_t stdcall_args_size)
{
drwrap_context_t *wrapcxt = (drwrap_context_t *) wrapcxt_opaque;
per_thread_t *pt = (per_thread_t *) drmgr_get_tls_field(wrapcxt->drcontext, tls_idx);
bool was_skipped = pt->skip[pt->wrap_level];
if (wrapcxt->where_am_i != DRWRAP_WHERE_PRE_FUNC)
return false; /* must be in pre to skip */
if (wrapcxt == NULL || wrapcxt->mc == NULL || wrapcxt->retaddr == NULL)
return false;
/* ensure we have the info we need */
drwrap_get_mcontext_internal(wrapcxt_opaque, DR_MC_INTEGER|DR_MC_CONTROL);
/* we can't redirect here b/c we need to release locks */
pt->skip[pt->wrap_level] = true;
if (!drwrap_set_retval(wrapcxt_opaque, retval)) {
pt->skip[pt->wrap_level] = was_skipped;
return false;
}
#ifdef X86
wrapcxt->mc->xsp += stdcall_args_size + sizeof(void*)/*retaddr*/;
#endif
wrapcxt->mc->pc = wrapcxt->retaddr;
return true;
}
/* i#1713: redirect execution from a post-function callback */
drext_status_t
drwrap_redirect_execution(void *wrapcxt_opaque)
{
drwrap_context_t *wrapcxt = (drwrap_context_t *) wrapcxt_opaque;
if (wrapcxt_opaque == NULL) {
NOTIFY(2, "%s: rejected redirect: NULL wrapcxt\n", __FUNCTION__);
return DREXT_ERROR;
}
if (wrapcxt->where_am_i != DRWRAP_WHERE_POST_FUNC) {
NOTIFY(2, "%s: rejected redirect in state %d\n", __FUNCTION__,
wrapcxt->where_am_i);
return DREXT_ERROR_INCOMPATIBLE_STATE;
}
if (wrapcxt->is_redirect_requested) {
NOTIFY(2, "%s: rejected redirect: already redirected\n", __FUNCTION__);
return DREXT_ERROR_INCOMPATIBLE_STATE;
}
DODEBUG({
per_thread_t *pt = (per_thread_t *) drmgr_get_tls_field(wrapcxt->drcontext,
tls_idx);
ASSERT(pt->wrap_level >= 0, "must be in a post-wrap");
NOTIFY(2, "%s: accepted redirect request from the return of "PFX" to "PFX"\n",
__FUNCTION__, pt->last_wrap_func[pt->wrap_level], wrapcxt->mc->pc);
});
drwrap_set_mcontext(wrapcxt_opaque);
wrapcxt->is_redirect_requested = true;
return DREXT_SUCCESS;
}
bool
drwrap_is_redirect_requested(void *wrapcxt_opaque)
{
drwrap_context_t *wrapcxt = (drwrap_context_t *) wrapcxt_opaque;
if (wrapcxt->where_am_i != DRWRAP_WHERE_POST_FUNC)
return false;
return wrapcxt->is_redirect_requested;
}
/***************************************************************************
* FORWARD DECLS
*/
static void
drwrap_thread_init(void *drcontext);
static void
drwrap_thread_exit(void *drcontext);
static dr_emit_flags_t
drwrap_event_bb_app2app(void *drcontext, void *tag, instrlist_t *bb,
bool for_trace, bool translating);
static dr_emit_flags_t
drwrap_event_bb_analysis(void *drcontext, void *tag, instrlist_t *bb,
bool for_trace, bool translating, OUT void **user_data);
static dr_emit_flags_t
drwrap_event_bb_insert(void *drcontext, void *tag, instrlist_t *bb, instr_t *inst,
bool for_trace, bool translating, void *user_data);
static void
drwrap_event_module_unload(void *drcontext, const module_data_t *info);
static void
drwrap_fragment_delete(void *dc/*may be NULL*/, void *tag);
static inline void
drwrap_in_callee_check_unwind(void *drcontext, per_thread_t *pt, dr_mcontext_t *mc);
#ifdef WINDOWS
static bool
drwrap_event_filter_syscall(void *drcontext, int sysnum);
static bool
drwrap_event_pre_syscall(void *drcontext, int sysnum);
bool
drwrap_event_exception(void *drcontext, dr_exception_t *excpt);
#endif
static void
drwrap_replace_init(void);
/***************************************************************************
* INIT
*/
static int drwrap_init_count;
DR_EXPORT
bool
drwrap_init(void)
{
/* make sure replace goes before app2app so use negative priority */
drmgr_priority_t pri_replace = {sizeof(pri_replace), DRMGR_PRIORITY_NAME_DRWRAP,
NULL, NULL, DRMGR_PRIORITY_APP2APP_DRWRAP};
drmgr_priority_t pri_insert = {sizeof(pri_insert), DRMGR_PRIORITY_NAME_DRWRAP,
NULL, NULL, DRMGR_PRIORITY_INSERT_DRWRAP};
#ifdef WINDOWS
/* DrMem i#1098: We use a late priority so we don't unwind if the client
* handles the fault.
*/
drmgr_priority_t pri_fault = {sizeof(pri_fault), DRMGR_PRIORITY_NAME_DRWRAP,
NULL, NULL, DRMGR_PRIORITY_FAULT_DRWRAP};
module_data_t *ntdll;
#endif
/* handle multiple sets of init/exit calls */
int count = dr_atomic_add32_return_sum(&drwrap_init_count, 1);
if (count > 1)
return true;
/* We have to fail if the stolen reg matches what we need */
if (dr_get_stolen_reg() != DR_REG_NULL &&
dr_get_stolen_reg() == CALL_POINT_SCRATCH_REG)
return false;
drmgr_init();
if (!drmgr_register_bb_app2app_event(drwrap_event_bb_app2app, &pri_replace))
return false;
if (!drmgr_register_bb_instrumentation_event(drwrap_event_bb_analysis,
drwrap_event_bb_insert,
&pri_insert))
return false;
hashtable_init(&replace_table, REPLACE_TABLE_HASH_BITS,
HASH_INTPTR, false/*!strdup*/);
hashtable_init_ex(&replace_native_table, REPLACE_NATIVE_TABLE_HASH_BITS,
HASH_INTPTR, false/*!strdup*/, false/*!synch*/,
replace_native_free, NULL, NULL);
hashtable_init_ex(&wrap_table, WRAP_TABLE_HASH_BITS, HASH_INTPTR,
false/*!str_dup*/, false/*!synch*/, wrap_entry_free,
NULL, NULL);
hashtable_init_ex(&call_site_table, CALL_SITE_TABLE_HASH_BITS, HASH_INTPTR,
false/*!strdup*/, false/*!synch*/, NULL, NULL, NULL);
hashtable_init_ex(&post_call_table, POST_CALL_TABLE_HASH_BITS, HASH_INTPTR,
false/*!str_dup*/, false/*!synch*/, post_call_entry_free,
NULL, NULL);
post_call_rwlock = dr_rwlock_create();
wrap_lock = dr_recurlock_create();
drmgr_register_module_unload_event(drwrap_event_module_unload);
dr_register_delete_event(drwrap_fragment_delete);
tls_idx = drmgr_register_tls_field();
if (tls_idx == -1)
return false;
if (!drmgr_register_thread_init_event(drwrap_thread_init))
return false;
if (!drmgr_register_thread_exit_event(drwrap_thread_exit))
return false;
#ifdef WINDOWS
ntdll = dr_lookup_module_by_name("ntdll.dll");
ASSERT(ntdll != NULL, "failed to find ntdll");
if (ntdll != NULL) {
app_pc wrapper = (app_pc) dr_get_proc_address(ntdll->handle, "NtContinue");
ASSERT(wrapper != NULL, "failed to find NtContinue wrapper");
if (wrapper != NULL) {
sysnum_NtContinue = drmgr_decode_sysnum_from_wrapper(wrapper);
ASSERT(sysnum_NtContinue != -1, "error decoding NtContinue");
dr_register_filter_syscall_event(drwrap_event_filter_syscall);
drmgr_register_pre_syscall_event(drwrap_event_pre_syscall);
}
dr_free_module_data(ntdll);
}
drmgr_register_exception_event_ex(drwrap_event_exception, &pri_fault);
#endif
drwrap_replace_init();
return true;
}
DR_EXPORT
void
drwrap_exit(void)
{
/* handle multiple sets of init/exit calls */
int count = dr_atomic_add32_return_sum(&drwrap_init_count, -1);
if (count != 0)
return;
hashtable_delete(&replace_table);
hashtable_delete(&replace_native_table);
hashtable_delete(&wrap_table);
hashtable_delete(&call_site_table);
hashtable_delete(&post_call_table);
dr_rwlock_destroy(post_call_rwlock);
dr_recurlock_destroy(wrap_lock);
drmgr_exit();
while (post_call_notify_list != NULL) {
post_call_notify_t *tmp = post_call_notify_list->next;
dr_global_free(post_call_notify_list, sizeof(*post_call_notify_list));
post_call_notify_list = tmp;
}
}
static void
drwrap_thread_init(void *drcontext)
{
per_thread_t *pt = (per_thread_t *) dr_thread_alloc(drcontext, sizeof(*pt));
memset(pt, 0, sizeof(*pt));
pt->wrap_level = -1;
drmgr_set_tls_field(drcontext, tls_idx, (void *) pt);
}
static void
drwrap_free_user_data(void *drcontext, per_thread_t *pt, int i)
{
if (pt->user_data[i] != NULL) {
dr_thread_free(drcontext, pt->user_data[i],
sizeof(void*)*pt->user_data_count[i]);
pt->user_data[i] = NULL;
}
if (pt->user_data_pre_cb[i] != NULL) {
dr_thread_free(drcontext, pt->user_data_pre_cb[i],
sizeof(void*)*pt->user_data_count[i]);
pt->user_data_pre_cb[i] = NULL;
}
if (pt->user_data_post_cb[i] != NULL) {
dr_thread_free(drcontext, pt->user_data_post_cb[i],
sizeof(void*)*pt->user_data_count[i]);
pt->user_data_post_cb[i] = NULL;
}
}
static void
drwrap_thread_exit(void *drcontext)
{
per_thread_t *pt = (per_thread_t *) drmgr_get_tls_field(drcontext, tls_idx);
int i;
for (i = 0; i < MAX_WRAP_NESTING; i++) {
drwrap_free_user_data(drcontext, pt, i);
}
dr_thread_free(drcontext, pt, sizeof(*pt));
}
DR_EXPORT
bool
drwrap_set_global_flags(drwrap_global_flags_t flags)
{
drwrap_global_flags_t old_flags;
bool res;
dr_recurlock_lock(wrap_lock);
/* if anyone asks for safe, be safe.
* since today the only 2 flags ask for safe, we can accomplish that
* by simply or-ing in each request.
* we now have DRWRAP_NO_FRILLS but it's documented as not being removable
* so we can continue or-ing.
*/
old_flags = global_flags;
global_flags |= flags;
res = (global_flags != old_flags);
dr_recurlock_unlock(wrap_lock);
return res;
}
/***************************************************************************
* FUNCTION REPLACING
*/
#define RET_IMM_LEN 3
static uint max_stack_adjust;
static byte *
get_func_entry(byte *addr)
{
/* On Windows with /debug the ILT is used. There may be a link flag to
* avoid that (the core seems to do so for its safe_read_asm_* labels,
* although the relevant flags /incremental and /ZI don't seem to be
* there for drwrap so further investigation is needed)
* but we may as well be robust to how it's built.
*/
if (*addr == 0xe9/*jmp*/)
return addr + 5 + *(int*)(addr+1); /* resolve jmp target */
else
return addr;
}
static void
drwrap_replace_init(void)
{
#if defined(DEBUG) && defined(X86)
void *drcontext;
instr_t inst;
byte *next_pc;
uint max_immed = 0;
#endif
byte *pc = get_func_entry((byte *)replace_native_ret_imms);
byte *end_pc = get_func_entry((byte *)replace_native_ret_imms_end);
max_stack_adjust = (uint) ((end_pc - pc) / RET_IMM_LEN) * sizeof(void*);
#if defined(DEBUG) && defined(X86)
drcontext = dr_get_current_drcontext();
instr_init(drcontext, &inst);
while (pc < end_pc) {
next_pc = decode(drcontext, pc, &inst);
ASSERT(next_pc != NULL, "invalid ret asm");
if (next_pc == NULL)
break; /* at least don't inf loop */
ASSERT(instr_get_opcode(&inst) == OP_ret, "invalid ret asm");
ASSERT(next_pc - pc == RET_IMM_LEN, "invalid ret len");
ASSERT(opnd_is_immed_int(instr_get_src(&inst, 0)), "invalid ret opnd");
max_immed = (uint) opnd_get_immed_int(instr_get_src(&inst, 0));
instr_reset(drcontext, &inst);
pc = next_pc;
}
ASSERT(max_immed == max_stack_adjust, "invalid max imm");
pc = get_func_entry((byte *)replace_native_rets);
decode(drcontext, pc, &inst);
ASSERT(instr_get_opcode(&inst) == OP_ret, "invalid ret asm");
instr_free(drcontext, &inst);
#endif
ASSERT(DRWRAP_REPLACE_NATIVE_DATA_SLOT != SPILL_SLOT_REDIRECT_NATIVE_TGT,
"TLS slot conflict");
ASSERT(DRWRAP_REPLACE_NATIVE_SP_SLOT != SPILL_SLOT_REDIRECT_NATIVE_TGT,
"TLS slot conflict");
}
static byte *
replace_native_ret_stub(uint stack_adjust)
{
if (stack_adjust > max_stack_adjust ||
!ALIGNED(stack_adjust, sizeof(void*)))
return NULL;
if (stack_adjust == 0)
return (byte *) replace_native_rets;
else {
return ((byte *)replace_native_ret_imms) +
((stack_adjust / sizeof(void*)) - 1/*skip 0*/) * RET_IMM_LEN;
}
}
DR_EXPORT
bool
drwrap_is_replaced(app_pc func)
{
return hashtable_lookup(&replace_table, func) != NULL;
}
DR_EXPORT
bool
drwrap_is_replaced_native(app_pc func)
{
bool res = false;
hashtable_lock(&replace_native_table);
res = hashtable_lookup(&replace_native_table, func) != NULL;
hashtable_unlock(&replace_native_table);
return res;
}
static bool
drwrap_replace_common(hashtable_t *table,
app_pc original, void *payload, bool override, bool force_flush)
{
bool res = true;
bool flush = force_flush;
if (original == NULL)
return false;
if (payload == NULL) {
if (!override)
res = false;
else {
flush = true;
res = hashtable_remove(table, (void *)original);
}
} else {
if (override) {
flush = (hashtable_add_replace(table, (void *)original, payload) != NULL);
} else
res = hashtable_add(table, (void *)original, payload);
}
/* XXX: we're assuming void* tag == pc
* XXX: we're assuming the replace target is not in the middle of a trace
*/
if (flush || dr_fragment_exists_at(dr_get_current_drcontext(), original)) {
/* we do not guarantee faster than a lazy flush.
* we can't use dr_unlink_flush_region() unless we require that
* caller hold no locks and be in clean call or syscall event.
*/
if (!dr_delay_flush_region(original, 1, 0, NULL))
ASSERT(false, "replace update flush failed");
}
return res;
}
DR_EXPORT
bool
drwrap_replace(app_pc original, app_pc replacement, bool override)
{
return drwrap_replace_common(&replace_table, original, replacement, override, false);
}
DR_EXPORT
bool
drwrap_replace_native(app_pc original, app_pc replacement, bool at_entry,
uint stack_adjust, void *user_data, bool override)
{
bool res = false;
replace_native_t *rn;
if (stack_adjust > max_stack_adjust ||
!ALIGNED(stack_adjust, sizeof(void*))
IF_NOT_X86(|| stack_adjust != 0))
return false;
if (replacement == NULL)
rn = NULL;
else {
rn = dr_global_alloc(sizeof(*rn));
rn->replacement = replacement;
rn->at_entry = at_entry;
rn->stack_adjust = stack_adjust;
rn->user_data = user_data;
}
hashtable_lock(&replace_native_table);
res = drwrap_replace_common(&replace_native_table, original, rn, override,
/* i#1438: if we're not at the entry, we'd better
* flush to ensure we replace. If this is done at
* module load, the flush will be empty and will cost
* just a few mutexes.
*/
!at_entry);
hashtable_unlock(&replace_native_table);
return res;
}
/* removes all instrs from start to the end of ilist
* XXX: add to DR and export?
*/
static void
instrlist_truncate(void *drcontext, instrlist_t *ilist, instr_t *start)
{
instr_t *next = start, *tmp;
while (next != NULL) {
tmp = next;
next = instr_get_next(next);
instrlist_remove(ilist, tmp);
instr_destroy(drcontext, tmp);
}
}
static void
drwrap_replace_bb(void *drcontext, instrlist_t *bb, instr_t *inst,
app_pc pc, app_pc replace)
{
#if defined(ARM) || defined(X64)
instr_t *first, *last;
#endif
/* remove the rest of the bb and replace w/ jmp to target.
* with i#427 we'd call instrlist_clear(drcontext, bb)
*/
instrlist_truncate(drcontext, bb, inst);
#if defined(ARM) || defined(X64)
/* XXX: simple jmp has reachability issues.
* Jumping through DR memory doesn't work well (meta instrs in app2app,
* ind jmp mangled w/ i#107).
* Probably best to add DR API to set exit cti target of bb
* which is i#429. For now we clobber CALL_POINT_SCRATCH_REG, which is scratch
* and unused for parameter transfer in most calling conventions.
*/
instrlist_insert_mov_immed_ptrsz(drcontext, (ptr_int_t)replace,
opnd_create_reg(CALL_POINT_SCRATCH_REG),
bb, NULL, &first, &last);
for (;; first = instr_get_next(first)) {
instr_set_app(first);
instr_set_translation(first, pc);
if (last == NULL || first == last)
break;
}
instrlist_append(bb, INSTR_XL8
(XINST_CREATE_jump_reg
(drcontext, opnd_create_reg(CALL_POINT_SCRATCH_REG)), pc));
#else
instrlist_append(bb, INSTR_XL8(INSTR_CREATE_jmp
(drcontext, opnd_create_pc(replace)), pc));
#endif
}
static void
drwrap_replace_native_push_retaddr(void *drcontext, instrlist_t *bb, app_pc pc,
ptr_int_t pushval, opnd_size_t stacksz
_IF_X86_64(bool x86))
{
#ifdef AARCHXX
instr_t *first, *last;
instrlist_insert_mov_immed_ptrsz(drcontext, pushval, opnd_create_reg(DR_REG_LR),
bb, NULL, &first, &last);
for (;; first = instr_get_next(first)) {
instr_set_app(first);
instr_set_translation(first, pc);
if (last == NULL || first == last)
break;
}
#else
if (stacksz == OPSZ_4 IF_X64(&& x86)) {
instrlist_append
(bb, INSTR_XL8(INSTR_CREATE_push_imm
(drcontext, OPND_CREATE_INT32(pushval)), pc));
}
# if defined(X86) && defined(X64)
else if (!x86 && stacksz == OPSZ_8) {
/* needs 2 steps */
instrlist_append
(bb, INSTR_XL8(INSTR_CREATE_push_imm
(drcontext, OPND_CREATE_INT32((int)pushval)), pc));
/* first push sign-extended so may not need 2nd */
if ((ptr_uint_t)pushval >= 0x80000000) {
instrlist_append
(bb, INSTR_XL8(INSTR_CREATE_mov_st
(drcontext, OPND_CREATE_MEM32(DR_REG_XSP, 4),
OPND_CREATE_INT32((int)((ptr_int_t)pushval >> 32))), pc));
}
}
# endif
else {
int sz = opnd_size_in_bytes(stacksz);
ptr_int_t val = 0;
if (stacksz == OPSZ_2)
val = pushval & (ptr_int_t) 0x0000ffff;
# if defined(X86) && defined(X64)
else {
ASSERT(stacksz == OPSZ_4 && !x86, "illegal stack size for call");
val = (ptr_int_t)pushval & (ptr_int_t) 0xffffffff;
}
# endif
/* can't do a non-default operand size with a push immed so we emulate */
instrlist_append
(bb, INSTR_XL8(INSTR_CREATE_lea
(drcontext, opnd_create_reg(DR_REG_XSP),
opnd_create_base_disp(DR_REG_XSP, DR_REG_NULL, 0,
-sz, OPSZ_lea)), pc));
instrlist_append
(bb, INSTR_XL8(INSTR_CREATE_mov_st
(drcontext, opnd_create_base_disp(DR_REG_XSP, DR_REG_NULL,
0, 0, stacksz),
opnd_create_immed_int(val, stacksz)), pc));
}
#endif /* !ARM */
}
static void
drwrap_replace_native_bb(void *drcontext, instrlist_t *bb, instr_t *inst,
app_pc pc, replace_native_t *rn, app_pc topush)
{
/* we're in the callee to handle indirect transfers, so the retaddr
* is already in place. We can't push a new retaddr on top of it b/c
* we need the args to be accessible with normal offsets.
* and we don't want to replace the retaddr w/ a code cache retaddr
* b/c that causes issues w/ callstacks (see
* https://github.com/DynamoRIO/drmemory/issues/935).
* We end up going with a continuation-based approach, which avoids
* a return point in the cache and thus simplifies issues w/
* the replacement code using app resources (see
* https://github.com/DynamoRIO/drmemory/issues/900).
*
* It's much easier to get the app xsp here so we store it in a
* tls slot. We also store the stack adjust for use later.
*
* if (topush != NULL) {
* push app retaddr
* }
* meta mov xsp to scratch slot
* if (user_data != NULL) {
* meta mov $user_data to scratch slot 2
* }
* meta jmp to replace routine
* <never reached>
* nop (to avoid non-empty bb)
*/
/* get data from inst before we destroy it */
#if defined(DEBUG) && defined(X86)
uint opc = instr_get_opcode(inst);
#endif
#if defined(X86) && defined(X64)
bool x86 = instr_get_x86_mode(inst);
#endif
opnd_size_t stacksz = OPSZ_NA;
#ifdef X86
if (topush != NULL) {
ASSERT(instr_num_dsts(inst) > 1 &&
opnd_is_base_disp(instr_get_dst(inst, 1)), "expected call");
stacksz = opnd_get_size(instr_get_dst(inst, 1));
ASSERT(IF_X86_ELSE(opc == OP_call || opc == OP_call_ind,
instr_is_call(inst)), "unsupported call type");
}
#endif
instrlist_truncate(drcontext, bb, inst);
ASSERT(DRWRAP_REPLACE_NATIVE_DATA_SLOT <= dr_max_opnd_accessible_spill_slot(),
"assuming TLS direct access");
ASSERT(DRWRAP_REPLACE_NATIVE_SP_SLOT <= dr_max_opnd_accessible_spill_slot(),
"assuming TLS direct access");
if (topush != NULL) {
drwrap_replace_native_push_retaddr(drcontext, bb, pc, (ptr_int_t) topush,
stacksz _IF_X86_64(x86));
}
#ifdef AARCH64
/* We clobber CALL_POINT_SCRATCH_REG, which is scratch in most call conventions. */
instrlist_meta_append(bb, XINST_CREATE_move
(drcontext, opnd_create_reg(CALL_POINT_SCRATCH_REG),
opnd_create_reg(DR_REG_XSP)));
#endif
instrlist_meta_append(bb, XINST_CREATE_store
(drcontext, dr_reg_spill_slot_opnd
(drcontext, DRWRAP_REPLACE_NATIVE_SP_SLOT),
opnd_create_reg(IF_AARCH64_ELSE(CALL_POINT_SCRATCH_REG,
DR_REG_XSP))));
/* We go ahead and use the 3rd fast spill slot for storage */
#ifdef AARCHXX
/* We don't support non-zero stack_adjust, so we use the slot to store LR. */
instrlist_meta_append(bb, XINST_CREATE_store
(drcontext, dr_reg_spill_slot_opnd
(drcontext, SPILL_SLOT_REDIRECT_NATIVE_TGT),
opnd_create_reg(DR_REG_LR)));
#else
instrlist_meta_append(bb, XINST_CREATE_store
(drcontext, dr_reg_spill_slot_opnd
(drcontext, SPILL_SLOT_REDIRECT_NATIVE_TGT),
OPND_CREATE_INT32(rn->stack_adjust)));
#endif
if (rn->user_data != NULL) {
#if defined(ARM) || defined(X64)
/* We clobber CALL_POINT_SCRATCH_REG, which is scratch in most call convs */
instrlist_insert_mov_immed_ptrsz(drcontext, (ptr_int_t)rn->user_data,
opnd_create_reg(CALL_POINT_SCRATCH_REG),
bb, NULL, NULL, NULL);
instrlist_meta_append(bb, XINST_CREATE_store
(drcontext, dr_reg_spill_slot_opnd
(drcontext, DRWRAP_REPLACE_NATIVE_DATA_SLOT),
opnd_create_reg(CALL_POINT_SCRATCH_REG)));
#else
instrlist_meta_append(bb, INSTR_CREATE_mov_st
(drcontext, dr_reg_spill_slot_opnd
(drcontext, DRWRAP_REPLACE_NATIVE_DATA_SLOT),
OPND_CREATE_INTPTR((ptr_int_t)rn->user_data)));
#endif
}
#if defined(ARM) || defined(X64)
/* XXX: simple call has reachability issues. For now we clobber
* CALL_POINT_SCRATCH_REG, which is scratch in most calling conventions.
*/
instrlist_insert_mov_immed_ptrsz(drcontext, (ptr_int_t)rn->replacement,
opnd_create_reg(CALL_POINT_SCRATCH_REG),
bb, NULL, NULL, NULL);
instrlist_meta_append(bb, XINST_CREATE_jump_reg
(drcontext, opnd_create_reg(CALL_POINT_SCRATCH_REG)));
#else
instrlist_meta_append(bb, INSTR_CREATE_jmp(drcontext,
opnd_create_pc(rn->replacement)));
#endif
instrlist_append(bb, INSTR_XL8(INSTR_CREATE_nop(drcontext), pc));
}
/* event for function replacing */
static dr_emit_flags_t
drwrap_event_bb_app2app(void *drcontext, void *tag, instrlist_t *bb,
bool for_trace, bool translating)
{
instr_t *inst;
app_pc pc, replace;
if (replace_table.entries == 0 && replace_native_table.entries == 0)
return DR_EMIT_DEFAULT;
/* XXX: if we had dr_bbs_cross_ctis() query (i#427) we could just check 1st instr */
for (inst = instrlist_first(bb);
inst != NULL;
inst = instr_get_next(inst)) {
/* XXX i#1689: supporting LSB=1 or LSB=0 gets complex. For now we
* assume calls from the client always pass LSB=1 (b/c from
* dr_get_proc_address()), which we store in the table. We assume that
* DR always gives us LSB=0, so we add LSB=1 before table lookups. This
* breaks down if the client passes dr_fragment_app_pc()!
*/
pc = dr_app_pc_as_jump_target(instr_get_isa_mode(inst), instr_get_app_pc(inst));
/* non-native takes precedence */
if (replace_table.entries > 0) {
replace = hashtable_lookup(&replace_table, pc);
if (replace != NULL) {
drwrap_replace_bb(drcontext, bb, inst, pc, replace);
break;
}
}
if (replace_native_table.entries > 0) {
replace_native_t *rn;
hashtable_lock(&replace_native_table);
rn = hashtable_lookup(&replace_native_table, pc);
if (rn != NULL) {
app_pc topush = NULL;
if (!rn->at_entry) {
if (instr_is_call(inst)) {
topush = pc + instr_length(drcontext, inst);
topush = dr_app_pc_as_jump_target(instr_get_isa_mode(inst),
topush);
} else if (!instr_is_ubr(inst)) {
/* usage error? no, we'll trust user knows what they're doing */
}
}
drwrap_replace_native_bb(drcontext, bb, inst, pc, rn, topush);
hashtable_unlock(&replace_native_table);
break;
}
hashtable_unlock(&replace_native_table);
}
}
return DR_EMIT_DEFAULT;
}
app_pc
replace_native_xfer_app_retaddr(void)
{
/* Return the app retaddr stored by drwrap_replace_native_fini().
* Note that we can't just leave it in this slot to add in bb event
* for ret gencode b/c the client ibl xfer will clobber spill slots.
*/
/* XXX: avoid calling dr_get_current_drcontext() 3x! See comment below. */
void *drcontext = dr_get_current_drcontext();
return (app_pc) dr_read_saved_reg(drcontext, DRWRAP_REPLACE_NATIVE_SP_SLOT);
}
uint
replace_native_xfer_stack_adjust(void)
{
#ifdef ARM
return 0;
#else
void *drcontext = dr_get_current_drcontext();
return (uint) dr_read_saved_reg(drcontext, SPILL_SLOT_REDIRECT_NATIVE_TGT);
#endif
}
byte *
replace_native_xfer_target(void)
{
/* Retrieve the data stored in the bb and in fini */
void *drcontext = dr_get_current_drcontext();
#ifdef AARCHXX
byte *target = replace_native_ret_stub(0);
#else
uint stack_adjust = (uint)
dr_read_saved_reg(drcontext, SPILL_SLOT_REDIRECT_NATIVE_TGT);
byte *target = replace_native_ret_stub(stack_adjust);
#endif
/* Set up for gencode. We want to re-do the stdcall arg and retaddr teardown,
* but we don't want the app to see it. We can't easily do it in
* replace_native_xfer asm code b/c we don't have enough registers, so
* we have our bb event recognize our gencode and add meta instrs.
*/
/* Set up for ibl xfer */
dr_write_saved_reg(drcontext, SPILL_SLOT_REDIRECT_NATIVE_TGT, (reg_t)target);
/* XXX: should DR export client_ibl_xfer_is_thread_private()? Then we could
* accept NULL drcontext for thread-shared (well we'd be skirting the API by
* passing GLOBAL_DCONTEXT to dr_{read,write}_saved_reg above)
*/
return dr_redirect_native_target(drcontext);
}
DR_EXPORT
void
drwrap_replace_native_fini(void *drcontext)
{
/* We change the retaddr from the original app retaddr (if left
* there, we'd lose control: but we wanted it original for
* callstack walk, etc. transparency) to our own routine that will
* then do a continuation to our gencode which will run in the code
* cache and duplicate the stdcall + retaddr teardown.
*/
volatile app_pc app_retaddr;
byte *xsp = (byte *) dr_read_saved_reg(drcontext, DRWRAP_REPLACE_NATIVE_SP_SLOT);
#ifdef AARCHXX
byte *cur_xsp = get_cur_xsp();
#endif
ASSERT(xsp != NULL, "did client clobber TLS slot?");
#ifdef AARCHXX
app_retaddr = (app_pc) dr_read_saved_reg(drcontext, SPILL_SLOT_REDIRECT_NATIVE_TGT);
#else
app_retaddr = *(app_pc *)xsp;
#endif
/* Store data for replace_native_xfer_helper */
dr_write_saved_reg(drcontext, DRWRAP_REPLACE_NATIVE_SP_SLOT, (reg_t)app_retaddr);
/* Redirect */
#ifdef AARCHXX
/* We assume the replacement routine pushed LR on the stack.
* We need to scan the stack until we find app_retaddr and then overwrite
* that slot.
* XXX: what if there are multiple copies? What if the retaddr is left in
* LR and never pushed on the stack?
*/
for (xsp -= sizeof(app_pc); xsp > cur_xsp && *(app_pc*)xsp != app_retaddr;
xsp -= sizeof(app_pc))
; /* empty body */
/* XXX: what can we do if we hit cur xsp? We'll lose control. */
ASSERT(xsp > cur_xsp, "did not find return address: going to lose control");
*(app_pc *)xsp = (app_pc) replace_native_xfer;
#else
*(app_pc *)xsp = (app_pc) replace_native_xfer;
#endif
/* DrMem i#1217: zero out this local to avoid messing up high-performance
* callstack stack scans.
*/
app_retaddr = 0;
}
/***************************************************************************
* FUNCTION WRAPPING
*/
static void
drwrap_flush_func(app_pc func)
{
/* we can't flush while holding the lock.
* we do not guarantee faster than a lazy flush.
*/
ASSERT(!dr_recurlock_self_owns(wrap_lock), "cannot hold lock while flushing");
if (!dr_unlink_flush_region(func, 1))
ASSERT(false, "wrap update flush failed");
}
#ifdef X86
static app_pc
get_retaddr_at_entry(reg_t xsp)
{
app_pc retaddr = NULL;
if (TEST(DRWRAP_SAFE_READ_RETADDR, global_flags)) {
if (!fast_safe_read((void *)xsp, sizeof(retaddr), &retaddr))
return NULL;
} else
retaddr = *(app_pc*)xsp;
return retaddr;
}
#endif
/* may not return */
static void
drwrap_mark_retaddr_for_instru(void *drcontext, app_pc decorated_pc,
drwrap_context_t *wrapcxt, bool enabled)
{
post_call_entry_t *e;
app_pc retaddr = dr_app_pc_as_load_target(DR_ISA_ARM_THUMB, wrapcxt->retaddr);
/* We will come here again after the flush-redirect.
* FIXME: should we try to flush the call instr itself: don't
* know size though but can be pretty sure.
*/
/* Ensure we have the retaddr instrumented for post-call events */
dr_rwlock_write_lock(post_call_rwlock);
e = (post_call_entry_t *) hashtable_lookup(&post_call_table, (void*)retaddr);
/* PR 454616: we may have added an entry and started a flush
* but not finished the flush, so we check not just the entry
* but also the existing_instrumented flag.
*/
if (e == NULL || !e->existing_instrumented) {
if (e == NULL) {
e = post_call_entry_add(retaddr, false);
}
/* now that we have an entry in the synchronized post_call_table
* any new code coming in will be instrumented
* we assume we only care about fragments starting at retaddr:
* other than traces, nothing should cross it unless there's some
* weird mid-call-instr target in which case it's not post-call.
*
* XXX: if callee is entirely inside a trace we'll miss the post-call!
* will only happen w/ wrapping requests after trace is built.
*/
/* XXX: we're assuming void* tag == pc */
if (dr_fragment_exists_at(drcontext, (void *)retaddr)) {
/* XXX: I'd use dr_unlink_flush_region but it requires -enable_full_api.
* should we dynamically check and use it if we can?
*/
/* unlock for the flush */
dr_rwlock_write_unlock(post_call_rwlock);
if (!enabled) {
/* We have to continue to instrument post-wrap points
* to avoid unbalanced pre vs post hooks, but these flushes
* are expensive so let's get rid of the disabled wraps.
*/
dr_recurlock_lock(wrap_lock);
disabled_count = DISABLED_COUNT_FLUSH_THRESHOLD + 1;
dr_recurlock_unlock(wrap_lock);
}
/* XXX: have a STATS mechanism to count flushes and add call
* site analysis if too many flushes.
*/
dr_flush_region(retaddr, 1);
/* now we are guaranteed no thread is inside the fragment */
/* another thread may have done a racy competing flush: should be fine */
dr_rwlock_read_lock(post_call_rwlock);
e = (post_call_entry_t *)
hashtable_lookup(&post_call_table, (void*)retaddr);
if (e != NULL) /* selfmod could disappear once have PR 408529 */
e->existing_instrumented = true;
/* XXX DrMem i#553: if e==NULL, recursion count could get off */
dr_rwlock_read_unlock(post_call_rwlock);
/* Since the flush may remove the fragment we're already in,
* we have to redirect execution to the callee again.
*/
/* ensure we have DR_MC_ALL */
drwrap_get_mcontext_internal((void*)wrapcxt, DR_MC_ALL);
wrapcxt->mc->pc = decorated_pc;
dr_redirect_execution(wrapcxt->mc);
ASSERT(false, "dr_redirect_execution should not return");
}
e->existing_instrumented = true;
}
dr_rwlock_write_unlock(post_call_rwlock);
}
/* For querying with a pc that has been normalized by throwing out LSB=1 (i#1689).
* Caller must hold wrap_table lock.
*/
static wrap_entry_t *
wrap_table_lookup_normalized_pc(app_pc pc)
{
wrap_entry_t *wrap = hashtable_lookup(&wrap_table, (void *)pc);
#ifdef ARM
if (wrap == NULL && !TEST(0x1, (ptr_uint_t)pc)) {
wrap = hashtable_lookup(&wrap_table, (void *)
dr_app_pc_as_jump_target(DR_ISA_ARM_THUMB, pc));
}
#endif
return wrap;
}
/* assumes that if TEST(DRWRAP_NO_FRILLS, global_flags) then
* wrap_lock is held
*/
static inline void
drwrap_ensure_postcall(void *drcontext, wrap_entry_t *wrap,
drwrap_context_t *wrapcxt, app_pc decorated_pc)
{
app_pc retaddr = dr_app_pc_as_load_target(DR_ISA_ARM_THUMB, wrapcxt->retaddr);
app_pc plain_pc = dr_app_pc_as_load_target(DR_ISA_ARM_THUMB, decorated_pc);
int i;
/* avoid lock and hashtable lookup by caching prior retaddrs */
for (i = 0; i < POSTCALL_CACHE_SIZE; i++) {
if (retaddr == postcall_cache[i])
return;
}
/* to write to the cache we need a write lock */
dr_rwlock_write_lock(post_call_rwlock);
/* add to FIFO cache */
postcall_cache_idx++;
if (postcall_cache_idx >= POSTCALL_CACHE_SIZE)
postcall_cache_idx = 0;
postcall_cache[postcall_cache_idx] = retaddr;
if (hashtable_lookup(&post_call_table, (void*)retaddr) == NULL) {
bool enabled = wrap->enabled;
/* this function may not return: but in that case it will redirect
* and we'll come back here to do the wrapping.
* release all locks.
*/
dr_rwlock_write_unlock(post_call_rwlock);
if (!TEST(DRWRAP_NO_FRILLS, global_flags))
dr_recurlock_unlock(wrap_lock);
drwrap_mark_retaddr_for_instru(drcontext, decorated_pc, wrapcxt, enabled);
/* if we come back, re-lookup */
if (!TEST(DRWRAP_NO_FRILLS, global_flags))
dr_recurlock_lock(wrap_lock);
wrap = wrap_table_lookup_normalized_pc(plain_pc);
} else
dr_rwlock_write_unlock(post_call_rwlock);
}
/* called via clean call at the top of callee */
static void
drwrap_in_callee(void *arg1, reg_t xsp _IF_NOT_X86(reg_t lr))
{
void *drcontext = dr_get_current_drcontext();
per_thread_t *pt = (per_thread_t *) drmgr_get_tls_field(drcontext, tls_idx);
wrap_entry_t *wrap = NULL, *e;
dr_mcontext_t mc;
uint idx;
drwrap_context_t wrapcxt;
app_pc pc, decorated_pc;
/* Do we care about the post wrapper? If not we can save a lot (b/c our
* call site method causes a lot of instrumentation when there's high fan-in)
*/
bool intercept_post = false;
mc.size = sizeof(mc);
/* we use a passed-in xsp to avoid dr_get_mcontext */
mc.xsp = xsp;
#ifdef AARCHXX
/* ditto */
mc.lr = lr;
#endif
mc.flags = 0; /* if anything else is asked for, lazily initialize */
ASSERT(arg1 != NULL, "drwrap_in_callee: arg1 is NULL!");
ASSERT(pt != NULL, "drwrap_in_callee: pt is NULL!");
if (TEST(DRWRAP_NO_FRILLS, global_flags)) {
wrap = (wrap_entry_t *) arg1;
pc = wrap->func;
} else
pc = (app_pc) arg1;
NOTIFY(2, "%s: level %d function "PFX"\n", __FUNCTION__, pt->wrap_level+1, pc);
drwrap_context_init(drcontext, &wrapcxt, pc, &mc, DRWRAP_WHERE_PRE_FUNC,
IF_X86_ELSE(get_retaddr_at_entry(xsp), (app_pc)lr));
drwrap_in_callee_check_unwind(drcontext, pt, &mc);
if (!TEST(DRWRAP_NO_FRILLS, global_flags)) {
dr_recurlock_lock(wrap_lock);
wrap = hashtable_lookup(&wrap_table, (void *)pc);
ASSERT(wrap != NULL, "failed to find wrap info");
}
/* i#1689: after setting wrapcxt.func for caller, clear LSB */
decorated_pc = pc;
pc = dr_app_pc_as_load_target(DR_ISA_ARM_THUMB, pc);
/* ensure we have post-call instru */
if (wrap != NULL) {
for (e = wrap; e != NULL; e = e->next) {
if (e->enabled && e->post_cb != NULL) {
intercept_post = true;
break; /* we do need a post-call hook */
}
}
if (intercept_post && wrapcxt.retaddr != NULL)
drwrap_ensure_postcall(drcontext, wrap, &wrapcxt, decorated_pc);
}
pt->wrap_level++;
ASSERT(pt->wrap_level >= 0, "wrapping level corrupted");
ASSERT(pt->wrap_level < MAX_WRAP_NESTING, "max wrapped nesting reached");
if (pt->wrap_level >= MAX_WRAP_NESTING) {
if (!TEST(DRWRAP_NO_FRILLS, global_flags))
dr_recurlock_unlock(wrap_lock);
wrapcxt.where_am_i = DRWRAP_WHERE_OUTSIDE_CALLBACK;
return; /* we'll have to skip stuff */
}
pt->last_wrap_func[pt->wrap_level] = decorated_pc;
if (TEST(DRWRAP_NO_FRILLS, global_flags))
pt->last_wrap_entry[pt->wrap_level] = wrap;
pt->app_esp[pt->wrap_level] = mc.xsp;
#ifdef DEBUG
for (idx = 0; idx < (uint) pt->wrap_level; idx++) {
/* note that this should no longer fire at all b/c of the check above but
* leaving as a sanity check
*/
ASSERT(pt->app_esp[idx] >= pt->app_esp[pt->wrap_level],
"stack pointer off: may miss post-wrap points");
}
#endif
if (TEST(DRWRAP_NO_FRILLS, global_flags)) {
if (!wrap->enabled) {
dr_recurlock_lock(wrap_lock);
disabled_count++;
dr_recurlock_unlock(wrap_lock);
} else if (wrap->pre_cb != NULL) {
pt->user_data_nofrills[pt->wrap_level] = wrap->user_data;
wrapcxt.callconv = wrap->callconv;
(*wrap->pre_cb)(&wrapcxt, &pt->user_data_nofrills[pt->wrap_level]);
}
} else {
/* because the list could change between pre and post events we count
* and store here instead of maintaining count in wrap_table
*/
for (idx = 0, e = wrap; e != NULL; idx++, e = e->next)
; /* nothing */
/* if we skipped the postcall we didn't free prior data yet */
drwrap_free_user_data(drcontext, pt, pt->wrap_level);
pt->user_data_count[pt->wrap_level] = idx;
pt->user_data[pt->wrap_level] = dr_thread_alloc(drcontext, sizeof(void*)*idx);
/* we have to keep both b/c we allow one to be null (i#562) */
pt->user_data_pre_cb[pt->wrap_level] =
dr_thread_alloc(drcontext, sizeof(void*)*idx);
pt->user_data_post_cb[pt->wrap_level] =
dr_thread_alloc(drcontext, sizeof(void*)*idx);
for (idx = 0; wrap != NULL; idx++, wrap = wrap->next) {
/* if the list does change try to match up in post */
pt->user_data_pre_cb[pt->wrap_level][idx] = (void *) wrap->pre_cb;
pt->user_data_post_cb[pt->wrap_level][idx] = (void *) wrap->post_cb;
if (!wrap->enabled) {
disabled_count++;
continue;
}
if (wrap->pre_cb != NULL) {
pt->user_data[pt->wrap_level][idx] = wrap->user_data;
wrapcxt.callconv = wrap->callconv;
(*wrap->pre_cb)(&wrapcxt, &pt->user_data[pt->wrap_level][idx]);
}
/* was there a request to skip? */
if (pt->skip[pt->wrap_level])
break;
}
dr_recurlock_unlock(wrap_lock);
}
if (pt->skip[pt->wrap_level]) {
/* drwrap_skip_call already adjusted the stack and pc */
/* ensure we have DR_MC_ALL */
dr_redirect_execution(drwrap_get_mcontext_internal((void*)&wrapcxt, DR_MC_ALL));
ASSERT(false, "dr_redirect_execution should not return");
}
if (wrapcxt.mc_modified)
dr_set_mcontext(drcontext, wrapcxt.mc);
if (!intercept_post) {
/* we won't decrement in post so decrement now. we needed to increment
* to set up for pt->skip, etc.
*/
if (!TEST(DRWRAP_NO_FRILLS, global_flags))
drwrap_free_user_data(drcontext, pt, pt->wrap_level);
pt->wrap_level--;
}
wrapcxt.where_am_i = DRWRAP_WHERE_OUTSIDE_CALLBACK;
}
/* called via clean call at return address(es) of callee
* if retaddr is NULL then this is a "fake" cleanup on abnormal stack unwind
*/
static void
drwrap_after_callee_func(void *drcontext, per_thread_t *pt, dr_mcontext_t *mc,
int level, app_pc retaddr,
bool unwind, bool only_requested_unwind)
{
wrap_entry_t *wrap, *next;
uint idx;
drwrap_context_t wrapcxt;
drvector_t toflush = {0,};
bool do_flush = false;
bool unwound_all = true;
app_pc pc = pt->last_wrap_func[level];
ASSERT(pc != NULL, "drwrap_after_callee: pc is NULL!");
ASSERT(pt != NULL, "drwrap_after_callee: pt is NULL!");
ASSERT(!only_requested_unwind || unwind, "only_requested_unwind implies unwind");
NOTIFY(2, "%s: level %d function "PFX"%s\n", __FUNCTION__, level, pc,
unwind ? " abnormal" : "");
drwrap_context_init(drcontext, &wrapcxt, pc, mc, DRWRAP_WHERE_POST_FUNC, retaddr);
if (level >= MAX_WRAP_NESTING) {
if (level == pt->wrap_level)
pt->wrap_level--;
return; /* we skipped the wrap */
}
if (pt->skip[level]) {
pt->skip[level] = false;
if (level == pt->wrap_level)
pt->wrap_level--;
else {
/* doing an SEH unwind and didn't clear earlier on stack */
pt->last_wrap_func[level] = NULL;
}
return; /* skip the post-func cbs */
}
if (TEST(DRWRAP_NO_FRILLS, global_flags)) {
wrap = pt->last_wrap_entry[level];
} else {
dr_recurlock_lock(wrap_lock);
wrap = wrap_table_lookup_normalized_pc(pc);
}
for (idx = 0; wrap != NULL; idx++, wrap = next) {
/* handle the list changing between pre and post events */
uint tmp = idx;
void *user_data = NULL;
/* handle drwrap_unwrap being called in post_cb */
next = wrap->next;
if (!wrap->enabled) {
if (TEST(DRWRAP_NO_FRILLS, global_flags))
dr_recurlock_lock(wrap_lock);
disabled_count++;
if (TEST(DRWRAP_NO_FRILLS, global_flags))
dr_recurlock_unlock(wrap_lock);
continue;
}
if (TEST(DRWRAP_NO_FRILLS, global_flags)) {
user_data = pt->user_data_nofrills[level];
} else {
/* we may have to skip some entries */
for (; idx < pt->user_data_count[level]; idx++) {
/* we have to check both b/c we allow one to be null (i#562) */
if (wrap->pre_cb == pt->user_data_pre_cb[level][idx] &&
wrap->post_cb == pt->user_data_post_cb[level][idx])
break; /* all set */
}
user_data = pt->user_data[level][idx];
}
if (!TEST(DRWRAP_NO_FRILLS, global_flags) &&
idx == pt->user_data_count[level]) {
/* we didn't find it, it must be new, so had no pre => skip post
* (even if only has post, to be consistent w/ timing)
*/
idx = tmp; /* reset */
} else if (wrap->post_cb != NULL) {
if (!unwind) {
wrapcxt.callconv = wrap->callconv;
(*wrap->post_cb)(&wrapcxt, user_data);
} else if (!only_requested_unwind ||
TEST(DRWRAP_UNWIND_ON_EXCEPTION, wrap->flags)) {
/* don't double-call those that we presumably already called
* that had the flag set. there might have been a longjmp and no
* exception (e.g., any longjmp on linux): but that's too bad:
* current impl doesn't handle that.
*/
if (only_requested_unwind ||
!TEST(DRWRAP_UNWIND_ON_EXCEPTION, wrap->flags)) {
(*wrap->post_cb)(NULL, user_data);
}
} else
unwound_all = false;
/* note that at this point wrap might be deleted */
}
}
if (disabled_count > DISABLED_COUNT_FLUSH_THRESHOLD) {
/* Lazy removal and flushing. To be non-lazy requires storing
* info inside unwrap and/or limiting when unwrap can be called.
* Lazy also means a wrap reversing an unwrap doesn't cost anything.
* More importantly, flushes are expensive, so we batch them up here.
* We can't flush while holding the lock so we use a local vector.
*/
uint i;
drvector_init(&toflush, 10, false/*no synch: wrapcxt-local*/, NULL);
if (TEST(DRWRAP_NO_FRILLS, global_flags))
dr_recurlock_lock(wrap_lock);
for (i = 0; i < HASHTABLE_SIZE(wrap_table.table_bits); i++) {
hash_entry_t *he, *next_he;
for (he = wrap_table.table[i]; he != NULL; he = next_he) {
wrap_entry_t *prev = NULL, *next;
next_he = he->next; /* allow removal */
for (wrap = (wrap_entry_t *) he->payload; wrap != NULL; wrap = next) {
next = wrap->next;
if (!wrap->enabled) {
if (prev == NULL) {
if (next == NULL) {
/* No wrappings left for this function so
* let's flush it
*/
drvector_append(&toflush, (void *)wrap->func);
hashtable_remove(&wrap_table, (void *)wrap->func);
wrap = NULL; /* don't double-free */
} else {
hashtable_add_replace(&wrap_table, (void *)wrap->func,
(void *)next);
}
} else
prev->next = next;
if (wrap != NULL) {
dr_global_free(wrap, sizeof(*wrap));
}
} else
prev = wrap;
}
}
}
do_flush = true;
disabled_count = 0;
if (TEST(DRWRAP_NO_FRILLS, global_flags))
dr_recurlock_unlock(wrap_lock);
}
if (!TEST(DRWRAP_NO_FRILLS, global_flags))
dr_recurlock_unlock(wrap_lock);
if (wrapcxt.mc_modified && !unwind)
dr_set_mcontext(drcontext, wrapcxt.mc);
if (do_flush) {
/* handle delayed flushes while holding no lock
* XXX: optimization: combine nearby addresses to reduce # flushes
*/
uint i;
for (i = 0; i < toflush.entries; i++)
drwrap_flush_func((app_pc)toflush.array[i]);
drvector_delete(&toflush);
}
if (unwound_all) {
if (!TEST(DRWRAP_NO_FRILLS, global_flags))
drwrap_free_user_data(drcontext, pt, level);
if (level == pt->wrap_level) {
ASSERT(pt->wrap_level >= 0, "internal wrapping error");
pt->wrap_level--;
} else {
/* doing an SEH unwind and didn't clear earlier on stack */
pt->last_wrap_func[level] = NULL;
}
} /* else, hopefully our unwind detection heuristics will */
if (wrapcxt.is_redirect_requested) {
NOTIFY(2, "%s: redirecting to "PFX"; stack at "PFX"\n", __FUNCTION__, mc->pc,
mc->xsp);
drwrap_get_mcontext_internal((void*) &wrapcxt, DR_MC_ALL);
wrapcxt.is_redirect_requested = false;
dr_redirect_execution(mc);
ASSERT(false, "reached code following a redirect");
}
wrapcxt.where_am_i = DRWRAP_WHERE_OUTSIDE_CALLBACK;
}
/* called via clean call at return address(es) of callee */
static void
drwrap_after_callee(app_pc retaddr, reg_t xsp)
{
void *drcontext = dr_get_current_drcontext();
per_thread_t *pt = (per_thread_t *) drmgr_get_tls_field(drcontext, tls_idx);
dr_mcontext_t mc;
mc.size = sizeof(mc);
/* we use a passed-in xsp to avoid dr_get_mcontext */
mc.xsp = xsp;
mc.flags = 0; /* if anything else is asked for, lazily initialize */
ASSERT(pt != NULL, "drwrap_after_callee: pt is NULL!");
if (pt->wrap_level < 0) {
/* jump or other method of targeting post-call site w/o executing
* call; or, did an indirect call that no longer matches */
return;
}
/* process post for all funcs whose frames we bypassed.
* we assume they were all bypassed b/c of tailcalls and that their
* posts should be called (on an exception we clear out our data
* and won't come here; for longjmp we assume we want to call the post
* although the retval won't be there...XXX).
*
* we no longer store the callee for a post-call site b/c there
* can be multiple and it's complex to control which one is used
* (outer or inner or middle) consistently. we don't need the
* callee to distinguish a jump or other transfer to a post-call
* site where the transfer happens inside a wrapped routine (passing
* the wrap_level==0 check above) b/c our stack
* check will identify whether we've left any wrapped routines we
* entered.
*/
/* XXX: I'm worried about the <= here. We need it for ARM b/c w/ no retaddr on
* the stack it's easy to have the same sp value, but I'm being conservative
* and leaving the < for x86.
*/
while (pt->wrap_level >= 0 && pt->app_esp[pt->wrap_level] IF_X86_ELSE(<,<=) mc.xsp) {
drwrap_after_callee_func(drcontext, pt, &mc, pt->wrap_level,
retaddr, false, false);
}
}
static dr_emit_flags_t
drwrap_event_bb_analysis(void *drcontext, void *tag, instrlist_t *bb,
bool for_trace, bool translating, OUT void **user_data)
{
/* nothing to do */
return DR_EMIT_DEFAULT;
}
static dr_emit_flags_t
drwrap_event_bb_insert(void *drcontext, void *tag, instrlist_t *bb, instr_t *inst,
bool for_trace, bool translating, void *user_data)
{
/* XXX: if we had dr_bbs_cross_ctis() query (i#427) we could just check 1st instr */
wrap_entry_t *wrap;
/* i#1689: we store in drwrap_table as the original from the client (which
* may have LSB=1), as well as in wrapcxt. We then clear LSB for all other
* uses, including all postcall uses.
*/
app_pc pc = dr_app_pc_as_jump_target(instr_get_isa_mode(inst),
instr_get_app_pc(inst));
/* Strategy: we don't bother to look at call sites; we wait for the callee
* and flush, under the assumption that we won't have already seen the
* return point and so won't have to incur the cost of a flush very often
*/
dr_recurlock_lock(wrap_lock);
wrap = hashtable_lookup(&wrap_table, (void *)pc);
if (wrap != NULL) {
void *arg1 = TEST(DRWRAP_NO_FRILLS, global_flags) ? (void *)wrap : (void *) pc;
/* i#690: do not bother saving registers that should be scratch at
* function entry, if requested by user.
* I considered building a custom context switch but that would require
* having DR expose PEB/TEB swapping code and duplicating
* stack alignment code; plus, skipping preservation was already
* mostly in place for clean call auto opt.
*/
dr_cleancall_save_t flags = TEST(DRWRAP_FAST_CLEANCALLS, global_flags) ?
(DR_CLEANCALL_NOSAVE_FLAGS|DR_CLEANCALL_NOSAVE_XMM_NONPARAM) : 0;
dr_insert_clean_call_ex(drcontext, bb, inst, (void *)drwrap_in_callee,
flags, IF_X86_ELSE(2, 3),
OPND_CREATE_INTPTR((ptr_int_t)arg1),
/* pass in xsp to avoid dr_get_mcontext */
opnd_create_reg(DR_REG_XSP)
_IF_NOT_X86(opnd_create_reg(DR_REG_LR)));
}
dr_recurlock_unlock(wrap_lock);
if (post_call_lookup_for_instru(instr_get_app_pc(inst)/*normalized*/)) {
/* XXX: for DRWRAP_FAST_CLEANCALLS we must preserve state b/c
* our post-call points can be reached through non-return paths.
* We could insert an inline check for "pt->wrap_level >= 0" but
* that requires spilling a GPR and flags and gets messy w/o drreg
* vs other components' spill slots.
*/
dr_cleancall_save_t flags = 0;
dr_insert_clean_call_ex(drcontext, bb, inst, (void *)drwrap_after_callee,
flags, 2,
/* i#1689: retaddrs do have LSB=1 */
OPND_CREATE_INTPTR((ptr_int_t)pc),
/* pass in xsp to avoid dr_get_mcontext */
opnd_create_reg(DR_REG_XSP));
}
return DR_EMIT_DEFAULT;
}
static void
drwrap_event_module_unload(void *drcontext, const module_data_t *info)
{
/* XXX: should also remove from post_call_table and call_site_table
* on other code modifications: for now we assume no such
* changes to app code that's being targeted for wrapping.
*/
hashtable_remove_range(&call_site_table, (void *)info->start, (void *)info->end);
dr_rwlock_write_lock(post_call_rwlock);
hashtable_remove_range(&post_call_table, (void *)info->start, (void *)info->end);
dr_rwlock_write_unlock(post_call_rwlock);
}
static void
drwrap_fragment_delete(void *dc/*may be NULL*/, void *tag)
{
/* switched to checking consistency at lookup time (DrMemi#673) */
}
DR_EXPORT
bool
drwrap_wrap_ex(app_pc func,
void (*pre_func_cb)(void *wrapcxt, INOUT void **user_data),
void (*post_func_cb)(void *wrapcxt, void *user_data),
void *user_data, uint flags)
{
wrap_entry_t *wrap_cur, *wrap_new;
/* allow one side to be NULL (i#562) */
if (func == NULL || (pre_func_cb == NULL && post_func_cb == NULL))
return false;
/* XXX i#1460: should drwrap auto-flush target in case called late?
* Currently we document that the caller must do that.
*/
wrap_new = dr_global_alloc(sizeof(*wrap_new));
wrap_new->func = func;
wrap_new->pre_cb = pre_func_cb;
wrap_new->post_cb = post_func_cb;
wrap_new->enabled = true;
wrap_new->user_data = user_data;
wrap_new->flags = EXCLUDE_CALLCONV(flags);
wrap_new->callconv = EXTRACT_CALLCONV(flags);
if (wrap_new->callconv == 0)
wrap_new->callconv = DRWRAP_CALLCONV_DEFAULT;
dr_recurlock_lock(wrap_lock);
wrap_cur = hashtable_lookup(&wrap_table, (void *)func);
if (wrap_cur != NULL) {
/* we add in reverse order (documented in interface) */
wrap_entry_t *e;
/* things will break down w/ duplicate cbs */
for (e = wrap_cur; e != NULL; e = e->next) {
if (e->pre_cb == pre_func_cb && e->post_cb == post_func_cb) {
/* no-frills requires 1st entry to be the live one */
if (!TEST(DRWRAP_NO_FRILLS, global_flags) || e == wrap_cur) {
/* matches existing request: re-enable if necessary */
e->enabled = true;
/* be sure to update all fields (xref drmem i#816) */
e->user_data = user_data;
e->flags = flags;
dr_global_free(wrap_new, sizeof(*wrap_new));
dr_recurlock_unlock(wrap_lock);
return true;
} /* else continue */
} else if (TEST(DRWRAP_NO_FRILLS, global_flags) && e->enabled) {
/* more than one wrap of same address is not allowed */
dr_global_free(wrap_new, sizeof(*wrap_new));
dr_recurlock_unlock(wrap_lock);
return false;
}
}
if (TEST(DRWRAP_NO_FRILLS, global_flags)) {
/* free whole chain of disabled entries */
wrap_entry_free(wrap_cur);
wrap_cur = NULL;
}
wrap_new->next = wrap_cur;
hashtable_add_replace(&wrap_table, (void *)func, (void *)wrap_new);
} else {
wrap_new->next = NULL;
hashtable_add(&wrap_table, (void *)func, (void *)wrap_new);
/* XXX: we're assuming void* tag == pc */
if (dr_fragment_exists_at(dr_get_current_drcontext(), func)) {
/* we do not guarantee faster than a lazy flush */
if (!dr_unlink_flush_region(func, 1))
ASSERT(false, "wrap update flush failed");
}
}
dr_recurlock_unlock(wrap_lock);
return true;
}
DR_EXPORT
bool
drwrap_wrap(app_pc func,
void (*pre_func_cb)(void *wrapcxt, OUT void **user_data),
void (*post_func_cb)(void *wrapcxt, void *user_data))
{
return drwrap_wrap_ex(func, pre_func_cb, post_func_cb, NULL, DRWRAP_CALLCONV_DEFAULT);
}
DR_EXPORT
bool
drwrap_unwrap(app_pc func,
void (*pre_func_cb)(void *wrapcxt, OUT void **user_data),
void (*post_func_cb)(void *wrapcxt, void *user_data))
{
wrap_entry_t *wrap;
bool res = false;
if (func == NULL ||
(pre_func_cb == NULL && post_func_cb == NULL))
return false;
dr_recurlock_lock(wrap_lock);
wrap = hashtable_lookup(&wrap_table, (void *)func);
for (; wrap != NULL; wrap = wrap->next) {
if (wrap->pre_cb == pre_func_cb &&
wrap->post_cb == post_func_cb) {
/* We use lazy removal and flushing to avoid complications of
* removing and flushing from a post-wrap callback (it's currently
* iterating, and it holds a lock).
*/
wrap->enabled = false;
res = true;
break;
}
}
dr_recurlock_unlock(wrap_lock);
return res;
}
DR_EXPORT
bool
drwrap_is_wrapped(app_pc func,
void (*pre_func_cb)(void *wrapcxt, OUT void **user_data),
void (*post_func_cb)(void *wrapcxt, void *user_data))
{
wrap_entry_t *wrap;
bool res = false;
if (func == NULL ||
(pre_func_cb == NULL && post_func_cb == NULL))
return false;
dr_recurlock_lock(wrap_lock);
wrap = hashtable_lookup(&wrap_table, (void *)func);
for (; wrap != NULL; wrap = wrap->next) {
if (wrap->enabled && wrap->pre_cb == pre_func_cb &&
wrap->post_cb == post_func_cb) {
res = true;
break;
}
}
dr_recurlock_unlock(wrap_lock);
return res;
}
DR_EXPORT
bool
drwrap_is_post_wrap(app_pc pc)
{
bool res = false;
if (pc == NULL)
return false;
dr_rwlock_read_lock(post_call_rwlock);
res = (hashtable_lookup(&post_call_table, (void*)pc) != NULL);
dr_rwlock_read_unlock(post_call_rwlock);
return res;
}
/***************************************************************************
* Several different approaches to try and handle SEH/longjmp unwind
*/
static inline void
drwrap_in_callee_check_unwind(void *drcontext, per_thread_t *pt, dr_mcontext_t *mc)
{
/* Try to handle an SEH unwind or longjmp that unrolled the stack.
* The stack may have been extended again since then, and we don't know
* the high-water point: so even if we're currently further down the
* stack than any recorded prior call, we verify all entries if we
* had an exception.
* XXX: should we verify all the time, to handle any longjmp?
* But our retaddr check is not bulletproof and might have issues
* in both directions (though we don't really support wrapping
* functions that change their retaddrs: still, it's not sufficient
* due to stale values).
*/
if (pt->wrap_level >= 0 && pt->app_esp[pt->wrap_level] < mc->xsp
IF_WINDOWS(|| pt->hit_exception)) {
NOTIFY(1, "%s: checking for bypass @ xsp="PFX"\n", __FUNCTION__, mc->xsp);
while (pt->wrap_level >= 0 &&
(pt->app_esp[pt->wrap_level] < mc->xsp
/* if we hit an exception, look for same xsp, b/c longjmp
* or handler may be at same level as aborted callee.
* we thus give up on correctly handling
* an exception in a tailcall sequence: but that's really
* hard anyway.
*/
IF_WINDOWS(|| (pt->hit_exception &&
pt->app_esp[pt->wrap_level] <= mc->xsp)))) {
drwrap_after_callee_func(drcontext, pt, mc, pt->wrap_level, NULL, true,
false);
}
#ifdef X86
/* Try to clean up entries we unrolled past and then came back
* down past in the other direction. Note that there's a
* decent chance retaddrs weren't clobbered though so this is
* not guaranteed.
*/
while (pt->wrap_level >= 0) {
app_pc ret;
if (TEST(DRWRAP_SAFE_READ_RETADDR, global_flags)) {
if (!fast_safe_read((void *)pt->app_esp[pt->wrap_level],
sizeof(ret), &ret))
ret = NULL;
} else
ret = *(app_pc*)pt->app_esp[pt->wrap_level];
if ((pt->wrap_level > 0 && ret == pt->last_wrap_func[pt->wrap_level - 1]) ||
post_call_lookup(ret))
break;
NOTIFY(2, "%s: found clobbered retaddr "PFX"\n", __FUNCTION__, ret);
drwrap_after_callee_func(drcontext, pt, mc, pt->wrap_level, NULL, true,
false);
}
#else
/* XXX i#1673: NYI for ARM */
#endif
IF_WINDOWS(pt->hit_exception = false;)
}
}
#ifdef WINDOWS
static bool
drwrap_event_filter_syscall(void *drcontext, int sysnum)
{
return sysnum == sysnum_NtContinue;
}
static bool
drwrap_event_pre_syscall(void *drcontext, int sysnum)
{
if (sysnum == sysnum_NtContinue) {
/* XXX: we assume the syscall will succeed */
per_thread_t *pt = (per_thread_t *) drmgr_get_tls_field(drcontext, tls_idx);
if (pt->wrap_level >= 0) {
CONTEXT *cxt = (CONTEXT *) dr_syscall_get_param(drcontext, 0);
reg_t tgt_xsp = (reg_t) cxt->IF_X64_ELSE(Rsp,Esp);
dr_mcontext_t mc;
mc.size = sizeof(mc);
mc.flags = DR_MC_CONTROL | DR_MC_INTEGER;
dr_get_mcontext(drcontext, &mc);
ASSERT(pt != NULL, "pt is NULL in pre-syscall");
/* Call post-call for every one we're skipping in our target, but
* pass NULL for wrapcxt to indicate this is not a normal post-call
*/
NOTIFY(1, "%s: unwinding those we'll bypass @ target xsp="PFX"\n",
__FUNCTION__, tgt_xsp);
while (pt->wrap_level >= 0 && pt->app_esp[pt->wrap_level] < tgt_xsp) {
NOTIFY(2, "%s: level %d\n", __FUNCTION__, pt->wrap_level);
drwrap_after_callee_func(drcontext, pt, &mc, pt->wrap_level, NULL,
true, false);
}
}
}
return true;
}
bool
drwrap_event_exception(void *drcontext, dr_exception_t *excpt)
{
per_thread_t *pt = (per_thread_t *) drmgr_get_tls_field(drcontext, tls_idx);
/* pt can be NULL for a crash at process init before any thread init (i#1219) */
if (pt != NULL && pt->wrap_level >= 0) {
int idx;
/* record whether we should check all the levels in the next hook
* if using heuristics
*/
pt->hit_exception = true;
/* forcibly unwind those that requested it */
NOTIFY(1, "%s: notifying those who requested\n", __FUNCTION__);
/* might not decrement pt->wrap_level so we use a for loop */
for (idx = pt->wrap_level; idx >= 0; idx--) {
NOTIFY(2, "%s: level %d\n", __FUNCTION__, idx);
drwrap_after_callee_func(drcontext, pt, excpt->mcontext, idx,
NULL, true, true);
}
}
return true;
}
#endif
| 1 | 13,538 | Check the return value of the drmgr ones. | DynamoRIO-dynamorio | c |
@@ -345,7 +345,10 @@ class FileUpload extends FormWidgetBase
protected function loadAssets()
{
$this->addCss('css/fileupload.css', 'core');
- $this->addJs('js/fileupload.js', 'core');
+ $this->addJs('js/fileupload.js', [
+ 'build' => 'core',
+ 'data-cfasync' => 'false'
+ ]);
}
/** | 1 | <?php namespace Backend\FormWidgets;
use Input;
use Request;
use Response;
use Validator;
use Backend\Classes\FormField;
use Backend\Classes\FormWidgetBase;
use Backend\Controllers\Files as FilesController;
use October\Rain\Filesystem\Definitions as FileDefinitions;
use ApplicationException;
use ValidationException;
use Exception;
/**
* File upload field
* Renders a form file uploader field.
*
* Supported options:
* - mode: image-single, image-multi, file-single, file-multi
* - upload-label: Add file
* - empty-label: No file uploaded
*
* @package october\backend
* @author Alexey Bobkov, Samuel Georges
*/
class FileUpload extends FormWidgetBase
{
use \Backend\Traits\FormModelWidget;
//
// Configurable properties
//
/**
* @var string Prompt text to display for the upload button.
*/
public $prompt;
/**
* @var int Preview image width
*/
public $imageWidth;
/**
* @var int Preview image height
*/
public $imageHeight;
/**
* @var mixed Collection of acceptable file types.
*/
public $fileTypes = false;
/**
* @var mixed Collection of acceptable mime types.
*/
public $mimeTypes = false;
/**
* @var array Options used for generating thumbnails.
*/
public $thumbOptions = [
'mode' => 'crop',
'extension' => 'auto'
];
/**
* @var boolean Allow the user to set a caption.
*/
public $useCaption = true;
/**
* @var boolean Automatically attaches the uploaded file on upload if the parent record exists instead of using deferred binding to attach on save of the parent record. Defaults to false.
*/
public $attachOnUpload = false;
//
// Object properties
//
/**
* @inheritDoc
*/
protected $defaultAlias = 'fileupload';
/**
* @inheritDoc
*/
public function init()
{
$this->fillFromConfig([
'prompt',
'imageWidth',
'imageHeight',
'fileTypes',
'mimeTypes',
'thumbOptions',
'useCaption',
'attachOnUpload',
]);
if ($this->formField->disabled) {
$this->previewMode = true;
}
$this->checkUploadPostback();
}
/**
* @inheritDoc
*/
public function render()
{
$this->prepareVars();
return $this->makePartial('fileupload');
}
/**
* Prepares the view data
*/
protected function prepareVars()
{
if ($this->formField->disabled) {
$this->previewMode = true;
}
if ($this->previewMode) {
$this->useCaption = false;
}
$this->vars['fileList'] = $fileList = $this->getFileList();
$this->vars['singleFile'] = $fileList->first();
$this->vars['displayMode'] = $this->getDisplayMode();
$this->vars['emptyIcon'] = $this->getConfig('emptyIcon', 'icon-upload');
$this->vars['imageHeight'] = $this->imageHeight;
$this->vars['imageWidth'] = $this->imageWidth;
$this->vars['acceptedFileTypes'] = $this->getAcceptedFileTypes(true);
$this->vars['cssDimensions'] = $this->getCssDimensions();
$this->vars['cssBlockDimensions'] = $this->getCssDimensions('block');
$this->vars['useCaption'] = $this->useCaption;
$this->vars['prompt'] = $this->getPromptText();
}
protected function getFileList()
{
$list = $this
->getRelationObject()
->withDeferred($this->sessionKey)
->orderBy('sort_order')
->get()
;
/*
* Decorate each file with thumb and custom download path
*/
$list->each(function ($file) {
$this->decorateFileAttributes($file);
});
return $list;
}
/**
* Returns the display mode for the file upload. Eg: file-multi, image-single, etc.
* @return string
*/
protected function getDisplayMode()
{
$mode = $this->getConfig('mode', 'image');
if (str_contains($mode, '-')) {
return $mode;
}
$relationType = $this->getRelationType();
$mode .= ($relationType == 'attachMany' || $relationType == 'morphMany') ? '-multi' : '-single';
return $mode;
}
/**
* Returns the escaped and translated prompt text to display according to the type.
* @return string
*/
protected function getPromptText()
{
if ($this->prompt === null) {
$isMulti = ends_with($this->getDisplayMode(), 'multi');
$this->prompt = $isMulti
? 'backend::lang.fileupload.upload_file'
: 'backend::lang.fileupload.default_prompt';
}
return str_replace('%s', '<i class="icon-upload"></i>', e(trans($this->prompt)));
}
/**
* Returns the CSS dimensions for the uploaded image,
* uses auto where no dimension is provided.
* @param string $mode
* @return string
*/
protected function getCssDimensions($mode = null)
{
if (!$this->imageWidth && !$this->imageHeight) {
return '';
}
$cssDimensions = '';
if ($mode == 'block') {
$cssDimensions .= $this->imageWidth
? 'width: '.$this->imageWidth.'px;'
: 'width: '.$this->imageHeight.'px;';
$cssDimensions .= ($this->imageHeight)
? 'max-height: '.$this->imageHeight.'px;'
: 'height: auto;';
}
else {
$cssDimensions .= $this->imageWidth
? 'width: '.$this->imageWidth.'px;'
: 'width: auto;';
$cssDimensions .= ($this->imageHeight)
? 'max-height: '.$this->imageHeight.'px;'
: 'height: auto;';
}
return $cssDimensions;
}
/**
* Returns the specified accepted file types, or the default
* based on the mode. Image mode will return:
* - jpg,jpeg,bmp,png,gif,svg
* @return string
*/
public function getAcceptedFileTypes($includeDot = false)
{
$types = $this->fileTypes;
if ($types === false) {
$isImage = starts_with($this->getDisplayMode(), 'image');
$types = implode(',', FileDefinitions::get($isImage ? 'imageExtensions' : 'defaultExtensions'));
}
if (!$types || $types == '*') {
return null;
}
if (!is_array($types)) {
$types = explode(',', $types);
}
$types = array_map(function ($value) use ($includeDot) {
$value = trim($value);
if (substr($value, 0, 1) == '.') {
$value = substr($value, 1);
}
if ($includeDot) {
$value = '.'.$value;
}
return $value;
}, $types);
return implode(',', $types);
}
/**
* Removes a file attachment.
*/
public function onRemoveAttachment()
{
$fileModel = $this->getRelationModel();
if (($fileId = post('file_id')) && ($file = $fileModel::find($fileId))) {
$this->getRelationObject()->remove($file, $this->sessionKey);
}
}
/**
* Sorts file attachments.
*/
public function onSortAttachments()
{
if ($sortData = post('sortOrder')) {
$ids = array_keys($sortData);
$orders = array_values($sortData);
$fileModel = $this->getRelationModel();
$fileModel->setSortableOrder($ids, $orders);
}
}
/**
* Loads the configuration form for an attachment, allowing title and description to be set.
*/
public function onLoadAttachmentConfig()
{
$fileModel = $this->getRelationModel();
if (($fileId = post('file_id')) && ($file = $fileModel::find($fileId))) {
$file = $this->decorateFileAttributes($file);
$this->vars['file'] = $file;
$this->vars['displayMode'] = $this->getDisplayMode();
$this->vars['cssDimensions'] = $this->getCssDimensions();
$this->vars['relationManageId'] = post('manage_id');
$this->vars['relationField'] = post('_relation_field');
return $this->makePartial('config_form');
}
throw new ApplicationException('Unable to find file, it may no longer exist');
}
/**
* Commit the changes of the attachment configuration form.
*/
public function onSaveAttachmentConfig()
{
try {
$fileModel = $this->getRelationModel();
if (($fileId = post('file_id')) && ($file = $fileModel::find($fileId))) {
$file->title = post('title');
$file->description = post('description');
$file->save();
return ['displayName' => $file->title ?: $file->file_name];
}
throw new ApplicationException('Unable to find file, it may no longer exist');
}
catch (Exception $ex) {
return json_encode(['error' => $ex->getMessage()]);
}
}
/**
* @inheritDoc
*/
protected function loadAssets()
{
$this->addCss('css/fileupload.css', 'core');
$this->addJs('js/fileupload.js', 'core');
}
/**
* @inheritDoc
*/
public function getSaveValue($value)
{
return FormField::NO_SAVE_DATA;
}
/**
* Checks the current request to see if it is a postback containing a file upload
* for this particular widget.
*/
protected function checkUploadPostback()
{
if (!($uniqueId = Request::header('X-OCTOBER-FILEUPLOAD')) || $uniqueId != $this->getId()) {
return;
}
try {
if (!Input::hasFile('file_data')) {
throw new ApplicationException('File missing from request');
}
$fileModel = $this->getRelationModel();
$uploadedFile = Input::file('file_data');
$validationRules = ['max:'.$fileModel::getMaxFilesize()];
if ($fileTypes = $this->getAcceptedFileTypes()) {
$validationRules[] = 'extensions:'.$fileTypes;
}
if ($this->mimeTypes) {
$validationRules[] = 'mimes:'.$this->mimeTypes;
}
$validation = Validator::make(
['file_data' => $uploadedFile],
['file_data' => $validationRules]
);
if ($validation->fails()) {
throw new ValidationException($validation);
}
if (!$uploadedFile->isValid()) {
throw new ApplicationException('File is not valid');
}
$fileRelation = $this->getRelationObject();
$file = $fileModel;
$file->data = $uploadedFile;
$file->is_public = $fileRelation->isPublic();
$file->save();
/**
* Attach directly to the parent model if it exists and attachOnUpload has been set to true
* else attach via deferred binding
*/
$parent = $fileRelation->getParent();
if ($this->attachOnUpload && $parent && $parent->exists) {
$fileRelation->add($file);
} else {
$fileRelation->add($file, $this->sessionKey);
}
$file = $this->decorateFileAttributes($file);
$result = [
'id' => $file->id,
'thumb' => $file->thumbUrl,
'path' => $file->pathUrl
];
Response::json($result, 200)->send();
}
catch (Exception $ex) {
Response::json($ex->getMessage(), 400)->send();
}
exit;
}
/**
* Adds the bespoke attributes used internally by this widget.
* - thumbUrl
* - pathUrl
* @return System\Models\File
*/
protected function decorateFileAttributes($file)
{
/*
* File is protected, create a secure public path
*/
if (!$file->isPublic()) {
$path = $thumb = FilesController::getDownloadUrl($file);
if ($this->imageWidth || $this->imageHeight) {
$thumb = FilesController::getThumbUrl($file, $this->imageWidth, $this->imageHeight, $this->thumbOptions);
}
}
/*
* Otherwise use public paths
*/
else {
$path = $thumb = $file->getPath();
if ($this->imageWidth || $this->imageHeight) {
$thumb = $file->getThumb($this->imageWidth, $this->imageHeight, $this->thumbOptions);
}
}
$file->pathUrl = $path;
$file->thumbUrl = $thumb;
return $file;
}
}
| 1 | 14,704 | This should be `'cache'` | octobercms-october | php |
@@ -36,7 +36,7 @@ type RepoWrangler interface {
// GetOldRepo opens and returns the old repo with read-only access
GetOldRepo() (*os.File, error)
// MakeNewRepo creates and returns the new repo dir with read/write permissions
- MakeNewRepo() (*os.File, error)
+ MakeNewRepo() error
// GetOldRepoPath returns the full path of the old repo
GetOldRepoPath() string
// GetNewRepoPath returns the full path of the old repo | 1 | package internal
import (
"os"
)
// Migration is the interface to all repo migration versions.
type Migration interface {
// Migrate performs all migration steps for the Migration that implements the interface.
// Migrate expects newRepo to be:
// a directory
// read/writeable by this process,
// contain a copy of the old repo.
Migrate(newRepoPath string) error
// Describe returns a list of steps, as a formatted string, that a given Migration will take.
// These should correspond to named functions in the given Migration.
Describe() string
// Validate performs validation operations, using oldRepo for comparison.
// Validation requirements will be different for every migration.
// Validate expects newRepo to be
// a directory
// readable by this process
// already migrated
// It expects oldRepo to be
// a directory
// read-only by this process
// A successful validation returns nil.
Validate(oldRepoPath, newRepoPath string) error
}
// RepoWrangler is a helper that manages filesystem operations and figures out what the correct paths
// are for everything.
type RepoWrangler interface {
// GetOldRepo opens and returns the old repo with read-only access
GetOldRepo() (*os.File, error)
// MakeNewRepo creates and returns the new repo dir with read/write permissions
MakeNewRepo() (*os.File, error)
// GetOldRepoPath returns the full path of the old repo
GetOldRepoPath() string
// GetNewRepoPath returns the full path of the old repo
GetNewRepoPath() string
}
type MigrationRunner struct {
verbose bool
command string
helper RepoWrangler
}
func NewMigrationRunner(verb bool, command, oldRepoOpt, newRepoPrefixOpt string) *MigrationRunner {
// TODO: Issue #2585 Implement repo migration version detection and upgrade decisioning
oldVersion := "1"
newVersion := "2"
helper := NewRepoFSWrangler(oldRepoOpt, newRepoPrefixOpt, oldVersion, newVersion)
return &MigrationRunner{
verbose: verb,
command: command,
helper: helper,
}
}
func (m *MigrationRunner) Run() error {
// TODO: Issue #2595 Implement first repo migration
return nil
}
| 1 | 18,862 | The name "old" might cause confusion here. After installation, the "old" repo is at an archived path, and the new migrated repo is at the old path. Maybe something like "target" or "canonical"? | filecoin-project-venus | go |
@@ -1744,6 +1744,7 @@ Collection.prototype.aggregate = function(pipeline, options, callback) {
options = Object.assign({}, options);
// Ensure we have the right read preference inheritance
options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this });
+ command.readPreference = options.readPreference;
// If explain has been specified add it
if (options.explain) { | 1 | 'use strict';
const checkCollectionName = require('./utils').checkCollectionName;
const ObjectID = require('mongodb-core').BSON.ObjectID;
const AggregationCursor = require('./aggregation_cursor');
const MongoError = require('mongodb-core').MongoError;
const toError = require('./utils').toError;
const normalizeHintField = require('./utils').normalizeHintField;
const handleCallback = require('./utils').handleCallback;
const decorateWithCollation = require('./utils').decorateWithCollation;
const decorateWithReadConcern = require('./utils').decorateWithReadConcern;
const formattedOrderClause = require('./utils').formattedOrderClause;
const ReadPreference = require('mongodb-core').ReadPreference;
const CommandCursor = require('./command_cursor');
const unordered = require('./bulk/unordered');
const ordered = require('./bulk/ordered');
const ChangeStream = require('./change_stream');
const executeOperation = require('./utils').executeOperation;
const applyWriteConcern = require('./utils').applyWriteConcern;
const resolveReadPreference = require('./utils').resolveReadPreference;
// Operations
const bulkWrite = require('./operations/collection_ops').bulkWrite;
const checkForAtomicOperators = require('./operations/collection_ops').checkForAtomicOperators;
const count = require('./operations/collection_ops').count;
const countDocuments = require('./operations/collection_ops').countDocuments;
const createIndex = require('./operations/collection_ops').createIndex;
const createIndexes = require('./operations/collection_ops').createIndexes;
const deleteMany = require('./operations/collection_ops').deleteMany;
const deleteOne = require('./operations/collection_ops').deleteOne;
const distinct = require('./operations/collection_ops').distinct;
const dropIndex = require('./operations/collection_ops').dropIndex;
const dropIndexes = require('./operations/collection_ops').dropIndexes;
const ensureIndex = require('./operations/collection_ops').ensureIndex;
const findAndModify = require('./operations/collection_ops').findAndModify;
const findAndRemove = require('./operations/collection_ops').findAndRemove;
const findOne = require('./operations/collection_ops').findOne;
const findOneAndDelete = require('./operations/collection_ops').findOneAndDelete;
const findOneAndReplace = require('./operations/collection_ops').findOneAndReplace;
const findOneAndUpdate = require('./operations/collection_ops').findOneAndUpdate;
const geoHaystackSearch = require('./operations/collection_ops').geoHaystackSearch;
const group = require('./operations/collection_ops').group;
const indexes = require('./operations/collection_ops').indexes;
const indexExists = require('./operations/collection_ops').indexExists;
const indexInformation = require('./operations/collection_ops').indexInformation;
const insertOne = require('./operations/collection_ops').insertOne;
const isCapped = require('./operations/collection_ops').isCapped;
const mapReduce = require('./operations/collection_ops').mapReduce;
const optionsOp = require('./operations/collection_ops').optionsOp;
const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan;
const prepareDocs = require('./operations/collection_ops').prepareDocs;
const reIndex = require('./operations/collection_ops').reIndex;
const removeDocuments = require('./operations/collection_ops').removeDocuments;
const rename = require('./operations/collection_ops').rename;
const replaceOne = require('./operations/collection_ops').replaceOne;
const save = require('./operations/collection_ops').save;
const stats = require('./operations/collection_ops').stats;
const updateDocuments = require('./operations/collection_ops').updateDocuments;
const updateMany = require('./operations/collection_ops').updateMany;
const updateOne = require('./operations/collection_ops').updateOne;
/**
* @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection
* allowing for insert/update/remove/find and other command operation on that MongoDB collection.
*
* **COLLECTION Cannot directly be instantiated**
* @example
* const MongoClient = require('mongodb').MongoClient;
* const test = require('assert');
* // Connection url
* const url = 'mongodb://localhost:27017';
* // Database Name
* const dbName = 'test';
* // Connect using MongoClient
* MongoClient.connect(url, function(err, client) {
* // Create a collection we want to drop later
* const col = client.db(dbName).collection('createIndexExample1');
* // Show that duplicate records got dropped
* col.find({}).toArray(function(err, items) {
* test.equal(null, err);
* test.equal(4, items.length);
* client.close();
* });
* });
*/
const mergeKeys = ['ignoreUndefined'];
/**
* Create a new Collection instance (INTERNAL TYPE, do not instantiate directly)
* @class
* @property {string} collectionName Get the collection name.
* @property {string} namespace Get the full collection namespace.
* @property {object} writeConcern The current write concern values.
* @property {object} readConcern The current read concern values.
* @property {object} hint Get current index hint for collection.
* @return {Collection} a Collection instance.
*/
function Collection(db, topology, dbName, name, pkFactory, options) {
checkCollectionName(name);
// Unpack variables
const internalHint = null;
const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk;
const serializeFunctions =
options == null || options.serializeFunctions == null
? db.s.options.serializeFunctions
: options.serializeFunctions;
const raw = options == null || options.raw == null ? db.s.options.raw : options.raw;
const promoteLongs =
options == null || options.promoteLongs == null
? db.s.options.promoteLongs
: options.promoteLongs;
const promoteValues =
options == null || options.promoteValues == null
? db.s.options.promoteValues
: options.promoteValues;
const promoteBuffers =
options == null || options.promoteBuffers == null
? db.s.options.promoteBuffers
: options.promoteBuffers;
let readPreference = null;
const collectionHint = null;
const namespace = `${dbName}.${name}`;
// Get the promiseLibrary
const promiseLibrary = options.promiseLibrary || Promise;
// Assign the right collection level readPreference
if (options && options.readPreference) {
readPreference = options.readPreference;
} else if (db.options.readPreference) {
readPreference = db.options.readPreference;
}
// Set custom primary key factory if provided
pkFactory = pkFactory == null ? ObjectID : pkFactory;
// Internal state
this.s = {
// Set custom primary key factory if provided
pkFactory: pkFactory,
// Db
db: db,
// Topology
topology: topology,
// dbName
dbName: dbName,
// Options
options: options,
// Namespace
namespace: namespace,
// Read preference
readPreference: readPreference,
// SlaveOK
slaveOk: slaveOk,
// Serialize functions
serializeFunctions: serializeFunctions,
// Raw
raw: raw,
// promoteLongs
promoteLongs: promoteLongs,
// promoteValues
promoteValues: promoteValues,
// promoteBuffers
promoteBuffers: promoteBuffers,
// internalHint
internalHint: internalHint,
// collectionHint
collectionHint: collectionHint,
// Name
name: name,
// Promise library
promiseLibrary: promiseLibrary,
// Read Concern
readConcern: options.readConcern,
// Write Concern
writeConcern: options.writeConcern
};
}
Object.defineProperty(Collection.prototype, 'dbName', {
enumerable: true,
get: function() {
return this.s.dbName;
}
});
Object.defineProperty(Collection.prototype, 'collectionName', {
enumerable: true,
get: function() {
return this.s.name;
}
});
Object.defineProperty(Collection.prototype, 'namespace', {
enumerable: true,
get: function() {
return this.s.namespace;
}
});
Object.defineProperty(Collection.prototype, 'readConcern', {
enumerable: true,
get: function() {
return this.s.readConcern || { level: 'local' };
}
});
Object.defineProperty(Collection.prototype, 'writeConcern', {
enumerable: true,
get: function() {
let ops = {};
if (this.s.writeConcern) {
return this.s.writeConcern;
}
if (this.s.options.w != null) ops.w = this.s.options.w;
if (this.s.options.j != null) ops.j = this.s.options.j;
if (this.s.options.fsync != null) ops.fsync = this.s.options.fsync;
if (this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout;
return ops;
}
});
/**
* @ignore
*/
Object.defineProperty(Collection.prototype, 'hint', {
enumerable: true,
get: function() {
return this.s.collectionHint;
},
set: function(v) {
this.s.collectionHint = normalizeHintField(v);
}
});
const DEPRECATED_FIND_OPTIONS = ['maxScan', 'snapshot'];
/**
* Creates a cursor for a query that can be used to iterate over results from MongoDB
* @method
* @param {object} [query={}] The cursor query object.
* @param {object} [options=null] Optional settings.
* @param {number} [options.limit=0] Sets the limit of documents returned in the query.
* @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
* @param {object} [options.projection=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
* @param {object} [options.fields=null] **Deprecated** Use `options.projection` instead
* @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination).
* @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
* @param {boolean} [options.explain=false] Explain the query instead of returning the data.
* @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query.
* @param {boolean} [options.timeout=false] Specify if the cursor can timeout.
* @param {boolean} [options.tailable=false] Specify if the cursor is tailable.
* @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results.
* @param {boolean} [options.returnKey=false] Only return the index key.
* @param {number} [options.maxScan=null] DEPRECATED: Limit the number of items to scan.
* @param {number} [options.min=null] Set index bounds.
* @param {number} [options.max=null] Set index bounds.
* @param {boolean} [options.showDiskLoc=false] Show disk location of results.
* @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler.
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
* @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
* @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
* @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system
* @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query.
* @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
* @param {ClientSession} [options.session] optional session to use for this operation
* @throws {MongoError}
* @return {Cursor}
*/
Collection.prototype.find = function(query, options, callback) {
let selector = query;
// figuring out arguments
if (typeof callback !== 'function') {
if (typeof options === 'function') {
callback = options;
options = undefined;
} else if (options == null) {
callback = typeof selector === 'function' ? selector : undefined;
selector = typeof selector === 'object' ? selector : undefined;
}
}
// Ensure selector is not null
selector = selector == null ? {} : selector;
// Validate correctness off the selector
const object = selector;
if (Buffer.isBuffer(object)) {
const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24);
if (object_size !== object.length) {
const error = new Error(
'query selector raw message size does not match message header size [' +
object.length +
'] != [' +
object_size +
']'
);
error.name = 'MongoError';
throw error;
}
}
// Check special case where we are using an objectId
if (selector != null && selector._bsontype === 'ObjectID') {
selector = { _id: selector };
}
if (!options) options = {};
let projection = options.projection || options.fields;
if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) {
projection = projection.length
? projection.reduce((result, field) => {
result[field] = 1;
return result;
}, {})
: { _id: 1 };
}
// Make a shallow copy of options
let newOptions = Object.assign({}, options);
// Make a shallow copy of the collection options
for (let key in this.s.options) {
if (mergeKeys.indexOf(key) !== -1) {
newOptions[key] = this.s.options[key];
}
}
// Unpack options
newOptions.skip = options.skip ? options.skip : 0;
newOptions.limit = options.limit ? options.limit : 0;
newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw;
newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint;
newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout;
// // If we have overridden slaveOk otherwise use the default db setting
newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk;
// Add read preference if needed
newOptions.readPreference = resolveReadPreference(newOptions, {
db: this.s.db,
collection: this
});
// Set slave ok to true if read preference different from primary
if (
newOptions.readPreference != null &&
(newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary')
) {
newOptions.slaveOk = true;
}
// Ensure the query is an object
if (selector != null && typeof selector !== 'object') {
throw MongoError.create({ message: 'query selector must be an object', driver: true });
}
// Build the find command
const findCommand = {
find: this.s.namespace,
limit: newOptions.limit,
skip: newOptions.skip,
query: selector
};
// Ensure we use the right await data option
if (typeof newOptions.awaitdata === 'boolean') {
newOptions.awaitData = newOptions.awaitdata;
}
// Translate to new command option noCursorTimeout
if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout;
// Merge in options to command
for (let name in newOptions) {
if (newOptions[name] != null && name !== 'session') {
findCommand[name] = newOptions[name];
}
}
DEPRECATED_FIND_OPTIONS.forEach(deprecatedOption => {
if (findCommand[deprecatedOption]) {
console.warn(
`Find option ${deprecatedOption} is deprecated, and will be removed in a later version`
);
}
});
if (projection) findCommand.fields = projection;
// Add db object to the new options
newOptions.db = this.s.db;
// Add the promise library
newOptions.promiseLibrary = this.s.promiseLibrary;
// Set raw if available at collection level
if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw;
// Set promoteLongs if available at collection level
if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean')
newOptions.promoteLongs = this.s.promoteLongs;
if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean')
newOptions.promoteValues = this.s.promoteValues;
if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean')
newOptions.promoteBuffers = this.s.promoteBuffers;
// Sort options
if (findCommand.sort) {
findCommand.sort = formattedOrderClause(findCommand.sort);
}
// Set the readConcern
decorateWithReadConcern(findCommand, this, options);
// Decorate find command with collation options
decorateWithCollation(findCommand, this, options);
const cursor = this.s.topology.cursor(this.s.namespace, findCommand, newOptions);
// automatically call map on the cursor if the map option is set
if (typeof this.s.options.map === 'function') {
cursor.map(this.s.options.map);
}
return typeof callback === 'function' ? handleCallback(callback, null, cursor) : cursor;
};
/**
* Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field,
* one will be added to each of the documents missing it by the driver, mutating the document. This behavior
* can be overridden by setting the **forceServerObjectId** flag.
*
* @method
* @param {object} doc Document to insert.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
* @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
* @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~insertOneWriteOpCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.insertOne = function(doc, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Add ignoreUndfined
if (this.s.options.ignoreUndefined) {
options = Object.assign({}, options);
options.ignoreUndefined = this.s.options.ignoreUndefined;
}
return executeOperation(this.s.topology, insertOne, [this, doc, options, callback]);
};
function mapInsertManyResults(docs, r) {
const finalResult = {
result: { ok: 1, n: r.insertedCount },
ops: docs,
insertedCount: r.insertedCount,
insertedIds: r.insertedIds
};
if (r.getLastOp()) {
finalResult.result.opTime = r.getLastOp();
}
return finalResult;
}
/**
* Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
* one will be added to each of the documents missing it by the driver, mutating the document. This behavior
* can be overridden by setting the **forceServerObjectId** flag.
*
* @method
* @param {object[]} docs Documents to insert.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
* @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
* @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
* @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~insertWriteOpCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.insertMany = function(docs, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options ? Object.assign({}, options) : { ordered: true };
if (!Array.isArray(docs) && typeof callback === 'function') {
return callback(
MongoError.create({ message: 'docs parameter must be an array of documents', driver: true })
);
} else if (!Array.isArray(docs)) {
return new this.s.promiseLibrary((resolve, reject) => {
reject(
MongoError.create({ message: 'docs parameter must be an array of documents', driver: true })
);
});
}
// If keep going set unordered
options['serializeFunctions'] = options['serializeFunctions'] || this.s.serializeFunctions;
docs = prepareDocs(this, docs, options);
// Generate the bulk write operations
const operations = [
{
insertMany: docs
}
];
return executeOperation(this.s.topology, bulkWrite, [this, operations, options, callback], {
resultMutator: result => mapInsertManyResults(docs, result)
});
};
/**
* @typedef {Object} Collection~BulkWriteOpResult
* @property {number} insertedCount Number of documents inserted.
* @property {number} matchedCount Number of documents matched for update.
* @property {number} modifiedCount Number of documents modified.
* @property {number} deletedCount Number of documents deleted.
* @property {number} upsertedCount Number of documents upserted.
* @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation
* @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation
* @property {object} result The command result object.
*/
/**
* The callback format for inserts
* @callback Collection~bulkWriteOpCallback
* @param {BulkWriteError} error An error instance representing the error during the execution.
* @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully.
*/
/**
* Perform a bulkWrite operation without a fluent API
*
* Legal operation types are
*
* { insertOne: { document: { a: 1 } } }
*
* { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
*
* { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
*
* { deleteOne: { filter: {c:1} } }
*
* { deleteMany: { filter: {c:1} } }
*
* { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}
*
* If documents passed in do not contain the **_id** field,
* one will be added to each of the documents missing it by the driver, mutating the document. This behavior
* can be overridden by setting the **forceServerObjectId** flag.
*
* @method
* @param {object[]} operations Bulk operations to perform.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
* @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion.
* @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~bulkWriteOpCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.bulkWrite = function(operations, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || { ordered: true };
if (!Array.isArray(operations)) {
throw MongoError.create({ message: 'operations must be an array of documents', driver: true });
}
return executeOperation(this.s.topology, bulkWrite, [this, operations, options, callback]);
};
/**
* @typedef {Object} Collection~WriteOpResult
* @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
* @property {object} connection The connection object used for the operation.
* @property {object} result The command result object.
*/
/**
* The callback format for inserts
* @callback Collection~writeOpCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {Collection~WriteOpResult} result The result object if the command was executed successfully.
*/
/**
* @typedef {Object} Collection~insertWriteOpResult
* @property {Number} insertedCount The total amount of documents inserted.
* @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
* @property {Object.<Number, ObjectId>} insertedIds Map of the index of the inserted document to the id of the inserted document.
* @property {object} connection The connection object used for the operation.
* @property {object} result The raw command result object returned from MongoDB (content might vary by server version).
* @property {Number} result.ok Is 1 if the command executed correctly.
* @property {Number} result.n The total count of documents inserted.
*/
/**
* @typedef {Object} Collection~insertOneWriteOpResult
* @property {Number} insertedCount The total amount of documents inserted.
* @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
* @property {ObjectId} insertedId The driver generated ObjectId for the insert operation.
* @property {object} connection The connection object used for the operation.
* @property {object} result The raw command result object returned from MongoDB (content might vary by server version).
* @property {Number} result.ok Is 1 if the command executed correctly.
* @property {Number} result.n The total count of documents inserted.
*/
/**
* The callback format for inserts
* @callback Collection~insertWriteOpCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully.
*/
/**
* The callback format for inserts
* @callback Collection~insertOneWriteOpCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully.
*/
/**
* Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
* one will be added to each of the documents missing it by the driver, mutating the document. This behavior
* can be overridden by setting the **forceServerObjectId** flag.
*
* @method
* @param {(object|object[])} docs Documents to insert.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
* @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
* @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~insertWriteOpCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
* @deprecated Use insertOne, insertMany or bulkWrite
*/
Collection.prototype.insert = function(docs, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || { ordered: false };
docs = !Array.isArray(docs) ? [docs] : docs;
if (options.keepGoing === true) {
options.ordered = false;
}
return this.insertMany(docs, options, callback);
};
/**
* @typedef {Object} Collection~updateWriteOpResult
* @property {Object} result The raw result returned from MongoDB, field will vary depending on server version.
* @property {Number} result.ok Is 1 if the command executed correctly.
* @property {Number} result.n The total count of documents scanned.
* @property {Number} result.nModified The total count of documents modified.
* @property {Object} connection The connection object used for the operation.
* @property {Number} matchedCount The number of documents that matched the filter.
* @property {Number} modifiedCount The number of documents that were modified.
* @property {Number} upsertedCount The number of documents upserted.
* @property {Object} upsertedId The upserted id.
* @property {ObjectId} upsertedId._id The upserted _id returned from the server.
*/
/**
* The callback format for inserts
* @callback Collection~updateWriteOpCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully.
*/
/**
* Update a single document on MongoDB
* @method
* @param {object} filter The Filter used to select the document to update
* @param {object} update The update operations to be applied to the document
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.upsert=false] Update operation is an upsert.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
* @param {Array} [options.arrayFilters=null] optional list of array filters referenced in filtered positional operators
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~updateWriteOpCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.updateOne = function(filter, update, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
const err = checkForAtomicOperators(update);
if (err) {
if (typeof callback === 'function') return callback(err);
return this.s.promiseLibrary.reject(err);
}
options = Object.assign({}, options);
// Add ignoreUndfined
if (this.s.options.ignoreUndefined) {
options = Object.assign({}, options);
options.ignoreUndefined = this.s.options.ignoreUndefined;
}
return executeOperation(this.s.topology, updateOne, [this, filter, update, options, callback]);
};
/**
* Replace a document on MongoDB
* @method
* @param {object} filter The Filter used to select the document to update
* @param {object} doc The Document that replaces the matching document
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.upsert=false] Update operation is an upsert.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~updateWriteOpCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.replaceOne = function(filter, doc, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = Object.assign({}, options);
// Add ignoreUndfined
if (this.s.options.ignoreUndefined) {
options = Object.assign({}, options);
options.ignoreUndefined = this.s.options.ignoreUndefined;
}
if (typeof this.s.options.unmap === 'function') {
doc = this.s.options.unmap(doc);
}
return executeOperation(this.s.topology, replaceOne, [this, filter, doc, options, callback]);
};
/**
* Update multiple documents on MongoDB
* @method
* @param {object} filter The Filter used to select the documents to update
* @param {object} update The update operations to be applied to the document
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.upsert=false] Update operation is an upsert.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {Array} [options.arrayFilters=null] optional list of array filters referenced in filtered positional operators
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~updateWriteOpCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.updateMany = function(filter, update, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
const err = checkForAtomicOperators(update);
if (err) {
if (typeof callback === 'function') return callback(err);
return this.s.promiseLibrary.reject(err);
}
options = Object.assign({}, options);
// Add ignoreUndfined
if (this.s.options.ignoreUndefined) {
options = Object.assign({}, options);
options.ignoreUndefined = this.s.options.ignoreUndefined;
}
return executeOperation(this.s.topology, updateMany, [this, filter, update, options, callback]);
};
/**
* Updates documents.
* @method
* @param {object} selector The selector for the update operation.
* @param {object} document The update document.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.upsert=false] Update operation is an upsert.
* @param {boolean} [options.multi=false] Update one/all documents with operation.
* @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
* @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
* @param {Array} [options.arrayFilters=null] optional list of array filters referenced in filtered positional operators
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~writeOpCallback} [callback] The command result callback
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
* @deprecated use updateOne, updateMany or bulkWrite
*/
Collection.prototype.update = function(selector, document, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Add ignoreUndfined
if (this.s.options.ignoreUndefined) {
options = Object.assign({}, options);
options.ignoreUndefined = this.s.options.ignoreUndefined;
}
return executeOperation(this.s.topology, updateDocuments, [
this,
selector,
document,
options,
callback
]);
};
/**
* @typedef {Object} Collection~deleteWriteOpResult
* @property {Object} result The raw result returned from MongoDB, field will vary depending on server version.
* @property {Number} result.ok Is 1 if the command executed correctly.
* @property {Number} result.n The total count of documents deleted.
* @property {Object} connection The connection object used for the operation.
* @property {Number} deletedCount The number of documents deleted.
*/
/**
* The callback format for inserts
* @callback Collection~deleteWriteOpCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully.
*/
/**
* Delete a document on MongoDB
* @method
* @param {object} filter The Filter used to select the document to remove
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~deleteWriteOpCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.deleteOne = function(filter, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = Object.assign({}, options);
// Add ignoreUndfined
if (this.s.options.ignoreUndefined) {
options = Object.assign({}, options);
options.ignoreUndefined = this.s.options.ignoreUndefined;
}
return executeOperation(this.s.topology, deleteOne, [this, filter, options, callback]);
};
Collection.prototype.removeOne = Collection.prototype.deleteOne;
/**
* Delete multiple documents on MongoDB
* @method
* @param {object} filter The Filter used to select the documents to remove
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~deleteWriteOpCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.deleteMany = function(filter, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = Object.assign({}, options);
// Add ignoreUndfined
if (this.s.options.ignoreUndefined) {
options = Object.assign({}, options);
options.ignoreUndefined = this.s.options.ignoreUndefined;
}
return executeOperation(this.s.topology, deleteMany, [this, filter, options, callback]);
};
Collection.prototype.removeMany = Collection.prototype.deleteMany;
/**
* Remove documents.
* @method
* @param {object} selector The selector for the update operation.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.single=false] Removes the first document found.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~writeOpCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
* @deprecated use deleteOne, deleteMany or bulkWrite
*/
Collection.prototype.remove = function(selector, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Add ignoreUndfined
if (this.s.options.ignoreUndefined) {
options = Object.assign({}, options);
options.ignoreUndefined = this.s.options.ignoreUndefined;
}
return executeOperation(this.s.topology, removeDocuments, [this, selector, options, callback]);
};
/**
* Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic
* operators and update instead for more efficient operations.
* @method
* @param {object} doc Document to save
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~writeOpCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
* @deprecated use insertOne, insertMany, updateOne or updateMany
*/
Collection.prototype.save = function(doc, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Add ignoreUndfined
if (this.s.options.ignoreUndefined) {
options = Object.assign({}, options);
options.ignoreUndefined = this.s.options.ignoreUndefined;
}
return executeOperation(this.s.topology, save, [this, doc, options, callback]);
};
/**
* The callback format for results
* @callback Collection~resultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {object} result The result object if the command was executed successfully.
*/
/**
* The callback format for an aggregation call
* @callback Collection~aggregationCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully.
*/
/**
* Fetches the first document that matches the query
* @method
* @param {object} query Query for find Operation
* @param {object} [options=null] Optional settings.
* @param {number} [options.limit=0] Sets the limit of documents returned in the query.
* @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
* @param {object} [options.projection=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
* @param {object} [options.fields=null] **Deprecated** Use `options.projection` instead
* @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination).
* @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
* @param {boolean} [options.explain=false] Explain the query instead of returning the data.
* @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query.
* @param {boolean} [options.timeout=false] Specify if the cursor can timeout.
* @param {boolean} [options.tailable=false] Specify if the cursor is tailable.
* @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results.
* @param {boolean} [options.returnKey=false] Only return the index key.
* @param {number} [options.maxScan=null] DEPRECATED: Limit the number of items to scan.
* @param {number} [options.min=null] Set index bounds.
* @param {number} [options.max=null] Set index bounds.
* @param {boolean} [options.showDiskLoc=false] Show disk location of results.
* @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler.
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
* @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
* @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
* @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system
* @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query.
* @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.findOne = function(query, options, callback) {
if (typeof query === 'function') (callback = query), (query = {}), (options = {});
if (typeof options === 'function') (callback = options), (options = {});
query = query || {};
options = options || {};
return executeOperation(this.s.topology, findOne, [this, query, options, callback]);
};
/**
* The callback format for the collection method, must be used if strict is specified
* @callback Collection~collectionResultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {Collection} collection The collection instance.
*/
/**
* Rename the collection.
*
* @method
* @param {string} newName New name of of the collection.
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~collectionResultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.rename = function(newName, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY });
return executeOperation(this.s.topology, rename, [this, newName, options, callback]);
};
/**
* Drop the collection from the database, removing it permanently. New accesses will create a new collection.
*
* @method
* @param {object} [options=null] Optional settings.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.drop = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
return executeOperation(this.s.topology, this.s.db.dropCollection.bind(this.s.db), [
this.s.name,
options,
callback
]);
};
/**
* Returns the options of the collection.
*
* @method
* @param {Object} [options] Optional settings
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.options = function(opts, callback) {
if (typeof opts === 'function') (callback = opts), (opts = {});
opts = opts || {};
return executeOperation(this.s.topology, optionsOp, [this, opts, callback]);
};
/**
* Returns if the collection is a capped collection
*
* @method
* @param {Object} [options] Optional settings
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.isCapped = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
return executeOperation(this.s.topology, isCapped, [this, options, callback]);
};
/**
* Creates an index on the db and collection collection.
* @method
* @param {(string|object)} fieldOrSpec Defines the index.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.unique=false] Creates an unique index.
* @param {boolean} [options.sparse=false] Creates a sparse index.
* @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
* @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
* @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates.
* @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates.
* @param {number} [options.v=null] Specify the format version of the indexes.
* @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
* @param {string} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
* @param {object} [options.partialFilterExpression=null] Creates a partial index based on the given filter object (MongoDB 3.2 or higher)
* @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.createIndex = function(fieldOrSpec, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
return executeOperation(this.s.topology, createIndex, [this, fieldOrSpec, options, callback]);
};
/**
* Creates multiple indexes in the collection, this method is only supported for
* MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
* error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/.
* @method
* @param {array} indexSpecs An array of index specifications to be created
* @param {Object} [options] Optional settings
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.createIndexes = function(indexSpecs, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options ? Object.assign({}, options) : {};
if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS;
return executeOperation(this.s.topology, createIndexes, [this, indexSpecs, options, callback]);
};
/**
* Drops an index from this collection.
* @method
* @param {string} indexName Name of the index to drop.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query.
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.dropIndex = function(indexName, options, callback) {
const args = Array.prototype.slice.call(arguments, 1);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
options = args.length ? args.shift() || {} : {};
// Run only against primary
options.readPreference = ReadPreference.PRIMARY;
return executeOperation(this.s.topology, dropIndex, [this, indexName, options, callback]);
};
/**
* Drops all indexes from this collection.
* @method
* @param {Object} [options] Optional settings
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query.
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.dropIndexes = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options ? Object.assign({}, options) : {};
if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS;
return executeOperation(this.s.topology, dropIndexes, [this, options, callback]);
};
/**
* Drops all indexes from this collection.
* @method
* @deprecated use dropIndexes
* @param {Collection~resultCallback} callback The command result callback
* @return {Promise} returns Promise if no [callback] passed
*/
Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes;
/**
* Reindex all indexes on the collection
* Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.
* @method
* @param {Object} [options] Optional settings
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.reIndex = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
return executeOperation(this.s.topology, reIndex, [this, options, callback]);
};
/**
* Get the list of all indexes information for the collection.
*
* @method
* @param {object} [options=null] Optional settings.
* @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {ClientSession} [options.session] optional session to use for this operation
* @return {CommandCursor}
*/
Collection.prototype.listIndexes = function(options) {
options = options || {};
// Clone the options
options = Object.assign({}, options);
// Determine the read preference in the options.
options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this });
// Set the CommandCursor constructor
options.cursorFactory = CommandCursor;
// Set the promiseLibrary
options.promiseLibrary = this.s.promiseLibrary;
if (!this.s.topology.capabilities()) {
throw new MongoError('cannot connect to server');
}
// Cursor options
let cursor = options.batchSize ? { batchSize: options.batchSize } : {};
// We have a list collections command
if (this.s.topology.capabilities().hasListIndexesCommand) {
// Build the command
const command = { listIndexes: this.s.name, cursor: cursor };
// Execute the cursor
cursor = this.s.topology.cursor(`${this.s.dbName}.$cmd`, command, options);
// Do we have a readPreference, apply it
if (options.readPreference) cursor.setReadPreference(options.readPreference);
// Return the cursor
return cursor;
}
// Get the namespace
const ns = `${this.s.dbName}.system.indexes`;
// Get the query
cursor = this.s.topology.cursor(ns, { find: ns, query: { ns: this.s.namespace } }, options);
// Do we have a readPreference, apply it
if (options.readPreference) cursor.setReadPreference(options.readPreference);
// Set the passed in batch size if one was provided
if (options.batchSize) cursor = cursor.batchSize(options.batchSize);
// Return the cursor
return cursor;
};
/**
* Ensures that an index exists, if it does not it creates it
* @method
* @deprecated use createIndexes instead
* @param {(string|object)} fieldOrSpec Defines the index.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.unique=false] Creates an unique index.
* @param {boolean} [options.sparse=false] Creates a sparse index.
* @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
* @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
* @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates.
* @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates.
* @param {number} [options.v=null] Specify the format version of the indexes.
* @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
* @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
* @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
return executeOperation(this.s.topology, ensureIndex, [this, fieldOrSpec, options, callback]);
};
/**
* Checks if one or more indexes exist on the collection, fails on first non-existing index
* @method
* @param {(string|array)} indexes One or more index names to check.
* @param {Object} [options] Optional settings
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.indexExists = function(indexes, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
return executeOperation(this.s.topology, indexExists, [this, indexes, options, callback]);
};
/**
* Retrieves this collections index info.
* @method
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.full=false] Returns the full raw index information.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.indexInformation = function(options, callback) {
const args = Array.prototype.slice.call(arguments, 0);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
options = args.length ? args.shift() || {} : {};
return executeOperation(this.s.topology, indexInformation, [this, options, callback]);
};
/**
* The callback format for results
* @callback Collection~countCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {number} result The count of documents that matched the query.
*/
/**
* Count number of matching documents in the db to a query.
* @method
* @param {object} query The query for the count.
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.limit=null] The limit of documents to count.
* @param {boolean} [options.skip=null] The number of documents to skip for the count.
* @param {string} [options.hint=null] An index name hint for the query.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~countCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
* @deprecated use countDocuments or estimatedDocumentCount instead
*/
Collection.prototype.count = function(query, options, callback) {
const args = Array.prototype.slice.call(arguments, 0);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
query = args.length ? args.shift() || {} : {};
options = args.length ? args.shift() || {} : {};
return executeOperation(this.s.topology, count, [this, query, options, callback]);
};
/**
* Gets an estimate of the count of documents in a collection using collection metadata.
* @method
* @param {object} [options] Optional settings.
* @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run.
* @param {Collection~countCallback} [callback] The command result callback.
* @return {Promise} returns Promise if no callback passed.
*/
Collection.prototype.estimatedDocumentCount = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
options = typeof options.maxTimeMS === 'number' ? options : {};
return executeOperation(this.s.topology, count, [this, null, options, callback]);
};
/**
* Gets the number of documents matching the filter.
* @param {object} [query] the query for the count
* @param {object} [options] Optional settings.
* @param {object} [options.collation] Specifies a collation.
* @param {string|object} [options.hint] The index to use.
* @param {number} [options.limit] The maximum number of document to count.
* @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run.
* @param {number} [options.skip] The number of documents to skip before counting.
* @param {Collection~countCallback} [callback] The command result callback.
* @return {Promise} returns Promise if no callback passed.
*/
Collection.prototype.countDocuments = function(query, options, callback) {
const args = Array.prototype.slice.call(arguments, 0);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
query = args.length ? args.shift() || {} : {};
options = args.length ? args.shift() || {} : {};
return executeOperation(this.s.topology, countDocuments, [this, query, options, callback]);
};
/**
* The distinct command returns returns a list of distinct values for the given key across a collection.
* @method
* @param {string} key Field of the document to find distinct values for.
* @param {object} query The query for filtering the set of documents to which we apply the distinct filter.
* @param {object} [options=null] Optional settings.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.distinct = function(key, query, options, callback) {
const args = Array.prototype.slice.call(arguments, 1);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
const queryOption = args.length ? args.shift() || {} : {};
const optionsOption = args.length ? args.shift() || {} : {};
return executeOperation(this.s.topology, distinct, [
this,
key,
queryOption,
optionsOption,
callback
]);
};
/**
* Retrieve all the indexes on the collection.
* @method
* @param {Object} [options] Optional settings
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.indexes = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
return executeOperation(this.s.topology, indexes, [this, options, callback]);
};
/**
* Get all the collection statistics.
*
* @method
* @param {object} [options=null] Optional settings.
* @param {number} [options.scale=null] Divide the returned sizes by scale value.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The collection result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.stats = function(options, callback) {
const args = Array.prototype.slice.call(arguments, 0);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
options = args.length ? args.shift() || {} : {};
return executeOperation(this.s.topology, stats, [this, options, callback]);
};
/**
* @typedef {Object} Collection~findAndModifyWriteOpResult
* @property {object} value Document returned from findAndModify command.
* @property {object} lastErrorObject The raw lastErrorObject returned from the command.
* @property {Number} ok Is 1 if the command executed correctly.
*/
/**
* The callback format for inserts
* @callback Collection~findAndModifyCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully.
*/
/**
* Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.
*
* @method
* @param {object} filter Document selection filter.
* @param {object} [options=null] Optional settings.
* @param {object} [options.projection=null] Limits the fields to return for all matching documents.
* @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents.
* @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~findAndModifyCallback} [callback] The collection result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.findOneAndDelete = function(filter, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Basic validation
if (filter == null || typeof filter !== 'object')
throw toError('filter parameter must be an object');
return executeOperation(this.s.topology, findOneAndDelete, [this, filter, options, callback]);
};
/**
* Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.
*
* @method
* @param {object} filter Document selection filter.
* @param {object} replacement Document replacing the matching document.
* @param {object} [options=null] Optional settings.
* @param {object} [options.projection=null] Limits the fields to return for all matching documents.
* @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents.
* @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run.
* @param {boolean} [options.upsert=false] Upsert the document if it does not exist.
* @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~findAndModifyCallback} [callback] The collection result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Basic validation
if (filter == null || typeof filter !== 'object')
throw toError('filter parameter must be an object');
if (replacement == null || typeof replacement !== 'object')
throw toError('replacement parameter must be an object');
return executeOperation(this.s.topology, findOneAndReplace, [
this,
filter,
replacement,
options,
callback
]);
};
/**
* Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.
*
* @method
* @param {object} filter Document selection filter.
* @param {object} update Update operations to be performed on the document
* @param {object} [options] Optional settings.
* @param {object} [options.projection] Limits the fields to return for all matching documents.
* @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents.
* @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run.
* @param {boolean} [options.upsert=false] Upsert the document if it does not exist.
* @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators
* @param {Collection~findAndModifyCallback} [callback] The collection result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Basic validation
if (filter == null || typeof filter !== 'object')
throw toError('filter parameter must be an object');
if (update == null || typeof update !== 'object')
throw toError('update parameter must be an object');
const err = checkForAtomicOperators(update);
if (err) {
if (typeof callback === 'function') return callback(err);
return this.s.promiseLibrary.reject(err);
}
return executeOperation(this.s.topology, findOneAndUpdate, [
this,
filter,
update,
options,
callback
]);
};
/**
* Find and update a document.
* @method
* @param {object} query Query object to locate the object to modify.
* @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate.
* @param {object} doc The fields/vals to be updated.
* @param {object} [options] Optional settings.
* @param {(number|string)} [options.w] The write concern.
* @param {number} [options.wtimeout] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.remove=false] Set to true to remove the object before returning.
* @param {boolean} [options.upsert=false] Perform an upsert operation.
* @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove.
* @param {object} [options.projection] Object containing the field projection for the result returned from the operation.
* @param {object} [options.fields] **Deprecated** Use `options.projection` instead
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators
* @param {Collection~findAndModifyCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
* @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead
*/
Collection.prototype.findAndModify = function(query, sort, doc, options, callback) {
const args = Array.prototype.slice.call(arguments, 1);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
sort = args.length ? args.shift() || [] : [];
doc = args.length ? args.shift() : null;
options = args.length ? args.shift() || {} : {};
// Clone options
options = Object.assign({}, options);
// Force read preference primary
options.readPreference = ReadPreference.PRIMARY;
return executeOperation(this.s.topology, findAndModify, [
this,
query,
sort,
doc,
options,
callback
]);
};
/**
* Find and remove a document.
* @method
* @param {object} query Query object to locate the object to modify.
* @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
* @deprecated use findOneAndDelete instead
*/
Collection.prototype.findAndRemove = function(query, sort, options, callback) {
const args = Array.prototype.slice.call(arguments, 1);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
sort = args.length ? args.shift() || [] : [];
options = args.length ? args.shift() || {} : {};
return executeOperation(this.s.topology, findAndRemove, [this, query, sort, options, callback]);
};
/**
* Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2
* @method
* @param {object} pipeline Array containing all the aggregation framework commands for the execution.
* @param {object} [options=null] Optional settings.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.
* @param {number} [options.cursor.batchSize=null] The batchSize for the cursor
* @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >).
* @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).
* @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
* @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
* @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
* @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
* @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
* @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
* @param {string} [options.comment] Add a comment to an aggregation command
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~aggregationCallback} callback The command result callback
* @return {(null|AggregationCursor)}
*/
Collection.prototype.aggregate = function(pipeline, options, callback) {
if (Array.isArray(pipeline)) {
// Set up callback if one is provided
if (typeof options === 'function') {
callback = options;
options = {};
}
// If we have no options or callback we are doing
// a cursor based aggregation
if (options == null && callback == null) {
options = {};
}
} else {
// Aggregation pipeline passed as arguments on the method
const args = Array.prototype.slice.call(arguments, 0);
// Get the callback
callback = args.pop();
// Get the possible options object
const opts = args[args.length - 1];
// If it contains any of the admissible options pop it of the args
options =
opts &&
(opts.readPreference ||
opts.explain ||
opts.cursor ||
opts.out ||
opts.maxTimeMS ||
opts.hint ||
opts.allowDiskUse)
? args.pop()
: {};
// Left over arguments is the pipeline
pipeline = args;
}
// Ignore readConcern option
let ignoreReadConcern = false;
// Build the command
const command = { aggregate: this.s.name, pipeline: pipeline };
// If out was specified
if (typeof options.out === 'string') {
pipeline.push({ $out: options.out });
// Ignore read concern
ignoreReadConcern = true;
} else if (pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) {
ignoreReadConcern = true;
}
// Decorate command with writeConcern if out has been specified
if (
pipeline.length > 0 &&
pipeline[pipeline.length - 1]['$out'] &&
this.s.topology.capabilities().commandsTakeWriteConcern
) {
applyWriteConcern(command, { db: this.s.db, collection: this }, options);
}
// Have we specified collation
decorateWithCollation(command, this, options);
// If we have bypassDocumentValidation set
if (options.bypassDocumentValidation === true) {
command.bypassDocumentValidation = options.bypassDocumentValidation;
}
// Do we have a readConcern specified
if (!ignoreReadConcern) {
decorateWithReadConcern(command, this, options);
}
// If we have allowDiskUse defined
if (options.allowDiskUse) command.allowDiskUse = options.allowDiskUse;
if (typeof options.maxTimeMS === 'number') command.maxTimeMS = options.maxTimeMS;
// If we are giving a hint
if (options.hint) command.hint = options.hint;
options = Object.assign({}, options);
// Ensure we have the right read preference inheritance
options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this });
// If explain has been specified add it
if (options.explain) {
if (command.readConcern || command.writeConcern) {
throw toError('"explain" cannot be used on an aggregate call with readConcern/writeConcern');
}
command.explain = options.explain;
}
if (typeof options.comment === 'string') command.comment = options.comment;
// Validate that cursor options is valid
if (options.cursor != null && typeof options.cursor !== 'object') {
throw toError('cursor options must be an object');
}
options.cursor = options.cursor || {};
if (options.batchSize) options.cursor.batchSize = options.batchSize;
command.cursor = options.cursor;
// promiseLibrary
options.promiseLibrary = this.s.promiseLibrary;
// Set the AggregationCursor constructor
options.cursorFactory = AggregationCursor;
if (typeof callback !== 'function') {
if (!this.s.topology.capabilities()) {
throw new MongoError('cannot connect to server');
}
// Allow disk usage command
if (typeof options.allowDiskUse === 'boolean') command.allowDiskUse = options.allowDiskUse;
if (typeof options.maxTimeMS === 'number') command.maxTimeMS = options.maxTimeMS;
// Execute the cursor
return this.s.topology.cursor(this.s.namespace, command, options);
}
return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, command, options));
};
/**
* Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.
* @method
* @since 3.0.0
* @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
* @param {object} [options] Optional settings
* @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.
* @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.
* @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query
* @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
* @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
* @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.
* @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp
* @param {ClientSession} [options.session] optional session to use for this operation
* @return {ChangeStream} a ChangeStream instance.
*/
Collection.prototype.watch = function(pipeline, options) {
pipeline = pipeline || [];
options = options || {};
// Allow optionally not specifying a pipeline
if (!Array.isArray(pipeline)) {
options = pipeline;
pipeline = [];
}
return new ChangeStream(this, pipeline, options);
};
/**
* The callback format for results
* @callback Collection~parallelCollectionScanCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection.
*/
/**
* Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are
* no ordering guarantees for returned results.
* @method
* @param {object} [options=null] Optional settings.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results.
* @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors)
* @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents.
* @param {Collection~parallelCollectionScanCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.parallelCollectionScan = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = { numCursors: 1 });
// Set number of cursors to 1
options.numCursors = options.numCursors || 1;
options.batchSize = options.batchSize || 1000;
options = Object.assign({}, options);
// Ensure we have the right read preference inheritance
options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this });
// Add a promiseLibrary
options.promiseLibrary = this.s.promiseLibrary;
if (options.session) {
options.session = undefined;
}
return executeOperation(this.s.topology, parallelCollectionScan, [this, options, callback], {
skipSessions: true
});
};
/**
* Execute a geo search using a geo haystack index on a collection.
*
* @method
* @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order.
* @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order.
* @param {object} [options=null] Optional settings.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {number} [options.maxDistance=null] Include results up to maxDistance from the point.
* @param {object} [options.search=null] Filter the results by a query.
* @param {number} [options.limit=false] Max number of results to return.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.geoHaystackSearch = function(x, y, options, callback) {
const args = Array.prototype.slice.call(arguments, 2);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
options = args.length ? args.shift() || {} : {};
return executeOperation(this.s.topology, geoHaystackSearch, [this, x, y, options, callback]);
};
/**
* Run a group command across a collection
*
* @method
* @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by.
* @param {object} condition An optional condition that must be true for a row to be considered.
* @param {object} initial Initial value of the aggregation counter object.
* @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated
* @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned.
* @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true.
* @param {object} [options=null] Optional settings.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
* @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework.
*/
Collection.prototype.group = function(
keys,
condition,
initial,
reduce,
finalize,
command,
options,
callback
) {
const args = Array.prototype.slice.call(arguments, 3);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
reduce = args.length ? args.shift() : null;
finalize = args.length ? args.shift() : null;
command = args.length ? args.shift() : null;
options = args.length ? args.shift() || {} : {};
// Make sure we are backward compatible
if (!(typeof finalize === 'function')) {
command = finalize;
finalize = null;
}
if (
!Array.isArray(keys) &&
keys instanceof Object &&
typeof keys !== 'function' &&
!(keys._bsontype === 'Code')
) {
keys = Object.keys(keys);
}
if (typeof reduce === 'function') {
reduce = reduce.toString();
}
if (typeof finalize === 'function') {
finalize = finalize.toString();
}
// Set up the command as default
command = command == null ? true : command;
return executeOperation(this.s.topology, group, [
this,
keys,
condition,
initial,
reduce,
finalize,
command,
options,
callback
]);
};
/**
* Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection.
*
* @method
* @param {(function|string)} map The mapping function.
* @param {(function|string)} reduce The reduce function.
* @param {object} [options=null] Optional settings.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}*
* @param {object} [options.query=null] Query filter object.
* @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces.
* @param {number} [options.limit=null] Number of objects to return from collection.
* @param {boolean} [options.keeptemp=false] Keep temporary data.
* @param {(function|string)} [options.finalize=null] Finalize function.
* @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize.
* @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X.
* @param {boolean} [options.verbose=false] Provide statistics on job execution time.
* @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Collection~resultCallback} [callback] The command result callback
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
*/
Collection.prototype.mapReduce = function(map, reduce, options, callback) {
if ('function' === typeof options) (callback = options), (options = {});
// Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers)
if (null == options.out) {
throw new Error(
'the out option parameter must be defined, see mongodb docs for possible values'
);
}
if ('function' === typeof map) {
map = map.toString();
}
if ('function' === typeof reduce) {
reduce = reduce.toString();
}
if ('function' === typeof options.finalize) {
options.finalize = options.finalize.toString();
}
return executeOperation(this.s.topology, mapReduce, [this, map, reduce, options, callback]);
};
/**
* Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
*
* @method
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {ClientSession} [options.session] optional session to use for this operation
* @return {UnorderedBulkOperation}
*/
Collection.prototype.initializeUnorderedBulkOp = function(options) {
options = options || {};
options.promiseLibrary = this.s.promiseLibrary;
return unordered(this.s.topology, this, options);
};
/**
* Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.
*
* @method
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {OrderedBulkOperation} callback The command result callback
* @return {null}
*/
Collection.prototype.initializeOrderedBulkOp = function(options) {
options = options || {};
options.promiseLibrary = this.s.promiseLibrary;
return ordered(this.s.topology, this, options);
};
module.exports = Collection;
| 1 | 14,533 | I think this is somewhat definitive proof that this error exists in `core` rather than `native`. We are correctly resolving the `readPreference` in the previous line, but you are able to identify that eventually the command generated in `core` is not decorated with the passed `readPreference`. Did you try to solve this there already? | mongodb-node-mongodb-native | js |
@@ -91,8 +91,9 @@ func SpawnIntermediateHashesStage(s *StageState, u Unwinder, tx kv.RwTx, cfg Tri
if cfg.checkRoot && root != expectedRootHash {
log.Error(fmt.Sprintf("[%s] Wrong trie root of block %d: %x, expected (from header): %x. Block hash: %x", logPrefix, to, root, expectedRootHash, headerHash))
if to > s.BlockNumber {
- log.Warn("Unwinding due to incorrect root hash", "to", to-1)
- u.UnwindTo(to-1, headerHash)
+ unwindTo := (to + s.BlockNumber) / 2 // Binary search for the correct block, biased to the lower numbers
+ log.Warn("Unwinding due to incorrect root hash", "to", unwindTo)
+ u.UnwindTo(unwindTo, headerHash)
}
} else if err = s.Update(tx, to); err != nil {
return trie.EmptyRoot, err | 1 | package stagedsync
import (
"bytes"
"context"
"fmt"
"math/bits"
"os"
"sort"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/erigon/common"
"github.com/ledgerwatch/erigon/common/changeset"
"github.com/ledgerwatch/erigon/common/dbutils"
"github.com/ledgerwatch/erigon/common/etl"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/core/types/accounts"
"github.com/ledgerwatch/erigon/eth/stagedsync/stages"
"github.com/ledgerwatch/erigon/turbo/trie"
"github.com/ledgerwatch/log/v3"
)
type TrieCfg struct {
db kv.RwDB
checkRoot bool
tmpDir string
saveNewHashesToDB bool // no reason to save changes when calculating root for mining
}
func StageTrieCfg(db kv.RwDB, checkRoot, saveNewHashesToDB bool, tmpDir string) TrieCfg {
return TrieCfg{
db: db,
checkRoot: checkRoot,
tmpDir: tmpDir,
saveNewHashesToDB: saveNewHashesToDB,
}
}
func SpawnIntermediateHashesStage(s *StageState, u Unwinder, tx kv.RwTx, cfg TrieCfg, ctx context.Context) (common.Hash, error) {
quit := ctx.Done()
useExternalTx := tx != nil
if !useExternalTx {
var err error
tx, err = cfg.db.BeginRw(context.Background())
if err != nil {
return trie.EmptyRoot, err
}
defer tx.Rollback()
}
to, err := s.ExecutionAt(tx)
if err != nil {
return trie.EmptyRoot, err
}
if s.BlockNumber == to {
// we already did hash check for this block
// we don't do the obvious `if s.BlockNumber > to` to support reorgs more naturally
return trie.EmptyRoot, nil
}
var expectedRootHash common.Hash
var headerHash common.Hash
if cfg.checkRoot {
var hash common.Hash
hash, err = rawdb.ReadCanonicalHash(tx, to)
if err != nil {
return trie.EmptyRoot, err
}
syncHeadHeader := rawdb.ReadHeader(tx, hash, to)
expectedRootHash = syncHeadHeader.Root
headerHash = syncHeadHeader.Hash()
}
logPrefix := s.LogPrefix()
if to > s.BlockNumber+16 {
log.Info(fmt.Sprintf("[%s] Generating intermediate hashes", logPrefix), "from", s.BlockNumber, "to", to)
}
var root common.Hash
if s.BlockNumber == 0 {
if root, err = RegenerateIntermediateHashes(logPrefix, tx, cfg, expectedRootHash, quit); err != nil {
return trie.EmptyRoot, err
}
} else {
if root, err = incrementIntermediateHashes(logPrefix, s, tx, to, cfg, expectedRootHash, quit); err != nil {
return trie.EmptyRoot, err
}
}
if err == nil {
if cfg.checkRoot && root != expectedRootHash {
log.Error(fmt.Sprintf("[%s] Wrong trie root of block %d: %x, expected (from header): %x. Block hash: %x", logPrefix, to, root, expectedRootHash, headerHash))
if to > s.BlockNumber {
log.Warn("Unwinding due to incorrect root hash", "to", to-1)
u.UnwindTo(to-1, headerHash)
}
} else if err = s.Update(tx, to); err != nil {
return trie.EmptyRoot, err
}
} else {
return trie.EmptyRoot, err
}
if !useExternalTx {
if err := tx.Commit(); err != nil {
return trie.EmptyRoot, err
}
}
return root, err
}
func RegenerateIntermediateHashes(logPrefix string, db kv.RwTx, cfg TrieCfg, expectedRootHash common.Hash, quit <-chan struct{}) (common.Hash, error) {
log.Info(fmt.Sprintf("[%s] Regeneration trie hashes started", logPrefix))
defer log.Info(fmt.Sprintf("[%s] Regeneration ended", logPrefix))
_ = db.ClearBucket(kv.TrieOfAccounts)
_ = db.ClearBucket(kv.TrieOfStorage)
accTrieCollector := etl.NewCollector(cfg.tmpDir, etl.NewSortableBuffer(etl.BufferOptimalSize))
defer accTrieCollector.Close(logPrefix)
accTrieCollectorFunc := accountTrieCollector(accTrieCollector)
stTrieCollector := etl.NewCollector(cfg.tmpDir, etl.NewSortableBuffer(etl.BufferOptimalSize))
defer stTrieCollector.Close(logPrefix)
stTrieCollectorFunc := storageTrieCollector(stTrieCollector)
loader := trie.NewFlatDBTrieLoader(logPrefix)
if err := loader.Reset(trie.NewRetainList(0), accTrieCollectorFunc, stTrieCollectorFunc, false); err != nil {
return trie.EmptyRoot, err
}
hash, err := loader.CalcTrieRoot(db, []byte{}, quit)
if err != nil {
return trie.EmptyRoot, err
}
if cfg.checkRoot && hash != expectedRootHash {
return hash, nil
}
log.Info(fmt.Sprintf("[%s] Trie root", logPrefix), "hash", hash.Hex())
if err := accTrieCollector.Load(logPrefix, db, kv.TrieOfAccounts, etl.IdentityLoadFunc, etl.TransformArgs{Quit: quit}); err != nil {
return trie.EmptyRoot, err
}
if err := stTrieCollector.Load(logPrefix, db, kv.TrieOfStorage, etl.IdentityLoadFunc, etl.TransformArgs{Quit: quit}); err != nil {
return trie.EmptyRoot, err
}
return hash, nil
}
type HashPromoter struct {
db kv.RwTx
ChangeSetBufSize uint64
TempDir string
quitCh <-chan struct{}
}
func NewHashPromoter(db kv.RwTx, quitCh <-chan struct{}) *HashPromoter {
return &HashPromoter{
db: db,
ChangeSetBufSize: 256 * 1024 * 1024,
TempDir: os.TempDir(),
quitCh: quitCh,
}
}
func (p *HashPromoter) Promote(logPrefix string, s *StageState, from, to uint64, storage bool, load etl.LoadFunc) error {
var changeSetBucket string
if storage {
changeSetBucket = kv.StorageChangeSet
} else {
changeSetBucket = kv.AccountChangeSet
}
log.Debug(fmt.Sprintf("[%s] Incremental state promotion of intermediate hashes", logPrefix), "from", from, "to", to, "csbucket", changeSetBucket)
startkey := dbutils.EncodeBlockNumber(from + 1)
decode := changeset.Mapper[changeSetBucket].Decode
var deletedAccounts [][]byte
extract := func(dbKey, dbValue []byte, next etl.ExtractNextFunc) error {
_, k, v := decode(dbKey, dbValue)
newK, err := transformPlainStateKey(k)
if err != nil {
return err
}
if !storage {
newValue, err := p.db.GetOne(kv.PlainState, k)
if err != nil {
return err
}
if len(v) > 0 {
var oldAccount accounts.Account
if err := oldAccount.DecodeForStorage(v); err != nil {
return err
}
if oldAccount.Incarnation > 0 {
if len(newValue) == 0 { // self-destructed
deletedAccounts = append(deletedAccounts, newK)
} else { // turns incarnation to zero
var newAccount accounts.Account
if err := newAccount.DecodeForStorage(newValue); err != nil {
return err
}
if newAccount.Incarnation < oldAccount.Incarnation {
deletedAccounts = append(deletedAccounts, newK)
}
}
}
}
}
return next(dbKey, newK, v)
}
var l OldestAppearedLoad
l.innerLoadFunc = load
if err := etl.Transform(
logPrefix,
p.db,
changeSetBucket,
"",
p.TempDir,
extract,
l.LoadFunc,
etl.TransformArgs{
BufferType: etl.SortableOldestAppearedBuffer,
ExtractStartKey: startkey,
Quit: p.quitCh,
},
); err != nil {
return err
}
if !storage { // delete Intermediate hashes of deleted accounts
sort.Slice(deletedAccounts, func(i, j int) bool { return bytes.Compare(deletedAccounts[i], deletedAccounts[j]) < 0 })
for _, k := range deletedAccounts {
if err := p.db.ForPrefix(kv.TrieOfStorage, k, func(k, v []byte) error {
if err := p.db.Delete(kv.TrieOfStorage, k, v); err != nil {
return err
}
return nil
}); err != nil {
return err
}
}
return nil
}
return nil
}
func (p *HashPromoter) Unwind(logPrefix string, s *StageState, u *UnwindState, storage bool, load etl.LoadFunc) error {
to := u.UnwindPoint
var changeSetBucket string
if storage {
changeSetBucket = kv.StorageChangeSet
} else {
changeSetBucket = kv.AccountChangeSet
}
log.Info(fmt.Sprintf("[%s] Unwinding of trie hashes", logPrefix), "from", s.BlockNumber, "to", to, "csbucket", changeSetBucket)
startkey := dbutils.EncodeBlockNumber(to + 1)
decode := changeset.Mapper[changeSetBucket].Decode
var deletedAccounts [][]byte
extract := func(dbKey, dbValue []byte, next etl.ExtractNextFunc) error {
_, k, v := decode(dbKey, dbValue)
newK, err := transformPlainStateKey(k)
if err != nil {
return err
}
// Plain state not unwind yet, it means - if key not-exists in PlainState but has value from ChangeSets - then need mark it as "created" in RetainList
value, err := p.db.GetOne(kv.PlainState, k)
if err != nil {
return err
}
if !storage && len(value) > 0 {
var oldAccount accounts.Account
if err = oldAccount.DecodeForStorage(value); err != nil {
return err
}
if oldAccount.Incarnation > 0 {
if len(v) == 0 { // self-destructed
deletedAccounts = append(deletedAccounts, newK)
} else {
var newAccount accounts.Account
if err = newAccount.DecodeForStorage(v); err != nil {
return err
}
if newAccount.Incarnation > oldAccount.Incarnation {
deletedAccounts = append(deletedAccounts, newK)
}
}
}
}
return next(k, newK, value)
}
var l OldestAppearedLoad
l.innerLoadFunc = load
if err := etl.Transform(
logPrefix,
p.db,
changeSetBucket,
"",
p.TempDir,
extract,
l.LoadFunc,
etl.TransformArgs{
BufferType: etl.SortableOldestAppearedBuffer,
ExtractStartKey: startkey,
Quit: p.quitCh,
},
); err != nil {
return err
}
if !storage { // delete Intermediate hashes of deleted accounts
sort.Slice(deletedAccounts, func(i, j int) bool { return bytes.Compare(deletedAccounts[i], deletedAccounts[j]) < 0 })
for _, k := range deletedAccounts {
if err := p.db.ForPrefix(kv.TrieOfStorage, k, func(k, v []byte) error {
if err := p.db.Delete(kv.TrieOfStorage, k, v); err != nil {
return err
}
return nil
}); err != nil {
return err
}
}
return nil
}
return nil
}
func incrementIntermediateHashes(logPrefix string, s *StageState, db kv.RwTx, to uint64, cfg TrieCfg, expectedRootHash common.Hash, quit <-chan struct{}) (common.Hash, error) {
p := NewHashPromoter(db, quit)
p.TempDir = cfg.tmpDir
rl := trie.NewRetainList(0)
collect := func(k, v []byte, _ etl.CurrentTableReader, _ etl.LoadNextFunc) error {
rl.AddKeyWithMarker(k, len(v) == 0)
return nil
}
if err := p.Promote(logPrefix, s, s.BlockNumber, to, false /* storage */, collect); err != nil {
return trie.EmptyRoot, err
}
if err := p.Promote(logPrefix, s, s.BlockNumber, to, true /* storage */, collect); err != nil {
return trie.EmptyRoot, err
}
accTrieCollector := etl.NewCollector(cfg.tmpDir, etl.NewSortableBuffer(etl.BufferOptimalSize))
defer accTrieCollector.Close(logPrefix)
accTrieCollectorFunc := accountTrieCollector(accTrieCollector)
stTrieCollector := etl.NewCollector(cfg.tmpDir, etl.NewSortableBuffer(etl.BufferOptimalSize))
defer stTrieCollector.Close(logPrefix)
stTrieCollectorFunc := storageTrieCollector(stTrieCollector)
loader := trie.NewFlatDBTrieLoader(logPrefix)
if err := loader.Reset(rl, accTrieCollectorFunc, stTrieCollectorFunc, false); err != nil {
return trie.EmptyRoot, err
}
hash, err := loader.CalcTrieRoot(db, []byte{}, quit)
if err != nil {
return trie.EmptyRoot, err
}
if cfg.checkRoot && hash != expectedRootHash {
return hash, nil
}
if err := accTrieCollector.Load(logPrefix, db, kv.TrieOfAccounts, etl.IdentityLoadFunc, etl.TransformArgs{Quit: quit}); err != nil {
return trie.EmptyRoot, err
}
if err := stTrieCollector.Load(logPrefix, db, kv.TrieOfStorage, etl.IdentityLoadFunc, etl.TransformArgs{Quit: quit}); err != nil {
return trie.EmptyRoot, err
}
return hash, nil
}
func UnwindIntermediateHashesStage(u *UnwindState, s *StageState, tx kv.RwTx, cfg TrieCfg, ctx context.Context) (err error) {
quit := ctx.Done()
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(ctx)
if err != nil {
return err
}
defer tx.Rollback()
}
hash, err := rawdb.ReadCanonicalHash(tx, u.UnwindPoint)
if err != nil {
return fmt.Errorf("read canonical hash: %w", err)
}
syncHeadHeader := rawdb.ReadHeader(tx, hash, u.UnwindPoint)
expectedRootHash := syncHeadHeader.Root
//fmt.Printf("\n\nu: %d->%d\n", s.BlockNumber, u.UnwindPoint)
// if cache != nil {
// if err = cacheWarmUpIfNeed(tx, cache); err != nil {
// return err
// }
// }
logPrefix := s.LogPrefix()
if err := unwindIntermediateHashesStageImpl(logPrefix, u, s, tx, cfg, expectedRootHash, quit); err != nil {
return err
}
if err := u.Done(tx); err != nil {
return err
}
if !useExternalTx {
if err := tx.Commit(); err != nil {
return err
}
}
return nil
}
func unwindIntermediateHashesStageImpl(logPrefix string, u *UnwindState, s *StageState, db kv.RwTx, cfg TrieCfg, expectedRootHash common.Hash, quit <-chan struct{}) error {
p := NewHashPromoter(db, quit)
p.TempDir = cfg.tmpDir
rl := trie.NewRetainList(0)
collect := func(k, v []byte, _ etl.CurrentTableReader, _ etl.LoadNextFunc) error {
rl.AddKeyWithMarker(k, len(v) == 0)
return nil
}
if err := p.Unwind(logPrefix, s, u, false /* storage */, collect); err != nil {
return err
}
if err := p.Unwind(logPrefix, s, u, true /* storage */, collect); err != nil {
return err
}
accTrieCollector := etl.NewCollector(cfg.tmpDir, etl.NewSortableBuffer(etl.BufferOptimalSize))
defer accTrieCollector.Close(logPrefix)
accTrieCollectorFunc := accountTrieCollector(accTrieCollector)
stTrieCollector := etl.NewCollector(cfg.tmpDir, etl.NewSortableBuffer(etl.BufferOptimalSize))
defer stTrieCollector.Close(logPrefix)
stTrieCollectorFunc := storageTrieCollector(stTrieCollector)
loader := trie.NewFlatDBTrieLoader(logPrefix)
if err := loader.Reset(rl, accTrieCollectorFunc, stTrieCollectorFunc, false); err != nil {
return err
}
hash, err := loader.CalcTrieRoot(db, []byte{}, quit)
if err != nil {
return err
}
if hash != expectedRootHash {
return fmt.Errorf("wrong trie root: %x, expected (from header): %x", hash, expectedRootHash)
}
log.Info(fmt.Sprintf("[%s] Trie root", logPrefix), "hash", hash.Hex())
if err := accTrieCollector.Load(logPrefix, db, kv.TrieOfAccounts, etl.IdentityLoadFunc, etl.TransformArgs{Quit: quit}); err != nil {
return err
}
if err := stTrieCollector.Load(logPrefix, db, kv.TrieOfStorage, etl.IdentityLoadFunc, etl.TransformArgs{Quit: quit}); err != nil {
return err
}
return nil
}
func ResetHashState(tx kv.RwTx) error {
if err := tx.ClearBucket(kv.HashedAccounts); err != nil {
return err
}
if err := tx.ClearBucket(kv.HashedStorage); err != nil {
return err
}
if err := tx.ClearBucket(kv.ContractCode); err != nil {
return err
}
if err := stages.SaveStageProgress(tx, stages.HashState, 0); err != nil {
return err
}
if err := stages.SaveStagePruneProgress(tx, stages.HashState, 0); err != nil {
return err
}
return nil
}
func ResetIH(tx kv.RwTx) error {
if err := tx.ClearBucket(kv.TrieOfAccounts); err != nil {
return err
}
if err := tx.ClearBucket(kv.TrieOfStorage); err != nil {
return err
}
if err := stages.SaveStageProgress(tx, stages.IntermediateHashes, 0); err != nil {
return err
}
if err := stages.SaveStagePruneProgress(tx, stages.IntermediateHashes, 0); err != nil {
return err
}
return nil
}
func assertSubset(a, b uint16) {
if (a & b) != a { // a & b == a - checks whether a is subset of b
panic(fmt.Errorf("invariant 'is subset' failed: %b, %b", a, b))
}
}
func accountTrieCollector(collector *etl.Collector) trie.HashCollector2 {
newV := make([]byte, 0, 1024)
return func(keyHex []byte, hasState, hasTree, hasHash uint16, hashes, _ []byte) error {
if len(keyHex) == 0 {
return nil
}
if hasState == 0 {
return collector.Collect(keyHex, nil)
}
if bits.OnesCount16(hasHash) != len(hashes)/common.HashLength {
panic(fmt.Errorf("invariant bits.OnesCount16(hasHash) == len(hashes) failed: %d, %d", bits.OnesCount16(hasHash), len(hashes)/common.HashLength))
}
assertSubset(hasTree, hasState)
assertSubset(hasHash, hasState)
newV = trie.MarshalTrieNode(hasState, hasTree, hasHash, hashes, nil, newV)
return collector.Collect(keyHex, newV)
}
}
func storageTrieCollector(collector *etl.Collector) trie.StorageHashCollector2 {
newK := make([]byte, 0, 128)
newV := make([]byte, 0, 1024)
return func(accWithInc []byte, keyHex []byte, hasState, hasTree, hasHash uint16, hashes, rootHash []byte) error {
newK = append(append(newK[:0], accWithInc...), keyHex...)
if hasState == 0 {
return collector.Collect(newK, nil)
}
if len(keyHex) > 0 && hasHash == 0 && hasTree == 0 {
return nil
}
if bits.OnesCount16(hasHash) != len(hashes)/common.HashLength {
panic(fmt.Errorf("invariant bits.OnesCount16(hasHash) == len(hashes) failed: %d, %d", bits.OnesCount16(hasHash), len(hashes)/common.HashLength))
}
assertSubset(hasTree, hasState)
assertSubset(hasHash, hasState)
newV = trie.MarshalTrieNode(hasState, hasTree, hasHash, hashes, rootHash, newV)
return collector.Collect(newK, newV)
}
}
func PruneIntermediateHashesStage(s *PruneState, tx kv.RwTx, cfg TrieCfg, ctx context.Context) (err error) {
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(ctx)
if err != nil {
return err
}
defer tx.Rollback()
}
s.Done(tx)
if !useExternalTx {
if err = tx.Commit(); err != nil {
return err
}
}
return nil
}
| 1 | 22,507 | During genesis sync it can unwind 5M blocks? | ledgerwatch-erigon | go |
@@ -852,6 +852,7 @@ func (s *matchingEngineSuite) TestConcurrentPublishConsumeActivities() {
}
func (s *matchingEngineSuite) TestConcurrentPublishConsumeActivitiesWithZeroDispatch() {
+ s.T().Skip("Racy - times out ~50% of the time running locally with --race")
// Set a short long poll expiration so we don't have to wait too long for 0 throttling cases
s.matchingEngine.config.LongPollExpirationInterval = dynamicconfig.GetDurationPropertyFnFilteredByTaskQueueInfo(20 * time.Millisecond)
dispatchLimitFn := func(wc int, tc int64) float64 { | 1 | // The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package matching
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/emirpasic/gods/maps/treemap"
"github.com/gogo/protobuf/types"
"github.com/golang/mock/gomock"
"github.com/pborman/uuid"
"github.com/stretchr/testify/suite"
"github.com/uber-go/tally"
commandpb "go.temporal.io/api/command/v1"
commonpb "go.temporal.io/api/common/v1"
enumspb "go.temporal.io/api/enums/v1"
historypb "go.temporal.io/api/history/v1"
"go.temporal.io/api/serviceerror"
taskqueuepb "go.temporal.io/api/taskqueue/v1"
"go.temporal.io/api/workflowservice/v1"
"go.temporal.io/server/api/historyservice/v1"
"go.temporal.io/server/api/historyservicemock/v1"
"go.temporal.io/server/api/matchingservice/v1"
persistencespb "go.temporal.io/server/api/persistence/v1"
tokenspb "go.temporal.io/server/api/token/v1"
"go.temporal.io/server/common"
"go.temporal.io/server/common/dynamicconfig"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
"go.temporal.io/server/common/metrics"
"go.temporal.io/server/common/namespace"
"go.temporal.io/server/common/payload"
"go.temporal.io/server/common/payloads"
"go.temporal.io/server/common/persistence"
"go.temporal.io/server/common/primitives/timestamp"
"go.temporal.io/server/common/quotas"
serviceerrors "go.temporal.io/server/common/serviceerror"
)
type (
matchingEngineSuite struct {
suite.Suite
controller *gomock.Controller
mockHistoryClient *historyservicemock.MockHistoryServiceClient
mockNamespaceCache *namespace.MockCache
matchingEngine *matchingEngineImpl
taskManager *testTaskManager
logger log.Logger
handlerContext *handlerContext
sync.Mutex
}
)
const (
matchingTestNamespace = "matching-test"
matchingTestTaskQueue = "matching-test-taskqueue"
)
func TestMatchingEngineSuite(t *testing.T) {
s := new(matchingEngineSuite)
suite.Run(t, s)
}
func (s *matchingEngineSuite) SetupSuite() {
}
func (s *matchingEngineSuite) TearDownSuite() {
}
func (s *matchingEngineSuite) SetupTest() {
s.logger = log.NewTestLogger()
s.Lock()
defer s.Unlock()
s.controller = gomock.NewController(s.T())
s.mockHistoryClient = historyservicemock.NewMockHistoryServiceClient(s.controller)
s.taskManager = newTestTaskManager(s.logger)
s.mockNamespaceCache = namespace.NewMockCache(s.controller)
s.mockNamespaceCache.EXPECT().GetNamespaceByID(gomock.Any()).Return(namespace.CreateNamespaceCacheEntry(matchingTestNamespace), nil).AnyTimes()
s.handlerContext = newHandlerContext(
context.Background(),
matchingTestNamespace,
&taskqueuepb.TaskQueue{Name: matchingTestTaskQueue, Kind: enumspb.TASK_QUEUE_KIND_NORMAL},
metrics.NewClient(tally.NoopScope, metrics.Matching),
metrics.MatchingTaskQueueMgrScope,
log.NewNoopLogger(),
)
s.matchingEngine = s.newMatchingEngine(defaultTestConfig(), s.taskManager)
s.matchingEngine.Start()
}
func (s *matchingEngineSuite) TearDownTest() {
s.matchingEngine.Stop()
s.controller.Finish()
}
func (s *matchingEngineSuite) newMatchingEngine(
config *Config, taskMgr persistence.TaskManager,
) *matchingEngineImpl {
return newMatchingEngine(config, taskMgr, s.mockHistoryClient, s.logger, s.mockNamespaceCache)
}
func newMatchingEngine(
config *Config, taskMgr persistence.TaskManager, mockHistoryClient historyservice.HistoryServiceClient,
logger log.Logger, mockNamespaceCache namespace.Cache,
) *matchingEngineImpl {
return &matchingEngineImpl{
taskManager: taskMgr,
historyService: mockHistoryClient,
taskQueues: make(map[taskQueueID]taskQueueManager),
logger: logger,
metricsClient: metrics.NewClient(tally.NoopScope, metrics.Matching),
tokenSerializer: common.NewProtoTaskTokenSerializer(),
config: config,
namespaceCache: mockNamespaceCache,
}
}
func (s *matchingEngineSuite) TestAckManager() {
m := newAckManager(s.logger)
m.setAckLevel(100)
s.EqualValues(100, m.getAckLevel())
s.EqualValues(100, m.getReadLevel())
const t1 = 200
const t2 = 220
const t3 = 320
const t4 = 340
const t5 = 360
m.addTask(t1)
s.EqualValues(100, m.getAckLevel())
s.EqualValues(t1, m.getReadLevel())
m.addTask(t2)
s.EqualValues(100, m.getAckLevel())
s.EqualValues(t2, m.getReadLevel())
m.completeTask(t2)
s.EqualValues(100, m.getAckLevel())
s.EqualValues(t2, m.getReadLevel())
m.completeTask(t1)
s.EqualValues(t2, m.getAckLevel())
s.EqualValues(t2, m.getReadLevel())
m.setAckLevel(300)
s.EqualValues(300, m.getAckLevel())
s.EqualValues(300, m.getReadLevel())
m.addTask(t3)
s.EqualValues(300, m.getAckLevel())
s.EqualValues(t3, m.getReadLevel())
m.addTask(t4)
s.EqualValues(300, m.getAckLevel())
s.EqualValues(t4, m.getReadLevel())
m.completeTask(t3)
s.EqualValues(t3, m.getAckLevel())
s.EqualValues(t4, m.getReadLevel())
m.completeTask(t4)
s.EqualValues(t4, m.getAckLevel())
s.EqualValues(t4, m.getReadLevel())
m.setReadLevel(t5)
s.EqualValues(t5, m.getReadLevel())
}
func (s *matchingEngineSuite) TestAckManager_Sort() {
m := newAckManager(s.logger)
const t0 = 100
m.setAckLevel(t0)
s.EqualValues(t0, m.getAckLevel())
s.EqualValues(t0, m.getReadLevel())
const t1 = 200
const t2 = 220
const t3 = 320
const t4 = 340
const t5 = 360
m.addTask(t1)
m.addTask(t2)
m.addTask(t3)
m.addTask(t4)
m.addTask(t5)
m.completeTask(t2)
s.EqualValues(t0, m.getAckLevel())
m.completeTask(t1)
s.EqualValues(t2, m.getAckLevel())
m.completeTask(t5)
s.EqualValues(t2, m.getAckLevel())
m.completeTask(t4)
s.EqualValues(t2, m.getAckLevel())
m.completeTask(t3)
s.EqualValues(t5, m.getAckLevel())
}
func (s *matchingEngineSuite) TestPollActivityTaskQueuesEmptyResult() {
s.PollForTasksEmptyResultTest(context.Background(), enumspb.TASK_QUEUE_TYPE_ACTIVITY)
}
func (s *matchingEngineSuite) TestPollWorkflowTaskQueuesEmptyResult() {
s.PollForTasksEmptyResultTest(context.Background(), enumspb.TASK_QUEUE_TYPE_WORKFLOW)
}
func (s *matchingEngineSuite) TestPollActivityTaskQueuesEmptyResultWithShortContext() {
shortContextTimeout := returnEmptyTaskTimeBudget + 10*time.Millisecond
callContext, cancel := context.WithTimeout(context.Background(), shortContextTimeout)
defer cancel()
s.PollForTasksEmptyResultTest(callContext, enumspb.TASK_QUEUE_TYPE_ACTIVITY)
}
func (s *matchingEngineSuite) TestPollWorkflowTaskQueuesEmptyResultWithShortContext() {
shortContextTimeout := returnEmptyTaskTimeBudget + 10*time.Millisecond
callContext, cancel := context.WithTimeout(context.Background(), shortContextTimeout)
defer cancel()
s.PollForTasksEmptyResultTest(callContext, enumspb.TASK_QUEUE_TYPE_WORKFLOW)
}
func (s *matchingEngineSuite) TestOnlyUnloadMatchingInstance() {
queueID := newTestTaskQueueID(
uuid.New(),
"makeToast",
enumspb.TASK_QUEUE_TYPE_ACTIVITY)
tqm, err := s.matchingEngine.getTaskQueueManager(
queueID,
enumspb.TASK_QUEUE_KIND_NORMAL)
s.Require().NoError(err)
tqm2, err := newTaskQueueManager(
s.matchingEngine,
queueID, // same queueID as above
enumspb.TASK_QUEUE_KIND_NORMAL,
s.matchingEngine.config)
s.Require().NoError(err)
// try to unload a different tqm instance with the same taskqueue ID
s.matchingEngine.unloadTaskQueue(tqm2)
got, err := s.matchingEngine.getTaskQueueManager(
queueID, enumspb.TASK_QUEUE_KIND_NORMAL)
s.Require().NoError(err)
s.Require().Same(tqm, got,
"Unload call with non-matching taskQueueManager should not cause unload")
// this time unload the right tqm
s.matchingEngine.unloadTaskQueue(tqm)
got, err = s.matchingEngine.getTaskQueueManager(
queueID, enumspb.TASK_QUEUE_KIND_NORMAL)
s.Require().NoError(err)
s.Require().NotSame(tqm, got,
"Unload call with matching incarnation should have caused unload")
}
func (s *matchingEngineSuite) TestPollWorkflowTaskQueues() {
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
stickyTl := "makeStickyToast"
stickyTlKind := enumspb.TASK_QUEUE_KIND_STICKY
identity := "selfDrivingToaster"
stickyTaskQueue := &taskqueuepb.TaskQueue{Name: stickyTl, Kind: stickyTlKind}
s.matchingEngine.config.RangeSize = 2 // to test that range is not updated without tasks
s.matchingEngine.config.LongPollExpirationInterval = dynamicconfig.GetDurationPropertyFnFilteredByTaskQueueInfo(10 * time.Millisecond)
runID := uuid.NewRandom().String()
workflowID := "workflow1"
workflowType := &commonpb.WorkflowType{
Name: "workflow",
}
execution := &commonpb.WorkflowExecution{RunId: runID, WorkflowId: workflowID}
scheduleID := int64(0)
// History service is using mock
s.mockHistoryClient.EXPECT().RecordWorkflowTaskStarted(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(ctx context.Context, taskRequest *historyservice.RecordWorkflowTaskStartedRequest, arg2 ...interface{}) (*historyservice.RecordWorkflowTaskStartedResponse, error) {
s.logger.Debug("Mock Received RecordWorkflowTaskStartedRequest")
response := &historyservice.RecordWorkflowTaskStartedResponse{
WorkflowType: workflowType,
PreviousStartedEventId: scheduleID,
ScheduledEventId: scheduleID + 1,
Attempt: 1,
StickyExecutionEnabled: true,
WorkflowExecutionTaskQueue: &taskqueuepb.TaskQueue{Name: tl, Kind: enumspb.TASK_QUEUE_KIND_NORMAL},
}
return response, nil
}).AnyTimes()
addRequest := matchingservice.AddWorkflowTaskRequest{
NamespaceId: namespaceID,
Execution: execution,
ScheduleId: scheduleID,
TaskQueue: stickyTaskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(1),
}
_, err := s.matchingEngine.AddWorkflowTask(s.handlerContext, &addRequest)
s.NoError(err)
resp, err := s.matchingEngine.PollWorkflowTaskQueue(s.handlerContext, &matchingservice.PollWorkflowTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollWorkflowTaskQueueRequest{
TaskQueue: stickyTaskQueue,
Identity: identity},
})
s.NoError(err)
expectedResp := &matchingservice.PollWorkflowTaskQueueResponse{
TaskToken: resp.TaskToken,
WorkflowExecution: execution,
WorkflowType: workflowType,
PreviousStartedEventId: scheduleID,
StartedEventId: common.EmptyEventID,
Attempt: 1,
NextEventId: common.EmptyEventID,
BacklogCountHint: 1,
StickyExecutionEnabled: true,
Query: nil,
WorkflowTaskInfo: nil,
WorkflowExecutionTaskQueue: &taskqueuepb.TaskQueue{
Name: tl,
Kind: enumspb.TASK_QUEUE_KIND_NORMAL,
},
BranchToken: nil,
ScheduledTime: nil,
StartedTime: nil,
Queries: nil,
}
s.Nil(err)
s.Equal(expectedResp, resp)
}
func (s *matchingEngineSuite) PollForTasksEmptyResultTest(callContext context.Context, taskType enumspb.TaskQueueType) {
s.matchingEngine.config.RangeSize = 2 // to test that range is not updated without tasks
if _, ok := callContext.Deadline(); !ok {
s.matchingEngine.config.LongPollExpirationInterval = dynamicconfig.GetDurationPropertyFnFilteredByTaskQueueInfo(10 * time.Millisecond)
}
namespaceID := uuid.New()
tl := "makeToast"
identity := "selfDrivingToaster"
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
var taskQueueType enumspb.TaskQueueType
tlID := newTestTaskQueueID(namespaceID, tl, taskType)
s.handlerContext.Context = callContext
const pollCount = 10
for i := 0; i < pollCount; i++ {
if taskType == enumspb.TASK_QUEUE_TYPE_ACTIVITY {
pollResp, err := s.matchingEngine.PollActivityTaskQueue(s.handlerContext, &matchingservice.PollActivityTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollActivityTaskQueueRequest{
TaskQueue: taskQueue,
Identity: identity,
},
})
s.NoError(err)
s.Equal(emptyPollActivityTaskQueueResponse, pollResp)
taskQueueType = enumspb.TASK_QUEUE_TYPE_ACTIVITY
} else {
resp, err := s.matchingEngine.PollWorkflowTaskQueue(s.handlerContext, &matchingservice.PollWorkflowTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollWorkflowTaskQueueRequest{
TaskQueue: taskQueue,
Identity: identity},
})
s.NoError(err)
s.Equal(emptyPollWorkflowTaskQueueResponse, resp)
taskQueueType = enumspb.TASK_QUEUE_TYPE_WORKFLOW
}
select {
case <-callContext.Done():
s.FailNow("Call context has expired.")
default:
}
// check the poller information
s.handlerContext.Context = context.Background()
descResp, err := s.matchingEngine.DescribeTaskQueue(s.handlerContext, &matchingservice.DescribeTaskQueueRequest{
NamespaceId: namespaceID,
DescRequest: &workflowservice.DescribeTaskQueueRequest{
TaskQueue: taskQueue,
TaskQueueType: taskQueueType,
IncludeTaskQueueStatus: false,
},
})
s.NoError(err)
s.Equal(1, len(descResp.Pollers))
s.Equal(identity, descResp.Pollers[0].GetIdentity())
s.NotEmpty(descResp.Pollers[0].GetLastAccessTime())
s.Nil(descResp.GetTaskQueueStatus())
}
s.EqualValues(1, s.taskManager.getTaskQueueManager(tlID).RangeID())
}
func (s *matchingEngineSuite) TestAddActivityTasks() {
s.AddTasksTest(enumspb.TASK_QUEUE_TYPE_ACTIVITY, false)
}
func (s *matchingEngineSuite) TestAddWorkflowTasks() {
s.AddTasksTest(enumspb.TASK_QUEUE_TYPE_WORKFLOW, false)
}
func (s *matchingEngineSuite) TestAddWorkflowTasksForwarded() {
s.AddTasksTest(enumspb.TASK_QUEUE_TYPE_WORKFLOW, true)
}
func (s *matchingEngineSuite) AddTasksTest(taskType enumspb.TaskQueueType, isForwarded bool) {
s.matchingEngine.config.RangeSize = 300 // override to low number for the test
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
forwardedFrom := "/_sys/makeToast/1"
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
const taskCount = 111
runID := uuid.NewRandom().String()
workflowID := "workflow1"
execution := &commonpb.WorkflowExecution{RunId: runID, WorkflowId: workflowID}
for i := int64(0); i < taskCount; i++ {
scheduleID := i * 3
var err error
if taskType == enumspb.TASK_QUEUE_TYPE_ACTIVITY {
addRequest := matchingservice.AddActivityTaskRequest{
SourceNamespaceId: namespaceID,
NamespaceId: namespaceID,
Execution: execution,
ScheduleId: scheduleID,
TaskQueue: taskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(1),
}
if isForwarded {
addRequest.ForwardedSource = forwardedFrom
}
_, err = s.matchingEngine.AddActivityTask(s.handlerContext, &addRequest)
} else {
addRequest := matchingservice.AddWorkflowTaskRequest{
NamespaceId: namespaceID,
Execution: execution,
ScheduleId: scheduleID,
TaskQueue: taskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(1),
}
if isForwarded {
addRequest.ForwardedSource = forwardedFrom
}
_, err = s.matchingEngine.AddWorkflowTask(s.handlerContext, &addRequest)
}
switch isForwarded {
case false:
s.NoError(err)
case true:
s.Equal(errRemoteSyncMatchFailed, err)
}
}
switch isForwarded {
case false:
s.EqualValues(taskCount, s.taskManager.getTaskCount(newTestTaskQueueID(namespaceID, tl, taskType)))
case true:
s.EqualValues(0, s.taskManager.getTaskCount(newTestTaskQueueID(namespaceID, tl, taskType)))
}
}
func (s *matchingEngineSuite) TestTaskWriterShutdown() {
s.matchingEngine.config.RangeSize = 300 // override to low number for the test
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
runID := uuid.NewRandom().String()
workflowID := "workflow1"
execution := &commonpb.WorkflowExecution{RunId: runID, WorkflowId: workflowID}
tlID := newTestTaskQueueID(namespaceID, tl, enumspb.TASK_QUEUE_TYPE_ACTIVITY)
tlKind := enumspb.TASK_QUEUE_KIND_NORMAL
tlm, err := s.matchingEngine.getTaskQueueManager(tlID, tlKind)
s.Nil(err)
addRequest := matchingservice.AddActivityTaskRequest{
SourceNamespaceId: namespaceID,
NamespaceId: namespaceID,
Execution: execution,
TaskQueue: taskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(1),
}
// stop the task writer explicitly
tlmImpl := tlm.(*taskQueueManagerImpl)
tlmImpl.taskWriter.Stop()
// now attempt to add a task
scheduleID := int64(5)
addRequest.ScheduleId = scheduleID
_, err = s.matchingEngine.AddActivityTask(s.handlerContext, &addRequest)
s.Error(err)
}
func (s *matchingEngineSuite) TestAddThenConsumeActivities() {
s.matchingEngine.config.LongPollExpirationInterval = dynamicconfig.GetDurationPropertyFnFilteredByTaskQueueInfo(10 * time.Millisecond)
runID := uuid.NewRandom().String()
workflowID := "workflow1"
workflowExecution := &commonpb.WorkflowExecution{RunId: runID, WorkflowId: workflowID}
const taskCount = 1000
const initialRangeID = 102
// TODO: Understand why publish is low when rangeSize is 3
const rangeSize = 30
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
tlID := newTestTaskQueueID(namespaceID, tl, enumspb.TASK_QUEUE_TYPE_ACTIVITY)
s.taskManager.getTaskQueueManager(tlID).rangeID = initialRangeID
s.matchingEngine.config.RangeSize = rangeSize // override to low number for the test
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
for i := int64(0); i < taskCount; i++ {
scheduleID := i * 3
addRequest := matchingservice.AddActivityTaskRequest{
SourceNamespaceId: namespaceID,
NamespaceId: namespaceID,
Execution: workflowExecution,
ScheduleId: scheduleID,
TaskQueue: taskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(1),
}
_, err := s.matchingEngine.AddActivityTask(s.handlerContext, &addRequest)
s.NoError(err)
}
s.EqualValues(taskCount, s.taskManager.getTaskCount(tlID))
activityTypeName := "activity1"
activityID := "activityId1"
activityType := &commonpb.ActivityType{Name: activityTypeName}
activityInput := payloads.EncodeString("Activity1 Input")
identity := "nobody"
// History service is using mock
s.mockHistoryClient.EXPECT().RecordActivityTaskStarted(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(ctx context.Context, taskRequest *historyservice.RecordActivityTaskStartedRequest, arg2 ...interface{}) (*historyservice.RecordActivityTaskStartedResponse, error) {
s.logger.Debug("Mock Received RecordActivityTaskStartedRequest")
resp := &historyservice.RecordActivityTaskStartedResponse{
Attempt: 1,
ScheduledEvent: newActivityTaskScheduledEvent(taskRequest.ScheduleId, 0,
&commandpb.ScheduleActivityTaskCommandAttributes{
ActivityId: activityID,
TaskQueue: &taskqueuepb.TaskQueue{Name: taskQueue.Name},
ActivityType: activityType,
Input: activityInput,
ScheduleToCloseTimeout: timestamp.DurationPtr(100 * time.Second),
ScheduleToStartTimeout: timestamp.DurationPtr(50 * time.Second),
StartToCloseTimeout: timestamp.DurationPtr(50 * time.Second),
HeartbeatTimeout: timestamp.DurationPtr(10 * time.Second),
}),
}
resp.StartedTime = timestamp.TimeNowPtrUtc()
return resp, nil
}).AnyTimes()
for i := int64(0); i < taskCount; {
scheduleID := i * 3
result, err := s.matchingEngine.PollActivityTaskQueue(s.handlerContext, &matchingservice.PollActivityTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollActivityTaskQueueRequest{
TaskQueue: taskQueue,
Identity: identity},
})
s.NoError(err)
s.NotNil(result)
if len(result.TaskToken) == 0 {
s.logger.Debug("empty poll returned")
continue
}
s.EqualValues(activityID, result.ActivityId)
s.EqualValues(activityType, result.ActivityType)
s.EqualValues(activityInput, result.Input)
s.EqualValues(workflowExecution, result.WorkflowExecution)
s.Equal(true, validateTimeRange(*result.ScheduledTime, time.Minute))
s.EqualValues(time.Second*100, *result.ScheduleToCloseTimeout)
s.Equal(true, validateTimeRange(*result.StartedTime, time.Minute))
s.EqualValues(time.Second*50, *result.StartToCloseTimeout)
s.EqualValues(time.Second*10, *result.HeartbeatTimeout)
taskToken := &tokenspb.Task{
ScheduleAttempt: 1,
NamespaceId: namespaceID,
WorkflowId: workflowID,
RunId: runID,
ScheduleId: scheduleID,
ActivityId: activityID,
ActivityType: activityTypeName,
}
serializedToken, _ := s.matchingEngine.tokenSerializer.Serialize(taskToken)
s.EqualValues(serializedToken, result.TaskToken)
i++
}
s.EqualValues(0, s.taskManager.getTaskCount(tlID))
expectedRange := int64(initialRangeID + taskCount/rangeSize)
if taskCount%rangeSize > 0 {
expectedRange++
}
// Due to conflicts some ids are skipped and more real ranges are used.
s.True(expectedRange <= s.taskManager.getTaskQueueManager(tlID).rangeID)
}
func (s *matchingEngineSuite) TestSyncMatchActivities() {
// Set a short long poll expiration so we don't have to wait too long for 0 throttling cases
s.matchingEngine.config.LongPollExpirationInterval = dynamicconfig.GetDurationPropertyFnFilteredByTaskQueueInfo(2 * time.Second)
runID := uuid.NewRandom().String()
workflowID := "workflow1"
workflowExecution := &commonpb.WorkflowExecution{RunId: runID, WorkflowId: workflowID}
const taskCount = 10
const initialRangeID = 102
// TODO: Understand why publish is low when rangeSize is 3
const rangeSize = 30
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
tlID := newTestTaskQueueID(namespaceID, tl, enumspb.TASK_QUEUE_TYPE_ACTIVITY)
tlKind := enumspb.TASK_QUEUE_KIND_NORMAL
s.matchingEngine.config.RangeSize = rangeSize // override to low number for the test
// So we can get snapshots
scope := tally.NewTestScope("test", nil)
s.matchingEngine.metricsClient = metrics.NewClient(scope, metrics.Matching)
s.taskManager.getTaskQueueManager(tlID).rangeID = initialRangeID
mgr, err := newTaskQueueManager(s.matchingEngine, tlID, tlKind, s.matchingEngine.config)
s.NoError(err)
mgrImpl, ok := mgr.(*taskQueueManagerImpl)
s.True(ok)
mgrImpl.matcher.config.MinTaskThrottlingBurstSize = func() int { return 0 }
mgrImpl.matcher.rateLimiter = quotas.NewRateLimiter(
defaultTaskDispatchRPS,
defaultTaskDispatchRPS,
)
mgrImpl.matcher.dynamicRate = &dynamicRateWrapper{
DynamicRate: quotas.NewDynamicRate(defaultTaskDispatchRPS),
RateLimiterImpl: mgrImpl.matcher.rateLimiter.(*quotas.RateLimiterImpl),
}
mgrImpl.matcher.dynamicBurst = &dynamicBurstWrapper{
DynamicBurst: quotas.NewDynamicBurst(defaultTaskDispatchRPS),
RateLimiterImpl: mgrImpl.matcher.rateLimiter.(*quotas.RateLimiterImpl),
}
s.matchingEngine.updateTaskQueue(tlID, mgr)
mgr.Start()
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
activityTypeName := "activity1"
activityID := "activityId1"
activityType := &commonpb.ActivityType{Name: activityTypeName}
activityInput := payloads.EncodeString("Activity1 Input")
identity := "nobody"
// History service is using mock
s.mockHistoryClient.EXPECT().RecordActivityTaskStarted(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(ctx context.Context, taskRequest *historyservice.RecordActivityTaskStartedRequest, arg2 ...interface{}) (*historyservice.RecordActivityTaskStartedResponse, error) {
s.logger.Debug("Mock Received RecordActivityTaskStartedRequest")
return &historyservice.RecordActivityTaskStartedResponse{
Attempt: 1,
ScheduledEvent: newActivityTaskScheduledEvent(taskRequest.ScheduleId, 0,
&commandpb.ScheduleActivityTaskCommandAttributes{
ActivityId: activityID,
TaskQueue: &taskqueuepb.TaskQueue{Name: taskQueue.Name},
ActivityType: activityType,
Input: activityInput,
ScheduleToStartTimeout: timestamp.DurationPtr(1 * time.Second),
ScheduleToCloseTimeout: timestamp.DurationPtr(2 * time.Second),
StartToCloseTimeout: timestamp.DurationPtr(1 * time.Second),
HeartbeatTimeout: timestamp.DurationPtr(1 * time.Second),
}),
}, nil
}).AnyTimes()
pollFunc := func(maxDispatch float64) (*matchingservice.PollActivityTaskQueueResponse, error) {
return s.matchingEngine.PollActivityTaskQueue(s.handlerContext, &matchingservice.PollActivityTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollActivityTaskQueueRequest{
TaskQueue: taskQueue,
Identity: identity,
TaskQueueMetadata: &taskqueuepb.TaskQueueMetadata{MaxTasksPerSecond: &types.DoubleValue{Value: maxDispatch}},
},
})
}
for i := int64(0); i < taskCount; i++ {
scheduleID := i * 3
var wg sync.WaitGroup
var result *matchingservice.PollActivityTaskQueueResponse
var pollErr error
maxDispatch := defaultTaskDispatchRPS
if i == taskCount/2 {
maxDispatch = 0
}
wg.Add(1)
go func() {
defer wg.Done()
result, pollErr = pollFunc(maxDispatch)
}()
time.Sleep(20 * time.Millisecond) // Necessary for sync match to happen
addRequest := matchingservice.AddActivityTaskRequest{
SourceNamespaceId: namespaceID,
NamespaceId: namespaceID,
Execution: workflowExecution,
ScheduleId: scheduleID,
TaskQueue: taskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(1),
}
_, err := s.matchingEngine.AddActivityTask(s.handlerContext, &addRequest)
wg.Wait()
s.NoError(err)
s.NoError(pollErr)
s.NotNil(result)
if len(result.TaskToken) == 0 {
// when ratelimit is set to zero, poller is expected to return empty result
// reset ratelimit, poll again and make sure task is returned this time
s.logger.Debug("empty poll returned")
s.Equal(float64(0), maxDispatch)
maxDispatch = defaultTaskDispatchRPS
wg.Add(1)
go func() {
defer wg.Done()
result, pollErr = pollFunc(maxDispatch)
}()
wg.Wait()
s.NoError(err)
s.NoError(pollErr)
s.NotNil(result)
s.True(len(result.TaskToken) > 0)
}
s.EqualValues(activityID, result.ActivityId)
s.EqualValues(activityType, result.ActivityType)
s.EqualValues(activityInput, result.Input)
s.EqualValues(workflowExecution, result.WorkflowExecution)
taskToken := &tokenspb.Task{
ScheduleAttempt: 1,
NamespaceId: namespaceID,
WorkflowId: workflowID,
RunId: runID,
ScheduleId: scheduleID,
ActivityId: activityID,
ActivityType: activityTypeName,
}
serializedToken, _ := s.matchingEngine.tokenSerializer.Serialize(taskToken)
// s.EqualValues(scheduleID, result.Task)
s.EqualValues(serializedToken, result.TaskToken)
}
time.Sleep(20 * time.Millisecond) // So any buffer tasks from 0 rps get picked up
syncCtr := scope.Snapshot().Counters()["test.sync_throttle_count_per_tl+namespace="+matchingTestNamespace+",operation=TaskQueueMgr,taskqueue=makeToast"]
s.Equal(1, int(syncCtr.Value())) // Check times zero rps is set = throttle counter
s.EqualValues(1, s.taskManager.getCreateTaskCount(tlID)) // Check times zero rps is set = Tasks stored in persistence
s.EqualValues(0, s.taskManager.getTaskCount(tlID))
expectedRange := int64(initialRangeID + taskCount/rangeSize)
if taskCount%rangeSize > 0 {
expectedRange++
}
// Due to conflicts some ids are skipped and more real ranges are used.
s.True(expectedRange <= s.taskManager.getTaskQueueManager(tlID).rangeID)
// check the poller information
tlType := enumspb.TASK_QUEUE_TYPE_ACTIVITY
descResp, err := s.matchingEngine.DescribeTaskQueue(s.handlerContext, &matchingservice.DescribeTaskQueueRequest{
NamespaceId: namespaceID,
DescRequest: &workflowservice.DescribeTaskQueueRequest{
TaskQueue: taskQueue,
TaskQueueType: tlType,
IncludeTaskQueueStatus: true,
},
})
s.NoError(err)
s.Equal(1, len(descResp.Pollers))
s.Equal(identity, descResp.Pollers[0].GetIdentity())
s.NotEmpty(descResp.Pollers[0].GetLastAccessTime())
s.Equal(defaultTaskDispatchRPS, descResp.Pollers[0].GetRatePerSecond())
s.NotNil(descResp.GetTaskQueueStatus())
numPartitions := float64(s.matchingEngine.config.NumTaskqueueWritePartitions("", "", tlType))
s.True(descResp.GetTaskQueueStatus().GetRatePerSecond()*numPartitions >= (defaultTaskDispatchRPS - 1))
}
func (s *matchingEngineSuite) TestConcurrentPublishConsumeActivities() {
dispatchLimitFn := func(int, int64) float64 {
return defaultTaskDispatchRPS
}
const workerCount = 20
const taskCount = 100
throttleCt := s.concurrentPublishConsumeActivities(workerCount, taskCount, dispatchLimitFn)
s.Zero(throttleCt)
}
func (s *matchingEngineSuite) TestConcurrentPublishConsumeActivitiesWithZeroDispatch() {
// Set a short long poll expiration so we don't have to wait too long for 0 throttling cases
s.matchingEngine.config.LongPollExpirationInterval = dynamicconfig.GetDurationPropertyFnFilteredByTaskQueueInfo(20 * time.Millisecond)
dispatchLimitFn := func(wc int, tc int64) float64 {
if tc%50 == 0 && wc%5 == 0 { // Gets triggered atleast 20 times
return 0
}
return defaultTaskDispatchRPS
}
const workerCount = 20
const taskCount = 100
s.matchingEngine.metricsClient = metrics.NewClient(tally.NewTestScope("test", nil), metrics.Matching)
throttleCt := s.concurrentPublishConsumeActivities(workerCount, taskCount, dispatchLimitFn)
s.logger.Info("Number of tasks throttled", tag.Number(throttleCt))
// atleast once from 0 dispatch poll, and until TTL is hit at which time throttle limit is reset
// hard to predict exactly how many times, since the atomic.Value load might not have updated.
s.True(throttleCt >= 1)
}
func (s *matchingEngineSuite) concurrentPublishConsumeActivities(
workerCount int,
taskCount int64,
dispatchLimitFn func(int, int64) float64,
) int64 {
scope := tally.NewTestScope("test", nil)
s.matchingEngine.metricsClient = metrics.NewClient(scope, metrics.Matching)
runID := uuid.NewRandom().String()
workflowID := "workflow1"
workflowExecution := &commonpb.WorkflowExecution{RunId: runID, WorkflowId: workflowID}
const initialRangeID = 0
const rangeSize = 3
var scheduleID int64 = 123
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
tlID := newTestTaskQueueID(namespaceID, tl, enumspb.TASK_QUEUE_TYPE_ACTIVITY)
tlKind := enumspb.TASK_QUEUE_KIND_NORMAL
s.matchingEngine.config.RangeSize = rangeSize // override to low number for the test
s.taskManager.getTaskQueueManager(tlID).rangeID = initialRangeID
mgr, err := newTaskQueueManager(s.matchingEngine, tlID, tlKind, s.matchingEngine.config)
s.NoError(err)
mgrImpl := mgr.(*taskQueueManagerImpl)
mgrImpl.matcher.config.MinTaskThrottlingBurstSize = func() int { return 0 }
mgrImpl.matcher.rateLimiter = quotas.NewRateLimiter(
defaultTaskDispatchRPS,
defaultTaskDispatchRPS,
)
mgrImpl.matcher.dynamicRate = &dynamicRateWrapper{
DynamicRate: quotas.NewDynamicRate(defaultTaskDispatchRPS),
RateLimiterImpl: mgrImpl.matcher.rateLimiter.(*quotas.RateLimiterImpl),
}
mgrImpl.matcher.dynamicBurst = &dynamicBurstWrapper{
DynamicBurst: quotas.NewDynamicBurst(defaultTaskDispatchRPS),
RateLimiterImpl: mgrImpl.matcher.rateLimiter.(*quotas.RateLimiterImpl),
}
s.matchingEngine.updateTaskQueue(tlID, mgr)
mgr.Start()
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
var wg sync.WaitGroup
wg.Add(2 * workerCount)
for p := 0; p < workerCount; p++ {
go func() {
defer wg.Done()
for i := int64(0); i < taskCount; i++ {
addRequest := matchingservice.AddActivityTaskRequest{
SourceNamespaceId: namespaceID,
NamespaceId: namespaceID,
Execution: workflowExecution,
ScheduleId: scheduleID,
TaskQueue: taskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(1),
}
_, err := s.matchingEngine.AddActivityTask(s.handlerContext, &addRequest)
if err != nil {
s.logger.Info("Failure in AddActivityTask", tag.Error(err))
i--
}
}
}()
}
activityTypeName := "activity1"
activityID := "activityId1"
activityType := &commonpb.ActivityType{Name: activityTypeName}
activityInput := payloads.EncodeString("Activity1 Input")
activityHeader := &commonpb.Header{
Fields: map[string]*commonpb.Payload{"tracing": payload.EncodeString("tracing data")},
}
identity := "nobody"
// History service is using mock
s.mockHistoryClient.EXPECT().RecordActivityTaskStarted(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(ctx context.Context, taskRequest *historyservice.RecordActivityTaskStartedRequest, arg2 ...interface{}) (*historyservice.RecordActivityTaskStartedResponse, error) {
s.logger.Debug("Mock Received RecordActivityTaskStartedRequest")
return &historyservice.RecordActivityTaskStartedResponse{
Attempt: 1,
ScheduledEvent: newActivityTaskScheduledEvent(taskRequest.ScheduleId, 0,
&commandpb.ScheduleActivityTaskCommandAttributes{
ActivityId: activityID,
TaskQueue: &taskqueuepb.TaskQueue{Name: taskQueue.Name},
ActivityType: activityType,
Input: activityInput,
Header: activityHeader,
ScheduleToStartTimeout: timestamp.DurationPtr(1 * time.Second),
ScheduleToCloseTimeout: timestamp.DurationPtr(2 * time.Second),
StartToCloseTimeout: timestamp.DurationPtr(1 * time.Second),
HeartbeatTimeout: timestamp.DurationPtr(1 * time.Second),
}),
}, nil
}).AnyTimes()
for p := 0; p < workerCount; p++ {
go func(wNum int) {
defer wg.Done()
for i := int64(0); i < taskCount; {
maxDispatch := dispatchLimitFn(wNum, i)
result, err := s.matchingEngine.PollActivityTaskQueue(s.handlerContext, &matchingservice.PollActivityTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollActivityTaskQueueRequest{
TaskQueue: taskQueue,
Identity: identity,
TaskQueueMetadata: &taskqueuepb.TaskQueueMetadata{MaxTasksPerSecond: &types.DoubleValue{Value: maxDispatch}},
},
})
s.NoError(err)
s.NotNil(result)
if len(result.TaskToken) == 0 {
s.logger.Debug("empty poll returned")
continue
}
s.EqualValues(activityID, result.ActivityId)
s.EqualValues(activityType, result.ActivityType)
s.EqualValues(activityInput, result.Input)
s.EqualValues(activityHeader, result.Header)
s.EqualValues(workflowExecution, result.WorkflowExecution)
taskToken := &tokenspb.Task{
ScheduleAttempt: 1,
NamespaceId: namespaceID,
WorkflowId: workflowID,
RunId: runID,
ScheduleId: scheduleID,
ActivityId: activityID,
ActivityType: activityTypeName,
}
resultToken, err := s.matchingEngine.tokenSerializer.Deserialize(result.TaskToken)
s.NoError(err)
// taskToken, _ := s.matchingEngine.tokenSerializer.Serialize(token)
// s.EqualValues(taskToken, result.Task, fmt.Sprintf("%v!=%v", string(taskToken)))
s.EqualValues(taskToken, resultToken, fmt.Sprintf("%v!=%v", taskToken, resultToken))
i++
}
}(p)
}
wg.Wait()
totalTasks := int(taskCount) * workerCount
persisted := s.taskManager.getCreateTaskCount(tlID)
s.True(persisted < totalTasks)
expectedRange := int64(initialRangeID + persisted/rangeSize)
if persisted%rangeSize > 0 {
expectedRange++
}
// Due to conflicts some ids are skipped and more real ranges are used.
s.True(expectedRange <= s.taskManager.getTaskQueueManager(tlID).rangeID)
s.EqualValues(0, s.taskManager.getTaskCount(tlID))
syncCtr := scope.Snapshot().Counters()["test.sync_throttle_count_per_tl+namespace="+matchingTestNamespace+",operation=TaskQueueMgr,taskqueue=makeToast"]
bufCtr := scope.Snapshot().Counters()["test.buffer_throttle_count_per_tl+namespace="+matchingTestNamespace+",operation=TaskQueueMgr,taskqueue=makeToast"]
total := int64(0)
if syncCtr != nil {
total += syncCtr.Value()
}
if bufCtr != nil {
total += bufCtr.Value()
}
return total
}
func (s *matchingEngineSuite) TestConcurrentPublishConsumeWorkflowTasks() {
runID := uuid.NewRandom().String()
workflowID := "workflow1"
workflowExecution := &commonpb.WorkflowExecution{RunId: runID, WorkflowId: workflowID}
const workerCount = 20
const taskCount = 100
const initialRangeID = 0
const rangeSize = 5
var scheduleID int64 = 123
var startedEventID int64 = 1412
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
tlID := newTestTaskQueueID(namespaceID, tl, enumspb.TASK_QUEUE_TYPE_WORKFLOW)
s.taskManager.getTaskQueueManager(tlID).rangeID = initialRangeID
s.matchingEngine.config.RangeSize = rangeSize // override to low number for the test
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
var wg sync.WaitGroup
wg.Add(2 * workerCount)
for p := 0; p < workerCount; p++ {
go func() {
for i := int64(0); i < taskCount; i++ {
addRequest := matchingservice.AddWorkflowTaskRequest{
NamespaceId: namespaceID,
Execution: workflowExecution,
ScheduleId: scheduleID,
TaskQueue: taskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(1),
}
_, err := s.matchingEngine.AddWorkflowTask(s.handlerContext, &addRequest)
if err != nil {
panic(err)
}
}
wg.Done()
}()
}
workflowTypeName := "workflowType1"
workflowType := &commonpb.WorkflowType{Name: workflowTypeName}
identity := "nobody"
// History service is using mock
s.mockHistoryClient.EXPECT().RecordWorkflowTaskStarted(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(ctx context.Context, taskRequest *historyservice.RecordWorkflowTaskStartedRequest, arg2 ...interface{}) (*historyservice.RecordWorkflowTaskStartedResponse, error) {
s.logger.Debug("Mock Received RecordWorkflowTaskStartedRequest")
return &historyservice.RecordWorkflowTaskStartedResponse{
PreviousStartedEventId: startedEventID,
StartedEventId: startedEventID,
ScheduledEventId: scheduleID,
WorkflowType: workflowType,
Attempt: 1,
}, nil
}).AnyTimes()
for p := 0; p < workerCount; p++ {
go func() {
for i := int64(0); i < taskCount; {
result, err := s.matchingEngine.PollWorkflowTaskQueue(s.handlerContext, &matchingservice.PollWorkflowTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollWorkflowTaskQueueRequest{
TaskQueue: taskQueue,
Identity: identity},
})
if err != nil {
panic(err)
}
s.NotNil(result)
if len(result.TaskToken) == 0 {
s.logger.Debug("empty poll returned")
continue
}
s.EqualValues(workflowExecution, result.WorkflowExecution)
s.EqualValues(workflowType, result.WorkflowType)
s.EqualValues(startedEventID, result.StartedEventId)
s.EqualValues(workflowExecution, result.WorkflowExecution)
taskToken := &tokenspb.Task{
ScheduleAttempt: 1,
NamespaceId: namespaceID,
WorkflowId: workflowID,
RunId: runID,
ScheduleId: scheduleID,
}
resultToken, err := s.matchingEngine.tokenSerializer.Deserialize(result.TaskToken)
if err != nil {
panic(err)
}
// taskToken, _ := s.matchingEngine.tokenSerializer.Serialize(token)
// s.EqualValues(taskToken, result.Task, fmt.Sprintf("%v!=%v", string(taskToken)))
s.EqualValues(taskToken, resultToken, fmt.Sprintf("%v!=%v", taskToken, resultToken))
i++
}
wg.Done()
}()
}
wg.Wait()
s.EqualValues(0, s.taskManager.getTaskCount(tlID))
totalTasks := taskCount * workerCount
persisted := s.taskManager.getCreateTaskCount(tlID)
s.True(persisted < totalTasks)
expectedRange := int64(initialRangeID + persisted/rangeSize)
if persisted%rangeSize > 0 {
expectedRange++
}
// Due to conflicts some ids are skipped and more real ranges are used.
s.True(expectedRange <= s.taskManager.getTaskQueueManager(tlID).rangeID)
}
func (s *matchingEngineSuite) TestPollWithExpiredContext() {
identity := "nobody"
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
// Try with cancelled context
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
cancel()
s.handlerContext.Context = ctx
_, err := s.matchingEngine.PollActivityTaskQueue(s.handlerContext, &matchingservice.PollActivityTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollActivityTaskQueueRequest{
TaskQueue: taskQueue,
Identity: identity},
})
s.Equal(ctx.Err(), err)
// Try with expired context
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
defer cancel()
s.handlerContext.Context = ctx
resp, err := s.matchingEngine.PollActivityTaskQueue(s.handlerContext, &matchingservice.PollActivityTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollActivityTaskQueueRequest{
TaskQueue: taskQueue,
Identity: identity},
})
s.Nil(err)
s.Equal(emptyPollActivityTaskQueueResponse, resp)
}
func (s *matchingEngineSuite) TestMultipleEnginesActivitiesRangeStealing() {
runID := uuid.NewRandom().String()
workflowID := "workflow1"
workflowExecution := &commonpb.WorkflowExecution{RunId: runID, WorkflowId: workflowID}
const engineCount = 2
const taskCount = 400
const iterations = 2
const initialRangeID = 0
const rangeSize = 10
var scheduleID int64 = 123
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
tlID := newTestTaskQueueID(namespaceID, tl, enumspb.TASK_QUEUE_TYPE_ACTIVITY)
s.taskManager.getTaskQueueManager(tlID).rangeID = initialRangeID
s.matchingEngine.config.RangeSize = rangeSize // override to low number for the test
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
engines := make([]*matchingEngineImpl, engineCount)
for p := 0; p < engineCount; p++ {
e := s.newMatchingEngine(defaultTestConfig(), s.taskManager)
e.config.RangeSize = rangeSize
engines[p] = e
e.Start()
}
for j := 0; j < iterations; j++ {
for p := 0; p < engineCount; p++ {
engine := engines[p]
for i := int64(0); i < taskCount; i++ {
addRequest := matchingservice.AddActivityTaskRequest{
SourceNamespaceId: namespaceID,
NamespaceId: namespaceID,
Execution: workflowExecution,
ScheduleId: scheduleID,
TaskQueue: taskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(600),
}
_, err := engine.AddActivityTask(s.handlerContext, &addRequest)
if err != nil {
if _, ok := err.(*persistence.ConditionFailedError); ok {
i-- // retry adding
} else {
panic(fmt.Sprintf("errType=%T, err=%v", err, err))
}
}
}
}
}
s.EqualValues(iterations*engineCount*taskCount, s.taskManager.getCreateTaskCount(tlID))
activityTypeName := "activity1"
activityID := "activityId1"
activityType := &commonpb.ActivityType{Name: activityTypeName}
activityInput := payloads.EncodeString("Activity1 Input")
identity := "nobody"
startedTasks := make(map[int64]bool)
// History service is using mock
s.mockHistoryClient.EXPECT().RecordActivityTaskStarted(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(ctx context.Context, taskRequest *historyservice.RecordActivityTaskStartedRequest, arg2 ...interface{}) (*historyservice.RecordActivityTaskStartedResponse, error) {
if _, ok := startedTasks[taskRequest.TaskId]; ok {
s.logger.Debug("From error function Mock Received DUPLICATED RecordActivityTaskStartedRequest", tag.TaskID(taskRequest.TaskId))
return nil, serviceerror.NewNotFound("already started")
}
s.logger.Debug("Mock Received RecordActivityTaskStartedRequest", tag.TaskID(taskRequest.TaskId))
startedTasks[taskRequest.TaskId] = true
return &historyservice.RecordActivityTaskStartedResponse{
Attempt: 1,
ScheduledEvent: newActivityTaskScheduledEvent(taskRequest.ScheduleId, 0,
&commandpb.ScheduleActivityTaskCommandAttributes{
ActivityId: activityID,
TaskQueue: &taskqueuepb.TaskQueue{Name: taskQueue.Name},
ActivityType: activityType,
Input: activityInput,
ScheduleToStartTimeout: timestamp.DurationPtr(600 * time.Second),
ScheduleToCloseTimeout: timestamp.DurationPtr(2 * time.Second),
StartToCloseTimeout: timestamp.DurationPtr(1 * time.Second),
HeartbeatTimeout: timestamp.DurationPtr(1 * time.Second),
}),
}, nil
}).AnyTimes()
for j := 0; j < iterations; j++ {
for p := 0; p < engineCount; p++ {
engine := engines[p]
for i := int64(0); i < taskCount; /* incremented explicitly to skip empty polls */ {
result, err := engine.PollActivityTaskQueue(s.handlerContext, &matchingservice.PollActivityTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollActivityTaskQueueRequest{
TaskQueue: taskQueue,
Identity: identity},
})
if err != nil {
panic(err)
}
s.NotNil(result)
if len(result.TaskToken) == 0 {
s.logger.Debug("empty poll returned")
continue
}
s.EqualValues(activityID, result.ActivityId)
s.EqualValues(activityType, result.ActivityType)
s.EqualValues(activityInput, result.Input)
s.EqualValues(workflowExecution, result.WorkflowExecution)
taskToken := &tokenspb.Task{
ScheduleAttempt: 1,
NamespaceId: namespaceID,
WorkflowId: workflowID,
RunId: runID,
ScheduleId: scheduleID,
ActivityId: activityID,
ActivityType: activityTypeName,
}
resultToken, err := engine.tokenSerializer.Deserialize(result.TaskToken)
if err != nil {
panic(err)
}
// taskToken, _ := s.matchingEngine.tokenSerializer.Serialize(token)
// s.EqualValues(taskToken, result.Task, fmt.Sprintf("%v!=%v", string(taskToken)))
s.EqualValues(taskToken, resultToken, fmt.Sprintf("%v!=%v", taskToken, resultToken))
i++
}
}
}
for _, e := range engines {
e.Stop()
}
s.EqualValues(0, s.taskManager.getTaskCount(tlID))
totalTasks := taskCount * engineCount * iterations
persisted := s.taskManager.getCreateTaskCount(tlID)
// No sync matching as all messages are published first
s.EqualValues(totalTasks, persisted)
expectedRange := int64(initialRangeID + persisted/rangeSize)
if persisted%rangeSize > 0 {
expectedRange++
}
// Due to conflicts some ids are skipped and more real ranges are used.
s.True(expectedRange <= s.taskManager.getTaskQueueManager(tlID).rangeID)
}
func (s *matchingEngineSuite) TestMultipleEnginesWorkflowTasksRangeStealing() {
runID := uuid.NewRandom().String()
workflowID := "workflow1"
workflowExecution := &commonpb.WorkflowExecution{RunId: runID, WorkflowId: workflowID}
const engineCount = 2
const taskCount = 400
const iterations = 2
const initialRangeID = 0
const rangeSize = 10
var scheduleID int64 = 123
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
tlID := newTestTaskQueueID(namespaceID, tl, enumspb.TASK_QUEUE_TYPE_WORKFLOW)
s.taskManager.getTaskQueueManager(tlID).rangeID = initialRangeID
s.matchingEngine.config.RangeSize = rangeSize // override to low number for the test
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
engines := make([]*matchingEngineImpl, engineCount)
for p := 0; p < engineCount; p++ {
e := s.newMatchingEngine(defaultTestConfig(), s.taskManager)
e.config.RangeSize = rangeSize
engines[p] = e
e.Start()
}
for j := 0; j < iterations; j++ {
for p := 0; p < engineCount; p++ {
engine := engines[p]
for i := int64(0); i < taskCount; i++ {
addRequest := matchingservice.AddWorkflowTaskRequest{
NamespaceId: namespaceID,
Execution: workflowExecution,
ScheduleId: scheduleID,
TaskQueue: taskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(600),
}
_, err := engine.AddWorkflowTask(s.handlerContext, &addRequest)
if err != nil {
if _, ok := err.(*persistence.ConditionFailedError); ok {
i-- // retry adding
} else {
panic(fmt.Sprintf("errType=%T, err=%v", err, err))
}
}
}
}
}
workflowTypeName := "workflowType1"
workflowType := &commonpb.WorkflowType{Name: workflowTypeName}
identity := "nobody"
var startedEventID int64 = 1412
startedTasks := make(map[int64]bool)
// History service is using mock
s.mockHistoryClient.EXPECT().RecordWorkflowTaskStarted(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(ctx context.Context, taskRequest *historyservice.RecordWorkflowTaskStartedRequest, arg2 ...interface{}) (*historyservice.RecordWorkflowTaskStartedResponse, error) {
if _, ok := startedTasks[taskRequest.TaskId]; ok {
s.logger.Debug("From error function Mock Received DUPLICATED RecordWorkflowTaskStartedRequest", tag.TaskID(taskRequest.TaskId))
return nil, serviceerrors.NewTaskAlreadyStarted("Workflow")
}
s.logger.Debug("Mock Received RecordWorkflowTaskStartedRequest", tag.TaskID(taskRequest.TaskId))
s.logger.Debug("Mock Received RecordWorkflowTaskStartedRequest")
startedTasks[taskRequest.TaskId] = true
return &historyservice.RecordWorkflowTaskStartedResponse{
PreviousStartedEventId: startedEventID,
StartedEventId: startedEventID,
ScheduledEventId: scheduleID,
WorkflowType: workflowType,
Attempt: 1,
}, nil
}).AnyTimes()
for j := 0; j < iterations; j++ {
for p := 0; p < engineCount; p++ {
engine := engines[p]
for i := int64(0); i < taskCount; /* incremented explicitly to skip empty polls */ {
result, err := engine.PollWorkflowTaskQueue(s.handlerContext, &matchingservice.PollWorkflowTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollWorkflowTaskQueueRequest{
TaskQueue: taskQueue,
Identity: identity},
})
if err != nil {
panic(err)
}
s.NotNil(result)
if len(result.TaskToken) == 0 {
s.logger.Debug("empty poll returned")
continue
}
s.EqualValues(workflowExecution, result.WorkflowExecution)
s.EqualValues(workflowType, result.WorkflowType)
s.EqualValues(startedEventID, result.StartedEventId)
s.EqualValues(workflowExecution, result.WorkflowExecution)
taskToken := &tokenspb.Task{
ScheduleAttempt: 1,
NamespaceId: namespaceID,
WorkflowId: workflowID,
RunId: runID,
ScheduleId: scheduleID,
}
resultToken, err := engine.tokenSerializer.Deserialize(result.TaskToken)
if err != nil {
panic(err)
}
// taskToken, _ := s.matchingEngine.tokenSerializer.Serialize(token)
// s.EqualValues(taskToken, result.Task, fmt.Sprintf("%v!=%v", string(taskToken)))
s.EqualValues(taskToken, resultToken, fmt.Sprintf("%v!=%v", taskToken, resultToken))
i++
}
}
}
for _, e := range engines {
e.Stop()
}
s.EqualValues(0, s.taskManager.getTaskCount(tlID))
totalTasks := taskCount * engineCount * iterations
persisted := s.taskManager.getCreateTaskCount(tlID)
// No sync matching as all messages are published first
s.EqualValues(totalTasks, persisted)
expectedRange := int64(initialRangeID + persisted/rangeSize)
if persisted%rangeSize > 0 {
expectedRange++
}
// Due to conflicts some ids are skipped and more real ranges are used.
s.True(expectedRange <= s.taskManager.getTaskQueueManager(tlID).rangeID)
}
func (s *matchingEngineSuite) TestAddTaskAfterStartFailure() {
runID := uuid.NewRandom().String()
workflowID := "workflow1"
workflowExecution := &commonpb.WorkflowExecution{RunId: runID, WorkflowId: workflowID}
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
tlID := newTestTaskQueueID(namespaceID, tl, enumspb.TASK_QUEUE_TYPE_ACTIVITY)
tlKind := enumspb.TASK_QUEUE_KIND_NORMAL
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
scheduleID := int64(0)
addRequest := matchingservice.AddActivityTaskRequest{
SourceNamespaceId: namespaceID,
NamespaceId: namespaceID,
Execution: workflowExecution,
ScheduleId: scheduleID,
TaskQueue: taskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(1),
}
_, err := s.matchingEngine.AddActivityTask(s.handlerContext, &addRequest)
s.NoError(err)
s.EqualValues(1, s.taskManager.getTaskCount(tlID))
ctx, err := s.matchingEngine.getTask(context.Background(), tlID, nil, tlKind)
s.NoError(err)
ctx.finish(errors.New("test error"))
s.EqualValues(1, s.taskManager.getTaskCount(tlID))
ctx2, err := s.matchingEngine.getTask(context.Background(), tlID, nil, tlKind)
s.NoError(err)
s.NotEqual(ctx.event.GetTaskId(), ctx2.event.GetTaskId())
s.Equal(ctx.event.Data.GetWorkflowId(), ctx2.event.Data.GetWorkflowId())
s.Equal(ctx.event.Data.GetRunId(), ctx2.event.Data.GetRunId())
s.Equal(ctx.event.Data.GetScheduleId(), ctx2.event.Data.GetScheduleId())
ctx2.finish(nil)
s.EqualValues(0, s.taskManager.getTaskCount(tlID))
}
func (s *matchingEngineSuite) TestTaskQueueManagerGetTaskBatch() {
runID := uuid.NewRandom().String()
workflowID := "workflow1"
workflowExecution := &commonpb.WorkflowExecution{RunId: runID, WorkflowId: workflowID}
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
tlID := newTestTaskQueueID(namespaceID, tl, enumspb.TASK_QUEUE_TYPE_ACTIVITY)
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
const taskCount = 1200
const rangeSize = 10
s.matchingEngine.config.RangeSize = rangeSize
// add taskCount tasks
for i := int64(0); i < taskCount; i++ {
scheduleID := i * 3
addRequest := matchingservice.AddActivityTaskRequest{
SourceNamespaceId: namespaceID,
NamespaceId: namespaceID,
Execution: workflowExecution,
ScheduleId: scheduleID,
TaskQueue: taskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(1),
}
_, err := s.matchingEngine.AddActivityTask(s.handlerContext, &addRequest)
s.NoError(err)
}
tlMgr, ok := s.matchingEngine.taskQueues[*tlID].(*taskQueueManagerImpl)
s.True(ok, "taskQueueManger doesn't implement taskQueueManager interface")
s.EqualValues(taskCount, s.taskManager.getTaskCount(tlID))
// wait until all tasks are read by the task pump and enqeued into the in-memory buffer
// at the end of this step, ackManager readLevel will also be equal to the buffer size
expectedBufSize := common.MinInt(cap(tlMgr.taskReader.taskBuffer), taskCount)
s.True(s.awaitCondition(func() bool { return len(tlMgr.taskReader.taskBuffer) == expectedBufSize }, time.Second))
// stop all goroutines that read / write tasks in the background
// remainder of this test works with the in-memory buffer
tlMgr.Stop()
// setReadLevel should NEVER be called without updating ackManager.outstandingTasks
// This is only for unit test purpose
tlMgr.taskAckManager.setReadLevel(tlMgr.taskWriter.GetMaxReadLevel())
tasks, readLevel, isReadBatchDone, err := tlMgr.taskReader.getTaskBatch()
s.Nil(err)
s.EqualValues(0, len(tasks))
s.EqualValues(tlMgr.taskWriter.GetMaxReadLevel(), readLevel)
s.True(isReadBatchDone)
tlMgr.taskAckManager.setReadLevel(0)
tasks, readLevel, isReadBatchDone, err = tlMgr.taskReader.getTaskBatch()
s.Nil(err)
s.EqualValues(rangeSize, len(tasks))
s.EqualValues(rangeSize, readLevel)
s.True(isReadBatchDone)
s.setupRecordActivityTaskStartedMock(tl)
// reset the ackManager readLevel to the buffer size and consume
// the in-memory tasks by calling Poll API - assert ackMgr state
// at the end
tlMgr.taskAckManager.setReadLevel(int64(expectedBufSize))
// complete rangeSize events
for i := int64(0); i < rangeSize; i++ {
identity := "nobody"
result, err := s.matchingEngine.PollActivityTaskQueue(s.handlerContext, &matchingservice.PollActivityTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollActivityTaskQueueRequest{
TaskQueue: taskQueue,
Identity: identity},
})
s.NoError(err)
s.NotNil(result)
s.NotEqual(emptyPollActivityTaskQueueResponse, result)
if len(result.TaskToken) == 0 {
s.logger.Debug("empty poll returned")
continue
}
}
s.EqualValues(taskCount-rangeSize, s.taskManager.getTaskCount(tlID))
tasks, _, isReadBatchDone, err = tlMgr.taskReader.getTaskBatch()
s.Nil(err)
s.True(0 < len(tasks) && len(tasks) <= rangeSize)
s.True(isReadBatchDone)
tlMgr.engine.removeTaskQueueManager(tlMgr.taskQueueID)
}
func (s *matchingEngineSuite) TestTaskQueueManagerGetTaskBatch_ReadBatchDone() {
namespaceID := uuid.NewRandom().String()
tl := "makeToast"
tlID := newTestTaskQueueID(namespaceID, tl, enumspb.TASK_QUEUE_TYPE_ACTIVITY)
tlNormal := enumspb.TASK_QUEUE_KIND_NORMAL
const rangeSize = 10
const maxReadLevel = int64(120)
config := defaultTestConfig()
config.RangeSize = rangeSize
tlMgr0, err := newTaskQueueManager(s.matchingEngine, tlID, tlNormal, config)
s.NoError(err)
tlMgr, ok := tlMgr0.(*taskQueueManagerImpl)
s.True(ok)
tlMgr.Start()
// tlMgr.taskWriter startup is async so give it time to complete, otherwise
// the following few lines get clobbered as part of the taskWriter.Start()
time.Sleep(100 * time.Millisecond)
tlMgr.taskAckManager.setReadLevel(0)
atomic.StoreInt64(&tlMgr.taskWriter.maxReadLevel, maxReadLevel)
tasks, readLevel, isReadBatchDone, err := tlMgr.taskReader.getTaskBatch()
s.Empty(tasks)
s.Equal(int64(rangeSize*10), readLevel)
s.False(isReadBatchDone)
s.NoError(err)
tlMgr.taskAckManager.setReadLevel(readLevel)
tasks, readLevel, isReadBatchDone, err = tlMgr.taskReader.getTaskBatch()
s.Empty(tasks)
s.Equal(maxReadLevel, readLevel)
s.True(isReadBatchDone)
s.NoError(err)
}
func (s *matchingEngineSuite) TestTaskExpiryAndCompletion() {
runID := uuid.NewRandom().String()
workflowID := uuid.New()
workflowExecution := &commonpb.WorkflowExecution{RunId: runID, WorkflowId: workflowID}
namespaceID := uuid.NewRandom().String()
tl := "task-expiry-completion-tl0"
tlID := newTestTaskQueueID(namespaceID, tl, enumspb.TASK_QUEUE_TYPE_ACTIVITY)
taskQueue := &taskqueuepb.TaskQueue{Name: tl}
const taskCount = 20
const rangeSize = 10
s.matchingEngine.config.RangeSize = rangeSize
s.matchingEngine.config.MaxTaskDeleteBatchSize = dynamicconfig.GetIntPropertyFilteredByTaskQueueInfo(2)
testCases := []struct {
maxTimeBtwnDeletes time.Duration
}{
{time.Minute}, // test taskGC deleting due to size threshold
{time.Nanosecond}, // test taskGC deleting due to time condition
}
for _, tc := range testCases {
for i := int64(0); i < taskCount; i++ {
scheduleID := i * 3
addRequest := matchingservice.AddActivityTaskRequest{
SourceNamespaceId: namespaceID,
NamespaceId: namespaceID,
Execution: workflowExecution,
ScheduleId: scheduleID,
TaskQueue: taskQueue,
ScheduleToStartTimeout: timestamp.DurationFromSeconds(5),
}
if i%2 == 0 {
// simulates creating a task whose scheduledToStartTimeout is already expired
addRequest.ScheduleToStartTimeout = timestamp.DurationFromSeconds(-5)
}
_, err := s.matchingEngine.AddActivityTask(s.handlerContext, &addRequest)
s.NoError(err)
}
tlMgr, ok := s.matchingEngine.taskQueues[*tlID].(*taskQueueManagerImpl)
s.True(ok, "failed to load task queue")
s.EqualValues(taskCount, s.taskManager.getTaskCount(tlID))
// wait until all tasks are loaded by into in-memory buffers by task queue manager
// the buffer size should be one less than expected because dispatcher will dequeue the head
s.True(s.awaitCondition(func() bool { return len(tlMgr.taskReader.taskBuffer) >= (taskCount/2 - 1) }, time.Second))
maxTimeBetweenTaskDeletes = tc.maxTimeBtwnDeletes
s.setupRecordActivityTaskStartedMock(tl)
pollReq := &matchingservice.PollActivityTaskQueueRequest{
NamespaceId: namespaceID,
PollRequest: &workflowservice.PollActivityTaskQueueRequest{TaskQueue: taskQueue, Identity: "test"},
}
remaining := taskCount
for i := 0; i < 2; i++ {
// verify that (1) expired tasks are not returned in poll result (2) taskCleaner deletes tasks correctly
for i := int64(0); i < taskCount/4; i++ {
result, err := s.matchingEngine.PollActivityTaskQueue(s.handlerContext, pollReq)
s.NoError(err)
s.NotNil(result)
s.NotEqual(result, emptyPollActivityTaskQueueResponse)
}
remaining -= taskCount / 2
// since every other task is expired, we expect half the tasks to be deleted
// after poll consumed 1/4th of what is available
s.EqualValues(remaining, s.taskManager.getTaskCount(tlID))
}
}
}
func (s *matchingEngineSuite) setupRecordActivityTaskStartedMock(tlName string) {
activityTypeName := "activity1"
activityID := "activityId1"
activityType := &commonpb.ActivityType{Name: activityTypeName}
activityInput := payloads.EncodeString("Activity1 Input")
// History service is using mock
s.mockHistoryClient.EXPECT().RecordActivityTaskStarted(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(ctx context.Context, taskRequest *historyservice.RecordActivityTaskStartedRequest, arg2 ...interface{}) (*historyservice.RecordActivityTaskStartedResponse, error) {
s.logger.Debug("Mock Received RecordActivityTaskStartedRequest")
return &historyservice.RecordActivityTaskStartedResponse{
Attempt: 1,
ScheduledEvent: newActivityTaskScheduledEvent(taskRequest.ScheduleId, 0,
&commandpb.ScheduleActivityTaskCommandAttributes{
ActivityId: activityID,
TaskQueue: &taskqueuepb.TaskQueue{Name: tlName},
ActivityType: activityType,
Input: activityInput,
ScheduleToCloseTimeout: timestamp.DurationPtr(100 * time.Second),
ScheduleToStartTimeout: timestamp.DurationPtr(50 * time.Second),
StartToCloseTimeout: timestamp.DurationPtr(50 * time.Second),
HeartbeatTimeout: timestamp.DurationPtr(10 * time.Second),
}),
}, nil
}).AnyTimes()
}
func (s *matchingEngineSuite) awaitCondition(cond func() bool, timeout time.Duration) bool {
expiry := time.Now().UTC().Add(timeout)
for !cond() {
time.Sleep(time.Millisecond * 5)
if time.Now().UTC().After(expiry) {
return false
}
}
return true
}
func newActivityTaskScheduledEvent(eventID int64, workflowTaskCompletedEventID int64,
scheduleAttributes *commandpb.ScheduleActivityTaskCommandAttributes) *historypb.HistoryEvent {
historyEvent := newHistoryEvent(eventID, enumspb.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED)
historyEvent.Attributes = &historypb.HistoryEvent_ActivityTaskScheduledEventAttributes{ActivityTaskScheduledEventAttributes: &historypb.ActivityTaskScheduledEventAttributes{
ActivityId: scheduleAttributes.ActivityId,
ActivityType: scheduleAttributes.ActivityType,
TaskQueue: scheduleAttributes.TaskQueue,
Input: scheduleAttributes.Input,
Header: scheduleAttributes.Header,
ScheduleToCloseTimeout: scheduleAttributes.ScheduleToCloseTimeout,
ScheduleToStartTimeout: scheduleAttributes.ScheduleToStartTimeout,
StartToCloseTimeout: scheduleAttributes.StartToCloseTimeout,
HeartbeatTimeout: scheduleAttributes.HeartbeatTimeout,
WorkflowTaskCompletedEventId: workflowTaskCompletedEventID,
}}
return historyEvent
}
func newHistoryEvent(eventID int64, eventType enumspb.EventType) *historypb.HistoryEvent {
historyEvent := &historypb.HistoryEvent{
EventId: eventID,
EventTime: timestamp.TimePtr(time.Now().UTC()),
EventType: eventType,
}
return historyEvent
}
var _ persistence.TaskManager = (*testTaskManager)(nil) // Asserts that interface is indeed implemented
type testTaskManager struct {
sync.Mutex
taskQueues map[taskQueueID]*testTaskQueueManager
logger log.Logger
}
func newTestTaskManager(logger log.Logger) *testTaskManager {
return &testTaskManager{taskQueues: make(map[taskQueueID]*testTaskQueueManager), logger: logger}
}
func (m *testTaskManager) GetName() string {
return "test"
}
func (m *testTaskManager) Close() {
return
}
func (m *testTaskManager) getTaskQueueManager(id *taskQueueID) *testTaskQueueManager {
m.Lock()
defer m.Unlock()
result, ok := m.taskQueues[*id]
if ok {
return result
}
result = newTestTaskQueueManager()
m.taskQueues[*id] = result
return result
}
type testTaskQueueManager struct {
sync.Mutex
rangeID int64
ackLevel int64
createTaskCount int
tasks *treemap.Map
}
func (m *testTaskQueueManager) RangeID() int64 {
m.Lock()
defer m.Unlock()
return m.rangeID
}
func Int64Comparator(a, b interface{}) int {
aAsserted := a.(int64)
bAsserted := b.(int64)
switch {
case aAsserted > bAsserted:
return 1
case aAsserted < bAsserted:
return -1
default:
return 0
}
}
func newTestTaskQueueManager() *testTaskQueueManager {
return &testTaskQueueManager{tasks: treemap.NewWith(Int64Comparator)}
}
func newTestTaskQueueID(namespaceID string, name string, taskType enumspb.TaskQueueType) *taskQueueID {
result, err := newTaskQueueID(namespaceID, name, taskType)
if err != nil {
panic(fmt.Sprintf("newTaskQueueID failed with error %v", err))
}
return result
}
// LeaseTaskQueue provides a mock function with given fields: request
func (m *testTaskManager) LeaseTaskQueue(request *persistence.LeaseTaskQueueRequest) (*persistence.LeaseTaskQueueResponse, error) {
tlm := m.getTaskQueueManager(newTestTaskQueueID(request.NamespaceID, request.TaskQueue, request.TaskType))
tlm.Lock()
defer tlm.Unlock()
tlm.rangeID++
m.logger.Debug("LeaseTaskQueue", tag.ShardRangeID(tlm.rangeID))
return &persistence.LeaseTaskQueueResponse{
TaskQueueInfo: &persistence.PersistedTaskQueueInfo{
Data: &persistencespb.TaskQueueInfo{
AckLevel: tlm.ackLevel,
NamespaceId: request.NamespaceID,
Name: request.TaskQueue,
TaskType: request.TaskType,
Kind: request.TaskQueueKind,
},
RangeID: tlm.rangeID,
},
}, nil
}
// UpdateTaskQueue provides a mock function with given fields: request
func (m *testTaskManager) UpdateTaskQueue(request *persistence.UpdateTaskQueueRequest) (*persistence.UpdateTaskQueueResponse, error) {
tli := request.TaskQueueInfo
tlm := m.getTaskQueueManager(newTestTaskQueueID(tli.GetNamespaceId(), tli.Name, tli.TaskType))
tlm.Lock()
defer tlm.Unlock()
if tlm.rangeID != request.RangeID {
return nil, &persistence.ConditionFailedError{
Msg: fmt.Sprintf("Failed to update task queue: name=%v, type=%v", tli.Name, tli.TaskType),
}
}
tlm.ackLevel = tli.AckLevel
return &persistence.UpdateTaskQueueResponse{}, nil
}
// CompleteTask provides a mock function with given fields: request
func (m *testTaskManager) CompleteTask(request *persistence.CompleteTaskRequest) error {
m.logger.Debug("CompleteTask", tag.TaskID(request.TaskID), tag.Name(request.TaskQueue.Name), tag.WorkflowTaskQueueType(request.TaskQueue.TaskType))
if request.TaskID <= 0 {
panic(fmt.Errorf("invalid taskID=%v", request.TaskID))
}
tli := request.TaskQueue
tlm := m.getTaskQueueManager(newTestTaskQueueID(tli.NamespaceID, tli.Name, tli.TaskType))
tlm.Lock()
defer tlm.Unlock()
tlm.tasks.Remove(request.TaskID)
return nil
}
func (m *testTaskManager) CompleteTasksLessThan(request *persistence.CompleteTasksLessThanRequest) (int, error) {
tlm := m.getTaskQueueManager(newTestTaskQueueID(request.NamespaceID, request.TaskQueueName, request.TaskType))
tlm.Lock()
defer tlm.Unlock()
keys := tlm.tasks.Keys()
for _, key := range keys {
id := key.(int64)
if id <= request.TaskID {
tlm.tasks.Remove(id)
}
}
return persistence.UnknownNumRowsAffected, nil
}
func (m *testTaskManager) ListTaskQueue(_ *persistence.ListTaskQueueRequest) (*persistence.ListTaskQueueResponse, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (m *testTaskManager) DeleteTaskQueue(request *persistence.DeleteTaskQueueRequest) error {
m.Lock()
defer m.Unlock()
key := newTestTaskQueueID(request.TaskQueue.NamespaceID, request.TaskQueue.Name, request.TaskQueue.TaskType)
delete(m.taskQueues, *key)
return nil
}
// CreateTask provides a mock function with given fields: request
func (m *testTaskManager) CreateTasks(request *persistence.CreateTasksRequest) (*persistence.CreateTasksResponse, error) {
namespaceID := request.TaskQueueInfo.Data.GetNamespaceId()
taskQueue := request.TaskQueueInfo.Data.Name
taskType := request.TaskQueueInfo.Data.TaskType
rangeID := request.TaskQueueInfo.RangeID
tlm := m.getTaskQueueManager(newTestTaskQueueID(namespaceID, taskQueue, taskType))
tlm.Lock()
defer tlm.Unlock()
// First validate the entire batch
for _, task := range request.Tasks {
m.logger.Debug("testTaskManager.CreateTask", tag.TaskID(task.GetTaskId()), tag.ShardRangeID(rangeID))
if task.GetTaskId() <= 0 {
panic(fmt.Errorf("invalid taskID=%v", task.GetTaskId()))
}
if tlm.rangeID != rangeID {
m.logger.Debug("testTaskManager.CreateTask ConditionFailedError",
tag.TaskID(task.GetTaskId()), tag.ShardRangeID(rangeID), tag.ShardRangeID(tlm.rangeID))
return nil, &persistence.ConditionFailedError{
Msg: fmt.Sprintf("testTaskManager.CreateTask failed. TaskQueue: %v, taskType: %v, rangeID: %v, db rangeID: %v",
taskQueue, taskType, rangeID, tlm.rangeID),
}
}
_, ok := tlm.tasks.Get(task.GetTaskId())
if ok {
panic(fmt.Sprintf("Duplicated TaskID %v", task.GetTaskId()))
}
}
// Then insert all tasks if no errors
for _, task := range request.Tasks {
tlm.tasks.Put(task.GetTaskId(), &persistencespb.AllocatedTaskInfo{
Data: task.Data,
TaskId: task.GetTaskId(),
})
tlm.createTaskCount++
}
return &persistence.CreateTasksResponse{}, nil
}
// GetTasks provides a mock function with given fields: request
func (m *testTaskManager) GetTasks(request *persistence.GetTasksRequest) (*persistence.GetTasksResponse, error) {
if request.MaxReadLevel != nil {
m.logger.Debug("testTaskManager.GetTasks", tag.ReadLevel(request.ReadLevel), tag.ReadLevel(*request.MaxReadLevel))
} else {
m.logger.Debug("testTaskManager.GetTasks", tag.ReadLevel(request.ReadLevel))
}
tlm := m.getTaskQueueManager(newTestTaskQueueID(request.NamespaceID, request.TaskQueue, request.TaskType))
tlm.Lock()
defer tlm.Unlock()
var tasks []*persistencespb.AllocatedTaskInfo
it := tlm.tasks.Iterator()
for it.Next() {
taskID := it.Key().(int64)
if taskID <= request.ReadLevel {
continue
}
if taskID > *request.MaxReadLevel {
break
}
tasks = append(tasks, it.Value().(*persistencespb.AllocatedTaskInfo))
}
return &persistence.GetTasksResponse{
Tasks: tasks,
}, nil
}
// getTaskCount returns number of tasks in a task queue
func (m *testTaskManager) getTaskCount(taskQueue *taskQueueID) int {
tlm := m.getTaskQueueManager(taskQueue)
tlm.Lock()
defer tlm.Unlock()
return tlm.tasks.Size()
}
// getCreateTaskCount returns how many times CreateTask was called
func (m *testTaskManager) getCreateTaskCount(taskQueue *taskQueueID) int {
tlm := m.getTaskQueueManager(taskQueue)
tlm.Lock()
defer tlm.Unlock()
return tlm.createTaskCount
}
func (m *testTaskManager) String() string {
m.Lock()
defer m.Unlock()
var result string
for id, tl := range m.taskQueues {
tl.Lock()
if id.taskType == enumspb.TASK_QUEUE_TYPE_ACTIVITY {
result += "Activity"
} else {
result += "Workflow"
}
result += " task queue " + id.name
result += "\n"
result += fmt.Sprintf("AckLevel=%v\n", tl.ackLevel)
result += fmt.Sprintf("CreateTaskCount=%v\n", tl.createTaskCount)
result += fmt.Sprintf("RangeID=%v\n", tl.rangeID)
result += "Tasks=\n"
for _, t := range tl.tasks.Values() {
result += fmt.Sprintf("%v\n", t)
}
tl.Unlock()
}
return result
}
func validateTimeRange(t time.Time, expectedDuration time.Duration) bool {
currentTime := time.Now().UTC()
diff := time.Duration(currentTime.UnixNano() - t.UnixNano())
if diff > expectedDuration {
fmt.Printf("Current time: %v, Application time: %v, Difference: %v \n", currentTime, t, diff)
return false
}
return true
}
func defaultTestConfig() *Config {
config := NewConfig(dynamicconfig.NewNoopCollection())
config.LongPollExpirationInterval = dynamicconfig.GetDurationPropertyFnFilteredByTaskQueueInfo(100 * time.Millisecond)
config.MaxTaskDeleteBatchSize = dynamicconfig.GetIntPropertyFilteredByTaskQueueInfo(1)
return config
}
type (
dynamicRateWrapper struct {
quotas.DynamicRate
*quotas.RateLimiterImpl
}
dynamicBurstWrapper struct {
quotas.DynamicBurst
*quotas.RateLimiterImpl
}
)
func (d *dynamicRateWrapper) Store(rate float64) {
d.DynamicRate.Store(rate)
d.RateLimiterImpl.SetRate(rate)
}
func (d *dynamicBurstWrapper) Store(burst int) {
d.DynamicBurst.Store(burst)
d.RateLimiterImpl.SetBurst(burst)
}
| 1 | 12,598 | was it caused by the removal of removeTaskQueueManager() from this test? | temporalio-temporal | go |
@@ -61,7 +61,7 @@ module Blacklight::CatalogHelperBehavior
# @see #page_entries_info
# @return [String]
def item_page_entry_info
- t('blacklight.search.entry_pagination_info.other', :current => number_with_delimiter(search_session[:counter]), :total => number_with_delimiter(search_session[:total]), :count => search_session[:total].to_i).html_safe
+ t('blacklight.search.entry_pagination_info.other', :current => number_with_delimiter(search_session['counter']), :total => number_with_delimiter(search_session['total']), :count => search_session['total'].to_i).html_safe
end
## | 1 | # -*- encoding : utf-8 -*-
module Blacklight::CatalogHelperBehavior
##
# Override the Kaminari page_entries_info helper with our own, blacklight-aware
# implementation.
# Displays the "showing X through Y of N" message.
#
# @param [RSolr::Resource] (or other Kaminari-compatible objects)
# @return [String]
def page_entries_info(collection, options = {})
entry_name = if options[:entry_name]
options[:entry_name]
elsif collection.respond_to? :model # DataMapper
collection.model.model_name.human.downcase
elsif collection.respond_to? :model_name and !collection.model_name.nil? # AR, Blacklight::PaginationMethods
collection.model_name.human.downcase
elsif collection.is_a?(::Kaminari::PaginatableArray)
'entry'
else
t('blacklight.entry_name.default')
end
entry_name = entry_name.pluralize unless collection.total_count == 1
# grouped response objects need special handling
end_num = if collection.respond_to? :groups and render_grouped_response? collection
collection.groups.length
else
collection.limit_value
end
end_num = if collection.offset_value + end_num <= collection.total_count
collection.offset_value + end_num
else
collection.total_count
end
case collection.total_count
when 0; t('blacklight.search.pagination_info.no_items_found', :entry_name => entry_name ).html_safe
when 1; t('blacklight.search.pagination_info.single_item_found', :entry_name => entry_name).html_safe
else; t('blacklight.search.pagination_info.pages', :entry_name => entry_name, :current_page => collection.current_page, :num_pages => collection.total_pages, :start_num => number_with_delimiter(collection.offset_value + 1) , :end_num => number_with_delimiter(end_num), :total_num => number_with_delimiter(collection.total_count), :count => collection.total_pages).html_safe
end
end
##
# Get the offset counter for a document
#
# @param [Integer] document index
# @return [Integer]
def document_counter_with_offset idx
unless render_grouped_response?
idx + 1 + @response.params[:start].to_i
end
end
##
# Like #page_entries_info above, but for an individual
# item show page. Displays "showing X of Y items" message.
#
# @see #page_entries_info
# @return [String]
def item_page_entry_info
t('blacklight.search.entry_pagination_info.other', :current => number_with_delimiter(search_session[:counter]), :total => number_with_delimiter(search_session[:total]), :count => search_session[:total].to_i).html_safe
end
##
# Look up search field user-displayable label
# based on params[:qt] and blacklight_configuration.
def search_field_label(params)
h( label_for_search_field(params[:search_field]) )
end
##
# Look up the current sort field, or provide the default if none is set
#
# @return [Blacklight::Configuration::SortField]
def current_sort_field
blacklight_config.sort_fields[params[:sort]] || default_sort_field
end
##
# Look up the current per page value, or the default if none if set
#
# @return [Integer]
def current_per_page
(@response.rows if @response and @response.rows > 0) || params.fetch(:per_page, default_per_page).to_i
end
##
# Export to Refworks URL
#
# @param [SolrDocument]
# @return [String]
def refworks_export_url(document = @document)
"http://www.refworks.com/express/expressimport.asp?vendor=#{CGI.escape(application_name)}&filter=MARC%20Format&encoding=65001&url=#{CGI.escape(polymorphic_path(document, :format => 'refworks_marc_txt', :only_path => false))}"
end
##
# Get the classes to add to a document's div
#
# @return [String]
def render_document_class(document = @document)
'blacklight-' + document.get(blacklight_config.view_config(document_index_view_type_field).display_type_field).parameterize rescue nil
end
##
# Render the sidebar partial for a document
#
# @param [SolrDocument]
# @return [String]
def render_document_sidebar_partial(document = @document)
render :partial => 'show_sidebar'
end
##
# Check if any search parameters have been set
# @return [Boolean]
def has_search_parameters?
!params[:q].blank? or !params[:f].blank? or !params[:search_field].blank?
end
##
# Should we display the sort and per page widget?
#
# @param [Blacklight::SolrResponse]
# @return [Boolean]
def show_sort_and_per_page? response = nil
response ||= @response
!response.empty?
end
##
# If no search parameters have been given, we should
# auto-focus the user's cursor into the searchbox
#
# @return [Boolean]
def should_autofocus_on_search_box?
controller.is_a? Blacklight::Catalog and
action_name == "index" and
!has_search_parameters?
end
##
# Does the document have a thumbnail to render?
#
# @param [SolrDocument]
# @return [Boolean]
def has_thumbnail? document
blacklight_config.view_config(document_index_view_type).thumbnail_method or
blacklight_config.view_config(document_index_view_type).thumbnail_field && document.has?(blacklight_config.view_config(document_index_view_type).thumbnail_field)
end
##
# Render the thumbnail, if available, for a document and
# link it to the document record.
#
# @param [SolrDocument]
# @param [Hash] options to pass to the image tag
# @param [Hash] url options to pass to #link_to_document
# @return [String]
def render_thumbnail_tag document, image_options = {}, url_options = {}
value = if blacklight_config.view_config(document_index_view_type).thumbnail_method
send(blacklight_config.view_config(document_index_view_type).thumbnail_method, document, image_options)
elsif blacklight_config.view_config(document_index_view_type).thumbnail_field
image_tag thumbnail_url(document), image_options
end
if value
if url_options === false || url_options[:suppress_link]
value
else
link_to_document document, url_options.merge(:label => value)
end
end
end
##
# Get the URL to a document's thumbnail image
#
# @param [SolrDocument]
# @return [String]
def thumbnail_url document
if document.has? blacklight_config.view_config(document_index_view_type).thumbnail_field
document.first(blacklight_config.view_config(document_index_view_type).thumbnail_field)
end
end
##
# Get url parameters to a search within a grouped result set
#
# @param [Blacklight::SolrResponse::Group]
# @return [Hash]
def add_group_facet_params_and_redirect group
add_facet_params_and_redirect(group.field, group.key)
end
##
# Render the view type icon for the results view picker
#
# @param [String]
# @return [String]
def render_view_type_group_icon view
content_tag :span, '', class: "glyphicon #{blacklight_config.view[view].icon_class || default_view_type_group_icon_classes(view) }"
end
##
# Get the default view type classes for a view in the results view picker
#
# @param [String]
# @return [String]
def default_view_type_group_icon_classes view
"glyphicon-#{view.to_s.parameterize } view-icon-#{view.to_s.parameterize}"
end
end
| 1 | 5,089 | Wouldn't it just be easier to force search_session to return `with_indifferent_access`? Since you've done the hard work already, I don't think there's a problem doing it this way, but.. | projectblacklight-blacklight | rb |
@@ -146,6 +146,8 @@ struct PROC_RESOURCES {
atp->needs_shmem = false;
}
}
+ if (rp->rr_sim_misses_deadline) return false;
+ // Don't schedule if the result is simulated to miss its deadline
if (rp->schedule_backoff > gstate.now) return false;
if (rp->uses_gpu()) {
if (gpu_suspend_reason) return false; | 1 | // This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2008 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with BOINC. If not, see <http://www.gnu.org/licenses/>.
// CPU scheduling logic.
//
// - create an ordered "run list" (make_run_list()).
// The ordering is roughly as follows:
// - GPU jobs first, then CPU jobs
// - for a given resource, jobs in deadline danger first
// - jobs from projects with lower recent est. credit first
// In principle, the run list could include all runnable jobs.
// For efficiency, we stop adding:
// - GPU jobs: when all GPU instances used
// - CPU jobs: when the # of CPUs allocated to single-thread jobs,
// OR the # allocated to multi-thread jobs, exceeds # CPUs
// (ensure we have enough single-thread jobs
// in case we can't run the multi-thread jobs)
// NOTE: RAM usage is not taken into consideration
// in the process of building this list.
// It's possible that we include a bunch of jobs that can't run
// because of memory limits,
// even though there are other jobs that could run.
// - add running jobs to the list
// (in case they haven't finished time slice or checkpointed)
// - sort the list according to "more_important()"
// - shuffle the list to avoid starving multi-thread jobs
//
// - scan through the resulting list, running the jobs and preempting
// other jobs (enforce_run_list).
// Don't run a job if
// - its GPUs can't be assigned (possible if need >1 GPU)
// - it's a multi-thread job, and CPU usage would be #CPUs+1 or more
// - it's a single-thread job, don't oversaturate CPU
// (details depend on whether a MT job is running)
// - its memory usage would exceed RAM limits
// If there's a running job using a given app version,
// unstarted jobs using that app version
// are assumed to have the same working set size.
#include "cpp.h"
#ifdef _WIN32
#include "boinc_win.h"
#include "sysmon_win.h"
#else
#include "config.h"
#include <string>
#include <cstring>
#include <list>
#endif
#include "coproc.h"
#include "error_numbers.h"
#include "filesys.h"
#include "str_util.h"
#include "util.h"
#include "app.h"
#include "app_config.h"
#include "client_msgs.h"
#include "client_state.h"
#include "coproc_sched.h"
#include "log_flags.h"
#include "project.h"
#include "result.h"
using std::vector;
using std::list;
static double rec_sum;
// used in make_run_list() to keep track of resources used
// by jobs tentatively scheduled so far
//
struct PROC_RESOURCES {
int ncpus;
double ncpus_used_st; // #CPUs of GPU or single-thread jobs
double ncpus_used_mt; // #CPUs of multi-thread jobs
COPROCS pr_coprocs;
void init() {
ncpus = gstate.ncpus;
ncpus_used_st = 0;
ncpus_used_mt = 0;
pr_coprocs.clone(coprocs, false);
pr_coprocs.clear_usage();
}
// should we stop scanning jobs?
//
inline bool stop_scan_cpu() {
if (ncpus_used_st >= ncpus) return true;
if (ncpus_used_mt >= 2*ncpus) return true;
// kind of arbitrary, but need to have some limit
// in case there are only MT jobs, and lots of them
return false;
}
inline bool stop_scan_coproc(int rsc_type) {
COPROC& cp = pr_coprocs.coprocs[rsc_type];
for (int i=0; i<cp.count; i++) {
if (cp.usage[i] < 1) return false;
}
return true;
}
// should we consider scheduling this job?
// (i.e add it to the runnable list; not actually run it)
//
bool can_schedule(RESULT* rp, ACTIVE_TASK* atp) {
if (atp) {
// don't schedule if something's pending
//
switch (atp->task_state()) {
case PROCESS_ABORT_PENDING:
case PROCESS_QUIT_PENDING:
return false;
}
if (gstate.retry_shmem_time > gstate.now) {
if (atp->app_client_shm.shm == NULL) {
if (log_flags.cpu_sched_debug) {
msg_printf(rp->project, MSG_INFO,
"[cpu_sched_debug] waiting for shared mem: %s",
rp->name
);
}
atp->needs_shmem = true;
return false;
}
atp->needs_shmem = false;
}
}
if (rp->schedule_backoff > gstate.now) return false;
if (rp->uses_gpu()) {
if (gpu_suspend_reason) return false;
}
if (rp->uses_coprocs()) {
if (sufficient_coprocs(*rp)) {
return true;
} else {
return false;
}
} else if (rp->avp->avg_ncpus > 1) {
if (ncpus_used_mt == 0) return true;
return (ncpus_used_mt + rp->avp->avg_ncpus <= ncpus);
} else {
return (ncpus_used_st < ncpus);
}
}
// we've decided to add this to the runnable list; update bookkeeping
//
void schedule(RESULT* rp, ACTIVE_TASK* atp, bool is_edf) {
int rt = rp->avp->gpu_usage.rsc_type;
// see if it's possible this job will be ruled out
// when we try to actually run it
// (e.g. it won't fit in RAM, or it uses GPU type w/ exclusions)
// If so, don't reserve CPU/GPU for it, to avoid starvation scenario
//
bool may_not_run = false;
if (atp && atp->too_large) {
may_not_run = true;
}
if (rt) {
PROJECT* p = rp->project;
if (p->rsc_pwf[rt].ncoprocs_excluded > 0) {
may_not_run = true;
}
}
if (!may_not_run) {
if (rt) {
reserve_coprocs(*rp);
// don't increment CPU usage.
// This may seem odd; the reason is the following scenario:
// - this job uses lots of CPU (say, a whole one)
// - there's an uncheckpointed GPU job that uses little CPU
// - we end up running the uncheckpointed job
// - this causes all or part of a CPU to be idle
//
} else if (rp->avp->avg_ncpus > 1) {
ncpus_used_mt += rp->avp->avg_ncpus;
} else {
ncpus_used_st += rp->avp->avg_ncpus;
}
}
if (log_flags.cpu_sched_debug) {
msg_printf(rp->project, MSG_INFO,
"[cpu_sched_debug] add to run list: %s (%s, %s) (prio %f)",
rp->name,
rsc_name_long(rt),
is_edf?"EDF":"FIFO",
rp->project->sched_priority
);
}
adjust_rec_sched(rp);
}
bool sufficient_coprocs(RESULT& r) {
APP_VERSION& av = *r.avp;
int rt = av.gpu_usage.rsc_type;
if (!rt) return true;
double x = av.gpu_usage.usage;
COPROC& cp = pr_coprocs.coprocs[rt];
for (int i=0; i<cp.count; i++) {
if (gpu_excluded(r.app, cp, i)) continue;
double unused = 1 - cp.usage[i];
x -= unused;
if (x <= 0) return true;
}
if (log_flags.cpu_sched_debug) {
msg_printf(r.project, MSG_INFO,
"[cpu_sched_debug] insufficient %s for %s",
cp.type, r.name
);
}
return false;
}
void reserve_coprocs(RESULT& r) {
double x;
APP_VERSION& av = *r.avp;
int rt = av.gpu_usage.rsc_type;
COPROC& cp = pr_coprocs.coprocs[rt];
x = av.gpu_usage.usage;
for (int i=0; i<cp.count; i++) {
if (gpu_excluded(r.app, cp, i)) continue;
double unused = 1 - cp.usage[i];
if (unused >= x) {
cp.usage[i] += x;
break;
} else {
cp.usage[i] = 1;
x -= unused;
}
}
if (log_flags.cpu_sched_debug) {
msg_printf(r.project, MSG_INFO,
"[cpu_sched_debug] reserving %f of coproc %s",
av.gpu_usage.usage, cp.type
);
}
}
};
bool gpus_usable = true;
#ifndef SIM
// see whether there's been a change in coproc usability;
// if so set or clear "coproc_missing" flags and return true.
//
bool check_coprocs_usable() {
#ifdef _WIN32
unsigned int i;
bool new_usable = !is_remote_desktop();
if (gpus_usable) {
if (!new_usable) {
gpus_usable = false;
for (i=0; i<gstate.results.size(); i++) {
RESULT* rp = gstate.results[i];
if (rp->avp->gpu_usage.rsc_type) {
rp->coproc_missing = true;
}
}
msg_printf(NULL, MSG_INFO,
"Remote desktop in use; disabling GPU tasks"
);
return true;
}
} else {
if (new_usable) {
gpus_usable = true;
for (i=0; i<gstate.results.size(); i++) {
RESULT* rp = gstate.results[i];
if (rp->avp->gpu_usage.rsc_type) {
rp->coproc_missing = false;
}
}
msg_printf(NULL, MSG_INFO,
"Remote desktop not in use; enabling GPU tasks"
);
return true;
}
}
#endif
return false;
}
#endif
// return true if the task has finished its time slice
// and has checkpointed since the end of the time slice
// (called only for scheduled tasks)
//
static inline bool finished_time_slice(ACTIVE_TASK* atp) {
double time_slice_end = atp->run_interval_start_wall_time + gstate.global_prefs.cpu_scheduling_period();
bool running_beyond_sched_period = gstate.now > time_slice_end;
bool checkpointed = atp->checkpoint_wall_time > time_slice_end;
if (running_beyond_sched_period && !checkpointed) {
atp->overdue_checkpoint = true;
}
return (running_beyond_sched_period && checkpointed);
}
// Choose a "best" runnable CPU job for each project
//
// Values are returned in project->next_runnable_result
// (skip projects for which this is already non-NULL)
//
// Don't choose results with already_selected == true;
// mark chosen results as already_selected.
//
// The preference order:
// 1. results with active tasks that are running
// 2. results with active tasks that are preempted (but have a process)
// 3. results with active tasks that have no process
// 4. results with no active task
//
// TODO: this is called in a loop over NCPUs, which is silly.
// Should call it once, and have it make an ordered list per project.
//
void CLIENT_STATE::assign_results_to_projects() {
unsigned int i;
RESULT* rp;
PROJECT* project;
// scan results with an ACTIVE_TASK
//
for (i=0; i<active_tasks.active_tasks.size(); i++) {
ACTIVE_TASK *atp = active_tasks.active_tasks[i];
if (!atp->runnable()) continue;
rp = atp->result;
if (rp->already_selected) continue;
if (rp->uses_coprocs()) continue;
if (!rp->runnable()) continue;
project = rp->project;
if (!project->next_runnable_result) {
project->next_runnable_result = rp;
continue;
}
// see if this task is "better" than the one currently
// selected for this project
//
ACTIVE_TASK *next_atp = lookup_active_task_by_result(
project->next_runnable_result
);
if ((next_atp->task_state() == PROCESS_UNINITIALIZED && atp->process_exists())
|| (next_atp->scheduler_state == CPU_SCHED_PREEMPTED
&& atp->scheduler_state == CPU_SCHED_SCHEDULED)
) {
project->next_runnable_result = atp->result;
}
}
// Now consider results that don't have an active task
//
for (i=0; i<results.size(); i++) {
rp = results[i];
if (rp->already_selected) continue;
if (rp->uses_coprocs()) continue;
if (lookup_active_task_by_result(rp)) continue;
if (!rp->runnable()) continue;
project = rp->project;
if (project->next_runnable_result) continue;
project->next_runnable_result = rp;
}
// mark selected results, so CPU scheduler won't try to consider
// a result more than once
//
for (i=0; i<projects.size(); i++) {
project = projects[i];
if (project->next_runnable_result) {
project->next_runnable_result->already_selected = true;
}
}
}
// Among projects with a "next runnable result",
// find the project P with the largest priority,
// and return its next runnable result
//
RESULT* CLIENT_STATE::highest_prio_project_best_result() {
PROJECT *best_project = NULL;
double best_prio = 0;
bool first = true;
unsigned int i;
for (i=0; i<projects.size(); i++) {
PROJECT* p = projects[i];
if (!p->next_runnable_result) continue;
if (p->non_cpu_intensive) continue;
if (first || p->sched_priority > best_prio) {
first = false;
best_project = p;
best_prio = p->sched_priority;
}
}
if (!best_project) return NULL;
RESULT* rp = best_project->next_runnable_result;
best_project->next_runnable_result = 0;
return rp;
}
// Return a job of the given type according to the following criteria
// (desc priority):
// - from project with higher priority
// - already-started job
// - earlier received_time
// - lexicographically earlier name
//
// Give priority to already-started jobs because of the following scenario:
// - client gets several jobs in a sched reply and starts downloading files
// - a later job finishes downloading and starts
// - an earlier finishes downloading and preempts
//
RESULT* first_coproc_result(int rsc_type) {
unsigned int i;
RESULT* best = NULL;
double best_prio=0, prio;
for (i=0; i<gstate.results.size(); i++) {
RESULT* rp = gstate.results[i];
if (rp->resource_type() != rsc_type) continue;
if (!rp->runnable()) {
//msg_printf(rp->project, MSG_INFO, "not runnable: %s", rp->name);
continue;
}
if (rp->non_cpu_intensive()) continue;
if (rp->already_selected) continue;
prio = rp->project->sched_priority;
if (!best) {
best = rp;
best_prio = prio;
continue;
}
if (prio < best_prio) {
continue;
}
if (prio > best_prio) {
best = rp;
best_prio = prio;
continue;
}
bool bs = !best->not_started;
bool rs = !rp->not_started;
if (rs && !bs) {
best = rp;
best_prio = prio;
continue;
}
if (!rs && bs) {
continue;
}
// else used "arrived first" order
//
if (rp->index < best->index) {
best = rp;
best_prio = prio;
}
}
return best;
}
// Return earliest-deadline result for given resource type;
// return only results projected to miss their deadline,
// or from projects with extreme DCF
//
static RESULT* earliest_deadline_result(int rsc_type) {
RESULT *best_result = NULL;
ACTIVE_TASK* best_atp = NULL;
unsigned int i;
for (i=0; i<gstate.results.size(); i++) {
RESULT* rp = gstate.results[i];
if (rp->resource_type() != rsc_type) continue;
if (rp->already_selected) continue;
if (!rp->runnable()) continue;
if (rp->non_cpu_intensive()) continue;
PROJECT* p = rp->project;
// Skip this job if the project's deadline-miss count is zero.
// If the project's DCF is > 90 (and we're not ignoring it)
// treat all jobs as deadline misses
//
if (p->dont_use_dcf || p->duration_correction_factor < 90.0) {
if (p->rsc_pwf[rsc_type].deadlines_missed_copy <= 0) {
continue;
}
}
bool new_best = false;
if (best_result) {
if (rp->report_deadline < best_result->report_deadline) {
new_best = true;
}
} else {
new_best = true;
}
if (new_best) {
best_result = rp;
best_atp = gstate.lookup_active_task_by_result(rp);
continue;
}
if (rp->report_deadline > best_result->report_deadline) {
continue;
}
// If there's a tie, pick the job with the least remaining time
// (but don't pick an unstarted job over one that's started)
//
ACTIVE_TASK* atp = gstate.lookup_active_task_by_result(rp);
if (best_atp && !atp) continue;
if (rp->estimated_runtime_remaining() < best_result->estimated_runtime_remaining()
|| (!best_atp && atp)
) {
best_result = rp;
best_atp = atp;
}
}
if (!best_result) return NULL;
return best_result;
}
void CLIENT_STATE::reset_rec_accounting() {
unsigned int i;
for (i=0; i<projects.size(); i++) {
PROJECT* p = projects[i];
for (int j=0; j<coprocs.n_rsc; j++) {
p->rsc_pwf[j].reset_rec_accounting();
}
}
for (int j=0; j<coprocs.n_rsc; j++) {
rsc_work_fetch[j].reset_rec_accounting();
}
rec_interval_start = now;
}
// update per-project accounting:
// - recent estimated credit (EC)
// - total CPU and GPU EC
// - total CPU and GPU time
//
static void update_rec() {
double f = gstate.host_info.p_fpops;
double on_frac = gstate.global_prefs.cpu_usage_limit / 100;
for (unsigned int i=0; i<gstate.projects.size(); i++) {
PROJECT* p = gstate.projects[i];
double x = 0;
for (int j=0; j<coprocs.n_rsc; j++) {
double dt = p->rsc_pwf[j].secs_this_rec_interval * on_frac;
double flops = dt * f * rsc_work_fetch[j].relative_speed;
x += flops;
if (j) {
p->gpu_ec += flops*COBBLESTONE_SCALE;
p->gpu_time += dt;
} else {
p->cpu_ec += flops*COBBLESTONE_SCALE;
p->cpu_time += dt;
}
}
x *= COBBLESTONE_SCALE;
double old = p->pwf.rec;
// start averages at zero
//
if (p->pwf.rec_time == 0) {
p->pwf.rec_time = gstate.rec_interval_start;
}
update_average(
gstate.now,
gstate.rec_interval_start,
x,
cc_config.rec_half_life,
p->pwf.rec,
p->pwf.rec_time
);
if (log_flags.priority_debug) {
double dt = gstate.now - gstate.rec_interval_start;
msg_printf(p, MSG_INFO,
"[prio] recent est credit: %.2fG in %.2f sec, %f + %f ->%f",
x, dt, old, p->pwf.rec-old, p->pwf.rec
);
}
}
}
static double peak_flops(APP_VERSION* avp) {
double f = gstate.host_info.p_fpops;
double x = f * avp->avg_ncpus;
int rt = avp->gpu_usage.rsc_type;
if (rt) {
x += f * avp->gpu_usage.usage * rsc_work_fetch[rt].relative_speed;
}
return x;
}
double total_peak_flops() {
static bool first=true;
static double tpf;
if (first) {
first = false;
tpf = gstate.host_info.p_fpops * gstate.ncpus;
for (int i=1; i<coprocs.n_rsc; i++) {
COPROC& cp = coprocs.coprocs[i];
tpf += rsc_work_fetch[i].relative_speed * gstate.host_info.p_fpops * cp.count;
}
}
return tpf;
}
// Initialize project "priorities" based on REC:
// compute resource share and REC fractions
// among compute-intensive, non-suspended projects
//
void project_priority_init(bool for_work_fetch) {
double rs_sum = 0;
rec_sum = 0;
for (unsigned int i=0; i<gstate.projects.size(); i++) {
PROJECT* p = gstate.projects[i];
if (p->non_cpu_intensive) continue;
if (for_work_fetch) {
if (!p->can_request_work()) continue;
} else {
if (!p->runnable(RSC_TYPE_ANY)) continue;
}
p->pwf.rec_temp = p->pwf.rec;
rs_sum += p->resource_share;
rec_sum += p->pwf.rec_temp;
}
if (rec_sum == 0) {
rec_sum = 1;
}
for (unsigned int i=0; i<gstate.projects.size(); i++) {
PROJECT* p = gstate.projects[i];
if (p->non_cpu_intensive || p->suspended_via_gui || rs_sum==0) {
p->resource_share_frac = 0;
p->sched_priority = 0;
} else {
p->resource_share_frac = p->resource_share/rs_sum;
p->compute_sched_priority();
if (log_flags.priority_debug) {
msg_printf(p, MSG_INFO, "[prio] %f rsf %f rt %f rs %f",
p->sched_priority, p->resource_share_frac,
p->pwf.rec_temp, rec_sum
);
}
}
}
}
void PROJECT::compute_sched_priority() {
double rec_frac = pwf.rec_temp/rec_sum;
// projects with zero resource share are always lower priority
// than those with positive resource share
//
if (resource_share == 0) {
sched_priority = -1e3 - rec_frac;
} else {
sched_priority = - rec_frac/resource_share_frac;
}
}
// called from the scheduler's job-selection loop;
// we plan to run this job;
// bump the project's temp REC by the estimated credit for 1 hour.
// This encourages a mixture jobs from different projects.
//
void adjust_rec_sched(RESULT* rp) {
PROJECT* p = rp->project;
p->pwf.rec_temp += peak_flops(rp->avp)/total_peak_flops() * rec_sum/24;
p->compute_sched_priority();
}
// make this a variable so simulator can change it
//
double rec_adjust_period = REC_ADJUST_PERIOD;
// adjust project REC
//
void CLIENT_STATE::adjust_rec() {
unsigned int i;
double elapsed_time = now - rec_interval_start;
// If the elapsed time is negative or more than 2*REC_ADJUST_PERIOD
// it must be because either
// - the system clock was changed.
// - the host was suspended for a long time.
// In either case, ignore the last period
//
if (elapsed_time > 2*rec_adjust_period || elapsed_time < 0) {
if (log_flags.priority_debug) {
msg_printf(NULL, MSG_INFO,
"[priority] adjust_rec: elapsed time (%.0f) negative or longer than sched enforce period(%.0f). Ignoring this period.",
elapsed_time, rec_adjust_period
);
}
reset_rec_accounting();
return;
}
// skip small intervals
//
if (elapsed_time < 1) {
return;
}
// total up how many instance-seconds projects got
//
for (i=0; i<active_tasks.active_tasks.size(); i++) {
ACTIVE_TASK* atp = active_tasks.active_tasks[i];
if (atp->scheduler_state != CPU_SCHED_SCHEDULED) continue;
PROJECT* p = atp->result->project;
if (p->non_cpu_intensive) continue;
work_fetch.accumulate_inst_sec(atp, elapsed_time);
}
update_rec();
reset_rec_accounting();
}
// Possibly do job scheduling.
// This is called periodically.
//
bool CLIENT_STATE::schedule_cpus() {
double elapsed_time;
static double last_reschedule=0;
vector<RESULT*> run_list;
if (projects.size() == 0) return false;
if (results.size() == 0) return false;
// Reschedule every CPU_SCHED_PERIOD seconds,
// or if must_schedule_cpus is set
// (meaning a new result is available, or a CPU has been freed).
//
elapsed_time = now - last_reschedule;
if (gstate.clock_change || elapsed_time >= CPU_SCHED_PERIOD) {
request_schedule_cpus("periodic CPU scheduling");
}
if (!must_schedule_cpus) return false;
last_reschedule = now;
must_schedule_cpus = false;
// NOTE: there's an assumption that REC is adjusted at
// least as often as the CPU sched period (see client_state.h).
// If you remove the following, make changes accordingly
//
adjust_rec();
make_run_list(run_list);
return enforce_run_list(run_list);
}
// Mark a job J as a deadline miss if either
// - it once ran in EDF, and its project has another job
// of the same resource type marked as deadline miss.
// This avoids domino-effect preemption
// - it was recently marked as a deadline miss by RR sim.
// This avoids "thrashing" if a job oscillates between miss and not miss.
//
static void promote_once_ran_edf() {
for (unsigned int i=0; i<gstate.active_tasks.active_tasks.size(); i++) {
ACTIVE_TASK* atp = gstate.active_tasks.active_tasks[i];
if (atp->result->rr_sim_misses_deadline) continue;
if (atp->once_ran_edf) {
RESULT* rp = atp->result;
PROJECT* p = rp->project;
if (p->deadlines_missed(rp->avp->rsc_type())) {
if (log_flags.cpu_sched_debug) {
msg_printf(p, MSG_INFO,
"[cpu_sched_debug] domino prevention: mark %s as deadline miss",
rp->name
);
}
rp->rr_sim_misses_deadline = true;
continue;
}
}
if (gstate.now - atp->last_deadline_miss_time < gstate.global_prefs.cpu_scheduling_period()) {
if (log_flags.cpu_sched_debug) {
RESULT* rp = atp->result;
PROJECT* p = rp->project;
msg_printf(p, MSG_INFO,
"[cpu_sched_debug] thrashing prevention: mark %s as deadline miss",
rp->name
);
}
atp->result->rr_sim_misses_deadline = true;
}
}
}
void add_coproc_jobs(
vector<RESULT*>& run_list, int rsc_type, PROC_RESOURCES& proc_rsc
) {
ACTIVE_TASK* atp;
RESULT* rp;
#ifdef SIM
if (!cpu_sched_rr_only) {
#endif
// choose coproc jobs from projects with coproc deadline misses
//
while (!proc_rsc.stop_scan_coproc(rsc_type)) {
rp = earliest_deadline_result(rsc_type);
if (!rp) break;
rp->already_selected = true;
atp = gstate.lookup_active_task_by_result(rp);
if (!proc_rsc.can_schedule(rp, atp)) continue;
proc_rsc.schedule(rp, atp, true);
rp->project->rsc_pwf[rsc_type].deadlines_missed_copy--;
rp->edf_scheduled = true;
run_list.push_back(rp);
}
#ifdef SIM
}
#endif
// then coproc jobs in FIFO order
//
while (!proc_rsc.stop_scan_coproc(rsc_type)) {
rp = first_coproc_result(rsc_type);
if (!rp) break;
rp->already_selected = true;
atp = gstate.lookup_active_task_by_result(rp);
if (!proc_rsc.can_schedule(rp, atp)) continue;
proc_rsc.schedule(rp, atp, false);
run_list.push_back(rp);
}
}
// Make an ordered list of jobs to run.
//
void CLIENT_STATE::make_run_list(vector<RESULT*>& run_list) {
RESULT* rp;
PROJECT* p;
unsigned int i;
PROC_RESOURCES proc_rsc;
ACTIVE_TASK* atp;
if (log_flags.cpu_sched_debug) {
msg_printf(0, MSG_INFO, "[cpu_sched_debug] schedule_cpus(): start");
}
proc_rsc.init();
// do round-robin simulation to find what results miss deadline
//
rr_simulation("CPU sched");
if (log_flags.rr_simulation) {
print_deadline_misses();
}
// avoid preemption of jobs that once ran EDF
//
promote_once_ran_edf();
// set temporary variables
//
project_priority_init(false);
for (i=0; i<results.size(); i++) {
rp = results[i];
rp->already_selected = false;
rp->edf_scheduled = false;
rp->not_started = !rp->computing_done();
}
for (i=0; i<projects.size(); i++) {
p = projects[i];
p->next_runnable_result = NULL;
for (int j=0; j<coprocs.n_rsc; j++) {
p->rsc_pwf[j].deadlines_missed_copy = p->rsc_pwf[j].deadlines_missed;
}
}
// compute max working set size for app versions
// (max of working sets of currently running jobs)
//
for (i=0; i<app_versions.size(); i++) {
app_versions[i]->max_working_set_size = 0;
}
for (i=0; i<active_tasks.active_tasks.size(); i++) {
atp = active_tasks.active_tasks[i];
atp->too_large = false;
double w = atp->procinfo.working_set_size_smoothed;
APP_VERSION* avp = atp->app_version;
if (w > avp->max_working_set_size) {
avp->max_working_set_size = w;
}
atp->result->not_started = false;
}
// first, add GPU jobs
for (int j=1; j<coprocs.n_rsc; j++) {
add_coproc_jobs(run_list, j, proc_rsc);
}
// enforce max concurrent specs for CPU jobs,
// to avoid having jobs in the run list that we can't actually run.
// Don't do this for GPU jobs; GPU exclusions screw things up
//
if (have_max_concurrent) {
max_concurrent_init();
}
// then add CPU jobs.
// Note: the jobs that actually get run are not necessarily
// an initial segment of this list;
// e.g. a multithread job may not get run because it has
// a high-priority single-thread job ahead of it.
// choose CPU jobs from projects with CPU deadline misses
//
#ifdef SIM
if (!cpu_sched_rr_only) {
#endif
while (!proc_rsc.stop_scan_cpu()) {
rp = earliest_deadline_result(RSC_TYPE_CPU);
if (!rp) break;
rp->already_selected = true;
if (have_max_concurrent && max_concurrent_exceeded(rp)) {
continue;
}
atp = lookup_active_task_by_result(rp);
if (!proc_rsc.can_schedule(rp, atp)) continue;
proc_rsc.schedule(rp, atp, true);
rp->project->rsc_pwf[0].deadlines_missed_copy--;
rp->edf_scheduled = true;
run_list.push_back(rp);
if (have_max_concurrent) {
max_concurrent_inc(rp);
}
}
#ifdef SIM
}
#endif
// Next, choose CPU jobs from highest priority projects
//
while (1) {
if (proc_rsc.stop_scan_cpu()) {
break;
}
assign_results_to_projects();
rp = highest_prio_project_best_result();
if (!rp) {
break;
}
if (have_max_concurrent && max_concurrent_exceeded(rp)) {
continue;
}
atp = lookup_active_task_by_result(rp);
if (!proc_rsc.can_schedule(rp, atp)) continue;
proc_rsc.schedule(rp, atp, false);
run_list.push_back(rp);
if (have_max_concurrent) {
max_concurrent_inc(rp);
}
}
}
static inline bool in_run_list(vector<RESULT*>& run_list, ACTIVE_TASK* atp) {
for (unsigned int i=0; i<run_list.size(); i++) {
if (atp->result == run_list[i]) return true;
}
return false;
}
#if 0
// scan the runnable list, keeping track of CPU usage X.
// if find a MT job J, and X < ncpus, move J before all non-MT jobs
// But don't promote a MT job ahead of a job in EDF
//
// This is needed because there may always be a 1-CPU job
// in the middle of its time-slice, and MT jobs could starve.
//
static void promote_multi_thread_jobs(vector<RESULT*>& runnable_jobs) {
double cpus_used = 0;
vector<RESULT*>::iterator first_non_mt = runnable_jobs.end();
vector<RESULT*>::iterator cur = runnable_jobs.begin();
while(1) {
if (cur == runnable_jobs.end()) break;
if (cpus_used >= gstate.ncpus) break;
RESULT* rp = *cur;
if (rp->rr_sim_misses_deadline) break;
double nc = rp->avp->avg_ncpus;
if (nc > 1) {
if (first_non_mt != runnable_jobs.end()) {
cur = runnable_jobs.erase(cur);
runnable_jobs.insert(first_non_mt, rp);
cpus_used = 0;
first_non_mt = runnable_jobs.end();
cur = runnable_jobs.begin();
continue;
}
} else {
if (first_non_mt == runnable_jobs.end()) {
first_non_mt = cur;
}
}
cpus_used += nc;
cur++;
}
}
#endif
// return true if r0 is more important to run than r1
//
static inline bool more_important(RESULT* r0, RESULT* r1) {
// favor jobs in danger of deadline miss
//
bool miss0 = r0->edf_scheduled;
bool miss1 = r1->edf_scheduled;
if (miss0 && !miss1) return true;
if (!miss0 && miss1) return false;
// favor coproc jobs, so that e.g. if we're RAM-limited
// we'll use the GPU instead of the CPU
//
bool cp0 = r0->uses_coprocs();
bool cp1 = r1->uses_coprocs();
if (cp0 && !cp1) return true;
if (!cp0 && cp1) return false;
// favor jobs in the middle of time slice,
// or that haven't checkpointed since start of time slice
//
bool unfin0 = r0->unfinished_time_slice;
bool unfin1 = r1->unfinished_time_slice;
if (unfin0 && !unfin1) return true;
if (!unfin0 && unfin1) return false;
// for CPU jobs, favor jobs that use more CPUs
//
if (!cp0) {
if (r0->avp->avg_ncpus > r1->avp->avg_ncpus) return true;
if (r1->avp->avg_ncpus > r0->avp->avg_ncpus) return false;
}
// favor jobs selected first by schedule_cpus()
// (e.g., because their project has high sched priority)
//
if (r0->seqno < r1->seqno) return true;
if (r0->seqno > r1->seqno) return false;
// tie breaker
return (r0 < r1);
}
static void print_job_list(vector<RESULT*>& jobs) {
for (unsigned int i=0; i<jobs.size(); i++) {
RESULT* rp = jobs[i];
msg_printf(rp->project, MSG_INFO,
"[cpu_sched_debug] %d: %s (MD: %s; UTS: %s)",
i, rp->name,
rp->edf_scheduled?"yes":"no",
rp->unfinished_time_slice?"yes":"no"
);
}
}
// find running jobs that haven't finished their time slice.
// Mark them as such, and add to list if not already there
//
void CLIENT_STATE::append_unfinished_time_slice(vector<RESULT*> &run_list) {
unsigned int i;
int seqno = (int)run_list.size();
for (i=0; i<active_tasks.active_tasks.size(); i++) {
ACTIVE_TASK* atp = active_tasks.active_tasks[i];
atp->overdue_checkpoint = false;
if (!atp->result->runnable()) continue;
if (atp->result->uses_gpu() && gpu_suspend_reason) continue;
if (atp->result->non_cpu_intensive()) continue;
if (atp->scheduler_state != CPU_SCHED_SCHEDULED) continue;
if (finished_time_slice(atp)) continue;
atp->result->unfinished_time_slice = true;
if (in_run_list(run_list, atp)) continue;
run_list.push_back(atp->result);
atp->result->seqno = seqno;
}
}
// Enforce the CPU schedule.
// Inputs:
// ordered_scheduled_results
// List of tasks that should (ideally) run, set by schedule_cpus().
// Most important tasks (e.g. early deadline) are first.
// The set of tasks that actually run may be different:
// - if a task hasn't checkpointed recently we avoid preempting it
// - we don't run tasks that would exceed working-set limits
// Details:
// Initially, each task's scheduler_state is PREEMPTED or SCHEDULED
// depending on whether or not it is running.
// This function sets each task's next_scheduler_state,
// and at the end it starts/resumes and preempts tasks
// based on scheduler_state and next_scheduler_state.
//
bool CLIENT_STATE::enforce_run_list(vector<RESULT*>& run_list) {
unsigned int i;
int retval;
double ncpus_used=0;
ACTIVE_TASK* atp;
bool action = false;
if (have_max_concurrent) {
max_concurrent_init();
}
#ifndef SIM
// check whether GPUs are usable
//
if (check_coprocs_usable()) {
request_schedule_cpus("GPU usability change");
return true;
}
#endif
if (log_flags.cpu_sched_debug) {
msg_printf(0, MSG_INFO, "[cpu_sched_debug] enforce_run_list(): start");
msg_printf(0, MSG_INFO, "[cpu_sched_debug] preliminary job list:");
print_job_list(run_list);
}
// Set next_scheduler_state to PREEMPT for all tasks
//
for (i=0; i< active_tasks.active_tasks.size(); i++) {
atp = active_tasks.active_tasks[i];
atp->next_scheduler_state = CPU_SCHED_PREEMPTED;
}
for (i=0; i<run_list.size(); i++) {
RESULT* rp = run_list[i];
rp->seqno = i;
rp->unfinished_time_slice = false;
}
// append running jobs not done with time slice to the to-run list
//
append_unfinished_time_slice(run_list);
// sort to-run list by decreasing importance
//
std::sort(
run_list.begin(),
run_list.end(),
more_important
);
#if 0
promote_multi_thread_jobs(run_list);
#endif
if (log_flags.cpu_sched_debug) {
msg_printf(0, MSG_INFO, "[cpu_sched_debug] final job list:");
print_job_list(run_list);
}
double ram_left = available_ram();
double swap_left = (global_prefs.vm_max_used_frac)*host_info.m_swap;
if (log_flags.mem_usage_debug) {
msg_printf(0, MSG_INFO,
"[mem_usage] enforce: available RAM %.2fMB swap %.2fMB",
ram_left/MEGA, swap_left/MEGA
);
}
// schedule non-CPU-intensive tasks,
// and look for backed-off GPU jobs
//
for (i=0; i<results.size(); i++) {
RESULT* rp = results[i];
if (rp->non_cpu_intensive() && rp->runnable()) {
atp = get_task(rp);
if (!atp) {
msg_printf(rp->project, MSG_INTERNAL_ERROR,
"Can't create task for %s", rp->name
);
continue;
}
atp->next_scheduler_state = CPU_SCHED_SCHEDULED;
// don't count RAM usage because it's used sporadically,
// and doing so can starve other jobs
//
//ram_left -= atp->procinfo.working_set_size_smoothed;
swap_left -= atp->procinfo.swap_size;
}
}
// assign coprocessors to coproc jobs,
// and prune those that can't be assigned
//
assign_coprocs(run_list);
//bool scheduled_mt = false;
// prune jobs that don't fit in RAM or that exceed CPU usage limits.
// Mark the rest as SCHEDULED
//
for (i=0; i<run_list.size(); i++) {
RESULT* rp = run_list[i];
if (have_max_concurrent && max_concurrent_exceeded(rp)) {
if (log_flags.cpu_sched_debug) {
msg_printf(rp->project, MSG_INFO,
"[cpu_sched_debug] skipping %s; max concurrent limit reached",
rp->name
);
}
continue;
}
atp = lookup_active_task_by_result(rp);
// if we're already using all the CPUs,
// don't allow additional CPU jobs;
// allow coproc jobs if the resulting CPU load is at most ncpus+1
//
if (ncpus_used >= ncpus) {
if (rp->uses_coprocs()) {
if (ncpus_used + rp->avp->avg_ncpus > ncpus+1) {
if (log_flags.cpu_sched_debug) {
msg_printf(rp->project, MSG_INFO,
"[cpu_sched_debug] skipping GPU job %s; CPU committed",
rp->name
);
}
continue;
}
} else {
if (log_flags.cpu_sched_debug) {
msg_printf(rp->project, MSG_INFO,
"[cpu_sched_debug] all CPUs used (%.2f >= %d), skipping %s",
ncpus_used, ncpus,
rp->name
);
}
continue;
}
}
#if 0
// Don't overcommit CPUs by > 1 if a MT job is scheduled.
// Skip this check for coproc jobs.
//
if (!rp->uses_coprocs()
&& (scheduled_mt || (rp->avp->avg_ncpus > 1))
&& (ncpus_used + rp->avp->avg_ncpus > ncpus + 1)
) {
if (log_flags.cpu_sched_debug) {
msg_printf(rp->project, MSG_INFO,
"[cpu_sched_debug] avoid MT overcommit: skipping %s",
rp->name
);
}
continue;
}
#endif
// skip jobs whose working set is too large to fit in available RAM
//
double wss = 0;
if (atp) {
atp->too_large = false;
wss = atp->procinfo.working_set_size_smoothed;
} else {
wss = rp->avp->max_working_set_size;
}
if (wss == 0) {
wss = rp->wup->rsc_memory_bound;
}
if (wss > ram_left) {
if (atp) {
atp->too_large = true;
}
if (log_flags.cpu_sched_debug || log_flags.mem_usage_debug) {
msg_printf(rp->project, MSG_INFO,
"[cpu_sched_debug] enforce: task %s can't run, too big %.2fMB > %.2fMB",
rp->name, wss/MEGA, ram_left/MEGA
);
}
continue;
}
if (log_flags.cpu_sched_debug) {
msg_printf(rp->project, MSG_INFO,
"[cpu_sched_debug] scheduling %s%s",
rp->name,
rp->edf_scheduled?" (high priority)":""
);
}
// We've decided to run this job; create an ACTIVE_TASK if needed.
//
if (!atp) {
atp = get_task(rp);
}
if (!atp) {
msg_printf(rp->project, MSG_INTERNAL_ERROR,
"Can't create task for %s", rp->name
);
continue;
}
#if 0
if (rp->avp->avg_ncpus > 1) {
scheduled_mt = true;
}
#endif
ncpus_used += rp->avp->avg_ncpus;
atp->next_scheduler_state = CPU_SCHED_SCHEDULED;
ram_left -= wss;
if (have_max_concurrent) {
max_concurrent_inc(rp);
}
}
if (log_flags.cpu_sched_debug && ncpus_used < ncpus) {
msg_printf(0, MSG_INFO, "[cpu_sched_debug] using %.2f out of %d CPUs",
ncpus_used, ncpus
);
if (ncpus_used < ncpus) {
request_work_fetch("CPUs idle");
}
}
bool check_swap = (host_info.m_swap != 0);
// in case couldn't measure swap on this host
// TODO: enforcement of swap space is broken right now
// preempt tasks as needed, and note whether there are any coproc jobs
// in QUIT_PENDING state (in which case we won't start new coproc jobs)
//
bool coproc_quit_pending = false;
for (i=0; i<active_tasks.active_tasks.size(); i++) {
atp = active_tasks.active_tasks[i];
#if 0
if (log_flags.cpu_sched_debug) {
msg_printf(atp->result->project, MSG_INFO,
"[cpu_sched_debug] %s sched state %d next %d task state %d",
atp->result->name, atp->scheduler_state,
atp->next_scheduler_state, atp->task_state()
);
}
#endif
int preempt_type = REMOVE_MAYBE_SCHED;
switch (atp->next_scheduler_state) {
case CPU_SCHED_PREEMPTED:
switch (atp->task_state()) {
case PROCESS_EXECUTING:
action = true;
if (check_swap && swap_left < 0) {
if (log_flags.mem_usage_debug) {
msg_printf(atp->result->project, MSG_INFO,
"[mem_usage] out of swap space, will preempt by quit"
);
}
preempt_type = REMOVE_ALWAYS;
}
if (atp->too_large) {
if (log_flags.mem_usage_debug) {
msg_printf(atp->result->project, MSG_INFO,
"[mem_usage] job using too much memory, will preempt by quit"
);
}
preempt_type = REMOVE_ALWAYS;
}
atp->preempt(preempt_type);
break;
case PROCESS_SUSPENDED:
// remove from memory GPU jobs that were suspended by CPU throttling
// and are now unscheduled.
//
if (atp->result->uses_gpu()) {
atp->preempt(REMOVE_ALWAYS);
request_schedule_cpus("removed suspended GPU task");
break;
}
// Handle the case where user changes prefs from
// "leave in memory" to "remove from memory";
// need to quit suspended tasks.
//
if (atp->checkpoint_cpu_time && !global_prefs.leave_apps_in_memory) {
atp->preempt(REMOVE_ALWAYS);
}
break;
}
atp->scheduler_state = CPU_SCHED_PREEMPTED;
break;
}
if (atp->result->uses_coprocs() && atp->task_state() == PROCESS_QUIT_PENDING) {
coproc_quit_pending = true;
}
}
bool coproc_start_deferred = false;
for (i=0; i<active_tasks.active_tasks.size(); i++) {
atp = active_tasks.active_tasks[i];
if (atp->next_scheduler_state != CPU_SCHED_SCHEDULED) continue;
int ts = atp->task_state();
if (ts == PROCESS_UNINITIALIZED || ts == PROCESS_SUSPENDED) {
// If there's a quit pending for a coproc job,
// don't start new ones since they may bomb out
// on memory allocation. Instead, trigger a retry
//
if (atp->result->uses_coprocs() && coproc_quit_pending) {
coproc_start_deferred = true;
continue;
}
action = true;
bool first_time;
// GPU tasks can get suspended before they're ever run,
// so the only safe way of telling whether this is the
// first time the app is run is to check
// whether the slot dir is empty
//
#ifdef SIM
first_time = atp->scheduler_state == CPU_SCHED_UNINITIALIZED;
#else
first_time = is_dir_empty(atp->slot_dir);
#endif
retval = atp->resume_or_start(first_time);
if ((retval == ERR_SHMGET) || (retval == ERR_SHMAT)) {
// Assume no additional shared memory segs
// will be available in the next 10 seconds
// (run only tasks which are already attached to shared memory).
//
if (gstate.retry_shmem_time < gstate.now) {
request_schedule_cpus("no more shared memory");
}
gstate.retry_shmem_time = gstate.now + 10.0;
continue;
}
if (retval) {
char err_msg[4096];
snprintf(err_msg, sizeof(err_msg),
"Couldn't start or resume: %d", retval
);
report_result_error(*(atp->result), err_msg);
request_schedule_cpus("start failed");
continue;
}
if (atp->result->rr_sim_misses_deadline) {
atp->once_ran_edf = true;
}
atp->run_interval_start_wall_time = now;
app_started = now;
}
if (log_flags.cpu_sched_status) {
msg_printf(atp->result->project, MSG_INFO,
"[css] running %s (%s)",
atp->result->name, atp->result->resources
);
}
atp->scheduler_state = CPU_SCHED_SCHEDULED;
swap_left -= atp->procinfo.swap_size;
#ifndef SIM
// if we've been in this loop for > 10 secs,
// break out of it and arrange for another schedule()
// so that we don't miss GUI RPCs, heartbeats etc.
//
if (dtime() - now > MAX_STARTUP_TIME) {
if (log_flags.cpu_sched_debug) {
msg_printf(0, MSG_INFO,
"[cpu_sched_debug] app startup took %f secs", dtime() - now
);
}
request_schedule_cpus("slow app startup");
break;
}
#endif
}
if (action) {
set_client_state_dirty("enforce_cpu_schedule");
}
if (log_flags.cpu_sched_debug) {
msg_printf(0, MSG_INFO, "[cpu_sched_debug] enforce_run_list: end");
}
if (coproc_start_deferred) {
if (log_flags.cpu_sched_debug) {
msg_printf(0, MSG_INFO,
"[cpu_sched_debug] coproc quit pending, deferring start"
);
}
request_schedule_cpus("coproc quit retry");
}
return action;
}
// trigger CPU scheduling.
// Called when a result is completed,
// when new results become runnable,
// or when the user performs a UI interaction
// (e.g. suspending or resuming a project or result).
//
void CLIENT_STATE::request_schedule_cpus(const char* where) {
if (log_flags.cpu_sched_debug) {
msg_printf(0, MSG_INFO, "[cpu_sched_debug] Request CPU reschedule: %s", where);
}
must_schedule_cpus = true;
}
// Find the active task for a given result
//
ACTIVE_TASK* CLIENT_STATE::lookup_active_task_by_result(RESULT* rep) {
for (unsigned int i = 0; i < active_tasks.active_tasks.size(); i ++) {
if (active_tasks.active_tasks[i]->result == rep) {
return active_tasks.active_tasks[i];
}
}
return NULL;
}
// find total resource shares of all CPU-intensive projects
//
double CLIENT_STATE::total_resource_share() {
double x = 0;
for (unsigned int i=0; i<projects.size(); i++) {
if (!projects[i]->non_cpu_intensive ) {
x += projects[i]->resource_share;
}
}
return x;
}
// same, but only runnable projects (can use CPU right now)
//
double CLIENT_STATE::runnable_resource_share(int rsc_type) {
double x = 0;
for (unsigned int i=0; i<projects.size(); i++) {
PROJECT* p = projects[i];
if (p->non_cpu_intensive) continue;
if (p->runnable(rsc_type)) {
x += p->resource_share;
}
}
return x;
}
// same, but potentially runnable (could ask for work right now)
//
double CLIENT_STATE::potentially_runnable_resource_share() {
double x = 0;
for (unsigned int i=0; i<projects.size(); i++) {
PROJECT* p = projects[i];
if (p->non_cpu_intensive) continue;
if (p->potentially_runnable()) {
x += p->resource_share;
}
}
return x;
}
// same, but nearly runnable (could be downloading work right now)
//
double CLIENT_STATE::nearly_runnable_resource_share() {
double x = 0;
for (unsigned int i=0; i<projects.size(); i++) {
PROJECT* p = projects[i];
if (p->non_cpu_intensive) continue;
if (p->nearly_runnable()) {
x += p->resource_share;
}
}
return x;
}
// if there's not an active task for the result, make one
//
ACTIVE_TASK* CLIENT_STATE::get_task(RESULT* rp) {
ACTIVE_TASK *atp = lookup_active_task_by_result(rp);
if (!atp) {
atp = new ACTIVE_TASK;
int retval = atp->get_free_slot(rp);
if (retval) {
delete atp;
return NULL;
}
atp->init(rp);
active_tasks.active_tasks.push_back(atp);
}
return atp;
}
// called at startup (after get_host_info())
// and when general prefs have been parsed.
// NOTE: GSTATE.NCPUS MUST BE 1 OR MORE; WE DIVIDE BY IT IN A COUPLE OF PLACES
//
void CLIENT_STATE::set_ncpus() {
int ncpus_old = ncpus;
// config file can say to act like host has N CPUs
//
static bool first = true;
static int original_p_ncpus;
if (first) {
original_p_ncpus = host_info.p_ncpus;
first = false;
}
if (cc_config.ncpus>0) {
ncpus = cc_config.ncpus;
host_info.p_ncpus = ncpus; // use this in scheduler requests
} else {
host_info.p_ncpus = original_p_ncpus;
ncpus = host_info.p_ncpus;
}
if (ncpus <= 0) {
ncpus = 1; // shouldn't happen
}
if (global_prefs.max_ncpus_pct) {
ncpus = (int)((ncpus * global_prefs.max_ncpus_pct)/100);
if (ncpus == 0) ncpus = 1;
}
if (initialized && ncpus != ncpus_old) {
msg_printf(0, MSG_INFO,
"Number of usable CPUs has changed from %d to %d.",
ncpus_old, ncpus
);
request_schedule_cpus("Number of usable CPUs has changed");
request_work_fetch("Number of usable CPUs has changed");
work_fetch.init();
}
}
// The given result has just completed successfully.
// Update the correction factor used to predict
// completion time for this project's results
//
void PROJECT::update_duration_correction_factor(ACTIVE_TASK* atp) {
if (dont_use_dcf) return;
RESULT* rp = atp->result;
double raw_ratio = atp->elapsed_time/rp->estimated_runtime_uncorrected();
double adj_ratio = atp->elapsed_time/rp->estimated_runtime();
double old_dcf = duration_correction_factor;
// it's OK to overestimate completion time,
// but bad to underestimate it.
// So make it easy for the factor to increase,
// but decrease it with caution
//
if (adj_ratio > 1.1) {
duration_correction_factor = raw_ratio;
} else {
// in particular, don't give much weight to results
// that completed a lot earlier than expected
//
if (adj_ratio < 0.1) {
duration_correction_factor = duration_correction_factor*0.99 + 0.01*raw_ratio;
} else {
duration_correction_factor = duration_correction_factor*0.9 + 0.1*raw_ratio;
}
}
// limit to [.01 .. 100]
//
if (duration_correction_factor > 100) duration_correction_factor = 100;
if (duration_correction_factor < 0.01) duration_correction_factor = 0.01;
if (log_flags.dcf_debug) {
msg_printf(this, MSG_INFO,
"[dcf] DCF: %f->%f, raw_ratio %f, adj_ratio %f",
old_dcf, duration_correction_factor, raw_ratio, adj_ratio
);
}
}
| 1 | 13,809 | So, such tasks that could possibly not meet the deadline will never have a chance to run? I think this is not nice behavior, especially for those projects who has sometimes some very small tasks after the big one. | BOINC-boinc | php |
@@ -10717,6 +10717,11 @@ int LuaScriptInterface::luaItemTypeCreate(lua_State* L)
id = Item::items.getItemIdByName(getString(L, 2));
}
+ if (id == 0) {
+ lua_pushnil(L);
+ return 1;
+ }
+
const ItemType& itemType = Item::items[id];
pushUserdata<const ItemType>(L, &itemType);
setMetatable(L, -1, "ItemType"); | 1 | /**
* The Forgotten Server - a free and open-source MMORPG server emulator
* Copyright (C) 2017 Mark Samman <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "otpch.h"
#include <boost/range/adaptor/reversed.hpp>
#include "luascript.h"
#include "chat.h"
#include "player.h"
#include "game.h"
#include "protocolstatus.h"
#include "spells.h"
#include "iologindata.h"
#include "configmanager.h"
#include "teleport.h"
#include "databasemanager.h"
#include "bed.h"
#include "monster.h"
#include "scheduler.h"
#include "databasetasks.h"
extern Chat* g_chat;
extern Game g_game;
extern Monsters g_monsters;
extern ConfigManager g_config;
extern Vocations g_vocations;
extern Spells* g_spells;
ScriptEnvironment::DBResultMap ScriptEnvironment::tempResults;
uint32_t ScriptEnvironment::lastResultId = 0;
std::multimap<ScriptEnvironment*, Item*> ScriptEnvironment::tempItems;
LuaEnvironment g_luaEnvironment;
ScriptEnvironment::ScriptEnvironment()
{
resetEnv();
}
ScriptEnvironment::~ScriptEnvironment()
{
resetEnv();
}
void ScriptEnvironment::resetEnv()
{
scriptId = 0;
callbackId = 0;
timerEvent = false;
interface = nullptr;
localMap.clear();
tempResults.clear();
auto pair = tempItems.equal_range(this);
auto it = pair.first;
while (it != pair.second) {
Item* item = it->second;
if (item->getParent() == VirtualCylinder::virtualCylinder) {
g_game.ReleaseItem(item);
}
it = tempItems.erase(it);
}
}
bool ScriptEnvironment::setCallbackId(int32_t callbackId, LuaScriptInterface* scriptInterface)
{
if (this->callbackId != 0) {
//nested callbacks are not allowed
if (interface) {
interface->reportErrorFunc("Nested callbacks!");
}
return false;
}
this->callbackId = callbackId;
interface = scriptInterface;
return true;
}
void ScriptEnvironment::getEventInfo(int32_t& scriptId, LuaScriptInterface*& scriptInterface, int32_t& callbackId, bool& timerEvent) const
{
scriptId = this->scriptId;
scriptInterface = interface;
callbackId = this->callbackId;
timerEvent = this->timerEvent;
}
uint32_t ScriptEnvironment::addThing(Thing* thing)
{
if (!thing || thing->isRemoved()) {
return 0;
}
Creature* creature = thing->getCreature();
if (creature) {
return creature->getID();
}
Item* item = thing->getItem();
if (item && item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) {
return item->getUniqueId();
}
for (const auto& it : localMap) {
if (it.second == item) {
return it.first;
}
}
localMap[++lastUID] = item;
return lastUID;
}
void ScriptEnvironment::insertItem(uint32_t uid, Item* item)
{
auto result = localMap.emplace(uid, item);
if (!result.second) {
std::cout << std::endl << "Lua Script Error: Thing uid already taken.";
}
}
Thing* ScriptEnvironment::getThingByUID(uint32_t uid)
{
if (uid >= 0x10000000) {
return g_game.getCreatureByID(uid);
}
if (uid <= std::numeric_limits<uint16_t>::max()) {
Item* item = g_game.getUniqueItem(uid);
if (item && !item->isRemoved()) {
return item;
}
return nullptr;
}
auto it = localMap.find(uid);
if (it != localMap.end()) {
Item* item = it->second;
if (!item->isRemoved()) {
return item;
}
}
return nullptr;
}
Item* ScriptEnvironment::getItemByUID(uint32_t uid)
{
Thing* thing = getThingByUID(uid);
if (!thing) {
return nullptr;
}
return thing->getItem();
}
Container* ScriptEnvironment::getContainerByUID(uint32_t uid)
{
Item* item = getItemByUID(uid);
if (!item) {
return nullptr;
}
return item->getContainer();
}
void ScriptEnvironment::removeItemByUID(uint32_t uid)
{
if (uid <= std::numeric_limits<uint16_t>::max()) {
g_game.removeUniqueItem(uid);
return;
}
auto it = localMap.find(uid);
if (it != localMap.end()) {
localMap.erase(it);
}
}
void ScriptEnvironment::addTempItem(Item* item)
{
tempItems.emplace(this, item);
}
void ScriptEnvironment::removeTempItem(Item* item)
{
for (auto it = tempItems.begin(), end = tempItems.end(); it != end; ++it) {
if (it->second == item) {
tempItems.erase(it);
break;
}
}
}
uint32_t ScriptEnvironment::addResult(DBResult_ptr res)
{
tempResults[++lastResultId] = res;
return lastResultId;
}
bool ScriptEnvironment::removeResult(uint32_t id)
{
auto it = tempResults.find(id);
if (it == tempResults.end()) {
return false;
}
tempResults.erase(it);
return true;
}
DBResult_ptr ScriptEnvironment::getResultByID(uint32_t id)
{
auto it = tempResults.find(id);
if (it == tempResults.end()) {
return nullptr;
}
return it->second;
}
std::string LuaScriptInterface::getErrorDesc(ErrorCode_t code)
{
switch (code) {
case LUA_ERROR_PLAYER_NOT_FOUND: return "Player not found";
case LUA_ERROR_CREATURE_NOT_FOUND: return "Creature not found";
case LUA_ERROR_ITEM_NOT_FOUND: return "Item not found";
case LUA_ERROR_THING_NOT_FOUND: return "Thing not found";
case LUA_ERROR_TILE_NOT_FOUND: return "Tile not found";
case LUA_ERROR_HOUSE_NOT_FOUND: return "House not found";
case LUA_ERROR_COMBAT_NOT_FOUND: return "Combat not found";
case LUA_ERROR_CONDITION_NOT_FOUND: return "Condition not found";
case LUA_ERROR_AREA_NOT_FOUND: return "Area not found";
case LUA_ERROR_CONTAINER_NOT_FOUND: return "Container not found";
case LUA_ERROR_VARIANT_NOT_FOUND: return "Variant not found";
case LUA_ERROR_VARIANT_UNKNOWN: return "Unknown variant type";
case LUA_ERROR_SPELL_NOT_FOUND: return "Spell not found";
default: return "Bad error code";
}
}
ScriptEnvironment LuaScriptInterface::scriptEnv[16];
int32_t LuaScriptInterface::scriptEnvIndex = -1;
LuaScriptInterface::LuaScriptInterface(std::string interfaceName) : interfaceName(std::move(interfaceName))
{
if (!g_luaEnvironment.getLuaState()) {
g_luaEnvironment.initState();
}
}
LuaScriptInterface::~LuaScriptInterface()
{
closeState();
}
bool LuaScriptInterface::reInitState()
{
g_luaEnvironment.clearCombatObjects(this);
g_luaEnvironment.clearAreaObjects(this);
closeState();
return initState();
}
/// Same as lua_pcall, but adds stack trace to error strings in called function.
int LuaScriptInterface::protectedCall(lua_State* L, int nargs, int nresults)
{
int error_index = lua_gettop(L) - nargs;
lua_pushcfunction(L, luaErrorHandler);
lua_insert(L, error_index);
int ret = lua_pcall(L, nargs, nresults, error_index);
lua_remove(L, error_index);
return ret;
}
int32_t LuaScriptInterface::loadFile(const std::string& file, Npc* npc /* = nullptr*/)
{
//loads file as a chunk at stack top
int ret = luaL_loadfile(luaState, file.c_str());
if (ret != 0) {
lastLuaError = popString(luaState);
return -1;
}
//check that it is loaded as a function
if (!isFunction(luaState, -1)) {
return -1;
}
loadingFile = file;
if (!reserveScriptEnv()) {
return -1;
}
ScriptEnvironment* env = getScriptEnv();
env->setScriptId(EVENT_ID_LOADING, this);
env->setNpc(npc);
//execute it
ret = protectedCall(luaState, 0, 0);
if (ret != 0) {
reportError(nullptr, popString(luaState));
resetScriptEnv();
return -1;
}
resetScriptEnv();
return 0;
}
int32_t LuaScriptInterface::getEvent(const std::string& eventName)
{
//get our events table
lua_rawgeti(luaState, LUA_REGISTRYINDEX, eventTableRef);
if (!isTable(luaState, -1)) {
lua_pop(luaState, 1);
return -1;
}
//get current event function pointer
lua_getglobal(luaState, eventName.c_str());
if (!isFunction(luaState, -1)) {
lua_pop(luaState, 2);
return -1;
}
//save in our events table
lua_pushvalue(luaState, -1);
lua_rawseti(luaState, -3, runningEventId);
lua_pop(luaState, 2);
//reset global value of this event
lua_pushnil(luaState);
lua_setglobal(luaState, eventName.c_str());
cacheFiles[runningEventId] = loadingFile + ":" + eventName;
return runningEventId++;
}
int32_t LuaScriptInterface::getMetaEvent(const std::string& globalName, const std::string& eventName)
{
//get our events table
lua_rawgeti(luaState, LUA_REGISTRYINDEX, eventTableRef);
if (!isTable(luaState, -1)) {
lua_pop(luaState, 1);
return -1;
}
//get current event function pointer
lua_getglobal(luaState, globalName.c_str());
lua_getfield(luaState, -1, eventName.c_str());
if (!isFunction(luaState, -1)) {
lua_pop(luaState, 3);
return -1;
}
//save in our events table
lua_pushvalue(luaState, -1);
lua_rawseti(luaState, -4, runningEventId);
lua_pop(luaState, 1);
//reset global value of this event
lua_pushnil(luaState);
lua_setfield(luaState, -2, eventName.c_str());
lua_pop(luaState, 2);
cacheFiles[runningEventId] = loadingFile + ":" + globalName + "@" + eventName;
return runningEventId++;
}
const std::string& LuaScriptInterface::getFileById(int32_t scriptId)
{
if (scriptId == EVENT_ID_LOADING) {
return loadingFile;
}
auto it = cacheFiles.find(scriptId);
if (it == cacheFiles.end()) {
static const std::string& unk = "(Unknown scriptfile)";
return unk;
}
return it->second;
}
std::string LuaScriptInterface::getStackTrace(const std::string& error_desc)
{
lua_getglobal(luaState, "debug");
if (!isTable(luaState, -1)) {
lua_pop(luaState, 1);
return error_desc;
}
lua_getfield(luaState, -1, "traceback");
if (!isFunction(luaState, -1)) {
lua_pop(luaState, 2);
return error_desc;
}
lua_replace(luaState, -2);
pushString(luaState, error_desc);
lua_call(luaState, 1, 1);
return popString(luaState);
}
void LuaScriptInterface::reportError(const char* function, const std::string& error_desc, bool stack_trace/* = false*/)
{
int32_t scriptId;
int32_t callbackId;
bool timerEvent;
LuaScriptInterface* scriptInterface;
getScriptEnv()->getEventInfo(scriptId, scriptInterface, callbackId, timerEvent);
std::cout << std::endl << "Lua Script Error: ";
if (scriptInterface) {
std::cout << '[' << scriptInterface->getInterfaceName() << "] " << std::endl;
if (timerEvent) {
std::cout << "in a timer event called from: " << std::endl;
}
if (callbackId) {
std::cout << "in callback: " << scriptInterface->getFileById(callbackId) << std::endl;
}
std::cout << scriptInterface->getFileById(scriptId) << std::endl;
}
if (function) {
std::cout << function << "(). ";
}
if (stack_trace && scriptInterface) {
std::cout << scriptInterface->getStackTrace(error_desc) << std::endl;
} else {
std::cout << error_desc << std::endl;
}
}
bool LuaScriptInterface::pushFunction(int32_t functionId)
{
lua_rawgeti(luaState, LUA_REGISTRYINDEX, eventTableRef);
if (!isTable(luaState, -1)) {
return false;
}
lua_rawgeti(luaState, -1, functionId);
lua_replace(luaState, -2);
return isFunction(luaState, -1);
}
bool LuaScriptInterface::initState()
{
luaState = g_luaEnvironment.getLuaState();
if (!luaState) {
return false;
}
lua_newtable(luaState);
eventTableRef = luaL_ref(luaState, LUA_REGISTRYINDEX);
runningEventId = EVENT_ID_USER;
return true;
}
bool LuaScriptInterface::closeState()
{
if (!g_luaEnvironment.getLuaState() || !luaState) {
return false;
}
cacheFiles.clear();
if (eventTableRef != -1) {
luaL_unref(luaState, LUA_REGISTRYINDEX, eventTableRef);
eventTableRef = -1;
}
luaState = nullptr;
return true;
}
int LuaScriptInterface::luaErrorHandler(lua_State* L)
{
const std::string& errorMessage = popString(L);
auto interface = getScriptEnv()->getScriptInterface();
assert(interface); //This fires if the ScriptEnvironment hasn't been setup
pushString(L, interface->getStackTrace(errorMessage));
return 1;
}
bool LuaScriptInterface::callFunction(int params)
{
bool result = false;
int size = lua_gettop(luaState);
if (protectedCall(luaState, params, 1) != 0) {
LuaScriptInterface::reportError(nullptr, LuaScriptInterface::getString(luaState, -1));
} else {
result = LuaScriptInterface::getBoolean(luaState, -1);
}
lua_pop(luaState, 1);
if ((lua_gettop(luaState) + params + 1) != size) {
LuaScriptInterface::reportError(nullptr, "Stack size changed!");
}
resetScriptEnv();
return result;
}
void LuaScriptInterface::callVoidFunction(int params)
{
int size = lua_gettop(luaState);
if (protectedCall(luaState, params, 0) != 0) {
LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(luaState));
}
if ((lua_gettop(luaState) + params + 1) != size) {
LuaScriptInterface::reportError(nullptr, "Stack size changed!");
}
resetScriptEnv();
}
void LuaScriptInterface::pushVariant(lua_State* L, const LuaVariant& var)
{
lua_createtable(L, 0, 2);
setField(L, "type", var.type);
switch (var.type) {
case VARIANT_NUMBER:
setField(L, "number", var.number);
break;
case VARIANT_STRING:
setField(L, "string", var.text);
break;
case VARIANT_TARGETPOSITION:
case VARIANT_POSITION: {
pushPosition(L, var.pos);
lua_setfield(L, -2, "pos");
break;
}
default:
break;
}
setMetatable(L, -1, "Variant");
}
void LuaScriptInterface::pushThing(lua_State* L, Thing* thing)
{
if (!thing) {
lua_createtable(L, 0, 4);
setField(L, "uid", 0);
setField(L, "itemid", 0);
setField(L, "actionid", 0);
setField(L, "type", 0);
return;
}
if (Item* item = thing->getItem()) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else if (Creature* creature = thing->getCreature()) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else {
lua_pushnil(L);
}
}
void LuaScriptInterface::pushCylinder(lua_State* L, Cylinder* cylinder)
{
if (Creature* creature = cylinder->getCreature()) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else if (Item* parentItem = cylinder->getItem()) {
pushUserdata<Item>(L, parentItem);
setItemMetatable(L, -1, parentItem);
} else if (Tile* tile = cylinder->getTile()) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else if (cylinder == VirtualCylinder::virtualCylinder) {
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
}
void LuaScriptInterface::pushString(lua_State* L, const std::string& value)
{
lua_pushlstring(L, value.c_str(), value.length());
}
void LuaScriptInterface::pushCallback(lua_State* L, int32_t callback)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, callback);
}
std::string LuaScriptInterface::popString(lua_State* L)
{
if (lua_gettop(L) == 0) {
return std::string();
}
std::string str(getString(L, -1));
lua_pop(L, 1);
return str;
}
int32_t LuaScriptInterface::popCallback(lua_State* L)
{
return luaL_ref(L, LUA_REGISTRYINDEX);
}
// Metatables
void LuaScriptInterface::setMetatable(lua_State* L, int32_t index, const std::string& name)
{
luaL_getmetatable(L, name.c_str());
lua_setmetatable(L, index - 1);
}
void LuaScriptInterface::setWeakMetatable(lua_State* L, int32_t index, const std::string& name)
{
static std::set<std::string> weakObjectTypes;
const std::string& weakName = name + "_weak";
auto result = weakObjectTypes.emplace(name);
if (result.second) {
luaL_getmetatable(L, name.c_str());
int childMetatable = lua_gettop(L);
luaL_newmetatable(L, weakName.c_str());
int metatable = lua_gettop(L);
static const std::vector<std::string> methodKeys = {"__index", "__metatable", "__eq"};
for (const std::string& metaKey : methodKeys) {
lua_getfield(L, childMetatable, metaKey.c_str());
lua_setfield(L, metatable, metaKey.c_str());
}
static const std::vector<int> methodIndexes = {'h', 'p', 't'};
for (int metaIndex : methodIndexes) {
lua_rawgeti(L, childMetatable, metaIndex);
lua_rawseti(L, metatable, metaIndex);
}
lua_pushnil(L);
lua_setfield(L, metatable, "__gc");
lua_remove(L, childMetatable);
} else {
luaL_getmetatable(L, weakName.c_str());
}
lua_setmetatable(L, index - 1);
}
void LuaScriptInterface::setItemMetatable(lua_State* L, int32_t index, const Item* item)
{
if (item->getContainer()) {
luaL_getmetatable(L, "Container");
} else if (item->getTeleport()) {
luaL_getmetatable(L, "Teleport");
} else {
luaL_getmetatable(L, "Item");
}
lua_setmetatable(L, index - 1);
}
void LuaScriptInterface::setCreatureMetatable(lua_State* L, int32_t index, const Creature* creature)
{
if (creature->getPlayer()) {
luaL_getmetatable(L, "Player");
} else if (creature->getMonster()) {
luaL_getmetatable(L, "Monster");
} else {
luaL_getmetatable(L, "Npc");
}
lua_setmetatable(L, index - 1);
}
// Get
CombatDamage LuaScriptInterface::getCombatDamage(lua_State* L)
{
CombatDamage damage;
damage.primary.value = getNumber<int32_t>(L, -4);
damage.primary.type = getNumber<CombatType_t>(L, -3);
damage.secondary.value = getNumber<int32_t>(L, -2);
damage.secondary.type = getNumber<CombatType_t>(L, -1);
lua_pop(L, 4);
return damage;
}
std::string LuaScriptInterface::getString(lua_State* L, int32_t arg)
{
size_t len;
const char* c_str = lua_tolstring(L, arg, &len);
if (!c_str || len == 0) {
return std::string();
}
return std::string(c_str, len);
}
Position LuaScriptInterface::getPosition(lua_State* L, int32_t arg, int32_t& stackpos)
{
Position position;
position.x = getField<uint16_t>(L, arg, "x");
position.y = getField<uint16_t>(L, arg, "y");
position.z = getField<uint8_t>(L, arg, "z");
lua_getfield(L, arg, "stackpos");
if (lua_isnil(L, -1) == 1) {
stackpos = 0;
} else {
stackpos = getNumber<int32_t>(L, -1);
}
lua_pop(L, 4);
return position;
}
Position LuaScriptInterface::getPosition(lua_State* L, int32_t arg)
{
Position position;
position.x = getField<uint16_t>(L, arg, "x");
position.y = getField<uint16_t>(L, arg, "y");
position.z = getField<uint8_t>(L, arg, "z");
lua_pop(L, 3);
return position;
}
Outfit_t LuaScriptInterface::getOutfit(lua_State* L, int32_t arg)
{
Outfit_t outfit;
outfit.lookMount = getField<uint16_t>(L, arg, "lookMount");
outfit.lookAddons = getField<uint8_t>(L, arg, "lookAddons");
outfit.lookFeet = getField<uint8_t>(L, arg, "lookFeet");
outfit.lookLegs = getField<uint8_t>(L, arg, "lookLegs");
outfit.lookBody = getField<uint8_t>(L, arg, "lookBody");
outfit.lookHead = getField<uint8_t>(L, arg, "lookHead");
outfit.lookTypeEx = getField<uint16_t>(L, arg, "lookTypeEx");
outfit.lookType = getField<uint16_t>(L, arg, "lookType");
lua_pop(L, 8);
return outfit;
}
LuaVariant LuaScriptInterface::getVariant(lua_State* L, int32_t arg)
{
LuaVariant var;
switch (var.type = getField<LuaVariantType_t>(L, arg, "type")) {
case VARIANT_NUMBER: {
var.number = getField<uint32_t>(L, arg, "number");
lua_pop(L, 2);
break;
}
case VARIANT_STRING: {
var.text = getFieldString(L, arg, "string");
lua_pop(L, 2);
break;
}
case VARIANT_POSITION:
case VARIANT_TARGETPOSITION: {
lua_getfield(L, arg, "pos");
var.pos = getPosition(L, lua_gettop(L));
lua_pop(L, 2);
break;
}
default: {
var.type = VARIANT_NONE;
lua_pop(L, 1);
break;
}
}
return var;
}
Thing* LuaScriptInterface::getThing(lua_State* L, int32_t arg)
{
Thing* thing;
if (lua_getmetatable(L, arg) != 0) {
lua_rawgeti(L, -1, 't');
switch(getNumber<uint32_t>(L, -1)) {
case LuaData_Item:
thing = getUserdata<Item>(L, arg);
break;
case LuaData_Container:
thing = getUserdata<Container>(L, arg);
break;
case LuaData_Teleport:
thing = getUserdata<Teleport>(L, arg);
break;
case LuaData_Player:
thing = getUserdata<Player>(L, arg);
break;
case LuaData_Monster:
thing = getUserdata<Monster>(L, arg);
break;
case LuaData_Npc:
thing = getUserdata<Npc>(L, arg);
break;
default:
thing = nullptr;
break;
}
lua_pop(L, 2);
} else {
thing = getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, arg));
}
return thing;
}
Creature* LuaScriptInterface::getCreature(lua_State* L, int32_t arg)
{
if (isUserdata(L, arg)) {
return getUserdata<Creature>(L, arg);
}
return g_game.getCreatureByID(getNumber<uint32_t>(L, arg));
}
Player* LuaScriptInterface::getPlayer(lua_State* L, int32_t arg)
{
if (isUserdata(L, arg)) {
return getUserdata<Player>(L, arg);
}
return g_game.getPlayerByID(getNumber<uint32_t>(L, arg));
}
std::string LuaScriptInterface::getFieldString(lua_State* L, int32_t arg, const std::string& key)
{
lua_getfield(L, arg, key.c_str());
return getString(L, -1);
}
LuaDataType LuaScriptInterface::getUserdataType(lua_State* L, int32_t arg)
{
if (lua_getmetatable(L, arg) == 0) {
return LuaData_Unknown;
}
lua_rawgeti(L, -1, 't');
LuaDataType type = getNumber<LuaDataType>(L, -1);
lua_pop(L, 2);
return type;
}
// Push
void LuaScriptInterface::pushBoolean(lua_State* L, bool value)
{
lua_pushboolean(L, value ? 1 : 0);
}
void LuaScriptInterface::pushCombatDamage(lua_State* L, const CombatDamage& damage)
{
lua_pushnumber(L, damage.primary.value);
lua_pushnumber(L, damage.primary.type);
lua_pushnumber(L, damage.secondary.value);
lua_pushnumber(L, damage.secondary.type);
lua_pushnumber(L, damage.origin);
}
void LuaScriptInterface::pushInstantSpell(lua_State* L, const InstantSpell& spell)
{
lua_createtable(L, 0, 6);
setField(L, "name", spell.getName());
setField(L, "words", spell.getWords());
setField(L, "level", spell.getLevel());
setField(L, "mlevel", spell.getMagicLevel());
setField(L, "mana", spell.getMana());
setField(L, "manapercent", spell.getManaPercent());
setMetatable(L, -1, "Spell");
}
void LuaScriptInterface::pushPosition(lua_State* L, const Position& position, int32_t stackpos/* = 0*/)
{
lua_createtable(L, 0, 4);
setField(L, "x", position.x);
setField(L, "y", position.y);
setField(L, "z", position.z);
setField(L, "stackpos", stackpos);
setMetatable(L, -1, "Position");
}
void LuaScriptInterface::pushOutfit(lua_State* L, const Outfit_t& outfit)
{
lua_createtable(L, 0, 8);
setField(L, "lookType", outfit.lookType);
setField(L, "lookTypeEx", outfit.lookTypeEx);
setField(L, "lookHead", outfit.lookHead);
setField(L, "lookBody", outfit.lookBody);
setField(L, "lookLegs", outfit.lookLegs);
setField(L, "lookFeet", outfit.lookFeet);
setField(L, "lookAddons", outfit.lookAddons);
setField(L, "lookMount", outfit.lookMount);
}
#define registerEnum(value) { std::string enumName = #value; registerGlobalVariable(enumName.substr(enumName.find_last_of(':') + 1), value); }
#define registerEnumIn(tableName, value) { std::string enumName = #value; registerVariable(tableName, enumName.substr(enumName.find_last_of(':') + 1), value); }
void LuaScriptInterface::registerFunctions()
{
//doPlayerAddItem(uid, itemid, <optional: default: 1> count/subtype)
//doPlayerAddItem(cid, itemid, <optional: default: 1> count, <optional: default: 1> canDropOnMap, <optional: default: 1>subtype)
//Returns uid of the created item
lua_register(luaState, "doPlayerAddItem", LuaScriptInterface::luaDoPlayerAddItem);
//doTileAddItemEx(pos, uid)
lua_register(luaState, "doTileAddItemEx", LuaScriptInterface::luaDoTileAddItemEx);
//doSetCreatureLight(cid, lightLevel, lightColor, time)
lua_register(luaState, "doSetCreatureLight", LuaScriptInterface::luaDoSetCreatureLight);
//isValidUID(uid)
lua_register(luaState, "isValidUID", LuaScriptInterface::luaIsValidUID);
//isDepot(uid)
lua_register(luaState, "isDepot", LuaScriptInterface::luaIsDepot);
//isMovable(uid)
lua_register(luaState, "isMovable", LuaScriptInterface::luaIsMoveable);
//doAddContainerItem(uid, itemid, <optional> count/subtype)
lua_register(luaState, "doAddContainerItem", LuaScriptInterface::luaDoAddContainerItem);
//getDepotId(uid)
lua_register(luaState, "getDepotId", LuaScriptInterface::luaGetDepotId);
//getWorldTime()
lua_register(luaState, "getWorldTime", LuaScriptInterface::luaGetWorldTime);
//getWorldLight()
lua_register(luaState, "getWorldLight", LuaScriptInterface::luaGetWorldLight);
//getWorldUpTime()
lua_register(luaState, "getWorldUpTime", LuaScriptInterface::luaGetWorldUpTime);
//createCombatArea( {area}, <optional> {extArea} )
lua_register(luaState, "createCombatArea", LuaScriptInterface::luaCreateCombatArea);
//doAreaCombatHealth(cid, type, pos, area, min, max, effect)
lua_register(luaState, "doAreaCombatHealth", LuaScriptInterface::luaDoAreaCombatHealth);
//doTargetCombatHealth(cid, target, type, min, max, effect)
lua_register(luaState, "doTargetCombatHealth", LuaScriptInterface::luaDoTargetCombatHealth);
//doAreaCombatMana(cid, pos, area, min, max, effect)
lua_register(luaState, "doAreaCombatMana", LuaScriptInterface::luaDoAreaCombatMana);
//doTargetCombatMana(cid, target, min, max, effect)
lua_register(luaState, "doTargetCombatMana", LuaScriptInterface::luaDoTargetCombatMana);
//doAreaCombatCondition(cid, pos, area, condition, effect)
lua_register(luaState, "doAreaCombatCondition", LuaScriptInterface::luaDoAreaCombatCondition);
//doTargetCombatCondition(cid, target, condition, effect)
lua_register(luaState, "doTargetCombatCondition", LuaScriptInterface::luaDoTargetCombatCondition);
//doAreaCombatDispel(cid, pos, area, type, effect)
lua_register(luaState, "doAreaCombatDispel", LuaScriptInterface::luaDoAreaCombatDispel);
//doTargetCombatDispel(cid, target, type, effect)
lua_register(luaState, "doTargetCombatDispel", LuaScriptInterface::luaDoTargetCombatDispel);
//doChallengeCreature(cid, target)
lua_register(luaState, "doChallengeCreature", LuaScriptInterface::luaDoChallengeCreature);
//addEvent(callback, delay, ...)
lua_register(luaState, "addEvent", LuaScriptInterface::luaAddEvent);
//stopEvent(eventid)
lua_register(luaState, "stopEvent", LuaScriptInterface::luaStopEvent);
//saveServer()
lua_register(luaState, "saveServer", LuaScriptInterface::luaSaveServer);
//cleanMap()
lua_register(luaState, "cleanMap", LuaScriptInterface::luaCleanMap);
//debugPrint(text)
lua_register(luaState, "debugPrint", LuaScriptInterface::luaDebugPrint);
//isInWar(cid, target)
lua_register(luaState, "isInWar", LuaScriptInterface::luaIsInWar);
//getWaypointPosition(name)
lua_register(luaState, "getWaypointPositionByName", LuaScriptInterface::luaGetWaypointPositionByName);
//sendChannelMessage(channelId, type, message)
lua_register(luaState, "sendChannelMessage", LuaScriptInterface::luaSendChannelMessage);
//sendGuildChannelMessage(guildId, type, message)
lua_register(luaState, "sendGuildChannelMessage", LuaScriptInterface::luaSendGuildChannelMessage);
#ifndef LUAJIT_VERSION
//bit operations for Lua, based on bitlib project release 24
//bit.bnot, bit.band, bit.bor, bit.bxor, bit.lshift, bit.rshift
luaL_register(luaState, "bit", LuaScriptInterface::luaBitReg);
#endif
//configManager table
luaL_register(luaState, "configManager", LuaScriptInterface::luaConfigManagerTable);
//db table
luaL_register(luaState, "db", LuaScriptInterface::luaDatabaseTable);
//result table
luaL_register(luaState, "result", LuaScriptInterface::luaResultTable);
/* New functions */
//registerClass(className, baseClass, newFunction)
//registerTable(tableName)
//registerMethod(className, functionName, function)
//registerMetaMethod(className, functionName, function)
//registerGlobalMethod(functionName, function)
//registerVariable(tableName, name, value)
//registerGlobalVariable(name, value)
//registerEnum(value)
//registerEnumIn(tableName, value)
// Enums
registerEnum(ACCOUNT_TYPE_NORMAL)
registerEnum(ACCOUNT_TYPE_TUTOR)
registerEnum(ACCOUNT_TYPE_SENIORTUTOR)
registerEnum(ACCOUNT_TYPE_GAMEMASTER)
registerEnum(ACCOUNT_TYPE_GOD)
registerEnum(BUG_CATEGORY_MAP)
registerEnum(BUG_CATEGORY_TYPO)
registerEnum(BUG_CATEGORY_TECHNICAL)
registerEnum(BUG_CATEGORY_OTHER)
registerEnum(CALLBACK_PARAM_LEVELMAGICVALUE)
registerEnum(CALLBACK_PARAM_SKILLVALUE)
registerEnum(CALLBACK_PARAM_TARGETTILE)
registerEnum(CALLBACK_PARAM_TARGETCREATURE)
registerEnum(COMBAT_FORMULA_UNDEFINED)
registerEnum(COMBAT_FORMULA_LEVELMAGIC)
registerEnum(COMBAT_FORMULA_SKILL)
registerEnum(COMBAT_FORMULA_DAMAGE)
registerEnum(DIRECTION_NORTH)
registerEnum(DIRECTION_EAST)
registerEnum(DIRECTION_SOUTH)
registerEnum(DIRECTION_WEST)
registerEnum(DIRECTION_SOUTHWEST)
registerEnum(DIRECTION_SOUTHEAST)
registerEnum(DIRECTION_NORTHWEST)
registerEnum(DIRECTION_NORTHEAST)
registerEnum(COMBAT_NONE)
registerEnum(COMBAT_PHYSICALDAMAGE)
registerEnum(COMBAT_ENERGYDAMAGE)
registerEnum(COMBAT_EARTHDAMAGE)
registerEnum(COMBAT_FIREDAMAGE)
registerEnum(COMBAT_UNDEFINEDDAMAGE)
registerEnum(COMBAT_LIFEDRAIN)
registerEnum(COMBAT_MANADRAIN)
registerEnum(COMBAT_HEALING)
registerEnum(COMBAT_DROWNDAMAGE)
registerEnum(COMBAT_ICEDAMAGE)
registerEnum(COMBAT_HOLYDAMAGE)
registerEnum(COMBAT_DEATHDAMAGE)
registerEnum(COMBAT_PARAM_TYPE)
registerEnum(COMBAT_PARAM_EFFECT)
registerEnum(COMBAT_PARAM_DISTANCEEFFECT)
registerEnum(COMBAT_PARAM_BLOCKSHIELD)
registerEnum(COMBAT_PARAM_BLOCKARMOR)
registerEnum(COMBAT_PARAM_TARGETCASTERORTOPMOST)
registerEnum(COMBAT_PARAM_CREATEITEM)
registerEnum(COMBAT_PARAM_AGGRESSIVE)
registerEnum(COMBAT_PARAM_DISPEL)
registerEnum(COMBAT_PARAM_USECHARGES)
registerEnum(CONDITION_NONE)
registerEnum(CONDITION_POISON)
registerEnum(CONDITION_FIRE)
registerEnum(CONDITION_ENERGY)
registerEnum(CONDITION_BLEEDING)
registerEnum(CONDITION_HASTE)
registerEnum(CONDITION_PARALYZE)
registerEnum(CONDITION_OUTFIT)
registerEnum(CONDITION_INVISIBLE)
registerEnum(CONDITION_LIGHT)
registerEnum(CONDITION_MANASHIELD)
registerEnum(CONDITION_INFIGHT)
registerEnum(CONDITION_DRUNK)
registerEnum(CONDITION_EXHAUST_WEAPON)
registerEnum(CONDITION_REGENERATION)
registerEnum(CONDITION_SOUL)
registerEnum(CONDITION_DROWN)
registerEnum(CONDITION_MUTED)
registerEnum(CONDITION_CHANNELMUTEDTICKS)
registerEnum(CONDITION_YELLTICKS)
registerEnum(CONDITION_ATTRIBUTES)
registerEnum(CONDITION_FREEZING)
registerEnum(CONDITION_DAZZLED)
registerEnum(CONDITION_CURSED)
registerEnum(CONDITION_EXHAUST_COMBAT)
registerEnum(CONDITION_EXHAUST_HEAL)
registerEnum(CONDITION_PACIFIED)
registerEnum(CONDITION_SPELLCOOLDOWN)
registerEnum(CONDITION_SPELLGROUPCOOLDOWN)
registerEnum(CONDITIONID_DEFAULT)
registerEnum(CONDITIONID_COMBAT)
registerEnum(CONDITIONID_HEAD)
registerEnum(CONDITIONID_NECKLACE)
registerEnum(CONDITIONID_BACKPACK)
registerEnum(CONDITIONID_ARMOR)
registerEnum(CONDITIONID_RIGHT)
registerEnum(CONDITIONID_LEFT)
registerEnum(CONDITIONID_LEGS)
registerEnum(CONDITIONID_FEET)
registerEnum(CONDITIONID_RING)
registerEnum(CONDITIONID_AMMO)
registerEnum(CONDITION_PARAM_OWNER)
registerEnum(CONDITION_PARAM_TICKS)
registerEnum(CONDITION_PARAM_HEALTHGAIN)
registerEnum(CONDITION_PARAM_HEALTHTICKS)
registerEnum(CONDITION_PARAM_MANAGAIN)
registerEnum(CONDITION_PARAM_MANATICKS)
registerEnum(CONDITION_PARAM_DELAYED)
registerEnum(CONDITION_PARAM_SPEED)
registerEnum(CONDITION_PARAM_LIGHT_LEVEL)
registerEnum(CONDITION_PARAM_LIGHT_COLOR)
registerEnum(CONDITION_PARAM_SOULGAIN)
registerEnum(CONDITION_PARAM_SOULTICKS)
registerEnum(CONDITION_PARAM_MINVALUE)
registerEnum(CONDITION_PARAM_MAXVALUE)
registerEnum(CONDITION_PARAM_STARTVALUE)
registerEnum(CONDITION_PARAM_TICKINTERVAL)
registerEnum(CONDITION_PARAM_FORCEUPDATE)
registerEnum(CONDITION_PARAM_SKILL_MELEE)
registerEnum(CONDITION_PARAM_SKILL_FIST)
registerEnum(CONDITION_PARAM_SKILL_CLUB)
registerEnum(CONDITION_PARAM_SKILL_SWORD)
registerEnum(CONDITION_PARAM_SKILL_AXE)
registerEnum(CONDITION_PARAM_SKILL_DISTANCE)
registerEnum(CONDITION_PARAM_SKILL_SHIELD)
registerEnum(CONDITION_PARAM_SKILL_FISHING)
registerEnum(CONDITION_PARAM_STAT_MAXHITPOINTS)
registerEnum(CONDITION_PARAM_STAT_MAXMANAPOINTS)
registerEnum(CONDITION_PARAM_STAT_MAGICPOINTS)
registerEnum(CONDITION_PARAM_STAT_MAXHITPOINTSPERCENT)
registerEnum(CONDITION_PARAM_STAT_MAXMANAPOINTSPERCENT)
registerEnum(CONDITION_PARAM_STAT_MAGICPOINTSPERCENT)
registerEnum(CONDITION_PARAM_PERIODICDAMAGE)
registerEnum(CONDITION_PARAM_SKILL_MELEEPERCENT)
registerEnum(CONDITION_PARAM_SKILL_FISTPERCENT)
registerEnum(CONDITION_PARAM_SKILL_CLUBPERCENT)
registerEnum(CONDITION_PARAM_SKILL_SWORDPERCENT)
registerEnum(CONDITION_PARAM_SKILL_AXEPERCENT)
registerEnum(CONDITION_PARAM_SKILL_DISTANCEPERCENT)
registerEnum(CONDITION_PARAM_SKILL_SHIELDPERCENT)
registerEnum(CONDITION_PARAM_SKILL_FISHINGPERCENT)
registerEnum(CONDITION_PARAM_BUFF_SPELL)
registerEnum(CONDITION_PARAM_SUBID)
registerEnum(CONDITION_PARAM_FIELD)
registerEnum(CONDITION_PARAM_DISABLE_DEFENSE)
registerEnum(CONST_ME_NONE)
registerEnum(CONST_ME_DRAWBLOOD)
registerEnum(CONST_ME_LOSEENERGY)
registerEnum(CONST_ME_POFF)
registerEnum(CONST_ME_BLOCKHIT)
registerEnum(CONST_ME_EXPLOSIONAREA)
registerEnum(CONST_ME_EXPLOSIONHIT)
registerEnum(CONST_ME_FIREAREA)
registerEnum(CONST_ME_YELLOW_RINGS)
registerEnum(CONST_ME_GREEN_RINGS)
registerEnum(CONST_ME_HITAREA)
registerEnum(CONST_ME_TELEPORT)
registerEnum(CONST_ME_ENERGYHIT)
registerEnum(CONST_ME_MAGIC_BLUE)
registerEnum(CONST_ME_MAGIC_RED)
registerEnum(CONST_ME_MAGIC_GREEN)
registerEnum(CONST_ME_HITBYFIRE)
registerEnum(CONST_ME_HITBYPOISON)
registerEnum(CONST_ME_MORTAREA)
registerEnum(CONST_ME_SOUND_GREEN)
registerEnum(CONST_ME_SOUND_RED)
registerEnum(CONST_ME_POISONAREA)
registerEnum(CONST_ME_SOUND_YELLOW)
registerEnum(CONST_ME_SOUND_PURPLE)
registerEnum(CONST_ME_SOUND_BLUE)
registerEnum(CONST_ME_SOUND_WHITE)
registerEnum(CONST_ME_BUBBLES)
registerEnum(CONST_ME_CRAPS)
registerEnum(CONST_ME_GIFT_WRAPS)
registerEnum(CONST_ME_FIREWORK_YELLOW)
registerEnum(CONST_ME_FIREWORK_RED)
registerEnum(CONST_ME_FIREWORK_BLUE)
registerEnum(CONST_ME_STUN)
registerEnum(CONST_ME_SLEEP)
registerEnum(CONST_ME_WATERCREATURE)
registerEnum(CONST_ME_GROUNDSHAKER)
registerEnum(CONST_ME_HEARTS)
registerEnum(CONST_ME_FIREATTACK)
registerEnum(CONST_ME_ENERGYAREA)
registerEnum(CONST_ME_SMALLCLOUDS)
registerEnum(CONST_ME_HOLYDAMAGE)
registerEnum(CONST_ME_BIGCLOUDS)
registerEnum(CONST_ME_ICEAREA)
registerEnum(CONST_ME_ICETORNADO)
registerEnum(CONST_ME_ICEATTACK)
registerEnum(CONST_ME_STONES)
registerEnum(CONST_ME_SMALLPLANTS)
registerEnum(CONST_ME_CARNIPHILA)
registerEnum(CONST_ME_PURPLEENERGY)
registerEnum(CONST_ME_YELLOWENERGY)
registerEnum(CONST_ME_HOLYAREA)
registerEnum(CONST_ME_BIGPLANTS)
registerEnum(CONST_ME_CAKE)
registerEnum(CONST_ME_GIANTICE)
registerEnum(CONST_ME_WATERSPLASH)
registerEnum(CONST_ME_PLANTATTACK)
registerEnum(CONST_ME_TUTORIALARROW)
registerEnum(CONST_ME_TUTORIALSQUARE)
registerEnum(CONST_ME_MIRRORHORIZONTAL)
registerEnum(CONST_ME_MIRRORVERTICAL)
registerEnum(CONST_ME_SKULLHORIZONTAL)
registerEnum(CONST_ME_SKULLVERTICAL)
registerEnum(CONST_ME_ASSASSIN)
registerEnum(CONST_ME_STEPSHORIZONTAL)
registerEnum(CONST_ME_BLOODYSTEPS)
registerEnum(CONST_ME_STEPSVERTICAL)
registerEnum(CONST_ME_YALAHARIGHOST)
registerEnum(CONST_ME_BATS)
registerEnum(CONST_ME_SMOKE)
registerEnum(CONST_ME_INSECTS)
registerEnum(CONST_ME_DRAGONHEAD)
registerEnum(CONST_ME_ORCSHAMAN)
registerEnum(CONST_ME_ORCSHAMAN_FIRE)
registerEnum(CONST_ME_THUNDER)
registerEnum(CONST_ME_FERUMBRAS)
registerEnum(CONST_ME_CONFETTI_HORIZONTAL)
registerEnum(CONST_ME_CONFETTI_VERTICAL)
registerEnum(CONST_ME_BLACKSMOKE)
registerEnum(CONST_ME_REDSMOKE)
registerEnum(CONST_ME_YELLOWSMOKE)
registerEnum(CONST_ME_GREENSMOKE)
registerEnum(CONST_ME_PURPLESMOKE)
registerEnum(CONST_ME_EARLY_THUNDER)
registerEnum(CONST_ME_RAGIAZ_BONECAPSULE)
registerEnum(CONST_ME_CRITICAL_DAMAGE)
registerEnum(CONST_ME_PLUNGING_FISH)
registerEnum(CONST_ANI_NONE)
registerEnum(CONST_ANI_SPEAR)
registerEnum(CONST_ANI_BOLT)
registerEnum(CONST_ANI_ARROW)
registerEnum(CONST_ANI_FIRE)
registerEnum(CONST_ANI_ENERGY)
registerEnum(CONST_ANI_POISONARROW)
registerEnum(CONST_ANI_BURSTARROW)
registerEnum(CONST_ANI_THROWINGSTAR)
registerEnum(CONST_ANI_THROWINGKNIFE)
registerEnum(CONST_ANI_SMALLSTONE)
registerEnum(CONST_ANI_DEATH)
registerEnum(CONST_ANI_LARGEROCK)
registerEnum(CONST_ANI_SNOWBALL)
registerEnum(CONST_ANI_POWERBOLT)
registerEnum(CONST_ANI_POISON)
registerEnum(CONST_ANI_INFERNALBOLT)
registerEnum(CONST_ANI_HUNTINGSPEAR)
registerEnum(CONST_ANI_ENCHANTEDSPEAR)
registerEnum(CONST_ANI_REDSTAR)
registerEnum(CONST_ANI_GREENSTAR)
registerEnum(CONST_ANI_ROYALSPEAR)
registerEnum(CONST_ANI_SNIPERARROW)
registerEnum(CONST_ANI_ONYXARROW)
registerEnum(CONST_ANI_PIERCINGBOLT)
registerEnum(CONST_ANI_WHIRLWINDSWORD)
registerEnum(CONST_ANI_WHIRLWINDAXE)
registerEnum(CONST_ANI_WHIRLWINDCLUB)
registerEnum(CONST_ANI_ETHEREALSPEAR)
registerEnum(CONST_ANI_ICE)
registerEnum(CONST_ANI_EARTH)
registerEnum(CONST_ANI_HOLY)
registerEnum(CONST_ANI_SUDDENDEATH)
registerEnum(CONST_ANI_FLASHARROW)
registerEnum(CONST_ANI_FLAMMINGARROW)
registerEnum(CONST_ANI_SHIVERARROW)
registerEnum(CONST_ANI_ENERGYBALL)
registerEnum(CONST_ANI_SMALLICE)
registerEnum(CONST_ANI_SMALLHOLY)
registerEnum(CONST_ANI_SMALLEARTH)
registerEnum(CONST_ANI_EARTHARROW)
registerEnum(CONST_ANI_EXPLOSION)
registerEnum(CONST_ANI_CAKE)
registerEnum(CONST_ANI_TARSALARROW)
registerEnum(CONST_ANI_VORTEXBOLT)
registerEnum(CONST_ANI_PRISMATICBOLT)
registerEnum(CONST_ANI_CRYSTALLINEARROW)
registerEnum(CONST_ANI_DRILLBOLT)
registerEnum(CONST_ANI_ENVENOMEDARROW)
registerEnum(CONST_ANI_GLOOTHSPEAR)
registerEnum(CONST_ANI_SIMPLEARROW)
registerEnum(CONST_ANI_WEAPONTYPE)
registerEnum(CONST_PROP_BLOCKSOLID)
registerEnum(CONST_PROP_HASHEIGHT)
registerEnum(CONST_PROP_BLOCKPROJECTILE)
registerEnum(CONST_PROP_BLOCKPATH)
registerEnum(CONST_PROP_ISVERTICAL)
registerEnum(CONST_PROP_ISHORIZONTAL)
registerEnum(CONST_PROP_MOVEABLE)
registerEnum(CONST_PROP_IMMOVABLEBLOCKSOLID)
registerEnum(CONST_PROP_IMMOVABLEBLOCKPATH)
registerEnum(CONST_PROP_IMMOVABLENOFIELDBLOCKPATH)
registerEnum(CONST_PROP_NOFIELDBLOCKPATH)
registerEnum(CONST_PROP_SUPPORTHANGABLE)
registerEnum(CONST_SLOT_HEAD)
registerEnum(CONST_SLOT_NECKLACE)
registerEnum(CONST_SLOT_BACKPACK)
registerEnum(CONST_SLOT_ARMOR)
registerEnum(CONST_SLOT_RIGHT)
registerEnum(CONST_SLOT_LEFT)
registerEnum(CONST_SLOT_LEGS)
registerEnum(CONST_SLOT_FEET)
registerEnum(CONST_SLOT_RING)
registerEnum(CONST_SLOT_AMMO)
registerEnum(CREATURE_EVENT_NONE)
registerEnum(CREATURE_EVENT_LOGIN)
registerEnum(CREATURE_EVENT_LOGOUT)
registerEnum(CREATURE_EVENT_THINK)
registerEnum(CREATURE_EVENT_PREPAREDEATH)
registerEnum(CREATURE_EVENT_DEATH)
registerEnum(CREATURE_EVENT_KILL)
registerEnum(CREATURE_EVENT_ADVANCE)
registerEnum(CREATURE_EVENT_MODALWINDOW)
registerEnum(CREATURE_EVENT_TEXTEDIT)
registerEnum(CREATURE_EVENT_HEALTHCHANGE)
registerEnum(CREATURE_EVENT_MANACHANGE)
registerEnum(CREATURE_EVENT_EXTENDED_OPCODE)
registerEnum(GAME_STATE_STARTUP)
registerEnum(GAME_STATE_INIT)
registerEnum(GAME_STATE_NORMAL)
registerEnum(GAME_STATE_CLOSED)
registerEnum(GAME_STATE_SHUTDOWN)
registerEnum(GAME_STATE_CLOSING)
registerEnum(GAME_STATE_MAINTAIN)
registerEnum(MESSAGE_STATUS_CONSOLE_BLUE)
registerEnum(MESSAGE_STATUS_CONSOLE_RED)
registerEnum(MESSAGE_STATUS_DEFAULT)
registerEnum(MESSAGE_STATUS_WARNING)
registerEnum(MESSAGE_EVENT_ADVANCE)
registerEnum(MESSAGE_STATUS_SMALL)
registerEnum(MESSAGE_INFO_DESCR)
registerEnum(MESSAGE_DAMAGE_DEALT)
registerEnum(MESSAGE_DAMAGE_RECEIVED)
registerEnum(MESSAGE_HEALED)
registerEnum(MESSAGE_EXPERIENCE)
registerEnum(MESSAGE_DAMAGE_OTHERS)
registerEnum(MESSAGE_HEALED_OTHERS)
registerEnum(MESSAGE_EXPERIENCE_OTHERS)
registerEnum(MESSAGE_EVENT_DEFAULT)
registerEnum(MESSAGE_GUILD)
registerEnum(MESSAGE_PARTY_MANAGEMENT)
registerEnum(MESSAGE_PARTY)
registerEnum(MESSAGE_EVENT_ORANGE)
registerEnum(MESSAGE_STATUS_CONSOLE_ORANGE)
registerEnum(CREATURETYPE_PLAYER)
registerEnum(CREATURETYPE_MONSTER)
registerEnum(CREATURETYPE_NPC)
registerEnum(CREATURETYPE_SUMMON_OWN)
registerEnum(CREATURETYPE_SUMMON_OTHERS)
registerEnum(CLIENTOS_LINUX)
registerEnum(CLIENTOS_WINDOWS)
registerEnum(CLIENTOS_FLASH)
registerEnum(CLIENTOS_OTCLIENT_LINUX)
registerEnum(CLIENTOS_OTCLIENT_WINDOWS)
registerEnum(CLIENTOS_OTCLIENT_MAC)
registerEnum(FIGHTMODE_ATTACK)
registerEnum(FIGHTMODE_BALANCED)
registerEnum(FIGHTMODE_DEFENSE)
registerEnum(ITEM_ATTRIBUTE_NONE)
registerEnum(ITEM_ATTRIBUTE_ACTIONID)
registerEnum(ITEM_ATTRIBUTE_UNIQUEID)
registerEnum(ITEM_ATTRIBUTE_DESCRIPTION)
registerEnum(ITEM_ATTRIBUTE_TEXT)
registerEnum(ITEM_ATTRIBUTE_DATE)
registerEnum(ITEM_ATTRIBUTE_WRITER)
registerEnum(ITEM_ATTRIBUTE_NAME)
registerEnum(ITEM_ATTRIBUTE_ARTICLE)
registerEnum(ITEM_ATTRIBUTE_PLURALNAME)
registerEnum(ITEM_ATTRIBUTE_WEIGHT)
registerEnum(ITEM_ATTRIBUTE_ATTACK)
registerEnum(ITEM_ATTRIBUTE_DEFENSE)
registerEnum(ITEM_ATTRIBUTE_EXTRADEFENSE)
registerEnum(ITEM_ATTRIBUTE_ARMOR)
registerEnum(ITEM_ATTRIBUTE_HITCHANCE)
registerEnum(ITEM_ATTRIBUTE_SHOOTRANGE)
registerEnum(ITEM_ATTRIBUTE_OWNER)
registerEnum(ITEM_ATTRIBUTE_DURATION)
registerEnum(ITEM_ATTRIBUTE_DECAYSTATE)
registerEnum(ITEM_ATTRIBUTE_CORPSEOWNER)
registerEnum(ITEM_ATTRIBUTE_CHARGES)
registerEnum(ITEM_ATTRIBUTE_FLUIDTYPE)
registerEnum(ITEM_ATTRIBUTE_DOORID)
registerEnum(ITEM_TYPE_DEPOT)
registerEnum(ITEM_TYPE_MAILBOX)
registerEnum(ITEM_TYPE_TRASHHOLDER)
registerEnum(ITEM_TYPE_CONTAINER)
registerEnum(ITEM_TYPE_DOOR)
registerEnum(ITEM_TYPE_MAGICFIELD)
registerEnum(ITEM_TYPE_TELEPORT)
registerEnum(ITEM_TYPE_BED)
registerEnum(ITEM_TYPE_KEY)
registerEnum(ITEM_TYPE_RUNE)
registerEnum(ITEM_BAG)
registerEnum(ITEM_GOLD_COIN)
registerEnum(ITEM_PLATINUM_COIN)
registerEnum(ITEM_CRYSTAL_COIN)
registerEnum(ITEM_AMULETOFLOSS)
registerEnum(ITEM_PARCEL)
registerEnum(ITEM_LABEL)
registerEnum(ITEM_FIREFIELD_PVP_FULL)
registerEnum(ITEM_FIREFIELD_PVP_MEDIUM)
registerEnum(ITEM_FIREFIELD_PVP_SMALL)
registerEnum(ITEM_FIREFIELD_PERSISTENT_FULL)
registerEnum(ITEM_FIREFIELD_PERSISTENT_MEDIUM)
registerEnum(ITEM_FIREFIELD_PERSISTENT_SMALL)
registerEnum(ITEM_FIREFIELD_NOPVP)
registerEnum(ITEM_POISONFIELD_PVP)
registerEnum(ITEM_POISONFIELD_PERSISTENT)
registerEnum(ITEM_POISONFIELD_NOPVP)
registerEnum(ITEM_ENERGYFIELD_PVP)
registerEnum(ITEM_ENERGYFIELD_PERSISTENT)
registerEnum(ITEM_ENERGYFIELD_NOPVP)
registerEnum(ITEM_MAGICWALL)
registerEnum(ITEM_MAGICWALL_PERSISTENT)
registerEnum(ITEM_MAGICWALL_SAFE)
registerEnum(ITEM_WILDGROWTH)
registerEnum(ITEM_WILDGROWTH_PERSISTENT)
registerEnum(ITEM_WILDGROWTH_SAFE)
registerEnum(PlayerFlag_CannotUseCombat)
registerEnum(PlayerFlag_CannotAttackPlayer)
registerEnum(PlayerFlag_CannotAttackMonster)
registerEnum(PlayerFlag_CannotBeAttacked)
registerEnum(PlayerFlag_CanConvinceAll)
registerEnum(PlayerFlag_CanSummonAll)
registerEnum(PlayerFlag_CanIllusionAll)
registerEnum(PlayerFlag_CanSenseInvisibility)
registerEnum(PlayerFlag_IgnoredByMonsters)
registerEnum(PlayerFlag_NotGainInFight)
registerEnum(PlayerFlag_HasInfiniteMana)
registerEnum(PlayerFlag_HasInfiniteSoul)
registerEnum(PlayerFlag_HasNoExhaustion)
registerEnum(PlayerFlag_CannotUseSpells)
registerEnum(PlayerFlag_CannotPickupItem)
registerEnum(PlayerFlag_CanAlwaysLogin)
registerEnum(PlayerFlag_CanBroadcast)
registerEnum(PlayerFlag_CanEditHouses)
registerEnum(PlayerFlag_CannotBeBanned)
registerEnum(PlayerFlag_CannotBePushed)
registerEnum(PlayerFlag_HasInfiniteCapacity)
registerEnum(PlayerFlag_CanPushAllCreatures)
registerEnum(PlayerFlag_CanTalkRedPrivate)
registerEnum(PlayerFlag_CanTalkRedChannel)
registerEnum(PlayerFlag_TalkOrangeHelpChannel)
registerEnum(PlayerFlag_NotGainExperience)
registerEnum(PlayerFlag_NotGainMana)
registerEnum(PlayerFlag_NotGainHealth)
registerEnum(PlayerFlag_NotGainSkill)
registerEnum(PlayerFlag_SetMaxSpeed)
registerEnum(PlayerFlag_SpecialVIP)
registerEnum(PlayerFlag_NotGenerateLoot)
registerEnum(PlayerFlag_CanTalkRedChannelAnonymous)
registerEnum(PlayerFlag_IgnoreProtectionZone)
registerEnum(PlayerFlag_IgnoreSpellCheck)
registerEnum(PlayerFlag_IgnoreWeaponCheck)
registerEnum(PlayerFlag_CannotBeMuted)
registerEnum(PlayerFlag_IsAlwaysPremium)
registerEnum(PLAYERSEX_FEMALE)
registerEnum(PLAYERSEX_MALE)
registerEnum(REPORT_REASON_NAMEINAPPROPRIATE)
registerEnum(REPORT_REASON_NAMEPOORFORMATTED)
registerEnum(REPORT_REASON_NAMEADVERTISING)
registerEnum(REPORT_REASON_NAMEUNFITTING)
registerEnum(REPORT_REASON_NAMERULEVIOLATION)
registerEnum(REPORT_REASON_INSULTINGSTATEMENT)
registerEnum(REPORT_REASON_SPAMMING)
registerEnum(REPORT_REASON_ADVERTISINGSTATEMENT)
registerEnum(REPORT_REASON_UNFITTINGSTATEMENT)
registerEnum(REPORT_REASON_LANGUAGESTATEMENT)
registerEnum(REPORT_REASON_DISCLOSURE)
registerEnum(REPORT_REASON_RULEVIOLATION)
registerEnum(REPORT_REASON_STATEMENT_BUGABUSE)
registerEnum(REPORT_REASON_UNOFFICIALSOFTWARE)
registerEnum(REPORT_REASON_PRETENDING)
registerEnum(REPORT_REASON_HARASSINGOWNERS)
registerEnum(REPORT_REASON_FALSEINFO)
registerEnum(REPORT_REASON_ACCOUNTSHARING)
registerEnum(REPORT_REASON_STEALINGDATA)
registerEnum(REPORT_REASON_SERVICEATTACKING)
registerEnum(REPORT_REASON_SERVICEAGREEMENT)
registerEnum(REPORT_TYPE_NAME)
registerEnum(REPORT_TYPE_STATEMENT)
registerEnum(REPORT_TYPE_BOT)
registerEnum(VOCATION_NONE)
registerEnum(SKILL_FIST)
registerEnum(SKILL_CLUB)
registerEnum(SKILL_SWORD)
registerEnum(SKILL_AXE)
registerEnum(SKILL_DISTANCE)
registerEnum(SKILL_SHIELD)
registerEnum(SKILL_FISHING)
registerEnum(SKILL_MAGLEVEL)
registerEnum(SKILL_LEVEL)
registerEnum(SKULL_NONE)
registerEnum(SKULL_YELLOW)
registerEnum(SKULL_GREEN)
registerEnum(SKULL_WHITE)
registerEnum(SKULL_RED)
registerEnum(SKULL_BLACK)
registerEnum(SKULL_ORANGE)
registerEnum(TALKTYPE_SAY)
registerEnum(TALKTYPE_WHISPER)
registerEnum(TALKTYPE_YELL)
registerEnum(TALKTYPE_PRIVATE_FROM)
registerEnum(TALKTYPE_PRIVATE_TO)
registerEnum(TALKTYPE_CHANNEL_Y)
registerEnum(TALKTYPE_CHANNEL_O)
registerEnum(TALKTYPE_PRIVATE_NP)
registerEnum(TALKTYPE_PRIVATE_PN)
registerEnum(TALKTYPE_BROADCAST)
registerEnum(TALKTYPE_CHANNEL_R1)
registerEnum(TALKTYPE_PRIVATE_RED_FROM)
registerEnum(TALKTYPE_PRIVATE_RED_TO)
registerEnum(TALKTYPE_MONSTER_SAY)
registerEnum(TALKTYPE_MONSTER_YELL)
registerEnum(TALKTYPE_CHANNEL_R2)
registerEnum(TEXTCOLOR_BLUE)
registerEnum(TEXTCOLOR_LIGHTGREEN)
registerEnum(TEXTCOLOR_LIGHTBLUE)
registerEnum(TEXTCOLOR_MAYABLUE)
registerEnum(TEXTCOLOR_DARKRED)
registerEnum(TEXTCOLOR_LIGHTGREY)
registerEnum(TEXTCOLOR_SKYBLUE)
registerEnum(TEXTCOLOR_PURPLE)
registerEnum(TEXTCOLOR_ELECTRICPURPLE)
registerEnum(TEXTCOLOR_RED)
registerEnum(TEXTCOLOR_PASTELRED)
registerEnum(TEXTCOLOR_ORANGE)
registerEnum(TEXTCOLOR_YELLOW)
registerEnum(TEXTCOLOR_WHITE_EXP)
registerEnum(TEXTCOLOR_NONE)
registerEnum(TILESTATE_NONE)
registerEnum(TILESTATE_PROTECTIONZONE)
registerEnum(TILESTATE_NOPVPZONE)
registerEnum(TILESTATE_NOLOGOUT)
registerEnum(TILESTATE_PVPZONE)
registerEnum(TILESTATE_FLOORCHANGE)
registerEnum(TILESTATE_FLOORCHANGE_DOWN)
registerEnum(TILESTATE_FLOORCHANGE_NORTH)
registerEnum(TILESTATE_FLOORCHANGE_SOUTH)
registerEnum(TILESTATE_FLOORCHANGE_EAST)
registerEnum(TILESTATE_FLOORCHANGE_WEST)
registerEnum(TILESTATE_TELEPORT)
registerEnum(TILESTATE_MAGICFIELD)
registerEnum(TILESTATE_MAILBOX)
registerEnum(TILESTATE_TRASHHOLDER)
registerEnum(TILESTATE_BED)
registerEnum(TILESTATE_DEPOT)
registerEnum(TILESTATE_BLOCKSOLID)
registerEnum(TILESTATE_BLOCKPATH)
registerEnum(TILESTATE_IMMOVABLEBLOCKSOLID)
registerEnum(TILESTATE_IMMOVABLEBLOCKPATH)
registerEnum(TILESTATE_IMMOVABLENOFIELDBLOCKPATH)
registerEnum(TILESTATE_NOFIELDBLOCKPATH)
registerEnum(TILESTATE_FLOORCHANGE_SOUTH_ALT)
registerEnum(TILESTATE_FLOORCHANGE_EAST_ALT)
registerEnum(TILESTATE_SUPPORTS_HANGABLE)
registerEnum(WEAPON_NONE)
registerEnum(WEAPON_SWORD)
registerEnum(WEAPON_CLUB)
registerEnum(WEAPON_AXE)
registerEnum(WEAPON_SHIELD)
registerEnum(WEAPON_DISTANCE)
registerEnum(WEAPON_WAND)
registerEnum(WEAPON_AMMO)
registerEnum(WORLD_TYPE_NO_PVP)
registerEnum(WORLD_TYPE_PVP)
registerEnum(WORLD_TYPE_PVP_ENFORCED)
// Use with container:addItem, container:addItemEx and possibly other functions.
registerEnum(FLAG_NOLIMIT)
registerEnum(FLAG_IGNOREBLOCKITEM)
registerEnum(FLAG_IGNOREBLOCKCREATURE)
registerEnum(FLAG_CHILDISOWNER)
registerEnum(FLAG_PATHFINDING)
registerEnum(FLAG_IGNOREFIELDDAMAGE)
registerEnum(FLAG_IGNORENOTMOVEABLE)
registerEnum(FLAG_IGNOREAUTOSTACK)
// Use with itemType:getSlotPosition
registerEnum(SLOTP_WHEREEVER)
registerEnum(SLOTP_HEAD)
registerEnum(SLOTP_NECKLACE)
registerEnum(SLOTP_BACKPACK)
registerEnum(SLOTP_ARMOR)
registerEnum(SLOTP_RIGHT)
registerEnum(SLOTP_LEFT)
registerEnum(SLOTP_LEGS)
registerEnum(SLOTP_FEET)
registerEnum(SLOTP_RING)
registerEnum(SLOTP_AMMO)
registerEnum(SLOTP_DEPOT)
registerEnum(SLOTP_TWO_HAND)
// Use with combat functions
registerEnum(ORIGIN_NONE)
registerEnum(ORIGIN_CONDITION)
registerEnum(ORIGIN_SPELL)
registerEnum(ORIGIN_MELEE)
registerEnum(ORIGIN_RANGED)
// Use with house:getAccessList, house:setAccessList
registerEnum(GUEST_LIST)
registerEnum(SUBOWNER_LIST)
// Use with npc:setSpeechBubble
registerEnum(SPEECHBUBBLE_NONE)
registerEnum(SPEECHBUBBLE_NORMAL)
registerEnum(SPEECHBUBBLE_TRADE)
registerEnum(SPEECHBUBBLE_QUEST)
registerEnum(SPEECHBUBBLE_QUESTTRADER)
// Use with player:addMapMark
registerEnum(MAPMARK_TICK)
registerEnum(MAPMARK_QUESTION)
registerEnum(MAPMARK_EXCLAMATION)
registerEnum(MAPMARK_STAR)
registerEnum(MAPMARK_CROSS)
registerEnum(MAPMARK_TEMPLE)
registerEnum(MAPMARK_KISS)
registerEnum(MAPMARK_SHOVEL)
registerEnum(MAPMARK_SWORD)
registerEnum(MAPMARK_FLAG)
registerEnum(MAPMARK_LOCK)
registerEnum(MAPMARK_BAG)
registerEnum(MAPMARK_SKULL)
registerEnum(MAPMARK_DOLLAR)
registerEnum(MAPMARK_REDNORTH)
registerEnum(MAPMARK_REDSOUTH)
registerEnum(MAPMARK_REDEAST)
registerEnum(MAPMARK_REDWEST)
registerEnum(MAPMARK_GREENNORTH)
registerEnum(MAPMARK_GREENSOUTH)
// Use with Game.getReturnMessage
registerEnum(RETURNVALUE_NOERROR)
registerEnum(RETURNVALUE_NOTPOSSIBLE)
registerEnum(RETURNVALUE_NOTENOUGHROOM)
registerEnum(RETURNVALUE_PLAYERISPZLOCKED)
registerEnum(RETURNVALUE_PLAYERISNOTINVITED)
registerEnum(RETURNVALUE_CANNOTTHROW)
registerEnum(RETURNVALUE_THEREISNOWAY)
registerEnum(RETURNVALUE_DESTINATIONOUTOFREACH)
registerEnum(RETURNVALUE_CREATUREBLOCK)
registerEnum(RETURNVALUE_NOTMOVEABLE)
registerEnum(RETURNVALUE_DROPTWOHANDEDITEM)
registerEnum(RETURNVALUE_BOTHHANDSNEEDTOBEFREE)
registerEnum(RETURNVALUE_CANONLYUSEONEWEAPON)
registerEnum(RETURNVALUE_NEEDEXCHANGE)
registerEnum(RETURNVALUE_CANNOTBEDRESSED)
registerEnum(RETURNVALUE_PUTTHISOBJECTINYOURHAND)
registerEnum(RETURNVALUE_PUTTHISOBJECTINBOTHHANDS)
registerEnum(RETURNVALUE_TOOFARAWAY)
registerEnum(RETURNVALUE_FIRSTGODOWNSTAIRS)
registerEnum(RETURNVALUE_FIRSTGOUPSTAIRS)
registerEnum(RETURNVALUE_CONTAINERNOTENOUGHROOM)
registerEnum(RETURNVALUE_NOTENOUGHCAPACITY)
registerEnum(RETURNVALUE_CANNOTPICKUP)
registerEnum(RETURNVALUE_THISISIMPOSSIBLE)
registerEnum(RETURNVALUE_DEPOTISFULL)
registerEnum(RETURNVALUE_CREATUREDOESNOTEXIST)
registerEnum(RETURNVALUE_CANNOTUSETHISOBJECT)
registerEnum(RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE)
registerEnum(RETURNVALUE_NOTREQUIREDLEVELTOUSERUNE)
registerEnum(RETURNVALUE_YOUAREALREADYTRADING)
registerEnum(RETURNVALUE_THISPLAYERISALREADYTRADING)
registerEnum(RETURNVALUE_YOUMAYNOTLOGOUTDURINGAFIGHT)
registerEnum(RETURNVALUE_DIRECTPLAYERSHOOT)
registerEnum(RETURNVALUE_NOTENOUGHLEVEL)
registerEnum(RETURNVALUE_NOTENOUGHMAGICLEVEL)
registerEnum(RETURNVALUE_NOTENOUGHMANA)
registerEnum(RETURNVALUE_NOTENOUGHSOUL)
registerEnum(RETURNVALUE_YOUAREEXHAUSTED)
registerEnum(RETURNVALUE_PLAYERISNOTREACHABLE)
registerEnum(RETURNVALUE_CANONLYUSETHISRUNEONCREATURES)
registerEnum(RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE)
registerEnum(RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER)
registerEnum(RETURNVALUE_YOUMAYNOTATTACKAPERSONINPROTECTIONZONE)
registerEnum(RETURNVALUE_YOUMAYNOTATTACKAPERSONWHILEINPROTECTIONZONE)
registerEnum(RETURNVALUE_YOUMAYNOTATTACKTHISCREATURE)
registerEnum(RETURNVALUE_YOUCANONLYUSEITONCREATURES)
registerEnum(RETURNVALUE_CREATUREISNOTREACHABLE)
registerEnum(RETURNVALUE_TURNSECUREMODETOATTACKUNMARKEDPLAYERS)
registerEnum(RETURNVALUE_YOUNEEDPREMIUMACCOUNT)
registerEnum(RETURNVALUE_YOUNEEDTOLEARNTHISSPELL)
registerEnum(RETURNVALUE_YOURVOCATIONCANNOTUSETHISSPELL)
registerEnum(RETURNVALUE_YOUNEEDAWEAPONTOUSETHISSPELL)
registerEnum(RETURNVALUE_PLAYERISPZLOCKEDLEAVEPVPZONE)
registerEnum(RETURNVALUE_PLAYERISPZLOCKEDENTERPVPZONE)
registerEnum(RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE)
registerEnum(RETURNVALUE_YOUCANNOTLOGOUTHERE)
registerEnum(RETURNVALUE_YOUNEEDAMAGICITEMTOCASTSPELL)
registerEnum(RETURNVALUE_CANNOTCONJUREITEMHERE)
registerEnum(RETURNVALUE_YOUNEEDTOSPLITYOURSPEARS)
registerEnum(RETURNVALUE_NAMEISTOOAMBIGUOUS)
registerEnum(RETURNVALUE_CANONLYUSEONESHIELD)
registerEnum(RETURNVALUE_NOPARTYMEMBERSINRANGE)
registerEnum(RETURNVALUE_YOUARENOTTHEOWNER)
registerEnum(RETURNVALUE_TRADEPLAYERFARAWAY)
registerEnum(RETURNVALUE_YOUDONTOWNTHISHOUSE)
registerEnum(RETURNVALUE_TRADEPLAYERALREADYOWNSAHOUSE)
registerEnum(RETURNVALUE_TRADEPLAYERHIGHESTBIDDER)
registerEnum(RETURNVALUE_YOUCANNOTTRADETHISHOUSE)
registerEnum(RELOAD_TYPE_ALL)
registerEnum(RELOAD_TYPE_ACTIONS)
registerEnum(RELOAD_TYPE_CHAT)
registerEnum(RELOAD_TYPE_CONFIG)
registerEnum(RELOAD_TYPE_CREATURESCRIPTS)
registerEnum(RELOAD_TYPE_EVENTS)
registerEnum(RELOAD_TYPE_GLOBAL)
registerEnum(RELOAD_TYPE_GLOBALEVENTS)
registerEnum(RELOAD_TYPE_ITEMS)
registerEnum(RELOAD_TYPE_MONSTERS)
registerEnum(RELOAD_TYPE_MOUNTS)
registerEnum(RELOAD_TYPE_MOVEMENTS)
registerEnum(RELOAD_TYPE_NPCS)
registerEnum(RELOAD_TYPE_QUESTS)
registerEnum(RELOAD_TYPE_RAIDS)
registerEnum(RELOAD_TYPE_SPELLS)
registerEnum(RELOAD_TYPE_TALKACTIONS)
registerEnum(RELOAD_TYPE_WEAPONS)
// _G
registerGlobalVariable("INDEX_WHEREEVER", INDEX_WHEREEVER);
registerGlobalBoolean("VIRTUAL_PARENT", true);
registerGlobalMethod("isType", LuaScriptInterface::luaIsType);
registerGlobalMethod("rawgetmetatable", LuaScriptInterface::luaRawGetMetatable);
// configKeys
registerTable("configKeys");
registerEnumIn("configKeys", ConfigManager::ALLOW_CHANGEOUTFIT)
registerEnumIn("configKeys", ConfigManager::ONE_PLAYER_ON_ACCOUNT)
registerEnumIn("configKeys", ConfigManager::AIMBOT_HOTKEY_ENABLED)
registerEnumIn("configKeys", ConfigManager::REMOVE_RUNE_CHARGES)
registerEnumIn("configKeys", ConfigManager::EXPERIENCE_FROM_PLAYERS)
registerEnumIn("configKeys", ConfigManager::FREE_PREMIUM)
registerEnumIn("configKeys", ConfigManager::REPLACE_KICK_ON_LOGIN)
registerEnumIn("configKeys", ConfigManager::ALLOW_CLONES)
registerEnumIn("configKeys", ConfigManager::BIND_ONLY_GLOBAL_ADDRESS)
registerEnumIn("configKeys", ConfigManager::OPTIMIZE_DATABASE)
registerEnumIn("configKeys", ConfigManager::MARKET_PREMIUM)
registerEnumIn("configKeys", ConfigManager::EMOTE_SPELLS)
registerEnumIn("configKeys", ConfigManager::STAMINA_SYSTEM)
registerEnumIn("configKeys", ConfigManager::WARN_UNSAFE_SCRIPTS)
registerEnumIn("configKeys", ConfigManager::CONVERT_UNSAFE_SCRIPTS)
registerEnumIn("configKeys", ConfigManager::CLASSIC_EQUIPMENT_SLOTS)
registerEnumIn("configKeys", ConfigManager::CLASSIC_ATTACK_SPEED)
registerEnumIn("configKeys", ConfigManager::MAP_NAME)
registerEnumIn("configKeys", ConfigManager::HOUSE_RENT_PERIOD)
registerEnumIn("configKeys", ConfigManager::SERVER_NAME)
registerEnumIn("configKeys", ConfigManager::OWNER_NAME)
registerEnumIn("configKeys", ConfigManager::OWNER_EMAIL)
registerEnumIn("configKeys", ConfigManager::URL)
registerEnumIn("configKeys", ConfigManager::LOCATION)
registerEnumIn("configKeys", ConfigManager::IP)
registerEnumIn("configKeys", ConfigManager::MOTD)
registerEnumIn("configKeys", ConfigManager::WORLD_TYPE)
registerEnumIn("configKeys", ConfigManager::MYSQL_HOST)
registerEnumIn("configKeys", ConfigManager::MYSQL_USER)
registerEnumIn("configKeys", ConfigManager::MYSQL_PASS)
registerEnumIn("configKeys", ConfigManager::MYSQL_DB)
registerEnumIn("configKeys", ConfigManager::MYSQL_SOCK)
registerEnumIn("configKeys", ConfigManager::DEFAULT_PRIORITY)
registerEnumIn("configKeys", ConfigManager::MAP_AUTHOR)
registerEnumIn("configKeys", ConfigManager::SQL_PORT)
registerEnumIn("configKeys", ConfigManager::MAX_PLAYERS)
registerEnumIn("configKeys", ConfigManager::PZ_LOCKED)
registerEnumIn("configKeys", ConfigManager::DEFAULT_DESPAWNRANGE)
registerEnumIn("configKeys", ConfigManager::DEFAULT_DESPAWNRADIUS)
registerEnumIn("configKeys", ConfigManager::RATE_EXPERIENCE)
registerEnumIn("configKeys", ConfigManager::RATE_SKILL)
registerEnumIn("configKeys", ConfigManager::RATE_LOOT)
registerEnumIn("configKeys", ConfigManager::RATE_MAGIC)
registerEnumIn("configKeys", ConfigManager::RATE_SPAWN)
registerEnumIn("configKeys", ConfigManager::HOUSE_PRICE)
registerEnumIn("configKeys", ConfigManager::KILLS_TO_RED)
registerEnumIn("configKeys", ConfigManager::KILLS_TO_BLACK)
registerEnumIn("configKeys", ConfigManager::MAX_MESSAGEBUFFER)
registerEnumIn("configKeys", ConfigManager::ACTIONS_DELAY_INTERVAL)
registerEnumIn("configKeys", ConfigManager::EX_ACTIONS_DELAY_INTERVAL)
registerEnumIn("configKeys", ConfigManager::KICK_AFTER_MINUTES)
registerEnumIn("configKeys", ConfigManager::PROTECTION_LEVEL)
registerEnumIn("configKeys", ConfigManager::DEATH_LOSE_PERCENT)
registerEnumIn("configKeys", ConfigManager::STATUSQUERY_TIMEOUT)
registerEnumIn("configKeys", ConfigManager::FRAG_TIME)
registerEnumIn("configKeys", ConfigManager::WHITE_SKULL_TIME)
registerEnumIn("configKeys", ConfigManager::GAME_PORT)
registerEnumIn("configKeys", ConfigManager::LOGIN_PORT)
registerEnumIn("configKeys", ConfigManager::STATUS_PORT)
registerEnumIn("configKeys", ConfigManager::STAIRHOP_DELAY)
registerEnumIn("configKeys", ConfigManager::MARKET_OFFER_DURATION)
registerEnumIn("configKeys", ConfigManager::CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES)
registerEnumIn("configKeys", ConfigManager::MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER)
registerEnumIn("configKeys", ConfigManager::EXP_FROM_PLAYERS_LEVEL_RANGE)
registerEnumIn("configKeys", ConfigManager::MAX_PACKETS_PER_SECOND)
// os
registerMethod("os", "mtime", LuaScriptInterface::luaSystemTime);
// table
registerMethod("table", "create", LuaScriptInterface::luaTableCreate);
// Game
registerTable("Game");
registerMethod("Game", "getSpectators", LuaScriptInterface::luaGameGetSpectators);
registerMethod("Game", "getPlayers", LuaScriptInterface::luaGameGetPlayers);
registerMethod("Game", "loadMap", LuaScriptInterface::luaGameLoadMap);
registerMethod("Game", "getExperienceStage", LuaScriptInterface::luaGameGetExperienceStage);
registerMethod("Game", "getMonsterCount", LuaScriptInterface::luaGameGetMonsterCount);
registerMethod("Game", "getPlayerCount", LuaScriptInterface::luaGameGetPlayerCount);
registerMethod("Game", "getNpcCount", LuaScriptInterface::luaGameGetNpcCount);
registerMethod("Game", "getTowns", LuaScriptInterface::luaGameGetTowns);
registerMethod("Game", "getHouses", LuaScriptInterface::luaGameGetHouses);
registerMethod("Game", "getGameState", LuaScriptInterface::luaGameGetGameState);
registerMethod("Game", "setGameState", LuaScriptInterface::luaGameSetGameState);
registerMethod("Game", "getWorldType", LuaScriptInterface::luaGameGetWorldType);
registerMethod("Game", "setWorldType", LuaScriptInterface::luaGameSetWorldType);
registerMethod("Game", "getReturnMessage", LuaScriptInterface::luaGameGetReturnMessage);
registerMethod("Game", "createItem", LuaScriptInterface::luaGameCreateItem);
registerMethod("Game", "createContainer", LuaScriptInterface::luaGameCreateContainer);
registerMethod("Game", "createMonster", LuaScriptInterface::luaGameCreateMonster);
registerMethod("Game", "createNpc", LuaScriptInterface::luaGameCreateNpc);
registerMethod("Game", "createTile", LuaScriptInterface::luaGameCreateTile);
registerMethod("Game", "startRaid", LuaScriptInterface::luaGameStartRaid);
registerMethod("Game", "getClientVersion", LuaScriptInterface::luaGameGetClientVersion);
registerMethod("Game", "reload", LuaScriptInterface::luaGameReload);
// Variant
registerClass("Variant", "", LuaScriptInterface::luaVariantCreate);
registerMethod("Variant", "getNumber", LuaScriptInterface::luaVariantGetNumber);
registerMethod("Variant", "getString", LuaScriptInterface::luaVariantGetString);
registerMethod("Variant", "getPosition", LuaScriptInterface::luaVariantGetPosition);
// Position
registerClass("Position", "", LuaScriptInterface::luaPositionCreate);
registerMetaMethod("Position", "__add", LuaScriptInterface::luaPositionAdd);
registerMetaMethod("Position", "__sub", LuaScriptInterface::luaPositionSub);
registerMetaMethod("Position", "__eq", LuaScriptInterface::luaPositionCompare);
registerMethod("Position", "getDistance", LuaScriptInterface::luaPositionGetDistance);
registerMethod("Position", "isSightClear", LuaScriptInterface::luaPositionIsSightClear);
registerMethod("Position", "sendMagicEffect", LuaScriptInterface::luaPositionSendMagicEffect);
registerMethod("Position", "sendDistanceEffect", LuaScriptInterface::luaPositionSendDistanceEffect);
// Tile
registerClass("Tile", "", LuaScriptInterface::luaTileCreate);
registerMetaMethod("Tile", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Tile", "getPosition", LuaScriptInterface::luaTileGetPosition);
registerMethod("Tile", "getGround", LuaScriptInterface::luaTileGetGround);
registerMethod("Tile", "getThing", LuaScriptInterface::luaTileGetThing);
registerMethod("Tile", "getThingCount", LuaScriptInterface::luaTileGetThingCount);
registerMethod("Tile", "getTopVisibleThing", LuaScriptInterface::luaTileGetTopVisibleThing);
registerMethod("Tile", "getTopTopItem", LuaScriptInterface::luaTileGetTopTopItem);
registerMethod("Tile", "getTopDownItem", LuaScriptInterface::luaTileGetTopDownItem);
registerMethod("Tile", "getFieldItem", LuaScriptInterface::luaTileGetFieldItem);
registerMethod("Tile", "getItemById", LuaScriptInterface::luaTileGetItemById);
registerMethod("Tile", "getItemByType", LuaScriptInterface::luaTileGetItemByType);
registerMethod("Tile", "getItemByTopOrder", LuaScriptInterface::luaTileGetItemByTopOrder);
registerMethod("Tile", "getItemCountById", LuaScriptInterface::luaTileGetItemCountById);
registerMethod("Tile", "getBottomCreature", LuaScriptInterface::luaTileGetBottomCreature);
registerMethod("Tile", "getTopCreature", LuaScriptInterface::luaTileGetTopCreature);
registerMethod("Tile", "getBottomVisibleCreature", LuaScriptInterface::luaTileGetBottomVisibleCreature);
registerMethod("Tile", "getTopVisibleCreature", LuaScriptInterface::luaTileGetTopVisibleCreature);
registerMethod("Tile", "getItems", LuaScriptInterface::luaTileGetItems);
registerMethod("Tile", "getItemCount", LuaScriptInterface::luaTileGetItemCount);
registerMethod("Tile", "getDownItemCount", LuaScriptInterface::luaTileGetDownItemCount);
registerMethod("Tile", "getTopItemCount", LuaScriptInterface::luaTileGetTopItemCount);
registerMethod("Tile", "getCreatures", LuaScriptInterface::luaTileGetCreatures);
registerMethod("Tile", "getCreatureCount", LuaScriptInterface::luaTileGetCreatureCount);
registerMethod("Tile", "getThingIndex", LuaScriptInterface::luaTileGetThingIndex);
registerMethod("Tile", "hasProperty", LuaScriptInterface::luaTileHasProperty);
registerMethod("Tile", "hasFlag", LuaScriptInterface::luaTileHasFlag);
registerMethod("Tile", "queryAdd", LuaScriptInterface::luaTileQueryAdd);
registerMethod("Tile", "getHouse", LuaScriptInterface::luaTileGetHouse);
// NetworkMessage
registerClass("NetworkMessage", "", LuaScriptInterface::luaNetworkMessageCreate);
registerMetaMethod("NetworkMessage", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMetaMethod("NetworkMessage", "__gc", LuaScriptInterface::luaNetworkMessageDelete);
registerMethod("NetworkMessage", "delete", LuaScriptInterface::luaNetworkMessageDelete);
registerMethod("NetworkMessage", "getByte", LuaScriptInterface::luaNetworkMessageGetByte);
registerMethod("NetworkMessage", "getU16", LuaScriptInterface::luaNetworkMessageGetU16);
registerMethod("NetworkMessage", "getU32", LuaScriptInterface::luaNetworkMessageGetU32);
registerMethod("NetworkMessage", "getU64", LuaScriptInterface::luaNetworkMessageGetU64);
registerMethod("NetworkMessage", "getString", LuaScriptInterface::luaNetworkMessageGetString);
registerMethod("NetworkMessage", "getPosition", LuaScriptInterface::luaNetworkMessageGetPosition);
registerMethod("NetworkMessage", "addByte", LuaScriptInterface::luaNetworkMessageAddByte);
registerMethod("NetworkMessage", "addU16", LuaScriptInterface::luaNetworkMessageAddU16);
registerMethod("NetworkMessage", "addU32", LuaScriptInterface::luaNetworkMessageAddU32);
registerMethod("NetworkMessage", "addU64", LuaScriptInterface::luaNetworkMessageAddU64);
registerMethod("NetworkMessage", "addString", LuaScriptInterface::luaNetworkMessageAddString);
registerMethod("NetworkMessage", "addPosition", LuaScriptInterface::luaNetworkMessageAddPosition);
registerMethod("NetworkMessage", "addDouble", LuaScriptInterface::luaNetworkMessageAddDouble);
registerMethod("NetworkMessage", "addItem", LuaScriptInterface::luaNetworkMessageAddItem);
registerMethod("NetworkMessage", "addItemId", LuaScriptInterface::luaNetworkMessageAddItemId);
registerMethod("NetworkMessage", "reset", LuaScriptInterface::luaNetworkMessageReset);
registerMethod("NetworkMessage", "skipBytes", LuaScriptInterface::luaNetworkMessageSkipBytes);
registerMethod("NetworkMessage", "sendToPlayer", LuaScriptInterface::luaNetworkMessageSendToPlayer);
// ModalWindow
registerClass("ModalWindow", "", LuaScriptInterface::luaModalWindowCreate);
registerMetaMethod("ModalWindow", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMetaMethod("ModalWindow", "__gc", LuaScriptInterface::luaModalWindowDelete);
registerMethod("ModalWindow", "delete", LuaScriptInterface::luaModalWindowDelete);
registerMethod("ModalWindow", "getId", LuaScriptInterface::luaModalWindowGetId);
registerMethod("ModalWindow", "getTitle", LuaScriptInterface::luaModalWindowGetTitle);
registerMethod("ModalWindow", "getMessage", LuaScriptInterface::luaModalWindowGetMessage);
registerMethod("ModalWindow", "setTitle", LuaScriptInterface::luaModalWindowSetTitle);
registerMethod("ModalWindow", "setMessage", LuaScriptInterface::luaModalWindowSetMessage);
registerMethod("ModalWindow", "getButtonCount", LuaScriptInterface::luaModalWindowGetButtonCount);
registerMethod("ModalWindow", "getChoiceCount", LuaScriptInterface::luaModalWindowGetChoiceCount);
registerMethod("ModalWindow", "addButton", LuaScriptInterface::luaModalWindowAddButton);
registerMethod("ModalWindow", "addChoice", LuaScriptInterface::luaModalWindowAddChoice);
registerMethod("ModalWindow", "getDefaultEnterButton", LuaScriptInterface::luaModalWindowGetDefaultEnterButton);
registerMethod("ModalWindow", "setDefaultEnterButton", LuaScriptInterface::luaModalWindowSetDefaultEnterButton);
registerMethod("ModalWindow", "getDefaultEscapeButton", LuaScriptInterface::luaModalWindowGetDefaultEscapeButton);
registerMethod("ModalWindow", "setDefaultEscapeButton", LuaScriptInterface::luaModalWindowSetDefaultEscapeButton);
registerMethod("ModalWindow", "hasPriority", LuaScriptInterface::luaModalWindowHasPriority);
registerMethod("ModalWindow", "setPriority", LuaScriptInterface::luaModalWindowSetPriority);
registerMethod("ModalWindow", "sendToPlayer", LuaScriptInterface::luaModalWindowSendToPlayer);
// Item
registerClass("Item", "", LuaScriptInterface::luaItemCreate);
registerMetaMethod("Item", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Item", "isItem", LuaScriptInterface::luaItemIsItem);
registerMethod("Item", "getParent", LuaScriptInterface::luaItemGetParent);
registerMethod("Item", "getTopParent", LuaScriptInterface::luaItemGetTopParent);
registerMethod("Item", "getId", LuaScriptInterface::luaItemGetId);
registerMethod("Item", "clone", LuaScriptInterface::luaItemClone);
registerMethod("Item", "split", LuaScriptInterface::luaItemSplit);
registerMethod("Item", "remove", LuaScriptInterface::luaItemRemove);
registerMethod("Item", "getUniqueId", LuaScriptInterface::luaItemGetUniqueId);
registerMethod("Item", "getActionId", LuaScriptInterface::luaItemGetActionId);
registerMethod("Item", "setActionId", LuaScriptInterface::luaItemSetActionId);
registerMethod("Item", "getCount", LuaScriptInterface::luaItemGetCount);
registerMethod("Item", "getCharges", LuaScriptInterface::luaItemGetCharges);
registerMethod("Item", "getFluidType", LuaScriptInterface::luaItemGetFluidType);
registerMethod("Item", "getWeight", LuaScriptInterface::luaItemGetWeight);
registerMethod("Item", "getSubType", LuaScriptInterface::luaItemGetSubType);
registerMethod("Item", "getName", LuaScriptInterface::luaItemGetName);
registerMethod("Item", "getPluralName", LuaScriptInterface::luaItemGetPluralName);
registerMethod("Item", "getArticle", LuaScriptInterface::luaItemGetArticle);
registerMethod("Item", "getPosition", LuaScriptInterface::luaItemGetPosition);
registerMethod("Item", "getTile", LuaScriptInterface::luaItemGetTile);
registerMethod("Item", "hasAttribute", LuaScriptInterface::luaItemHasAttribute);
registerMethod("Item", "getAttribute", LuaScriptInterface::luaItemGetAttribute);
registerMethod("Item", "setAttribute", LuaScriptInterface::luaItemSetAttribute);
registerMethod("Item", "removeAttribute", LuaScriptInterface::luaItemRemoveAttribute);
registerMethod("Item", "moveTo", LuaScriptInterface::luaItemMoveTo);
registerMethod("Item", "transform", LuaScriptInterface::luaItemTransform);
registerMethod("Item", "decay", LuaScriptInterface::luaItemDecay);
registerMethod("Item", "getDescription", LuaScriptInterface::luaItemGetDescription);
registerMethod("Item", "hasProperty", LuaScriptInterface::luaItemHasProperty);
registerMethod("Item", "isLoadedFromMap", LuaScriptInterface::luaItemIsLoadedFromMap);
// Container
registerClass("Container", "Item", LuaScriptInterface::luaContainerCreate);
registerMetaMethod("Container", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Container", "getSize", LuaScriptInterface::luaContainerGetSize);
registerMethod("Container", "getCapacity", LuaScriptInterface::luaContainerGetCapacity);
registerMethod("Container", "getEmptySlots", LuaScriptInterface::luaContainerGetEmptySlots);
registerMethod("Container", "getItemHoldingCount", LuaScriptInterface::luaContainerGetItemHoldingCount);
registerMethod("Container", "getItemCountById", LuaScriptInterface::luaContainerGetItemCountById);
registerMethod("Container", "getItem", LuaScriptInterface::luaContainerGetItem);
registerMethod("Container", "hasItem", LuaScriptInterface::luaContainerHasItem);
registerMethod("Container", "addItem", LuaScriptInterface::luaContainerAddItem);
registerMethod("Container", "addItemEx", LuaScriptInterface::luaContainerAddItemEx);
// Teleport
registerClass("Teleport", "Item", LuaScriptInterface::luaTeleportCreate);
registerMetaMethod("Teleport", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Teleport", "getDestination", LuaScriptInterface::luaTeleportGetDestination);
registerMethod("Teleport", "setDestination", LuaScriptInterface::luaTeleportSetDestination);
// Creature
registerClass("Creature", "", LuaScriptInterface::luaCreatureCreate);
registerMetaMethod("Creature", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Creature", "getEvents", LuaScriptInterface::luaCreatureGetEvents);
registerMethod("Creature", "registerEvent", LuaScriptInterface::luaCreatureRegisterEvent);
registerMethod("Creature", "unregisterEvent", LuaScriptInterface::luaCreatureUnregisterEvent);
registerMethod("Creature", "isRemoved", LuaScriptInterface::luaCreatureIsRemoved);
registerMethod("Creature", "isCreature", LuaScriptInterface::luaCreatureIsCreature);
registerMethod("Creature", "isInGhostMode", LuaScriptInterface::luaCreatureIsInGhostMode);
registerMethod("Creature", "isHealthHidden", LuaScriptInterface::luaCreatureIsHealthHidden);
registerMethod("Creature", "isImmune", LuaScriptInterface::luaCreatureIsImmune);
registerMethod("Creature", "canSee", LuaScriptInterface::luaCreatureCanSee);
registerMethod("Creature", "canSeeCreature", LuaScriptInterface::luaCreatureCanSeeCreature);
registerMethod("Creature", "getParent", LuaScriptInterface::luaCreatureGetParent);
registerMethod("Creature", "getId", LuaScriptInterface::luaCreatureGetId);
registerMethod("Creature", "getName", LuaScriptInterface::luaCreatureGetName);
registerMethod("Creature", "getTarget", LuaScriptInterface::luaCreatureGetTarget);
registerMethod("Creature", "setTarget", LuaScriptInterface::luaCreatureSetTarget);
registerMethod("Creature", "getFollowCreature", LuaScriptInterface::luaCreatureGetFollowCreature);
registerMethod("Creature", "setFollowCreature", LuaScriptInterface::luaCreatureSetFollowCreature);
registerMethod("Creature", "getMaster", LuaScriptInterface::luaCreatureGetMaster);
registerMethod("Creature", "setMaster", LuaScriptInterface::luaCreatureSetMaster);
registerMethod("Creature", "getLight", LuaScriptInterface::luaCreatureGetLight);
registerMethod("Creature", "setLight", LuaScriptInterface::luaCreatureSetLight);
registerMethod("Creature", "getSpeed", LuaScriptInterface::luaCreatureGetSpeed);
registerMethod("Creature", "getBaseSpeed", LuaScriptInterface::luaCreatureGetBaseSpeed);
registerMethod("Creature", "changeSpeed", LuaScriptInterface::luaCreatureChangeSpeed);
registerMethod("Creature", "setDropLoot", LuaScriptInterface::luaCreatureSetDropLoot);
registerMethod("Creature", "setSkillLoss", LuaScriptInterface::luaCreatureSetSkillLoss);
registerMethod("Creature", "getPosition", LuaScriptInterface::luaCreatureGetPosition);
registerMethod("Creature", "getTile", LuaScriptInterface::luaCreatureGetTile);
registerMethod("Creature", "getDirection", LuaScriptInterface::luaCreatureGetDirection);
registerMethod("Creature", "setDirection", LuaScriptInterface::luaCreatureSetDirection);
registerMethod("Creature", "getHealth", LuaScriptInterface::luaCreatureGetHealth);
registerMethod("Creature", "addHealth", LuaScriptInterface::luaCreatureAddHealth);
registerMethod("Creature", "getMaxHealth", LuaScriptInterface::luaCreatureGetMaxHealth);
registerMethod("Creature", "setMaxHealth", LuaScriptInterface::luaCreatureSetMaxHealth);
registerMethod("Creature", "setHiddenHealth", LuaScriptInterface::luaCreatureSetHiddenHealth);
registerMethod("Creature", "getSkull", LuaScriptInterface::luaCreatureGetSkull);
registerMethod("Creature", "setSkull", LuaScriptInterface::luaCreatureSetSkull);
registerMethod("Creature", "getOutfit", LuaScriptInterface::luaCreatureGetOutfit);
registerMethod("Creature", "setOutfit", LuaScriptInterface::luaCreatureSetOutfit);
registerMethod("Creature", "getCondition", LuaScriptInterface::luaCreatureGetCondition);
registerMethod("Creature", "addCondition", LuaScriptInterface::luaCreatureAddCondition);
registerMethod("Creature", "removeCondition", LuaScriptInterface::luaCreatureRemoveCondition);
registerMethod("Creature", "hasCondition", LuaScriptInterface::luaCreatureHasCondition);
registerMethod("Creature", "remove", LuaScriptInterface::luaCreatureRemove);
registerMethod("Creature", "teleportTo", LuaScriptInterface::luaCreatureTeleportTo);
registerMethod("Creature", "say", LuaScriptInterface::luaCreatureSay);
registerMethod("Creature", "getDamageMap", LuaScriptInterface::luaCreatureGetDamageMap);
registerMethod("Creature", "getSummons", LuaScriptInterface::luaCreatureGetSummons);
registerMethod("Creature", "getDescription", LuaScriptInterface::luaCreatureGetDescription);
registerMethod("Creature", "getPathTo", LuaScriptInterface::luaCreatureGetPathTo);
registerMethod("Creature", "move", LuaScriptInterface::luaCreatureMove);
// Player
registerClass("Player", "Creature", LuaScriptInterface::luaPlayerCreate);
registerMetaMethod("Player", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Player", "isPlayer", LuaScriptInterface::luaPlayerIsPlayer);
registerMethod("Player", "getGuid", LuaScriptInterface::luaPlayerGetGuid);
registerMethod("Player", "getIp", LuaScriptInterface::luaPlayerGetIp);
registerMethod("Player", "getAccountId", LuaScriptInterface::luaPlayerGetAccountId);
registerMethod("Player", "getLastLoginSaved", LuaScriptInterface::luaPlayerGetLastLoginSaved);
registerMethod("Player", "getLastLogout", LuaScriptInterface::luaPlayerGetLastLogout);
registerMethod("Player", "getAccountType", LuaScriptInterface::luaPlayerGetAccountType);
registerMethod("Player", "setAccountType", LuaScriptInterface::luaPlayerSetAccountType);
registerMethod("Player", "getCapacity", LuaScriptInterface::luaPlayerGetCapacity);
registerMethod("Player", "setCapacity", LuaScriptInterface::luaPlayerSetCapacity);
registerMethod("Player", "getFreeCapacity", LuaScriptInterface::luaPlayerGetFreeCapacity);
registerMethod("Player", "getDepotChest", LuaScriptInterface::luaPlayerGetDepotChest);
registerMethod("Player", "getInbox", LuaScriptInterface::luaPlayerGetInbox);
registerMethod("Player", "getSkullTime", LuaScriptInterface::luaPlayerGetSkullTime);
registerMethod("Player", "setSkullTime", LuaScriptInterface::luaPlayerSetSkullTime);
registerMethod("Player", "getDeathPenalty", LuaScriptInterface::luaPlayerGetDeathPenalty);
registerMethod("Player", "getExperience", LuaScriptInterface::luaPlayerGetExperience);
registerMethod("Player", "addExperience", LuaScriptInterface::luaPlayerAddExperience);
registerMethod("Player", "removeExperience", LuaScriptInterface::luaPlayerRemoveExperience);
registerMethod("Player", "getLevel", LuaScriptInterface::luaPlayerGetLevel);
registerMethod("Player", "getMagicLevel", LuaScriptInterface::luaPlayerGetMagicLevel);
registerMethod("Player", "getBaseMagicLevel", LuaScriptInterface::luaPlayerGetBaseMagicLevel);
registerMethod("Player", "getMana", LuaScriptInterface::luaPlayerGetMana);
registerMethod("Player", "addMana", LuaScriptInterface::luaPlayerAddMana);
registerMethod("Player", "getMaxMana", LuaScriptInterface::luaPlayerGetMaxMana);
registerMethod("Player", "setMaxMana", LuaScriptInterface::luaPlayerSetMaxMana);
registerMethod("Player", "getManaSpent", LuaScriptInterface::luaPlayerGetManaSpent);
registerMethod("Player", "addManaSpent", LuaScriptInterface::luaPlayerAddManaSpent);
registerMethod("Player", "getBaseMaxHealth", LuaScriptInterface::luaPlayerGetBaseMaxHealth);
registerMethod("Player", "getBaseMaxMana", LuaScriptInterface::luaPlayerGetBaseMaxMana);
registerMethod("Player", "getSkillLevel", LuaScriptInterface::luaPlayerGetSkillLevel);
registerMethod("Player", "getEffectiveSkillLevel", LuaScriptInterface::luaPlayerGetEffectiveSkillLevel);
registerMethod("Player", "getSkillPercent", LuaScriptInterface::luaPlayerGetSkillPercent);
registerMethod("Player", "getSkillTries", LuaScriptInterface::luaPlayerGetSkillTries);
registerMethod("Player", "addSkillTries", LuaScriptInterface::luaPlayerAddSkillTries);
registerMethod("Player", "addOfflineTrainingTime", LuaScriptInterface::luaPlayerAddOfflineTrainingTime);
registerMethod("Player", "getOfflineTrainingTime", LuaScriptInterface::luaPlayerGetOfflineTrainingTime);
registerMethod("Player", "removeOfflineTrainingTime", LuaScriptInterface::luaPlayerRemoveOfflineTrainingTime);
registerMethod("Player", "addOfflineTrainingTries", LuaScriptInterface::luaPlayerAddOfflineTrainingTries);
registerMethod("Player", "getOfflineTrainingSkill", LuaScriptInterface::luaPlayerGetOfflineTrainingSkill);
registerMethod("Player", "setOfflineTrainingSkill", LuaScriptInterface::luaPlayerSetOfflineTrainingSkill);
registerMethod("Player", "getItemCount", LuaScriptInterface::luaPlayerGetItemCount);
registerMethod("Player", "getItemById", LuaScriptInterface::luaPlayerGetItemById);
registerMethod("Player", "getVocation", LuaScriptInterface::luaPlayerGetVocation);
registerMethod("Player", "setVocation", LuaScriptInterface::luaPlayerSetVocation);
registerMethod("Player", "getSex", LuaScriptInterface::luaPlayerGetSex);
registerMethod("Player", "setSex", LuaScriptInterface::luaPlayerSetSex);
registerMethod("Player", "getTown", LuaScriptInterface::luaPlayerGetTown);
registerMethod("Player", "setTown", LuaScriptInterface::luaPlayerSetTown);
registerMethod("Player", "getGuild", LuaScriptInterface::luaPlayerGetGuild);
registerMethod("Player", "setGuild", LuaScriptInterface::luaPlayerSetGuild);
registerMethod("Player", "getGuildLevel", LuaScriptInterface::luaPlayerGetGuildLevel);
registerMethod("Player", "setGuildLevel", LuaScriptInterface::luaPlayerSetGuildLevel);
registerMethod("Player", "getGuildNick", LuaScriptInterface::luaPlayerGetGuildNick);
registerMethod("Player", "setGuildNick", LuaScriptInterface::luaPlayerSetGuildNick);
registerMethod("Player", "getGroup", LuaScriptInterface::luaPlayerGetGroup);
registerMethod("Player", "setGroup", LuaScriptInterface::luaPlayerSetGroup);
registerMethod("Player", "getStamina", LuaScriptInterface::luaPlayerGetStamina);
registerMethod("Player", "setStamina", LuaScriptInterface::luaPlayerSetStamina);
registerMethod("Player", "getSoul", LuaScriptInterface::luaPlayerGetSoul);
registerMethod("Player", "addSoul", LuaScriptInterface::luaPlayerAddSoul);
registerMethod("Player", "getMaxSoul", LuaScriptInterface::luaPlayerGetMaxSoul);
registerMethod("Player", "getBankBalance", LuaScriptInterface::luaPlayerGetBankBalance);
registerMethod("Player", "setBankBalance", LuaScriptInterface::luaPlayerSetBankBalance);
registerMethod("Player", "getStorageValue", LuaScriptInterface::luaPlayerGetStorageValue);
registerMethod("Player", "setStorageValue", LuaScriptInterface::luaPlayerSetStorageValue);
registerMethod("Player", "addItem", LuaScriptInterface::luaPlayerAddItem);
registerMethod("Player", "addItemEx", LuaScriptInterface::luaPlayerAddItemEx);
registerMethod("Player", "removeItem", LuaScriptInterface::luaPlayerRemoveItem);
registerMethod("Player", "getMoney", LuaScriptInterface::luaPlayerGetMoney);
registerMethod("Player", "addMoney", LuaScriptInterface::luaPlayerAddMoney);
registerMethod("Player", "removeMoney", LuaScriptInterface::luaPlayerRemoveMoney);
registerMethod("Player", "showTextDialog", LuaScriptInterface::luaPlayerShowTextDialog);
registerMethod("Player", "sendTextMessage", LuaScriptInterface::luaPlayerSendTextMessage);
registerMethod("Player", "sendChannelMessage", LuaScriptInterface::luaPlayerSendChannelMessage);
registerMethod("Player", "sendPrivateMessage", LuaScriptInterface::luaPlayerSendPrivateMessage);
registerMethod("Player", "channelSay", LuaScriptInterface::luaPlayerChannelSay);
registerMethod("Player", "openChannel", LuaScriptInterface::luaPlayerOpenChannel);
registerMethod("Player", "getSlotItem", LuaScriptInterface::luaPlayerGetSlotItem);
registerMethod("Player", "getParty", LuaScriptInterface::luaPlayerGetParty);
registerMethod("Player", "addOutfit", LuaScriptInterface::luaPlayerAddOutfit);
registerMethod("Player", "addOutfitAddon", LuaScriptInterface::luaPlayerAddOutfitAddon);
registerMethod("Player", "removeOutfit", LuaScriptInterface::luaPlayerRemoveOutfit);
registerMethod("Player", "removeOutfitAddon", LuaScriptInterface::luaPlayerRemoveOutfitAddon);
registerMethod("Player", "hasOutfit", LuaScriptInterface::luaPlayerHasOutfit);
registerMethod("Player", "sendOutfitWindow", LuaScriptInterface::luaPlayerSendOutfitWindow);
registerMethod("Player", "addMount", LuaScriptInterface::luaPlayerAddMount);
registerMethod("Player", "removeMount", LuaScriptInterface::luaPlayerRemoveMount);
registerMethod("Player", "hasMount", LuaScriptInterface::luaPlayerHasMount);
registerMethod("Player", "getPremiumDays", LuaScriptInterface::luaPlayerGetPremiumDays);
registerMethod("Player", "addPremiumDays", LuaScriptInterface::luaPlayerAddPremiumDays);
registerMethod("Player", "removePremiumDays", LuaScriptInterface::luaPlayerRemovePremiumDays);
registerMethod("Player", "hasBlessing", LuaScriptInterface::luaPlayerHasBlessing);
registerMethod("Player", "addBlessing", LuaScriptInterface::luaPlayerAddBlessing);
registerMethod("Player", "removeBlessing", LuaScriptInterface::luaPlayerRemoveBlessing);
registerMethod("Player", "canLearnSpell", LuaScriptInterface::luaPlayerCanLearnSpell);
registerMethod("Player", "learnSpell", LuaScriptInterface::luaPlayerLearnSpell);
registerMethod("Player", "forgetSpell", LuaScriptInterface::luaPlayerForgetSpell);
registerMethod("Player", "hasLearnedSpell", LuaScriptInterface::luaPlayerHasLearnedSpell);
registerMethod("Player", "sendTutorial", LuaScriptInterface::luaPlayerSendTutorial);
registerMethod("Player", "addMapMark", LuaScriptInterface::luaPlayerAddMapMark);
registerMethod("Player", "save", LuaScriptInterface::luaPlayerSave);
registerMethod("Player", "popupFYI", LuaScriptInterface::luaPlayerPopupFYI);
registerMethod("Player", "isPzLocked", LuaScriptInterface::luaPlayerIsPzLocked);
registerMethod("Player", "getClient", LuaScriptInterface::luaPlayerGetClient);
registerMethod("Player", "getHouse", LuaScriptInterface::luaPlayerGetHouse);
registerMethod("Player", "sendHouseWindow", LuaScriptInterface::luaPlayerSendHouseWindow);
registerMethod("Player", "setEditHouse", LuaScriptInterface::luaPlayerSetEditHouse);
registerMethod("Player", "setGhostMode", LuaScriptInterface::luaPlayerSetGhostMode);
registerMethod("Player", "getContainerId", LuaScriptInterface::luaPlayerGetContainerId);
registerMethod("Player", "getContainerById", LuaScriptInterface::luaPlayerGetContainerById);
registerMethod("Player", "getContainerIndex", LuaScriptInterface::luaPlayerGetContainerIndex);
registerMethod("Player", "getInstantSpells", LuaScriptInterface::luaPlayerGetInstantSpells);
registerMethod("Player", "canCast", LuaScriptInterface::luaPlayerCanCast);
registerMethod("Player", "hasChaseMode", LuaScriptInterface::luaPlayerHasChaseMode);
registerMethod("Player", "hasSecureMode", LuaScriptInterface::luaPlayerHasSecureMode);
registerMethod("Player", "getFightMode", LuaScriptInterface::luaPlayerGetFightMode);
// Monster
registerClass("Monster", "Creature", LuaScriptInterface::luaMonsterCreate);
registerMetaMethod("Monster", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Monster", "isMonster", LuaScriptInterface::luaMonsterIsMonster);
registerMethod("Monster", "getType", LuaScriptInterface::luaMonsterGetType);
registerMethod("Monster", "getSpawnPosition", LuaScriptInterface::luaMonsterGetSpawnPosition);
registerMethod("Monster", "isInSpawnRange", LuaScriptInterface::luaMonsterIsInSpawnRange);
registerMethod("Monster", "isIdle", LuaScriptInterface::luaMonsterIsIdle);
registerMethod("Monster", "setIdle", LuaScriptInterface::luaMonsterSetIdle);
registerMethod("Monster", "isTarget", LuaScriptInterface::luaMonsterIsTarget);
registerMethod("Monster", "isOpponent", LuaScriptInterface::luaMonsterIsOpponent);
registerMethod("Monster", "isFriend", LuaScriptInterface::luaMonsterIsFriend);
registerMethod("Monster", "addFriend", LuaScriptInterface::luaMonsterAddFriend);
registerMethod("Monster", "removeFriend", LuaScriptInterface::luaMonsterRemoveFriend);
registerMethod("Monster", "getFriendList", LuaScriptInterface::luaMonsterGetFriendList);
registerMethod("Monster", "getFriendCount", LuaScriptInterface::luaMonsterGetFriendCount);
registerMethod("Monster", "addTarget", LuaScriptInterface::luaMonsterAddTarget);
registerMethod("Monster", "removeTarget", LuaScriptInterface::luaMonsterRemoveTarget);
registerMethod("Monster", "getTargetList", LuaScriptInterface::luaMonsterGetTargetList);
registerMethod("Monster", "getTargetCount", LuaScriptInterface::luaMonsterGetTargetCount);
registerMethod("Monster", "selectTarget", LuaScriptInterface::luaMonsterSelectTarget);
registerMethod("Monster", "searchTarget", LuaScriptInterface::luaMonsterSearchTarget);
// Npc
registerClass("Npc", "Creature", LuaScriptInterface::luaNpcCreate);
registerMetaMethod("Npc", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Npc", "isNpc", LuaScriptInterface::luaNpcIsNpc);
registerMethod("Npc", "setMasterPos", LuaScriptInterface::luaNpcSetMasterPos);
registerMethod("Npc", "getSpeechBubble", LuaScriptInterface::luaNpcGetSpeechBubble);
registerMethod("Npc", "setSpeechBubble", LuaScriptInterface::luaNpcSetSpeechBubble);
// Guild
registerClass("Guild", "", LuaScriptInterface::luaGuildCreate);
registerMetaMethod("Guild", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Guild", "getId", LuaScriptInterface::luaGuildGetId);
registerMethod("Guild", "getName", LuaScriptInterface::luaGuildGetName);
registerMethod("Guild", "getMembersOnline", LuaScriptInterface::luaGuildGetMembersOnline);
registerMethod("Guild", "addRank", LuaScriptInterface::luaGuildAddRank);
registerMethod("Guild", "getRankById", LuaScriptInterface::luaGuildGetRankById);
registerMethod("Guild", "getRankByLevel", LuaScriptInterface::luaGuildGetRankByLevel);
registerMethod("Guild", "getMotd", LuaScriptInterface::luaGuildGetMotd);
registerMethod("Guild", "setMotd", LuaScriptInterface::luaGuildSetMotd);
// Group
registerClass("Group", "", LuaScriptInterface::luaGroupCreate);
registerMetaMethod("Group", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Group", "getId", LuaScriptInterface::luaGroupGetId);
registerMethod("Group", "getName", LuaScriptInterface::luaGroupGetName);
registerMethod("Group", "getFlags", LuaScriptInterface::luaGroupGetFlags);
registerMethod("Group", "getAccess", LuaScriptInterface::luaGroupGetAccess);
registerMethod("Group", "getMaxDepotItems", LuaScriptInterface::luaGroupGetMaxDepotItems);
registerMethod("Group", "getMaxVipEntries", LuaScriptInterface::luaGroupGetMaxVipEntries);
registerMethod("Group", "hasFlag", LuaScriptInterface::luaGroupHasFlag);
// Vocation
registerClass("Vocation", "", LuaScriptInterface::luaVocationCreate);
registerMetaMethod("Vocation", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Vocation", "getId", LuaScriptInterface::luaVocationGetId);
registerMethod("Vocation", "getClientId", LuaScriptInterface::luaVocationGetClientId);
registerMethod("Vocation", "getName", LuaScriptInterface::luaVocationGetName);
registerMethod("Vocation", "getDescription", LuaScriptInterface::luaVocationGetDescription);
registerMethod("Vocation", "getRequiredSkillTries", LuaScriptInterface::luaVocationGetRequiredSkillTries);
registerMethod("Vocation", "getRequiredManaSpent", LuaScriptInterface::luaVocationGetRequiredManaSpent);
registerMethod("Vocation", "getCapacityGain", LuaScriptInterface::luaVocationGetCapacityGain);
registerMethod("Vocation", "getHealthGain", LuaScriptInterface::luaVocationGetHealthGain);
registerMethod("Vocation", "getHealthGainTicks", LuaScriptInterface::luaVocationGetHealthGainTicks);
registerMethod("Vocation", "getHealthGainAmount", LuaScriptInterface::luaVocationGetHealthGainAmount);
registerMethod("Vocation", "getManaGain", LuaScriptInterface::luaVocationGetManaGain);
registerMethod("Vocation", "getManaGainTicks", LuaScriptInterface::luaVocationGetManaGainTicks);
registerMethod("Vocation", "getManaGainAmount", LuaScriptInterface::luaVocationGetManaGainAmount);
registerMethod("Vocation", "getMaxSoul", LuaScriptInterface::luaVocationGetMaxSoul);
registerMethod("Vocation", "getSoulGainTicks", LuaScriptInterface::luaVocationGetSoulGainTicks);
registerMethod("Vocation", "getAttackSpeed", LuaScriptInterface::luaVocationGetAttackSpeed);
registerMethod("Vocation", "getBaseSpeed", LuaScriptInterface::luaVocationGetBaseSpeed);
registerMethod("Vocation", "getDemotion", LuaScriptInterface::luaVocationGetDemotion);
registerMethod("Vocation", "getPromotion", LuaScriptInterface::luaVocationGetPromotion);
// Town
registerClass("Town", "", LuaScriptInterface::luaTownCreate);
registerMetaMethod("Town", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Town", "getId", LuaScriptInterface::luaTownGetId);
registerMethod("Town", "getName", LuaScriptInterface::luaTownGetName);
registerMethod("Town", "getTemplePosition", LuaScriptInterface::luaTownGetTemplePosition);
// House
registerClass("House", "", LuaScriptInterface::luaHouseCreate);
registerMetaMethod("House", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("House", "getId", LuaScriptInterface::luaHouseGetId);
registerMethod("House", "getName", LuaScriptInterface::luaHouseGetName);
registerMethod("House", "getTown", LuaScriptInterface::luaHouseGetTown);
registerMethod("House", "getExitPosition", LuaScriptInterface::luaHouseGetExitPosition);
registerMethod("House", "getRent", LuaScriptInterface::luaHouseGetRent);
registerMethod("House", "getOwnerGuid", LuaScriptInterface::luaHouseGetOwnerGuid);
registerMethod("House", "setOwnerGuid", LuaScriptInterface::luaHouseSetOwnerGuid);
registerMethod("House", "startTrade", LuaScriptInterface::luaHouseStartTrade);
registerMethod("House", "getBeds", LuaScriptInterface::luaHouseGetBeds);
registerMethod("House", "getBedCount", LuaScriptInterface::luaHouseGetBedCount);
registerMethod("House", "getDoors", LuaScriptInterface::luaHouseGetDoors);
registerMethod("House", "getDoorCount", LuaScriptInterface::luaHouseGetDoorCount);
registerMethod("House", "getDoorIdByPosition", LuaScriptInterface::luaHouseGetDoorIdByPosition);
registerMethod("House", "getTiles", LuaScriptInterface::luaHouseGetTiles);
registerMethod("House", "getTileCount", LuaScriptInterface::luaHouseGetTileCount);
registerMethod("House", "canEditAccessList", LuaScriptInterface::luaHouseCanEditAccessList);
registerMethod("House", "getAccessList", LuaScriptInterface::luaHouseGetAccessList);
registerMethod("House", "setAccessList", LuaScriptInterface::luaHouseSetAccessList);
registerMethod("House", "kickPlayer", LuaScriptInterface::luaHouseKickPlayer);
// ItemType
registerClass("ItemType", "", LuaScriptInterface::luaItemTypeCreate);
registerMetaMethod("ItemType", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("ItemType", "isCorpse", LuaScriptInterface::luaItemTypeIsCorpse);
registerMethod("ItemType", "isDoor", LuaScriptInterface::luaItemTypeIsDoor);
registerMethod("ItemType", "isContainer", LuaScriptInterface::luaItemTypeIsContainer);
registerMethod("ItemType", "isFluidContainer", LuaScriptInterface::luaItemTypeIsFluidContainer);
registerMethod("ItemType", "isMovable", LuaScriptInterface::luaItemTypeIsMovable);
registerMethod("ItemType", "isRune", LuaScriptInterface::luaItemTypeIsRune);
registerMethod("ItemType", "isStackable", LuaScriptInterface::luaItemTypeIsStackable);
registerMethod("ItemType", "isReadable", LuaScriptInterface::luaItemTypeIsReadable);
registerMethod("ItemType", "isWritable", LuaScriptInterface::luaItemTypeIsWritable);
registerMethod("ItemType", "isBlocking", LuaScriptInterface::luaItemTypeIsBlocking);
registerMethod("ItemType", "isGroundTile", LuaScriptInterface::luaItemTypeIsGroundTile);
registerMethod("ItemType", "isMagicField", LuaScriptInterface::luaItemTypeIsMagicField);
registerMethod("ItemType", "isUseable", LuaScriptInterface::luaItemTypeIsUseable);
registerMethod("ItemType", "isPickupable", LuaScriptInterface::luaItemTypeIsPickupable);
registerMethod("ItemType", "getType", LuaScriptInterface::luaItemTypeGetType);
registerMethod("ItemType", "getId", LuaScriptInterface::luaItemTypeGetId);
registerMethod("ItemType", "getClientId", LuaScriptInterface::luaItemTypeGetClientId);
registerMethod("ItemType", "getName", LuaScriptInterface::luaItemTypeGetName);
registerMethod("ItemType", "getPluralName", LuaScriptInterface::luaItemTypeGetPluralName);
registerMethod("ItemType", "getArticle", LuaScriptInterface::luaItemTypeGetArticle);
registerMethod("ItemType", "getDescription", LuaScriptInterface::luaItemTypeGetDescription);
registerMethod("ItemType", "getSlotPosition", LuaScriptInterface::luaItemTypeGetSlotPosition);
registerMethod("ItemType", "getCharges", LuaScriptInterface::luaItemTypeGetCharges);
registerMethod("ItemType", "getFluidSource", LuaScriptInterface::luaItemTypeGetFluidSource);
registerMethod("ItemType", "getCapacity", LuaScriptInterface::luaItemTypeGetCapacity);
registerMethod("ItemType", "getWeight", LuaScriptInterface::luaItemTypeGetWeight);
registerMethod("ItemType", "getHitChance", LuaScriptInterface::luaItemTypeGetHitChance);
registerMethod("ItemType", "getShootRange", LuaScriptInterface::luaItemTypeGetShootRange);
registerMethod("ItemType", "getAttack", LuaScriptInterface::luaItemTypeGetAttack);
registerMethod("ItemType", "getDefense", LuaScriptInterface::luaItemTypeGetDefense);
registerMethod("ItemType", "getExtraDefense", LuaScriptInterface::luaItemTypeGetExtraDefense);
registerMethod("ItemType", "getArmor", LuaScriptInterface::luaItemTypeGetArmor);
registerMethod("ItemType", "getWeaponType", LuaScriptInterface::luaItemTypeGetWeaponType);
registerMethod("ItemType", "getElementType", LuaScriptInterface::luaItemTypeGetElementType);
registerMethod("ItemType", "getElementDamage", LuaScriptInterface::luaItemTypeGetElementDamage);
registerMethod("ItemType", "getTransformEquipId", LuaScriptInterface::luaItemTypeGetTransformEquipId);
registerMethod("ItemType", "getTransformDeEquipId", LuaScriptInterface::luaItemTypeGetTransformDeEquipId);
registerMethod("ItemType", "getDestroyId", LuaScriptInterface::luaItemTypeGetDestroyId);
registerMethod("ItemType", "getDecayId", LuaScriptInterface::luaItemTypeGetDecayId);
registerMethod("ItemType", "getRequiredLevel", LuaScriptInterface::luaItemTypeGetRequiredLevel);
registerMethod("ItemType", "getAmmoType", LuaScriptInterface::luaItemTypeGetAmmoType);
registerMethod("ItemType", "getCorpseType", LuaScriptInterface::luaItemTypeGetCorpseType);
registerMethod("ItemType", "hasSubType", LuaScriptInterface::luaItemTypeHasSubType);
// Combat
registerClass("Combat", "", LuaScriptInterface::luaCombatCreate);
registerMetaMethod("Combat", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Combat", "setParameter", LuaScriptInterface::luaCombatSetParameter);
registerMethod("Combat", "setFormula", LuaScriptInterface::luaCombatSetFormula);
registerMethod("Combat", "setArea", LuaScriptInterface::luaCombatSetArea);
registerMethod("Combat", "addCondition", LuaScriptInterface::luaCombatAddCondition);
registerMethod("Combat", "setCallback", LuaScriptInterface::luaCombatSetCallback);
registerMethod("Combat", "setOrigin", LuaScriptInterface::luaCombatSetOrigin);
registerMethod("Combat", "execute", LuaScriptInterface::luaCombatExecute);
// Condition
registerClass("Condition", "", LuaScriptInterface::luaConditionCreate);
registerMetaMethod("Condition", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMetaMethod("Condition", "__gc", LuaScriptInterface::luaConditionDelete);
registerMethod("Condition", "delete", LuaScriptInterface::luaConditionDelete);
registerMethod("Condition", "getId", LuaScriptInterface::luaConditionGetId);
registerMethod("Condition", "getSubId", LuaScriptInterface::luaConditionGetSubId);
registerMethod("Condition", "getType", LuaScriptInterface::luaConditionGetType);
registerMethod("Condition", "getIcons", LuaScriptInterface::luaConditionGetIcons);
registerMethod("Condition", "getEndTime", LuaScriptInterface::luaConditionGetEndTime);
registerMethod("Condition", "clone", LuaScriptInterface::luaConditionClone);
registerMethod("Condition", "getTicks", LuaScriptInterface::luaConditionGetTicks);
registerMethod("Condition", "setTicks", LuaScriptInterface::luaConditionSetTicks);
registerMethod("Condition", "setParameter", LuaScriptInterface::luaConditionSetParameter);
registerMethod("Condition", "setFormula", LuaScriptInterface::luaConditionSetFormula);
registerMethod("Condition", "setOutfit", LuaScriptInterface::luaConditionSetOutfit);
registerMethod("Condition", "addDamage", LuaScriptInterface::luaConditionAddDamage);
// MonsterType
registerClass("MonsterType", "", LuaScriptInterface::luaMonsterTypeCreate);
registerMetaMethod("MonsterType", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("MonsterType", "isAttackable", LuaScriptInterface::luaMonsterTypeIsAttackable);
registerMethod("MonsterType", "isConvinceable", LuaScriptInterface::luaMonsterTypeIsConvinceable);
registerMethod("MonsterType", "isSummonable", LuaScriptInterface::luaMonsterTypeIsSummonable);
registerMethod("MonsterType", "isIllusionable", LuaScriptInterface::luaMonsterTypeIsIllusionable);
registerMethod("MonsterType", "isHostile", LuaScriptInterface::luaMonsterTypeIsHostile);
registerMethod("MonsterType", "isPushable", LuaScriptInterface::luaMonsterTypeIsPushable);
registerMethod("MonsterType", "isHealthShown", LuaScriptInterface::luaMonsterTypeIsHealthShown);
registerMethod("MonsterType", "canPushItems", LuaScriptInterface::luaMonsterTypeCanPushItems);
registerMethod("MonsterType", "canPushCreatures", LuaScriptInterface::luaMonsterTypeCanPushCreatures);
registerMethod("MonsterType", "getName", LuaScriptInterface::luaMonsterTypeGetName);
registerMethod("MonsterType", "getNameDescription", LuaScriptInterface::luaMonsterTypeGetNameDescription);
registerMethod("MonsterType", "getHealth", LuaScriptInterface::luaMonsterTypeGetHealth);
registerMethod("MonsterType", "getMaxHealth", LuaScriptInterface::luaMonsterTypeGetMaxHealth);
registerMethod("MonsterType", "getRunHealth", LuaScriptInterface::luaMonsterTypeGetRunHealth);
registerMethod("MonsterType", "getExperience", LuaScriptInterface::luaMonsterTypeGetExperience);
registerMethod("MonsterType", "getCombatImmunities", LuaScriptInterface::luaMonsterTypeGetCombatImmunities);
registerMethod("MonsterType", "getConditionImmunities", LuaScriptInterface::luaMonsterTypeGetConditionImmunities);
registerMethod("MonsterType", "getAttackList", LuaScriptInterface::luaMonsterTypeGetAttackList);
registerMethod("MonsterType", "getDefenseList", LuaScriptInterface::luaMonsterTypeGetDefenseList);
registerMethod("MonsterType", "getElementList", LuaScriptInterface::luaMonsterTypeGetElementList);
registerMethod("MonsterType", "getVoices", LuaScriptInterface::luaMonsterTypeGetVoices);
registerMethod("MonsterType", "getLoot", LuaScriptInterface::luaMonsterTypeGetLoot);
registerMethod("MonsterType", "getCreatureEvents", LuaScriptInterface::luaMonsterTypeGetCreatureEvents);
registerMethod("MonsterType", "getSummonList", LuaScriptInterface::luaMonsterTypeGetSummonList);
registerMethod("MonsterType", "getMaxSummons", LuaScriptInterface::luaMonsterTypeGetMaxSummons);
registerMethod("MonsterType", "getArmor", LuaScriptInterface::luaMonsterTypeGetArmor);
registerMethod("MonsterType", "getDefense", LuaScriptInterface::luaMonsterTypeGetDefense);
registerMethod("MonsterType", "getOutfit", LuaScriptInterface::luaMonsterTypeGetOutfit);
registerMethod("MonsterType", "getRace", LuaScriptInterface::luaMonsterTypeGetRace);
registerMethod("MonsterType", "getCorpseId", LuaScriptInterface::luaMonsterTypeGetCorpseId);
registerMethod("MonsterType", "getManaCost", LuaScriptInterface::luaMonsterTypeGetManaCost);
registerMethod("MonsterType", "getBaseSpeed", LuaScriptInterface::luaMonsterTypeGetBaseSpeed);
registerMethod("MonsterType", "getLight", LuaScriptInterface::luaMonsterTypeGetLight);
registerMethod("MonsterType", "getStaticAttackChance", LuaScriptInterface::luaMonsterTypeGetStaticAttackChance);
registerMethod("MonsterType", "getTargetDistance", LuaScriptInterface::luaMonsterTypeGetTargetDistance);
registerMethod("MonsterType", "getYellChance", LuaScriptInterface::luaMonsterTypeGetYellChance);
registerMethod("MonsterType", "getYellSpeedTicks", LuaScriptInterface::luaMonsterTypeGetYellSpeedTicks);
registerMethod("MonsterType", "getChangeTargetChance", LuaScriptInterface::luaMonsterTypeGetChangeTargetChance);
registerMethod("MonsterType", "getChangeTargetSpeed", LuaScriptInterface::luaMonsterTypeGetChangeTargetSpeed);
// Party
registerClass("Party", "", nullptr);
registerMetaMethod("Party", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Party", "disband", LuaScriptInterface::luaPartyDisband);
registerMethod("Party", "getLeader", LuaScriptInterface::luaPartyGetLeader);
registerMethod("Party", "setLeader", LuaScriptInterface::luaPartySetLeader);
registerMethod("Party", "getMembers", LuaScriptInterface::luaPartyGetMembers);
registerMethod("Party", "getMemberCount", LuaScriptInterface::luaPartyGetMemberCount);
registerMethod("Party", "getInvitees", LuaScriptInterface::luaPartyGetInvitees);
registerMethod("Party", "getInviteeCount", LuaScriptInterface::luaPartyGetInviteeCount);
registerMethod("Party", "addInvite", LuaScriptInterface::luaPartyAddInvite);
registerMethod("Party", "removeInvite", LuaScriptInterface::luaPartyRemoveInvite);
registerMethod("Party", "addMember", LuaScriptInterface::luaPartyAddMember);
registerMethod("Party", "removeMember", LuaScriptInterface::luaPartyRemoveMember);
registerMethod("Party", "isSharedExperienceActive", LuaScriptInterface::luaPartyIsSharedExperienceActive);
registerMethod("Party", "isSharedExperienceEnabled", LuaScriptInterface::luaPartyIsSharedExperienceEnabled);
registerMethod("Party", "shareExperience", LuaScriptInterface::luaPartyShareExperience);
registerMethod("Party", "setSharedExperience", LuaScriptInterface::luaPartySetSharedExperience);
// Spells
registerClass("Spell", "", LuaScriptInterface::luaSpellCreate);
registerMetaMethod("Spell", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Spell", "getManaCost", LuaScriptInterface::luaSpellGetManaCost);
registerMethod("Spell", "getSoulCost", LuaScriptInterface::luaSpellGetSoulCost);
registerMethod("Spell", "isPremium", LuaScriptInterface::luaSpellIsPremium);
registerMethod("Spell", "isLearnable", LuaScriptInterface::luaSpellIsLearnable);
}
#undef registerEnum
#undef registerEnumIn
void LuaScriptInterface::registerClass(const std::string& className, const std::string& baseClass, lua_CFunction newFunction/* = nullptr*/)
{
// className = {}
lua_newtable(luaState);
lua_pushvalue(luaState, -1);
lua_setglobal(luaState, className.c_str());
int methods = lua_gettop(luaState);
// methodsTable = {}
lua_newtable(luaState);
int methodsTable = lua_gettop(luaState);
if (newFunction) {
// className.__call = newFunction
lua_pushcfunction(luaState, newFunction);
lua_setfield(luaState, methodsTable, "__call");
}
uint32_t parents = 0;
if (!baseClass.empty()) {
lua_getglobal(luaState, baseClass.c_str());
lua_rawgeti(luaState, -1, 'p');
parents = getNumber<uint32_t>(luaState, -1) + 1;
lua_pop(luaState, 1);
lua_setfield(luaState, methodsTable, "__index");
}
// setmetatable(className, methodsTable)
lua_setmetatable(luaState, methods);
// className.metatable = {}
luaL_newmetatable(luaState, className.c_str());
int metatable = lua_gettop(luaState);
// className.metatable.__metatable = className
lua_pushvalue(luaState, methods);
lua_setfield(luaState, metatable, "__metatable");
// className.metatable.__index = className
lua_pushvalue(luaState, methods);
lua_setfield(luaState, metatable, "__index");
// className.metatable['h'] = hash
lua_pushnumber(luaState, std::hash<std::string>()(className));
lua_rawseti(luaState, metatable, 'h');
// className.metatable['p'] = parents
lua_pushnumber(luaState, parents);
lua_rawseti(luaState, metatable, 'p');
// className.metatable['t'] = type
if (className == "Item") {
lua_pushnumber(luaState, LuaData_Item);
} else if (className == "Container") {
lua_pushnumber(luaState, LuaData_Container);
} else if (className == "Teleport") {
lua_pushnumber(luaState, LuaData_Teleport);
} else if (className == "Player") {
lua_pushnumber(luaState, LuaData_Player);
} else if (className == "Monster") {
lua_pushnumber(luaState, LuaData_Monster);
} else if (className == "Npc") {
lua_pushnumber(luaState, LuaData_Npc);
} else if (className == "Tile") {
lua_pushnumber(luaState, LuaData_Tile);
} else {
lua_pushnumber(luaState, LuaData_Unknown);
}
lua_rawseti(luaState, metatable, 't');
// pop className, className.metatable
lua_pop(luaState, 2);
}
void LuaScriptInterface::registerTable(const std::string& tableName)
{
// _G[tableName] = {}
lua_newtable(luaState);
lua_setglobal(luaState, tableName.c_str());
}
void LuaScriptInterface::registerMethod(const std::string& globalName, const std::string& methodName, lua_CFunction func)
{
// globalName.methodName = func
lua_getglobal(luaState, globalName.c_str());
lua_pushcfunction(luaState, func);
lua_setfield(luaState, -2, methodName.c_str());
// pop globalName
lua_pop(luaState, 1);
}
void LuaScriptInterface::registerMetaMethod(const std::string& className, const std::string& methodName, lua_CFunction func)
{
// className.metatable.methodName = func
luaL_getmetatable(luaState, className.c_str());
lua_pushcfunction(luaState, func);
lua_setfield(luaState, -2, methodName.c_str());
// pop className.metatable
lua_pop(luaState, 1);
}
void LuaScriptInterface::registerGlobalMethod(const std::string& functionName, lua_CFunction func)
{
// _G[functionName] = func
lua_pushcfunction(luaState, func);
lua_setglobal(luaState, functionName.c_str());
}
void LuaScriptInterface::registerVariable(const std::string& tableName, const std::string& name, lua_Number value)
{
// tableName.name = value
lua_getglobal(luaState, tableName.c_str());
setField(luaState, name.c_str(), value);
// pop tableName
lua_pop(luaState, 1);
}
void LuaScriptInterface::registerGlobalVariable(const std::string& name, lua_Number value)
{
// _G[name] = value
lua_pushnumber(luaState, value);
lua_setglobal(luaState, name.c_str());
}
void LuaScriptInterface::registerGlobalBoolean(const std::string& name, bool value)
{
// _G[name] = value
pushBoolean(luaState, value);
lua_setglobal(luaState, name.c_str());
}
int LuaScriptInterface::luaDoPlayerAddItem(lua_State* L)
{
//doPlayerAddItem(cid, itemid, <optional: default: 1> count/subtype, <optional: default: 1> canDropOnMap)
//doPlayerAddItem(cid, itemid, <optional: default: 1> count, <optional: default: 1> canDropOnMap, <optional: default: 1>subtype)
Player* player = getPlayer(L, 1);
if (!player) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint16_t itemId = getNumber<uint16_t>(L, 2);
int32_t count = getNumber<int32_t>(L, 3, 1);
bool canDropOnMap = getBoolean(L, 4, true);
uint16_t subType = getNumber<uint16_t>(L, 5, 1);
const ItemType& it = Item::items[itemId];
int32_t itemCount;
auto parameters = lua_gettop(L);
if (parameters > 4) {
//subtype already supplied, count then is the amount
itemCount = std::max<int32_t>(1, count);
} else if (it.hasSubType()) {
if (it.stackable) {
itemCount = static_cast<int32_t>(std::ceil(static_cast<float>(count) / 100));
} else {
itemCount = 1;
}
subType = count;
} else {
itemCount = std::max<int32_t>(1, count);
}
while (itemCount > 0) {
uint16_t stackCount = subType;
if (it.stackable && stackCount > 100) {
stackCount = 100;
}
Item* newItem = Item::CreateItem(itemId, stackCount);
if (!newItem) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (it.stackable) {
subType -= stackCount;
}
ReturnValue ret = g_game.internalPlayerAddItem(player, newItem, canDropOnMap);
if (ret != RETURNVALUE_NOERROR) {
delete newItem;
pushBoolean(L, false);
return 1;
}
if (--itemCount == 0) {
if (newItem->getParent()) {
uint32_t uid = getScriptEnv()->addThing(newItem);
lua_pushnumber(L, uid);
return 1;
} else {
//stackable item stacked with existing object, newItem will be released
pushBoolean(L, false);
return 1;
}
}
}
pushBoolean(L, false);
return 1;
}
int LuaScriptInterface::luaDoTileAddItemEx(lua_State* L)
{
//doTileAddItemEx(pos, uid)
const Position& pos = getPosition(L, 1);
Tile* tile = g_game.map.getTile(pos);
if (!tile) {
std::ostringstream ss;
ss << pos << ' ' << getErrorDesc(LUA_ERROR_TILE_NOT_FOUND);
reportErrorFunc(ss.str());
pushBoolean(L, false);
return 1;
}
uint32_t uid = getNumber<uint32_t>(L, 2);
Item* item = getScriptEnv()->getItemByUID(uid);
if (!item) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (item->getParent() != VirtualCylinder::virtualCylinder) {
reportErrorFunc("Item already has a parent");
pushBoolean(L, false);
return 1;
}
lua_pushnumber(L, g_game.internalAddItem(tile, item));
return 1;
}
int LuaScriptInterface::luaDebugPrint(lua_State* L)
{
//debugPrint(text)
reportErrorFunc(getString(L, -1));
return 0;
}
int LuaScriptInterface::luaGetWorldTime(lua_State* L)
{
//getWorldTime()
uint32_t time = g_game.getLightHour();
lua_pushnumber(L, time);
return 1;
}
int LuaScriptInterface::luaGetWorldLight(lua_State* L)
{
//getWorldLight()
LightInfo lightInfo = g_game.getWorldLightInfo();
lua_pushnumber(L, lightInfo.level);
lua_pushnumber(L, lightInfo.color);
return 2;
}
int LuaScriptInterface::luaGetWorldUpTime(lua_State* L)
{
//getWorldUpTime()
uint64_t uptime = (OTSYS_TIME() - ProtocolStatus::start) / 1000;
lua_pushnumber(L, uptime);
return 1;
}
bool LuaScriptInterface::getArea(lua_State* L, std::list<uint32_t>& list, uint32_t& rows)
{
lua_pushnil(L);
for (rows = 0; lua_next(L, -2) != 0; ++rows) {
if (!isTable(L, -1)) {
return false;
}
lua_pushnil(L);
while (lua_next(L, -2) != 0) {
if (!isNumber(L, -1)) {
return false;
}
list.push_back(getNumber<uint32_t>(L, -1));
lua_pop(L, 1);
}
lua_pop(L, 1);
}
lua_pop(L, 1);
return (rows != 0);
}
int LuaScriptInterface::luaCreateCombatArea(lua_State* L)
{
//createCombatArea( {area}, <optional> {extArea} )
ScriptEnvironment* env = getScriptEnv();
if (env->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
uint32_t areaId = g_luaEnvironment.createAreaObject(env->getScriptInterface());
AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
int parameters = lua_gettop(L);
if (parameters >= 2) {
uint32_t rowsExtArea;
std::list<uint32_t> listExtArea;
if (!isTable(L, 2) || !getArea(L, listExtArea, rowsExtArea)) {
reportErrorFunc("Invalid extended area table.");
pushBoolean(L, false);
return 1;
}
area->setupExtArea(listExtArea, rowsExtArea);
}
uint32_t rowsArea = 0;
std::list<uint32_t> listArea;
if (!isTable(L, 1) || !getArea(L, listArea, rowsArea)) {
reportErrorFunc("Invalid area table.");
pushBoolean(L, false);
return 1;
}
area->setupArea(listArea, rowsArea);
lua_pushnumber(L, areaId);
return 1;
}
int LuaScriptInterface::luaDoAreaCombatHealth(lua_State* L)
{
//doAreaCombatHealth(cid, type, pos, area, min, max, effect[, origin = ORIGIN_SPELL])
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 4);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (area || areaId == 0) {
CombatType_t combatType = getNumber<CombatType_t>(L, 2);
CombatParams params;
params.combatType = combatType;
params.impactEffect = getNumber<uint8_t>(L, 7);
CombatDamage damage;
damage.origin = getNumber<CombatOrigin>(L, 8, ORIGIN_SPELL);
damage.primary.type = combatType;
damage.primary.value = normal_random(getNumber<int32_t>(L, 6), getNumber<int32_t>(L, 5));
Combat::doCombatHealth(creature, getPosition(L, 3), area, damage, params);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoTargetCombatHealth(lua_State* L)
{
//doTargetCombatHealth(cid, target, type, min, max, effect[, origin = ORIGIN_SPELL])
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CombatType_t combatType = getNumber<CombatType_t>(L, 3);
CombatParams params;
params.combatType = combatType;
params.impactEffect = getNumber<uint8_t>(L, 6);
CombatDamage damage;
damage.origin = getNumber<CombatOrigin>(L, 7, ORIGIN_SPELL);
damage.primary.type = combatType;
damage.primary.value = normal_random(getNumber<int32_t>(L, 4), getNumber<int32_t>(L, 5));
Combat::doCombatHealth(creature, target, damage, params);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoAreaCombatMana(lua_State* L)
{
//doAreaCombatMana(cid, pos, area, min, max, effect[, origin = ORIGIN_SPELL])
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 3);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (area || areaId == 0) {
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 6);
CombatDamage damage;
damage.origin = getNumber<CombatOrigin>(L, 7, ORIGIN_SPELL);
damage.primary.type = COMBAT_MANADRAIN;
damage.primary.value = normal_random(getNumber<int32_t>(L, 4), getNumber<int32_t>(L, 5));
Position pos = getPosition(L, 2);
Combat::doCombatMana(creature, pos, area, damage, params);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoTargetCombatMana(lua_State* L)
{
//doTargetCombatMana(cid, target, min, max, effect[, origin = ORIGIN_SPELL)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 5);
CombatDamage damage;
damage.origin = getNumber<CombatOrigin>(L, 6, ORIGIN_SPELL);
damage.primary.type = COMBAT_MANADRAIN;
damage.primary.value = normal_random(getNumber<int32_t>(L, 3), getNumber<int32_t>(L, 4));
Combat::doCombatMana(creature, target, damage, params);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoAreaCombatCondition(lua_State* L)
{
//doAreaCombatCondition(cid, pos, area, condition, effect)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
const Condition* condition = getUserdata<Condition>(L, 4);
if (!condition) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 3);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (area || areaId == 0) {
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 5);
params.conditionList.emplace_front(condition->clone());
Combat::doCombatCondition(creature, getPosition(L, 2), area, params);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoTargetCombatCondition(lua_State* L)
{
//doTargetCombatCondition(cid, target, condition, effect)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
const Condition* condition = getUserdata<Condition>(L, 3);
if (!condition) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 4);
params.conditionList.emplace_front(condition->clone());
Combat::doCombatCondition(creature, target, params);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoAreaCombatDispel(lua_State* L)
{
//doAreaCombatDispel(cid, pos, area, type, effect)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 3);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (area || areaId == 0) {
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 5);
params.dispelType = getNumber<ConditionType_t>(L, 4);
Combat::doCombatDispel(creature, getPosition(L, 2), area, params);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoTargetCombatDispel(lua_State* L)
{
//doTargetCombatDispel(cid, target, type, effect)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CombatParams params;
params.dispelType = getNumber<ConditionType_t>(L, 3);
params.impactEffect = getNumber<uint8_t>(L, 4);
Combat::doCombatDispel(creature, target, params);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoChallengeCreature(lua_State* L)
{
//doChallengeCreature(cid, target)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
target->challengeCreature(creature);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaIsValidUID(lua_State* L)
{
//isValidUID(uid)
pushBoolean(L, getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, -1)) != nullptr);
return 1;
}
int LuaScriptInterface::luaIsDepot(lua_State* L)
{
//isDepot(uid)
Container* container = getScriptEnv()->getContainerByUID(getNumber<uint32_t>(L, -1));
pushBoolean(L, container && container->getDepotLocker());
return 1;
}
int LuaScriptInterface::luaIsMoveable(lua_State* L)
{
//isMoveable(uid)
//isMovable(uid)
Thing* thing = getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, -1));
pushBoolean(L, thing && thing->isPushable());
return 1;
}
int LuaScriptInterface::luaDoAddContainerItem(lua_State* L)
{
//doAddContainerItem(uid, itemid, <optional> count/subtype)
uint32_t uid = getNumber<uint32_t>(L, 1);
ScriptEnvironment* env = getScriptEnv();
Container* container = env->getContainerByUID(uid);
if (!container) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONTAINER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint16_t itemId = getNumber<uint16_t>(L, 2);
const ItemType& it = Item::items[itemId];
int32_t itemCount = 1;
int32_t subType = 1;
uint32_t count = getNumber<uint32_t>(L, 3, 1);
if (it.hasSubType()) {
if (it.stackable) {
itemCount = static_cast<int32_t>(std::ceil(static_cast<float>(count) / 100));
}
subType = count;
} else {
itemCount = std::max<int32_t>(1, count);
}
while (itemCount > 0) {
int32_t stackCount = std::min<int32_t>(100, subType);
Item* newItem = Item::CreateItem(itemId, stackCount);
if (!newItem) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (it.stackable) {
subType -= stackCount;
}
ReturnValue ret = g_game.internalAddItem(container, newItem);
if (ret != RETURNVALUE_NOERROR) {
delete newItem;
pushBoolean(L, false);
return 1;
}
if (--itemCount == 0) {
if (newItem->getParent()) {
lua_pushnumber(L, env->addThing(newItem));
} else {
//stackable item stacked with existing object, newItem will be released
pushBoolean(L, false);
}
return 1;
}
}
pushBoolean(L, false);
return 1;
}
int LuaScriptInterface::luaGetDepotId(lua_State* L)
{
//getDepotId(uid)
uint32_t uid = getNumber<uint32_t>(L, -1);
Container* container = getScriptEnv()->getContainerByUID(uid);
if (!container) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONTAINER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
DepotLocker* depotLocker = container->getDepotLocker();
if (!depotLocker) {
reportErrorFunc("Depot not found");
pushBoolean(L, false);
return 1;
}
lua_pushnumber(L, depotLocker->getDepotId());
return 1;
}
int LuaScriptInterface::luaDoSetCreatureLight(lua_State* L)
{
//doSetCreatureLight(cid, lightLevel, lightColor, time)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint16_t level = getNumber<uint16_t>(L, 2);
uint16_t color = getNumber<uint16_t>(L, 3);
uint32_t time = getNumber<uint32_t>(L, 4);
Condition* condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_LIGHT, time, level | (color << 8));
creature->addCondition(condition);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaAddEvent(lua_State* L)
{
//addEvent(callback, delay, ...)
lua_State* globalState = g_luaEnvironment.getLuaState();
if (!globalState) {
reportErrorFunc("No valid script interface!");
pushBoolean(L, false);
return 1;
} else if (globalState != L) {
lua_xmove(L, globalState, lua_gettop(L));
}
int parameters = lua_gettop(globalState);
if (!isFunction(globalState, -parameters)) { //-parameters means the first parameter from left to right
reportErrorFunc("callback parameter should be a function.");
pushBoolean(L, false);
return 1;
}
if (g_config.getBoolean(ConfigManager::WARN_UNSAFE_SCRIPTS) || g_config.getBoolean(ConfigManager::CONVERT_UNSAFE_SCRIPTS)) {
std::vector<std::pair<int32_t, LuaDataType>> indexes;
for (int i = 3; i <= parameters; ++i) {
if (lua_getmetatable(globalState, i) == 0) {
continue;
}
lua_rawgeti(L, -1, 't');
LuaDataType type = getNumber<LuaDataType>(L, -1);
if (type != LuaData_Unknown && type != LuaData_Tile) {
indexes.push_back({i, type});
}
lua_pop(globalState, 2);
}
if (!indexes.empty()) {
if (g_config.getBoolean(ConfigManager::WARN_UNSAFE_SCRIPTS)) {
bool plural = indexes.size() > 1;
std::string warningString = "Argument";
if (plural) {
warningString += 's';
}
for (const auto& entry : indexes) {
if (entry == indexes.front()) {
warningString += ' ';
} else if (entry == indexes.back()) {
warningString += " and ";
} else {
warningString += ", ";
}
warningString += '#';
warningString += std::to_string(entry.first);
}
if (plural) {
warningString += " are unsafe";
} else {
warningString += " is unsafe";
}
reportErrorFunc(warningString);
}
if (g_config.getBoolean(ConfigManager::CONVERT_UNSAFE_SCRIPTS)) {
for (const auto& entry : indexes) {
switch (entry.second) {
case LuaData_Item:
case LuaData_Container:
case LuaData_Teleport: {
lua_getglobal(globalState, "Item");
lua_getfield(globalState, -1, "getUniqueId");
break;
}
case LuaData_Player:
case LuaData_Monster:
case LuaData_Npc: {
lua_getglobal(globalState, "Creature");
lua_getfield(globalState, -1, "getId");
break;
}
default:
break;
}
lua_replace(globalState, -2);
lua_pushvalue(globalState, entry.first);
lua_call(globalState, 1, 1);
lua_replace(globalState, entry.first);
}
}
}
}
LuaTimerEventDesc eventDesc;
for (int i = 0; i < parameters - 2; ++i) { //-2 because addEvent needs at least two parameters
eventDesc.parameters.push_back(luaL_ref(globalState, LUA_REGISTRYINDEX));
}
uint32_t delay = std::max<uint32_t>(100, getNumber<uint32_t>(globalState, 2));
lua_pop(globalState, 1);
eventDesc.function = luaL_ref(globalState, LUA_REGISTRYINDEX);
eventDesc.scriptId = getScriptEnv()->getScriptId();
auto& lastTimerEventId = g_luaEnvironment.lastEventTimerId;
eventDesc.eventId = g_scheduler.addEvent(createSchedulerTask(
delay, std::bind(&LuaEnvironment::executeTimerEvent, &g_luaEnvironment, lastTimerEventId)
));
g_luaEnvironment.timerEvents.emplace(lastTimerEventId, std::move(eventDesc));
lua_pushnumber(L, lastTimerEventId++);
return 1;
}
int LuaScriptInterface::luaStopEvent(lua_State* L)
{
//stopEvent(eventid)
lua_State* globalState = g_luaEnvironment.getLuaState();
if (!globalState) {
reportErrorFunc("No valid script interface!");
pushBoolean(L, false);
return 1;
}
uint32_t eventId = getNumber<uint32_t>(L, 1);
auto& timerEvents = g_luaEnvironment.timerEvents;
auto it = timerEvents.find(eventId);
if (it == timerEvents.end()) {
pushBoolean(L, false);
return 1;
}
LuaTimerEventDesc timerEventDesc = std::move(it->second);
timerEvents.erase(it);
g_scheduler.stopEvent(timerEventDesc.eventId);
luaL_unref(globalState, LUA_REGISTRYINDEX, timerEventDesc.function);
for (auto parameter : timerEventDesc.parameters) {
luaL_unref(globalState, LUA_REGISTRYINDEX, parameter);
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaSaveServer(lua_State* L)
{
g_game.saveGameState();
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCleanMap(lua_State* L)
{
lua_pushnumber(L, g_game.map.clean());
return 1;
}
int LuaScriptInterface::luaIsInWar(lua_State* L)
{
//isInWar(cid, target)
Player* player = getPlayer(L, 1);
if (!player) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Player* targetPlayer = getPlayer(L, 2);
if (!targetPlayer) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
pushBoolean(L, player->isInWar(targetPlayer));
return 1;
}
int LuaScriptInterface::luaGetWaypointPositionByName(lua_State* L)
{
//getWaypointPositionByName(name)
auto& waypoints = g_game.map.waypoints;
auto it = waypoints.find(getString(L, -1));
if (it != waypoints.end()) {
pushPosition(L, it->second);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaSendChannelMessage(lua_State* L)
{
//sendChannelMessage(channelId, type, message)
uint32_t channelId = getNumber<uint32_t>(L, 1);
ChatChannel* channel = g_chat->getChannelById(channelId);
if (!channel) {
pushBoolean(L, false);
return 1;
}
SpeakClasses type = getNumber<SpeakClasses>(L, 2);
std::string message = getString(L, 3);
channel->sendToAll(message, type);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaSendGuildChannelMessage(lua_State* L)
{
//sendGuildChannelMessage(guildId, type, message)
uint32_t guildId = getNumber<uint32_t>(L, 1);
ChatChannel* channel = g_chat->getGuildChannelById(guildId);
if (!channel) {
pushBoolean(L, false);
return 1;
}
SpeakClasses type = getNumber<SpeakClasses>(L, 2);
std::string message = getString(L, 3);
channel->sendToAll(message, type);
pushBoolean(L, true);
return 1;
}
std::string LuaScriptInterface::escapeString(const std::string& string)
{
std::string s = string;
replaceString(s, "\\", "\\\\");
replaceString(s, "\"", "\\\"");
replaceString(s, "'", "\\'");
replaceString(s, "[[", "\\[[");
return s;
}
#ifndef LUAJIT_VERSION
const luaL_Reg LuaScriptInterface::luaBitReg[] = {
//{"tobit", LuaScriptInterface::luaBitToBit},
{"bnot", LuaScriptInterface::luaBitNot},
{"band", LuaScriptInterface::luaBitAnd},
{"bor", LuaScriptInterface::luaBitOr},
{"bxor", LuaScriptInterface::luaBitXor},
{"lshift", LuaScriptInterface::luaBitLeftShift},
{"rshift", LuaScriptInterface::luaBitRightShift},
//{"arshift", LuaScriptInterface::luaBitArithmeticalRightShift},
//{"rol", LuaScriptInterface::luaBitRotateLeft},
//{"ror", LuaScriptInterface::luaBitRotateRight},
//{"bswap", LuaScriptInterface::luaBitSwapEndian},
//{"tohex", LuaScriptInterface::luaBitToHex},
{nullptr, nullptr}
};
int LuaScriptInterface::luaBitNot(lua_State* L)
{
lua_pushnumber(L, ~getNumber<uint32_t>(L, -1));
return 1;
}
#define MULTIOP(name, op) \
int LuaScriptInterface::luaBit##name(lua_State* L) \
{ \
int n = lua_gettop(L); \
uint32_t w = getNumber<uint32_t>(L, -1); \
for (int i = 1; i < n; ++i) \
w op getNumber<uint32_t>(L, i); \
lua_pushnumber(L, w); \
return 1; \
}
MULTIOP(And, &= )
MULTIOP(Or, |= )
MULTIOP(Xor, ^= )
#define SHIFTOP(name, op) \
int LuaScriptInterface::luaBit##name(lua_State* L) \
{ \
uint32_t n1 = getNumber<uint32_t>(L, 1), n2 = getNumber<uint32_t>(L, 2); \
lua_pushnumber(L, (n1 op n2)); \
return 1; \
}
SHIFTOP(LeftShift, << )
SHIFTOP(RightShift, >> )
#endif
const luaL_Reg LuaScriptInterface::luaConfigManagerTable[] = {
{"getString", LuaScriptInterface::luaConfigManagerGetString},
{"getNumber", LuaScriptInterface::luaConfigManagerGetNumber},
{"getBoolean", LuaScriptInterface::luaConfigManagerGetBoolean},
{nullptr, nullptr}
};
int LuaScriptInterface::luaConfigManagerGetString(lua_State* L)
{
pushString(L, g_config.getString(getNumber<ConfigManager::string_config_t>(L, -1)));
return 1;
}
int LuaScriptInterface::luaConfigManagerGetNumber(lua_State* L)
{
lua_pushnumber(L, g_config.getNumber(getNumber<ConfigManager::integer_config_t>(L, -1)));
return 1;
}
int LuaScriptInterface::luaConfigManagerGetBoolean(lua_State* L)
{
pushBoolean(L, g_config.getBoolean(getNumber<ConfigManager::boolean_config_t>(L, -1)));
return 1;
}
const luaL_Reg LuaScriptInterface::luaDatabaseTable[] = {
{"query", LuaScriptInterface::luaDatabaseExecute},
{"asyncQuery", LuaScriptInterface::luaDatabaseAsyncExecute},
{"storeQuery", LuaScriptInterface::luaDatabaseStoreQuery},
{"asyncStoreQuery", LuaScriptInterface::luaDatabaseAsyncStoreQuery},
{"escapeString", LuaScriptInterface::luaDatabaseEscapeString},
{"escapeBlob", LuaScriptInterface::luaDatabaseEscapeBlob},
{"lastInsertId", LuaScriptInterface::luaDatabaseLastInsertId},
{"tableExists", LuaScriptInterface::luaDatabaseTableExists},
{nullptr, nullptr}
};
int LuaScriptInterface::luaDatabaseExecute(lua_State* L)
{
pushBoolean(L, Database::getInstance().executeQuery(getString(L, -1)));
return 1;
}
int LuaScriptInterface::luaDatabaseAsyncExecute(lua_State* L)
{
std::function<void(DBResult_ptr, bool)> callback;
if (lua_gettop(L) > 1) {
int32_t ref = luaL_ref(L, LUA_REGISTRYINDEX);
auto scriptId = getScriptEnv()->getScriptId();
callback = [ref, scriptId](DBResult_ptr, bool success) {
lua_State* luaState = g_luaEnvironment.getLuaState();
if (!luaState) {
return;
}
if (!LuaScriptInterface::reserveScriptEnv()) {
luaL_unref(luaState, LUA_REGISTRYINDEX, ref);
return;
}
lua_rawgeti(luaState, LUA_REGISTRYINDEX, ref);
pushBoolean(luaState, success);
auto env = getScriptEnv();
env->setScriptId(scriptId, &g_luaEnvironment);
g_luaEnvironment.callFunction(1);
luaL_unref(luaState, LUA_REGISTRYINDEX, ref);
};
}
g_databaseTasks.addTask(getString(L, -1), callback);
return 0;
}
int LuaScriptInterface::luaDatabaseStoreQuery(lua_State* L)
{
if (DBResult_ptr res = Database::getInstance().storeQuery(getString(L, -1))) {
lua_pushnumber(L, ScriptEnvironment::addResult(res));
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDatabaseAsyncStoreQuery(lua_State* L)
{
std::function<void(DBResult_ptr, bool)> callback;
if (lua_gettop(L) > 1) {
int32_t ref = luaL_ref(L, LUA_REGISTRYINDEX);
auto scriptId = getScriptEnv()->getScriptId();
callback = [ref, scriptId](DBResult_ptr result, bool) {
lua_State* luaState = g_luaEnvironment.getLuaState();
if (!luaState) {
return;
}
if (!LuaScriptInterface::reserveScriptEnv()) {
luaL_unref(luaState, LUA_REGISTRYINDEX, ref);
return;
}
lua_rawgeti(luaState, LUA_REGISTRYINDEX, ref);
if (result) {
lua_pushnumber(luaState, ScriptEnvironment::addResult(result));
} else {
pushBoolean(luaState, false);
}
auto env = getScriptEnv();
env->setScriptId(scriptId, &g_luaEnvironment);
g_luaEnvironment.callFunction(1);
luaL_unref(luaState, LUA_REGISTRYINDEX, ref);
};
}
g_databaseTasks.addTask(getString(L, -1), callback, true);
return 0;
}
int LuaScriptInterface::luaDatabaseEscapeString(lua_State* L)
{
pushString(L, Database::getInstance().escapeString(getString(L, -1)));
return 1;
}
int LuaScriptInterface::luaDatabaseEscapeBlob(lua_State* L)
{
uint32_t length = getNumber<uint32_t>(L, 2);
pushString(L, Database::getInstance().escapeBlob(getString(L, 1).c_str(), length));
return 1;
}
int LuaScriptInterface::luaDatabaseLastInsertId(lua_State* L)
{
lua_pushnumber(L, Database::getInstance().getLastInsertId());
return 1;
}
int LuaScriptInterface::luaDatabaseTableExists(lua_State* L)
{
pushBoolean(L, DatabaseManager::tableExists(getString(L, -1)));
return 1;
}
const luaL_Reg LuaScriptInterface::luaResultTable[] = {
{"getNumber", LuaScriptInterface::luaResultGetNumber},
{"getString", LuaScriptInterface::luaResultGetString},
{"getStream", LuaScriptInterface::luaResultGetStream},
{"next", LuaScriptInterface::luaResultNext},
{"free", LuaScriptInterface::luaResultFree},
{nullptr, nullptr}
};
int LuaScriptInterface::luaResultGetNumber(lua_State* L)
{
DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1));
if (!res) {
pushBoolean(L, false);
return 1;
}
const std::string& s = getString(L, 2);
lua_pushnumber(L, res->getNumber<int64_t>(s));
return 1;
}
int LuaScriptInterface::luaResultGetString(lua_State* L)
{
DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1));
if (!res) {
pushBoolean(L, false);
return 1;
}
const std::string& s = getString(L, 2);
pushString(L, res->getString(s));
return 1;
}
int LuaScriptInterface::luaResultGetStream(lua_State* L)
{
DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1));
if (!res) {
pushBoolean(L, false);
return 1;
}
unsigned long length;
const char* stream = res->getStream(getString(L, 2), length);
lua_pushlstring(L, stream, length);
lua_pushnumber(L, length);
return 2;
}
int LuaScriptInterface::luaResultNext(lua_State* L)
{
DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, -1));
if (!res) {
pushBoolean(L, false);
return 1;
}
pushBoolean(L, res->next());
return 1;
}
int LuaScriptInterface::luaResultFree(lua_State* L)
{
pushBoolean(L, ScriptEnvironment::removeResult(getNumber<uint32_t>(L, -1)));
return 1;
}
// Userdata
int LuaScriptInterface::luaUserdataCompare(lua_State* L)
{
// userdataA == userdataB
pushBoolean(L, getUserdata<void>(L, 1) == getUserdata<void>(L, 2));
return 1;
}
// _G
int LuaScriptInterface::luaIsType(lua_State* L)
{
// isType(derived, base)
lua_getmetatable(L, -2);
lua_getmetatable(L, -2);
lua_rawgeti(L, -2, 'p');
uint_fast8_t parentsB = getNumber<uint_fast8_t>(L, 1);
lua_rawgeti(L, -3, 'h');
size_t hashB = getNumber<size_t>(L, 1);
lua_rawgeti(L, -3, 'p');
uint_fast8_t parentsA = getNumber<uint_fast8_t>(L, 1);
for (uint_fast8_t i = parentsA; i < parentsB; ++i) {
lua_getfield(L, -3, "__index");
lua_replace(L, -4);
}
lua_rawgeti(L, -4, 'h');
size_t hashA = getNumber<size_t>(L, 1);
pushBoolean(L, hashA == hashB);
return 1;
}
int LuaScriptInterface::luaRawGetMetatable(lua_State* L)
{
// rawgetmetatable(metatableName)
luaL_getmetatable(L, getString(L, 1).c_str());
return 1;
}
// os
int LuaScriptInterface::luaSystemTime(lua_State* L)
{
// os.mtime()
lua_pushnumber(L, OTSYS_TIME());
return 1;
}
// table
int LuaScriptInterface::luaTableCreate(lua_State* L)
{
// table.create(arrayLength, keyLength)
lua_createtable(L, getNumber<int32_t>(L, 1), getNumber<int32_t>(L, 2));
return 1;
}
// Game
int LuaScriptInterface::luaGameGetSpectators(lua_State* L)
{
// Game.getSpectators(position[, multifloor = false[, onlyPlayer = false[, minRangeX = 0[, maxRangeX = 0[, minRangeY = 0[, maxRangeY = 0]]]]]])
const Position& position = getPosition(L, 1);
bool multifloor = getBoolean(L, 2, false);
bool onlyPlayers = getBoolean(L, 3, false);
int32_t minRangeX = getNumber<int32_t>(L, 4, 0);
int32_t maxRangeX = getNumber<int32_t>(L, 5, 0);
int32_t minRangeY = getNumber<int32_t>(L, 6, 0);
int32_t maxRangeY = getNumber<int32_t>(L, 7, 0);
SpectatorHashSet spectators;
g_game.map.getSpectators(spectators, position, multifloor, onlyPlayers, minRangeX, maxRangeX, minRangeY, maxRangeY);
lua_createtable(L, spectators.size(), 0);
int index = 0;
for (Creature* creature : spectators) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGameGetPlayers(lua_State* L)
{
// Game.getPlayers()
lua_createtable(L, g_game.getPlayersOnline(), 0);
int index = 0;
for (const auto& playerEntry : g_game.getPlayers()) {
pushUserdata<Player>(L, playerEntry.second);
setMetatable(L, -1, "Player");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGameLoadMap(lua_State* L)
{
// Game.loadMap(path)
const std::string& path = getString(L, 1);
g_dispatcher.addTask(createTask(std::bind(&Game::loadMap, &g_game, path)));
return 0;
}
int LuaScriptInterface::luaGameGetExperienceStage(lua_State* L)
{
// Game.getExperienceStage(level)
uint32_t level = getNumber<uint32_t>(L, 1);
lua_pushnumber(L, g_game.getExperienceStage(level));
return 1;
}
int LuaScriptInterface::luaGameGetMonsterCount(lua_State* L)
{
// Game.getMonsterCount()
lua_pushnumber(L, g_game.getMonstersOnline());
return 1;
}
int LuaScriptInterface::luaGameGetPlayerCount(lua_State* L)
{
// Game.getPlayerCount()
lua_pushnumber(L, g_game.getPlayersOnline());
return 1;
}
int LuaScriptInterface::luaGameGetNpcCount(lua_State* L)
{
// Game.getNpcCount()
lua_pushnumber(L, g_game.getNpcsOnline());
return 1;
}
int LuaScriptInterface::luaGameGetTowns(lua_State* L)
{
// Game.getTowns()
const auto& towns = g_game.map.towns.getTowns();
lua_createtable(L, towns.size(), 0);
int index = 0;
for (auto townEntry : towns) {
pushUserdata<Town>(L, townEntry.second);
setMetatable(L, -1, "Town");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGameGetHouses(lua_State* L)
{
// Game.getHouses()
const auto& houses = g_game.map.houses.getHouses();
lua_createtable(L, houses.size(), 0);
int index = 0;
for (auto houseEntry : houses) {
pushUserdata<House>(L, houseEntry.second);
setMetatable(L, -1, "House");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGameGetGameState(lua_State* L)
{
// Game.getGameState()
lua_pushnumber(L, g_game.getGameState());
return 1;
}
int LuaScriptInterface::luaGameSetGameState(lua_State* L)
{
// Game.setGameState(state)
GameState_t state = getNumber<GameState_t>(L, 1);
g_game.setGameState(state);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaGameGetWorldType(lua_State* L)
{
// Game.getWorldType()
lua_pushnumber(L, g_game.getWorldType());
return 1;
}
int LuaScriptInterface::luaGameSetWorldType(lua_State* L)
{
// Game.setWorldType(type)
WorldType_t type = getNumber<WorldType_t>(L, 1);
g_game.setWorldType(type);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaGameGetReturnMessage(lua_State* L)
{
// Game.getReturnMessage(value)
ReturnValue value = getNumber<ReturnValue>(L, 1);
pushString(L, getReturnMessage(value));
return 1;
}
int LuaScriptInterface::luaGameCreateItem(lua_State* L)
{
// Game.createItem(itemId[, count[, position]])
uint16_t count = getNumber<uint16_t>(L, 2, 1);
uint16_t id;
if (isNumber(L, 1)) {
id = getNumber<uint16_t>(L, 1);
} else {
id = Item::items.getItemIdByName(getString(L, 1));
if (id == 0) {
lua_pushnil(L);
return 1;
}
}
const ItemType& it = Item::items[id];
if (it.stackable) {
count = std::min<uint16_t>(count, 100);
}
Item* item = Item::CreateItem(id, count);
if (!item) {
lua_pushnil(L);
return 1;
}
if (lua_gettop(L) >= 3) {
const Position& position = getPosition(L, 3);
Tile* tile = g_game.map.getTile(position);
if (!tile) {
delete item;
lua_pushnil(L);
return 1;
}
g_game.internalAddItem(tile, item, INDEX_WHEREEVER, FLAG_NOLIMIT);
} else {
getScriptEnv()->addTempItem(item);
item->setParent(VirtualCylinder::virtualCylinder);
}
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
return 1;
}
int LuaScriptInterface::luaGameCreateContainer(lua_State* L)
{
// Game.createContainer(itemId, size[, position])
uint16_t size = getNumber<uint16_t>(L, 2);
uint16_t id;
if (isNumber(L, 1)) {
id = getNumber<uint16_t>(L, 1);
} else {
id = Item::items.getItemIdByName(getString(L, 1));
if (id == 0) {
lua_pushnil(L);
return 1;
}
}
Container* container = Item::CreateItemAsContainer(id, size);
if (!container) {
lua_pushnil(L);
return 1;
}
if (lua_gettop(L) >= 3) {
const Position& position = getPosition(L, 3);
Tile* tile = g_game.map.getTile(position);
if (!tile) {
delete container;
lua_pushnil(L);
return 1;
}
g_game.internalAddItem(tile, container, INDEX_WHEREEVER, FLAG_NOLIMIT);
} else {
getScriptEnv()->addTempItem(container);
container->setParent(VirtualCylinder::virtualCylinder);
}
pushUserdata<Container>(L, container);
setMetatable(L, -1, "Container");
return 1;
}
int LuaScriptInterface::luaGameCreateMonster(lua_State* L)
{
// Game.createMonster(monsterName, position[, extended = false[, force = false]])
Monster* monster = Monster::createMonster(getString(L, 1));
if (!monster) {
lua_pushnil(L);
return 1;
}
const Position& position = getPosition(L, 2);
bool extended = getBoolean(L, 3, false);
bool force = getBoolean(L, 4, false);
if (g_game.placeCreature(monster, position, extended, force)) {
pushUserdata<Monster>(L, monster);
setMetatable(L, -1, "Monster");
} else {
delete monster;
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGameCreateNpc(lua_State* L)
{
// Game.createNpc(npcName, position[, extended = false[, force = false]])
Npc* npc = Npc::createNpc(getString(L, 1));
if (!npc) {
lua_pushnil(L);
return 1;
}
const Position& position = getPosition(L, 2);
bool extended = getBoolean(L, 3, false);
bool force = getBoolean(L, 4, false);
if (g_game.placeCreature(npc, position, extended, force)) {
pushUserdata<Npc>(L, npc);
setMetatable(L, -1, "Npc");
} else {
delete npc;
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGameCreateTile(lua_State* L)
{
// Game.createTile(x, y, z[, isDynamic = false])
// Game.createTile(position[, isDynamic = false])
Position position;
bool isDynamic;
if (isTable(L, 1)) {
position = getPosition(L, 1);
isDynamic = getBoolean(L, 2, false);
} else {
position.x = getNumber<uint16_t>(L, 1);
position.y = getNumber<uint16_t>(L, 2);
position.z = getNumber<uint16_t>(L, 3);
isDynamic = getBoolean(L, 4, false);
}
Tile* tile = g_game.map.getTile(position);
if (!tile) {
if (isDynamic) {
tile = new DynamicTile(position.x, position.y, position.z);
} else {
tile = new StaticTile(position.x, position.y, position.z);
}
g_game.map.setTile(position, tile);
}
pushUserdata(L, tile);
setMetatable(L, -1, "Tile");
return 1;
}
int LuaScriptInterface::luaGameStartRaid(lua_State* L)
{
// Game.startRaid(raidName)
const std::string& raidName = getString(L, 1);
Raid* raid = g_game.raids.getRaidByName(raidName);
if (!raid || !raid->isLoaded()) {
lua_pushnumber(L, RETURNVALUE_NOSUCHRAIDEXISTS);
return 1;
}
if (g_game.raids.getRunning()) {
lua_pushnumber(L, RETURNVALUE_ANOTHERRAIDISALREADYEXECUTING);
return 1;
}
g_game.raids.setRunning(raid);
raid->startRaid();
lua_pushnumber(L, RETURNVALUE_NOERROR);
return 1;
}
int LuaScriptInterface::luaGameGetClientVersion(lua_State* L)
{
// Game.getClientVersion()
lua_createtable(L, 0, 3);
setField(L, "min", CLIENT_VERSION_MIN);
setField(L, "max", CLIENT_VERSION_MAX);
setField(L, "string", CLIENT_VERSION_STR);
return 1;
}
int LuaScriptInterface::luaGameReload(lua_State* L)
{
// Game.reload(reloadType)
ReloadTypes_t reloadType = getNumber<ReloadTypes_t>(L, 1);
if (reloadType == RELOAD_TYPE_GLOBAL) {
pushBoolean(L, g_luaEnvironment.loadFile("data/global.lua") == 0);
} else {
pushBoolean(L, g_game.reload(reloadType));
}
lua_gc(g_luaEnvironment.getLuaState(), LUA_GCCOLLECT, 0);
return 1;
}
// Variant
int LuaScriptInterface::luaVariantCreate(lua_State* L)
{
// Variant(number or string or position or thing)
LuaVariant variant;
if (isUserdata(L, 2)) {
if (Thing* thing = getThing(L, 2)) {
variant.type = VARIANT_TARGETPOSITION;
variant.pos = thing->getPosition();
}
} else if (isTable(L, 2)) {
variant.type = VARIANT_POSITION;
variant.pos = getPosition(L, 2);
} else if (isNumber(L, 2)) {
variant.type = VARIANT_NUMBER;
variant.number = getNumber<uint32_t>(L, 2);
} else if (isString(L, 2)) {
variant.type = VARIANT_STRING;
variant.text = getString(L, 2);
}
pushVariant(L, variant);
return 1;
}
int LuaScriptInterface::luaVariantGetNumber(lua_State* L)
{
// Variant:getNumber()
const LuaVariant& variant = getVariant(L, 1);
if (variant.type == VARIANT_NUMBER) {
lua_pushnumber(L, variant.number);
} else {
lua_pushnumber(L, 0);
}
return 1;
}
int LuaScriptInterface::luaVariantGetString(lua_State* L)
{
// Variant:getString()
const LuaVariant& variant = getVariant(L, 1);
if (variant.type == VARIANT_STRING) {
pushString(L, variant.text);
} else {
pushString(L, std::string());
}
return 1;
}
int LuaScriptInterface::luaVariantGetPosition(lua_State* L)
{
// Variant:getPosition()
const LuaVariant& variant = getVariant(L, 1);
if (variant.type == VARIANT_POSITION || variant.type == VARIANT_TARGETPOSITION) {
pushPosition(L, variant.pos);
} else {
pushPosition(L, Position());
}
return 1;
}
// Position
int LuaScriptInterface::luaPositionCreate(lua_State* L)
{
// Position([x = 0[, y = 0[, z = 0[, stackpos = 0]]]])
// Position([position])
if (lua_gettop(L) <= 1) {
pushPosition(L, Position());
return 1;
}
int32_t stackpos;
if (isTable(L, 2)) {
const Position& position = getPosition(L, 2, stackpos);
pushPosition(L, position, stackpos);
} else {
uint16_t x = getNumber<uint16_t>(L, 2, 0);
uint16_t y = getNumber<uint16_t>(L, 3, 0);
uint8_t z = getNumber<uint8_t>(L, 4, 0);
stackpos = getNumber<int32_t>(L, 5, 0);
pushPosition(L, Position(x, y, z), stackpos);
}
return 1;
}
int LuaScriptInterface::luaPositionAdd(lua_State* L)
{
// positionValue = position + positionEx
int32_t stackpos;
const Position& position = getPosition(L, 1, stackpos);
Position positionEx;
if (stackpos == 0) {
positionEx = getPosition(L, 2, stackpos);
} else {
positionEx = getPosition(L, 2);
}
pushPosition(L, position + positionEx, stackpos);
return 1;
}
int LuaScriptInterface::luaPositionSub(lua_State* L)
{
// positionValue = position - positionEx
int32_t stackpos;
const Position& position = getPosition(L, 1, stackpos);
Position positionEx;
if (stackpos == 0) {
positionEx = getPosition(L, 2, stackpos);
} else {
positionEx = getPosition(L, 2);
}
pushPosition(L, position - positionEx, stackpos);
return 1;
}
int LuaScriptInterface::luaPositionCompare(lua_State* L)
{
// position == positionEx
const Position& positionEx = getPosition(L, 2);
const Position& position = getPosition(L, 1);
pushBoolean(L, position == positionEx);
return 1;
}
int LuaScriptInterface::luaPositionGetDistance(lua_State* L)
{
// position:getDistance(positionEx)
const Position& positionEx = getPosition(L, 2);
const Position& position = getPosition(L, 1);
lua_pushnumber(L, std::max<int32_t>(
std::max<int32_t>(
std::abs(Position::getDistanceX(position, positionEx)),
std::abs(Position::getDistanceY(position, positionEx))
),
std::abs(Position::getDistanceZ(position, positionEx))
));
return 1;
}
int LuaScriptInterface::luaPositionIsSightClear(lua_State* L)
{
// position:isSightClear(positionEx[, sameFloor = true])
bool sameFloor = getBoolean(L, 3, true);
const Position& positionEx = getPosition(L, 2);
const Position& position = getPosition(L, 1);
pushBoolean(L, g_game.isSightClear(position, positionEx, sameFloor));
return 1;
}
int LuaScriptInterface::luaPositionSendMagicEffect(lua_State* L)
{
// position:sendMagicEffect(magicEffect[, player = nullptr])
SpectatorHashSet spectators;
if (lua_gettop(L) >= 3) {
Player* player = getPlayer(L, 3);
if (player) {
spectators.insert(player);
}
}
MagicEffectClasses magicEffect = getNumber<MagicEffectClasses>(L, 2);
const Position& position = getPosition(L, 1);
if (!spectators.empty()) {
Game::addMagicEffect(spectators, position, magicEffect);
} else {
g_game.addMagicEffect(position, magicEffect);
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPositionSendDistanceEffect(lua_State* L)
{
// position:sendDistanceEffect(positionEx, distanceEffect[, player = nullptr])
SpectatorHashSet spectators;
if (lua_gettop(L) >= 4) {
Player* player = getPlayer(L, 4);
if (player) {
spectators.insert(player);
}
}
ShootType_t distanceEffect = getNumber<ShootType_t>(L, 3);
const Position& positionEx = getPosition(L, 2);
const Position& position = getPosition(L, 1);
if (!spectators.empty()) {
Game::addDistanceEffect(spectators, position, positionEx, distanceEffect);
} else {
g_game.addDistanceEffect(position, positionEx, distanceEffect);
}
pushBoolean(L, true);
return 1;
}
// Tile
int LuaScriptInterface::luaTileCreate(lua_State* L)
{
// Tile(x, y, z)
// Tile(position)
Tile* tile;
if (isTable(L, 2)) {
tile = g_game.map.getTile(getPosition(L, 2));
} else {
uint8_t z = getNumber<uint8_t>(L, 4);
uint16_t y = getNumber<uint16_t>(L, 3);
uint16_t x = getNumber<uint16_t>(L, 2);
tile = g_game.map.getTile(x, y, z);
}
if (tile) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetPosition(lua_State* L)
{
// tile:getPosition()
Tile* tile = getUserdata<Tile>(L, 1);
if (tile) {
pushPosition(L, tile->getPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetGround(lua_State* L)
{
// tile:getGround()
Tile* tile = getUserdata<Tile>(L, 1);
if (tile && tile->getGround()) {
pushUserdata<Item>(L, tile->getGround());
setItemMetatable(L, -1, tile->getGround());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetThing(lua_State* L)
{
// tile:getThing(index)
int32_t index = getNumber<int32_t>(L, 2);
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Thing* thing = tile->getThing(index);
if (!thing) {
lua_pushnil(L);
return 1;
}
if (Creature* creature = thing->getCreature()) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else if (Item* item = thing->getItem()) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetThingCount(lua_State* L)
{
// tile:getThingCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (tile) {
lua_pushnumber(L, tile->getThingCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopVisibleThing(lua_State* L)
{
// tile:getTopVisibleThing(creature)
Creature* creature = getCreature(L, 2);
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Thing* thing = tile->getTopVisibleThing(creature);
if (!thing) {
lua_pushnil(L);
return 1;
}
if (Creature* visibleCreature = thing->getCreature()) {
pushUserdata<Creature>(L, visibleCreature);
setCreatureMetatable(L, -1, visibleCreature);
} else if (Item* visibleItem = thing->getItem()) {
pushUserdata<Item>(L, visibleItem);
setItemMetatable(L, -1, visibleItem);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopTopItem(lua_State* L)
{
// tile:getTopTopItem()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Item* item = tile->getTopTopItem();
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopDownItem(lua_State* L)
{
// tile:getTopDownItem()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Item* item = tile->getTopDownItem();
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetFieldItem(lua_State* L)
{
// tile:getFieldItem()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Item* item = tile->getFieldItem();
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetItemById(lua_State* L)
{
// tile:getItemById(itemId[, subType = -1])
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
Item* item = g_game.findItemOfType(tile, itemId, false, subType);
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetItemByType(lua_State* L)
{
// tile:getItemByType(itemType)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
bool found;
ItemTypes_t itemType = getNumber<ItemTypes_t>(L, 2);
switch (itemType) {
case ITEM_TYPE_TELEPORT:
found = tile->hasFlag(TILESTATE_TELEPORT);
break;
case ITEM_TYPE_MAGICFIELD:
found = tile->hasFlag(TILESTATE_MAGICFIELD);
break;
case ITEM_TYPE_MAILBOX:
found = tile->hasFlag(TILESTATE_MAILBOX);
break;
case ITEM_TYPE_TRASHHOLDER:
found = tile->hasFlag(TILESTATE_TRASHHOLDER);
break;
case ITEM_TYPE_BED:
found = tile->hasFlag(TILESTATE_BED);
break;
case ITEM_TYPE_DEPOT:
found = tile->hasFlag(TILESTATE_DEPOT);
break;
default:
found = true;
break;
}
if (!found) {
lua_pushnil(L);
return 1;
}
if (Item* item = tile->getGround()) {
const ItemType& it = Item::items[item->getID()];
if (it.type == itemType) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
return 1;
}
}
if (const TileItemVector* items = tile->getItemList()) {
for (Item* item : *items) {
const ItemType& it = Item::items[item->getID()];
if (it.type == itemType) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
return 1;
}
}
}
lua_pushnil(L);
return 1;
}
int LuaScriptInterface::luaTileGetItemByTopOrder(lua_State* L)
{
// tile:getItemByTopOrder(topOrder)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
int32_t topOrder = getNumber<int32_t>(L, 2);
Item* item = tile->getItemByTopOrder(topOrder);
if (!item) {
lua_pushnil(L);
return 1;
}
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
return 1;
}
int LuaScriptInterface::luaTileGetItemCountById(lua_State* L)
{
// tile:getItemCountById(itemId[, subType = -1])
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
lua_pushnumber(L, tile->getItemTypeCount(itemId, subType));
return 1;
}
int LuaScriptInterface::luaTileGetBottomCreature(lua_State* L)
{
// tile:getBottomCreature()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
const Creature* creature = tile->getBottomCreature();
if (!creature) {
lua_pushnil(L);
return 1;
}
pushUserdata<const Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
return 1;
}
int LuaScriptInterface::luaTileGetTopCreature(lua_State* L)
{
// tile:getTopCreature()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Creature* creature = tile->getTopCreature();
if (!creature) {
lua_pushnil(L);
return 1;
}
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
return 1;
}
int LuaScriptInterface::luaTileGetBottomVisibleCreature(lua_State* L)
{
// tile:getBottomVisibleCreature(creature)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Creature* creature = getCreature(L, 2);
if (!creature) {
lua_pushnil(L);
return 1;
}
const Creature* visibleCreature = tile->getBottomVisibleCreature(creature);
if (visibleCreature) {
pushUserdata<const Creature>(L, visibleCreature);
setCreatureMetatable(L, -1, visibleCreature);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopVisibleCreature(lua_State* L)
{
// tile:getTopVisibleCreature(creature)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Creature* creature = getCreature(L, 2);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* visibleCreature = tile->getTopVisibleCreature(creature);
if (visibleCreature) {
pushUserdata<Creature>(L, visibleCreature);
setCreatureMetatable(L, -1, visibleCreature);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetItems(lua_State* L)
{
// tile:getItems()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
TileItemVector* itemVector = tile->getItemList();
if (!itemVector) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, itemVector->size(), 0);
int index = 0;
for (Item* item : *itemVector) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaTileGetItemCount(lua_State* L)
{
// tile:getItemCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, tile->getItemCount());
return 1;
}
int LuaScriptInterface::luaTileGetDownItemCount(lua_State* L)
{
// tile:getDownItemCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (tile) {
lua_pushnumber(L, tile->getDownItemCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopItemCount(lua_State* L)
{
// tile:getTopItemCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, tile->getTopItemCount());
return 1;
}
int LuaScriptInterface::luaTileGetCreatures(lua_State* L)
{
// tile:getCreatures()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
CreatureVector* creatureVector = tile->getCreatures();
if (!creatureVector) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, creatureVector->size(), 0);
int index = 0;
for (Creature* creature : *creatureVector) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaTileGetCreatureCount(lua_State* L)
{
// tile:getCreatureCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, tile->getCreatureCount());
return 1;
}
int LuaScriptInterface::luaTileHasProperty(lua_State* L)
{
// tile:hasProperty(property[, item])
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Item* item;
if (lua_gettop(L) >= 3) {
item = getUserdata<Item>(L, 3);
} else {
item = nullptr;
}
ITEMPROPERTY property = getNumber<ITEMPROPERTY>(L, 2);
if (item) {
pushBoolean(L, tile->hasProperty(item, property));
} else {
pushBoolean(L, tile->hasProperty(property));
}
return 1;
}
int LuaScriptInterface::luaTileGetThingIndex(lua_State* L)
{
// tile:getThingIndex(thing)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Thing* thing = getThing(L, 2);
if (thing) {
lua_pushnumber(L, tile->getThingIndex(thing));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileHasFlag(lua_State* L)
{
// tile:hasFlag(flag)
Tile* tile = getUserdata<Tile>(L, 1);
if (tile) {
tileflags_t flag = getNumber<tileflags_t>(L, 2);
pushBoolean(L, tile->hasFlag(flag));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileQueryAdd(lua_State* L)
{
// tile:queryAdd(thing[, flags])
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Thing* thing = getThing(L, 2);
if (thing) {
uint32_t flags = getNumber<uint32_t>(L, 3, 0);
lua_pushnumber(L, tile->queryAdd(0, *thing, 1, flags));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetHouse(lua_State* L)
{
// tile:getHouse()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
if (HouseTile* houseTile = dynamic_cast<HouseTile*>(tile)) {
pushUserdata<House>(L, houseTile->getHouse());
setMetatable(L, -1, "House");
} else {
lua_pushnil(L);
}
return 1;
}
// NetworkMessage
int LuaScriptInterface::luaNetworkMessageCreate(lua_State* L)
{
// NetworkMessage()
pushUserdata<NetworkMessage>(L, new NetworkMessage);
setMetatable(L, -1, "NetworkMessage");
return 1;
}
int LuaScriptInterface::luaNetworkMessageDelete(lua_State* L)
{
NetworkMessage** messagePtr = getRawUserdata<NetworkMessage>(L, 1);
if (messagePtr && *messagePtr) {
delete *messagePtr;
*messagePtr = nullptr;
}
return 0;
}
int LuaScriptInterface::luaNetworkMessageGetByte(lua_State* L)
{
// networkMessage:getByte()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
lua_pushnumber(L, message->getByte());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetU16(lua_State* L)
{
// networkMessage:getU16()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
lua_pushnumber(L, message->get<uint16_t>());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetU32(lua_State* L)
{
// networkMessage:getU32()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
lua_pushnumber(L, message->get<uint32_t>());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetU64(lua_State* L)
{
// networkMessage:getU64()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
lua_pushnumber(L, message->get<uint64_t>());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetString(lua_State* L)
{
// networkMessage:getString()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
pushString(L, message->getString());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetPosition(lua_State* L)
{
// networkMessage:getPosition()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
pushPosition(L, message->getPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddByte(lua_State* L)
{
// networkMessage:addByte(number)
uint8_t number = getNumber<uint8_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addByte(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddU16(lua_State* L)
{
// networkMessage:addU16(number)
uint16_t number = getNumber<uint16_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->add<uint16_t>(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddU32(lua_State* L)
{
// networkMessage:addU32(number)
uint32_t number = getNumber<uint32_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->add<uint32_t>(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddU64(lua_State* L)
{
// networkMessage:addU64(number)
uint64_t number = getNumber<uint64_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->add<uint64_t>(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddString(lua_State* L)
{
// networkMessage:addString(string)
const std::string& string = getString(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addString(string);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddPosition(lua_State* L)
{
// networkMessage:addPosition(position)
const Position& position = getPosition(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addPosition(position);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddDouble(lua_State* L)
{
// networkMessage:addDouble(number)
double number = getNumber<double>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addDouble(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddItem(lua_State* L)
{
// networkMessage:addItem(item)
Item* item = getUserdata<Item>(L, 2);
if (!item) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
lua_pushnil(L);
return 1;
}
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addItem(item);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddItemId(lua_State* L)
{
// networkMessage:addItemId(itemId)
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (!message) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
message->addItemId(itemId);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaNetworkMessageReset(lua_State* L)
{
// networkMessage:reset()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->reset();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageSkipBytes(lua_State* L)
{
// networkMessage:skipBytes(number)
int16_t number = getNumber<int16_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->skipBytes(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageSendToPlayer(lua_State* L)
{
// networkMessage:sendToPlayer(player)
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (!message) {
lua_pushnil(L);
return 1;
}
Player* player = getPlayer(L, 2);
if (player) {
player->sendNetworkMessage(*message);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
lua_pushnil(L);
}
return 1;
}
// ModalWindow
int LuaScriptInterface::luaModalWindowCreate(lua_State* L)
{
// ModalWindow(id, title, message)
const std::string& message = getString(L, 4);
const std::string& title = getString(L, 3);
uint32_t id = getNumber<uint32_t>(L, 2);
pushUserdata<ModalWindow>(L, new ModalWindow(id, title, message));
setMetatable(L, -1, "ModalWindow");
return 1;
}
int LuaScriptInterface::luaModalWindowDelete(lua_State* L)
{
ModalWindow** windowPtr = getRawUserdata<ModalWindow>(L, 1);
if (windowPtr && *windowPtr) {
delete *windowPtr;
*windowPtr = nullptr;
}
return 0;
}
int LuaScriptInterface::luaModalWindowGetId(lua_State* L)
{
// modalWindow:getId()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->id);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetTitle(lua_State* L)
{
// modalWindow:getTitle()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
pushString(L, window->title);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetMessage(lua_State* L)
{
// modalWindow:getMessage()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
pushString(L, window->message);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetTitle(lua_State* L)
{
// modalWindow:setTitle(text)
const std::string& text = getString(L, 2);
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->title = text;
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetMessage(lua_State* L)
{
// modalWindow:setMessage(text)
const std::string& text = getString(L, 2);
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->message = text;
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetButtonCount(lua_State* L)
{
// modalWindow:getButtonCount()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->buttons.size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetChoiceCount(lua_State* L)
{
// modalWindow:getChoiceCount()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->choices.size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowAddButton(lua_State* L)
{
// modalWindow:addButton(id, text)
const std::string& text = getString(L, 3);
uint8_t id = getNumber<uint8_t>(L, 2);
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->buttons.emplace_back(text, id);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowAddChoice(lua_State* L)
{
// modalWindow:addChoice(id, text)
const std::string& text = getString(L, 3);
uint8_t id = getNumber<uint8_t>(L, 2);
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->choices.emplace_back(text, id);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetDefaultEnterButton(lua_State* L)
{
// modalWindow:getDefaultEnterButton()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->defaultEnterButton);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetDefaultEnterButton(lua_State* L)
{
// modalWindow:setDefaultEnterButton(buttonId)
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->defaultEnterButton = getNumber<uint8_t>(L, 2);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetDefaultEscapeButton(lua_State* L)
{
// modalWindow:getDefaultEscapeButton()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->defaultEscapeButton);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetDefaultEscapeButton(lua_State* L)
{
// modalWindow:setDefaultEscapeButton(buttonId)
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->defaultEscapeButton = getNumber<uint8_t>(L, 2);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowHasPriority(lua_State* L)
{
// modalWindow:hasPriority()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
pushBoolean(L, window->priority);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetPriority(lua_State* L)
{
// modalWindow:setPriority(priority)
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->priority = getBoolean(L, 2);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSendToPlayer(lua_State* L)
{
// modalWindow:sendToPlayer(player)
Player* player = getPlayer(L, 2);
if (!player) {
lua_pushnil(L);
return 1;
}
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
if (!player->hasModalWindowOpen(window->id)) {
player->sendModalWindow(*window);
}
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
// Item
int LuaScriptInterface::luaItemCreate(lua_State* L)
{
// Item(uid)
uint32_t id = getNumber<uint32_t>(L, 2);
Item* item = getScriptEnv()->getItemByUID(id);
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemIsItem(lua_State* L)
{
// item:isItem()
pushBoolean(L, getUserdata<const Item>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaItemGetParent(lua_State* L)
{
// item:getParent()
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
Cylinder* parent = item->getParent();
if (!parent) {
lua_pushnil(L);
return 1;
}
pushCylinder(L, parent);
return 1;
}
int LuaScriptInterface::luaItemGetTopParent(lua_State* L)
{
// item:getTopParent()
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
Cylinder* topParent = item->getTopParent();
if (!topParent) {
lua_pushnil(L);
return 1;
}
pushCylinder(L, topParent);
return 1;
}
int LuaScriptInterface::luaItemGetId(lua_State* L)
{
// item:getId()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getID());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemClone(lua_State* L)
{
// item:clone()
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
Item* clone = item->clone();
if (!clone) {
lua_pushnil(L);
return 1;
}
getScriptEnv()->addTempItem(clone);
clone->setParent(VirtualCylinder::virtualCylinder);
pushUserdata<Item>(L, clone);
setItemMetatable(L, -1, clone);
return 1;
}
int LuaScriptInterface::luaItemSplit(lua_State* L)
{
// item:split([count = 1])
Item** itemPtr = getRawUserdata<Item>(L, 1);
if (!itemPtr) {
lua_pushnil(L);
return 1;
}
Item* item = *itemPtr;
if (!item || !item->isStackable()) {
lua_pushnil(L);
return 1;
}
uint16_t count = std::min<uint16_t>(getNumber<uint16_t>(L, 2, 1), item->getItemCount());
uint16_t diff = item->getItemCount() - count;
Item* splitItem = item->clone();
if (!splitItem) {
lua_pushnil(L);
return 1;
}
splitItem->setItemCount(count);
ScriptEnvironment* env = getScriptEnv();
uint32_t uid = env->addThing(item);
Item* newItem = g_game.transformItem(item, item->getID(), diff);
if (item->isRemoved()) {
env->removeItemByUID(uid);
}
if (newItem && newItem != item) {
env->insertItem(uid, newItem);
}
*itemPtr = newItem;
splitItem->setParent(VirtualCylinder::virtualCylinder);
env->addTempItem(splitItem);
pushUserdata<Item>(L, splitItem);
setItemMetatable(L, -1, splitItem);
return 1;
}
int LuaScriptInterface::luaItemRemove(lua_State* L)
{
// item:remove([count = -1])
Item* item = getUserdata<Item>(L, 1);
if (item) {
int32_t count = getNumber<int32_t>(L, 2, -1);
pushBoolean(L, g_game.internalRemoveItem(item, count) == RETURNVALUE_NOERROR);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetUniqueId(lua_State* L)
{
// item:getUniqueId()
Item* item = getUserdata<Item>(L, 1);
if (item) {
uint32_t uniqueId = item->getUniqueId();
if (uniqueId == 0) {
uniqueId = getScriptEnv()->addThing(item);
}
lua_pushnumber(L, uniqueId);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetActionId(lua_State* L)
{
// item:getActionId()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getActionId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemSetActionId(lua_State* L)
{
// item:setActionId(actionId)
uint16_t actionId = getNumber<uint16_t>(L, 2);
Item* item = getUserdata<Item>(L, 1);
if (item) {
item->setActionId(actionId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetCount(lua_State* L)
{
// item:getCount()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getItemCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetCharges(lua_State* L)
{
// item:getCharges()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getCharges());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetFluidType(lua_State* L)
{
// item:getFluidType()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getFluidType());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetWeight(lua_State* L)
{
// item:getWeight()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getWeight());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetSubType(lua_State* L)
{
// item:getSubType()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getSubType());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetName(lua_State* L)
{
// item:getName()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushString(L, item->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetPluralName(lua_State* L)
{
// item:getPluralName()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushString(L, item->getPluralName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetArticle(lua_State* L)
{
// item:getArticle()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushString(L, item->getArticle());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetPosition(lua_State* L)
{
// item:getPosition()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushPosition(L, item->getPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetTile(lua_State* L)
{
// item:getTile()
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
Tile* tile = item->getTile();
if (tile) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemHasAttribute(lua_State* L)
{
// item:hasAttribute(key)
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
itemAttrTypes attribute;
if (isNumber(L, 2)) {
attribute = getNumber<itemAttrTypes>(L, 2);
} else if (isString(L, 2)) {
attribute = stringToItemAttribute(getString(L, 2));
} else {
attribute = ITEM_ATTRIBUTE_NONE;
}
pushBoolean(L, item->hasAttribute(attribute));
return 1;
}
int LuaScriptInterface::luaItemGetAttribute(lua_State* L)
{
// item:getAttribute(key)
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
itemAttrTypes attribute;
if (isNumber(L, 2)) {
attribute = getNumber<itemAttrTypes>(L, 2);
} else if (isString(L, 2)) {
attribute = stringToItemAttribute(getString(L, 2));
} else {
attribute = ITEM_ATTRIBUTE_NONE;
}
if (ItemAttributes::isIntAttrType(attribute)) {
lua_pushnumber(L, item->getIntAttr(attribute));
} else if (ItemAttributes::isStrAttrType(attribute)) {
pushString(L, item->getStrAttr(attribute));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemSetAttribute(lua_State* L)
{
// item:setAttribute(key, value)
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
itemAttrTypes attribute;
if (isNumber(L, 2)) {
attribute = getNumber<itemAttrTypes>(L, 2);
} else if (isString(L, 2)) {
attribute = stringToItemAttribute(getString(L, 2));
} else {
attribute = ITEM_ATTRIBUTE_NONE;
}
if (ItemAttributes::isIntAttrType(attribute)) {
if (attribute == ITEM_ATTRIBUTE_UNIQUEID) {
reportErrorFunc("Attempt to set protected key \"uid\"");
pushBoolean(L, false);
return 1;
}
item->setIntAttr(attribute, getNumber<int32_t>(L, 3));
pushBoolean(L, true);
} else if (ItemAttributes::isStrAttrType(attribute)) {
item->setStrAttr(attribute, getString(L, 3));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemRemoveAttribute(lua_State* L)
{
// item:removeAttribute(key)
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
itemAttrTypes attribute;
if (isNumber(L, 2)) {
attribute = getNumber<itemAttrTypes>(L, 2);
} else if (isString(L, 2)) {
attribute = stringToItemAttribute(getString(L, 2));
} else {
attribute = ITEM_ATTRIBUTE_NONE;
}
bool ret = attribute != ITEM_ATTRIBUTE_UNIQUEID;
if (ret) {
item->removeAttribute(attribute);
} else {
reportErrorFunc("Attempt to erase protected key \"uid\"");
}
pushBoolean(L, ret);
return 1;
}
int LuaScriptInterface::luaItemMoveTo(lua_State* L)
{
// item:moveTo(position or cylinder[, flags])
Item** itemPtr = getRawUserdata<Item>(L, 1);
if (!itemPtr) {
lua_pushnil(L);
return 1;
}
Item* item = *itemPtr;
if (!item || item->isRemoved()) {
lua_pushnil(L);
return 1;
}
Cylinder* toCylinder;
if (isUserdata(L, 2)) {
const LuaDataType type = getUserdataType(L, 2);
switch (type) {
case LuaData_Container:
toCylinder = getUserdata<Container>(L, 2);
break;
case LuaData_Player:
toCylinder = getUserdata<Player>(L, 2);
break;
case LuaData_Tile:
toCylinder = getUserdata<Tile>(L, 2);
break;
default:
toCylinder = nullptr;
break;
}
} else {
toCylinder = g_game.map.getTile(getPosition(L, 2));
}
if (!toCylinder) {
lua_pushnil(L);
return 1;
}
if (item->getParent() == toCylinder) {
pushBoolean(L, true);
return 1;
}
uint32_t flags = getNumber<uint32_t>(L, 3, FLAG_NOLIMIT | FLAG_IGNOREBLOCKITEM | FLAG_IGNOREBLOCKCREATURE | FLAG_IGNORENOTMOVEABLE);
if (item->getParent() == VirtualCylinder::virtualCylinder) {
pushBoolean(L, g_game.internalAddItem(toCylinder, item, INDEX_WHEREEVER, flags) == RETURNVALUE_NOERROR);
} else {
Item* moveItem = nullptr;
ReturnValue ret = g_game.internalMoveItem(item->getParent(), toCylinder, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem, flags);
if (moveItem) {
*itemPtr = moveItem;
}
pushBoolean(L, ret == RETURNVALUE_NOERROR);
}
return 1;
}
int LuaScriptInterface::luaItemTransform(lua_State* L)
{
// item:transform(itemId[, count/subType = -1])
Item** itemPtr = getRawUserdata<Item>(L, 1);
if (!itemPtr) {
lua_pushnil(L);
return 1;
}
Item*& item = *itemPtr;
if (!item) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
if (item->getID() == itemId && (subType == -1 || subType == item->getSubType())) {
pushBoolean(L, true);
return 1;
}
const ItemType& it = Item::items[itemId];
if (it.stackable) {
subType = std::min<int32_t>(subType, 100);
}
ScriptEnvironment* env = getScriptEnv();
uint32_t uid = env->addThing(item);
Item* newItem = g_game.transformItem(item, itemId, subType);
if (item->isRemoved()) {
env->removeItemByUID(uid);
}
if (newItem && newItem != item) {
env->insertItem(uid, newItem);
}
item = newItem;
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaItemDecay(lua_State* L)
{
// item:decay(decayId)
Item* item = getUserdata<Item>(L, 1);
if (item) {
if (isNumber(L, 2)) {
ItemType& it = Item::items.getItemType(item->getID());
it.decayTo = getNumber<int32_t>(L, 2);
}
g_game.startDecay(item);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetDescription(lua_State* L)
{
// item:getDescription(distance)
Item* item = getUserdata<Item>(L, 1);
if (item) {
int32_t distance = getNumber<int32_t>(L, 2);
pushString(L, item->getDescription(distance));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemHasProperty(lua_State* L)
{
// item:hasProperty(property)
Item* item = getUserdata<Item>(L, 1);
if (item) {
ITEMPROPERTY property = getNumber<ITEMPROPERTY>(L, 2);
pushBoolean(L, item->hasProperty(property));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemIsLoadedFromMap(lua_State* L)
{
// item:isLoadedFromMap()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushBoolean(L, item->isLoadedFromMap());
} else {
lua_pushnil(L);
}
return 1;
}
// Container
int LuaScriptInterface::luaContainerCreate(lua_State* L)
{
// Container(uid)
uint32_t id = getNumber<uint32_t>(L, 2);
Container* container = getScriptEnv()->getContainerByUID(id);
if (container) {
pushUserdata(L, container);
setMetatable(L, -1, "Container");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerGetSize(lua_State* L)
{
// container:getSize()
Container* container = getUserdata<Container>(L, 1);
if (container) {
lua_pushnumber(L, container->size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerGetCapacity(lua_State* L)
{
// container:getCapacity()
Container* container = getUserdata<Container>(L, 1);
if (container) {
lua_pushnumber(L, container->capacity());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerGetEmptySlots(lua_State* L)
{
// container:getEmptySlots([recursive = false])
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
uint32_t slots = container->capacity() - container->size();
bool recursive = getBoolean(L, 2, false);
if (recursive) {
for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) {
if (Container* tmpContainer = (*it)->getContainer()) {
slots += tmpContainer->capacity() - tmpContainer->size();
}
}
}
lua_pushnumber(L, slots);
return 1;
}
int LuaScriptInterface::luaContainerGetItemHoldingCount(lua_State* L)
{
// container:getItemHoldingCount()
Container* container = getUserdata<Container>(L, 1);
if (container) {
lua_pushnumber(L, container->getItemHoldingCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerGetItem(lua_State* L)
{
// container:getItem(index)
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
uint32_t index = getNumber<uint32_t>(L, 2);
Item* item = container->getItemByIndex(index);
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerHasItem(lua_State* L)
{
// container:hasItem(item)
Item* item = getUserdata<Item>(L, 2);
Container* container = getUserdata<Container>(L, 1);
if (container) {
pushBoolean(L, container->isHoldingItem(item));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerAddItem(lua_State* L)
{
// container:addItem(itemId[, count/subType = 1[, index = INDEX_WHEREEVER[, flags = 0]]])
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
uint32_t count = getNumber<uint32_t>(L, 3, 1);
const ItemType& it = Item::items[itemId];
if (it.stackable) {
count = std::min<uint16_t>(count, 100);
}
Item* item = Item::CreateItem(itemId, count);
if (!item) {
lua_pushnil(L);
return 1;
}
int32_t index = getNumber<int32_t>(L, 4, INDEX_WHEREEVER);
uint32_t flags = getNumber<uint32_t>(L, 5, 0);
ReturnValue ret = g_game.internalAddItem(container, item, index, flags);
if (ret == RETURNVALUE_NOERROR) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
delete item;
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerAddItemEx(lua_State* L)
{
// container:addItemEx(item[, index = INDEX_WHEREEVER[, flags = 0]])
Item* item = getUserdata<Item>(L, 2);
if (!item) {
lua_pushnil(L);
return 1;
}
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
if (item->getParent() != VirtualCylinder::virtualCylinder) {
reportErrorFunc("Item already has a parent");
lua_pushnil(L);
return 1;
}
int32_t index = getNumber<int32_t>(L, 3, INDEX_WHEREEVER);
uint32_t flags = getNumber<uint32_t>(L, 4, 0);
ReturnValue ret = g_game.internalAddItem(container, item, index, flags);
if (ret == RETURNVALUE_NOERROR) {
ScriptEnvironment::removeTempItem(item);
}
lua_pushnumber(L, ret);
return 1;
}
int LuaScriptInterface::luaContainerGetItemCountById(lua_State* L)
{
// container:getItemCountById(itemId[, subType = -1])
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
lua_pushnumber(L, container->getItemTypeCount(itemId, subType));
return 1;
}
// Teleport
int LuaScriptInterface::luaTeleportCreate(lua_State* L)
{
// Teleport(uid)
uint32_t id = getNumber<uint32_t>(L, 2);
Item* item = getScriptEnv()->getItemByUID(id);
if (item && item->getTeleport()) {
pushUserdata(L, item);
setMetatable(L, -1, "Teleport");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTeleportGetDestination(lua_State* L)
{
// teleport:getDestination()
Teleport* teleport = getUserdata<Teleport>(L, 1);
if (teleport) {
pushPosition(L, teleport->getDestPos());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTeleportSetDestination(lua_State* L)
{
// teleport:setDestination(position)
Teleport* teleport = getUserdata<Teleport>(L, 1);
if (teleport) {
teleport->setDestPos(getPosition(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
// Creature
int LuaScriptInterface::luaCreatureCreate(lua_State* L)
{
// Creature(id or name or userdata)
Creature* creature;
if (isNumber(L, 2)) {
creature = g_game.getCreatureByID(getNumber<uint32_t>(L, 2));
} else if (isString(L, 2)) {
creature = g_game.getCreatureByName(getString(L, 2));
} else if (isUserdata(L, 2)) {
LuaDataType type = getUserdataType(L, 2);
if (type != LuaData_Player && type != LuaData_Monster && type != LuaData_Npc) {
lua_pushnil(L);
return 1;
}
creature = getUserdata<Creature>(L, 2);
} else {
creature = nullptr;
}
if (creature) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetEvents(lua_State* L)
{
// creature:getEvents(type)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
CreatureEventType_t eventType = getNumber<CreatureEventType_t>(L, 2);
const auto& eventList = creature->getCreatureEvents(eventType);
lua_createtable(L, eventList.size(), 0);
int index = 0;
for (CreatureEvent* event : eventList) {
pushString(L, event->getName());
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaCreatureRegisterEvent(lua_State* L)
{
// creature:registerEvent(name)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
const std::string& name = getString(L, 2);
pushBoolean(L, creature->registerCreatureEvent(name));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureUnregisterEvent(lua_State* L)
{
// creature:unregisterEvent(name)
const std::string& name = getString(L, 2);
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
pushBoolean(L, creature->unregisterCreatureEvent(name));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureIsRemoved(lua_State* L)
{
// creature:isRemoved()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushBoolean(L, creature->isRemoved());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureIsCreature(lua_State* L)
{
// creature:isCreature()
pushBoolean(L, getUserdata<const Creature>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaCreatureIsInGhostMode(lua_State* L)
{
// creature:isInGhostMode()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushBoolean(L, creature->isInGhostMode());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureIsHealthHidden(lua_State* L)
{
// creature:isHealthHidden()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushBoolean(L, creature->isHealthHidden());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureCanSee(lua_State* L)
{
// creature:canSee(position)
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
const Position& position = getPosition(L, 2);
pushBoolean(L, creature->canSee(position));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureCanSeeCreature(lua_State* L)
{
// creature:canSeeCreature(creature)
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
const Creature* otherCreature = getCreature(L, 2);
pushBoolean(L, creature->canSeeCreature(otherCreature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetParent(lua_State* L)
{
// creature:getParent()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Cylinder* parent = creature->getParent();
if (!parent) {
lua_pushnil(L);
return 1;
}
pushCylinder(L, parent);
return 1;
}
int LuaScriptInterface::luaCreatureGetId(lua_State* L)
{
// creature:getId()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getID());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetName(lua_State* L)
{
// creature:getName()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushString(L, creature->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetTarget(lua_State* L)
{
// creature:getTarget()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* target = creature->getAttackedCreature();
if (target) {
pushUserdata<Creature>(L, target);
setCreatureMetatable(L, -1, target);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetTarget(lua_State* L)
{
// creature:setTarget(target)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
Creature* target = getCreature(L, 2);
pushBoolean(L, creature->setAttackedCreature(target));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetFollowCreature(lua_State* L)
{
// creature:getFollowCreature()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* followCreature = creature->getFollowCreature();
if (followCreature) {
pushUserdata<Creature>(L, followCreature);
setCreatureMetatable(L, -1, followCreature);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetFollowCreature(lua_State* L)
{
// creature:setFollowCreature(followedCreature)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
Creature* followCreature = getCreature(L, 2);
pushBoolean(L, creature->setFollowCreature(followCreature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetMaster(lua_State* L)
{
// creature:getMaster()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* master = creature->getMaster();
if (!master) {
lua_pushnil(L);
return 1;
}
pushUserdata<Creature>(L, master);
setCreatureMetatable(L, -1, master);
return 1;
}
int LuaScriptInterface::luaCreatureSetMaster(lua_State* L)
{
// creature:setMaster(master)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
pushBoolean(L, creature->setMaster(getCreature(L, 2)));
g_game.updateCreatureType(creature);
return 1;
}
int LuaScriptInterface::luaCreatureGetLight(lua_State* L)
{
// creature:getLight()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
LightInfo lightInfo = creature->getCreatureLight();
lua_pushnumber(L, lightInfo.level);
lua_pushnumber(L, lightInfo.color);
return 2;
}
int LuaScriptInterface::luaCreatureSetLight(lua_State* L)
{
// creature:setLight(color, level)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
LightInfo light;
light.color = getNumber<uint8_t>(L, 2);
light.level = getNumber<uint8_t>(L, 3);
creature->setCreatureLight(light);
g_game.changeLight(creature);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureGetSpeed(lua_State* L)
{
// creature:getSpeed()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getSpeed());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetBaseSpeed(lua_State* L)
{
// creature:getBaseSpeed()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getBaseSpeed());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureChangeSpeed(lua_State* L)
{
// creature:changeSpeed(delta)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
int32_t delta = getNumber<int32_t>(L, 2);
g_game.changeSpeed(creature, delta);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureSetDropLoot(lua_State* L)
{
// creature:setDropLoot(doDrop)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->setDropLoot(getBoolean(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetSkillLoss(lua_State* L)
{
// creature:setSkillLoss(skillLoss)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->setSkillLoss(getBoolean(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetPosition(lua_State* L)
{
// creature:getPosition()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushPosition(L, creature->getPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetTile(lua_State* L)
{
// creature:getTile()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Tile* tile = creature->getTile();
if (tile) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetDirection(lua_State* L)
{
// creature:getDirection()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getDirection());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetDirection(lua_State* L)
{
// creature:setDirection(direction)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
pushBoolean(L, g_game.internalCreatureTurn(creature, getNumber<Direction>(L, 2)));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetHealth(lua_State* L)
{
// creature:getHealth()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getHealth());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureAddHealth(lua_State* L)
{
// creature:addHealth(healthChange)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
CombatDamage damage;
damage.primary.value = getNumber<int32_t>(L, 2);
if (damage.primary.value >= 0) {
damage.primary.type = COMBAT_HEALING;
} else {
damage.primary.type = COMBAT_UNDEFINEDDAMAGE;
}
pushBoolean(L, g_game.combatChangeHealth(nullptr, creature, damage));
return 1;
}
int LuaScriptInterface::luaCreatureGetMaxHealth(lua_State* L)
{
// creature:getMaxHealth()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getMaxHealth());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetMaxHealth(lua_State* L)
{
// creature:setMaxHealth(maxHealth)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
creature->healthMax = getNumber<uint32_t>(L, 2);
creature->health = std::min<int32_t>(creature->health, creature->healthMax);
g_game.addCreatureHealth(creature);
Player* player = creature->getPlayer();
if (player) {
player->sendStats();
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureSetHiddenHealth(lua_State* L)
{
// creature:setHiddenHealth(hide)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->setHiddenHealth(getBoolean(L, 2));
g_game.addCreatureHealth(creature);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetSkull(lua_State* L)
{
// creature:getSkull()
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getSkull());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetSkull(lua_State* L)
{
// creature:setSkull(skull)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->setSkull(getNumber<Skulls_t>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetOutfit(lua_State* L)
{
// creature:getOutfit()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushOutfit(L, creature->getCurrentOutfit());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetOutfit(lua_State* L)
{
// creature:setOutfit(outfit)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->defaultOutfit = getOutfit(L, 2);
g_game.internalCreatureChangeOutfit(creature, creature->defaultOutfit);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetCondition(lua_State* L)
{
// creature:getCondition(conditionType[, conditionId = CONDITIONID_COMBAT[, subId = 0]])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2);
ConditionId_t conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT);
uint32_t subId = getNumber<uint32_t>(L, 4, 0);
Condition* condition = creature->getCondition(conditionType, conditionId, subId);
if (condition) {
pushUserdata<Condition>(L, condition);
setWeakMetatable(L, -1, "Condition");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureAddCondition(lua_State* L)
{
// creature:addCondition(condition[, force = false])
Creature* creature = getUserdata<Creature>(L, 1);
Condition* condition = getUserdata<Condition>(L, 2);
if (creature && condition) {
bool force = getBoolean(L, 3, false);
pushBoolean(L, creature->addCondition(condition->clone(), force));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureRemoveCondition(lua_State* L)
{
// creature:removeCondition(conditionType[, conditionId = CONDITIONID_COMBAT[, subId = 0[, force = false]]])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2);
ConditionId_t conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT);
uint32_t subId = getNumber<uint32_t>(L, 4, 0);
Condition* condition = creature->getCondition(conditionType, conditionId, subId);
if (condition) {
bool force = getBoolean(L, 5, false);
creature->removeCondition(condition, force);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureHasCondition(lua_State* L)
{
// creature:hasCondition(conditionType[, subId = 0])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2);
uint32_t subId = getNumber<uint32_t>(L, 3, 0);
pushBoolean(L, creature->hasCondition(conditionType, subId));
return 1;
}
int LuaScriptInterface::luaCreatureIsImmune(lua_State* L)
{
// creature:isImmune(condition or conditionType)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
if (isNumber(L, 2)) {
pushBoolean(L, creature->isImmune(getNumber<ConditionType_t>(L, 2)));
} else if (Condition* condition = getUserdata<Condition>(L, 2)) {
pushBoolean(L, creature->isImmune(condition->getType()));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureRemove(lua_State* L)
{
// creature:remove()
Creature** creaturePtr = getRawUserdata<Creature>(L, 1);
if (!creaturePtr) {
lua_pushnil(L);
return 1;
}
Creature* creature = *creaturePtr;
if (!creature) {
lua_pushnil(L);
return 1;
}
Player* player = creature->getPlayer();
if (player) {
player->kickPlayer(true);
} else {
g_game.removeCreature(creature);
}
*creaturePtr = nullptr;
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureTeleportTo(lua_State* L)
{
// creature:teleportTo(position[, pushMovement = false])
bool pushMovement = getBoolean(L, 3, false);
const Position& position = getPosition(L, 2);
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
const Position oldPosition = creature->getPosition();
if (g_game.internalTeleport(creature, position, pushMovement) != RETURNVALUE_NOERROR) {
pushBoolean(L, false);
return 1;
}
if (pushMovement) {
if (oldPosition.x == position.x) {
if (oldPosition.y < position.y) {
g_game.internalCreatureTurn(creature, DIRECTION_SOUTH);
} else {
g_game.internalCreatureTurn(creature, DIRECTION_NORTH);
}
} else if (oldPosition.x > position.x) {
g_game.internalCreatureTurn(creature, DIRECTION_WEST);
} else if (oldPosition.x < position.x) {
g_game.internalCreatureTurn(creature, DIRECTION_EAST);
}
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureSay(lua_State* L)
{
// creature:say(text, type[, ghost = false[, target = nullptr[, position]]])
int parameters = lua_gettop(L);
Position position;
if (parameters >= 6) {
position = getPosition(L, 6);
if (!position.x || !position.y) {
reportErrorFunc("Invalid position specified.");
pushBoolean(L, false);
return 1;
}
}
Creature* target = nullptr;
if (parameters >= 5) {
target = getCreature(L, 5);
}
bool ghost = getBoolean(L, 4, false);
SpeakClasses type = getNumber<SpeakClasses>(L, 3);
const std::string& text = getString(L, 2);
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
SpectatorHashSet spectators;
if (target) {
spectators.insert(target);
}
if (position.x != 0) {
pushBoolean(L, g_game.internalCreatureSay(creature, type, text, ghost, &spectators, &position));
} else {
pushBoolean(L, g_game.internalCreatureSay(creature, type, text, ghost, &spectators));
}
return 1;
}
int LuaScriptInterface::luaCreatureGetDamageMap(lua_State* L)
{
// creature:getDamageMap()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, creature->damageMap.size(), 0);
for (auto damageEntry : creature->damageMap) {
lua_createtable(L, 0, 2);
setField(L, "total", damageEntry.second.total);
setField(L, "ticks", damageEntry.second.ticks);
lua_rawseti(L, -2, damageEntry.first);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetSummons(lua_State* L)
{
// creature:getSummons()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, creature->getSummonCount(), 0);
int index = 0;
for (Creature* summon : creature->getSummons()) {
pushUserdata<Creature>(L, summon);
setCreatureMetatable(L, -1, summon);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetDescription(lua_State* L)
{
// creature:getDescription(distance)
int32_t distance = getNumber<int32_t>(L, 2);
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
pushString(L, creature->getDescription(distance));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetPathTo(lua_State* L)
{
// creature:getPathTo(pos[, minTargetDist = 0[, maxTargetDist = 1[, fullPathSearch = true[, clearSight = true[, maxSearchDist = 0]]]]])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
const Position& position = getPosition(L, 2);
FindPathParams fpp;
fpp.minTargetDist = getNumber<int32_t>(L, 3, 0);
fpp.maxTargetDist = getNumber<int32_t>(L, 4, 1);
fpp.fullPathSearch = getBoolean(L, 5, fpp.fullPathSearch);
fpp.clearSight = getBoolean(L, 6, fpp.clearSight);
fpp.maxSearchDist = getNumber<int32_t>(L, 7, fpp.maxSearchDist);
std::forward_list<Direction> dirList;
if (creature->getPathTo(position, dirList, fpp)) {
lua_newtable(L);
int index = 0;
for (Direction dir : dirList) {
lua_pushnumber(L, dir);
lua_rawseti(L, -2, ++index);
}
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaCreatureMove(lua_State* L)
{
// creature:move(direction)
// creature:move(tile[, flags = 0])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
if (isNumber(L, 2)) {
Direction direction = getNumber<Direction>(L, 2);
if (direction > DIRECTION_LAST) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, g_game.internalMoveCreature(creature, direction, FLAG_NOLIMIT));
} else {
Tile* tile = getUserdata<Tile>(L, 2);
if (!tile) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, g_game.internalMoveCreature(*creature, *tile, getNumber<uint32_t>(L, 3)));
}
return 1;
}
// Player
int LuaScriptInterface::luaPlayerCreate(lua_State* L)
{
// Player(id or name or userdata)
Player* player;
if (isNumber(L, 2)) {
player = g_game.getPlayerByID(getNumber<uint32_t>(L, 2));
} else if (isString(L, 2)) {
ReturnValue ret = g_game.getPlayerByNameWildcard(getString(L, 2), player);
if (ret != RETURNVALUE_NOERROR) {
lua_pushnil(L);
lua_pushnumber(L, ret);
return 2;
}
} else if (isUserdata(L, 2)) {
if (getUserdataType(L, 2) != LuaData_Player) {
lua_pushnil(L);
return 1;
}
player = getUserdata<Player>(L, 2);
} else {
player = nullptr;
}
if (player) {
pushUserdata<Player>(L, player);
setMetatable(L, -1, "Player");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerIsPlayer(lua_State* L)
{
// player:isPlayer()
pushBoolean(L, getUserdata<const Player>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaPlayerGetGuid(lua_State* L)
{
// player:getGuid()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getGUID());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetIp(lua_State* L)
{
// player:getIp()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getIP());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetAccountId(lua_State* L)
{
// player:getAccountId()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getAccount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetLastLoginSaved(lua_State* L)
{
// player:getLastLoginSaved()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getLastLoginSaved());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetLastLogout(lua_State* L)
{
// player:getLastLogout()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getLastLogout());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetAccountType(lua_State* L)
{
// player:getAccountType()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getAccountType());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetAccountType(lua_State* L)
{
// player:setAccountType(accountType)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->accountType = getNumber<AccountType_t>(L, 2);
IOLoginData::setAccountType(player->getAccount(), player->accountType);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetCapacity(lua_State* L)
{
// player:getCapacity()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getCapacity());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetCapacity(lua_State* L)
{
// player:setCapacity(capacity)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->capacity = getNumber<uint32_t>(L, 2);
player->sendStats();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetFreeCapacity(lua_State* L)
{
// player:getFreeCapacity()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getFreeCapacity());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetDepotChest(lua_State* L)
{
// player:getDepotChest(depotId[, autoCreate = false])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint32_t depotId = getNumber<uint32_t>(L, 2);
bool autoCreate = getBoolean(L, 3, false);
DepotChest* depotChest = player->getDepotChest(depotId, autoCreate);
if (depotChest) {
pushUserdata<Item>(L, depotChest);
setItemMetatable(L, -1, depotChest);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetInbox(lua_State* L)
{
// player:getInbox()
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Inbox* inbox = player->getInbox();
if (inbox) {
pushUserdata<Item>(L, inbox);
setItemMetatable(L, -1, inbox);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSkullTime(lua_State* L)
{
// player:getSkullTime()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getSkullTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetSkullTime(lua_State* L)
{
// player:setSkullTime(skullTime)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setSkullTicks(getNumber<int64_t>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetDeathPenalty(lua_State* L)
{
// player:getDeathPenalty()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, static_cast<uint32_t>(player->getLostPercent() * 100));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetExperience(lua_State* L)
{
// player:getExperience()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getExperience());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddExperience(lua_State* L)
{
// player:addExperience(experience[, sendText = false])
Player* player = getUserdata<Player>(L, 1);
if (player) {
int64_t experience = getNumber<int64_t>(L, 2);
bool sendText = getBoolean(L, 3, false);
player->addExperience(nullptr, experience, sendText);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveExperience(lua_State* L)
{
// player:removeExperience(experience[, sendText = false])
Player* player = getUserdata<Player>(L, 1);
if (player) {
int64_t experience = getNumber<int64_t>(L, 2);
bool sendText = getBoolean(L, 3, false);
player->removeExperience(experience, sendText);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetLevel(lua_State* L)
{
// player:getLevel()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getLevel());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetMagicLevel(lua_State* L)
{
// player:getMagicLevel()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getMagicLevel());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetBaseMagicLevel(lua_State* L)
{
// player:getBaseMagicLevel()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getBaseMagicLevel());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetMana(lua_State* L)
{
// player:getMana()
const Player* player = getUserdata<const Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getMana());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddMana(lua_State* L)
{
// player:addMana(manaChange[, animationOnLoss = false])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
int32_t manaChange = getNumber<int32_t>(L, 2);
bool animationOnLoss = getBoolean(L, 3, false);
if (!animationOnLoss && manaChange < 0) {
player->changeMana(manaChange);
} else {
CombatDamage damage;
damage.primary.value = manaChange;
damage.origin = ORIGIN_NONE;
g_game.combatChangeMana(nullptr, player, damage);
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerGetMaxMana(lua_State* L)
{
// player:getMaxMana()
const Player* player = getUserdata<const Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getMaxMana());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetMaxMana(lua_State* L)
{
// player:setMaxMana(maxMana)
Player* player = getPlayer(L, 1);
if (player) {
player->manaMax = getNumber<int32_t>(L, 2);
player->mana = std::min<int32_t>(player->mana, player->manaMax);
player->sendStats();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetManaSpent(lua_State* L)
{
// player:getManaSpent()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getSpentMana());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddManaSpent(lua_State* L)
{
// player:addManaSpent(amount)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->addManaSpent(getNumber<uint64_t>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetBaseMaxHealth(lua_State* L)
{
// player:getBaseMaxHealth()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->healthMax);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetBaseMaxMana(lua_State* L)
{
// player:getBaseMaxMana()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->manaMax);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSkillLevel(lua_State* L)
{
// player:getSkillLevel(skillType)
skills_t skillType = getNumber<skills_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player && skillType <= SKILL_LAST) {
lua_pushnumber(L, player->skills[skillType].level);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetEffectiveSkillLevel(lua_State* L)
{
// player:getEffectiveSkillLevel(skillType)
skills_t skillType = getNumber<skills_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player && skillType <= SKILL_LAST) {
lua_pushnumber(L, player->getSkillLevel(skillType));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSkillPercent(lua_State* L)
{
// player:getSkillPercent(skillType)
skills_t skillType = getNumber<skills_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player && skillType <= SKILL_LAST) {
lua_pushnumber(L, player->skills[skillType].percent);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSkillTries(lua_State* L)
{
// player:getSkillTries(skillType)
skills_t skillType = getNumber<skills_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player && skillType <= SKILL_LAST) {
lua_pushnumber(L, player->skills[skillType].tries);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddSkillTries(lua_State* L)
{
// player:addSkillTries(skillType, tries)
Player* player = getUserdata<Player>(L, 1);
if (player) {
skills_t skillType = getNumber<skills_t>(L, 2);
uint64_t tries = getNumber<uint64_t>(L, 3);
player->addSkillAdvance(skillType, tries);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddOfflineTrainingTime(lua_State* L)
{
// player:addOfflineTrainingTime(time)
Player* player = getUserdata<Player>(L, 1);
if (player) {
int32_t time = getNumber<int32_t>(L, 2);
player->addOfflineTrainingTime(time);
player->sendStats();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetOfflineTrainingTime(lua_State* L)
{
// player:getOfflineTrainingTime()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getOfflineTrainingTime());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveOfflineTrainingTime(lua_State* L)
{
// player:removeOfflineTrainingTime(time)
Player* player = getUserdata<Player>(L, 1);
if (player) {
int32_t time = getNumber<int32_t>(L, 2);
player->removeOfflineTrainingTime(time);
player->sendStats();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddOfflineTrainingTries(lua_State* L)
{
// player:addOfflineTrainingTries(skillType, tries)
Player* player = getUserdata<Player>(L, 1);
if (player) {
skills_t skillType = getNumber<skills_t>(L, 2);
uint64_t tries = getNumber<uint64_t>(L, 3);
pushBoolean(L, player->addOfflineTrainingTries(skillType, tries));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetOfflineTrainingSkill(lua_State* L)
{
// player:getOfflineTrainingSkill()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getOfflineTrainingSkill());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetOfflineTrainingSkill(lua_State* L)
{
// player:setOfflineTrainingSkill(skillId)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint32_t skillId = getNumber<uint32_t>(L, 2);
player->setOfflineTrainingSkill(skillId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetItemCount(lua_State* L)
{
// player:getItemCount(itemId[, subType = -1])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
lua_pushnumber(L, player->getItemTypeCount(itemId, subType));
return 1;
}
int LuaScriptInterface::luaPlayerGetItemById(lua_State* L)
{
// player:getItemById(itemId, deepSearch[, subType = -1])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
bool deepSearch = getBoolean(L, 3);
int32_t subType = getNumber<int32_t>(L, 4, -1);
Item* item = g_game.findItemOfType(player, itemId, deepSearch, subType);
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetVocation(lua_State* L)
{
// player:getVocation()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushUserdata<Vocation>(L, player->getVocation());
setMetatable(L, -1, "Vocation");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetVocation(lua_State* L)
{
// player:setVocation(id or name or userdata)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Vocation* vocation;
if (isNumber(L, 2)) {
vocation = g_vocations.getVocation(getNumber<uint16_t>(L, 2));
} else if (isString(L, 2)) {
vocation = g_vocations.getVocation(g_vocations.getVocationId(getString(L, 2)));
} else if (isUserdata(L, 2)) {
vocation = getUserdata<Vocation>(L, 2);
} else {
vocation = nullptr;
}
if (!vocation) {
pushBoolean(L, false);
return 1;
}
player->setVocation(vocation->getId());
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerGetSex(lua_State* L)
{
// player:getSex()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getSex());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetSex(lua_State* L)
{
// player:setSex(newSex)
Player* player = getUserdata<Player>(L, 1);
if (player) {
PlayerSex_t newSex = getNumber<PlayerSex_t>(L, 2);
player->setSex(newSex);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetTown(lua_State* L)
{
// player:getTown()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushUserdata<Town>(L, player->getTown());
setMetatable(L, -1, "Town");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetTown(lua_State* L)
{
// player:setTown(town)
Town* town = getUserdata<Town>(L, 2);
if (!town) {
pushBoolean(L, false);
return 1;
}
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setTown(town);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetGuild(lua_State* L)
{
// player:getGuild()
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Guild* guild = player->getGuild();
if (!guild) {
lua_pushnil(L);
return 1;
}
pushUserdata<Guild>(L, guild);
setMetatable(L, -1, "Guild");
return 1;
}
int LuaScriptInterface::luaPlayerSetGuild(lua_State* L)
{
// player:setGuild(guild)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
player->setGuild(getUserdata<Guild>(L, 2));
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerGetGuildLevel(lua_State* L)
{
// player:getGuildLevel()
Player* player = getUserdata<Player>(L, 1);
if (player && player->getGuild()) {
lua_pushnumber(L, player->getGuildRank()->level);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetGuildLevel(lua_State* L)
{
// player:setGuildLevel(level)
uint8_t level = getNumber<uint8_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (!player || !player->getGuild()) {
lua_pushnil(L);
return 1;
}
const GuildRank* rank = player->getGuild()->getRankByLevel(level);
if (!rank) {
pushBoolean(L, false);
} else {
player->setGuildRank(rank);
pushBoolean(L, true);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetGuildNick(lua_State* L)
{
// player:getGuildNick()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushString(L, player->getGuildNick());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetGuildNick(lua_State* L)
{
// player:setGuildNick(nick)
const std::string& nick = getString(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setGuildNick(nick);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetGroup(lua_State* L)
{
// player:getGroup()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushUserdata<Group>(L, player->getGroup());
setMetatable(L, -1, "Group");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetGroup(lua_State* L)
{
// player:setGroup(group)
Group* group = getUserdata<Group>(L, 2);
if (!group) {
pushBoolean(L, false);
return 1;
}
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setGroup(group);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetStamina(lua_State* L)
{
// player:getStamina()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getStaminaMinutes());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetStamina(lua_State* L)
{
// player:setStamina(stamina)
uint16_t stamina = getNumber<uint16_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->staminaMinutes = std::min<uint16_t>(2520, stamina);
player->sendStats();
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSoul(lua_State* L)
{
// player:getSoul()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getSoul());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddSoul(lua_State* L)
{
// player:addSoul(soulChange)
int32_t soulChange = getNumber<int32_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->changeSoul(soulChange);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetMaxSoul(lua_State* L)
{
// player:getMaxSoul()
Player* player = getUserdata<Player>(L, 1);
if (player && player->vocation) {
lua_pushnumber(L, player->vocation->getSoulMax());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetBankBalance(lua_State* L)
{
// player:getBankBalance()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getBankBalance());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetBankBalance(lua_State* L)
{
// player:setBankBalance(bankBalance)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
int64_t balance = getNumber<int64_t>(L, 2);
if (balance < 0) {
reportErrorFunc("Invalid bank balance value.");
lua_pushnil(L);
return 1;
}
player->setBankBalance(balance);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerGetStorageValue(lua_State* L)
{
// player:getStorageValue(key)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint32_t key = getNumber<uint32_t>(L, 2);
int32_t value;
if (player->getStorageValue(key, value)) {
lua_pushnumber(L, value);
} else {
lua_pushnumber(L, -1);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetStorageValue(lua_State* L)
{
// player:setStorageValue(key, value)
int32_t value = getNumber<int32_t>(L, 3);
uint32_t key = getNumber<uint32_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (IS_IN_KEYRANGE(key, RESERVED_RANGE)) {
std::ostringstream ss;
ss << "Accessing reserved range: " << key;
reportErrorFunc(ss.str());
pushBoolean(L, false);
return 1;
}
if (player) {
player->addStorageValue(key, value);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddItem(lua_State* L)
{
// player:addItem(itemId[, count = 1[, canDropOnMap = true[, subType = 1[, slot = CONST_SLOT_WHEREEVER]]]])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
pushBoolean(L, false);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t count = getNumber<int32_t>(L, 3, 1);
int32_t subType = getNumber<int32_t>(L, 5, 1);
const ItemType& it = Item::items[itemId];
int32_t itemCount = 1;
int parameters = lua_gettop(L);
if (parameters >= 4) {
itemCount = std::max<int32_t>(1, count);
} else if (it.hasSubType()) {
if (it.stackable) {
itemCount = std::ceil(count / 100.f);
}
subType = count;
} else {
itemCount = std::max<int32_t>(1, count);
}
bool hasTable = itemCount > 1;
if (hasTable) {
lua_newtable(L);
} else if (itemCount == 0) {
lua_pushnil(L);
return 1;
}
bool canDropOnMap = getBoolean(L, 4, true);
slots_t slot = getNumber<slots_t>(L, 6, CONST_SLOT_WHEREEVER);
for (int32_t i = 1; i <= itemCount; ++i) {
int32_t stackCount = subType;
if (it.stackable) {
stackCount = std::min<int32_t>(stackCount, 100);
subType -= stackCount;
}
Item* item = Item::CreateItem(itemId, stackCount);
if (!item) {
if (!hasTable) {
lua_pushnil(L);
}
return 1;
}
ReturnValue ret = g_game.internalPlayerAddItem(player, item, canDropOnMap, slot);
if (ret != RETURNVALUE_NOERROR) {
delete item;
if (!hasTable) {
lua_pushnil(L);
}
return 1;
}
if (hasTable) {
lua_pushnumber(L, i);
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
lua_settable(L, -3);
} else {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
}
}
return 1;
}
int LuaScriptInterface::luaPlayerAddItemEx(lua_State* L)
{
// player:addItemEx(item[, canDropOnMap = false[, index = INDEX_WHEREEVER[, flags = 0]]])
// player:addItemEx(item[, canDropOnMap = true[, slot = CONST_SLOT_WHEREEVER]])
Item* item = getUserdata<Item>(L, 2);
if (!item) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
if (item->getParent() != VirtualCylinder::virtualCylinder) {
reportErrorFunc("Item already has a parent");
pushBoolean(L, false);
return 1;
}
bool canDropOnMap = getBoolean(L, 3, false);
ReturnValue returnValue;
if (canDropOnMap) {
slots_t slot = getNumber<slots_t>(L, 4, CONST_SLOT_WHEREEVER);
returnValue = g_game.internalPlayerAddItem(player, item, true, slot);
} else {
int32_t index = getNumber<int32_t>(L, 4, INDEX_WHEREEVER);
uint32_t flags = getNumber<uint32_t>(L, 5, 0);
returnValue = g_game.internalAddItem(player, item, index, flags);
}
if (returnValue == RETURNVALUE_NOERROR) {
ScriptEnvironment::removeTempItem(item);
}
lua_pushnumber(L, returnValue);
return 1;
}
int LuaScriptInterface::luaPlayerRemoveItem(lua_State* L)
{
// player:removeItem(itemId, count[, subType = -1[, ignoreEquipped = false]])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
uint32_t count = getNumber<uint32_t>(L, 3);
int32_t subType = getNumber<int32_t>(L, 4, -1);
bool ignoreEquipped = getBoolean(L, 5, false);
pushBoolean(L, player->removeItemOfType(itemId, count, subType, ignoreEquipped));
return 1;
}
int LuaScriptInterface::luaPlayerGetMoney(lua_State* L)
{
// player:getMoney()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getMoney());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddMoney(lua_State* L)
{
// player:addMoney(money)
uint64_t money = getNumber<uint64_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
g_game.addMoney(player, money);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveMoney(lua_State* L)
{
// player:removeMoney(money)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint64_t money = getNumber<uint64_t>(L, 2);
pushBoolean(L, g_game.removeMoney(player, money));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerShowTextDialog(lua_State* L)
{
// player:showTextDialog(itemId[, text[, canWrite[, length]]])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
int32_t length = getNumber<int32_t>(L, 5, -1);
bool canWrite = getBoolean(L, 4, false);
std::string text;
int parameters = lua_gettop(L);
if (parameters >= 3) {
text = getString(L, 3);
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
Item* item = Item::CreateItem(itemId);
if (!item) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (length < 0) {
length = Item::items[item->getID()].maxTextLen;
}
if (!text.empty()) {
item->setText(text);
length = std::max<int32_t>(text.size(), length);
}
item->setParent(player);
player->setWriteItem(item, length);
player->sendTextWindow(item, length, canWrite);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerSendTextMessage(lua_State* L)
{
// player:sendTextMessage(type, text[, position, primaryValue = 0, primaryColor = TEXTCOLOR_NONE[, secondaryValue = 0, secondaryColor = TEXTCOLOR_NONE]])
// player:sendTextMessage(type, text, channelId)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
int parameters = lua_gettop(L);
TextMessage message(getNumber<MessageClasses>(L, 2), getString(L, 3));
if (parameters == 4) {
uint16_t channelId = getNumber<uint16_t>(L, 4);
ChatChannel* channel = g_chat->getChannel(*player, channelId);
if (!channel || !channel->hasUser(*player)) {
pushBoolean(L, false);
return 1;
}
message.channelId = channelId;
} else {
if (parameters >= 6) {
message.position = getPosition(L, 4);
message.primary.value = getNumber<int32_t>(L, 5);
message.primary.color = getNumber<TextColor_t>(L, 6);
}
if (parameters >= 8) {
message.secondary.value = getNumber<int32_t>(L, 7);
message.secondary.color = getNumber<TextColor_t>(L, 8);
}
}
player->sendTextMessage(message);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerSendChannelMessage(lua_State* L)
{
// player:sendChannelMessage(author, text, type, channelId)
uint16_t channelId = getNumber<uint16_t>(L, 5);
SpeakClasses type = getNumber<SpeakClasses>(L, 4);
const std::string& text = getString(L, 3);
const std::string& author = getString(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->sendChannelMessage(author, text, type, channelId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSendPrivateMessage(lua_State* L)
{
// player:sendPrivateMessage(speaker, text[, type])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
const Player* speaker = getUserdata<const Player>(L, 2);
const std::string& text = getString(L, 3);
SpeakClasses type = getNumber<SpeakClasses>(L, 4, TALKTYPE_PRIVATE_FROM);
player->sendPrivateMessage(speaker, type, text);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerChannelSay(lua_State* L)
{
// player:channelSay(speaker, type, text, channelId)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Creature* speaker = getCreature(L, 2);
SpeakClasses type = getNumber<SpeakClasses>(L, 3);
const std::string& text = getString(L, 4);
uint16_t channelId = getNumber<uint16_t>(L, 5);
player->sendToChannel(speaker, type, text, channelId);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerOpenChannel(lua_State* L)
{
// player:openChannel(channelId)
uint16_t channelId = getNumber<uint16_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
g_game.playerOpenChannel(player->getID(), channelId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSlotItem(lua_State* L)
{
// player:getSlotItem(slot)
const Player* player = getUserdata<const Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint32_t slot = getNumber<uint32_t>(L, 2);
Thing* thing = player->getThing(slot);
if (!thing) {
lua_pushnil(L);
return 1;
}
Item* item = thing->getItem();
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetParty(lua_State* L)
{
// player:getParty()
const Player* player = getUserdata<const Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Party* party = player->getParty();
if (party) {
pushUserdata<Party>(L, party);
setMetatable(L, -1, "Party");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddOutfit(lua_State* L)
{
// player:addOutfit(lookType)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->addOutfit(getNumber<uint16_t>(L, 2), 0);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddOutfitAddon(lua_State* L)
{
// player:addOutfitAddon(lookType, addon)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint16_t lookType = getNumber<uint16_t>(L, 2);
uint8_t addon = getNumber<uint8_t>(L, 3);
player->addOutfit(lookType, addon);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveOutfit(lua_State* L)
{
// player:removeOutfit(lookType)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint16_t lookType = getNumber<uint16_t>(L, 2);
pushBoolean(L, player->removeOutfit(lookType));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveOutfitAddon(lua_State* L)
{
// player:removeOutfitAddon(lookType, addon)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint16_t lookType = getNumber<uint16_t>(L, 2);
uint8_t addon = getNumber<uint8_t>(L, 3);
pushBoolean(L, player->removeOutfitAddon(lookType, addon));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerHasOutfit(lua_State* L)
{
// player:hasOutfit(lookType[, addon = 0])
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint16_t lookType = getNumber<uint16_t>(L, 2);
uint8_t addon = getNumber<uint8_t>(L, 3, 0);
pushBoolean(L, player->canWear(lookType, addon));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSendOutfitWindow(lua_State* L)
{
// player:sendOutfitWindow()
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->sendOutfitWindow();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddMount(lua_State* L) {
// player:addMount(mountId or mountName)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint8_t mountId;
if (isNumber(L, 2)) {
mountId = getNumber<uint8_t>(L, 2);
} else {
Mount* mount = g_game.mounts.getMountByName(getString(L, 2));
if (!mount) {
lua_pushnil(L);
return 1;
}
mountId = mount->id;
}
pushBoolean(L, player->tameMount(mountId));
return 1;
}
int LuaScriptInterface::luaPlayerRemoveMount(lua_State* L) {
// player:removeMount(mountId or mountName)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint8_t mountId;
if (isNumber(L, 2)) {
mountId = getNumber<uint8_t>(L, 2);
} else {
Mount* mount = g_game.mounts.getMountByName(getString(L, 2));
if (!mount) {
lua_pushnil(L);
return 1;
}
mountId = mount->id;
}
pushBoolean(L, player->untameMount(mountId));
return 1;
}
int LuaScriptInterface::luaPlayerHasMount(lua_State* L) {
// player:hasMount(mountId or mountName)
const Player* player = getUserdata<const Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Mount* mount = nullptr;
if (isNumber(L, 2)) {
mount = g_game.mounts.getMountByID(getNumber<uint8_t>(L, 2));
} else {
mount = g_game.mounts.getMountByName(getString(L, 2));
}
if (mount) {
pushBoolean(L, player->hasMount(mount));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetPremiumDays(lua_State* L)
{
// player:getPremiumDays()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->premiumDays);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddPremiumDays(lua_State* L)
{
// player:addPremiumDays(days)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
if (player->premiumDays != std::numeric_limits<uint16_t>::max()) {
uint16_t days = getNumber<uint16_t>(L, 2);
int32_t addDays = std::min<int32_t>(0xFFFE - player->premiumDays, days);
if (addDays > 0) {
player->setPremiumDays(player->premiumDays + addDays);
IOLoginData::addPremiumDays(player->getAccount(), addDays);
}
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerRemovePremiumDays(lua_State* L)
{
// player:removePremiumDays(days)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
if (player->premiumDays != std::numeric_limits<uint16_t>::max()) {
uint16_t days = getNumber<uint16_t>(L, 2);
int32_t removeDays = std::min<int32_t>(player->premiumDays, days);
if (removeDays > 0) {
player->setPremiumDays(player->premiumDays - removeDays);
IOLoginData::removePremiumDays(player->getAccount(), removeDays);
}
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerHasBlessing(lua_State* L)
{
// player:hasBlessing(blessing)
uint8_t blessing = getNumber<uint8_t>(L, 2) - 1;
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushBoolean(L, player->hasBlessing(blessing));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddBlessing(lua_State* L)
{
// player:addBlessing(blessing)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint8_t blessing = getNumber<uint8_t>(L, 2) - 1;
if (player->hasBlessing(blessing)) {
pushBoolean(L, false);
return 1;
}
player->addBlessing(1 << blessing);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerRemoveBlessing(lua_State* L)
{
// player:removeBlessing(blessing)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint8_t blessing = getNumber<uint8_t>(L, 2) - 1;
if (!player->hasBlessing(blessing)) {
pushBoolean(L, false);
return 1;
}
player->removeBlessing(1 << blessing);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerCanLearnSpell(lua_State* L)
{
// player:canLearnSpell(spellName)
const Player* player = getUserdata<const Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
const std::string& spellName = getString(L, 2);
InstantSpell* spell = g_spells->getInstantSpellByName(spellName);
if (!spell) {
reportErrorFunc("Spell \"" + spellName + "\" not found");
pushBoolean(L, false);
return 1;
}
if (player->hasFlag(PlayerFlag_IgnoreSpellCheck)) {
pushBoolean(L, true);
return 1;
}
const auto& vocMap = spell->getVocMap();
if (vocMap.count(player->getVocationId()) == 0) {
pushBoolean(L, false);
} else if (player->getLevel() < spell->getLevel()) {
pushBoolean(L, false);
} else if (player->getMagicLevel() < spell->getMagicLevel()) {
pushBoolean(L, false);
} else {
pushBoolean(L, true);
}
return 1;
}
int LuaScriptInterface::luaPlayerLearnSpell(lua_State* L)
{
// player:learnSpell(spellName)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const std::string& spellName = getString(L, 2);
player->learnInstantSpell(spellName);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerForgetSpell(lua_State* L)
{
// player:forgetSpell(spellName)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const std::string& spellName = getString(L, 2);
player->forgetInstantSpell(spellName);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerHasLearnedSpell(lua_State* L)
{
// player:hasLearnedSpell(spellName)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const std::string& spellName = getString(L, 2);
pushBoolean(L, player->hasLearnedInstantSpell(spellName));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSendTutorial(lua_State* L)
{
// player:sendTutorial(tutorialId)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint8_t tutorialId = getNumber<uint8_t>(L, 2);
player->sendTutorial(tutorialId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddMapMark(lua_State* L)
{
// player:addMapMark(position, type, description)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const Position& position = getPosition(L, 2);
uint8_t type = getNumber<uint8_t>(L, 3);
const std::string& description = getString(L, 4);
player->sendAddMarker(position, type, description);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSave(lua_State* L)
{
// player:save()
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->loginPosition = player->getPosition();
pushBoolean(L, IOLoginData::savePlayer(player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerPopupFYI(lua_State* L)
{
// player:popupFYI(message)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const std::string& message = getString(L, 2);
player->sendFYIBox(message);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerIsPzLocked(lua_State* L)
{
// player:isPzLocked()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushBoolean(L, player->isPzLocked());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetClient(lua_State* L)
{
// player:getClient()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_createtable(L, 0, 2);
setField(L, "version", player->getProtocolVersion());
setField(L, "os", player->getOperatingSystem());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetHouse(lua_State* L)
{
// player:getHouse()
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
House* house = g_game.map.houses.getHouseByPlayerId(player->getGUID());
if (house) {
pushUserdata<House>(L, house);
setMetatable(L, -1, "House");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSendHouseWindow(lua_State* L)
{
// player:sendHouseWindow(house, listId)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
House* house = getUserdata<House>(L, 2);
if (!house) {
lua_pushnil(L);
return 1;
}
uint32_t listId = getNumber<uint32_t>(L, 3);
player->sendHouseWindow(house, listId);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerSetEditHouse(lua_State* L)
{
// player:setEditHouse(house, listId)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
House* house = getUserdata<House>(L, 2);
if (!house) {
lua_pushnil(L);
return 1;
}
uint32_t listId = getNumber<uint32_t>(L, 3);
player->setEditHouse(house, listId);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerSetGhostMode(lua_State* L)
{
// player:setGhostMode(enabled[, showEffect=true])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
bool enabled = getBoolean(L, 2);
if (player->isInGhostMode() == enabled) {
pushBoolean(L, true);
return 1;
}
bool showEffect = getBoolean(L, 3, true);
player->switchGhostMode();
Tile* tile = player->getTile();
const Position& position = player->getPosition();
SpectatorHashSet spectators;
g_game.map.getSpectators(spectators, position, true, true);
for (Creature* spectator : spectators) {
Player* tmpPlayer = spectator->getPlayer();
if (tmpPlayer != player && !tmpPlayer->isAccessPlayer()) {
if (enabled) {
tmpPlayer->sendRemoveTileThing(position, tile->getStackposOfCreature(tmpPlayer, player));
} else {
tmpPlayer->sendCreatureAppear(player, position, showEffect);
}
} else {
tmpPlayer->sendCreatureChangeVisible(player, !enabled);
}
}
if (player->isInGhostMode()) {
for (const auto& it : g_game.getPlayers()) {
if (!it.second->isAccessPlayer()) {
it.second->notifyStatusChange(player, VIPSTATUS_OFFLINE);
}
}
IOLoginData::updateOnlineStatus(player->getGUID(), false);
} else {
for (const auto& it : g_game.getPlayers()) {
if (!it.second->isAccessPlayer()) {
it.second->notifyStatusChange(player, VIPSTATUS_ONLINE);
}
}
IOLoginData::updateOnlineStatus(player->getGUID(), true);
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerGetContainerId(lua_State* L)
{
// player:getContainerId(container)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Container* container = getUserdata<Container>(L, 2);
if (container) {
lua_pushnumber(L, player->getContainerID(container));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetContainerById(lua_State* L)
{
// player:getContainerById(id)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Container* container = player->getContainerByID(getNumber<uint8_t>(L, 2));
if (container) {
pushUserdata<Container>(L, container);
setMetatable(L, -1, "Container");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetContainerIndex(lua_State* L)
{
// player:getContainerIndex(id)
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getContainerIndex(getNumber<uint8_t>(L, 2)));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetInstantSpells(lua_State* L)
{
// player:getInstantSpells()
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
std::vector<InstantSpell*> spells;
for (auto spell : g_spells->getInstantSpells()) {
if (spell.second->canCast(player)) {
spells.push_back(spell.second);
}
}
lua_createtable(L, spells.size(), 0);
int index = 0;
for (auto spell : spells) {
pushInstantSpell(L, *spell);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaPlayerCanCast(lua_State* L)
{
// player:canCast(spell)
Player* player = getUserdata<Player>(L, 1);
InstantSpell* spell = getUserdata<InstantSpell>(L, 2);
if (player && spell) {
pushBoolean(L, spell->canCast(player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerHasChaseMode(lua_State* L)
{
// player:hasChaseMode()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushBoolean(L, player->chaseMode);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerHasSecureMode(lua_State* L)
{
// player:hasSecureMode()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushBoolean(L, player->secureMode);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetFightMode(lua_State* L)
{
// player:getFightMode()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->fightMode);
} else {
lua_pushnil(L);
}
return 1;
}
// Monster
int LuaScriptInterface::luaMonsterCreate(lua_State* L)
{
// Monster(id or userdata)
Monster* monster;
if (isNumber(L, 2)) {
monster = g_game.getMonsterByID(getNumber<uint32_t>(L, 2));
} else if (isUserdata(L, 2)) {
if (getUserdataType(L, 2) != LuaData_Monster) {
lua_pushnil(L);
return 1;
}
monster = getUserdata<Monster>(L, 2);
} else {
monster = nullptr;
}
if (monster) {
pushUserdata<Monster>(L, monster);
setMetatable(L, -1, "Monster");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsMonster(lua_State* L)
{
// monster:isMonster()
pushBoolean(L, getUserdata<const Monster>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaMonsterGetType(lua_State* L)
{
// monster:getType()
const Monster* monster = getUserdata<const Monster>(L, 1);
if (monster) {
pushUserdata<MonsterType>(L, monster->mType);
setMetatable(L, -1, "MonsterType");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterGetSpawnPosition(lua_State* L)
{
// monster:getSpawnPosition()
const Monster* monster = getUserdata<const Monster>(L, 1);
if (monster) {
pushPosition(L, monster->getMasterPos());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsInSpawnRange(lua_State* L)
{
// monster:isInSpawnRange([position])
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
pushBoolean(L, monster->isInSpawnRange(lua_gettop(L) >= 2 ? getPosition(L, 2) : monster->getPosition()));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsIdle(lua_State* L)
{
// monster:isIdle()
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
pushBoolean(L, monster->getIdleStatus());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterSetIdle(lua_State* L)
{
// monster:setIdle(idle)
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
monster->setIdle(getBoolean(L, 2));
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaMonsterIsTarget(lua_State* L)
{
// monster:isTarget(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
const Creature* creature = getCreature(L, 2);
pushBoolean(L, monster->isTarget(creature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsOpponent(lua_State* L)
{
// monster:isOpponent(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
const Creature* creature = getCreature(L, 2);
pushBoolean(L, monster->isOpponent(creature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsFriend(lua_State* L)
{
// monster:isFriend(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
const Creature* creature = getCreature(L, 2);
pushBoolean(L, monster->isFriend(creature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterAddFriend(lua_State* L)
{
// monster:addFriend(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
Creature* creature = getCreature(L, 2);
monster->addFriend(creature);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterRemoveFriend(lua_State* L)
{
// monster:removeFriend(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
Creature* creature = getCreature(L, 2);
monster->removeFriend(creature);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterGetFriendList(lua_State* L)
{
// monster:getFriendList()
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
const auto& friendList = monster->getFriendList();
lua_createtable(L, friendList.size(), 0);
int index = 0;
for (Creature* creature : friendList) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterGetFriendCount(lua_State* L)
{
// monster:getFriendCount()
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
lua_pushnumber(L, monster->getFriendList().size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterAddTarget(lua_State* L)
{
// monster:addTarget(creature[, pushFront = false])
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
Creature* creature = getCreature(L, 2);
bool pushFront = getBoolean(L, 3, false);
monster->addTarget(creature, pushFront);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaMonsterRemoveTarget(lua_State* L)
{
// monster:removeTarget(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
monster->removeTarget(getCreature(L, 2));
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaMonsterGetTargetList(lua_State* L)
{
// monster:getTargetList()
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
const auto& targetList = monster->getTargetList();
lua_createtable(L, targetList.size(), 0);
int index = 0;
for (Creature* creature : targetList) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterGetTargetCount(lua_State* L)
{
// monster:getTargetCount()
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
lua_pushnumber(L, monster->getTargetList().size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterSelectTarget(lua_State* L)
{
// monster:selectTarget(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
Creature* creature = getCreature(L, 2);
pushBoolean(L, monster->selectTarget(creature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterSearchTarget(lua_State* L)
{
// monster:searchTarget([searchType = TARGETSEARCH_DEFAULT])
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
TargetSearchType_t searchType = getNumber<TargetSearchType_t>(L, 2, TARGETSEARCH_DEFAULT);
pushBoolean(L, monster->searchTarget(searchType));
} else {
lua_pushnil(L);
}
return 1;
}
// Npc
int LuaScriptInterface::luaNpcCreate(lua_State* L)
{
// Npc([id or name or userdata])
Npc* npc;
if (lua_gettop(L) >= 2) {
if (isNumber(L, 2)) {
npc = g_game.getNpcByID(getNumber<uint32_t>(L, 2));
} else if (isString(L, 2)) {
npc = g_game.getNpcByName(getString(L, 2));
} else if (isUserdata(L, 2)) {
if (getUserdataType(L, 2) != LuaData_Npc) {
lua_pushnil(L);
return 1;
}
npc = getUserdata<Npc>(L, 2);
} else {
npc = nullptr;
}
} else {
npc = getScriptEnv()->getNpc();
}
if (npc) {
pushUserdata<Npc>(L, npc);
setMetatable(L, -1, "Npc");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNpcIsNpc(lua_State* L)
{
// npc:isNpc()
pushBoolean(L, getUserdata<const Npc>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaNpcSetMasterPos(lua_State* L)
{
// npc:setMasterPos(pos[, radius])
Npc* npc = getUserdata<Npc>(L, 1);
if (!npc) {
lua_pushnil(L);
return 1;
}
const Position& pos = getPosition(L, 2);
int32_t radius = getNumber<int32_t>(L, 3, 1);
npc->setMasterPos(pos, radius);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaNpcGetSpeechBubble(lua_State* L)
{
// npc:getSpeechBubble()
Npc* npc = getUserdata<Npc>(L, 1);
if (npc) {
lua_pushnumber(L, npc->getSpeechBubble());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNpcSetSpeechBubble(lua_State* L)
{
// npc:setSpeechBubble(speechBubble)
Npc* npc = getUserdata<Npc>(L, 1);
if (npc) {
npc->setSpeechBubble(getNumber<uint8_t>(L, 2));
}
return 0;
}
// Guild
int LuaScriptInterface::luaGuildCreate(lua_State* L)
{
// Guild(id)
uint32_t id = getNumber<uint32_t>(L, 2);
Guild* guild = g_game.getGuild(id);
if (guild) {
pushUserdata<Guild>(L, guild);
setMetatable(L, -1, "Guild");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetId(lua_State* L)
{
// guild:getId()
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
lua_pushnumber(L, guild->getId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetName(lua_State* L)
{
// guild:getName()
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
pushString(L, guild->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetMembersOnline(lua_State* L)
{
// guild:getMembersOnline()
const Guild* guild = getUserdata<const Guild>(L, 1);
if (!guild) {
lua_pushnil(L);
return 1;
}
const auto& members = guild->getMembersOnline();
lua_createtable(L, members.size(), 0);
int index = 0;
for (Player* player : members) {
pushUserdata<Player>(L, player);
setMetatable(L, -1, "Player");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGuildAddRank(lua_State* L)
{
// guild:addRank(id, name, level)
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
uint32_t id = getNumber<uint32_t>(L, 2);
const std::string& name = getString(L, 3);
uint8_t level = getNumber<uint8_t>(L, 4);
guild->addRank(id, name, level);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetRankById(lua_State* L)
{
// guild:getRankById(id)
Guild* guild = getUserdata<Guild>(L, 1);
if (!guild) {
lua_pushnil(L);
return 1;
}
uint32_t id = getNumber<uint32_t>(L, 2);
GuildRank* rank = guild->getRankById(id);
if (rank) {
lua_createtable(L, 0, 3);
setField(L, "id", rank->id);
setField(L, "name", rank->name);
setField(L, "level", rank->level);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetRankByLevel(lua_State* L)
{
// guild:getRankByLevel(level)
const Guild* guild = getUserdata<const Guild>(L, 1);
if (!guild) {
lua_pushnil(L);
return 1;
}
uint8_t level = getNumber<uint8_t>(L, 2);
const GuildRank* rank = guild->getRankByLevel(level);
if (rank) {
lua_createtable(L, 0, 3);
setField(L, "id", rank->id);
setField(L, "name", rank->name);
setField(L, "level", rank->level);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetMotd(lua_State* L)
{
// guild:getMotd()
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
pushString(L, guild->getMotd());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildSetMotd(lua_State* L)
{
// guild:setMotd(motd)
const std::string& motd = getString(L, 2);
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
guild->setMotd(motd);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
// Group
int LuaScriptInterface::luaGroupCreate(lua_State* L)
{
// Group(id)
uint32_t id = getNumber<uint32_t>(L, 2);
Group* group = g_game.groups.getGroup(id);
if (group) {
pushUserdata<Group>(L, group);
setMetatable(L, -1, "Group");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetId(lua_State* L)
{
// group:getId()
Group* group = getUserdata<Group>(L, 1);
if (group) {
lua_pushnumber(L, group->id);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetName(lua_State* L)
{
// group:getName()
Group* group = getUserdata<Group>(L, 1);
if (group) {
pushString(L, group->name);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetFlags(lua_State* L)
{
// group:getFlags()
Group* group = getUserdata<Group>(L, 1);
if (group) {
lua_pushnumber(L, group->flags);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetAccess(lua_State* L)
{
// group:getAccess()
Group* group = getUserdata<Group>(L, 1);
if (group) {
pushBoolean(L, group->access);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetMaxDepotItems(lua_State* L)
{
// group:getMaxDepotItems()
Group* group = getUserdata<Group>(L, 1);
if (group) {
lua_pushnumber(L, group->maxDepotItems);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetMaxVipEntries(lua_State* L)
{
// group:getMaxVipEntries()
Group* group = getUserdata<Group>(L, 1);
if (group) {
lua_pushnumber(L, group->maxVipEntries);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupHasFlag(lua_State* L)
{
// group:hasFlag(flag)
Group* group = getUserdata<Group>(L, 1);
if (group) {
PlayerFlags flag = getNumber<PlayerFlags>(L, 2);
pushBoolean(L, (group->flags & flag) != 0);
} else {
lua_pushnil(L);
}
return 1;
}
// Vocation
int LuaScriptInterface::luaVocationCreate(lua_State* L)
{
// Vocation(id or name)
uint32_t id;
if (isNumber(L, 2)) {
id = getNumber<uint32_t>(L, 2);
} else {
id = g_vocations.getVocationId(getString(L, 2));
}
Vocation* vocation = g_vocations.getVocation(id);
if (vocation) {
pushUserdata<Vocation>(L, vocation);
setMetatable(L, -1, "Vocation");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetId(lua_State* L)
{
// vocation:getId()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetClientId(lua_State* L)
{
// vocation:getClientId()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getClientId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetName(lua_State* L)
{
// vocation:getName()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
pushString(L, vocation->getVocName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetDescription(lua_State* L)
{
// vocation:getDescription()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
pushString(L, vocation->getVocDescription());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetRequiredSkillTries(lua_State* L)
{
// vocation:getRequiredSkillTries(skillType, skillLevel)
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
skills_t skillType = getNumber<skills_t>(L, 2);
uint16_t skillLevel = getNumber<uint16_t>(L, 3);
lua_pushnumber(L, vocation->getReqSkillTries(skillType, skillLevel));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetRequiredManaSpent(lua_State* L)
{
// vocation:getRequiredManaSpent(magicLevel)
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
uint32_t magicLevel = getNumber<uint32_t>(L, 2);
lua_pushnumber(L, vocation->getReqMana(magicLevel));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetCapacityGain(lua_State* L)
{
// vocation:getCapacityGain()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getCapGain());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetHealthGain(lua_State* L)
{
// vocation:getHealthGain()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getHPGain());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetHealthGainTicks(lua_State* L)
{
// vocation:getHealthGainTicks()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getHealthGainTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetHealthGainAmount(lua_State* L)
{
// vocation:getHealthGainAmount()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getHealthGainAmount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetManaGain(lua_State* L)
{
// vocation:getManaGain()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getManaGain());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetManaGainTicks(lua_State* L)
{
// vocation:getManaGainTicks()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getManaGainTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetManaGainAmount(lua_State* L)
{
// vocation:getManaGainAmount()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getManaGainAmount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetMaxSoul(lua_State* L)
{
// vocation:getMaxSoul()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getSoulMax());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetSoulGainTicks(lua_State* L)
{
// vocation:getSoulGainTicks()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getSoulGainTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetAttackSpeed(lua_State* L)
{
// vocation:getAttackSpeed()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getAttackSpeed());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetBaseSpeed(lua_State* L)
{
// vocation:getBaseSpeed()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getBaseSpeed());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetDemotion(lua_State* L)
{
// vocation:getDemotion()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (!vocation) {
lua_pushnil(L);
return 1;
}
uint16_t fromId = vocation->getFromVocation();
if (fromId == VOCATION_NONE) {
lua_pushnil(L);
return 1;
}
Vocation* demotedVocation = g_vocations.getVocation(fromId);
if (demotedVocation && demotedVocation != vocation) {
pushUserdata<Vocation>(L, demotedVocation);
setMetatable(L, -1, "Vocation");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetPromotion(lua_State* L)
{
// vocation:getPromotion()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (!vocation) {
lua_pushnil(L);
return 1;
}
uint16_t promotedId = g_vocations.getPromotedVocation(vocation->getId());
if (promotedId == VOCATION_NONE) {
lua_pushnil(L);
return 1;
}
Vocation* promotedVocation = g_vocations.getVocation(promotedId);
if (promotedVocation && promotedVocation != vocation) {
pushUserdata<Vocation>(L, promotedVocation);
setMetatable(L, -1, "Vocation");
} else {
lua_pushnil(L);
}
return 1;
}
// Town
int LuaScriptInterface::luaTownCreate(lua_State* L)
{
// Town(id or name)
Town* town;
if (isNumber(L, 2)) {
town = g_game.map.towns.getTown(getNumber<uint32_t>(L, 2));
} else if (isString(L, 2)) {
town = g_game.map.towns.getTown(getString(L, 2));
} else {
town = nullptr;
}
if (town) {
pushUserdata<Town>(L, town);
setMetatable(L, -1, "Town");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTownGetId(lua_State* L)
{
// town:getId()
Town* town = getUserdata<Town>(L, 1);
if (town) {
lua_pushnumber(L, town->getID());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTownGetName(lua_State* L)
{
// town:getName()
Town* town = getUserdata<Town>(L, 1);
if (town) {
pushString(L, town->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTownGetTemplePosition(lua_State* L)
{
// town:getTemplePosition()
Town* town = getUserdata<Town>(L, 1);
if (town) {
pushPosition(L, town->getTemplePosition());
} else {
lua_pushnil(L);
}
return 1;
}
// House
int LuaScriptInterface::luaHouseCreate(lua_State* L)
{
// House(id)
House* house = g_game.map.houses.getHouse(getNumber<uint32_t>(L, 2));
if (house) {
pushUserdata<House>(L, house);
setMetatable(L, -1, "House");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetId(lua_State* L)
{
// house:getId()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetName(lua_State* L)
{
// house:getName()
House* house = getUserdata<House>(L, 1);
if (house) {
pushString(L, house->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetTown(lua_State* L)
{
// house:getTown()
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
Town* town = g_game.map.towns.getTown(house->getTownId());
if (town) {
pushUserdata<Town>(L, town);
setMetatable(L, -1, "Town");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetExitPosition(lua_State* L)
{
// house:getExitPosition()
House* house = getUserdata<House>(L, 1);
if (house) {
pushPosition(L, house->getEntryPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetRent(lua_State* L)
{
// house:getRent()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getRent());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetOwnerGuid(lua_State* L)
{
// house:getOwnerGuid()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getOwner());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseSetOwnerGuid(lua_State* L)
{
// house:setOwnerGuid(guid[, updateDatabase = true])
House* house = getUserdata<House>(L, 1);
if (house) {
uint32_t guid = getNumber<uint32_t>(L, 2);
bool updateDatabase = getBoolean(L, 3, true);
house->setOwner(guid, updateDatabase);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseStartTrade(lua_State* L)
{
// house:startTrade(player, tradePartner)
House* house = getUserdata<House>(L, 1);
Player* player = getUserdata<Player>(L, 2);
Player* tradePartner = getUserdata<Player>(L, 3);
if (!player || !tradePartner || !house) {
lua_pushnil(L);
return 1;
}
if (!Position::areInRange<2, 2, 0>(tradePartner->getPosition(), player->getPosition())) {
lua_pushnumber(L, RETURNVALUE_TRADEPLAYERFARAWAY);
return 1;
}
if (house->getOwner() != player->getGUID()) {
lua_pushnumber(L, RETURNVALUE_YOUDONTOWNTHISHOUSE);
return 1;
}
if (g_game.map.houses.getHouseByPlayerId(tradePartner->getGUID())) {
lua_pushnumber(L, RETURNVALUE_TRADEPLAYERALREADYOWNSAHOUSE);
return 1;
}
if (IOLoginData::hasBiddedOnHouse(tradePartner->getGUID())) {
lua_pushnumber(L, RETURNVALUE_TRADEPLAYERHIGHESTBIDDER);
return 1;
}
Item* transferItem = house->getTransferItem();
if (!transferItem) {
lua_pushnumber(L, RETURNVALUE_YOUCANNOTTRADETHISHOUSE);
return 1;
}
transferItem->getParent()->setParent(player);
if (!g_game.internalStartTrade(player, tradePartner, transferItem)) {
house->resetTransferItem();
}
lua_pushnumber(L, RETURNVALUE_NOERROR);
return 1;
}
int LuaScriptInterface::luaHouseGetBeds(lua_State* L)
{
// house:getBeds()
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
const auto& beds = house->getBeds();
lua_createtable(L, beds.size(), 0);
int index = 0;
for (BedItem* bedItem : beds) {
pushUserdata<Item>(L, bedItem);
setItemMetatable(L, -1, bedItem);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaHouseGetBedCount(lua_State* L)
{
// house:getBedCount()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getBedCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetDoors(lua_State* L)
{
// house:getDoors()
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
const auto& doors = house->getDoors();
lua_createtable(L, doors.size(), 0);
int index = 0;
for (Door* door : doors) {
pushUserdata<Item>(L, door);
setItemMetatable(L, -1, door);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaHouseGetDoorCount(lua_State* L)
{
// house:getDoorCount()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getDoors().size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetDoorIdByPosition(lua_State* L)
{
// house:getDoorIdByPosition(position)
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
Door* door = house->getDoorByPosition(getPosition(L, 2));
if (door) {
lua_pushnumber(L, door->getDoorId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetTiles(lua_State* L)
{
// house:getTiles()
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
const auto& tiles = house->getTiles();
lua_createtable(L, tiles.size(), 0);
int index = 0;
for (Tile* tile : tiles) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaHouseGetTileCount(lua_State* L)
{
// house:getTileCount()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getTiles().size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseCanEditAccessList(lua_State* L)
{
// house:canEditAccessList(listId, player)
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
uint32_t listId = getNumber<uint32_t>(L, 2);
Player* player = getPlayer(L, 3);
pushBoolean(L, house->canEditAccessList(listId, player));
return 1;
}
int LuaScriptInterface::luaHouseGetAccessList(lua_State* L)
{
// house:getAccessList(listId)
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
std::string list;
uint32_t listId = getNumber<uint32_t>(L, 2);
if (house->getAccessList(listId, list)) {
pushString(L, list);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaHouseSetAccessList(lua_State* L)
{
// house:setAccessList(listId, list)
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
uint32_t listId = getNumber<uint32_t>(L, 2);
const std::string& list = getString(L, 3);
house->setAccessList(listId, list);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaHouseKickPlayer(lua_State* L)
{
// house:kickPlayer(player, targetPlayer)
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
pushBoolean(L, house->kickPlayer(getPlayer(L, 2), getPlayer(L, 3)));
return 1;
}
// ItemType
int LuaScriptInterface::luaItemTypeCreate(lua_State* L)
{
// ItemType(id or name)
uint32_t id;
if (isNumber(L, 2)) {
id = getNumber<uint32_t>(L, 2);
} else {
id = Item::items.getItemIdByName(getString(L, 2));
}
const ItemType& itemType = Item::items[id];
pushUserdata<const ItemType>(L, &itemType);
setMetatable(L, -1, "ItemType");
return 1;
}
int LuaScriptInterface::luaItemTypeIsCorpse(lua_State* L)
{
// itemType:isCorpse()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->corpseType != RACE_NONE);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsDoor(lua_State* L)
{
// itemType:isDoor()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isDoor());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsContainer(lua_State* L)
{
// itemType:isContainer()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isContainer());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsFluidContainer(lua_State* L)
{
// itemType:isFluidContainer()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isFluidContainer());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsMovable(lua_State* L)
{
// itemType:isMovable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->moveable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsRune(lua_State* L)
{
// itemType:isRune()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isRune());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsStackable(lua_State* L)
{
// itemType:isStackable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->stackable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsReadable(lua_State* L)
{
// itemType:isReadable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->canReadText);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsWritable(lua_State* L)
{
// itemType:isWritable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->canWriteText);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsBlocking(lua_State* L)
{
// itemType:isBlocking()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->blockProjectile || itemType->blockSolid);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsGroundTile(lua_State* L)
{
// itemType:isGroundTile()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isGroundTile());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsMagicField(lua_State* L)
{
// itemType:isMagicField()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isMagicField());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsUseable(lua_State* L)
{
// itemType:isUseable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isUseable());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsPickupable(lua_State* L)
{
// itemType:isPickupable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isPickupable());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetType(lua_State* L)
{
// itemType:getType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->type);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetId(lua_State* L)
{
// itemType:getId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->id);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetClientId(lua_State* L)
{
// itemType:getClientId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->clientId);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetName(lua_State* L)
{
// itemType:getName()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushString(L, itemType->name);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetPluralName(lua_State* L)
{
// itemType:getPluralName()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushString(L, itemType->getPluralName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetArticle(lua_State* L)
{
// itemType:getArticle()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushString(L, itemType->article);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetDescription(lua_State* L)
{
// itemType:getDescription()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushString(L, itemType->description);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetSlotPosition(lua_State *L)
{
// itemType:getSlotPosition()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->slotPosition);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetCharges(lua_State* L)
{
// itemType:getCharges()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->charges);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetFluidSource(lua_State* L)
{
// itemType:getFluidSource()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->fluidSource);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetCapacity(lua_State* L)
{
// itemType:getCapacity()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->maxItems);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetWeight(lua_State* L)
{
// itemType:getWeight([count = 1])
uint16_t count = getNumber<uint16_t>(L, 2, 1);
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (!itemType) {
lua_pushnil(L);
return 1;
}
uint64_t weight = static_cast<uint64_t>(itemType->weight) * std::max<int32_t>(1, count);
lua_pushnumber(L, weight);
return 1;
}
int LuaScriptInterface::luaItemTypeGetHitChance(lua_State* L)
{
// itemType:getHitChance()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->hitChance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetShootRange(lua_State* L)
{
// itemType:getShootRange()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->shootRange);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetAttack(lua_State* L)
{
// itemType:getAttack()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->attack);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetDefense(lua_State* L)
{
// itemType:getDefense()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->defense);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetExtraDefense(lua_State* L)
{
// itemType:getExtraDefense()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->extraDefense);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetArmor(lua_State* L)
{
// itemType:getArmor()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->armor);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetWeaponType(lua_State* L)
{
// itemType:getWeaponType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->weaponType);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetAmmoType(lua_State* L)
{
// itemType:getAmmoType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->ammoType);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetCorpseType(lua_State* L)
{
// itemType:getCorpseType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->corpseType);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetElementType(lua_State* L)
{
// itemType:getElementType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (!itemType) {
lua_pushnil(L);
return 1;
}
auto& abilities = itemType->abilities;
if (abilities) {
lua_pushnumber(L, abilities->elementType);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetElementDamage(lua_State* L)
{
// itemType:getElementDamage()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (!itemType) {
lua_pushnil(L);
return 1;
}
auto& abilities = itemType->abilities;
if (abilities) {
lua_pushnumber(L, abilities->elementDamage);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetTransformEquipId(lua_State* L)
{
// itemType:getTransformEquipId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->transformEquipTo);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetTransformDeEquipId(lua_State* L)
{
// itemType:getTransformDeEquipId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->transformDeEquipTo);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetDestroyId(lua_State* L)
{
// itemType:getDestroyId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->destroyTo);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetDecayId(lua_State* L)
{
// itemType:getDecayId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->decayTo);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetRequiredLevel(lua_State* L)
{
// itemType:getRequiredLevel()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->minReqLevel);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeHasSubType(lua_State* L)
{
// itemType:hasSubType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->hasSubType());
} else {
lua_pushnil(L);
}
return 1;
}
// Combat
int LuaScriptInterface::luaCombatCreate(lua_State* L)
{
// Combat()
pushUserdata<Combat>(L, g_luaEnvironment.createCombatObject(getScriptEnv()->getScriptInterface()));
setMetatable(L, -1, "Combat");
return 1;
}
int LuaScriptInterface::luaCombatSetParameter(lua_State* L)
{
// combat:setParameter(key, value)
Combat* combat = getUserdata<Combat>(L, 1);
if (!combat) {
lua_pushnil(L);
return 1;
}
CombatParam_t key = getNumber<CombatParam_t>(L, 2);
uint32_t value;
if (isBoolean(L, 3)) {
value = getBoolean(L, 3) ? 1 : 0;
} else {
value = getNumber<uint32_t>(L, 3);
}
combat->setParam(key, value);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCombatSetFormula(lua_State* L)
{
// combat:setFormula(type, mina, minb, maxa, maxb)
Combat* combat = getUserdata<Combat>(L, 1);
if (!combat) {
lua_pushnil(L);
return 1;
}
formulaType_t type = getNumber<formulaType_t>(L, 2);
double mina = getNumber<double>(L, 3);
double minb = getNumber<double>(L, 4);
double maxa = getNumber<double>(L, 5);
double maxb = getNumber<double>(L, 6);
combat->setPlayerCombatValues(type, mina, minb, maxa, maxb);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCombatSetArea(lua_State* L)
{
// combat:setArea(area)
if (getScriptEnv()->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
lua_pushnil(L);
return 1;
}
const AreaCombat* area = g_luaEnvironment.getAreaObject(getNumber<uint32_t>(L, 2));
if (!area) {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
lua_pushnil(L);
return 1;
}
Combat* combat = getUserdata<Combat>(L, 1);
if (combat) {
combat->setArea(new AreaCombat(*area));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCombatAddCondition(lua_State* L)
{
// combat:addCondition(condition)
Condition* condition = getUserdata<Condition>(L, 2);
Combat* combat = getUserdata<Combat>(L, 1);
if (combat && condition) {
combat->addCondition(condition->clone());
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCombatSetCallback(lua_State* L)
{
// combat:setCallback(key, function)
Combat* combat = getUserdata<Combat>(L, 1);
if (!combat) {
lua_pushnil(L);
return 1;
}
CallBackParam_t key = getNumber<CallBackParam_t>(L, 2);
if (!combat->setCallback(key)) {
lua_pushnil(L);
return 1;
}
CallBack* callback = combat->getCallback(key);
if (!callback) {
lua_pushnil(L);
return 1;
}
const std::string& function = getString(L, 3);
pushBoolean(L, callback->loadCallBack(getScriptEnv()->getScriptInterface(), function));
return 1;
}
int LuaScriptInterface::luaCombatSetOrigin(lua_State* L)
{
// combat:setOrigin(origin)
Combat* combat = getUserdata<Combat>(L, 1);
if (combat) {
combat->setOrigin(getNumber<CombatOrigin>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCombatExecute(lua_State* L)
{
// combat:execute(creature, variant)
Combat* combat = getUserdata<Combat>(L, 1);
if (!combat) {
pushBoolean(L, false);
return 1;
}
Creature* creature = getCreature(L, 2);
const LuaVariant& variant = getVariant(L, 3);
switch (variant.type) {
case VARIANT_NUMBER: {
Creature* target = g_game.getCreatureByID(variant.number);
if (!target) {
pushBoolean(L, false);
return 1;
}
if (combat->hasArea()) {
combat->doCombat(creature, target->getPosition());
} else {
combat->doCombat(creature, target);
}
break;
}
case VARIANT_POSITION: {
combat->doCombat(creature, variant.pos);
break;
}
case VARIANT_TARGETPOSITION: {
if (combat->hasArea()) {
combat->doCombat(creature, variant.pos);
} else {
combat->postCombatEffects(creature, variant.pos);
g_game.addMagicEffect(variant.pos, CONST_ME_POFF);
}
break;
}
case VARIANT_STRING: {
Player* target = g_game.getPlayerByName(variant.text);
if (!target) {
pushBoolean(L, false);
return 1;
}
combat->doCombat(creature, target);
break;
}
case VARIANT_NONE: {
reportErrorFunc(getErrorDesc(LUA_ERROR_VARIANT_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
default: {
break;
}
}
pushBoolean(L, true);
return 1;
}
// Condition
int LuaScriptInterface::luaConditionCreate(lua_State* L)
{
// Condition(conditionType[, conditionId = CONDITIONID_COMBAT])
ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2);
ConditionId_t conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT);
Condition* condition = Condition::createCondition(conditionId, conditionType, 0, 0);
if (condition) {
pushUserdata<Condition>(L, condition);
setMetatable(L, -1, "Condition");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionDelete(lua_State* L)
{
// condition:delete()
Condition** conditionPtr = getRawUserdata<Condition>(L, 1);
if (conditionPtr && *conditionPtr) {
delete *conditionPtr;
*conditionPtr = nullptr;
}
return 0;
}
int LuaScriptInterface::luaConditionGetId(lua_State* L)
{
// condition:getId()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetSubId(lua_State* L)
{
// condition:getSubId()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getSubId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetType(lua_State* L)
{
// condition:getType()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getType());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetIcons(lua_State* L)
{
// condition:getIcons()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getIcons());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetEndTime(lua_State* L)
{
// condition:getEndTime()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getEndTime());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionClone(lua_State* L)
{
// condition:clone()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
pushUserdata<Condition>(L, condition->clone());
setMetatable(L, -1, "Condition");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetTicks(lua_State* L)
{
// condition:getTicks()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionSetTicks(lua_State* L)
{
// condition:setTicks(ticks)
int32_t ticks = getNumber<int32_t>(L, 2);
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
condition->setTicks(ticks);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionSetParameter(lua_State* L)
{
// condition:setParameter(key, value)
Condition* condition = getUserdata<Condition>(L, 1);
if (!condition) {
lua_pushnil(L);
return 1;
}
ConditionParam_t key = getNumber<ConditionParam_t>(L, 2);
int32_t value;
if (isBoolean(L, 3)) {
value = getBoolean(L, 3) ? 1 : 0;
} else {
value = getNumber<int32_t>(L, 3);
}
condition->setParam(key, value);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaConditionSetFormula(lua_State* L)
{
// condition:setFormula(mina, minb, maxa, maxb)
double maxb = getNumber<double>(L, 5);
double maxa = getNumber<double>(L, 4);
double minb = getNumber<double>(L, 3);
double mina = getNumber<double>(L, 2);
ConditionSpeed* condition = dynamic_cast<ConditionSpeed*>(getUserdata<Condition>(L, 1));
if (condition) {
condition->setFormulaVars(mina, minb, maxa, maxb);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionSetOutfit(lua_State* L)
{
// condition:setOutfit(outfit)
// condition:setOutfit(lookTypeEx, lookType, lookHead, lookBody, lookLegs, lookFeet[, lookAddons[, lookMount]])
Outfit_t outfit;
if (isTable(L, 2)) {
outfit = getOutfit(L, 2);
} else {
outfit.lookMount = getNumber<uint16_t>(L, 9, outfit.lookMount);
outfit.lookAddons = getNumber<uint8_t>(L, 8, outfit.lookAddons);
outfit.lookFeet = getNumber<uint8_t>(L, 7);
outfit.lookLegs = getNumber<uint8_t>(L, 6);
outfit.lookBody = getNumber<uint8_t>(L, 5);
outfit.lookHead = getNumber<uint8_t>(L, 4);
outfit.lookType = getNumber<uint16_t>(L, 3);
outfit.lookTypeEx = getNumber<uint16_t>(L, 2);
}
ConditionOutfit* condition = dynamic_cast<ConditionOutfit*>(getUserdata<Condition>(L, 1));
if (condition) {
condition->setOutfit(outfit);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionAddDamage(lua_State* L)
{
// condition:addDamage(rounds, time, value)
int32_t value = getNumber<int32_t>(L, 4);
int32_t time = getNumber<int32_t>(L, 3);
int32_t rounds = getNumber<int32_t>(L, 2);
ConditionDamage* condition = dynamic_cast<ConditionDamage*>(getUserdata<Condition>(L, 1));
if (condition) {
pushBoolean(L, condition->addDamage(rounds, time, value));
} else {
lua_pushnil(L);
}
return 1;
}
// MonsterType
int LuaScriptInterface::luaMonsterTypeCreate(lua_State* L)
{
// MonsterType(name)
MonsterType* monsterType = g_monsters.getMonsterType(getString(L, 2));
if (monsterType) {
pushUserdata<MonsterType>(L, monsterType);
setMetatable(L, -1, "MonsterType");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsAttackable(lua_State* L)
{
// monsterType:isAttackable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.isAttackable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsConvinceable(lua_State* L)
{
// monsterType:isConvinceable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.isConvinceable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsSummonable(lua_State* L)
{
// monsterType:isSummonable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.isSummonable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsIllusionable(lua_State* L)
{
// monsterType:isIllusionable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.isIllusionable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsHostile(lua_State* L)
{
// monsterType:isHostile()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.isHostile);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsPushable(lua_State* L)
{
// monsterType:isPushable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.pushable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsHealthShown(lua_State* L)
{
// monsterType:isHealthShown()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, !monsterType->info.hiddenHealth);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeCanPushItems(lua_State* L)
{
// monsterType:canPushItems()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.canPushItems);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeCanPushCreatures(lua_State* L)
{
// monsterType:canPushCreatures()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.canPushCreatures);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetName(lua_State* L)
{
// monsterType:getName()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushString(L, monsterType->name);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetNameDescription(lua_State* L)
{
// monsterType:getNameDescription()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushString(L, monsterType->nameDescription);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetHealth(lua_State* L)
{
// monsterType:getHealth()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.health);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetMaxHealth(lua_State* L)
{
// monsterType:getMaxHealth()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.healthMax);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetRunHealth(lua_State* L)
{
// monsterType:getRunHealth()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.runAwayHealth);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetExperience(lua_State* L)
{
// monsterType:getExperience()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.experience);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetCombatImmunities(lua_State* L)
{
// monsterType:getCombatImmunities()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.damageImmunities);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetConditionImmunities(lua_State* L)
{
// monsterType:getConditionImmunities()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.conditionImmunities);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetAttackList(lua_State* L)
{
// monsterType:getAttackList()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, monsterType->info.attackSpells.size(), 0);
int index = 0;
for (const auto& spellBlock : monsterType->info.attackSpells) {
lua_createtable(L, 0, 8);
setField(L, "chance", spellBlock.chance);
setField(L, "isCombatSpell", spellBlock.combatSpell ? 1 : 0);
setField(L, "isMelee", spellBlock.isMelee ? 1 : 0);
setField(L, "minCombatValue", spellBlock.minCombatValue);
setField(L, "maxCombatValue", spellBlock.maxCombatValue);
setField(L, "range", spellBlock.range);
setField(L, "speed", spellBlock.speed);
pushUserdata<CombatSpell>(L, static_cast<CombatSpell*>(spellBlock.spell));
lua_setfield(L, -2, "spell");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetDefenseList(lua_State* L)
{
// monsterType:getDefenseList()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, monsterType->info.defenseSpells.size(), 0);
int index = 0;
for (const auto& spellBlock : monsterType->info.defenseSpells) {
lua_createtable(L, 0, 8);
setField(L, "chance", spellBlock.chance);
setField(L, "isCombatSpell", spellBlock.combatSpell ? 1 : 0);
setField(L, "isMelee", spellBlock.isMelee ? 1 : 0);
setField(L, "minCombatValue", spellBlock.minCombatValue);
setField(L, "maxCombatValue", spellBlock.maxCombatValue);
setField(L, "range", spellBlock.range);
setField(L, "speed", spellBlock.speed);
pushUserdata<CombatSpell>(L, static_cast<CombatSpell*>(spellBlock.spell));
lua_setfield(L, -2, "spell");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetElementList(lua_State* L)
{
// monsterType:getElementList()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, monsterType->info.elementMap.size(), 0);
for (const auto& elementEntry : monsterType->info.elementMap) {
lua_pushnumber(L, elementEntry.second);
lua_rawseti(L, -2, elementEntry.first);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetVoices(lua_State* L)
{
// monsterType:getVoices()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
int index = 0;
lua_createtable(L, monsterType->info.voiceVector.size(), 0);
for (const auto& voiceBlock : monsterType->info.voiceVector) {
lua_createtable(L, 0, 2);
setField(L, "text", voiceBlock.text);
setField(L, "yellText", voiceBlock.yellText);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetLoot(lua_State* L)
{
// monsterType:getLoot()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
static const std::function<void(const std::vector<LootBlock>&)> parseLoot = [&](const std::vector<LootBlock>& lootList) {
lua_createtable(L, lootList.size(), 0);
int index = 0;
for (const auto& lootBlock : lootList) {
lua_createtable(L, 0, 7);
setField(L, "itemId", lootBlock.id);
setField(L, "chance", lootBlock.chance);
setField(L, "subType", lootBlock.subType);
setField(L, "maxCount", lootBlock.countmax);
setField(L, "actionId", lootBlock.actionId);
setField(L, "text", lootBlock.text);
parseLoot(lootBlock.childLoot);
lua_setfield(L, -2, "childLoot");
lua_rawseti(L, -2, ++index);
}
};
parseLoot(monsterType->info.lootItems);
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetCreatureEvents(lua_State* L)
{
// monsterType:getCreatureEvents()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
int index = 0;
lua_createtable(L, monsterType->info.scripts.size(), 0);
for (const std::string& creatureEvent : monsterType->info.scripts) {
pushString(L, creatureEvent);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetSummonList(lua_State* L)
{
// monsterType:getSummonList()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
int index = 0;
lua_createtable(L, monsterType->info.summons.size(), 0);
for (const auto& summonBlock : monsterType->info.summons) {
lua_createtable(L, 0, 3);
setField(L, "name", summonBlock.name);
setField(L, "speed", summonBlock.speed);
setField(L, "chance", summonBlock.chance);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetMaxSummons(lua_State* L)
{
// monsterType:getMaxSummons()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.maxSummons);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetArmor(lua_State* L)
{
// monsterType:getArmor()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.armor);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetDefense(lua_State* L)
{
// monsterType:getDefense()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.defense);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetOutfit(lua_State* L)
{
// monsterType:getOutfit()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushOutfit(L, monsterType->info.outfit);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetRace(lua_State* L)
{
// monsterType:getRace()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.race);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetCorpseId(lua_State* L)
{
// monsterType:getCorpseId()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.lookcorpse);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetManaCost(lua_State* L)
{
// monsterType:getManaCost()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.manaCost);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetBaseSpeed(lua_State* L)
{
// monsterType:getBaseSpeed()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.baseSpeed);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetLight(lua_State* L)
{
// monsterType:getLight()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, monsterType->info.light.level);
lua_pushnumber(L, monsterType->info.light.color);
return 2;
}
int LuaScriptInterface::luaMonsterTypeGetStaticAttackChance(lua_State* L)
{
// monsterType:getStaticAttackChance()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.staticAttackChance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetTargetDistance(lua_State* L)
{
// monsterType:getTargetDistance()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.targetDistance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetYellChance(lua_State* L)
{
// monsterType:getYellChance()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.yellChance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetYellSpeedTicks(lua_State* L)
{
// monsterType:getYellSpeedTicks()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.yellSpeedTicks);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetChangeTargetChance(lua_State* L)
{
// monsterType:getChangeTargetChance()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.changeTargetChance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetChangeTargetSpeed(lua_State* L)
{
// monsterType:getChangeTargetSpeed()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.changeTargetSpeed);
} else {
lua_pushnil(L);
}
return 1;
}
// Party
int LuaScriptInterface::luaPartyDisband(lua_State* L)
{
// party:disband()
Party** partyPtr = getRawUserdata<Party>(L, 1);
if (partyPtr && *partyPtr) {
Party*& party = *partyPtr;
party->disband();
party = nullptr;
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyGetLeader(lua_State* L)
{
// party:getLeader()
Party* party = getUserdata<Party>(L, 1);
if (!party) {
lua_pushnil(L);
return 1;
}
Player* leader = party->getLeader();
if (leader) {
pushUserdata<Player>(L, leader);
setMetatable(L, -1, "Player");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartySetLeader(lua_State* L)
{
// party:setLeader(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->passPartyLeadership(player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyGetMembers(lua_State* L)
{
// party:getMembers()
Party* party = getUserdata<Party>(L, 1);
if (!party) {
lua_pushnil(L);
return 1;
}
int index = 0;
lua_createtable(L, party->getMemberCount(), 0);
for (Player* player : party->getMembers()) {
pushUserdata<Player>(L, player);
setMetatable(L, -1, "Player");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaPartyGetMemberCount(lua_State* L)
{
// party:getMemberCount()
Party* party = getUserdata<Party>(L, 1);
if (party) {
lua_pushnumber(L, party->getMemberCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyGetInvitees(lua_State* L)
{
// party:getInvitees()
Party* party = getUserdata<Party>(L, 1);
if (party) {
lua_createtable(L, party->getInvitationCount(), 0);
int index = 0;
for (Player* player : party->getInvitees()) {
pushUserdata<Player>(L, player);
setMetatable(L, -1, "Player");
lua_rawseti(L, -2, ++index);
}
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyGetInviteeCount(lua_State* L)
{
// party:getInviteeCount()
Party* party = getUserdata<Party>(L, 1);
if (party) {
lua_pushnumber(L, party->getInvitationCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyAddInvite(lua_State* L)
{
// party:addInvite(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->invitePlayer(*player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyRemoveInvite(lua_State* L)
{
// party:removeInvite(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->removeInvite(*player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyAddMember(lua_State* L)
{
// party:addMember(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->joinParty(*player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyRemoveMember(lua_State* L)
{
// party:removeMember(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->leaveParty(player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyIsSharedExperienceActive(lua_State* L)
{
// party:isSharedExperienceActive()
Party* party = getUserdata<Party>(L, 1);
if (party) {
pushBoolean(L, party->isSharedExperienceActive());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyIsSharedExperienceEnabled(lua_State* L)
{
// party:isSharedExperienceEnabled()
Party* party = getUserdata<Party>(L, 1);
if (party) {
pushBoolean(L, party->isSharedExperienceEnabled());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyShareExperience(lua_State* L)
{
// party:shareExperience(experience)
uint64_t experience = getNumber<uint64_t>(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party) {
party->shareExperience(experience);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartySetSharedExperience(lua_State* L)
{
// party:setSharedExperience(active)
bool active = getBoolean(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party) {
pushBoolean(L, party->setSharedExperience(party->getLeader(), active));
} else {
lua_pushnil(L);
}
return 1;
}
// Spells
int LuaScriptInterface::luaSpellCreate(lua_State* L)
{
// Spell(words, name or id)
InstantSpell* spell = nullptr;
if (isNumber(L, 2)) {
spell = g_spells->getInstantSpellById(getNumber<uint32_t>(L, 2));
} else {
std::string stringArgument = getString(L, 2);
spell = g_spells->getInstantSpellByName(stringArgument);
if (!spell) {
spell = g_spells->getInstantSpell(stringArgument);
}
}
if (spell) {
pushInstantSpell(L, *spell);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaSpellGetManaCost(lua_State* L)
{
// spell:getManaCost(player)
InstantSpell* spell = getUserdata<InstantSpell>(L, 1);
Player* player = getUserdata<Player>(L, 2);
if (spell && player) {
lua_pushnumber(L, spell->getManaCost(player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaSpellGetSoulCost(lua_State* L)
{
// spell:getSoulCost()
if (InstantSpell* spell = getUserdata<InstantSpell>(L, 1)) {
lua_pushnumber(L, spell->getSoulCost());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaSpellIsPremium(lua_State* L)
{
// spell:isPremium()
if (InstantSpell* spell = getUserdata<InstantSpell>(L, 1)) {
pushBoolean(L, spell->isPremium());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaSpellIsLearnable(lua_State* L)
{
// spell:isLearnable()
if (InstantSpell* spell = getUserdata<InstantSpell>(L, 1)) {
pushBoolean(L, spell->isLearnable());
} else {
lua_pushnil(L);
}
return 1;
}
//
LuaEnvironment::LuaEnvironment() : LuaScriptInterface("Main Interface") {}
LuaEnvironment::~LuaEnvironment()
{
delete testInterface;
closeState();
}
bool LuaEnvironment::initState()
{
luaState = luaL_newstate();
if (!luaState) {
return false;
}
luaL_openlibs(luaState);
registerFunctions();
runningEventId = EVENT_ID_USER;
return true;
}
bool LuaEnvironment::reInitState()
{
// TODO: get children, reload children
closeState();
return initState();
}
bool LuaEnvironment::closeState()
{
if (!luaState) {
return false;
}
for (const auto& combatEntry : combatIdMap) {
clearCombatObjects(combatEntry.first);
}
for (const auto& areaEntry : areaIdMap) {
clearAreaObjects(areaEntry.first);
}
for (auto& timerEntry : timerEvents) {
LuaTimerEventDesc timerEventDesc = std::move(timerEntry.second);
for (int32_t parameter : timerEventDesc.parameters) {
luaL_unref(luaState, LUA_REGISTRYINDEX, parameter);
}
luaL_unref(luaState, LUA_REGISTRYINDEX, timerEventDesc.function);
}
combatIdMap.clear();
areaIdMap.clear();
timerEvents.clear();
cacheFiles.clear();
lua_close(luaState);
luaState = nullptr;
return true;
}
LuaScriptInterface* LuaEnvironment::getTestInterface()
{
if (!testInterface) {
testInterface = new LuaScriptInterface("Test Interface");
testInterface->initState();
}
return testInterface;
}
Combat* LuaEnvironment::getCombatObject(uint32_t id) const
{
auto it = combatMap.find(id);
if (it == combatMap.end()) {
return nullptr;
}
return it->second;
}
Combat* LuaEnvironment::createCombatObject(LuaScriptInterface* interface)
{
Combat* combat = new Combat;
combatMap[++lastCombatId] = combat;
combatIdMap[interface].push_back(lastCombatId);
return combat;
}
void LuaEnvironment::clearCombatObjects(LuaScriptInterface* interface)
{
auto it = combatIdMap.find(interface);
if (it == combatIdMap.end()) {
return;
}
for (uint32_t id : it->second) {
auto itt = combatMap.find(id);
if (itt != combatMap.end()) {
delete itt->second;
combatMap.erase(itt);
}
}
it->second.clear();
}
AreaCombat* LuaEnvironment::getAreaObject(uint32_t id) const
{
auto it = areaMap.find(id);
if (it == areaMap.end()) {
return nullptr;
}
return it->second;
}
uint32_t LuaEnvironment::createAreaObject(LuaScriptInterface* interface)
{
areaMap[++lastAreaId] = new AreaCombat;
areaIdMap[interface].push_back(lastAreaId);
return lastAreaId;
}
void LuaEnvironment::clearAreaObjects(LuaScriptInterface* interface)
{
auto it = areaIdMap.find(interface);
if (it == areaIdMap.end()) {
return;
}
for (uint32_t id : it->second) {
auto itt = areaMap.find(id);
if (itt != areaMap.end()) {
delete itt->second;
areaMap.erase(itt);
}
}
it->second.clear();
}
void LuaEnvironment::executeTimerEvent(uint32_t eventIndex)
{
auto it = timerEvents.find(eventIndex);
if (it == timerEvents.end()) {
return;
}
LuaTimerEventDesc timerEventDesc = std::move(it->second);
timerEvents.erase(it);
//push function
lua_rawgeti(luaState, LUA_REGISTRYINDEX, timerEventDesc.function);
//push parameters
for (auto parameter : boost::adaptors::reverse(timerEventDesc.parameters)) {
lua_rawgeti(luaState, LUA_REGISTRYINDEX, parameter);
}
//call the function
if (reserveScriptEnv()) {
ScriptEnvironment* env = getScriptEnv();
env->setTimerEvent();
env->setScriptId(timerEventDesc.scriptId, this);
callFunction(timerEventDesc.parameters.size());
} else {
std::cout << "[Error - LuaScriptInterface::executeTimerEvent] Call stack overflow" << std::endl;
}
//free resources
luaL_unref(luaState, LUA_REGISTRYINDEX, timerEventDesc.function);
for (auto parameter : timerEventDesc.parameters) {
luaL_unref(luaState, LUA_REGISTRYINDEX, parameter);
}
}
| 1 | 15,172 | You should add the check above this line instead. If string is empty, don't even call the function. | otland-forgottenserver | cpp |
@@ -101,6 +101,13 @@ public class DynamoDBCertRecordStoreConnection implements CertRecordStoreConnect
}
private X509CertRecord itemToX509CertRecord(Item item) {
+ boolean clientCert;
+ try {
+ clientCert = item.getBoolean(KEY_CLIENT_CERT);
+ } catch (Exception ex) {
+ LOGGER.warn("clientCert for item doesn't exist. Will set it to false. Item: {}", item.toString());
+ clientCert = false;
+ }
X509CertRecord certRecord = new X509CertRecord();
certRecord.setProvider(item.getString(KEY_PROVIDER));
certRecord.setInstanceId(item.getString(KEY_INSTANCE_ID)); | 1 | /*
* Copyright 2018 Oath, 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.
*/
package com.yahoo.athenz.zts.cert.impl;
import java.util.*;
import java.util.concurrent.TimeUnit;
import com.amazonaws.services.dynamodbv2.document.*;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.ReturnValue;
import com.yahoo.athenz.common.server.cert.CertRecordStoreConnection;
import com.yahoo.athenz.common.server.cert.X509CertRecord;
import com.yahoo.athenz.zts.ZTSConsts;
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.yahoo.athenz.zts.utils.DynamoDBUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DynamoDBCertRecordStoreConnection implements CertRecordStoreConnection {
private static final Logger LOGGER = LoggerFactory.getLogger(DynamoDBCertRecordStoreConnection.class);
private static final String KEY_PRIMARY = "primaryKey";
private static final String KEY_PROVIDER = "provider";
private static final String KEY_INSTANCE_ID = "instanceId";
private static final String KEY_SERVICE = "service";
private static final String KEY_CURRENT_SERIAL = "currentSerial";
private static final String KEY_CURRENT_TIME = "currentTime";
private static final String KEY_CURRENT_DATE = "currentDate";
private static final String KEY_CURRENT_IP = "currentIP";
private static final String KEY_PREV_SERIAL = "prevSerial";
private static final String KEY_PREV_TIME = "prevTime";
private static final String KEY_PREV_IP = "prevIP";
private static final String KEY_CLIENT_CERT = "clientCert";
private static final String KEY_LAST_NOTIFIED_TIME = "lastNotifiedTime";
private static final String KEY_LAST_NOTIFIED_SERVER = "lastNotifiedServer";
private static final String KEY_EXPIRY_TIME = "expiryTime";
private static final String KEY_HOSTNAME = "hostName";
private static final String KEY_TTL = "ttl";
private static final String KEY_REGISTER_TIME = "registerTime";
private static final String KEY_SVC_DATA_UPDATE_TIME = "svcDataUpdateTime";
private static final int NOTIFICATIONS_GRACE_PERIOD_IN_HOURS = 72;
// the configuration setting is in hours so we'll automatically
// convert into seconds since that's what dynamoDB needs
// we need to expire records in 30 days
private static final Long EXPIRY_HOURS = Long.parseLong(
System.getProperty(ZTSConsts.ZTS_PROP_CERT_DYNAMODB_ITEM_TTL_HOURS, "720"));
private static long expiryTime = 3660 * EXPIRY_HOURS;
private Table table;
private Index index;
public DynamoDBCertRecordStoreConnection(DynamoDB dynamoDB, final String tableName, String indexName) {
this.table = dynamoDB.getTable(tableName);
this.index = table.getIndex(indexName);
}
@Override
public void setOperationTimeout(int queryTimeout) {
}
@Override
public void close() {
}
@Override
public X509CertRecord getX509CertRecord(String provider, String instanceId, String service) {
final String primaryKey = getPrimaryKey(provider, instanceId, service);
try {
Item item = table.getItem(KEY_PRIMARY, primaryKey);
if (item == null) {
LOGGER.error("DynamoDB Get Error for {}: item not found", primaryKey);
return null;
}
return itemToX509CertRecord(item);
} catch (Exception ex) {
LOGGER.error("DynamoDB Get Error for {}: {}/{}", primaryKey, ex.getClass(), ex.getMessage());
return null;
}
}
private X509CertRecord itemToX509CertRecord(Item item) {
X509CertRecord certRecord = new X509CertRecord();
certRecord.setProvider(item.getString(KEY_PROVIDER));
certRecord.setInstanceId(item.getString(KEY_INSTANCE_ID));
certRecord.setService(item.getString(KEY_SERVICE));
certRecord.setCurrentSerial(item.getString(KEY_CURRENT_SERIAL));
certRecord.setCurrentIP(item.getString(KEY_CURRENT_IP));
certRecord.setCurrentTime(getDateFromItem(item, KEY_CURRENT_TIME));
certRecord.setPrevSerial(item.getString(KEY_PREV_SERIAL));
certRecord.setPrevIP(item.getString(KEY_PREV_IP));
certRecord.setPrevTime(getDateFromItem(item, KEY_PREV_TIME));
certRecord.setClientCert(item.getBoolean(KEY_CLIENT_CERT));
certRecord.setLastNotifiedTime(getDateFromItem(item, KEY_LAST_NOTIFIED_TIME));
certRecord.setLastNotifiedServer(item.getString(KEY_LAST_NOTIFIED_SERVER));
certRecord.setExpiryTime(getDateFromItem(item, KEY_EXPIRY_TIME));
certRecord.setHostName(item.getString(KEY_HOSTNAME));
certRecord.setSvcDataUpdateTime(getDateFromItem(item, KEY_SVC_DATA_UPDATE_TIME));
return certRecord;
}
private Date getDateFromItem(Item item, String key) {
if (item.isNull(key) || item.get(key) == null) {
return null;
}
return new Date(item.getLong(key));
}
private Object getLongFromDate(Date date) {
if (date == null) {
return null;
}
return date.getTime();
}
@Override
public boolean updateX509CertRecord(X509CertRecord certRecord) {
final String primaryKey = getPrimaryKey(certRecord.getProvider(), certRecord.getInstanceId(),
certRecord.getService());
// if we don't have a svc update time we'll default to
// the current time
if (certRecord.getSvcDataUpdateTime() == null) {
certRecord.setSvcDataUpdateTime(new Date());
}
try {
UpdateItemSpec updateItemSpec = new UpdateItemSpec()
.withPrimaryKey(KEY_PRIMARY, primaryKey)
.withAttributeUpdate(
new AttributeUpdate(KEY_INSTANCE_ID).put(certRecord.getInstanceId()),
new AttributeUpdate(KEY_PROVIDER).put(certRecord.getProvider()),
new AttributeUpdate(KEY_SERVICE).put(certRecord.getService()),
new AttributeUpdate(KEY_CURRENT_SERIAL).put(certRecord.getCurrentSerial()),
new AttributeUpdate(KEY_CURRENT_IP).put(certRecord.getCurrentIP()),
new AttributeUpdate(KEY_CURRENT_TIME).put(getLongFromDate(certRecord.getCurrentTime())),
new AttributeUpdate(KEY_CURRENT_DATE).put(DynamoDBUtils.getIso8601FromDate(certRecord.getCurrentTime())),
new AttributeUpdate(KEY_PREV_SERIAL).put(certRecord.getPrevSerial()),
new AttributeUpdate(KEY_PREV_IP).put(certRecord.getPrevIP()),
new AttributeUpdate(KEY_PREV_TIME).put(getLongFromDate(certRecord.getPrevTime())),
new AttributeUpdate(KEY_CLIENT_CERT).put(certRecord.getClientCert()),
new AttributeUpdate(KEY_TTL).put(certRecord.getCurrentTime().getTime() / 1000L + expiryTime),
new AttributeUpdate(KEY_SVC_DATA_UPDATE_TIME).put(getLongFromDate(certRecord.getSvcDataUpdateTime())),
new AttributeUpdate(KEY_EXPIRY_TIME).put(getLongFromDate(certRecord.getExpiryTime()))
);
if (certRecord.getHostName() != null) {
updateItemSpec.addAttributeUpdate(new AttributeUpdate(KEY_HOSTNAME).put(certRecord.getHostName()));
}
table.updateItem(updateItemSpec);
return true;
} catch (Exception ex) {
LOGGER.error("DynamoDB Update Error for {}: {}/{}", primaryKey, ex.getClass(), ex.getMessage());
return false;
}
}
@Override
public boolean insertX509CertRecord(X509CertRecord certRecord) {
final String primaryKey = getPrimaryKey(certRecord.getProvider(), certRecord.getInstanceId(),
certRecord.getService());
try {
Item item = new Item()
.withPrimaryKey(KEY_PRIMARY, primaryKey)
.withString(KEY_INSTANCE_ID, certRecord.getInstanceId())
.withString(KEY_PROVIDER, certRecord.getProvider())
.withString(KEY_SERVICE, certRecord.getService())
.withString(KEY_CURRENT_SERIAL, certRecord.getCurrentSerial())
.withString(KEY_CURRENT_IP, certRecord.getCurrentIP())
.with(KEY_CURRENT_TIME, getLongFromDate(certRecord.getCurrentTime()))
.withString(KEY_CURRENT_DATE, DynamoDBUtils.getIso8601FromDate(certRecord.getCurrentTime()))
.withString(KEY_PREV_SERIAL, certRecord.getPrevSerial())
.withString(KEY_PREV_IP, certRecord.getPrevIP())
.with(KEY_PREV_TIME, getLongFromDate(certRecord.getPrevTime()))
.withBoolean(KEY_CLIENT_CERT, certRecord.getClientCert())
.withLong(KEY_TTL, certRecord.getCurrentTime().getTime() / 1000L + expiryTime)
.with(KEY_EXPIRY_TIME, getLongFromDate(certRecord.getExpiryTime()))
.with(KEY_SVC_DATA_UPDATE_TIME, getLongFromDate(certRecord.getSvcDataUpdateTime()))
.withLong(KEY_REGISTER_TIME, System.currentTimeMillis())
.with(KEY_HOSTNAME, certRecord.getHostName());
table.putItem(item);
return true;
} catch (Exception ex) {
LOGGER.error("DynamoDB Insert Error for {}: {}/{}", primaryKey, ex.getClass(), ex.getMessage());
return false;
}
}
@Override
public boolean deleteX509CertRecord(String provider, String instanceId, String service) {
final String primaryKey = getPrimaryKey(provider, instanceId, service);
try {
DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
.withPrimaryKey(KEY_PRIMARY, primaryKey);
table.deleteItem(deleteItemSpec);
return true;
} catch (Exception ex) {
LOGGER.error("DynamoDB Delete Error for {}: {}/{}", primaryKey, ex.getClass(), ex.getMessage());
return false;
}
}
@Override
public int deleteExpiredX509CertRecords(int expiryTimeMins) {
// with dynamo db there is no need to manually expunge expired
// record since we have the TTL option enabled for our table
// and we just need to make sure the attribute is updated with
// the epoch time + timeout seconds when it should retire
return 0;
}
@Override
public List<X509CertRecord> updateUnrefreshedCertificatesNotificationTimestamp(String lastNotifiedServer,
long lastNotifiedTime,
String provider) {
try {
List<Item> items = getUnrefreshedCertsRecords(lastNotifiedTime, provider);
return updateLastNotified(lastNotifiedServer, lastNotifiedTime, items);
} catch (Exception ex) {
LOGGER.error("DynamoDB updateUnrefreshedCertificatesNotificationTimestamp Error: {}/{}", ex.getClass(), ex.getMessage());
return new ArrayList<>();
}
}
private String getPrimaryKey(final String provider, final String instanceId, final String service) {
return provider + ":" + service + ":" + instanceId;
}
private List<X509CertRecord> updateLastNotified(String lastNotifiedServer, long lastNotifiedTime, List<Item> items) {
long yesterday = lastNotifiedTime - TimeUnit.DAYS.toMillis(1);
List<X509CertRecord> updatedRecords = new ArrayList<>();
for (Item item : items) {
// For each item, update lastNotifiedTime and lastNotifiedServer (unless they were already updated)
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey(KEY_PRIMARY, item.getString(KEY_PRIMARY))
.withReturnValues(ReturnValue.ALL_NEW)
.withUpdateExpression("set lastNotifiedTime = :lastNotifiedTimeVal, lastNotifiedServer = :lastNotifiedServerVal")
.withConditionExpression("attribute_not_exists(lastNotifiedTime) OR lastNotifiedTime < :v_yesterday")
.withValueMap(new ValueMap()
.with(":lastNotifiedTimeVal", lastNotifiedTime)
.withNumber(":v_yesterday", yesterday)
.withString(":lastNotifiedServerVal", lastNotifiedServer));
Item updatedItem = table.updateItem(updateItemSpec).getItem();
if (isRecordUpdatedWithNotificationTimeAndServer(lastNotifiedServer, lastNotifiedTime, updatedItem)) {
X509CertRecord x509CertRecord = itemToX509CertRecord(updatedItem);
updatedRecords.add(x509CertRecord);
}
}
return updatedRecords;
}
private boolean isRecordUpdatedWithNotificationTimeAndServer(String lastNotifiedServer, long lastNotifiedTime, Item updatedItem) {
return updatedItem != null &&
updatedItem.getLong(KEY_LAST_NOTIFIED_TIME) == lastNotifiedTime &&
updatedItem.getString(KEY_LAST_NOTIFIED_SERVER) != null &&
updatedItem.getString(KEY_LAST_NOTIFIED_SERVER).equals(lastNotifiedServer);
}
private List<Item> getUnrefreshedCertsRecords(long lastNotifiedTime, String provider) {
long yesterday = lastNotifiedTime - TimeUnit.DAYS.toMillis(1);
long unrefreshedCertsRangeBegin = lastNotifiedTime - TimeUnit.HOURS.toMillis(EXPIRY_HOURS);
long unrefreshedCertsRangeEnd = lastNotifiedTime - TimeUnit.HOURS.toMillis(NOTIFICATIONS_GRACE_PERIOD_IN_HOURS);
List<Item> items = new ArrayList<>();
List<String> unrefreshedCertDates = DynamoDBUtils.getISODatesByRange(unrefreshedCertsRangeBegin, unrefreshedCertsRangeEnd);
for (String unrefreshedCertDate : unrefreshedCertDates) {
items.addAll(getUnrefreshedCertRecordsByDate(provider, index, yesterday, unrefreshedCertDate));
}
return items;
}
private List<Item> getUnrefreshedCertRecordsByDate(String provider, Index index, long yesterday, String unrefreshedCertDate) {
QuerySpec spec = new QuerySpec()
.withKeyConditionExpression("currentDate = :v_current_date")
.withFilterExpression("provider = :v_provider AND (attribute_not_exists(lastNotifiedTime) OR lastNotifiedTime < :v_last_notified)")
.withValueMap(new ValueMap()
.withString(":v_current_date", unrefreshedCertDate)
.withNumber(":v_last_notified", yesterday)
.withString(":v_provider", provider));
ItemCollection<QueryOutcome> outcome = index.query(spec);
List<Item> items = new ArrayList<>();
for (Item item : outcome) {
items.add(item);
}
return items;
}
}
| 1 | 5,434 | If clientCert attribute doesn't exist for some reason I set it to false. | AthenZ-athenz | java |
@@ -301,7 +301,11 @@ module Travis
cmd_opts = {retry: true, assert: false, echo: 'Installing caching utilities'}
if casher_branch == 'production'
static_file_location = "https://#{app_host}/files/#{name}".output_safe
- sh.cmd curl_cmd(flags, location, static_file_location), cmd_opts
+ app_host_flags = flags
+ if Travis::Build.config&.ssl&.verify == false
+ app_host_flags += ' -k '
+ end
+ sh.cmd curl_cmd(app_host_flags, location, static_file_location), cmd_opts
sh.if "$? -ne 0" do
cmd_opts[:echo] = "Installing caching utilities from the Travis CI server (#{static_file_location}) failed, failing over to using GitHub (#{remote_location})"
sh.cmd curl_cmd(flags, location, remote_location), cmd_opts | 1 | require 'shellwords'
require 'travis/build/script/shared/directory_cache/signatures/aws2_signature'
require 'travis/build/script/shared/directory_cache/signatures/aws4_signature'
module Travis
module Build
class Script
module DirectoryCache
class Base
MSGS = {
config_missing: 'Worker %s config missing: %s'
}
VALIDATE = {
bucket: 'bucket name',
access_key_id: 'access key id',
secret_access_key: 'secret access key'
}
CURL_FORMAT = <<-EOF
time_namelookup: %{time_namelookup} s
time_connect: %{time_connect} s
time_appconnect: %{time_appconnect} s
time_pretransfer: %{time_pretransfer} s
time_redirect: %{time_redirect} s
time_starttransfer: %{time_starttransfer} s
speed_download: %{speed_download} bytes/s
url_effective: %{url_effective}
----------
time_total: %{time_total} s
EOF
DEFAULT_AWS_SIGNATURE_VERSION = '4'
COMMANDS_REQUIRING_SIG = %w(fetch push)
# maximum number of directories to be 'added' to cache via casher
# in one invocation
ADD_DIR_MAX = 100
KeyPair = Struct.new(:id, :secret)
Location = Struct.new(:scheme, :region, :bucket, :path, :host, :signature_version) do
def hostname
case signature_version
when '2'
"#{bucket}.#{host}"
else
host
end
end
end
CASHER_URL = 'https://raw.githubusercontent.com/travis-ci/casher/%s/bin/casher'
BIN_PATH = '$CASHER_DIR/bin/casher'
attr_reader :sh, :data, :slug, :start, :msgs
attr_accessor :signer
def initialize(sh, data, slug, start = Time.now)
@sh = sh
@data = data
@slug = slug
@start = start
@msgs = []
end
def valid?
validate
msgs.empty?
end
def signature(verb, path, options)
@signer = case data_store_options.fetch(:aws_signature_version, DEFAULT_AWS_SIGNATURE_VERSION).to_s
when '2'
Signatures::AWS2Signature.new(
key: key_pair,
http_verb: verb,
location: location(path),
expires: (start+ options[:expires].to_i).to_i,
access_id_param: self.class.const_get(:ACCESS_ID_PARAM_NAME),
)
else
Signatures::AWS4Signature.new(
key: key_pair,
http_verb: verb,
location: location(path),
expires: options[:expires],
timestamp: start
)
end
end
def setup_casher
fold 'Setting up build cache' do
run_rvm_use
install
fetch
add(directories) if data.cache?(:directories)
end
sh.newline
end
def run_rvm_use
sh.raw "rvm use $(rvm current 2>/dev/null) >&/dev/null"
end
def install
sh.export 'CASHER_DIR', '${TRAVIS_HOME}/.casher'
sh.mkdir '$CASHER_DIR/bin', echo: false, recursive: true
update_static_file('casher', BIN_PATH, casher_url, true)
sh.if "$? -ne 0" do
sh.echo 'Failed to fetch casher from GitHub, disabling cache.', ansi: :yellow
end
sh.if "-f #{BIN_PATH}" do
sh.chmod '+x', BIN_PATH, assert: false, echo: false
end
end
def add(*paths)
if paths
paths.flatten.each_slice(ADD_DIR_MAX) { |dirs| run('add', dirs) }
end
end
def fetch
run('fetch', fetch_urls.map {|url| Shellwords.escape(url).to_s}, timing: true)
end
def fetch_urls
urls = [
fetch_url(uri_normalize_name(group), true),
fetch_url(uri_normalize_name(group)),
fetch_url(normalize_name(group), true),
fetch_url(normalize_name(group))
]
if data.pull_request
urls << fetch_url(uri_normalize_name(data.branch), true)
urls << fetch_url(uri_normalize_name(data.branch))
urls << fetch_url(normalize_name(data.branch), true)
urls << fetch_url(normalize_name(data.branch))
end
if data.branch != data.repository[:default_branch]
urls << fetch_url(uri_normalize_name(data.repository[:default_branch]), true)
urls << fetch_url(uri_normalize_name(data.repository[:default_branch]))
urls << fetch_url(normalize_name(data.repository[:default_branch]), true)
urls << fetch_url(normalize_name(data.repository[:default_branch]))
end
urls.uniq.compact
end
def push
run('push', Shellwords.escape(push_url.to_s), assert: false, timing: true)
end
def fetch_url(branch = group, extras = false)
prefix = prefixed(branch, extras)
if prefix
url('GET', prefix, expires: fetch_timeout)
end
end
def push_url(branch = group)
prefix = prefixed(uri_normalize_name(branch), true)
if prefix
url('PUT', prefix, expires: push_timeout)
end
end
def fold(message = nil)
@fold_count ||= 0
@fold_count += 1
sh.fold "cache.#{@fold_count}" do
sh.echo message if message
yield
end
end
private
def host_proc
raise "#{__method__} must be overridden"
end
def validate
VALIDATE.each { |key, msg| msgs << msg unless data_store_options[key] }
sh.echo MSGS[:config_missing] % [ self.class.name.split('::').last.upcase, msgs.join(', ')], ansi: :red unless msgs.empty?
end
def run(command, args, options = {})
sh.with_errexit_off do
sh.if "-f #{BIN_PATH}" do
sh.if "-e ~/.rvm/scripts/rvm" do
sh.cmd('type rvm &>/dev/null || source ~/.rvm/scripts/rvm', echo: false, assert: false)
sh.cmd "rvm $(travis_internal_ruby) --fuzzy do #{BIN_PATH} #{command} #{Array(args).join(' ')}", options.merge(echo: false, assert: false)
end
sh.else do
sh.cmd "#{BIN_PATH} #{command} #{Array(args).join(' ')}", options.merge(echo: false, assert: false)
end
end
end
end
def group
data.pull_request ? "PR.#{data.pull_request}" : data.branch
end
def directories
Array(data.cache[:directories])
end
def fetch_timeout
cache_options.fetch(:fetch_timeout)
end
def push_timeout
cache_options.fetch(:push_timeout)
end
def location(path)
region = data_store_options.fetch(:region, 'us-east-1')
Location.new(
data_store_options.fetch(:scheme, 'https'),
region,
data_store_options.fetch(:bucket, ''),
path,
data_store_options.fetch(:hostname, host_proc.call(region)),
data_store_options.fetch(:aws_signature_version, DEFAULT_AWS_SIGNATURE_VERSION).to_s
)
end
def prefixed(branch, extras = false)
slug_local = slug.dup
if ! extras
slug_local = slug.gsub(/^cache(.+?)(?=--)/,'cache')
end
case data_store_options.fetch(:aws_signature_version, DEFAULT_AWS_SIGNATURE_VERSION).to_s
when '2'
args = [data.github_id, branch, slug_local].compact
else
args = [data_store_options.fetch(:bucket, ''), data.github_id, branch, slug_local].compact
end
args.map!(&:to_s)
return if args.any? {|part| part.empty?}
'/' << args.join('/') << '.tgz'
end
def url(verb, path, options = {})
signature(verb, path, options).to_uri.to_s.output_safe
end
def key_pair
@key_pair ||= KeyPair.new(data_store_options[:access_key_id], data_store_options[:secret_access_key])
end
def data_store
cache_options[:type]
end
def data_store_options
cache_options[data_store.to_sym] || {}
end
def cache_options
data.cache_options || {}
end
def casher_url
CASHER_URL % casher_branch
end
def casher_branch
if branch = data.cache[:branch]
branch
else
edge? ? 'master' : 'production'
end
end
def edge?
data.cache?(:edge)
end
def debug_flags
"-v -w '#{CURL_FORMAT}'" if data.cache[:debug]
end
def app_host
@app_host ||= Travis::Build.config.app_host.to_s.strip.output_safe
end
def update_static_file(name, location, remote_location, assert = false)
flags = "-sf #{debug_flags}"
cmd_opts = {retry: true, assert: false, echo: 'Installing caching utilities'}
if casher_branch == 'production'
static_file_location = "https://#{app_host}/files/#{name}".output_safe
sh.cmd curl_cmd(flags, location, static_file_location), cmd_opts
sh.if "$? -ne 0" do
cmd_opts[:echo] = "Installing caching utilities from the Travis CI server (#{static_file_location}) failed, failing over to using GitHub (#{remote_location})"
sh.cmd curl_cmd(flags, location, remote_location), cmd_opts
end
else
sh.cmd curl_cmd(flags, location, (CASHER_URL % casher_branch)), cmd_opts
end
end
def curl_cmd(flags, location, remote_location)
"curl #{flags} -o #{location} #{remote_location}"
end
def normalize_name(branch)
branch.to_s.gsub(/[^\w\.\_\-]+/, '')
end
def uri_normalize_name(branch)
URI.encode(branch)
end
end
end
end
end
end
| 1 | 17,362 | Do we need `app_host_flags` variable? We can directly concat with `flags`. `sh.cmd curl_cmd(unless Travis::Build.config&.ssl&.verify ? flags + ' -k' : flags, location, static_file_location), cmd_opts` right? | travis-ci-travis-build | rb |
@@ -211,11 +211,11 @@ void Creature::onWalk()
forceUpdateFollowPath = true;
}
} else {
+ stopEventWalk();
+
if (listWalkDir.empty()) {
onWalkComplete();
}
-
- stopEventWalk();
}
}
| 1 | /**
* The Forgotten Server - a free and open-source MMORPG server emulator
* Copyright (C) 2019 Mark Samman <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "otpch.h"
#include "creature.h"
#include "game.h"
#include "monster.h"
#include "configmanager.h"
#include "scheduler.h"
double Creature::speedA = 857.36;
double Creature::speedB = 261.29;
double Creature::speedC = -4795.01;
extern Game g_game;
extern ConfigManager g_config;
extern CreatureEvents* g_creatureEvents;
Creature::Creature()
{
onIdleStatus();
}
Creature::~Creature()
{
for (Creature* summon : summons) {
summon->setAttackedCreature(nullptr);
summon->removeMaster();
}
for (Condition* condition : conditions) {
condition->endCondition(this);
delete condition;
}
}
bool Creature::canSee(const Position& myPos, const Position& pos, int32_t viewRangeX, int32_t viewRangeY)
{
if (myPos.z <= 7) {
// we are on ground level or above (7 -> 0)
// view is from 7 -> 0
if (pos.z > 7) {
return false;
}
} else if (myPos.z >= 8) {
// we are underground (8 -> 15)
// we can't see floors above 8
if (pos.z < 8) {
return false;
}
// view is +/- 2 from the floor we stand on
if (Position::getDistanceZ(myPos, pos) > 2) {
return false;
}
}
const int_fast32_t offsetz = myPos.getZ() - pos.getZ();
return (pos.getX() >= myPos.getX() - viewRangeX + offsetz) && (pos.getX() <= myPos.getX() + viewRangeX + offsetz)
&& (pos.getY() >= myPos.getY() - viewRangeY + offsetz) && (pos.getY() <= myPos.getY() + viewRangeY + offsetz);
}
bool Creature::canSee(const Position& pos) const
{
return canSee(getPosition(), pos, Map::maxViewportX, Map::maxViewportY);
}
bool Creature::canSeeCreature(const Creature* creature) const
{
if (!canSeeGhostMode(creature) && creature->isInGhostMode()) {
return false;
}
if (!canSeeInvisibility() && creature->isInvisible()) {
return false;
}
return true;
}
void Creature::setSkull(Skulls_t newSkull)
{
skull = newSkull;
g_game.updateCreatureSkull(this);
}
int64_t Creature::getTimeSinceLastMove() const
{
if (lastStep) {
return OTSYS_TIME() - lastStep;
}
return std::numeric_limits<int64_t>::max();
}
int32_t Creature::getWalkDelay(Direction dir) const
{
if (lastStep == 0) {
return 0;
}
int64_t ct = OTSYS_TIME();
int64_t stepDuration = getStepDuration(dir);
return stepDuration - (ct - lastStep);
}
int32_t Creature::getWalkDelay() const
{
//Used for auto-walking
if (lastStep == 0) {
return 0;
}
int64_t ct = OTSYS_TIME();
int64_t stepDuration = getStepDuration() * lastStepCost;
return stepDuration - (ct - lastStep);
}
void Creature::onThink(uint32_t interval)
{
if (!isMapLoaded && useCacheMap()) {
isMapLoaded = true;
updateMapCache();
}
if (followCreature && master != followCreature && !canSeeCreature(followCreature)) {
onCreatureDisappear(followCreature, false);
}
if (attackedCreature && master != attackedCreature && !canSeeCreature(attackedCreature)) {
onCreatureDisappear(attackedCreature, false);
}
blockTicks += interval;
if (blockTicks >= 1000) {
blockCount = std::min<uint32_t>(blockCount + 1, 2);
blockTicks = 0;
}
if (followCreature) {
walkUpdateTicks += interval;
if (forceUpdateFollowPath || walkUpdateTicks >= 2000) {
walkUpdateTicks = 0;
forceUpdateFollowPath = false;
isUpdatingPath = true;
}
}
if (isUpdatingPath) {
isUpdatingPath = false;
goToFollowCreature();
}
//scripting event - onThink
const CreatureEventList& thinkEvents = getCreatureEvents(CREATURE_EVENT_THINK);
for (CreatureEvent* thinkEvent : thinkEvents) {
thinkEvent->executeOnThink(this, interval);
}
}
void Creature::onAttacking(uint32_t interval)
{
if (!attackedCreature) {
return;
}
onAttacked();
attackedCreature->onAttacked();
if (g_game.isSightClear(getPosition(), attackedCreature->getPosition(), true)) {
doAttacking(interval);
}
}
void Creature::onIdleStatus()
{
if (getHealth() > 0) {
damageMap.clear();
lastHitCreatureId = 0;
}
}
void Creature::onWalk()
{
if (getWalkDelay() <= 0) {
Direction dir;
uint32_t flags = FLAG_IGNOREFIELDDAMAGE;
if (getNextStep(dir, flags)) {
ReturnValue ret = g_game.internalMoveCreature(this, dir, flags);
if (ret != RETURNVALUE_NOERROR) {
if (Player* player = getPlayer()) {
player->sendCancelMessage(ret);
player->sendCancelWalk();
}
forceUpdateFollowPath = true;
}
} else {
if (listWalkDir.empty()) {
onWalkComplete();
}
stopEventWalk();
}
}
if (cancelNextWalk) {
listWalkDir.clear();
onWalkAborted();
cancelNextWalk = false;
}
if (eventWalk != 0) {
eventWalk = 0;
addEventWalk();
}
}
void Creature::onWalk(Direction& dir)
{
if (!hasCondition(CONDITION_DRUNK)) {
return;
}
uint16_t rand = uniform_random(0, 399);
if (rand / 4 > getDrunkenness()) {
return;
}
dir = static_cast<Direction>(rand % 4);
g_game.internalCreatureSay(this, TALKTYPE_MONSTER_SAY, "Hicks!", false);
}
bool Creature::getNextStep(Direction& dir, uint32_t&)
{
if (listWalkDir.empty()) {
return false;
}
dir = listWalkDir.back();
listWalkDir.pop_back();
onWalk(dir);
return true;
}
void Creature::startAutoWalk()
{
Player* player = getPlayer();
if (player && player->isMovementBlocked()) {
player->sendCancelWalk();
return;
}
addEventWalk(listWalkDir.size() == 1);
}
void Creature::startAutoWalk(Direction direction)
{
Player* player = getPlayer();
if (player && player->isMovementBlocked()) {
player->sendCancelWalk();
return;
}
listWalkDir.clear();
listWalkDir.push_back(direction);
addEventWalk(true);
}
void Creature::startAutoWalk(const std::vector<Direction>& listDir)
{
Player* player = getPlayer();
if (player && player->isMovementBlocked()) {
player->sendCancelWalk();
return;
}
listWalkDir = listDir;
addEventWalk(listWalkDir.size() == 1);
}
void Creature::addEventWalk(bool firstStep)
{
cancelNextWalk = false;
if (getStepSpeed() <= 0) {
return;
}
if (eventWalk != 0) {
return;
}
int64_t ticks = getEventStepTicks(firstStep);
if (ticks <= 0) {
return;
}
// Take first step right away, but still queue the next
if (ticks == 1) {
g_game.checkCreatureWalk(getID());
}
eventWalk = g_scheduler.addEvent(createSchedulerTask(ticks, std::bind(&Game::checkCreatureWalk, &g_game, getID())));
}
void Creature::stopEventWalk()
{
if (eventWalk != 0) {
g_scheduler.stopEvent(eventWalk);
eventWalk = 0;
}
}
void Creature::updateMapCache()
{
Tile* tile;
const Position& myPos = getPosition();
Position pos(0, 0, myPos.z);
for (int32_t y = -maxWalkCacheHeight; y <= maxWalkCacheHeight; ++y) {
for (int32_t x = -maxWalkCacheWidth; x <= maxWalkCacheWidth; ++x) {
pos.x = myPos.getX() + x;
pos.y = myPos.getY() + y;
tile = g_game.map.getTile(pos);
updateTileCache(tile, pos);
}
}
}
void Creature::updateTileCache(const Tile* tile, int32_t dx, int32_t dy)
{
if (std::abs(dx) <= maxWalkCacheWidth && std::abs(dy) <= maxWalkCacheHeight) {
localMapCache[maxWalkCacheHeight + dy][maxWalkCacheWidth + dx] = tile && tile->queryAdd(0, *this, 1, FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) == RETURNVALUE_NOERROR;
}
}
void Creature::updateTileCache(const Tile* tile, const Position& pos)
{
const Position& myPos = getPosition();
if (pos.z == myPos.z) {
int32_t dx = Position::getOffsetX(pos, myPos);
int32_t dy = Position::getOffsetY(pos, myPos);
updateTileCache(tile, dx, dy);
}
}
int32_t Creature::getWalkCache(const Position& pos) const
{
if (!useCacheMap()) {
return 2;
}
const Position& myPos = getPosition();
if (myPos.z != pos.z) {
return 0;
}
if (pos == myPos) {
return 1;
}
int32_t dx = Position::getOffsetX(pos, myPos);
if (std::abs(dx) <= maxWalkCacheWidth) {
int32_t dy = Position::getOffsetY(pos, myPos);
if (std::abs(dy) <= maxWalkCacheHeight) {
if (localMapCache[maxWalkCacheHeight + dy][maxWalkCacheWidth + dx]) {
return 1;
} else {
return 0;
}
}
}
//out of range
return 2;
}
void Creature::onAddTileItem(const Tile* tile, const Position& pos)
{
if (isMapLoaded && pos.z == getPosition().z) {
updateTileCache(tile, pos);
}
}
void Creature::onUpdateTileItem(const Tile* tile, const Position& pos, const Item*,
const ItemType& oldType, const Item*, const ItemType& newType)
{
if (!isMapLoaded) {
return;
}
if (oldType.blockSolid || oldType.blockPathFind || newType.blockPathFind || newType.blockSolid) {
if (pos.z == getPosition().z) {
updateTileCache(tile, pos);
}
}
}
void Creature::onRemoveTileItem(const Tile* tile, const Position& pos, const ItemType& iType, const Item*)
{
if (!isMapLoaded) {
return;
}
if (iType.blockSolid || iType.blockPathFind || iType.isGroundTile()) {
if (pos.z == getPosition().z) {
updateTileCache(tile, pos);
}
}
}
void Creature::onCreatureAppear(Creature* creature, bool isLogin)
{
if (creature == this) {
if (useCacheMap()) {
isMapLoaded = true;
updateMapCache();
}
if (isLogin) {
setLastPosition(getPosition());
}
} else if (isMapLoaded) {
if (creature->getPosition().z == getPosition().z) {
updateTileCache(creature->getTile(), creature->getPosition());
}
}
}
void Creature::onRemoveCreature(Creature* creature, bool)
{
onCreatureDisappear(creature, true);
if (creature == this) {
if (master && !master->isRemoved()) {
setMaster(nullptr);
}
} else if (isMapLoaded) {
if (creature->getPosition().z == getPosition().z) {
updateTileCache(creature->getTile(), creature->getPosition());
}
}
}
void Creature::onCreatureDisappear(const Creature* creature, bool isLogout)
{
if (attackedCreature == creature) {
setAttackedCreature(nullptr);
onAttackedCreatureDisappear(isLogout);
}
if (followCreature == creature) {
setFollowCreature(nullptr);
onFollowCreatureDisappear(isLogout);
}
}
void Creature::onChangeZone(ZoneType_t zone)
{
if (attackedCreature && zone == ZONE_PROTECTION) {
onCreatureDisappear(attackedCreature, false);
}
}
void Creature::onAttackedCreatureChangeZone(ZoneType_t zone)
{
if (zone == ZONE_PROTECTION) {
onCreatureDisappear(attackedCreature, false);
}
}
void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos,
const Tile* oldTile, const Position& oldPos, bool teleport)
{
if (creature == this) {
lastStep = OTSYS_TIME();
lastStepCost = 1;
if (!teleport) {
if (oldPos.z != newPos.z) {
//floor change extra cost
lastStepCost = 2;
} else if (Position::getDistanceX(newPos, oldPos) >= 1 && Position::getDistanceY(newPos, oldPos) >= 1) {
//diagonal extra cost
lastStepCost = 3;
}
} else {
stopEventWalk();
}
if (!summons.empty()) {
//check if any of our summons is out of range (+/- 2 floors or 30 tiles away)
std::forward_list<Creature*> despawnList;
for (Creature* summon : summons) {
const Position& pos = summon->getPosition();
if (Position::getDistanceZ(newPos, pos) > 2 || (std::max<int32_t>(Position::getDistanceX(newPos, pos), Position::getDistanceY(newPos, pos)) > 30)) {
despawnList.push_front(summon);
}
}
for (Creature* despawnCreature : despawnList) {
g_game.removeCreature(despawnCreature, true);
}
}
if (newTile->getZone() != oldTile->getZone()) {
onChangeZone(getZone());
}
//update map cache
if (isMapLoaded) {
if (teleport || oldPos.z != newPos.z) {
updateMapCache();
} else {
const Position& myPos = getPosition();
if (oldPos.y > newPos.y) { //north
//shift y south
for (int32_t y = mapWalkHeight - 1; --y >= 0;) {
memcpy(localMapCache[y + 1], localMapCache[y], sizeof(localMapCache[y]));
}
//update 0
for (int32_t x = -maxWalkCacheWidth; x <= maxWalkCacheWidth; ++x) {
Tile* cacheTile = g_game.map.getTile(myPos.getX() + x, myPos.getY() - maxWalkCacheHeight, myPos.z);
updateTileCache(cacheTile, x, -maxWalkCacheHeight);
}
} else if (oldPos.y < newPos.y) { // south
//shift y north
for (int32_t y = 0; y <= mapWalkHeight - 2; ++y) {
memcpy(localMapCache[y], localMapCache[y + 1], sizeof(localMapCache[y]));
}
//update mapWalkHeight - 1
for (int32_t x = -maxWalkCacheWidth; x <= maxWalkCacheWidth; ++x) {
Tile* cacheTile = g_game.map.getTile(myPos.getX() + x, myPos.getY() + maxWalkCacheHeight, myPos.z);
updateTileCache(cacheTile, x, maxWalkCacheHeight);
}
}
if (oldPos.x < newPos.x) { // east
//shift y west
int32_t starty = 0;
int32_t endy = mapWalkHeight - 1;
int32_t dy = Position::getDistanceY(oldPos, newPos);
if (dy < 0) {
endy += dy;
} else if (dy > 0) {
starty = dy;
}
for (int32_t y = starty; y <= endy; ++y) {
for (int32_t x = 0; x <= mapWalkWidth - 2; ++x) {
localMapCache[y][x] = localMapCache[y][x + 1];
}
}
//update mapWalkWidth - 1
for (int32_t y = -maxWalkCacheHeight; y <= maxWalkCacheHeight; ++y) {
Tile* cacheTile = g_game.map.getTile(myPos.x + maxWalkCacheWidth, myPos.y + y, myPos.z);
updateTileCache(cacheTile, maxWalkCacheWidth, y);
}
} else if (oldPos.x > newPos.x) { // west
//shift y east
int32_t starty = 0;
int32_t endy = mapWalkHeight - 1;
int32_t dy = Position::getDistanceY(oldPos, newPos);
if (dy < 0) {
endy += dy;
} else if (dy > 0) {
starty = dy;
}
for (int32_t y = starty; y <= endy; ++y) {
for (int32_t x = mapWalkWidth - 1; --x >= 0;) {
localMapCache[y][x + 1] = localMapCache[y][x];
}
}
//update 0
for (int32_t y = -maxWalkCacheHeight; y <= maxWalkCacheHeight; ++y) {
Tile* cacheTile = g_game.map.getTile(myPos.x - maxWalkCacheWidth, myPos.y + y, myPos.z);
updateTileCache(cacheTile, -maxWalkCacheWidth, y);
}
}
updateTileCache(oldTile, oldPos);
}
}
} else {
if (isMapLoaded) {
const Position& myPos = getPosition();
if (newPos.z == myPos.z) {
updateTileCache(newTile, newPos);
}
if (oldPos.z == myPos.z) {
updateTileCache(oldTile, oldPos);
}
}
}
if (creature == followCreature || (creature == this && followCreature)) {
if (hasFollowPath) {
isUpdatingPath = true;
}
if (newPos.z != oldPos.z || !canSee(followCreature->getPosition())) {
onCreatureDisappear(followCreature, false);
}
}
if (creature == attackedCreature || (creature == this && attackedCreature)) {
if (newPos.z != oldPos.z || !canSee(attackedCreature->getPosition())) {
onCreatureDisappear(attackedCreature, false);
} else {
if (hasExtraSwing()) {
//our target is moving lets see if we can get in hit
g_dispatcher.addTask(createTask(std::bind(&Game::checkCreatureAttack, &g_game, getID())));
}
if (newTile->getZone() != oldTile->getZone()) {
onAttackedCreatureChangeZone(attackedCreature->getZone());
}
}
}
}
CreatureVector Creature::getKillers()
{
CreatureVector killers;
const int64_t timeNow = OTSYS_TIME();
const uint32_t inFightTicks = g_config.getNumber(ConfigManager::PZ_LOCKED);
for (const auto& it : damageMap) {
Creature* attacker = g_game.getCreatureByID(it.first);
if (attacker && attacker != this && timeNow - it.second.ticks <= inFightTicks) {
killers.push_back(attacker);
}
}
return killers;
}
void Creature::onDeath()
{
bool lastHitUnjustified = false;
bool mostDamageUnjustified = false;
Creature* lastHitCreature = g_game.getCreatureByID(lastHitCreatureId);
Creature* lastHitCreatureMaster;
if (lastHitCreature) {
lastHitUnjustified = lastHitCreature->onKilledCreature(this);
lastHitCreatureMaster = lastHitCreature->getMaster();
} else {
lastHitCreatureMaster = nullptr;
}
Creature* mostDamageCreature = nullptr;
const int64_t timeNow = OTSYS_TIME();
const uint32_t inFightTicks = g_config.getNumber(ConfigManager::PZ_LOCKED);
int32_t mostDamage = 0;
std::map<Creature*, uint64_t> experienceMap;
for (const auto& it : damageMap) {
if (Creature* attacker = g_game.getCreatureByID(it.first)) {
CountBlock_t cb = it.second;
if ((cb.total > mostDamage && (timeNow - cb.ticks <= inFightTicks))) {
mostDamage = cb.total;
mostDamageCreature = attacker;
}
if (attacker != this) {
uint64_t gainExp = getGainedExperience(attacker);
if (Player* attackerPlayer = attacker->getPlayer()) {
attackerPlayer->removeAttacked(getPlayer());
Party* party = attackerPlayer->getParty();
if (party && party->getLeader() && party->isSharedExperienceActive() && party->isSharedExperienceEnabled()) {
attacker = party->getLeader();
}
}
auto tmpIt = experienceMap.find(attacker);
if (tmpIt == experienceMap.end()) {
experienceMap[attacker] = gainExp;
} else {
tmpIt->second += gainExp;
}
}
}
}
for (const auto& it : experienceMap) {
it.first->onGainExperience(it.second, this);
}
if (mostDamageCreature) {
if (mostDamageCreature != lastHitCreature && mostDamageCreature != lastHitCreatureMaster) {
Creature* mostDamageCreatureMaster = mostDamageCreature->getMaster();
if (lastHitCreature != mostDamageCreatureMaster && (lastHitCreatureMaster == nullptr || mostDamageCreatureMaster != lastHitCreatureMaster)) {
mostDamageUnjustified = mostDamageCreature->onKilledCreature(this, false);
}
}
}
bool droppedCorpse = dropCorpse(lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified);
death(lastHitCreature);
if (master) {
setMaster(nullptr);
}
if (droppedCorpse) {
g_game.removeCreature(this, false);
}
}
bool Creature::dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified)
{
if (!lootDrop && getMonster()) {
if (master) {
//scripting event - onDeath
const CreatureEventList& deathEvents = getCreatureEvents(CREATURE_EVENT_DEATH);
for (CreatureEvent* deathEvent : deathEvents) {
deathEvent->executeOnDeath(this, nullptr, lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified);
}
}
g_game.addMagicEffect(getPosition(), CONST_ME_POFF);
} else {
Item* splash;
switch (getRace()) {
case RACE_VENOM:
splash = Item::CreateItem(ITEM_FULLSPLASH, FLUID_SLIME);
break;
case RACE_BLOOD:
splash = Item::CreateItem(ITEM_FULLSPLASH, FLUID_BLOOD);
break;
default:
splash = nullptr;
break;
}
Tile* tile = getTile();
if (splash) {
g_game.internalAddItem(tile, splash, INDEX_WHEREEVER, FLAG_NOLIMIT);
g_game.startDecay(splash);
}
Item* corpse = getCorpse(lastHitCreature, mostDamageCreature);
if (corpse) {
g_game.internalAddItem(tile, corpse, INDEX_WHEREEVER, FLAG_NOLIMIT);
g_game.startDecay(corpse);
}
//scripting event - onDeath
for (CreatureEvent* deathEvent : getCreatureEvents(CREATURE_EVENT_DEATH)) {
deathEvent->executeOnDeath(this, corpse, lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified);
}
if (corpse) {
dropLoot(corpse->getContainer(), lastHitCreature);
}
}
return true;
}
bool Creature::hasBeenAttacked(uint32_t attackerId)
{
auto it = damageMap.find(attackerId);
if (it == damageMap.end()) {
return false;
}
return (OTSYS_TIME() - it->second.ticks) <= g_config.getNumber(ConfigManager::PZ_LOCKED);
}
Item* Creature::getCorpse(Creature*, Creature*)
{
return Item::CreateItem(getLookCorpse());
}
void Creature::changeHealth(int32_t healthChange, bool sendHealthChange/* = true*/)
{
int32_t oldHealth = health;
if (healthChange > 0) {
health += std::min<int32_t>(healthChange, getMaxHealth() - health);
} else {
health = std::max<int32_t>(0, health + healthChange);
}
if (sendHealthChange && oldHealth != health) {
g_game.addCreatureHealth(this);
}
if (health <= 0) {
g_dispatcher.addTask(createTask(std::bind(&Game::executeDeath, &g_game, getID())));
}
}
void Creature::gainHealth(Creature* healer, int32_t healthGain)
{
changeHealth(healthGain);
if (healer) {
healer->onTargetCreatureGainHealth(this, healthGain);
}
}
void Creature::drainHealth(Creature* attacker, int32_t damage)
{
changeHealth(-damage, false);
if (attacker) {
attacker->onAttackedCreatureDrainHealth(this, damage);
} else {
lastHitCreatureId = 0;
}
}
BlockType_t Creature::blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage,
bool checkDefense /* = false */, bool checkArmor /* = false */, bool /* field = false */, bool /* ignoreResistances = false */)
{
BlockType_t blockType = BLOCK_NONE;
if (isImmune(combatType)) {
damage = 0;
blockType = BLOCK_IMMUNITY;
} else if (checkDefense || checkArmor) {
bool hasDefense = false;
if (blockCount > 0) {
--blockCount;
hasDefense = true;
}
if (checkDefense && hasDefense && canUseDefense) {
int32_t defense = getDefense();
damage -= uniform_random(defense / 2, defense);
if (damage <= 0) {
damage = 0;
blockType = BLOCK_DEFENSE;
checkArmor = false;
}
}
if (checkArmor) {
int32_t armor = getArmor();
if (armor > 3) {
damage -= uniform_random(armor / 2, armor - (armor % 2 + 1));
} else if (armor > 0) {
--damage;
}
if (damage <= 0) {
damage = 0;
blockType = BLOCK_ARMOR;
}
}
if (hasDefense && blockType != BLOCK_NONE) {
onBlockHit();
}
}
if (attacker) {
attacker->onAttackedCreature(this);
attacker->onAttackedCreatureBlockHit(blockType);
}
onAttacked();
return blockType;
}
bool Creature::setAttackedCreature(Creature* creature)
{
if (creature) {
const Position& creaturePos = creature->getPosition();
if (creaturePos.z != getPosition().z || !canSee(creaturePos)) {
attackedCreature = nullptr;
return false;
}
attackedCreature = creature;
onAttackedCreature(attackedCreature);
attackedCreature->onAttacked();
} else {
attackedCreature = nullptr;
}
for (Creature* summon : summons) {
summon->setAttackedCreature(creature);
}
return true;
}
void Creature::getPathSearchParams(const Creature*, FindPathParams& fpp) const
{
fpp.fullPathSearch = !hasFollowPath;
fpp.clearSight = true;
fpp.maxSearchDist = 12;
fpp.minTargetDist = 1;
fpp.maxTargetDist = 1;
}
void Creature::goToFollowCreature()
{
if (followCreature) {
FindPathParams fpp;
getPathSearchParams(followCreature, fpp);
Monster* monster = getMonster();
if (monster && !monster->getMaster() && (monster->isFleeing() || fpp.maxTargetDist > 1)) {
Direction dir = DIRECTION_NONE;
if (monster->isFleeing()) {
monster->getDistanceStep(followCreature->getPosition(), dir, true);
} else { // maxTargetDist > 1
if (!monster->getDistanceStep(followCreature->getPosition(), dir)) {
// if we can't get anything then let the A* calculate
listWalkDir.clear();
if (getPathTo(followCreature->getPosition(), listWalkDir, fpp)) {
hasFollowPath = true;
startAutoWalk();
} else {
hasFollowPath = false;
}
return;
}
}
if (dir != DIRECTION_NONE) {
listWalkDir.clear();
listWalkDir.push_back(dir);
hasFollowPath = true;
startAutoWalk();
}
} else {
listWalkDir.clear();
if (getPathTo(followCreature->getPosition(), listWalkDir, fpp)) {
hasFollowPath = true;
startAutoWalk();
} else {
hasFollowPath = false;
}
}
}
onFollowCreatureComplete(followCreature);
}
bool Creature::setFollowCreature(Creature* creature)
{
if (creature) {
if (followCreature == creature) {
return true;
}
const Position& creaturePos = creature->getPosition();
if (creaturePos.z != getPosition().z || !canSee(creaturePos)) {
followCreature = nullptr;
return false;
}
if (!listWalkDir.empty()) {
listWalkDir.clear();
onWalkAborted();
}
hasFollowPath = false;
forceUpdateFollowPath = false;
followCreature = creature;
isUpdatingPath = true;
} else {
isUpdatingPath = false;
followCreature = nullptr;
}
onFollowCreature(creature);
return true;
}
double Creature::getDamageRatio(Creature* attacker) const
{
uint32_t totalDamage = 0;
uint32_t attackerDamage = 0;
for (const auto& it : damageMap) {
const CountBlock_t& cb = it.second;
totalDamage += cb.total;
if (it.first == attacker->getID()) {
attackerDamage += cb.total;
}
}
if (totalDamage == 0) {
return 0;
}
return (static_cast<double>(attackerDamage) / totalDamage);
}
uint64_t Creature::getGainedExperience(Creature* attacker) const
{
return std::floor(getDamageRatio(attacker) * getLostExperience());
}
void Creature::addDamagePoints(Creature* attacker, int32_t damagePoints)
{
if (damagePoints <= 0) {
return;
}
uint32_t attackerId = attacker->id;
auto it = damageMap.find(attackerId);
if (it == damageMap.end()) {
CountBlock_t cb;
cb.ticks = OTSYS_TIME();
cb.total = damagePoints;
damageMap[attackerId] = cb;
} else {
it->second.total += damagePoints;
it->second.ticks = OTSYS_TIME();
}
lastHitCreatureId = attackerId;
}
void Creature::onAddCondition(ConditionType_t type)
{
if (type == CONDITION_PARALYZE && hasCondition(CONDITION_HASTE)) {
removeCondition(CONDITION_HASTE);
} else if (type == CONDITION_HASTE && hasCondition(CONDITION_PARALYZE)) {
removeCondition(CONDITION_PARALYZE);
}
}
void Creature::onAddCombatCondition(ConditionType_t)
{
//
}
void Creature::onEndCondition(ConditionType_t)
{
//
}
void Creature::onTickCondition(ConditionType_t type, bool& bRemove)
{
const MagicField* field = getTile()->getFieldItem();
if (!field) {
return;
}
switch (type) {
case CONDITION_FIRE:
bRemove = (field->getCombatType() != COMBAT_FIREDAMAGE);
break;
case CONDITION_ENERGY:
bRemove = (field->getCombatType() != COMBAT_ENERGYDAMAGE);
break;
case CONDITION_POISON:
bRemove = (field->getCombatType() != COMBAT_EARTHDAMAGE);
break;
case CONDITION_FREEZING:
bRemove = (field->getCombatType() != COMBAT_ICEDAMAGE);
break;
case CONDITION_DAZZLED:
bRemove = (field->getCombatType() != COMBAT_HOLYDAMAGE);
break;
case CONDITION_CURSED:
bRemove = (field->getCombatType() != COMBAT_DEATHDAMAGE);
break;
case CONDITION_DROWN:
bRemove = (field->getCombatType() != COMBAT_DROWNDAMAGE);
break;
case CONDITION_BLEEDING:
bRemove = (field->getCombatType() != COMBAT_PHYSICALDAMAGE);
break;
default:
break;
}
}
void Creature::onCombatRemoveCondition(Condition* condition)
{
removeCondition(condition);
}
void Creature::onAttacked()
{
//
}
void Creature::onAttackedCreatureDrainHealth(Creature* target, int32_t points)
{
target->addDamagePoints(this, points);
}
bool Creature::onKilledCreature(Creature* target, bool)
{
if (master) {
master->onKilledCreature(target);
}
//scripting event - onKill
const CreatureEventList& killEvents = getCreatureEvents(CREATURE_EVENT_KILL);
for (CreatureEvent* killEvent : killEvents) {
killEvent->executeOnKill(this, target);
}
return false;
}
void Creature::onGainExperience(uint64_t gainExp, Creature* target)
{
if (gainExp == 0 || !master) {
return;
}
gainExp /= 2;
master->onGainExperience(gainExp, target);
SpectatorVec spectators;
g_game.map.getSpectators(spectators, position, false, true);
if (spectators.empty()) {
return;
}
TextMessage message(MESSAGE_EXPERIENCE_OTHERS, ucfirst(getNameDescription()) + " gained " + std::to_string(gainExp) + (gainExp != 1 ? " experience points." : " experience point."));
message.position = position;
message.primary.color = TEXTCOLOR_WHITE_EXP;
message.primary.value = gainExp;
for (Creature* spectator : spectators) {
spectator->getPlayer()->sendTextMessage(message);
}
}
bool Creature::setMaster(Creature* newMaster) {
if (!newMaster && !master) {
return false;
}
if (newMaster) {
incrementReferenceCounter();
newMaster->summons.push_back(this);
}
Creature* oldMaster = master;
master = newMaster;
if (oldMaster) {
auto summon = std::find(oldMaster->summons.begin(), oldMaster->summons.end(), this);
if (summon != oldMaster->summons.end()) {
oldMaster->summons.erase(summon);
decrementReferenceCounter();
}
}
return true;
}
bool Creature::addCondition(Condition* condition, bool force/* = false*/)
{
if (condition == nullptr) {
return false;
}
if (!force && condition->getType() == CONDITION_HASTE && hasCondition(CONDITION_PARALYZE)) {
int64_t walkDelay = getWalkDelay();
if (walkDelay > 0) {
g_scheduler.addEvent(createSchedulerTask(walkDelay, std::bind(&Game::forceAddCondition, &g_game, getID(), condition)));
return false;
}
}
Condition* prevCond = getCondition(condition->getType(), condition->getId(), condition->getSubId());
if (prevCond) {
prevCond->addCondition(this, condition);
delete condition;
return true;
}
if (condition->startCondition(this)) {
conditions.push_back(condition);
onAddCondition(condition->getType());
return true;
}
delete condition;
return false;
}
bool Creature::addCombatCondition(Condition* condition)
{
//Caution: condition variable could be deleted after the call to addCondition
ConditionType_t type = condition->getType();
if (!addCondition(condition)) {
return false;
}
onAddCombatCondition(type);
return true;
}
void Creature::removeCondition(ConditionType_t type, bool force/* = false*/)
{
auto it = conditions.begin(), end = conditions.end();
while (it != end) {
Condition* condition = *it;
if (condition->getType() != type) {
++it;
continue;
}
if (!force && type == CONDITION_PARALYZE) {
int64_t walkDelay = getWalkDelay();
if (walkDelay > 0) {
g_scheduler.addEvent(createSchedulerTask(walkDelay, std::bind(&Game::forceRemoveCondition, &g_game, getID(), type)));
return;
}
}
it = conditions.erase(it);
condition->endCondition(this);
delete condition;
onEndCondition(type);
}
}
void Creature::removeCondition(ConditionType_t type, ConditionId_t conditionId, bool force/* = false*/)
{
auto it = conditions.begin(), end = conditions.end();
while (it != end) {
Condition* condition = *it;
if (condition->getType() != type || condition->getId() != conditionId) {
++it;
continue;
}
if (!force && type == CONDITION_PARALYZE) {
int64_t walkDelay = getWalkDelay();
if (walkDelay > 0) {
g_scheduler.addEvent(createSchedulerTask(walkDelay, std::bind(&Game::forceRemoveCondition, &g_game, getID(), type)));
return;
}
}
it = conditions.erase(it);
condition->endCondition(this);
delete condition;
onEndCondition(type);
}
}
void Creature::removeCombatCondition(ConditionType_t type)
{
std::vector<Condition*> removeConditions;
for (Condition* condition : conditions) {
if (condition->getType() == type) {
removeConditions.push_back(condition);
}
}
for (Condition* condition : removeConditions) {
onCombatRemoveCondition(condition);
}
}
void Creature::removeCondition(Condition* condition, bool force/* = false*/)
{
auto it = std::find(conditions.begin(), conditions.end(), condition);
if (it == conditions.end()) {
return;
}
if (!force && condition->getType() == CONDITION_PARALYZE) {
int64_t walkDelay = getWalkDelay();
if (walkDelay > 0) {
g_scheduler.addEvent(createSchedulerTask(walkDelay, std::bind(&Game::forceRemoveCondition, &g_game, getID(), condition->getType())));
return;
}
}
conditions.erase(it);
condition->endCondition(this);
onEndCondition(condition->getType());
delete condition;
}
Condition* Creature::getCondition(ConditionType_t type) const
{
for (Condition* condition : conditions) {
if (condition->getType() == type) {
return condition;
}
}
return nullptr;
}
Condition* Creature::getCondition(ConditionType_t type, ConditionId_t conditionId, uint32_t subId/* = 0*/) const
{
for (Condition* condition : conditions) {
if (condition->getType() == type && condition->getId() == conditionId && condition->getSubId() == subId) {
return condition;
}
}
return nullptr;
}
void Creature::executeConditions(uint32_t interval)
{
ConditionList tempConditions{ conditions };
for (Condition* condition : tempConditions) {
auto it = std::find(conditions.begin(), conditions.end(), condition);
if (it == conditions.end()) {
continue;
}
if (!condition->executeCondition(this, interval)) {
it = std::find(conditions.begin(), conditions.end(), condition);
if (it != conditions.end()) {
conditions.erase(it);
condition->endCondition(this);
onEndCondition(condition->getType());
delete condition;
}
}
}
}
bool Creature::hasCondition(ConditionType_t type, uint32_t subId/* = 0*/) const
{
if (isSuppress(type)) {
return false;
}
int64_t timeNow = OTSYS_TIME();
for (Condition* condition : conditions) {
if (condition->getType() != type || condition->getSubId() != subId) {
continue;
}
if (condition->getEndTime() >= timeNow || condition->getTicks() == -1) {
return true;
}
}
return false;
}
bool Creature::isImmune(CombatType_t type) const
{
return hasBitSet(static_cast<uint32_t>(type), getDamageImmunities());
}
bool Creature::isImmune(ConditionType_t type) const
{
return hasBitSet(static_cast<uint32_t>(type), getConditionImmunities());
}
bool Creature::isSuppress(ConditionType_t type) const
{
return hasBitSet(static_cast<uint32_t>(type), getConditionSuppressions());
}
int64_t Creature::getStepDuration(Direction dir) const
{
int64_t stepDuration = getStepDuration();
if ((dir & DIRECTION_DIAGONAL_MASK) != 0) {
stepDuration *= 3;
}
return stepDuration;
}
int64_t Creature::getStepDuration() const
{
if (isRemoved()) {
return 0;
}
uint32_t calculatedStepSpeed;
uint32_t groundSpeed;
int32_t stepSpeed = getStepSpeed();
if (stepSpeed > -Creature::speedB) {
calculatedStepSpeed = floor((Creature::speedA * log((stepSpeed / 2) + Creature::speedB) + Creature::speedC) + 0.5);
if (calculatedStepSpeed == 0) {
calculatedStepSpeed = 1;
}
} else {
calculatedStepSpeed = 1;
}
Item* ground = tile->getGround();
if (ground) {
groundSpeed = Item::items[ground->getID()].speed;
if (groundSpeed == 0) {
groundSpeed = 150;
}
} else {
groundSpeed = 150;
}
double duration = std::floor(1000 * groundSpeed / calculatedStepSpeed);
int64_t stepDuration = std::ceil(duration / 50) * 50;
const Monster* monster = getMonster();
if (monster && monster->isTargetNearby() && !monster->isFleeing() && !monster->getMaster()) {
stepDuration *= 2;
}
return stepDuration;
}
int64_t Creature::getEventStepTicks(bool onlyDelay) const
{
int64_t ret = getWalkDelay();
if (ret <= 0) {
int64_t stepDuration = getStepDuration();
if (onlyDelay && stepDuration > 0) {
ret = 1;
} else {
ret = stepDuration * lastStepCost;
}
}
return ret;
}
LightInfo Creature::getCreatureLight() const
{
return internalLight;
}
void Creature::setCreatureLight(LightInfo lightInfo) {
internalLight = std::move(lightInfo);
}
void Creature::setNormalCreatureLight()
{
internalLight = {};
}
bool Creature::registerCreatureEvent(const std::string& name)
{
CreatureEvent* event = g_creatureEvents->getEventByName(name);
if (!event) {
return false;
}
CreatureEventType_t type = event->getEventType();
if (hasEventRegistered(type)) {
for (CreatureEvent* creatureEvent : eventsList) {
if (creatureEvent == event) {
return false;
}
}
} else {
scriptEventsBitField |= static_cast<uint32_t>(1) << type;
}
eventsList.push_back(event);
return true;
}
bool Creature::unregisterCreatureEvent(const std::string& name)
{
CreatureEvent* event = g_creatureEvents->getEventByName(name);
if (!event) {
return false;
}
CreatureEventType_t type = event->getEventType();
if (!hasEventRegistered(type)) {
return false;
}
bool resetTypeBit = true;
auto it = eventsList.begin(), end = eventsList.end();
while (it != end) {
CreatureEvent* curEvent = *it;
if (curEvent == event) {
it = eventsList.erase(it);
continue;
}
if (curEvent->getEventType() == type) {
resetTypeBit = false;
}
++it;
}
if (resetTypeBit) {
scriptEventsBitField &= ~(static_cast<uint32_t>(1) << type);
}
return true;
}
CreatureEventList Creature::getCreatureEvents(CreatureEventType_t type)
{
CreatureEventList tmpEventList;
if (!hasEventRegistered(type)) {
return tmpEventList;
}
for (CreatureEvent* creatureEvent : eventsList) {
if (!creatureEvent->isLoaded()) {
continue;
}
if (creatureEvent->getEventType() == type) {
tmpEventList.push_back(creatureEvent);
}
}
return tmpEventList;
}
bool FrozenPathingConditionCall::isInRange(const Position& startPos, const Position& testPos,
const FindPathParams& fpp) const
{
if (fpp.fullPathSearch) {
if (testPos.x > targetPos.x + fpp.maxTargetDist) {
return false;
}
if (testPos.x < targetPos.x - fpp.maxTargetDist) {
return false;
}
if (testPos.y > targetPos.y + fpp.maxTargetDist) {
return false;
}
if (testPos.y < targetPos.y - fpp.maxTargetDist) {
return false;
}
} else {
int_fast32_t dx = Position::getOffsetX(startPos, targetPos);
int32_t dxMax = (dx >= 0 ? fpp.maxTargetDist : 0);
if (testPos.x > targetPos.x + dxMax) {
return false;
}
int32_t dxMin = (dx <= 0 ? fpp.maxTargetDist : 0);
if (testPos.x < targetPos.x - dxMin) {
return false;
}
int_fast32_t dy = Position::getOffsetY(startPos, targetPos);
int32_t dyMax = (dy >= 0 ? fpp.maxTargetDist : 0);
if (testPos.y > targetPos.y + dyMax) {
return false;
}
int32_t dyMin = (dy <= 0 ? fpp.maxTargetDist : 0);
if (testPos.y < targetPos.y - dyMin) {
return false;
}
}
return true;
}
bool FrozenPathingConditionCall::operator()(const Position& startPos, const Position& testPos,
const FindPathParams& fpp, int32_t& bestMatchDist) const
{
if (!isInRange(startPos, testPos, fpp)) {
return false;
}
if (fpp.clearSight && !g_game.isSightClear(testPos, targetPos, true)) {
return false;
}
int32_t testDist = std::max<int32_t>(Position::getDistanceX(targetPos, testPos), Position::getDistanceY(targetPos, testPos));
if (fpp.maxTargetDist == 1) {
if (testDist < fpp.minTargetDist || testDist > fpp.maxTargetDist) {
return false;
}
return true;
} else if (testDist <= fpp.maxTargetDist) {
if (testDist < fpp.minTargetDist) {
return false;
}
if (testDist == fpp.maxTargetDist) {
bestMatchDist = 0;
return true;
} else if (testDist > bestMatchDist) {
//not quite what we want, but the best so far
bestMatchDist = testDist;
return true;
}
}
return false;
}
bool Creature::isInvisible() const
{
return std::find_if(conditions.begin(), conditions.end(), [] (const Condition* condition) {
return condition->getType() == CONDITION_INVISIBLE;
}) != conditions.end();
}
bool Creature::getPathTo(const Position& targetPos, std::vector<Direction>& dirList, const FindPathParams& fpp) const
{
return g_game.map.getPathMatching(*this, dirList, FrozenPathingConditionCall(targetPos), fpp);
}
bool Creature::getPathTo(const Position& targetPos, std::vector<Direction>& dirList, int32_t minTargetDist, int32_t maxTargetDist, bool fullPathSearch /*= true*/, bool clearSight /*= true*/, int32_t maxSearchDist /*= 0*/) const
{
FindPathParams fpp;
fpp.fullPathSearch = fullPathSearch;
fpp.maxSearchDist = maxSearchDist;
fpp.clearSight = clearSight;
fpp.minTargetDist = minTargetDist;
fpp.maxTargetDist = maxTargetDist;
return getPathTo(targetPos, dirList, fpp);
}
| 1 | 19,330 | Walk should actually be completed (`onWalkCompleted`) after the event is stopped. This also makes it possible for monster to walk by smaller paths. | otland-forgottenserver | cpp |
@@ -31,6 +31,17 @@ func NewSimpleJoiner(getter storage.Getter) file.Joiner {
}
func (s *simpleJoiner) Size(ctx context.Context, address swarm.Address) (dataSize int64, err error) {
+ // Handle size based on weather the root chunk is encrypted or not
+ toDecrypt := len(address.Bytes()) == swarm.EncryptedReferenceSize
+
+ var key encryption.Key
+ addrBytes := address.Bytes()
+ if toDecrypt {
+ addrBytes = address.Bytes()[:swarm.HashSize]
+ key = address.Bytes()[swarm.HashSize : swarm.HashSize+encryption.KeyLength]
+ }
+
+ address = swarm.NewAddress(addrBytes)
// retrieve the root chunk to read the total data length the be retrieved
rootChunk, err := s.getter.Get(ctx, storage.ModeGetRequest, address)
if err != nil { | 1 | // Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package joiner provides implementations of the file.Joiner interface
package joiner
import (
"context"
"encoding/binary"
"fmt"
"io"
"github.com/ethersphere/bee/pkg/encryption"
"github.com/ethersphere/bee/pkg/file"
"github.com/ethersphere/bee/pkg/file/joiner/internal"
"github.com/ethersphere/bee/pkg/storage"
"github.com/ethersphere/bee/pkg/swarm"
)
// simpleJoiner wraps a non-optimized implementation of file.Joiner.
type simpleJoiner struct {
getter storage.Getter
}
// NewSimpleJoiner creates a new simpleJoiner.
func NewSimpleJoiner(getter storage.Getter) file.Joiner {
return &simpleJoiner{
getter: getter,
}
}
func (s *simpleJoiner) Size(ctx context.Context, address swarm.Address) (dataSize int64, err error) {
// retrieve the root chunk to read the total data length the be retrieved
rootChunk, err := s.getter.Get(ctx, storage.ModeGetRequest, address)
if err != nil {
return 0, err
}
chunkLength := rootChunk.Data()
if len(chunkLength) < 8 {
return 0, fmt.Errorf("invalid chunk content of %d bytes", chunkLength)
}
dataLength := binary.LittleEndian.Uint64(rootChunk.Data())
return int64(dataLength), nil
}
// Join implements the file.Joiner interface.
//
// It uses a non-optimized internal component that only retrieves a data chunk
// after the previous has been read.
func (s *simpleJoiner) Join(ctx context.Context, address swarm.Address, toDecrypt bool) (dataOut io.ReadCloser, dataSize int64, err error) {
var addr []byte
var key encryption.Key
if toDecrypt {
addr = address.Bytes()[:swarm.HashSize]
key = address.Bytes()[swarm.HashSize : swarm.HashSize+encryption.KeyLength]
} else {
addr = address.Bytes()
}
// retrieve the root chunk to read the total data length the be retrieved
rootChunk, err := s.getter.Get(ctx, storage.ModeGetRequest, swarm.NewAddress(addr))
if err != nil {
return nil, 0, err
}
var chunkData []byte
if toDecrypt {
originalData, err := internal.DecryptChunkData(rootChunk.Data(), key)
if err != nil {
return nil, 0, err
}
chunkData = originalData
} else {
chunkData = rootChunk.Data()
}
// if this is a single chunk, short circuit to returning just that chunk
spanLength := binary.LittleEndian.Uint64(chunkData[:8])
chunkToSend := rootChunk
if spanLength <= swarm.ChunkSize {
data := chunkData[8:]
return file.NewSimpleReadCloser(data), int64(spanLength), nil
}
if toDecrypt {
chunkToSend = swarm.NewChunk(swarm.NewAddress(addr), chunkData)
}
r := internal.NewSimpleJoinerJob(ctx, s.getter, chunkToSend, toDecrypt)
return r, int64(spanLength), nil
}
| 1 | 11,546 | typo in `weather` (should be `whether`) | ethersphere-bee | go |
@@ -35,6 +35,7 @@ var (
sourceOS = flag.String("source-os", "", fmt.Sprintf("OS version of the source instance to upgrade. Supported values: %v", strings.Join(upgrader.SupportedSourceOSVersions(), ", ")))
targetOS = flag.String("target-os", "", fmt.Sprintf("Version of the OS after upgrade. Supported values: %v", strings.Join(upgrader.SupportedTargetOSVersions(), ", ")))
timeout = flag.String("timeout", "", "Maximum time limit for an upgrade. For example, if the time limit is set to 2h, the upgrade times out after two hours. For more information about time duration formats, see $ gcloud topic datetimes")
+ useStagingInstallMedia = flag.Bool("use-staging-install-media", false, "Use staging install media. This flag is for testing only. Set to true to upgrade with staging windows install media.")
scratchBucketGcsPath = flag.String("scratch-bucket-gcs-path", "", "Scratch GCS bucket. This setting overrides the workflow setting.")
oauth = flag.String("oauth", "", "Path to OAuth .json file. This setting overrides the workflow setting.")
ce = flag.String("compute-endpoint-override", "", "API endpoint. This setting overrides the default API endpoint setting.") | 1 | // Copyright 2020 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.
// gce_windows_upgrade is a tool for upgrading GCE Windows instances.
package main
import (
"flag"
"fmt"
"os"
"strings"
"github.com/GoogleCloudPlatform/compute-image-tools/cli_tools/common/utils/logging/service"
"github.com/GoogleCloudPlatform/compute-image-tools/cli_tools/gce_windows_upgrade/upgrader"
)
var (
clientID = flag.String(upgrader.ClientIDFlagKey, "", "Identifies the upgrade client. Set to `gcloud`, `api` or `pantheon`.")
project = flag.String("project", "", "Project containing the instance to upgrade.")
zone = flag.String("zone", "", "Project containing the instance to upgrade.")
instance = flag.String("instance", "Instance to upgrade. Can be either the instance name or the full path to the instance in the following format: 'projects/<project>/zones/<zone>/instances/'. If the full path is specified, flags -project and -zone will be ignored.", "")
skipMachineImageBackup = flag.Bool("skip-machine-image-backup", false, "Set to false to generate a backup for the instance. Set to true to prevent generation of a backup instance. True is not recommended unless there is already a backup of the instance.")
autoRollback = flag.Bool("auto-rollback", false, "Set to false to retain the OS disk after a failed upgrade. Set to true to delete the OS disk that failed to upgrade; setting to true can make debugging more difficult.")
sourceOS = flag.String("source-os", "", fmt.Sprintf("OS version of the source instance to upgrade. Supported values: %v", strings.Join(upgrader.SupportedSourceOSVersions(), ", ")))
targetOS = flag.String("target-os", "", fmt.Sprintf("Version of the OS after upgrade. Supported values: %v", strings.Join(upgrader.SupportedTargetOSVersions(), ", ")))
timeout = flag.String("timeout", "", "Maximum time limit for an upgrade. For example, if the time limit is set to 2h, the upgrade times out after two hours. For more information about time duration formats, see $ gcloud topic datetimes")
scratchBucketGcsPath = flag.String("scratch-bucket-gcs-path", "", "Scratch GCS bucket. This setting overrides the workflow setting.")
oauth = flag.String("oauth", "", "Path to OAuth .json file. This setting overrides the workflow setting.")
ce = flag.String("compute-endpoint-override", "", "API endpoint. This setting overrides the default API endpoint setting.")
gcsLogsDisabled = flag.Bool("disable-gcs-logging", false, "Set to false to prevent logs from being saved to GCS.")
cloudLogsDisabled = flag.Bool("disable-cloud-logging", false, "Set to false to prevent logs from being saved to Cloud Logging.")
stdoutLogsDisabled = flag.Bool("disable-stdout-logging", false, "Set to false to disable detailed stdout information.")
)
func upgradeEntry() (service.Loggable, error) {
p := &upgrader.InputParams{
ClientID: strings.TrimSpace(*clientID),
Instance: strings.TrimSpace(*instance),
SkipMachineImageBackup: *skipMachineImageBackup,
AutoRollback: *autoRollback,
SourceOS: strings.TrimSpace(*sourceOS),
TargetOS: strings.TrimSpace(*targetOS),
ProjectPtr: project,
Zone: *zone,
Timeout: strings.TrimSpace(*timeout),
ScratchBucketGcsPath: strings.TrimSpace(*scratchBucketGcsPath),
Oauth: strings.TrimSpace(*oauth),
Ce: strings.TrimSpace(*ce),
GcsLogsDisabled: *gcsLogsDisabled,
CloudLogsDisabled: *cloudLogsDisabled,
StdoutLogsDisabled: *stdoutLogsDisabled,
}
return upgrader.Run(p)
}
func main() {
flag.Parse()
paramLog := service.InputParams{
WindowsUpgradeParams: &service.WindowsUpgradeParams{
CommonParams: &service.CommonParams{
ClientID: *clientID,
Timeout: *timeout,
Project: *project,
ObfuscatedProject: service.Hash(*project),
Zone: *zone,
ScratchBucketGcsPath: *scratchBucketGcsPath,
Oauth: *oauth,
ComputeEndpointOverride: *ce,
DisableGcsLogging: *gcsLogsDisabled,
DisableCloudLogging: *cloudLogsDisabled,
DisableStdoutLogging: *stdoutLogsDisabled,
},
Instance: *instance,
SkipMachineImageBackup: *skipMachineImageBackup,
AutoRollback: *autoRollback,
SourceOS: *sourceOS,
TargetOS: *targetOS,
},
}
if err := service.RunWithServerLogging(service.WindowsUpgrade, paramLog, project, upgradeEntry); err != nil {
os.Exit(1)
}
}
| 1 | 10,886 | Thoughts on having the URI as the param, instead of a boolean? The default value would be the normal prod image, and then your test would override with the staging image. | GoogleCloudPlatform-compute-image-tools | go |
@@ -351,7 +351,8 @@ static bool ReadAAPairs(
return false;
}
unsigned n = 0;
- fscanf(fp, "%d", &n);
+ int num_scan = fscanf(fp, "%d", &n);
+ RDUNUSED_PARAM(num_scan);
char buffer[80];
| 1 | //
// Copyright (C) 2016 Novartis Institutes for BioMedical Research
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <ctype.h>
#include <memory.h>
#include <errno.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <boost/property_tree/json_parser.hpp>
#include "../../RDGeneral/StreamOps.h"
#include "../FileParsers/FileParsers.h"
#include "../FileParsers/MolSupplier.h" //SDF
#include "../SmilesParse/SmilesParse.h"
#include "StructCheckerOptions.h"
#include "AugmentedAtomData.cpp"
namespace RDKit {
namespace StructureCheck {
bool parseOptionsJSON(const std::string &json, StructCheckerOptions &op) {
if (json.empty()) return false;
try {
std::istringstream ss;
ss.str(json);
boost::property_tree::ptree pt;
boost::property_tree::read_json(ss, pt);
op = StructCheckerOptions(); // reset to default values
op.AcidityLimit = pt.get<double>("AcidityLimit", op.AcidityLimit);
op.RemoveMinorFragments =
pt.get<bool>("RemoveMinorFragments", op.RemoveMinorFragments);
op.DesiredCharge = pt.get<int>("DesiredCharge", op.DesiredCharge);
op.CheckCollisions = pt.get<bool>("CheckCollisions", op.CheckCollisions);
op.CollisionLimitPercent =
pt.get<int>("CollisionLimitPercent", op.CollisionLimitPercent);
op.MaxMolSize = pt.get<int>("MaxMolSize", op.MaxMolSize);
op.ConvertSText = pt.get<bool>("ConvertSText", op.ConvertSText);
op.SqueezeIdentifiers =
pt.get<bool>("SqueezeIdentifiers", op.SqueezeIdentifiers);
op.StripZeros = pt.get<bool>("StripZeros", op.StripZeros);
op.CheckStereo = pt.get<bool>("CheckStereo", op.CheckStereo);
op.ConvertAtomTexts = pt.get<bool>("ConvertAtomTexts", op.ConvertAtomTexts);
op.GroupsToSGroups = pt.get<bool>("GroupsToSGroups", op.GroupsToSGroups);
op.Verbose = pt.get<bool>("Verbose", op.Verbose);
} catch (boost::property_tree::json_parser_error &ex) {
BOOST_LOG(rdErrorLog) << "JSON StructureCheck Options:" << ex.message()
<< "\n";
return false;
} catch (std::exception &ex) {
BOOST_LOG(rdErrorLog) << "JSON StructureCheck Options:" << ex.what()
<< "\n";
return false;
} catch (...) {
BOOST_LOG(rdErrorLog)
<< "JSON StructureCheck Options: Unknown exception.\n";
return false;
}
return true;
}
bool loadOptionsFromFiles(
StructCheckerOptions &op, const std::string &augmentedAtomTranslationsFile,
const std::string &patternFile, // file with clean patterns
const std::string &rotatePatternFile, // file with rotate patterns
const std::string &stereoPatternFile, // file with stereo patterns
const std::string &tautomerFile) {
bool res = true;
if (!augmentedAtomTranslationsFile.empty())
res &= op.loadAugmentedAtomTranslations(augmentedAtomTranslationsFile);
if (!patternFile.empty()) res &= op.loadPatterns(patternFile);
if (!rotatePatternFile.empty())
res &= op.loadRotatePatterns(rotatePatternFile);
if (!stereoPatternFile.empty())
res &= op.loadStereoPatterns(stereoPatternFile);
if (!tautomerFile.empty()) res &= op.loadTautomerData(tautomerFile);
return res;
}
//=====================================================================
// File parsers helper functions:
static const char
*bond_to_string[] = // ordered in according with BondType values
{"?", "-", "=", "#", "~", "-=", "-~", "=~", "*"};
// used in unit test
bool StringToAugmentedAtom(const char *str, AugmentedAtom &aa) {
/*
* The syntax of a augmented atom string is as follows:
*
* <AAString> ::= ['@'|'!@'] <Atom Symbol> [<Charge>]
* {'(' <Bond Symbol> <Atom Symbol> [<Charge>] ')'}.
* Bond symbols and charge descriptors are defined in the symbol tables
* 'bond_to_string' and 'charge_to_string'.
* '@' means central atom is in ring, '!@' means central atom is not in ring,
*omitting means any topography could match.
*/
size_t i;
aa.ShortName = str;
if (str[0] == '@') {
aa.Topology = RING;
str++;
} else if (str[0] == '!' && str[1] == '@') {
aa.Topology = CHAIN;
str++;
str++;
}
aa.Ligands.clear(); // initially no ligands
// fetch atom symbol
if (!isalpha(*str)) { // atom symbol is required
BOOST_LOG(rdErrorLog) << "atom symbol is required '" << str << "'\n";
return false;
}
i = 0;
while (isalnum(str[i]) || str[i] == ',' || str[i] == '#') i++;
aa.AtomSymbol = std::string(str, i);
str += i;
// charge definition
if (str[0] == '+' && str[1] == '-') { // "+-" - ANY_CHARGE
aa.Charge = ANY_CHARGE;
str += 2;
} else if (*str == '-' || *str == '+') {
int sign = (*str == '-') ? (-1) : (1);
str++;
if (*str >= '1' && *str <= '7') {
aa.Charge = sign * (*str - '0');
str++;
} else { // no match
BOOST_LOG(rdErrorLog) << "syntax error '" << str - 1 << "'\n";
return false;
}
} else
aa.Charge = 0; // NONE; default
// radical definition
if (str == strpbrk(str, "|.:") &&
!isdigit(str[1])) { // don't confuse with degree specification
switch (*str) {
case '|':
aa.Radical = SINGLET; // RadicalType::SINGLET;
str++;
break;
case '.':
aa.Radical = DOUBLET;
str++;
break;
case ':':
aa.Radical = TRIPLET;
str++;
break;
default:
return false; // never
};
} else
aa.Radical = RT_NONE;
// read ligand descriptions
while (*str == '(') {
aa.Ligands.push_back(Ligand());
str++; // skip '('
// read bond type
bool found = false;
for (i = 0; i < sizeof(bond_to_string) / sizeof(*bond_to_string); i++) {
if (0 == memcmp(str, bond_to_string[i], isalpha(str[1]) ? 1 : 2)) {
found = true;
aa.Ligands.back().BondType = (AABondType)(i);
str += strlen(bond_to_string[i]);
break;
}
}
if (!found) {
BOOST_LOG(rdErrorLog) << "syntax error '" << str
<< "'\nthere must be a bond type symbol.\n";
return false;
}
if (!isalpha(*str)) { /* there must be an atom symbol */
BOOST_LOG(rdErrorLog) << "syntax error '" << str
<< "'\nthere must be an atom symbol.\n";
return false;
}
i = 0; /* fetch atom symbol */
while (isalnum(str[i]) || str[i] == ',' || str[i] == '#') i++;
aa.Ligands.back().AtomSymbol = std::string(str, i);
str += i;
// charge definition
if (str[0] == '+' && str[1] == '-') { // "+-" - ANY_CHARGE
aa.Ligands.back().Charge = ANY_CHARGE;
str += 2;
} else if (*str == '-' || *str == '+') {
int sign = (*str == '-') ? (-1) : (1);
str++;
if (*str >= '1' && *str <= '7') {
aa.Ligands.back().Charge = sign * (*str - '0');
str++;
} else { // no match
BOOST_LOG(rdErrorLog) << "syntax error '" << str - 1 << "'\n";
return false;
}
} else
aa.Ligands.back().Charge = 0; // NONE; default
// radical definition
if (str == strpbrk(str, "|.:") &&
!isdigit(str[1])) { // don't confuse with degree specification
switch (*str) {
case '|':
aa.Ligands.back().Radical = SINGLET;
str++;
break;
case '.':
aa.Ligands.back().Radical = DOUBLET;
str++;
break;
case ':':
aa.Ligands.back().Radical = TRIPLET;
str++;
break;
default:
return false; // never
};
} else
aa.Ligands.back().Radical = RT_NONE;
// substitution count descriptor
if (str[0] == ':' && isdigit(str[1])) {
aa.Ligands.back().SubstitutionCount = str[1] - '0';
str += 2;
} else
aa.Ligands.back().SubstitutionCount = 0;
if (*str == ')') // check for close ')'
str++;
else {
BOOST_LOG(rdErrorLog) << "unclosed ( '" << str << "'\n";
return false;
}
}
if (*str != '\0') { // there are some extra symbols after scan (inside quoted
// AA string)
BOOST_LOG(rdErrorLog) << "unexpected symbols after scan '" << str << "'\n";
return false;
}
return true;
}
static bool ReadAugmentedAtoms(const std::string &path,
std::vector<AugmentedAtom> &atoms) {
/*
* '*.chk' and '*.aci' files loader
* Only the portion of the strings between the two '"' characters is used,
* other characters are regarded as comments.
*/
FILE *fp = fopen(path.c_str(), "r");
if (!fp) {
BOOST_LOG(rdErrorLog) << "could not open file '" << path << "'\n"
<< strerror(errno) << "\n";
return false;
}
unsigned n = 0;
char str[1024];
while (fgets(str, sizeof(str), fp)) { // comment block in '*.aci' file
if (*str != '#') break;
}
sscanf(str, "%d", &n);
atoms.clear();
atoms.resize(n);
/* read: "! _N10_" - unused version string // '*.chk' file only
char buffer[80];
char *cp;
int vers_len;
fgets(buffer, 80, fp);
cp = strchr(buffer, '_');
if (cp && strchr(cp + 1, '_'))
{
vers_len = (int)(strchr(cp + 1, '_') - cp) - 1;
strncpy(aa_check_version, cp + 1, vers_len);
aa_check_version[vers_len] = '\0';
}
if (log_file)
fprintf(log_file, "augmented atom check version = %s\n",
aa_check_version);
*/
for (unsigned i = 0; i < n && !feof(fp); i++) {
str[0] = '\0';
if (fgets(str, sizeof(str), fp)) {
char *s = str;
while (*s >= ' ' && *s != '"') s++;
if (*s == '"') {
s++;
size_t len = 0;
while (s[len] >= ' ' && s[len] != '"') len++;
s[len] = '\0'; // == atom_string
if (!StringToAugmentedAtom(s, atoms[i])) {
BOOST_LOG(rdErrorLog) << "unsuccessful AA parsing of " << i + 1 << " "
<< str << "\n";
fclose(fp);
return false;
}
} else { // incorrect text line
BOOST_LOG(rdErrorLog) << "unsuccessful AA parsing of " << i + 1 << " "
<< str << "\n";
fclose(fp);
return false;
}
} else if (ferror(fp)) {
BOOST_LOG(rdErrorLog) << "unsuccessful AA parsing of " << i + 1 << " "
<< str << "\n";
fclose(fp);
return false;
}
}
fclose(fp);
return true;
}
static bool ReadAAPairs(
const std::string &path,
std::vector<std::pair<AugmentedAtom, AugmentedAtom>> &trans_pairs) {
/*
* '*.trn' file loader
* Reads file and constructs an array of pairs of augmented atom
* descriptions. The first one being the search pattern and the second
* one the target pattern.
* The function expects the number of augmented atom description pairs
* on the first line and the strings corresponding to the data structures
* on the n following lines.
* Only the portion of the strings between the two '"' characters is used,
* other characters are regarded as comments.
*/
FILE *fp = fopen(path.c_str(), "r");
if (!fp) {
BOOST_LOG(rdErrorLog) << "could not open file '" << path << "'\n"
<< strerror(errno) << "\n";
return false;
}
unsigned n = 0;
fscanf(fp, "%d", &n);
char buffer[80];
// Reads the version from the first line in the file
if (fgets(buffer, sizeof(buffer), fp)) {
/*
int vers_len;
char *cp;
cp = strchr(buffer, '_');
if (cp && strchr(cp + 1, '_'))
{
vers_len = (int)(strchr(cp + 1, '_') - cp) - 1;
strncpy(aa_trans_version, cp + 1, vers_len);
aa_trans_version[vers_len] = '\0';
}
if (log_file)
fprintf(log_file, "augmented atom transformation version =
%s\n", aa_trans_version);
*/
}
trans_pairs.clear();
trans_pairs.resize(n);
for (unsigned i = 0; i < n; i++) {
char str[1024];
str[0] = '\0';
if (fgets(str, sizeof(str), fp)) {
char *s = str;
while (*s >= ' ' && *s != '"') s++;
if (*s == '"') {
s++;
size_t len = 0;
while (s[len] >= ' ' && s[len] != '"') len++;
s[len] = '\0'; // == atom_string
if (!StringToAugmentedAtom(s, trans_pairs[i].first)) {
BOOST_LOG(rdErrorLog) << "unsuccessful translation of " << str
<< "\n";
fclose(fp);
return false;
}
s += len;
s++;
// second atom quoted string
while (*s >= ' ' && *s != '"') s++;
if (*s == '"') {
s++;
len = 0;
while (s[len] >= ' ' && s[len] != '"') len++;
s[len] = '\0'; // == atom_string
if (!StringToAugmentedAtom(s, trans_pairs[i].second)) {
BOOST_LOG(rdErrorLog) << "unsuccessful translation of " << str
<< "\n";
fclose(fp);
return false;
}
}
}
}
}
fclose(fp);
if (trans_pairs.size() != n) {
BOOST_LOG(rdErrorLog) << "syntax error in translation file " << path
<< " pair " << trans_pairs.size() + 1 << "\n";
return false;
}
return true;
}
//=====================================================================
static void loadDefaultAugmentedAtoms(StructCheckerOptions &struchkOpts) {
std::vector<AugmentedAtom> good;
good.reserve(sizeof(DefaultGoodAtoms) / sizeof(*DefaultGoodAtoms));
for (const auto &DefaultGoodAtom : DefaultGoodAtoms) {
good.push_back(AugmentedAtom());
if (!StringToAugmentedAtom(DefaultGoodAtom.str, good.back())) {
throw "INTERNAL ERROR in default data";
}
}
std::vector<AugmentedAtom> acidic;
acidic.reserve(sizeof(DefaultAcidicAtoms) / sizeof(*DefaultAcidicAtoms));
for (const auto &DefaultAcidicAtom : DefaultAcidicAtoms) {
acidic.push_back(AugmentedAtom());
if (!StringToAugmentedAtom(DefaultAcidicAtom.str, acidic.back())) {
throw "INTERNAL ERROR in default data";
}
}
std::vector<std::pair<AugmentedAtom, AugmentedAtom>> trans_pairs;
trans_pairs.resize(sizeof(DefaultAugmentedAtomTransforms) /
sizeof(*DefaultAugmentedAtomTransforms));
for (size_t i = 0; i < sizeof(DefaultAugmentedAtomTransforms) /
sizeof(*DefaultAugmentedAtomTransforms);
++i) {
if (!StringToAugmentedAtom(DefaultAugmentedAtomTransforms[i].from,
trans_pairs[i].first)) {
throw "INTERNAL Error in default augmented atom transforms";
}
if (!StringToAugmentedAtom(DefaultAugmentedAtomTransforms[i].to,
trans_pairs[i].second)) {
throw "INTERNAL Error in default augmented atom transforms";
}
}
struchkOpts.setGoodAugmentedAtoms(good);
struchkOpts.setAcidicAugmentedAtoms(acidic);
struchkOpts.setAugmentedAtomTranslations(trans_pairs);
}
//=====================================================================
bool StructCheckerOptions::loadAugmentedAtomTranslations(
const std::string &path) {
AugmentedAtomPairs.clear();
if (path.empty()) return false;
return ReadAAPairs(path, AugmentedAtomPairs);
}
void StructCheckerOptions::setAugmentedAtomTranslations(
const std::vector<std::pair<AugmentedAtom, AugmentedAtom>> &aaPairs) {
AugmentedAtomPairs = aaPairs;
}
bool StructCheckerOptions::loadAcidicAugmentedAtoms(const std::string &path) {
AcidicAtoms.clear();
if (path.empty()) return false;
return ReadAugmentedAtoms(path, AcidicAtoms);
}
void StructCheckerOptions::setAcidicAugmentedAtoms(
const std::vector<AugmentedAtom> &atoms) {
AcidicAtoms = atoms;
}
bool StructCheckerOptions::loadGoodAugmentedAtoms(const std::string &path) {
GoodAtoms.clear();
if (path.empty()) return false;
return ReadAugmentedAtoms(path, GoodAtoms);
}
void StructCheckerOptions::setGoodAugmentedAtoms(
const std::vector<AugmentedAtom> &atoms) {
GoodAtoms = atoms;
}
static bool loadSDF(const std::string &path, std::vector<ROMOL_SPTR> &mols) {
mols.clear();
try {
SDMolSupplier suppler(path);
while (!suppler.atEnd()) {
ROMol *m = suppler.next();
if (m) {
// ?? MakeHydrogensImplicit()
mols.push_back(ROMOL_SPTR(m));
}
}
} catch (std::exception &ex) {
BOOST_LOG(rdErrorLog) << ex.what(); // log error
return false;
}
return true;
}
bool StructCheckerOptions::loadPatterns(const std::string &path) {
Patterns.clear();
if (path.empty()) return false;
return loadSDF(path, Patterns);
}
void StructCheckerOptions::setPatterns(const std::vector<ROMOL_SPTR> &p) {
Patterns = p;
}
bool StructCheckerOptions::loadRotatePatterns(const std::string &path) {
RotatePatterns.clear();
if (path.empty()) return false;
return loadSDF(path, RotatePatterns);
}
void StructCheckerOptions::setRotatePatterns(const std::vector<ROMOL_SPTR> &p) {
RotatePatterns = p;
}
bool StructCheckerOptions::loadStereoPatterns(const std::string &path) {
StereoPatterns.clear();
if (path.empty()) return false;
return loadSDF(path, StereoPatterns);
}
void StructCheckerOptions::setStereoPatterns(const std::vector<ROMOL_SPTR> &p) {
StereoPatterns = p;
}
bool StructCheckerOptions::loadTautomerData(const std::string &path) {
ToTautomer.clear();
FromTautomer.clear();
if (path.empty()) return false;
try {
std::string ext = path.substr(path.find_last_of(".") + 1);
if (ext == "sdf" || ext == "SDF") {
SDMolSupplier suppler(path);
while (!suppler.atEnd()) {
ROMol *m1 = suppler.next();
if (suppler.atEnd()) break;
ROMol *m2 = suppler.next();
if (m1 && m2) {
// ?? MakeHydrogensImplicit()
FromTautomer.push_back(ROMOL_SPTR(m1));
ToTautomer.push_back(ROMOL_SPTR(m2));
}
}
} else if (ext == "rdf" ||
ext == "RDF") { // load RD-File, see CTfile format specification
std::ifstream in(path.c_str());
if (!in) {
BOOST_LOG(rdErrorLog) << "could not open file '" << path << "'\n"
<< strerror(errno) << "\n";
return false;
}
std::string str;
unsigned line = 0;
do {
str = getLine(in);
line++;
if (str.length() >= 4 && 0 == strcmp(str.c_str(), "$RXN")) {
while (!in.eof()) {
str = getLine(in);
line++;
if (str.length() >= 4 && 0 == strcmp(str.c_str(), "$MOL")) {
RWMol *molFrom = MolDataStreamToMol(in, line);
if (!molFrom) {
BOOST_LOG(rdErrorLog) << "RD-file corrupted. " << path
<< " line " << line << "\n"; // log error
return false;
}
while (molFrom && !in.eof()) {
str = getLine(in);
line++;
if (str.length() >= 4 && 0 == strcmp(str.c_str(), "$MOL")) {
RWMol *molTo = MolDataStreamToMol(in, line);
if (!molTo) {
BOOST_LOG(rdErrorLog) << "RD-file corrupted. " << path
<< " line " << line
<< "\n"; // log error
return false;
}
// ?? MakeHydrogensImplicit()
FromTautomer.push_back(ROMOL_SPTR(molFrom));
ToTautomer.push_back(ROMOL_SPTR(molTo));
}
}
}
}
}
} while (!in.eof());
} else {
BOOST_LOG(rdErrorLog) << "unsupported file type. " << path
<< "\n"; // log error
return false;
}
} catch (std::exception &ex) {
BOOST_LOG(rdErrorLog) << ex.what() << "\n"; // log error
return false;
}
return true;
}
void StructCheckerOptions::setTautomerData(const std::vector<ROMOL_SPTR> &from,
const std::vector<ROMOL_SPTR> &to) {
FromTautomer = from;
ToTautomer = to;
}
static void parseSMARTS(std::vector<ROMOL_SPTR> &mols,
const std::vector<std::string> &smarts) {
mols.clear();
for (const auto &patt : smarts) {
ROMol *m = SmartsToMol(patt);
if (m) mols.push_back(ROMOL_SPTR(m));
}
}
void StructCheckerOptions::parsePatterns(
const std::vector<std::string> &smarts) {
parseSMARTS(Patterns, smarts);
}
void StructCheckerOptions::parseRotatePatterns(
const std::vector<std::string> &smarts) {
parseSMARTS(RotatePatterns, smarts);
}
void StructCheckerOptions::parseStereoPatterns(
const std::vector<std::string> &smarts) {
parseSMARTS(StereoPatterns, smarts);
}
void StructCheckerOptions::parseTautomerData(
const std::vector<std::string> &smartsFrom,
const std::vector<std::string> &smartsTo) {
parseSMARTS(FromTautomer, smartsFrom);
parseSMARTS(ToTautomer, smartsTo);
}
//--------------------------------------------------------------------------
bool loadChargeDataTables(const std::string& path) {
// TODO: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
RDUNUSED_PARAM(path);
/*
double Elneg0; // elneg_table[0].value;
std::map<unsigned, double> ElnegTable; // AtomicNumber -> eleng
std::vector<inc_entry_t> AtomAcidity; //atom_acidity_table[]
std::vector<inc_entry_t> charge_inc_table; // std::map AtomicNumber ->
...
double Alpha, Beta;
std::vector<path_entry_t> alpha_path_table, beta_path_table;
*/
return true;
}
StructCheckerOptions::StructCheckerOptions()
: AcidityLimit(0.0),
RemoveMinorFragments(false),
DesiredCharge(0),
CheckCollisions(false),
CollisionLimitPercent(15),
MaxMolSize(255),
ConvertSText(false),
SqueezeIdentifiers(false),
StripZeros(false),
CheckStereo(false),
ConvertAtomTexts(false),
GroupsToSGroups(false),
Verbose(false),
Elneg0(0.0) // elneg_table[0].value;
,
Alpha(0.0),
Beta(0.0) {
loadDefaultAugmentedAtoms(*this);
}
} // namespace StructureCheck
} // namespace RDKit
| 1 | 19,042 | I'm surprised this is needed, but we should probably assert num_scan == 1 at least, otherwise I expect the file is pretty broken. | rdkit-rdkit | cpp |
@@ -17,7 +17,9 @@ namespace storage {
TEST(AddEdgesTest, SimpleTest) {
fs::TempDir rootPath("/tmp/AddEdgesTest.XXXXXX");
- std::unique_ptr<kvstore::KVStore> kv = TestUtils::initKV(rootPath.path());
+ constexpr int32_t partitions = 6;
+ std::unique_ptr<kvstore::KVStore> kv = TestUtils::initKV(rootPath.path(), partitions,
+ {0, network::NetworkUtils::getAvailablePort()});
auto schemaMan = TestUtils::mockSchemaMan();
auto indexMan = TestUtils::mockIndexMan();
auto* processor = AddEdgesProcessor::instance(kv.get(), | 1 | /* Copyright (c) 2018 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "base/Base.h"
#include "utils/NebulaKeyUtils.h"
#include <gtest/gtest.h>
#include <rocksdb/db.h>
#include "fs/TempDir.h"
#include "storage/test/TestUtils.h"
#include "storage/mutate/AddEdgesProcessor.h"
namespace nebula {
namespace storage {
TEST(AddEdgesTest, SimpleTest) {
fs::TempDir rootPath("/tmp/AddEdgesTest.XXXXXX");
std::unique_ptr<kvstore::KVStore> kv = TestUtils::initKV(rootPath.path());
auto schemaMan = TestUtils::mockSchemaMan();
auto indexMan = TestUtils::mockIndexMan();
auto* processor = AddEdgesProcessor::instance(kv.get(),
schemaMan.get(),
indexMan.get(),
nullptr);
LOG(INFO) << "Build AddEdgesRequest...";
cpp2::AddEdgesRequest req;
req.space_id = 0;
req.overwritable = true;
// partId => List<Edge>
// Edge => {EdgeKey, props}
for (PartitionID partId = 1; partId <= 3; partId++) {
auto edges = TestUtils::setupEdges(partId, partId * 10, 10 * (partId + 1));
req.parts.emplace(partId, std::move(edges));
}
LOG(INFO) << "Test AddEdgesProcessor...";
auto fut = processor->getFuture();
processor->process(req);
auto resp = std::move(fut).get();
EXPECT_EQ(0, resp.result.failed_codes.size());
LOG(INFO) << "Check data in kv store...";
for (PartitionID partId = 1; partId <= 3; partId++) {
for (VertexID srcId = 10 * partId; srcId < 10 * (partId + 1); srcId++) {
auto prefix = NebulaKeyUtils::edgePrefix(partId, srcId, 101);
std::unique_ptr<kvstore::KVIterator> iter;
EXPECT_EQ(kvstore::ResultCode::SUCCEEDED, kv->prefix(0, partId, prefix, &iter));
int num = 0;
while (iter->valid()) {
auto edgeType = 101;
auto dstId = srcId * 100 + 2;
EXPECT_EQ(TestUtils::encodeValue(partId, srcId, dstId, edgeType),
iter->val().str());
num++;
iter->next();
}
EXPECT_EQ(1, num);
}
}
}
} // namespace storage
} // namespace nebula
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
folly::init(&argc, &argv, true);
google::SetStderrLogging(google::INFO);
return RUN_ALL_TESTS();
}
| 1 | 28,920 | Could we set a default value for `partitions` and `{0, network::NetworkUtils::getAvailablePort()}` ? | vesoft-inc-nebula | cpp |
@@ -0,0 +1,14 @@
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System;
+
+namespace Microsoft.AspNetCore.Server.Kestrel.Core
+{
+ public class RequestBodyTimeout
+ {
+ public TimeSpan MinimumTime { get; set; }
+ public TimeSpan? MaximumTime { get; set; }
+ public double? MinimumRate { get; set; }
+ }
+} | 1 | 1 | 13,336 | Needs xml docs. The API names alone don't provide enough explanation about what these mean and how to set them. Also, we should provide some validation of inputs, such as MaxTime must be > MinTime, MinimumRate must be >= 0, etc. Consider making the properties readonly and adding a constructor that does these validations. | aspnet-KestrelHttpServer | .cs |
|
@@ -0,0 +1,12 @@
+package testutils
+
+import (
+ "os"
+ "path"
+)
+
+func TestDataFile(name string) string {
+ dir, _ := os.Getwd()
+
+ return path.Join(dir, "testdata", name)
+} | 1 | 1 | 17,059 | Would it make sense to create an empty file here, perhaps in a tmp dir, instead of checking empty files into Git? | projectcalico-felix | go |
|
@@ -1823,7 +1823,9 @@ class CSharpGenerator : public BaseGenerator {
code += "[idx" + NumToString(j++) + "]";
}
code += ";";
- for (size_t i = 0; i < array_only_lengths.size(); ++i) { code += "}"; }
+ for (size_t i = 0; i < array_only_lengths.size(); ++i) {
+ code += "}";
+ }
} else {
code += "_o";
for (size_t i = 0; i < array_lengths.size(); ++i) { | 1 | /*
* Copyright 2014 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.
*/
// independent from idl_parser, since this code is not needed for most clients
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#if defined(FLATBUFFERS_CPP98_STL)
# include <cctype>
#endif // defined(FLATBUFFERS_CPP98_STL)
namespace flatbuffers {
static TypedFloatConstantGenerator CSharpFloatGen("Double.", "Single.", "NaN",
"PositiveInfinity",
"NegativeInfinity");
static CommentConfig comment_config = {
nullptr,
"///",
nullptr,
};
namespace csharp {
class CSharpGenerator : public BaseGenerator {
struct FieldArrayLength {
std::string name;
int length;
};
public:
CSharpGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "", ".", "cs"),
cur_name_space_(nullptr) {}
CSharpGenerator &operator=(const CSharpGenerator &);
bool generate() {
std::string one_file_code;
cur_name_space_ = parser_.current_namespace_;
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
std::string enumcode;
auto &enum_def = **it;
if (!parser_.opts.one_file) cur_name_space_ = enum_def.defined_namespace;
GenEnum(enum_def, &enumcode, parser_.opts);
if (parser_.opts.one_file) {
one_file_code += enumcode;
} else {
if (!SaveType(enum_def.name, *enum_def.defined_namespace, enumcode,
false))
return false;
}
}
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
std::string declcode;
auto &struct_def = **it;
if (!parser_.opts.one_file)
cur_name_space_ = struct_def.defined_namespace;
GenStruct(struct_def, &declcode, parser_.opts);
if (parser_.opts.one_file) {
one_file_code += declcode;
} else {
if (!SaveType(struct_def.name, *struct_def.defined_namespace, declcode,
true))
return false;
}
}
if (parser_.opts.one_file) {
return SaveType(file_name_, *parser_.current_namespace_, one_file_code,
true);
}
return true;
}
// Save out the generated code for a single class while adding
// declaration boilerplate.
bool SaveType(const std::string &defname, const Namespace &ns,
const std::string &classcode, bool needs_includes) const {
if (!classcode.length()) return true;
std::string code =
"// <auto-generated>\n"
"// " +
std::string(FlatBuffersGeneratedWarning()) +
"\n"
"// </auto-generated>\n\n";
std::string namespace_name = FullNamespace(".", ns);
if (!namespace_name.empty()) {
code += "namespace " + namespace_name + "\n{\n\n";
}
if (needs_includes) {
code += "using global::System;\n";
code += "using global::System.Collections.Generic;\n";
code += "using global::FlatBuffers;\n\n";
}
code += classcode;
if (!namespace_name.empty()) { code += "\n}\n"; }
auto filename = NamespaceDir(ns) + defname + ".cs";
return SaveFile(filename.c_str(), code, false);
}
const Namespace *CurrentNameSpace() const { return cur_name_space_; }
std::string GenTypeBasic(const Type &type, bool enableLangOverrides) const {
// clang-format off
static const char * const csharp_typename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, ...) \
#NTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
// clang-format on
if (enableLangOverrides) {
if (IsEnum(type)) return WrapInNameSpace(*type.enum_def);
if (type.base_type == BASE_TYPE_STRUCT) {
return "Offset<" + WrapInNameSpace(*type.struct_def) + ">";
}
}
return csharp_typename[type.base_type];
}
inline std::string GenTypeBasic(const Type &type) const {
return GenTypeBasic(type, true);
}
std::string GenTypePointer(const Type &type) const {
switch (type.base_type) {
case BASE_TYPE_STRING: return "string";
case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
case BASE_TYPE_STRUCT: return WrapInNameSpace(*type.struct_def);
case BASE_TYPE_UNION: return "TTable";
default: return "Table";
}
}
std::string GenTypeGet(const Type &type) const {
return IsScalar(type.base_type)
? GenTypeBasic(type)
: (IsArray(type) ? GenTypeGet(type.VectorType())
: GenTypePointer(type));
}
std::string GenOffsetType(const StructDef &struct_def) const {
return "Offset<" + WrapInNameSpace(struct_def) + ">";
}
std::string GenOffsetConstruct(const StructDef &struct_def,
const std::string &variable_name) const {
return "new Offset<" + WrapInNameSpace(struct_def) + ">(" + variable_name +
")";
}
// Casts necessary to correctly read serialized data
std::string DestinationCast(const Type &type) const {
if (IsSeries(type)) {
return DestinationCast(type.VectorType());
} else {
if (IsEnum(type)) return "(" + WrapInNameSpace(*type.enum_def) + ")";
}
return "";
}
// Cast statements for mutator method parameters.
// In Java, parameters representing unsigned numbers need to be cast down to
// their respective type. For example, a long holding an unsigned int value
// would be cast down to int before being put onto the buffer. In C#, one cast
// directly cast an Enum to its underlying type, which is essential before
// putting it onto the buffer.
std::string SourceCast(const Type &type) const {
if (IsSeries(type)) {
return SourceCast(type.VectorType());
} else {
if (IsEnum(type)) return "(" + GenTypeBasic(type, false) + ")";
}
return "";
}
std::string SourceCastBasic(const Type &type) const {
return IsScalar(type.base_type) ? SourceCast(type) : "";
}
std::string GenEnumDefaultValue(const FieldDef &field) const {
auto &value = field.value;
FLATBUFFERS_ASSERT(value.type.enum_def);
auto &enum_def = *value.type.enum_def;
auto enum_val = enum_def.FindByValue(value.constant);
return enum_val ? (WrapInNameSpace(enum_def) + "." + enum_val->name)
: value.constant;
}
std::string GenDefaultValue(const FieldDef &field,
bool enableLangOverrides) const {
auto &value = field.value;
if (enableLangOverrides) {
// handles both enum case and vector of enum case
if (value.type.enum_def != nullptr &&
value.type.base_type != BASE_TYPE_UNION) {
return GenEnumDefaultValue(field);
}
}
auto longSuffix = "";
switch (value.type.base_type) {
case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
case BASE_TYPE_ULONG: return value.constant;
case BASE_TYPE_UINT:
case BASE_TYPE_LONG: return value.constant + longSuffix;
default:
if (IsFloat(value.type.base_type))
return CSharpFloatGen.GenFloatConstant(field);
else
return value.constant;
}
}
std::string GenDefaultValue(const FieldDef &field) const {
return GenDefaultValue(field, true);
}
std::string GenDefaultValueBasic(const FieldDef &field,
bool enableLangOverrides) const {
auto &value = field.value;
if (!IsScalar(value.type.base_type)) {
if (enableLangOverrides) {
switch (value.type.base_type) {
case BASE_TYPE_STRING: return "default(StringOffset)";
case BASE_TYPE_STRUCT:
return "default(Offset<" + WrapInNameSpace(*value.type.struct_def) +
">)";
case BASE_TYPE_VECTOR: return "default(VectorOffset)";
default: break;
}
}
return "0";
}
return GenDefaultValue(field, enableLangOverrides);
}
std::string GenDefaultValueBasic(const FieldDef &field) const {
return GenDefaultValueBasic(field, true);
}
void GenEnum(EnumDef &enum_def, std::string *code_ptr,
const IDLOptions &opts) const {
std::string &code = *code_ptr;
if (enum_def.generated) return;
// Generate enum definitions of the form:
// public static (final) int name = value;
// In Java, we use ints rather than the Enum feature, because we want them
// to map directly to how they're used in C/C++ and file formats.
// That, and Java Enums are expensive, and not universally liked.
GenComment(enum_def.doc_comment, code_ptr, &comment_config);
if (opts.cs_gen_json_serializer && opts.generate_object_based_api) {
code +=
"[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters."
"StringEnumConverter))]\n";
}
// In C# this indicates enumeration values can be treated as bit flags.
if (enum_def.attributes.Lookup("bit_flags")) {
code += "[System.FlagsAttribute]\n";
}
if (enum_def.attributes.Lookup("private")) {
code += "internal ";
} else {
code += "public ";
}
code += "enum " + enum_def.name;
code += " : " + GenTypeBasic(enum_def.underlying_type, false);
code += "\n{\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
GenComment(ev.doc_comment, code_ptr, &comment_config, " ");
code += " ";
code += ev.name + " = ";
code += enum_def.ToString(ev);
code += ",\n";
}
// Close the class
code += "};\n\n";
if (opts.generate_object_based_api) {
GenEnum_ObjectAPI(enum_def, code_ptr, opts);
}
}
bool HasUnionStringValue(const EnumDef &enum_def) const {
if (!enum_def.is_union) return false;
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &val = **it;
if (val.union_type.base_type == BASE_TYPE_STRING) { return true; }
}
return false;
}
// Returns the function name that is able to read a value of the given type.
std::string GenGetter(const Type &type) const {
switch (type.base_type) {
case BASE_TYPE_STRING: return "__p.__string";
case BASE_TYPE_STRUCT: return "__p.__struct";
case BASE_TYPE_UNION: return "__p.__union";
case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
case BASE_TYPE_ARRAY: return GenGetter(type.VectorType());
default: {
std::string getter = "__p.bb.Get";
if (type.base_type == BASE_TYPE_BOOL) {
getter = "0!=" + getter;
} else if (GenTypeBasic(type, false) != "byte") {
getter += MakeCamel(GenTypeBasic(type, false));
}
return getter;
}
}
}
// Returns the function name that is able to read a value of the given type.
std::string GenGetterForLookupByKey(flatbuffers::FieldDef *key_field,
const std::string &data_buffer,
const char *num = nullptr) const {
auto type = key_field->value.type;
auto dest_mask = "";
auto dest_cast = DestinationCast(type);
auto getter = data_buffer + ".Get";
if (GenTypeBasic(type, false) != "byte") {
getter += MakeCamel(GenTypeBasic(type, false));
}
getter = dest_cast + getter + "(" + GenOffsetGetter(key_field, num) + ")" +
dest_mask;
return getter;
}
// Direct mutation is only allowed for scalar fields.
// Hence a setter method will only be generated for such fields.
std::string GenSetter(const Type &type) const {
if (IsScalar(type.base_type)) {
std::string setter = "__p.bb.Put";
if (GenTypeBasic(type, false) != "byte" &&
type.base_type != BASE_TYPE_BOOL) {
setter += MakeCamel(GenTypeBasic(type, false));
}
return setter;
} else {
return "";
}
}
// Returns the method name for use with add/put calls.
std::string GenMethod(const Type &type) const {
return IsScalar(type.base_type) ? MakeCamel(GenTypeBasic(type, false))
: (IsStruct(type) ? "Struct" : "Offset");
}
// Recursively generate arguments for a constructor, to deal with nested
// structs.
void GenStructArgs(const StructDef &struct_def, std::string *code_ptr,
const char *nameprefix, size_t array_count = 0) const {
std::string &code = *code_ptr;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
const auto &field_type = field.value.type;
const auto array_field = IsArray(field_type);
const auto &type = array_field ? field_type.VectorType() : field_type;
const auto array_cnt = array_field ? (array_count + 1) : array_count;
if (IsStruct(type)) {
// Generate arguments for a struct inside a struct. To ensure names
// don't clash, and to make it obvious these arguments are constructing
// a nested struct, prefix the name with the field name.
GenStructArgs(*field_type.struct_def, code_ptr,
(nameprefix + (field.name + "_")).c_str(), array_cnt);
} else {
code += ", ";
code += GenTypeBasic(type);
if (array_cnt > 0) {
code += "[";
for (size_t i = 1; i < array_cnt; i++) code += ",";
code += "]";
}
code += " ";
code += nameprefix;
code += MakeCamel(field.name, true);
}
}
}
// Recusively generate struct construction statements of the form:
// builder.putType(name);
// and insert manual padding.
void GenStructBody(const StructDef &struct_def, std::string *code_ptr,
const char *nameprefix, size_t index = 0,
bool in_array = false) const {
std::string &code = *code_ptr;
std::string indent((index + 1) * 2, ' ');
code += indent + " builder.Prep(";
code += NumToString(struct_def.minalign) + ", ";
code += NumToString(struct_def.bytesize) + ");\n";
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
auto &field = **it;
const auto &field_type = field.value.type;
if (field.padding) {
code += indent + " builder.Pad(";
code += NumToString(field.padding) + ");\n";
}
if (IsStruct(field_type)) {
GenStructBody(*field_type.struct_def, code_ptr,
(nameprefix + (field.name + "_")).c_str(), index,
in_array);
} else {
const auto &type =
IsArray(field_type) ? field_type.VectorType() : field_type;
const auto index_var = "_idx" + NumToString(index);
if (IsArray(field_type)) {
code += indent + " for (int " + index_var + " = ";
code += NumToString(field_type.fixed_length);
code += "; " + index_var + " > 0; " + index_var + "--) {\n";
in_array = true;
}
if (IsStruct(type)) {
GenStructBody(*field_type.struct_def, code_ptr,
(nameprefix + (field.name + "_")).c_str(), index + 1,
in_array);
} else {
code += IsArray(field_type) ? " " : "";
code += indent + " builder.Put";
code += GenMethod(type) + "(";
code += SourceCast(type);
auto argname = nameprefix + MakeCamel(field.name, true);
code += argname;
size_t array_cnt = index + (IsArray(field_type) ? 1 : 0);
if (array_cnt > 0) {
code += "[";
for (size_t i = 0; in_array && i < array_cnt; i++) {
code += "_idx" + NumToString(i) + "-1";
if (i != (array_cnt - 1)) code += ",";
}
code += "]";
}
code += ");\n";
}
if (IsArray(field_type)) { code += indent + " }\n"; }
}
}
}
std::string GenOffsetGetter(flatbuffers::FieldDef *key_field,
const char *num = nullptr) const {
std::string key_offset =
"Table.__offset(" + NumToString(key_field->value.offset) + ", ";
if (num) {
key_offset += num;
key_offset += ".Value, builder.DataBuffer)";
} else {
key_offset += "bb.Length";
key_offset += " - tableOffset, bb)";
}
return key_offset;
}
std::string GenLookupKeyGetter(flatbuffers::FieldDef *key_field) const {
std::string key_getter = " ";
key_getter += "int tableOffset = Table.";
key_getter += "__indirect(vectorLocation + 4 * (start + middle)";
key_getter += ", bb);\n ";
if (key_field->value.type.base_type == BASE_TYPE_STRING) {
key_getter += "int comp = Table.";
key_getter += "CompareStrings(";
key_getter += GenOffsetGetter(key_field);
key_getter += ", byteKey, bb);\n";
} else {
auto get_val = GenGetterForLookupByKey(key_field, "bb");
key_getter += "int comp = " + get_val + ".CompareTo(key);\n";
}
return key_getter;
}
std::string GenKeyGetter(flatbuffers::FieldDef *key_field) const {
std::string key_getter = "";
auto data_buffer = "builder.DataBuffer";
if (key_field->value.type.base_type == BASE_TYPE_STRING) {
key_getter += "Table.CompareStrings(";
key_getter += GenOffsetGetter(key_field, "o1") + ", ";
key_getter += GenOffsetGetter(key_field, "o2") + ", " + data_buffer + ")";
} else {
auto field_getter = GenGetterForLookupByKey(key_field, data_buffer, "o1");
key_getter += field_getter;
field_getter = GenGetterForLookupByKey(key_field, data_buffer, "o2");
key_getter += ".CompareTo(" + field_getter + ")";
}
return key_getter;
}
void GenStruct(StructDef &struct_def, std::string *code_ptr,
const IDLOptions &opts) const {
if (struct_def.generated) return;
std::string &code = *code_ptr;
// Generate a struct accessor class, with methods of the form:
// public type name() { return bb.getType(i + offset); }
// or for tables of the form:
// public type name() {
// int o = __offset(offset); return o != 0 ? bb.getType(o + i) : default;
// }
GenComment(struct_def.doc_comment, code_ptr, &comment_config);
if (struct_def.attributes.Lookup("private")) {
code += "internal ";
} else {
code += "public ";
}
if (struct_def.attributes.Lookup("csharp_partial")) {
// generate a partial class for this C# struct/table
code += "partial ";
}
code += "struct " + struct_def.name;
code += " : IFlatbufferObject";
code += "\n{\n";
code += " private ";
code += struct_def.fixed ? "Struct" : "Table";
code += " __p;\n";
code += " public ByteBuffer ByteBuffer { get { return __p.bb; } }\n";
if (!struct_def.fixed) {
// Generate verson check method.
// Force compile time error if not using the same version runtime.
code += " public static void ValidateVersion() {";
code += " FlatBufferConstants.";
code += "FLATBUFFERS_1_12_0(); ";
code += "}\n";
// Generate a special accessor for the table that when used as the root
// of a FlatBuffer
std::string method_name = "GetRootAs" + struct_def.name;
std::string method_signature =
" public static " + struct_def.name + " " + method_name;
// create convenience method that doesn't require an existing object
code += method_signature + "(ByteBuffer _bb) ";
code += "{ return " + method_name + "(_bb, new " + struct_def.name +
"()); }\n";
// create method that allows object reuse
code +=
method_signature + "(ByteBuffer _bb, " + struct_def.name + " obj) { ";
code += "return (obj.__assign(_bb.GetInt(_bb.Position";
code += ") + _bb.Position";
code += ", _bb)); }\n";
if (parser_.root_struct_def_ == &struct_def) {
if (parser_.file_identifier_.length()) {
// Check if a buffer has the identifier.
code += " public static ";
code += "bool " + struct_def.name;
code += "BufferHasIdentifier(ByteBuffer _bb) { return ";
code += "Table.__has_identifier(_bb, \"";
code += parser_.file_identifier_;
code += "\"); }\n";
}
}
}
// Generate the __init method that sets the field in a pre-existing
// accessor object. This is to allow object reuse.
code += " public void __init(int _i, ByteBuffer _bb) ";
code += "{ ";
code += "__p = new ";
code += struct_def.fixed ? "Struct" : "Table";
code += "(_i, _bb); ";
code += "}\n";
code +=
" public " + struct_def.name + " __assign(int _i, ByteBuffer _bb) ";
code += "{ __init(_i, _bb); return this; }\n\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
GenComment(field.doc_comment, code_ptr, &comment_config, " ");
std::string type_name = GenTypeGet(field.value.type);
std::string type_name_dest = GenTypeGet(field.value.type);
std::string conditional_cast = "";
std::string optional = "";
if (!struct_def.fixed &&
(field.value.type.base_type == BASE_TYPE_STRUCT ||
field.value.type.base_type == BASE_TYPE_UNION ||
(field.value.type.base_type == BASE_TYPE_VECTOR &&
(field.value.type.element == BASE_TYPE_STRUCT ||
field.value.type.element == BASE_TYPE_UNION)))) {
optional = "?";
conditional_cast = "(" + type_name_dest + optional + ")";
}
std::string dest_mask = "";
std::string dest_cast = DestinationCast(field.value.type);
std::string src_cast = SourceCast(field.value.type);
std::string method_start = " public " + type_name_dest + optional + " " +
MakeCamel(field.name, true);
std::string obj = "(new " + type_name + "())";
// Most field accessors need to retrieve and test the field offset first,
// this is the prefix code for that:
auto offset_prefix =
IsArray(field.value.type)
? " { return "
: (" { int o = __p.__offset(" + NumToString(field.value.offset) +
"); return o != 0 ? ");
// Generate the accessors that don't do object reuse.
if (field.value.type.base_type == BASE_TYPE_STRUCT) {
} else if (field.value.type.base_type == BASE_TYPE_VECTOR &&
field.value.type.element == BASE_TYPE_STRUCT) {
} else if (field.value.type.base_type == BASE_TYPE_UNION ||
(field.value.type.base_type == BASE_TYPE_VECTOR &&
field.value.type.VectorType().base_type == BASE_TYPE_UNION)) {
method_start += "<TTable>";
type_name = type_name_dest;
}
std::string getter = dest_cast + GenGetter(field.value.type);
code += method_start;
std::string default_cast = "";
// only create default casts for c# scalars or vectors of scalars
if ((IsScalar(field.value.type.base_type) ||
(field.value.type.base_type == BASE_TYPE_VECTOR &&
IsScalar(field.value.type.element)))) {
// For scalars, default value will be returned by GetDefaultValue().
// If the scalar is an enum, GetDefaultValue() returns an actual c# enum
// that doesn't need to be casted. However, default values for enum
// elements of vectors are integer literals ("0") and are still casted
// for clarity.
if (field.value.type.enum_def == nullptr ||
field.value.type.base_type == BASE_TYPE_VECTOR) {
default_cast = "(" + type_name_dest + ")";
}
}
std::string member_suffix = "; ";
if (IsScalar(field.value.type.base_type)) {
code += " { get";
member_suffix += "} ";
if (struct_def.fixed) {
code += " { return " + getter;
code += "(__p.bb_pos + ";
code += NumToString(field.value.offset) + ")";
code += dest_mask;
} else {
code += offset_prefix + getter;
code += "(o + __p.bb_pos)" + dest_mask;
code += " : " + default_cast;
code += GenDefaultValue(field);
}
} else {
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT:
code += " { get";
member_suffix += "} ";
if (struct_def.fixed) {
code += " { return " + obj + ".__assign(" + "__p.";
code += "bb_pos + " + NumToString(field.value.offset) + ", ";
code += "__p.bb)";
} else {
code += offset_prefix + conditional_cast;
code += obj + ".__assign(";
code += field.value.type.struct_def->fixed
? "o + __p.bb_pos"
: "__p.__indirect(o + __p.bb_pos)";
code += ", __p.bb) : null";
}
break;
case BASE_TYPE_STRING:
code += " { get";
member_suffix += "} ";
code += offset_prefix + getter + "(o + " + "__p.";
code += "bb_pos) : null";
break;
case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
auto vectortype = field.value.type.VectorType();
if (vectortype.base_type == BASE_TYPE_UNION) {
conditional_cast = "(TTable?)";
getter += "<TTable>";
}
code += "(";
if (vectortype.base_type == BASE_TYPE_STRUCT) {
getter = obj + ".__assign";
} else if (vectortype.base_type == BASE_TYPE_UNION) {
}
code += "int j)";
const auto body = offset_prefix + conditional_cast + getter + "(";
if (vectortype.base_type == BASE_TYPE_UNION) {
code += " where TTable : struct, IFlatbufferObject" + body;
} else {
code += body;
}
std::string index = "__p.";
if (IsArray(field.value.type)) {
index += "bb_pos + " + NumToString(field.value.offset) + " + ";
} else {
index += "__vector(o) + ";
}
index += "j * " + NumToString(InlineSize(vectortype));
if (vectortype.base_type == BASE_TYPE_STRUCT) {
code += vectortype.struct_def->fixed
? index
: "__p.__indirect(" + index + ")";
code += ", __p.bb";
} else {
code += index;
}
code += ")" + dest_mask;
if (!IsArray(field.value.type)) {
code += " : ";
code +=
field.value.type.element == BASE_TYPE_BOOL
? "false"
: (IsScalar(field.value.type.element) ? default_cast + "0"
: "null");
}
if (vectortype.base_type == BASE_TYPE_UNION &&
HasUnionStringValue(*vectortype.enum_def)) {
code += member_suffix;
code += "}\n";
code += " public string " + MakeCamel(field.name, true) +
"AsString(int j)";
code += offset_prefix + GenGetter(Type(BASE_TYPE_STRING));
code += "(" + index + ") : null";
}
break;
}
case BASE_TYPE_UNION:
code += "() where TTable : struct, IFlatbufferObject";
code += offset_prefix + "(TTable?)" + getter;
code += "<TTable>(o + __p.bb_pos) : null";
if (HasUnionStringValue(*field.value.type.enum_def)) {
code += member_suffix;
code += "}\n";
code += " public string " + MakeCamel(field.name, true) +
"AsString()";
code += offset_prefix + GenGetter(Type(BASE_TYPE_STRING));
code += "(o + __p.bb_pos) : null";
}
break;
default: FLATBUFFERS_ASSERT(0);
}
}
code += member_suffix;
code += "}\n";
if (field.value.type.base_type == BASE_TYPE_VECTOR) {
code += " public int " + MakeCamel(field.name, true);
code += "Length";
code += " { get";
code += offset_prefix;
code += "__p.__vector_len(o) : 0; ";
code += "} ";
code += "}\n";
// See if we should generate a by-key accessor.
if (field.value.type.element == BASE_TYPE_STRUCT &&
!field.value.type.struct_def->fixed) {
auto &sd = *field.value.type.struct_def;
auto &fields = sd.fields.vec;
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
auto &key_field = **kit;
if (key_field.key) {
auto qualified_name = WrapInNameSpace(sd);
code += " public " + qualified_name + "? ";
code += MakeCamel(field.name, true) + "ByKey(";
code += GenTypeGet(key_field.value.type) + " key)";
code += offset_prefix;
code += qualified_name + ".__lookup_by_key(";
code += "__p.__vector(o), key, ";
code += "__p.bb) : null; ";
code += "}\n";
break;
}
}
}
}
// Generate a ByteBuffer accessor for strings & vectors of scalars.
if ((field.value.type.base_type == BASE_TYPE_VECTOR &&
IsScalar(field.value.type.VectorType().base_type)) ||
field.value.type.base_type == BASE_TYPE_STRING) {
code += "#if ENABLE_SPAN_T\n";
code += " public Span<" + GenTypeBasic(field.value.type.VectorType()) +
"> Get";
code += MakeCamel(field.name, true);
code += "Bytes() { return ";
code += "__p.__vector_as_span<" +
GenTypeBasic(field.value.type.VectorType()) + ">(";
code += NumToString(field.value.offset);
code +=
", " + NumToString(SizeOf(field.value.type.VectorType().base_type));
code += "); }\n";
code += "#else\n";
code += " public ArraySegment<byte>? Get";
code += MakeCamel(field.name, true);
code += "Bytes() { return ";
code += "__p.__vector_as_arraysegment(";
code += NumToString(field.value.offset);
code += "); }\n";
code += "#endif\n";
// For direct blockcopying the data into a typed array
code += " public ";
code += GenTypeBasic(field.value.type.VectorType());
code += "[] Get";
code += MakeCamel(field.name, true);
code += "Array() { ";
if (IsEnum(field.value.type.VectorType())) {
// Since __vector_as_array does not work for enum types,
// fill array using an explicit loop.
code += "int o = __p.__offset(";
code += NumToString(field.value.offset);
code += "); if (o == 0) return null; int p = ";
code += "__p.__vector(o); int l = ";
code += "__p.__vector_len(o); ";
code += GenTypeBasic(field.value.type.VectorType());
code += "[] a = new ";
code += GenTypeBasic(field.value.type.VectorType());
code += "[l]; for (int i = 0; i < l; i++) { a[i] = " + getter;
code += "(p + i * ";
code += NumToString(InlineSize(field.value.type.VectorType()));
code += "); } return a;";
} else {
code += "return ";
code += "__p.__vector_as_array<";
code += GenTypeBasic(field.value.type.VectorType());
code += ">(";
code += NumToString(field.value.offset);
code += ");";
}
code += " }\n";
}
// generate object accessors if is nested_flatbuffer
if (field.nested_flatbuffer) {
auto nested_type_name = WrapInNameSpace(*field.nested_flatbuffer);
auto nested_method_name =
MakeCamel(field.name, true) + "As" + field.nested_flatbuffer->name;
auto get_nested_method_name = nested_method_name;
get_nested_method_name = "Get" + nested_method_name;
conditional_cast = "(" + nested_type_name + "?)";
obj = "(new " + nested_type_name + "())";
code += " public " + nested_type_name + "? ";
code += get_nested_method_name + "(";
code += ") { int o = __p.__offset(";
code += NumToString(field.value.offset) + "); ";
code += "return o != 0 ? " + conditional_cast + obj + ".__assign(";
code += "__p.";
code += "__indirect(__p.__vector(o)), ";
code += "__p.bb) : null; }\n";
}
// Generate mutators for scalar fields or vectors of scalars.
if (parser_.opts.mutable_buffer) {
auto is_series = (IsSeries(field.value.type));
const auto &underlying_type =
is_series ? field.value.type.VectorType() : field.value.type;
// Boolean parameters have to be explicitly converted to byte
// representation.
auto setter_parameter = underlying_type.base_type == BASE_TYPE_BOOL
? "(byte)(" + field.name + " ? 1 : 0)"
: field.name;
auto mutator_prefix = MakeCamel("mutate", true);
// A vector mutator also needs the index of the vector element it should
// mutate.
auto mutator_params = (is_series ? "(int j, " : "(") +
GenTypeGet(underlying_type) + " " + field.name +
") { ";
auto setter_index =
is_series
? "__p." +
(IsArray(field.value.type)
? "bb_pos + " + NumToString(field.value.offset)
: "__vector(o)") +
+" + j * " + NumToString(InlineSize(underlying_type))
: (struct_def.fixed
? "__p.bb_pos + " + NumToString(field.value.offset)
: "o + __p.bb_pos");
if (IsScalar(underlying_type.base_type) && !IsUnion(field.value.type)) {
code += " public ";
code += struct_def.fixed ? "void " : "bool ";
code += mutator_prefix + MakeCamel(field.name, true);
code += mutator_params;
if (struct_def.fixed) {
code += GenSetter(underlying_type) + "(" + setter_index + ", ";
code += src_cast + setter_parameter + "); }\n";
} else {
code += "int o = __p.__offset(";
code += NumToString(field.value.offset) + ");";
code += " if (o != 0) { " + GenSetter(underlying_type);
code += "(" + setter_index + ", " + src_cast + setter_parameter +
"); return true; } else { return false; } }\n";
}
}
}
if (parser_.opts.java_primitive_has_method &&
IsScalar(field.value.type.base_type) && !struct_def.fixed) {
auto vt_offset_constant = " public static final int VT_" +
MakeScreamingCamel(field.name) + " = " +
NumToString(field.value.offset) + ";";
code += vt_offset_constant;
code += "\n";
}
}
code += "\n";
auto struct_has_create = false;
std::set<flatbuffers::FieldDef *> field_has_create_set;
flatbuffers::FieldDef *key_field = nullptr;
if (struct_def.fixed) {
struct_has_create = true;
// create a struct constructor function
code += " public static " + GenOffsetType(struct_def) + " ";
code += "Create";
code += struct_def.name + "(FlatBufferBuilder builder";
GenStructArgs(struct_def, code_ptr, "");
code += ") {\n";
GenStructBody(struct_def, code_ptr, "");
code += " return ";
code += GenOffsetConstruct(struct_def, "builder.Offset");
code += ";\n }\n";
} else {
// Generate a method that creates a table in one go. This is only possible
// when the table has no struct fields, since those have to be created
// inline, and there's no way to do so in Java.
bool has_no_struct_fields = true;
int num_fields = 0;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
if (IsStruct(field.value.type)) {
has_no_struct_fields = false;
} else {
num_fields++;
}
}
// JVM specifications restrict default constructor params to be < 255.
// Longs and doubles take up 2 units, so we set the limit to be < 127.
if ((has_no_struct_fields || opts.generate_object_based_api) &&
num_fields && num_fields < 127) {
struct_has_create = true;
// Generate a table constructor of the form:
// public static int createName(FlatBufferBuilder builder, args...)
code += " public static " + GenOffsetType(struct_def) + " ";
code += "Create" + struct_def.name;
code += "(FlatBufferBuilder builder";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
code += ",\n ";
if (IsStruct(field.value.type) && opts.generate_object_based_api) {
code += WrapInNameSpace(
field.value.type.struct_def->defined_namespace,
GenTypeName_ObjectAPI(field.value.type.struct_def->name, opts));
code += " ";
code += field.name;
code += " = null";
} else {
code += GenTypeBasic(field.value.type);
code += " ";
code += field.name;
if (!IsScalar(field.value.type.base_type)) code += "Offset";
code += " = ";
code += GenDefaultValueBasic(field);
}
}
code += ") {\n builder.";
code += "StartTable(";
code += NumToString(struct_def.fields.vec.size()) + ");\n";
for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
size; size /= 2) {
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
auto &field = **it;
if (!field.deprecated &&
(!struct_def.sortbysize ||
size == SizeOf(field.value.type.base_type))) {
code += " " + struct_def.name + ".";
code += "Add";
code += MakeCamel(field.name) + "(builder, ";
if (IsStruct(field.value.type) &&
opts.generate_object_based_api) {
code += GenTypePointer(field.value.type) + ".Pack(builder, " +
field.name + ")";
} else {
code += field.name;
if (!IsScalar(field.value.type.base_type)) code += "Offset";
}
code += ");\n";
}
}
}
code += " return " + struct_def.name + ".";
code += "End" + struct_def.name;
code += "(builder);\n }\n\n";
}
// Generate a set of static methods that allow table construction,
// of the form:
// public static void addName(FlatBufferBuilder builder, short name)
// { builder.addShort(id, name, default); }
// Unlike the Create function, these always work.
code += " public static void Start";
code += struct_def.name;
code += "(FlatBufferBuilder builder) { builder.";
code += "StartTable(";
code += NumToString(struct_def.fields.vec.size()) + "); }\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
if (field.key) key_field = &field;
code += " public static void Add";
code += MakeCamel(field.name);
code += "(FlatBufferBuilder builder, ";
code += GenTypeBasic(field.value.type);
auto argname = MakeCamel(field.name, false);
if (!IsScalar(field.value.type.base_type)) argname += "Offset";
code += " " + argname + ") { builder.Add";
code += GenMethod(field.value.type) + "(";
code += NumToString(it - struct_def.fields.vec.begin()) + ", ";
code += SourceCastBasic(field.value.type);
code += argname;
if (!IsScalar(field.value.type.base_type) &&
field.value.type.base_type != BASE_TYPE_UNION) {
code += ".Value";
}
code += ", ";
code += GenDefaultValue(field, false);
code += "); }\n";
if (field.value.type.base_type == BASE_TYPE_VECTOR) {
auto vector_type = field.value.type.VectorType();
auto alignment = InlineAlignment(vector_type);
auto elem_size = InlineSize(vector_type);
if (!IsStruct(vector_type)) {
field_has_create_set.insert(&field);
code += " public static VectorOffset ";
code += "Create";
code += MakeCamel(field.name);
code += "Vector(FlatBufferBuilder builder, ";
code += GenTypeBasic(vector_type) + "[] data) ";
code += "{ builder.StartVector(";
code += NumToString(elem_size);
code += ", data.Length, ";
code += NumToString(alignment);
code += "); for (int i = data.";
code += "Length - 1; i >= 0; i--) builder.";
code += "Add";
code += GenMethod(vector_type);
code += "(";
code += SourceCastBasic(vector_type);
code += "data[i]";
if ((vector_type.base_type == BASE_TYPE_STRUCT ||
vector_type.base_type == BASE_TYPE_STRING))
code += ".Value";
code += "); return ";
code += "builder.EndVector(); }\n";
code += " public static VectorOffset ";
code += "Create";
code += MakeCamel(field.name);
code += "VectorBlock(FlatBufferBuilder builder, ";
code += GenTypeBasic(vector_type) + "[] data) ";
code += "{ builder.StartVector(";
code += NumToString(elem_size);
code += ", data.Length, ";
code += NumToString(alignment);
code += "); builder.Add(data); return builder.EndVector(); }\n";
}
// Generate a method to start a vector, data to be added manually
// after.
code += " public static void Start";
code += MakeCamel(field.name);
code += "Vector(FlatBufferBuilder builder, int numElems) ";
code += "{ builder.StartVector(";
code += NumToString(elem_size);
code += ", numElems, " + NumToString(alignment);
code += "); }\n";
}
}
code += " public static " + GenOffsetType(struct_def) + " ";
code += "End" + struct_def.name;
code += "(FlatBufferBuilder builder) {\n int o = builder.";
code += "EndTable();\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (!field.deprecated && field.required) {
code += " builder.Required(o, ";
code += NumToString(field.value.offset);
code += "); // " + field.name + "\n";
}
}
code += " return " + GenOffsetConstruct(struct_def, "o") + ";\n }\n";
if (parser_.root_struct_def_ == &struct_def) {
std::string size_prefix[] = { "", "SizePrefixed" };
for (int i = 0; i < 2; ++i) {
code += " public static void ";
code += "Finish" + size_prefix[i] + struct_def.name;
code +=
"Buffer(FlatBufferBuilder builder, " + GenOffsetType(struct_def);
code += " offset) {";
code += " builder.Finish" + size_prefix[i] + "(offset";
code += ".Value";
if (parser_.file_identifier_.length())
code += ", \"" + parser_.file_identifier_ + "\"";
code += "); }\n";
}
}
}
// Only generate key compare function for table,
// because `key_field` is not set for struct
if (struct_def.has_key && !struct_def.fixed) {
FLATBUFFERS_ASSERT(key_field);
code += "\n public static VectorOffset ";
code += "CreateSortedVectorOf" + struct_def.name;
code += "(FlatBufferBuilder builder, ";
code += "Offset<" + struct_def.name + ">";
code += "[] offsets) {\n";
code += " Array.Sort(offsets, (Offset<" + struct_def.name +
"> o1, Offset<" + struct_def.name + "> o2) => " +
GenKeyGetter(key_field);
code += ");\n";
code += " return builder.CreateVectorOfTables(offsets);\n }\n";
code += "\n public static " + struct_def.name + "?";
code += " __lookup_by_key(";
code += "int vectorLocation, ";
code += GenTypeGet(key_field->value.type);
code += " key, ByteBuffer bb) {\n";
if (key_field->value.type.base_type == BASE_TYPE_STRING) {
code += " byte[] byteKey = ";
code += "System.Text.Encoding.UTF8.GetBytes(key);\n";
}
code += " int span = ";
code += "bb.GetInt(vectorLocation - 4);\n";
code += " int start = 0;\n";
code += " while (span != 0) {\n";
code += " int middle = span / 2;\n";
code += GenLookupKeyGetter(key_field);
code += " if (comp > 0) {\n";
code += " span = middle;\n";
code += " } else if (comp < 0) {\n";
code += " middle++;\n";
code += " start += middle;\n";
code += " span -= middle;\n";
code += " } else {\n";
code += " return ";
code += "new " + struct_def.name + "()";
code += ".__assign(tableOffset, bb);\n";
code += " }\n }\n";
code += " return null;\n";
code += " }\n";
}
if (opts.generate_object_based_api) {
GenPackUnPack_ObjectAPI(struct_def, code_ptr, opts, struct_has_create,
field_has_create_set);
}
code += "};\n\n";
if (opts.generate_object_based_api) {
GenStruct_ObjectAPI(struct_def, code_ptr, opts);
}
}
void GenVectorAccessObject(StructDef &struct_def,
std::string *code_ptr) const {
auto &code = *code_ptr;
// Generate a vector of structs accessor class.
code += "\n";
code += " ";
if (!struct_def.attributes.Lookup("private")) code += "public ";
code += "static struct Vector : BaseVector\n{\n";
// Generate the __assign method that sets the field in a pre-existing
// accessor object. This is to allow object reuse.
std::string method_indent = " ";
code += method_indent + "public Vector ";
code += "__assign(int _vector, int _element_size, ByteBuffer _bb) { ";
code += "__reset(_vector, _element_size, _bb); return this; }\n\n";
auto type_name = struct_def.name;
auto method_start = method_indent + "public " + type_name + " Get";
// Generate the accessors that don't do object reuse.
code += method_start + "(int j) { return Get";
code += "(new " + type_name + "(), j); }\n";
code += method_start + "(" + type_name + " obj, int j) { ";
code += " return obj.__assign(";
code += struct_def.fixed ? "__p.__element(j)"
: "__p.__indirect(__p.__element(j), bb)";
code += ", __p.bb); }\n";
// See if we should generate a by-key accessor.
if (!struct_def.fixed) {
auto &fields = struct_def.fields.vec;
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
auto &key_field = **kit;
if (key_field.key) {
auto nullable_annotation =
parser_.opts.gen_nullable ? "@Nullable " : "";
code += method_indent + nullable_annotation;
code += "public " + type_name + "? ";
code += "GetByKey(";
code += GenTypeGet(key_field.value.type) + " key) { ";
code += " return __lookup_by_key(null, ";
code += "__p.__vector(), key, ";
code += "__p.bb); ";
code += "}\n";
code += method_indent + nullable_annotation;
code += "public " + type_name + "?" + " ";
code += "GetByKey(";
code += type_name + "? obj, ";
code += GenTypeGet(key_field.value.type) + " key) { ";
code += " return __lookup_by_key(obj, ";
code += "__p.__vector(), key, ";
code += "__p.bb); ";
code += "}\n";
break;
}
}
}
code += " }\n";
}
void GenEnum_ObjectAPI(EnumDef &enum_def, std::string *code_ptr,
const IDLOptions &opts) const {
auto &code = *code_ptr;
if (enum_def.generated) return;
if (!enum_def.is_union) return;
if (enum_def.attributes.Lookup("private")) {
code += "internal ";
} else {
code += "public ";
}
auto union_name = enum_def.name + "Union";
code += "class " + union_name + " {\n";
// Type
code += " public " + enum_def.name + " Type { get; set; }\n";
// Value
code += " public object Value { get; set; }\n";
code += "\n";
// Constructor
code += " public " + union_name + "() {\n";
code += " this.Type = " + enum_def.name + "." +
enum_def.Vals()[0]->name + ";\n";
code += " this.Value = null;\n";
code += " }\n\n";
// As<T>
code += " public T As<T>() where T : class { return this.Value as T; }\n";
// As
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
if (ev.union_type.base_type == BASE_TYPE_NONE) continue;
auto type_name = GenTypeGet_ObjectAPI(ev.union_type, opts);
if (ev.union_type.base_type == BASE_TYPE_STRUCT &&
ev.union_type.struct_def->attributes.Lookup("private")) {
code += " internal ";
} else {
code += " public ";
}
code += type_name + " As" + ev.name + "() { return this.As<" + type_name +
">(); }\n";
}
code += "\n";
// Pack()
code += " public static int Pack(FlatBuffers.FlatBufferBuilder builder, " +
union_name + " _o) {\n";
code += " switch (_o.Type) {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
if (ev.union_type.base_type == BASE_TYPE_NONE) {
code += " default: return 0;\n";
} else {
code += " case " + enum_def.name + "." + ev.name + ": return ";
if (ev.union_type.base_type == BASE_TYPE_STRING) {
code += "builder.CreateString(_o.As" + ev.name + "()).Value;\n";
} else {
code += GenTypeGet(ev.union_type) + ".Pack(builder, _o.As" + ev.name +
"()).Value;\n";
}
}
}
code += " }\n";
code += " }\n";
code += "}\n\n";
// JsonConverter
if (opts.cs_gen_json_serializer) {
if (enum_def.attributes.Lookup("private")) {
code += "internal ";
} else {
code += "public ";
}
code += "class " + union_name +
"_JsonConverter : Newtonsoft.Json.JsonConverter {\n";
code += " public override bool CanConvert(System.Type objectType) {\n";
code += " return objectType == typeof(" + union_name +
") || objectType == typeof(System.Collections.Generic.List<" +
union_name + ">);\n";
code += " }\n";
code +=
" public override void WriteJson(Newtonsoft.Json.JsonWriter writer, "
"object value, "
"Newtonsoft.Json.JsonSerializer serializer) {\n";
code += " var _olist = value as System.Collections.Generic.List<" +
union_name + ">;\n";
code += " if (_olist != null) {\n";
code += " writer.WriteStartArray();\n";
code +=
" foreach (var _o in _olist) { this.WriteJson(writer, _o, "
"serializer); }\n";
code += " writer.WriteEndArray();\n";
code += " } else {\n";
code += " this.WriteJson(writer, value as " + union_name +
", serializer);\n";
code += " }\n";
code += " }\n";
code += " public void WriteJson(Newtonsoft.Json.JsonWriter writer, " +
union_name +
" _o, "
"Newtonsoft.Json.JsonSerializer serializer) {\n";
code += " if (_o == null) return;\n";
code += " serializer.Serialize(writer, _o.Value);\n";
code += " }\n";
code +=
" public override object ReadJson(Newtonsoft.Json.JsonReader "
"reader, "
"System.Type objectType, "
"object existingValue, Newtonsoft.Json.JsonSerializer serializer) "
"{\n";
code +=
" var _olist = existingValue as System.Collections.Generic.List<" +
union_name + ">;\n";
code += " if (_olist != null) {\n";
code += " for (var _j = 0; _j < _olist.Count; ++_j) {\n";
code += " reader.Read();\n";
code +=
" _olist[_j] = this.ReadJson(reader, _olist[_j], "
"serializer);\n";
code += " }\n";
code += " reader.Read();\n";
code += " return _olist;\n";
code += " } else {\n";
code += " return this.ReadJson(reader, existingValue as " +
union_name + ", serializer);\n";
code += " }\n";
code += " }\n";
code += " public " + union_name +
" ReadJson(Newtonsoft.Json.JsonReader reader, " + union_name +
" _o, Newtonsoft.Json.JsonSerializer serializer) {\n";
code += " if (_o == null) return null;\n";
code += " switch (_o.Type) {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
auto &ev = **it;
if (ev.union_type.base_type == BASE_TYPE_NONE) {
code += " default: break;\n";
} else {
auto type_name = GenTypeGet_ObjectAPI(ev.union_type, opts);
code += " case " + enum_def.name + "." + ev.name +
": _o.Value = serializer.Deserialize<" + type_name +
">(reader); break;\n";
}
}
code += " }\n";
code += " return _o;\n";
code += " }\n";
code += "}\n\n";
}
}
std::string GenTypeName_ObjectAPI(const std::string &name,
const IDLOptions &opts) const {
return opts.object_prefix + name + opts.object_suffix;
}
void GenUnionUnPack_ObjectAPI(const EnumDef &enum_def, std::string *code_ptr,
const std::string &camel_name,
bool is_vector) const {
auto &code = *code_ptr;
std::string varialbe_name = "_o." + camel_name;
std::string type_suffix = "";
std::string func_suffix = "()";
std::string indent = " ";
if (is_vector) {
varialbe_name = "_o_" + camel_name;
type_suffix = "(_j)";
func_suffix = "(_j)";
indent = " ";
}
if (is_vector) {
code += indent + "var " + varialbe_name + " = new ";
} else {
code += indent + varialbe_name + " = new ";
}
code += WrapInNameSpace(enum_def) + "Union();\n";
code += indent + varialbe_name + ".Type = this." + camel_name + "Type" +
type_suffix + ";\n";
code +=
indent + "switch (this." + camel_name + "Type" + type_suffix + ") {\n";
for (auto eit = enum_def.Vals().begin(); eit != enum_def.Vals().end();
++eit) {
auto &ev = **eit;
if (ev.union_type.base_type == BASE_TYPE_NONE) {
code += indent + " default: break;\n";
} else {
code += indent + " case " + WrapInNameSpace(enum_def) + "." + ev.name +
":\n";
code += indent + " " + varialbe_name + ".Value = this." + camel_name;
if (ev.union_type.base_type == BASE_TYPE_STRING) {
code += "AsString" + func_suffix + ";\n";
} else {
code += "<" + GenTypeGet(ev.union_type) + ">" + func_suffix;
code += ".HasValue ? this." + camel_name;
code += "<" + GenTypeGet(ev.union_type) + ">" + func_suffix +
".Value.UnPack() : null;\n";
}
code += indent + " break;\n";
}
}
code += indent + "}\n";
if (is_vector) {
code += indent + "_o." + camel_name + ".Add(" + varialbe_name + ");\n";
}
}
void GenPackUnPack_ObjectAPI(
StructDef &struct_def, std::string *code_ptr, const IDLOptions &opts,
bool struct_has_create,
const std::set<FieldDef *> &field_has_create) const {
auto &code = *code_ptr;
auto struct_name = GenTypeName_ObjectAPI(struct_def.name, opts);
// UnPack()
code += " public " + struct_name + " UnPack() {\n";
code += " var _o = new " + struct_name + "();\n";
code += " this.UnPackTo(_o);\n";
code += " return _o;\n";
code += " }\n";
// UnPackTo()
code += " public void UnPackTo(" + struct_name + " _o) {\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
auto camel_name = MakeCamel(field.name);
auto start = " _o." + camel_name + " = ";
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
auto fixed = struct_def.fixed && field.value.type.struct_def->fixed;
if (fixed) {
code += start + "this." + camel_name + ".UnPack();\n";
} else {
code += start + "this." + camel_name + ".HasValue ? this." +
camel_name + ".Value.UnPack() : null;\n";
}
break;
}
case BASE_TYPE_ARRAY: {
auto type_name = GenTypeGet_ObjectAPI(field.value.type, opts);
auto length_str = NumToString(field.value.type.fixed_length);
auto unpack_method = field.value.type.struct_def == nullptr
? ""
: field.value.type.struct_def->fixed
? ".UnPack()"
: "?.UnPack()";
code += start + "new " + type_name.substr(0, type_name.length() - 1) +
length_str + "];\n";
code += " for (var _j = 0; _j < " + length_str + "; ++_j) { _o." +
camel_name + "[_j] = this." + camel_name + "(_j)" +
unpack_method + "; }\n";
break;
}
case BASE_TYPE_VECTOR:
if (field.value.type.element == BASE_TYPE_UNION) {
code += start + "new " +
GenTypeGet_ObjectAPI(field.value.type, opts) + "();\n";
code += " for (var _j = 0; _j < this." + camel_name +
"Length; ++_j) {\n";
GenUnionUnPack_ObjectAPI(*field.value.type.enum_def, code_ptr,
camel_name, true);
code += " }\n";
} else if (field.value.type.element != BASE_TYPE_UTYPE) {
auto fixed = field.value.type.struct_def == nullptr;
code += start + "new " +
GenTypeGet_ObjectAPI(field.value.type, opts) + "();\n";
code += " for (var _j = 0; _j < this." + camel_name +
"Length; ++_j) {";
code += "_o." + camel_name + ".Add(";
if (fixed) {
code += "this." + camel_name + "(_j)";
} else {
code += "this." + camel_name + "(_j).HasValue ? this." +
camel_name + "(_j).Value.UnPack() : null";
}
code += ");}\n";
}
break;
case BASE_TYPE_UTYPE: break;
case BASE_TYPE_UNION: {
GenUnionUnPack_ObjectAPI(*field.value.type.enum_def, code_ptr,
camel_name, false);
break;
}
default: {
code += start + "this." + camel_name + ";\n";
break;
}
}
}
code += " }\n";
// Pack()
code += " public static " + GenOffsetType(struct_def) +
" Pack(FlatBufferBuilder builder, " + struct_name + " _o) {\n";
code += " if (_o == null) return default(" + GenOffsetType(struct_def) +
");\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
auto camel_name = MakeCamel(field.name);
// pre
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
if (!field.value.type.struct_def->fixed) {
code += " var _" + field.name + " = _o." + camel_name +
" == null ? default(" +
GenOffsetType(*field.value.type.struct_def) +
") : " + GenTypeGet(field.value.type) +
".Pack(builder, _o." + camel_name + ");\n";
} else if (struct_def.fixed && struct_has_create) {
std::vector<FieldArrayLength> array_lengths;
FieldArrayLength tmp_array_length = {
field.name,
field.value.type.fixed_length,
};
array_lengths.push_back(tmp_array_length);
GenStructPackDecl_ObjectAPI(*field.value.type.struct_def, code_ptr,
array_lengths);
}
break;
}
case BASE_TYPE_STRING: {
std::string create_string =
field.shared ? "CreateSharedString" : "CreateString";
code += " var _" + field.name + " = _o." + camel_name +
" == null ? default(StringOffset) : "
"builder." +
create_string + "(_o." + camel_name + ");\n";
break;
}
case BASE_TYPE_VECTOR: {
if (field_has_create.find(&field) != field_has_create.end()) {
auto property_name = camel_name;
auto gen_for_loop = true;
std::string array_name = "__" + field.name;
std::string array_type = "";
std::string to_array = "";
switch (field.value.type.element) {
case BASE_TYPE_STRING: {
std::string create_string =
field.shared ? "CreateSharedString" : "CreateString";
array_type = "StringOffset";
to_array += "builder." + create_string + "(_o." +
property_name + "[_j])";
break;
}
case BASE_TYPE_STRUCT:
array_type = "Offset<" + GenTypeGet(field.value.type) + ">";
to_array = GenTypeGet(field.value.type) + ".Pack(builder, _o." +
property_name + "[_j])";
break;
case BASE_TYPE_UTYPE:
property_name = camel_name.substr(0, camel_name.size() - 4);
array_type = WrapInNameSpace(*field.value.type.enum_def);
to_array = "_o." + property_name + "[_j].Type";
break;
case BASE_TYPE_UNION:
array_type = "int";
to_array = WrapInNameSpace(*field.value.type.enum_def) +
"Union.Pack(builder, _o." + property_name + "[_j])";
break;
default: gen_for_loop = false; break;
}
code += " var _" + field.name + " = default(VectorOffset);\n";
code += " if (_o." + property_name + " != null) {\n";
if (gen_for_loop) {
code += " var " + array_name + " = new " + array_type +
"[_o." + property_name + ".Count];\n";
code += " for (var _j = 0; _j < " + array_name +
".Length; ++_j) { ";
code += array_name + "[_j] = " + to_array + "; }\n";
} else {
code += " var " + array_name + " = _o." + property_name +
".ToArray();\n";
}
code += " _" + field.name + " = Create" + camel_name +
"Vector(builder, " + array_name + ");\n";
code += " }\n";
} else {
auto pack_method =
field.value.type.struct_def == nullptr
? "builder.Add" + GenMethod(field.value.type.VectorType()) +
"(_o." + camel_name + "[_j]);"
: GenTypeGet(field.value.type) + ".Pack(builder, _o." +
camel_name + "[_j]);";
code += " var _" + field.name + " = default(VectorOffset);\n";
code += " if (_o." + camel_name + " != null) {\n";
code += " Start" + camel_name + "Vector(builder, _o." +
camel_name + ".Count);\n";
code += " for (var _j = _o." + camel_name +
".Count - 1; _j >= 0; --_j) { " + pack_method + " }\n";
code += " _" + field.name + " = builder.EndVector();\n";
code += " }\n";
}
break;
}
case BASE_TYPE_ARRAY: {
if (field.value.type.struct_def != nullptr) {
std::vector<FieldArrayLength> array_lengths;
FieldArrayLength tmp_array_length = {
field.name,
field.value.type.fixed_length,
};
array_lengths.push_back(tmp_array_length);
GenStructPackDecl_ObjectAPI(*field.value.type.struct_def, code_ptr,
array_lengths);
} else {
code += " var _" + field.name + " = _o." + camel_name + ";\n";
}
break;
}
case BASE_TYPE_UNION: {
code += " var _" + field.name + "_type = _o." + camel_name +
" == null ? " + WrapInNameSpace(*field.value.type.enum_def) +
".NONE : " + "_o." + camel_name + ".Type;\n";
code +=
" var _" + field.name + " = _o." + camel_name +
" == null ? 0 : " + GenTypeGet_ObjectAPI(field.value.type, opts) +
".Pack(builder, _o." + camel_name + ");\n";
break;
}
default: break;
}
}
if (struct_has_create) {
// Create
code += " return Create" + struct_def.name + "(\n";
code += " builder";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
auto camel_name = MakeCamel(field.name);
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
if (struct_def.fixed) {
GenStructPackCall_ObjectAPI(*field.value.type.struct_def,
code_ptr,
" _" + field.name + "_");
} else {
code += ",\n";
if (field.value.type.struct_def->fixed) {
if (opts.generate_object_based_api)
code += " _o." + camel_name;
else
code += " " + GenTypeGet(field.value.type) +
".Pack(builder, _o." + camel_name + ")";
} else {
code += " _" + field.name;
}
}
break;
}
case BASE_TYPE_ARRAY: {
if (field.value.type.struct_def != nullptr) {
GenStructPackCall_ObjectAPI(*field.value.type.struct_def,
code_ptr,
" _" + field.name + "_");
} else {
code += ",\n";
code += " _" + field.name;
}
break;
}
case BASE_TYPE_UNION: FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_UTYPE: FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_STRING: FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
code += ",\n";
code += " _" + field.name;
break;
}
default: // scalar
code += ",\n";
code += " _o." + camel_name;
break;
}
}
code += ");\n";
} else {
// Start, End
code += " Start" + struct_def.name + "(builder);\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
auto camel_name = MakeCamel(field.name);
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
if (field.value.type.struct_def->fixed) {
code += " Add" + camel_name + "(builder, " +
GenTypeGet(field.value.type) + ".Pack(builder, _o." +
camel_name + "));\n";
} else {
code +=
" Add" + camel_name + "(builder, _" + field.name + ");\n";
}
break;
}
case BASE_TYPE_STRING: FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
code +=
" Add" + camel_name + "(builder, _" + field.name + ");\n";
break;
}
case BASE_TYPE_UTYPE: break;
case BASE_TYPE_UNION: {
code += " Add" + camel_name + "Type(builder, _" + field.name +
"_type);\n";
code +=
" Add" + camel_name + "(builder, _" + field.name + ");\n";
break;
}
// scalar
default: {
code +=
" Add" + camel_name + "(builder, _o." + camel_name + ");\n";
break;
}
}
}
code += " return End" + struct_def.name + "(builder);\n";
}
code += " }\n";
}
void GenStructPackDecl_ObjectAPI(
const StructDef &struct_def, std::string *code_ptr,
std::vector<FieldArrayLength> &array_lengths) const {
auto &code = *code_ptr;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
auto is_array = IsArray(field.value.type);
const auto &field_type =
is_array ? field.value.type.VectorType() : field.value.type;
FieldArrayLength tmp_array_length = {
field.name,
field_type.fixed_length,
};
array_lengths.push_back(tmp_array_length);
if (field_type.struct_def != nullptr) {
GenStructPackDecl_ObjectAPI(*field_type.struct_def, code_ptr,
array_lengths);
} else {
std::vector<FieldArrayLength> array_only_lengths;
for (size_t i = 0; i < array_lengths.size(); ++i) {
if (array_lengths[i].length > 0) {
array_only_lengths.push_back(array_lengths[i]);
}
}
std::string name;
for (size_t i = 0; i < array_lengths.size(); ++i) {
name += "_" + array_lengths[i].name;
}
code += " var " + name + " = ";
if (array_only_lengths.size() > 0) {
code += "new " + GenTypeBasic(field_type) + "[";
for (size_t i = 0; i < array_only_lengths.size(); ++i) {
if (i != 0) { code += ","; }
code += NumToString(array_only_lengths[i].length);
}
code += "];\n";
code += " ";
// initialize array
for (size_t i = 0; i < array_only_lengths.size(); ++i) {
auto idx = "idx" + NumToString(i);
code += "for (var " + idx + " = 0; " + idx + " < " +
NumToString(array_only_lengths[i].length) + "; ++" + idx +
") {";
}
for (size_t i = 0; i < array_only_lengths.size(); ++i) {
auto idx = "idx" + NumToString(i);
if (i == 0) {
code += name + "[" + idx;
} else {
code += "," + idx;
}
}
code += "] = _o";
for (size_t i = 0, j = 0; i < array_lengths.size(); ++i) {
code += "." + MakeCamel(array_lengths[i].name);
if (array_lengths[i].length <= 0) continue;
code += "[idx" + NumToString(j++) + "]";
}
code += ";";
for (size_t i = 0; i < array_only_lengths.size(); ++i) { code += "}"; }
} else {
code += "_o";
for (size_t i = 0; i < array_lengths.size(); ++i) {
code += "." + MakeCamel(array_lengths[i].name);
}
code += ";";
}
code += "\n";
}
array_lengths.pop_back();
}
}
void GenStructPackCall_ObjectAPI(const StructDef &struct_def,
std::string *code_ptr,
std::string prefix) const {
auto &code = *code_ptr;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
const auto &field_type = field.value.type;
if (field_type.struct_def != nullptr) {
GenStructPackCall_ObjectAPI(*field_type.struct_def, code_ptr,
prefix + field.name + "_");
} else {
code += ",\n";
code += prefix + field.name;
}
}
}
std::string GenTypeGet_ObjectAPI(flatbuffers::Type type,
const IDLOptions &opts) const {
auto type_name = GenTypeGet(type);
// Replace to ObjectBaseAPI Type Name
switch (type.base_type) {
case BASE_TYPE_STRUCT: FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
if (type.struct_def != nullptr) {
auto type_name_length = type.struct_def->name.length();
auto new_type_name =
GenTypeName_ObjectAPI(type.struct_def->name, opts);
type_name.replace(type_name.length() - type_name_length,
type_name_length, new_type_name);
} else if (type.element == BASE_TYPE_UNION) {
type_name = WrapInNameSpace(*type.enum_def) + "Union";
}
break;
}
case BASE_TYPE_UNION: {
type_name = WrapInNameSpace(*type.enum_def) + "Union";
break;
}
default: break;
}
switch (type.base_type) {
case BASE_TYPE_ARRAY: {
type_name = type_name + "[]";
break;
}
case BASE_TYPE_VECTOR: {
type_name = "List<" + type_name + ">";
break;
}
default: break;
}
return type_name;
}
void GenStruct_ObjectAPI(StructDef &struct_def, std::string *code_ptr,
const IDLOptions &opts) const {
auto &code = *code_ptr;
if (struct_def.attributes.Lookup("private")) {
code += "internal ";
} else {
code += "public ";
}
if (struct_def.attributes.Lookup("csharp_partial")) {
// generate a partial class for this C# struct/table
code += "partial ";
}
auto class_name = GenTypeName_ObjectAPI(struct_def.name, opts);
code += "class " + class_name;
code += "\n{\n";
// Generate Properties
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
if (field.value.type.element == BASE_TYPE_UTYPE) continue;
auto type_name = GenTypeGet_ObjectAPI(field.value.type, opts);
auto camel_name = MakeCamel(field.name, true);
if (opts.cs_gen_json_serializer) {
if (IsUnion(field.value.type)) {
auto utype_name = WrapInNameSpace(*field.value.type.enum_def);
code +=
" [Newtonsoft.Json.JsonProperty(\"" + field.name + "_type\")]\n";
if (field.value.type.base_type == BASE_TYPE_VECTOR) {
code += " private " + utype_name + "[] " + camel_name + "Type {\n";
code += " get {\n";
code += " if (this." + camel_name + " == null) return null;\n";
code += " var _o = new " + utype_name + "[this." + camel_name +
".Count];\n";
code +=
" for (var _j = 0; _j < _o.Length; ++_j) { _o[_j] = "
"this." +
camel_name + "[_j].Type; }\n";
code += " return _o;\n";
code += " }\n";
code += " set {\n";
code += " this." + camel_name + " = new List<" + utype_name +
"Union>();\n";
code += " for (var _j = 0; _j < value.Length; ++_j) {\n";
code += " var _o = new " + utype_name + "Union();\n";
code += " _o.Type = value[_j];\n";
code += " this." + camel_name + ".Add(_o);\n";
code += " }\n";
code += " }\n";
code += " }\n";
} else {
code += " private " + utype_name + " " + camel_name + "Type {\n";
code += " get {\n";
code += " return this." + camel_name + " != null ? this." +
camel_name + ".Type : " + utype_name + ".NONE;\n";
code += " }\n";
code += " set {\n";
code += " this." + camel_name + " = new " + utype_name +
"Union();\n";
code += " this." + camel_name + ".Type = value;\n";
code += " }\n";
code += " }\n";
}
}
code += " [Newtonsoft.Json.JsonProperty(\"" + field.name + "\")]\n";
if (IsUnion(field.value.type)) {
auto union_name =
(field.value.type.base_type == BASE_TYPE_VECTOR)
? GenTypeGet_ObjectAPI(field.value.type.VectorType(), opts)
: type_name;
code += " [Newtonsoft.Json.JsonConverter(typeof(" + union_name +
"_JsonConverter))]\n";
}
if (field.attributes.Lookup("hash")) {
code += " [Newtonsoft.Json.JsonIgnore()]\n";
}
}
code += " public " + type_name + " " + camel_name + " { get; set; }\n";
}
// Generate Constructor
code += "\n";
code += " public " + class_name + "() {\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
if (field.value.type.element == BASE_TYPE_UTYPE) continue;
code += " this." + MakeCamel(field.name) + " = ";
auto type_name = GenTypeGet_ObjectAPI(field.value.type, opts);
if (IsScalar(field.value.type.base_type)) {
code += GenDefaultValue(field) + ";\n";
} else {
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
if (IsStruct(field.value.type)) {
code += "new " + type_name + "();\n";
} else {
code += "null;\n";
}
break;
}
case BASE_TYPE_ARRAY: {
code += "new " + type_name.substr(0, type_name.length() - 1) +
NumToString(field.value.type.fixed_length) + "];\n";
break;
}
default: {
code += "null;\n";
break;
}
}
}
}
code += " }\n";
// Generate Serialization
if (opts.cs_gen_json_serializer &&
parser_.root_struct_def_ == &struct_def) {
code += "\n";
code += " public static " + class_name +
" DeserializeFromJson(string jsonText) {\n";
code += " return Newtonsoft.Json.JsonConvert.DeserializeObject<" +
class_name + ">(jsonText);\n";
code += " }\n";
code += " public string SerializeToJson() {\n";
code +=
" return Newtonsoft.Json.JsonConvert.SerializeObject(this, "
"Newtonsoft.Json.Formatting.Indented);\n";
code += " }\n";
}
if (parser_.root_struct_def_ == &struct_def) {
code += " public static " + class_name +
" DeserializeFromBinary(byte[] fbBuffer) {\n";
code += " return " + struct_def.name + ".GetRootAs" + struct_def.name +
"(new ByteBuffer(fbBuffer)).UnPack();\n";
code += " }\n";
code += " public byte[] SerializeToBinary() {\n";
code += " var fbb = new FlatBufferBuilder(0x10000);\n";
code +=
" fbb.Finish(" + struct_def.name + ".Pack(fbb, this).Value);\n";
code += " return fbb.DataBuffer.ToSizedArray();\n";
code += " }\n";
}
code += "}\n\n";
}
// This tracks the current namespace used to determine if a type need to be
// prefixed by its namespace
const Namespace *cur_name_space_;
};
} // namespace csharp
bool GenerateCSharp(const Parser &parser, const std::string &path,
const std::string &file_name) {
csharp::CSharpGenerator generator(parser, path, file_name);
return generator.generate();
}
} // namespace flatbuffers
| 1 | 18,311 | This change is due to `clang_format` and is not related to this PR. | google-flatbuffers | java |
@@ -359,6 +359,11 @@ block_all_signals_except(kernel_sigset_t *oset, int num_signals,
kernel_sigdelset(&set, va_arg(ap, int));
}
va_end(ap);
+ /* We never block SIGSEGV or SIGBUS: we need them for various safe reads and to
+ * properly report crashes.
+ */
+ kernel_sigdelset(&set, SIGSEGV);
+ kernel_sigdelset(&set, SIGBUS);
sigprocmask_syscall(SIG_SETMASK, &set, oset, sizeof(set));
}
| 1 | /* **********************************************************
* Copyright (c) 2011-2019 Google, Inc. All rights reserved.
* Copyright (c) 2000-2010 VMware, 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 VMware, 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 VMWARE, 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.
*/
/* Copyright (c) 2003-2007 Determina Corp. */
/* Copyright (c) 2001-2003 Massachusetts Institute of Technology */
/* Copyright (c) 2000-2001 Hewlett-Packard Company */
/*
* signal.c - dynamorio signal handler
*/
#include <errno.h>
#undef errno
#include "signal_private.h" /* pulls in globals.h for us, in right order */
/* We want to build on older toolchains so we have our own copy of signal
* data structures
*/
#include "include/siginfo.h"
#ifdef LINUX
# include "include/sigcontext.h"
# include "include/signalfd.h"
# include "../globals.h" /* after our sigcontext.h, to preclude bits/sigcontext.h */
#elif defined(MACOS)
# include "../globals.h" /* this defines _XOPEN_SOURCE for Mac */
# include <signal.h> /* after globals.h, for _XOPEN_SOURCE from os_exports.h */
#endif
#ifdef LINUX
# include <linux/sched.h>
#endif
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <ucontext.h>
#include "os_private.h"
#include "../fragment.h"
#include "../fcache.h"
#include "../perfctr.h"
#include "arch.h"
#include "../monitor.h" /* for trace_abort */
#include "../link.h" /* for linking interrupted fragment_t */
#include "instr.h" /* to find target of SIGSEGV */
#include "decode.h" /* to find target of SIGSEGV */
#include "decode_fast.h" /* to handle self-mod code */
#include "../synch.h"
#include "../nudge.h"
#include "disassemble.h"
#include "ksynch.h"
#include "tls.h" /* tls_reinstate_selector */
#include "../translate.h"
#ifdef LINUX
# include "include/syscall.h"
#else
# include <sys/syscall.h>
#endif
#ifdef CLIENT_INTERFACE
# include "instrument.h"
#endif
#ifdef VMX86_SERVER
# include <errno.h>
#endif
/* Define the Linux names, which the code is already using */
#ifndef SA_NOMASK
# define SA_NOMASK SA_NODEFER
#endif
#ifndef SA_ONESHOT
# define SA_ONESHOT SA_RESETHAND
#endif
#ifndef SS_AUTODISARM
# define SS_AUTODISARM (1U << 31)
#endif
#ifndef SS_FLAG_BITS
# define SS_FLAG_BITS SS_AUTODISARM
#endif
#ifdef X86
/* Kernel-only flags. */
# define SA_IA32_ABI 0x02000000U
# define SA_X32_ABI 0x01000000U
#endif
/**** data structures ***************************************************/
/* The signal numbers are slightly different between operating systems.
* To support differing default actions, we have separate arrays, rather
* than indirecting to a single all-signals array.
*/
extern int default_action[];
/* We know that many signals are always asynchronous.
* Others, however, may be synchronous or may not -- e.g., another process
* could send us a SIGSEGV, and there is no way we can tell whether it
* was generated by a real memory fault or not. Thus we have to assume
* that we must not delay any SIGSEGV deliveries.
*/
extern bool can_always_delay[];
static inline bool
sig_is_alarm_signal(int sig)
{
return (sig == SIGALRM || sig == SIGVTALRM || sig == SIGPROF);
}
/* we do not use SIGSTKSZ b/c for things like code modification
* we end up calling many core routines and so want more space
* (though currently non-debug stack size == SIGSTKSZ (8KB))
*/
#define SIGSTACK_SIZE (DYNAMO_OPTION(signal_stack_size))
/* this flag not defined in our headers */
#define SA_RESTORER 0x04000000
/* if no app sigaction, it's RT, since that's our handler */
#ifdef LINUX
# define IS_RT_FOR_APP(info, sig) \
IF_X64_ELSE(true, \
((info)->app_sigaction[(sig)] == NULL \
? true \
: (TEST(SA_SIGINFO, (info)->app_sigaction[(sig)]->flags))))
#elif defined(MACOS)
# define IS_RT_FOR_APP(info, sig) (true)
#endif
/* kernel sets size and sp to 0 for SS_DISABLE
* when asked, will hand back SS_ONSTACK only if current xsp is inside the
* alt stack; otherwise, if an alt stack is registered, it will give flags of 0
* We do not support the "legacy stack switching" that uses the restorer field
* as seen in kernel sources.
*/
#define APP_HAS_SIGSTACK(info) \
((info)->app_sigstack.ss_sp != NULL && (info)->app_sigstack.ss_flags != SS_DISABLE)
/* Under normal circumstances the app_sigaction is lazily initialized when the
* app registers a signal handler, but during detach there are points where we
* are still intercepting signals after app_sigaction has been set to
* zeros. To be extra defensive, we do a NULL check.
*/
#define USE_APP_SIGSTACK(info, sig) \
(APP_HAS_SIGSTACK(info) && (info)->app_sigaction[sig] != NULL && \
TEST(SA_ONSTACK, (info)->app_sigaction[sig]->flags))
/* If we only intercept a few signals, we leave whether un-intercepted signals
* are blocked unchanged and stored in the kernel. If we intercept all (not
* quite yet: PR 297033, hence the need for this macro) we emulate the mask for
* all.
*/
#define EMULATE_SIGMASK(info, sig) \
(DYNAMO_OPTION(intercept_all_signals) || (info)->we_intercept[(sig)])
/* i#27: custom data to pass to the child of a clone */
/* PR i#149/403015: clone record now passed via a new dstack */
typedef struct _clone_record_t {
byte *dstack; /* dstack for new thread - allocated by parent thread */
#ifdef MACOS
/* XXX i#1403: once we have lower-level, earlier thread interception we can
* likely switch to something closer to what we do on Linux.
* This is used for bsdthread_create, where app_thread_xsp is NULL;
* for vfork, app_thread_xsp is non-NULL and this is unused.
*/
void *thread_arg;
#endif
reg_t app_thread_xsp; /* app xsp preserved for new thread to use */
app_pc continuation_pc;
thread_id_t caller_id;
int clone_sysnum;
uint clone_flags;
thread_sig_info_t info;
thread_sig_info_t *parent_info;
void *pcprofile_info;
#ifdef AARCHXX
/* To ensure we have the right value as of the point of the clone, we
* store it here (we'll have races if we try to get it during new thread
* init).
*/
reg_t app_stolen_value;
# ifndef AARCH64
dr_isa_mode_t isa_mode;
# endif
/* To ensure we have the right app lib tls base in child thread,
* we store it here if necessary (clone w/o CLONE_SETTLS or vfork).
*/
void *app_lib_tls_base;
#endif
/* we leave some padding at base of stack for dynamorio_clone
* to store values
*/
reg_t for_dynamorio_clone[4];
} __attribute__((__aligned__(ABI_STACK_ALIGNMENT))) clone_record_t;
/* i#350: set up signal handler for safe_read/faults during init */
static thread_sig_info_t init_info;
static kernel_sigset_t init_sigmask;
#ifdef DEBUG
static bool removed_sig_handler;
#endif
os_cxt_ptr_t osc_empty;
/**** function prototypes ***********************************************/
/* in x86.asm */
void
master_signal_handler(int sig, kernel_siginfo_t *siginfo, kernel_ucontext_t *ucxt);
static void
set_handler_and_record_app(dcontext_t *dcontext, thread_sig_info_t *info, int sig,
kernel_sigaction_t *act);
static void
intercept_signal(dcontext_t *dcontext, thread_sig_info_t *info, int sig);
static void
signal_info_init_sigaction(dcontext_t *dcontext, thread_sig_info_t *info);
static void
signal_info_exit_sigaction(dcontext_t *dcontext, thread_sig_info_t *info,
bool other_thread);
static bool
execute_handler_from_cache(dcontext_t *dcontext, int sig, sigframe_rt_t *our_frame,
sigcontext_t *sc_orig,
fragment_t *f _IF_CLIENT(byte *access_address));
static bool
execute_handler_from_dispatch(dcontext_t *dcontext, int sig);
/* Execute default action from code cache and may terminate the process.
* If returns, the return value decides if caller should restore
* the untranslated context.
*/
static bool
execute_default_from_cache(dcontext_t *dcontext, int sig, sigframe_rt_t *frame,
sigcontext_t *sc_orig, bool forged);
static void
execute_default_from_dispatch(dcontext_t *dcontext, int sig, sigframe_rt_t *frame);
static bool
handle_alarm(dcontext_t *dcontext, int sig, kernel_ucontext_t *ucxt);
static bool
handle_suspend_signal(dcontext_t *dcontext, kernel_ucontext_t *ucxt,
sigframe_rt_t *frame);
static bool
handle_nudge_signal(dcontext_t *dcontext, kernel_siginfo_t *siginfo,
kernel_ucontext_t *ucxt);
static void
init_itimer(dcontext_t *dcontext, bool first);
static bool
set_actual_itimer(dcontext_t *dcontext, int which, thread_sig_info_t *info, bool enable);
static bool
alarm_signal_has_DR_only_itimer(dcontext_t *dcontext, int signal);
#ifdef DEBUG
static void
dump_sigset(dcontext_t *dcontext, kernel_sigset_t *set);
#endif
static bool
is_sys_kill(dcontext_t *dcontext, byte *pc, byte *xsp, kernel_siginfo_t *info);
int
sigaction_syscall(int sig, kernel_sigaction_t *act, kernel_sigaction_t *oact)
{
#if !defined(VMX86_SERVER) && defined(LINUX)
/* PR 305020: must have SA_RESTORER for x64 */
/* i#2812: must have SA_RESTORER to handle vsyscall32 being disabled */
if (act != NULL && !TEST(SA_RESTORER, act->flags)) {
act->flags |= SA_RESTORER;
act->restorer = (void (*)(void))dynamorio_sigreturn;
}
#endif
return dynamorio_syscall(IF_MACOS_ELSE(SYS_sigaction, SYS_rt_sigaction), 4, sig, act,
oact, sizeof(kernel_sigset_t));
}
static inline bool
signal_is_interceptable(int sig)
{
return (sig != SIGKILL && sig != SIGSTOP);
}
static inline int
sigaltstack_syscall(const stack_t *newstack, stack_t *oldstack)
{
return dynamorio_syscall(SYS_sigaltstack, 2, newstack, oldstack);
}
static inline int
getitimer_syscall(int which, struct itimerval *val)
{
return dynamorio_syscall(SYS_getitimer, 2, which, val);
}
static inline int
setitimer_syscall(int which, struct itimerval *val, struct itimerval *old)
{
return dynamorio_syscall(SYS_setitimer, 3, which, val, old);
}
static inline int
sigprocmask_syscall(int how, kernel_sigset_t *set, kernel_sigset_t *oset,
size_t sigsetsize)
{
return dynamorio_syscall(IF_MACOS_ELSE(SYS_sigprocmask, SYS_rt_sigprocmask), 4, how,
set, oset, sigsetsize);
}
void
block_all_signals_except(kernel_sigset_t *oset, int num_signals,
... /* list of signals */)
{
kernel_sigset_t set;
kernel_sigfillset(&set);
va_list ap;
va_start(ap, num_signals);
for (int i = 0; i < num_signals; ++i) {
kernel_sigdelset(&set, va_arg(ap, int));
}
va_end(ap);
sigprocmask_syscall(SIG_SETMASK, &set, oset, sizeof(set));
}
static void
unblock_all_signals(kernel_sigset_t *oset)
{
kernel_sigset_t set;
kernel_sigemptyset(&set);
sigprocmask_syscall(SIG_SETMASK, &set, oset, sizeof(set));
}
/* exported for stackdump.c */
bool
set_default_signal_action(int sig)
{
kernel_sigset_t set;
kernel_sigaction_t act;
int rc;
memset(&act, 0, sizeof(act));
act.handler = (handler_t)SIG_DFL;
/* arm the signal */
rc = sigaction_syscall(sig, &act, NULL);
DODEBUG({ removed_sig_handler = true; });
/* If we're in our handler now, we have to unblock */
kernel_sigemptyset(&set);
kernel_sigaddset(&set, sig);
sigprocmask_syscall(SIG_UNBLOCK, &set, NULL, sizeof(set));
return (rc == 0);
}
static bool
set_ignore_signal_action(int sig)
{
kernel_sigaction_t act;
int rc;
memset(&act, 0, sizeof(act));
act.handler = (handler_t)SIG_IGN;
/* arm the signal */
rc = sigaction_syscall(sig, &act, NULL);
return (rc == 0);
}
/* We assume that signal handlers will be shared most of the time
* (pthreads shares them)
* Rather than start out with the handler table in local memory and then
* having to transfer to global, we just always use global
*/
static void
handler_free(dcontext_t *dcontext, void *p, size_t size)
{
global_heap_free(p, size HEAPACCT(ACCT_OTHER));
}
static void *
handler_alloc(dcontext_t *dcontext, size_t size)
{
return global_heap_alloc(size HEAPACCT(ACCT_OTHER));
}
/**** top-level routines ***********************************************/
static bool
os_itimers_thread_shared(void)
{
static bool itimers_shared;
static bool cached = false;
if (!cached) {
file_t f = os_open("/proc/version", OS_OPEN_READ);
if (f != INVALID_FILE) {
char buf[128];
int major, minor, rel;
os_read(f, buf, BUFFER_SIZE_ELEMENTS(buf));
NULL_TERMINATE_BUFFER(buf);
if (sscanf(buf, "%*s %*s %d.%d.%d", &major, &minor, &rel) == 3) {
/* Linux NPTL in kernel 2.6.12+ has POSIX-style itimers shared
* among threads.
*/
LOG(GLOBAL, LOG_ASYNCH, 1, "kernel version = %d.%d.%d\n", major, minor,
rel);
itimers_shared = ((major == 2 && minor >= 6 && rel >= 12) ||
(major >= 3 /* linux-3.0 or above */));
cached = true;
}
os_close(f);
}
if (!cached) {
/* assume not shared */
itimers_shared = false;
cached = true;
}
LOG(GLOBAL, LOG_ASYNCH, 1, "itimers are %s\n",
itimers_shared ? "thread-shared" : "thread-private");
}
return itimers_shared;
}
static void
unset_initial_crash_handlers(dcontext_t *dcontext)
{
ASSERT(init_info.app_sigaction != NULL);
signal_info_exit_sigaction(GLOBAL_DCONTEXT, &init_info, false /*!other_thread*/);
/* Undo the unblock-all */
sigprocmask_syscall(SIG_SETMASK, &init_sigmask, NULL, sizeof(init_sigmask));
DOLOG(2, LOG_ASYNCH, {
LOG(THREAD, LOG_ASYNCH, 2, "initial app signal mask:\n");
dump_sigset(dcontext, &init_sigmask);
});
}
void
d_r_signal_init(void)
{
kernel_sigset_t set;
IF_LINUX(IF_X86_64(ASSERT(ALIGNED(offsetof(sigpending_t, xstate), AVX_ALIGNMENT))));
IF_MACOS(ASSERT(sizeof(kernel_sigset_t) == sizeof(__darwin_sigset_t)));
os_itimers_thread_shared();
/* Set up a handler for safe_read (or other fault detection) during
* DR init before thread is initialized.
*
* XXX: could set up a clone_record_t and pass to the initial
* signal_thread_inherit() but that would require further code changes.
* Could also call signal_thread_inherit to init this, but we don't want
* to intercept timer signals, etc. before we're ready to handle them,
* so we do a partial init.
*/
signal_info_init_sigaction(GLOBAL_DCONTEXT, &init_info);
intercept_signal(GLOBAL_DCONTEXT, &init_info, SIGSEGV);
intercept_signal(GLOBAL_DCONTEXT, &init_info, SIGBUS);
kernel_sigemptyset(&set);
kernel_sigaddset(&set, SIGSEGV);
kernel_sigaddset(&set, SIGBUS);
sigprocmask_syscall(SIG_UNBLOCK, &set, &init_sigmask, sizeof(set));
IF_LINUX(signalfd_init());
signal_arch_init();
}
void
d_r_signal_exit()
{
IF_LINUX(signalfd_exit());
if (init_info.app_sigaction != NULL) {
/* We never took over the app (e.g., standalone mode). Restore its state. */
unset_initial_crash_handlers(GLOBAL_DCONTEXT);
}
#ifdef DEBUG
if (d_r_stats->loglevel > 0 && (d_r_stats->logmask & (LOG_ASYNCH | LOG_STATS)) != 0) {
LOG(GLOBAL, LOG_ASYNCH | LOG_STATS, 1, "Total signals delivered: %d\n",
GLOBAL_STAT(num_signals));
}
#endif
}
#ifdef HAVE_SIGALTSTACK
/* Separated out to run from the dstack (i#2016: see below). */
static void
set_our_alt_stack(void *arg)
{
thread_sig_info_t *info = (thread_sig_info_t *)arg;
DEBUG_DECLARE(int rc =)
sigaltstack_syscall(&info->sigstack, &info->app_sigstack);
ASSERT(rc == 0);
}
#endif
void
signal_thread_init(dcontext_t *dcontext, void *os_data)
{
thread_sig_info_t *info =
HEAP_TYPE_ALLOC(dcontext, thread_sig_info_t, ACCT_OTHER, PROTECTED);
size_t pend_unit_size = sizeof(sigpending_t) +
/* include alignment for xsave on xstate */
signal_frame_extra_size(true)
/* sigpending_t has xstate inside it already */
IF_LINUX(IF_X86(-sizeof(kernel_xstate_t)));
IF_X86(ASSERT(YMM_ENABLED() || !ZMM_ENABLED()));
/* pend_unit_size may not be aligned, even for AVX. We request alignment from the
* allocator for all pending units (xref i#3749, i#3380).
*/
/* all fields want to be initialized to 0 */
memset(info, 0, sizeof(thread_sig_info_t));
dcontext->signal_field = (void *)info;
/* our special heap to avoid reentrancy problems
* composed entirely of sigpending_t units
* Note that it's fine to have the special heap do page-at-a-time
* committing, which does not use locks (unless triggers reset!),
* but if we need a new unit that will grab a lock: we try to
* avoid that by limiting the # of pending alarm signals (PR 596768).
*/
info->sigheap = special_heap_init_aligned(
pend_unit_size, IF_X86_ELSE(AVX_ALIGNMENT, 0),
false /* cannot have any locking */, false /* -x */, true /* persistent */,
pend_unit_size * DYNAMO_OPTION(max_pending_signals));
#ifdef HAVE_SIGALTSTACK
/* set up alternate stack
* i#552 we may terminate the process without freeing the stack, so we
* stack_alloc it to exempt from the memory leak check.
*/
info->sigstack.ss_sp = (char *)stack_alloc(SIGSTACK_SIZE, NULL) - SIGSTACK_SIZE;
info->sigstack.ss_size = SIGSTACK_SIZE;
/* kernel will set xsp to sp+size to grow down from there, we don't have to */
info->sigstack.ss_flags = 0;
/* i#2016: for late takeover, this app thread may already be on its own alt
* stack. Not setting SA_ONSTACK for SUSPEND_SIGNAL is not sufficient to avoid
* this, as our SUSPEND_SIGNAL can interrupt the app inside its own signal
* handler. Thus, we simply swap to another stack temporarily to avoid the
* kernel complaining. The dstack is set up but it has the clone record and
* initial mcxt, so we use the new alt stack.
*/
call_switch_stack((void *)info, (byte *)info->sigstack.ss_sp + info->sigstack.ss_size,
set_our_alt_stack, NULL, true /*return*/);
LOG(THREAD, LOG_ASYNCH, 1, "signal stack is " PFX " - " PFX "\n",
info->sigstack.ss_sp, info->sigstack.ss_sp + info->sigstack.ss_size);
/* app_sigstack dealt with below, based on parentage */
#endif
kernel_sigemptyset(&info->app_sigblocked);
ASSIGN_INIT_LOCK_FREE(info->child_lock, child_lock);
/* signal_thread_inherit() finishes per-thread init and is invoked
* by os_thread_init_finalize(): we need it after synch_thread_init() and
* other post-os_thread_init() setup b/c we can't yet record pending signals,
* but we need it before we give up thread_initexit_lock so we can handle
* our own suspend signals (i#2779).
*/
}
bool
is_thread_signal_info_initialized(dcontext_t *dcontext)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
return info->fully_initialized;
}
/* i#27: create custom data to pass to the child of a clone
* since we can't rely on being able to find the caller, or that
* its syscall data is still valid, once in the child.
*
* i#149/ PR 403015: The clone record is passed to the new thread via the dstack
* created for it. Unlike before, where the child thread would create its own
* dstack, now the parent thread creates the dstack. Also, switches app stack
* to dstack.
*
* XXX i#1403: for Mac we want to eventually do lower-level earlier interception
* of threads, but for now we're later and higher-level, intercepting the user
* thread function on the new thread's stack. We ignore app_thread_xsp.
*/
void *
#ifdef MACOS
create_clone_record(dcontext_t *dcontext, reg_t *app_thread_xsp, app_pc thread_func,
void *thread_arg)
#else
create_clone_record(dcontext_t *dcontext, reg_t *app_thread_xsp)
#endif
{
clone_record_t *record;
byte *dstack = stack_alloc(DYNAMORIO_STACK_SIZE, NULL);
LOG(THREAD, LOG_ASYNCH, 1, "create_clone_record: dstack for new thread is " PFX "\n",
dstack);
#ifdef MACOS
if (app_thread_xsp == NULL) {
record = HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, clone_record_t, ACCT_THREAD_MGT,
true /*prot*/);
record->app_thread_xsp = 0;
record->continuation_pc = thread_func;
record->thread_arg = thread_arg;
record->clone_flags = CLONE_THREAD | CLONE_VM | CLONE_SIGHAND | SIGCHLD;
} else {
#endif
/* Note, the stack grows to low memory addr, so dstack points to the high
* end of the allocated stack region. So, we must subtract to get space for
* the clone record.
*/
record = (clone_record_t *)(dstack - sizeof(clone_record_t));
ASSERT(ALIGNED(record, get_ABI_stack_alignment()));
record->app_thread_xsp = *app_thread_xsp;
/* asynch_target is set in d_r_dispatch() prior to calling pre_system_call(). */
record->continuation_pc = dcontext->asynch_target;
record->clone_flags = dcontext->sys_param0;
#ifdef MACOS
}
#endif
LOG(THREAD, LOG_ASYNCH, 1, "allocated clone record: " PFX "\n", record);
record->dstack = dstack;
record->caller_id = dcontext->owning_thread;
record->clone_sysnum = dcontext->sys_num;
record->info = *((thread_sig_info_t *)dcontext->signal_field);
/* Sigstack is not inherited so clear it now to avoid having to figure out
* where it got its value in signal_thread_inherit (i#3116).
*/
memset(&record->info.app_sigstack, 0, sizeof(record->info.app_sigstack));
record->info.app_sigstack.ss_flags = SS_DISABLE;
record->parent_info = (thread_sig_info_t *)dcontext->signal_field;
record->pcprofile_info = dcontext->pcprofile_field;
#ifdef AARCHXX
record->app_stolen_value = get_stolen_reg_val(get_mcontext(dcontext));
# ifndef AARCH64
record->isa_mode = dr_get_isa_mode(dcontext);
# endif
/* If the child thread shares the same TLS with parent by not setting
* CLONE_SETTLS or vfork, we put the TLS base here and clear the
* thread register in new_thread_setup, so that DR can distinguish
* this case from normal pthread thread creation.
*/
record->app_lib_tls_base = (!TEST(CLONE_SETTLS, record->clone_flags))
? os_get_app_tls_base(dcontext, TLS_REG_LIB)
: NULL;
#endif
LOG(THREAD, LOG_ASYNCH, 1, "create_clone_record: thread " TIDFMT ", pc " PFX "\n",
record->caller_id, record->continuation_pc);
#ifdef MACOS
if (app_thread_xsp != NULL) {
#endif
/* Set the thread stack to point to the dstack, below the clone record.
* Note: it's glibc who sets up the arg to the thread start function;
* the kernel just does a fork + stack swap, so we can get away w/ our
* own stack swap if we restore before the glibc asm code takes over.
* We restore this parameter to the app value in
* restore_clone_param_from_clone_record().
*/
/* i#754: set stack to be XSTATE aligned for saving YMM registers */
ASSERT(ALIGNED(XSTATE_ALIGNMENT, REGPARM_END_ALIGN));
*app_thread_xsp = ALIGN_BACKWARD(record, XSTATE_ALIGNMENT);
#ifdef MACOS
}
#endif
return (void *)record;
}
/* This is to support dr_create_client_thread() */
void
set_clone_record_fields(void *record, reg_t app_thread_xsp, app_pc continuation_pc,
uint clone_sysnum, uint clone_flags)
{
clone_record_t *rec = (clone_record_t *)record;
ASSERT(rec != NULL);
rec->app_thread_xsp = app_thread_xsp;
rec->continuation_pc = continuation_pc;
rec->clone_sysnum = clone_sysnum;
rec->clone_flags = clone_flags;
}
/* i#149/PR 403015: The clone record is passed to the new thread by placing it
* at the bottom of the dstack, i.e., the high memory. So the new thread gets
* it from the base of the dstack. The dstack is then set as the app stack.
*
* CAUTION: don't use a lot of stack in this routine as it gets invoked on the
* dstack from new_thread_setup - this is because this routine assumes
* no more than a page of dstack has been used so far since the clone
* system call was done.
*/
void *
get_clone_record(reg_t xsp)
{
clone_record_t *record;
byte *dstack_base;
/* xsp should be in a dstack, i.e., dynamorio heap. */
ASSERT(is_dynamo_address((app_pc)xsp));
/* The (size of the clone record +
* stack used by new_thread_start (only for setting up priv_mcontext_t) +
* stack used by new_thread_setup before calling get_clone_record())
* is less than a page. This is verified by the assert below. If it does
* exceed a page, it won't happen at random during runtime, but in a
* predictable way during development, which will be caught by the assert.
* The current usage is about 800 bytes for clone_record +
* sizeof(priv_mcontext_t) + few words in new_thread_setup before
* get_clone_record() is called.
*/
dstack_base = (byte *)ALIGN_FORWARD(xsp, PAGE_SIZE);
record = (clone_record_t *)(dstack_base - sizeof(clone_record_t));
/* dstack_base and the dstack in the clone record should be the same. */
ASSERT(dstack_base == record->dstack);
#ifdef MACOS
ASSERT(record->app_thread_xsp != 0); /* else it's not in dstack */
#endif
return (void *)record;
}
/* i#149/PR 403015: App xsp is passed to the new thread via the clone record. */
reg_t
get_clone_record_app_xsp(void *record)
{
ASSERT(record != NULL);
return ((clone_record_t *)record)->app_thread_xsp;
}
#ifdef MACOS
void *
get_clone_record_thread_arg(void *record)
{
ASSERT(record != NULL);
return ((clone_record_t *)record)->thread_arg;
}
#endif
byte *
get_clone_record_dstack(void *record)
{
ASSERT(record != NULL);
return ((clone_record_t *)record)->dstack;
}
#ifdef AARCHXX
reg_t
get_clone_record_stolen_value(void *record)
{
ASSERT(record != NULL);
return ((clone_record_t *)record)->app_stolen_value;
}
# ifndef AARCH64
uint /* dr_isa_mode_t but we have a header ordering problem */
get_clone_record_isa_mode(void *record)
{
ASSERT(record != NULL);
return ((clone_record_t *)record)->isa_mode;
}
# endif
void
set_thread_register_from_clone_record(void *record)
{
/* If record->app_lib_tls_base is not NULL, it means the parent
* thread did not setup TLS for the child, and we need clear the
* thread register.
*/
if (((clone_record_t *)record)->app_lib_tls_base != NULL)
write_thread_register(NULL);
}
void
set_app_lib_tls_base_from_clone_record(dcontext_t *dcontext, void *record)
{
if (((clone_record_t *)record)->app_lib_tls_base != NULL) {
/* child and parent share the same TLS */
os_set_app_tls_base(dcontext, TLS_REG_LIB,
((clone_record_t *)record)->app_lib_tls_base);
}
}
#endif
void
restore_clone_param_from_clone_record(dcontext_t *dcontext, void *record)
{
#ifdef LINUX
ASSERT(record != NULL);
clone_record_t *crec = (clone_record_t *)record;
if (crec->clone_sysnum == SYS_clone && TEST(CLONE_VM, crec->clone_flags)) {
/* Restore the original stack parameter to the syscall, which we clobbered
* in create_clone_record(). Some apps examine it post-syscall (i#3171).
*/
set_syscall_param(dcontext, SYSCALL_PARAM_CLONE_STACK,
get_mcontext(dcontext)->xsp);
}
#endif
}
/* Initializes info's app_sigaction, restorer_valid, and we_intercept fields */
static void
signal_info_init_sigaction(dcontext_t *dcontext, thread_sig_info_t *info)
{
info->app_sigaction = (kernel_sigaction_t **)handler_alloc(
dcontext, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *));
memset(info->app_sigaction, 0, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *));
memset(&info->restorer_valid, -1, SIGARRAY_SIZE * sizeof(info->restorer_valid[0]));
info->we_intercept = (bool *)handler_alloc(dcontext, SIGARRAY_SIZE * sizeof(bool));
memset(info->we_intercept, 0, SIGARRAY_SIZE * sizeof(bool));
}
/* Cleans up info's app_sigaction and we_intercept entries */
static void
signal_info_exit_sigaction(dcontext_t *dcontext, thread_sig_info_t *info,
bool other_thread)
{
int i;
kernel_sigaction_t act;
memset(&act, 0, sizeof(act));
act.handler = (handler_t)SIG_DFL;
kernel_sigemptyset(&act.mask); /* does mask matter for SIG_DFL? */
for (i = 1; i <= MAX_SIGNUM; i++) {
if (sig_is_alarm_signal(i) && doing_detach &&
IF_CLIENT_INTERFACE(!standalone_library &&)
alarm_signal_has_DR_only_itimer(dcontext, i)) {
/* We ignore alarms *during* detach in signal_remove_alarm_handlers(),
* but to avoid crashing on an alarm arriving post-detach we set to
* SIG_IGN if we have an itimer and the app does not (a slight
* transparency violation to gain robustness: i#2270).
*/
set_ignore_signal_action(i);
} else if (!other_thread) {
if (info->app_sigaction[i] != NULL) {
/* Restore to old handler, but not if exiting whole process:
* else may get itimer during cleanup, so we set to SIG_IGN. We
* do this during detach in signal_remove_alarm_handlers() (and
* post-detach above).
*/
if (dynamo_exited && !doing_detach) {
info->app_sigaction[i]->handler = (handler_t)SIG_IGN;
}
LOG(THREAD, LOG_ASYNCH, 2, "\trestoring " PFX " as handler for %d\n",
info->app_sigaction[i]->handler, i);
sigaction_syscall(i, info->app_sigaction[i], NULL);
} else if (info->we_intercept[i]) {
/* restore to default */
LOG(THREAD, LOG_ASYNCH, 2, "\trestoring SIG_DFL as handler for %d\n", i);
sigaction_syscall(i, &act, NULL);
}
}
if (info->app_sigaction[i] != NULL) {
handler_free(dcontext, info->app_sigaction[i], sizeof(kernel_sigaction_t));
}
}
handler_free(dcontext, info->app_sigaction,
SIGARRAY_SIZE * sizeof(kernel_sigaction_t *));
info->app_sigaction = NULL;
handler_free(dcontext, info->we_intercept, SIGARRAY_SIZE * sizeof(bool));
info->we_intercept = NULL;
}
/* Called to finalize per-thread initialization.
* Inherited and shared fields are set up here.
* The clone_record contains the continuation pc, which is stored in dcontext->next_tag.
*/
void
signal_thread_inherit(dcontext_t *dcontext, void *clone_record)
{
clone_record_t *record = (clone_record_t *)clone_record;
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int i;
if (record != NULL) {
LOG(THREAD, LOG_ASYNCH, 1, "continuation pc is " PFX "\n",
record->continuation_pc);
dcontext->next_tag = record->continuation_pc;
LOG(THREAD, LOG_ASYNCH, 1,
"parent tid is " TIDFMT ", parent sysnum is %d(%s), clone flags=" PIFX "\n",
record->caller_id, record->clone_sysnum,
#ifdef SYS_vfork
(record->clone_sysnum == SYS_vfork)
? "vfork"
:
#endif
(IF_LINUX(record->clone_sysnum == SYS_clone ? "clone" :) IF_MACOS(
record->clone_sysnum == SYS_bsdthread_create ? "bsdthread_create"
:) "unexpected"),
record->clone_flags);
#ifdef SYS_vfork
if (record->clone_sysnum == SYS_vfork) {
/* The above clone_flags argument is bogus.
SYS_vfork doesn't have a free register to keep the hardcoded value
see /usr/src/linux/arch/i386/kernel/process.c */
/* CHECK: is this the only place real clone flags are needed? */
record->clone_flags = CLONE_VFORK | CLONE_VM | SIGCHLD;
}
#endif
/* handlers are either inherited or shared */
if (TEST(CLONE_SIGHAND, record->clone_flags)) {
/* need to share table of handlers! */
LOG(THREAD, LOG_ASYNCH, 2, "sharing signal handlers with parent\n");
info->shared_app_sigaction = true;
info->shared_refcount = record->info.shared_refcount;
info->shared_lock = record->info.shared_lock;
info->app_sigaction = record->info.app_sigaction;
info->we_intercept = record->info.we_intercept;
d_r_mutex_lock(info->shared_lock);
(*info->shared_refcount)++;
#ifdef DEBUG
for (i = 1; i <= MAX_SIGNUM; i++) {
if (info->app_sigaction[i] != NULL) {
LOG(THREAD, LOG_ASYNCH, 2, "\thandler for signal %d is " PFX "\n", i,
info->app_sigaction[i]->handler);
}
}
#endif
d_r_mutex_unlock(info->shared_lock);
} else {
/* copy handlers */
LOG(THREAD, LOG_ASYNCH, 2, "inheriting signal handlers from parent\n");
info->app_sigaction = (kernel_sigaction_t **)handler_alloc(
dcontext, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *));
memset(info->app_sigaction, 0, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *));
for (i = 1; i <= MAX_SIGNUM; i++) {
info->restorer_valid[i] = -1; /* clear cache */
if (record->info.app_sigaction[i] != NULL) {
info->app_sigaction[i] = (kernel_sigaction_t *)handler_alloc(
dcontext, sizeof(kernel_sigaction_t));
memcpy(info->app_sigaction[i], record->info.app_sigaction[i],
sizeof(kernel_sigaction_t));
LOG(THREAD, LOG_ASYNCH, 2, "\thandler for signal %d is " PFX "\n", i,
info->app_sigaction[i]->handler);
}
}
info->we_intercept =
(bool *)handler_alloc(dcontext, SIGARRAY_SIZE * sizeof(bool));
memcpy(info->we_intercept, record->info.we_intercept,
SIGARRAY_SIZE * sizeof(bool));
d_r_mutex_lock(&record->info.child_lock);
record->info.num_unstarted_children--;
d_r_mutex_unlock(&record->info.child_lock);
/* this should be safe since parent should wait for us */
d_r_mutex_lock(&record->parent_info->child_lock);
record->parent_info->num_unstarted_children--;
d_r_mutex_unlock(&record->parent_info->child_lock);
}
/* itimers are either private or shared */
if (TEST(CLONE_THREAD, record->clone_flags) && os_itimers_thread_shared()) {
ASSERT(record->info.shared_itimer);
LOG(THREAD, LOG_ASYNCH, 2, "sharing itimers with parent\n");
info->shared_itimer = true;
info->shared_itimer_refcount = record->info.shared_itimer_refcount;
info->shared_itimer_underDR = record->info.shared_itimer_underDR;
info->itimer = record->info.itimer;
atomic_add_exchange_int((volatile int *)info->shared_itimer_refcount, 1);
/* shared_itimer_underDR will be incremented in start_itimer() */
} else {
info->shared_itimer = false;
init_itimer(dcontext, false /*!first thread*/);
}
/* rest of state is never shared.
* app_sigstack should already be in place, when we set up our sigstack
* we asked for old sigstack.
* FIXME: are current pending or blocked inherited?
*/
#ifdef MACOS
if (record->app_thread_xsp != 0) {
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, record, clone_record_t, ACCT_THREAD_MGT,
true /*prot*/);
}
#endif
} else {
/* Initialize in isolation */
if (APP_HAS_SIGSTACK(info)) {
/* parent was NOT under our control, so the real sigstack we see is
* a real sigstack that was present before we took control
*/
LOG(THREAD, LOG_ASYNCH, 1, "app already has signal stack " PFX " - " PFX "\n",
info->app_sigstack.ss_sp,
info->app_sigstack.ss_sp + info->app_sigstack.ss_size);
}
signal_info_init_sigaction(dcontext, info);
info->shared_itimer = false; /* we'll set to true if a child is created */
init_itimer(dcontext, true /*first*/);
/* We split init vs start for the signal handlers and mask. We do not
* install ours until we start running the app, to avoid races like
* i#2335. We'll set them up when os_process_under_dynamorio_*() invokes
* signal_reinstate_handlers(). All we do now is mark which signals we
* want to intercept.
*/
if (DYNAMO_OPTION(intercept_all_signals)) {
/* PR 304708: to support client signal handlers without
* the complexity of per-thread and per-signal callbacks
* we always intercept all signals. We also check here
* for handlers the app registered before our init.
*/
for (i = 1; i <= MAX_SIGNUM; i++) {
/* cannot intercept KILL or STOP */
if (signal_is_interceptable(i) &&
/* FIXME PR 297033: we don't support intercepting DEFAULT_STOP /
* DEFAULT_CONTINUE signals. Once add support, update
* dr_register_signal_event() comments.
*/
default_action[i] != DEFAULT_STOP &&
default_action[i] != DEFAULT_CONTINUE)
info->we_intercept[i] = true;
}
} else {
/* we intercept the following signals ourselves: */
info->we_intercept[SIGSEGV] = true;
/* PR 313665: look for DR crashes on unaligned memory or mmap bounds */
info->we_intercept[SIGBUS] = true;
/* PR 212090: the signal we use to suspend threads */
info->we_intercept[SUSPEND_SIGNAL] = true;
#ifdef PAPI
/* use SIGPROF for updating gui so it can be distinguished from SIGVTALRM */
info->we_intercept[SIGPROF] = true;
#endif
/* vtalarm only used with pc profiling. it interferes w/ PAPI
* so arm this signal only if necessary
*/
if (INTERNAL_OPTION(profile_pcs)) {
info->we_intercept[SIGVTALRM] = true;
}
#ifdef CLIENT_INTERFACE
info->we_intercept[SIGALRM] = true;
#endif
#ifdef SIDELINE
info->we_intercept[SIGCHLD] = true;
#endif
/* i#61/PR 211530: the signal we use for nudges */
info->we_intercept[NUDGESIG_SIGNUM] = true;
}
/* should be 1st thread */
if (d_r_get_num_threads() > 1)
ASSERT_NOT_REACHED();
}
/* only when SIGVTALRM handler is in place should we start itimer (PR 537743) */
if (INTERNAL_OPTION(profile_pcs)) {
/* even if the parent thread exits, we can use a pointer to its
* pcprofile_info b/c when shared it's process-shared and is not freed
* until the entire process exits
*/
pcprofile_thread_init(dcontext, info->shared_itimer,
(record == NULL) ? NULL : record->pcprofile_info);
}
info->pre_syscall_app_sigprocmask_valid = false;
/* Assumed to be async safe. */
info->fully_initialized = true;
}
/* When taking over existing app threads, we assume they're using pthreads and
* expect to share signal handlers, memory, thread group id, etc.
* Invokes dynamo_thread_init() with the appropriate os_data.
*/
dcontext_t *
init_thread_with_shared_siginfo(priv_mcontext_t *mc, dcontext_t *takeover_dc)
{
clone_record_t crec = {
0,
};
thread_sig_info_t *parent_siginfo = (thread_sig_info_t *)takeover_dc->signal_field;
/* Create a fake clone record with the given siginfo. All threads in the
* same thread group must share signal handlers since Linux 2.5.35, but we
* have to guess at the other flags.
* FIXME i#764: If we take over non-pthreads threads, we'll need some way to
* tell if they're sharing signal handlers or not.
*/
crec.caller_id = takeover_dc->owning_thread;
#ifdef LINUX
crec.clone_sysnum = SYS_clone;
#else
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#58: NYI on Mac */
#endif
crec.clone_flags = PTHREAD_CLONE_FLAGS;
crec.parent_info = parent_siginfo;
crec.info = *parent_siginfo;
crec.pcprofile_info = takeover_dc->pcprofile_field;
IF_DEBUG(int r =)
dynamo_thread_init(NULL, mc, &crec _IF_CLIENT_INTERFACE(false));
ASSERT(r == SUCCESS);
return get_thread_private_dcontext();
}
static void
free_pending_signal(thread_sig_info_t *info, int sig)
{
sigpending_t *temp = info->sigpending[sig];
info->sigpending[sig] = temp->next;
special_heap_free(info->sigheap, temp);
info->num_pending--;
}
/* This is split from os_fork_init() so the new logfiles are available
* (xref i#189/PR 452168). It had to be after dynamo_other_thread_exit()
* called in dynamorio_fork_init() after os_fork_init() else we clean
* up data structs used in signal_thread_exit().
*/
void
signal_fork_init(dcontext_t *dcontext)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int i;
/* Child of fork is a single thread in a new process so should
* start over w/ no sharing (xref i#190/PR 452178)
*/
if (info->shared_app_sigaction) {
info->shared_app_sigaction = false;
if (info->shared_lock != NULL) {
DELETE_LOCK(*info->shared_lock);
global_heap_free(info->shared_lock, sizeof(mutex_t) HEAPACCT(ACCT_OTHER));
}
if (info->shared_refcount != NULL)
global_heap_free(info->shared_refcount, sizeof(int) HEAPACCT(ACCT_OTHER));
info->shared_lock = NULL;
info->shared_refcount = NULL;
}
if (info->shared_itimer) {
/* itimers are not inherited across fork */
info->shared_itimer = false;
for (i = 0; i < NUM_ITIMERS; i++)
DELETE_RECURSIVE_LOCK((*info->itimer)[i].lock);
if (os_itimers_thread_shared())
global_heap_free(info->itimer, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER));
else
heap_free(dcontext, info->itimer, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER));
info->itimer = NULL; /* reset by init_itimer */
ASSERT(info->shared_itimer_refcount != NULL);
global_heap_free(info->shared_itimer_refcount, sizeof(int) HEAPACCT(ACCT_OTHER));
info->shared_itimer_refcount = NULL;
ASSERT(info->shared_itimer_underDR != NULL);
global_heap_free(info->shared_itimer_underDR, sizeof(int) HEAPACCT(ACCT_OTHER));
info->shared_itimer_underDR = NULL;
init_itimer(dcontext, true /*first*/);
}
info->num_unstarted_children = 0;
for (i = 1; i <= MAX_SIGNUM; i++) {
/* "A child created via fork(2) initially has an empty pending signal set" */
dcontext->signals_pending = 0;
while (info->sigpending[i] != NULL) {
free_pending_signal(info, i);
}
info->num_pending = 0;
}
if (INTERNAL_OPTION(profile_pcs)) {
pcprofile_fork_init(dcontext);
}
info->pre_syscall_app_sigprocmask_valid = false;
/* Assumed to be async safe. */
info->fully_initialized = true;
}
#ifdef DEBUG
static bool
sigsegv_handler_is_ours(void)
{
int rc;
kernel_sigaction_t oldact;
rc = sigaction_syscall(SIGSEGV, NULL, &oldact);
return (rc == 0 && oldact.handler == (handler_t)master_signal_handler);
}
#endif /* DEBUG */
#if defined(X86) && defined(LINUX)
static byte *
get_and_initialize_xstate_buffer(dcontext_t *dcontext)
{
/* See thread_sig_info_t.xstate_buf comments for why this is in TLS. */
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
if (info->xstate_buf == NULL) {
info->xstate_alloc =
heap_alloc(dcontext, signal_frame_extra_size(true) HEAPACCT(ACCT_OTHER));
info->xstate_buf = (byte *)ALIGN_FORWARD(info->xstate_alloc, XSTATE_ALIGNMENT);
ASSERT(info->xstate_alloc + signal_frame_extra_size(true) >=
info->xstate_buf + signal_frame_extra_size(false));
}
kernel_fpstate_t *fpstate = (kernel_fpstate_t *)info->xstate_buf;
/* If we pass uninitialized values for kernel_xsave_hdr_t.reserved1 through
* sigreturn, we'll get a SIGSEGV. Best to zero it all out.
*/
memset(fpstate, 0, signal_frame_extra_size(false));
fpstate->sw_reserved.extended_size = signal_frame_extra_size(false);
if (YMM_ENABLED()) { /* ZMM_ENABLED() always implies YMM_ENABLED() too. */
fpstate->sw_reserved.magic1 = FP_XSTATE_MAGIC1;
fpstate->sw_reserved.xstate_size = signal_frame_extra_size(false) -
FP_XSTATE_MAGIC2_SIZE IF_X86_32(-FSAVE_FPSTATE_PREFIX_SIZE);
uint bv_high, bv_low;
dr_xgetbv(&bv_high, &bv_low);
fpstate->sw_reserved.xstate_bv = (((uint64)bv_high) << 32) | bv_low;
*(int *)((byte *)fpstate + fpstate->sw_reserved.extended_size -
FP_XSTATE_MAGIC2_SIZE) = FP_XSTATE_MAGIC2;
} else {
fpstate->sw_reserved.magic1 = 0;
fpstate->sw_reserved.xstate_size = sizeof(kernel_fpstate_t);
fpstate->sw_reserved.xstate_bv = 0;
}
return info->xstate_buf;
}
#endif
void
signal_thread_exit(dcontext_t *dcontext, bool other_thread)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int i;
/* i#1012: DR's signal handler should always be installed before this point.
*/
ASSERT(sigsegv_handler_is_ours() || removed_sig_handler);
while (info->num_unstarted_children > 0) {
/* must wait for children to start and copy our state
* before we destroy it!
*/
os_thread_yield();
}
/* stop_itimer() was already called by os_thread_not_under_dynamo() called
* from dynamo_thread_exit_common(). We need to leave the app itimers in place
* in case we're detaching.
*/
#if defined(X86) && defined(LINUX)
if (info->xstate_alloc != NULL) {
heap_free(dcontext, info->xstate_alloc,
signal_frame_extra_size(true) HEAPACCT(ACCT_OTHER));
}
#endif
/* FIXME: w/ shared handlers, if parent (the owner here) dies,
* can children keep living w/ a copy of the handlers?
*/
if (info->shared_app_sigaction) {
d_r_mutex_lock(info->shared_lock);
(*info->shared_refcount)--;
d_r_mutex_unlock(info->shared_lock);
}
if (!info->shared_app_sigaction || *info->shared_refcount == 0) {
LOG(THREAD, LOG_ASYNCH, 2, "signal handler cleanup:\n");
signal_info_exit_sigaction(dcontext, info, other_thread);
if (info->shared_lock != NULL) {
DELETE_LOCK(*info->shared_lock);
global_heap_free(info->shared_lock, sizeof(mutex_t) HEAPACCT(ACCT_OTHER));
}
if (info->shared_refcount != NULL)
global_heap_free(info->shared_refcount, sizeof(int) HEAPACCT(ACCT_OTHER));
}
if (info->shared_itimer) {
atomic_add_exchange_int((volatile int *)info->shared_itimer_refcount, -1);
}
if (!info->shared_itimer || *info->shared_itimer_refcount == 0) {
if (INTERNAL_OPTION(profile_pcs)) {
/* no cleanup needed for non-final thread in group */
pcprofile_thread_exit(dcontext);
}
for (i = 0; i < NUM_ITIMERS; i++)
DELETE_RECURSIVE_LOCK((*info->itimer)[i].lock);
if (os_itimers_thread_shared())
global_heap_free(info->itimer, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER));
else
heap_free(dcontext, info->itimer, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER));
if (info->shared_itimer_refcount != NULL) {
global_heap_free(info->shared_itimer_refcount,
sizeof(int) HEAPACCT(ACCT_OTHER));
ASSERT(info->shared_itimer_underDR != NULL);
global_heap_free(info->shared_itimer_underDR,
sizeof(int) HEAPACCT(ACCT_OTHER));
}
}
for (i = 1; i <= MAX_SIGNUM; i++) {
/* pending queue is per-thread and not shared */
while (info->sigpending[i] != NULL) {
sigpending_t *temp = info->sigpending[i];
info->sigpending[i] = temp->next;
special_heap_free(info->sigheap, temp);
}
info->num_pending = 0;
}
/* If no detach flag is set, we assume that this thread is on its way to exit.
* In order to prevent receiving signals while a thread is on its way to exit
* without a valid dcontext, signals at this stage are blocked. The exceptions
* are the suspend signal and any signal that a terminating SYS_kill may need.
* (i#2921). In this case, we do not want to restore the signal mask. For detach,
* we do need to restore the app's mask.
*/
if (!other_thread && doing_detach)
signal_swap_mask(dcontext, true /*to_app*/);
#ifdef HAVE_SIGALTSTACK
/* Remove our sigstack and restore the app sigstack if it had one. */
if (!other_thread) {
LOG(THREAD, LOG_ASYNCH, 2, "removing our signal stack " PFX " - " PFX "\n",
info->sigstack.ss_sp, info->sigstack.ss_sp + info->sigstack.ss_size);
if (APP_HAS_SIGSTACK(info)) {
LOG(THREAD, LOG_ASYNCH, 2, "restoring app signal stack " PFX " - " PFX "\n",
info->app_sigstack.ss_sp,
info->app_sigstack.ss_sp + info->app_sigstack.ss_size);
} else {
ASSERT(TEST(SS_DISABLE, info->app_sigstack.ss_flags));
}
if (info->sigstack.ss_sp != NULL) {
/* i#552: to raise client exit event, we may call dynamo_process_exit
* on sigstack in signal handler.
* In that case we set sigstack (ss_sp) NULL to avoid stack swap.
*/
# ifdef MACOS
if (info->app_sigstack.ss_sp == NULL) {
/* Kernel fails w/ ENOMEM (even for SS_DISABLE) if ss_size is too small */
info->sigstack.ss_flags = SS_DISABLE;
i = sigaltstack_syscall(&info->sigstack, NULL);
/* i#1814: kernel gives EINVAL if last handler didn't call sigreturn! */
ASSERT(i == 0 || i == -EINVAL);
} else {
i = sigaltstack_syscall(&info->app_sigstack, NULL);
/* i#1814: kernel gives EINVAL if last handler didn't call sigreturn! */
ASSERT(i == 0 || i == -EINVAL);
}
# else
i = sigaltstack_syscall(&info->app_sigstack, NULL);
ASSERT(i == 0);
# endif
}
}
#endif
IF_LINUX(signalfd_thread_exit(dcontext, info));
special_heap_exit(info->sigheap);
DELETE_LOCK(info->child_lock);
#ifdef DEBUG
/* for non-debug we do fast exit path and don't free local heap */
# ifdef HAVE_SIGALTSTACK
if (info->sigstack.ss_sp != NULL) {
/* i#552: to raise client exit event, we may call dynamo_process_exit
* on sigstack in signal handler.
* In that case we set sigstack (ss_sp) NULL to avoid stack free.
*/
stack_free(info->sigstack.ss_sp + info->sigstack.ss_size, info->sigstack.ss_size);
}
# endif
HEAP_TYPE_FREE(dcontext, info, thread_sig_info_t, ACCT_OTHER, PROTECTED);
#endif
#ifdef PAPI
/* use SIGPROF for updating gui so it can be distinguished from SIGVTALRM */
set_itimer_callback(
dcontext, ITIMER_PROF, 500,
(void (*func)(dcontext_t *, priv_mcontext_t *))perfctr_update_gui());
#endif
}
void
set_handler_sigact(kernel_sigaction_t *act, int sig, handler_t handler)
{
act->handler = handler;
#ifdef MACOS
/* This is the real target */
act->tramp = (tramp_t)handler;
#endif
act->flags = SA_SIGINFO; /* send 3 args to handler */
#ifdef HAVE_SIGALTSTACK
act->flags |= SA_ONSTACK; /* use our sigstack */
#endif
/* We want the kernel to help us auto-restart syscalls, esp. when our signals
* interrupt native code such as during attach or in client or DR code (i#2659).
*/
act->flags |= SA_RESTART;
#if !defined(VMX86_SERVER) && defined(LINUX)
/* PR 305020: must have SA_RESTORER for x64 */
/* i#2812: must have SA_RESTORER to handle vsyscall32 being disabled */
act->flags |= SA_RESTORER;
act->restorer = (void (*)(void))dynamorio_sigreturn;
#endif
/* We block most signals within our handler */
kernel_sigfillset(&act->mask);
/* i#184/PR 450670: we let our suspend signal interrupt our own handler
* We never send more than one before resuming, so no danger to stack usage
* from our own: but app could pile them up.
*/
kernel_sigdelset(&act->mask, SUSPEND_SIGNAL);
/* i#193/PR 287309: we need to NOT suppress further SIGSEGV, for decode faults,
* for try/except, and for !HAVE_MEMINFO probes.
* Just like SUSPEND_SIGNAL, if app sends repeated SEGV, could run out of
* alt stack: seems too corner-case to be worth increasing stack size.
*/
kernel_sigdelset(&act->mask, SIGSEGV);
if (sig == SUSPEND_SIGNAL || sig == SIGSEGV)
act->flags |= SA_NODEFER;
/* Sigset is a 1 or 2 elt array of longs on X64/X86. Treat as 2 elt of
* uint32. */
IF_DEBUG(uint32 *mask_sig = (uint32 *)&act->mask.sig[0]);
LOG(THREAD_GET, LOG_ASYNCH, 3, "mask for our handler is " PFX " " PFX "\n",
mask_sig[0], mask_sig[1]);
}
static void
set_our_handler_sigact(kernel_sigaction_t *act, int sig)
{
set_handler_sigact(act, sig, (handler_t)master_signal_handler);
}
static void
set_handler_and_record_app(dcontext_t *dcontext, thread_sig_info_t *info, int sig,
kernel_sigaction_t *act)
{
int rc;
kernel_sigaction_t oldact;
ASSERT(sig <= MAX_SIGNUM);
/* arm the signal */
rc = sigaction_syscall(sig, act, &oldact);
ASSERT(rc ==
0
/* Workaround for PR 223720, which was fixed in ESX4.0 but
* is present in ESX3.5 and earlier: vmkernel treats
* 63 and 64 as invalid signal numbers.
*/
IF_VMX86(|| (sig >= 63 && rc == -EINVAL)));
if (rc != 0) /* be defensive: app will probably still work */
return;
if (oldact.handler != (handler_t)SIG_DFL &&
oldact.handler != (handler_t)master_signal_handler) {
/* save the app's action for sig */
if (info->shared_app_sigaction) {
/* app_sigaction structure is shared */
d_r_mutex_lock(info->shared_lock);
}
if (info->app_sigaction[sig] != NULL) {
/* go ahead and toss the old one, it's up to the app to store
* and then restore later if it wants to
*/
handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t));
}
info->app_sigaction[sig] =
(kernel_sigaction_t *)handler_alloc(dcontext, sizeof(kernel_sigaction_t));
memcpy(info->app_sigaction[sig], &oldact, sizeof(kernel_sigaction_t));
/* clear cache */
info->restorer_valid[sig] = -1;
if (info->shared_app_sigaction)
d_r_mutex_unlock(info->shared_lock);
#ifdef DEBUG
if (oldact.handler == (handler_t)SIG_IGN) {
LOG(THREAD, LOG_ASYNCH, 2,
"app already installed SIG_IGN as sigaction for signal %d\n", sig);
} else {
LOG(THREAD, LOG_ASYNCH, 2,
"app already installed " PFX " as sigaction flags=0x%x for signal %d\n",
oldact.handler, oldact.flags, sig);
}
#endif
} else {
LOG(THREAD, LOG_ASYNCH, 2,
"prior handler is " PFX " vs master " PFX " with flags=0x%x for signal %d\n",
oldact.handler, master_signal_handler, oldact.flags, sig);
if (info->app_sigaction[sig] != NULL) {
if (info->shared_app_sigaction)
d_r_mutex_lock(info->shared_lock);
handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t));
info->app_sigaction[sig] = NULL;
if (info->shared_app_sigaction)
d_r_mutex_unlock(info->shared_lock);
}
}
LOG(THREAD, LOG_ASYNCH, 3, "\twe intercept signal %d\n", sig);
}
/* Set up master_signal_handler as the handler for signal "sig",
* for the current thread. Since we deal with kernel data structures
* in our interception of system calls, we use them here as well,
* to avoid having to translate to/from libc data structures.
*/
static void
intercept_signal(dcontext_t *dcontext, thread_sig_info_t *info, int sig)
{
kernel_sigaction_t act;
ASSERT(sig <= MAX_SIGNUM);
set_our_handler_sigact(&act, sig);
set_handler_and_record_app(dcontext, info, sig, &act);
}
static void
intercept_signal_ignore_initially(dcontext_t *dcontext, thread_sig_info_t *info, int sig)
{
kernel_sigaction_t act;
ASSERT(sig <= MAX_SIGNUM);
memset(&act, 0, sizeof(act));
act.handler = (handler_t)SIG_IGN;
set_handler_and_record_app(dcontext, info, sig, &act);
}
static void
intercept_signal_no_longer_ignore(dcontext_t *dcontext, thread_sig_info_t *info, int sig)
{
kernel_sigaction_t act;
int rc;
ASSERT(sig <= MAX_SIGNUM);
set_our_handler_sigact(&act, sig);
rc = sigaction_syscall(sig, &act, NULL);
ASSERT(rc == 0);
}
/* i#1921: For proper single-threaded native execution with re-takeover we need
* to propagate signals. For now we only support going completely native in
* this thread but without a full detach, so we abandon our signal handlers w/o
* freeing memory up front.
* We also use this for the start/stop interface where we are going fully native
* for all threads.
*/
void
signal_remove_handlers(dcontext_t *dcontext)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int i;
kernel_sigaction_t act;
memset(&act, 0, sizeof(act));
act.handler = (handler_t)SIG_DFL;
kernel_sigemptyset(&act.mask);
for (i = 1; i <= MAX_SIGNUM; i++) {
if (info->app_sigaction[i] != NULL) {
LOG(THREAD, LOG_ASYNCH, 2, "\trestoring " PFX " as handler for %d\n",
info->app_sigaction[i]->handler, i);
sigaction_syscall(i, info->app_sigaction[i], NULL);
} else if (info->we_intercept[i]) {
/* restore to default */
LOG(THREAD, LOG_ASYNCH, 2, "\trestoring SIG_DFL as handler for %d\n", i);
sigaction_syscall(i, &act, NULL);
}
}
DODEBUG({ removed_sig_handler = true; });
}
void
signal_remove_alarm_handlers(dcontext_t *dcontext)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int i;
for (i = 1; i <= MAX_SIGNUM; i++) {
if (!info->we_intercept[i])
continue;
if (sig_is_alarm_signal(i)) {
set_ignore_signal_action(i);
}
}
}
/* For attaching mid-run, we assume regular POSIX with handlers global to just one
* thread group in the process.
* We also use this routine for the initial setup of our handlers, which we
* split from signal_thread_inherit() to support start/stop.
*/
void
signal_reinstate_handlers(dcontext_t *dcontext, bool ignore_alarm)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int i;
for (i = 1; i <= MAX_SIGNUM; i++) {
bool skip = false;
if (!info->we_intercept[i]) {
skip = true;
if (signal_is_interceptable(i)) {
/* We do have to intercept everything the app does.
* If the app removes its handler, we'll never remove ours, which we
* can live with.
*/
kernel_sigaction_t oldact;
int rc = sigaction_syscall(i, NULL, &oldact);
ASSERT(rc == 0);
if (rc == 0 && oldact.handler != (handler_t)SIG_DFL &&
oldact.handler != (handler_t)master_signal_handler) {
skip = false;
}
}
}
if (skip)
continue;
if (sig_is_alarm_signal(i) && ignore_alarm) {
LOG(THREAD, LOG_ASYNCH, 2, "\tignoring %d initially\n", i);
intercept_signal_ignore_initially(dcontext, info, i);
} else {
LOG(THREAD, LOG_ASYNCH, 2, "\trestoring DR handler for %d\n", i);
intercept_signal(dcontext, info, i);
}
}
DODEBUG({ removed_sig_handler = false; });
}
void
signal_reinstate_alarm_handlers(dcontext_t *dcontext)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int i;
for (i = 1; i <= MAX_SIGNUM; i++) {
if (!info->we_intercept[i] || !sig_is_alarm_signal(i))
continue;
LOG(THREAD, LOG_ASYNCH, 2, "\trestoring DR handler for %d\n", i);
intercept_signal_no_longer_ignore(dcontext, info, i);
}
}
/**** system call handlers ***********************************************/
/* FIXME: invalid pointer passed to kernel will currently show up
* probably as a segfault in our handlers below...need to make them
* look like kernel, and pass error code back to os.c
*/
void
handle_clone(dcontext_t *dcontext, uint flags)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
if ((flags & CLONE_VM) == 0) {
/* separate process not sharing memory */
if ((flags & CLONE_SIGHAND) != 0) {
/* FIXME: how deal with this?
* "man clone" says: "Since Linux 2.6.0-test6, flags must also
* include CLONE_VM if CLONE_SIGHAND is specified"
*/
LOG(THREAD, LOG_ASYNCH, 1, "WARNING: !CLONE_VM but CLONE_SIGHAND!\n");
ASSERT_NOT_IMPLEMENTED(false);
}
return;
}
pre_second_thread();
if ((flags & CLONE_SIGHAND) != 0) {
/* need to share table of handlers! */
LOG(THREAD, LOG_ASYNCH, 2, "handle_clone: CLONE_SIGHAND set!\n");
if (!info->shared_app_sigaction) {
/* this is the start of a chain of sharing
* no synch needed here, child not created yet
*/
info->shared_app_sigaction = true;
info->shared_refcount =
(int *)global_heap_alloc(sizeof(int) HEAPACCT(ACCT_OTHER));
*info->shared_refcount = 1;
info->shared_lock =
(mutex_t *)global_heap_alloc(sizeof(mutex_t) HEAPACCT(ACCT_OTHER));
ASSIGN_INIT_LOCK_FREE(*info->shared_lock, shared_lock);
} /* else, some ancestor is already owner */
} else {
/* child will inherit copy of current table -> cannot modify it
* until child is scheduled! FIXME: any other way?
*/
d_r_mutex_lock(&info->child_lock);
info->num_unstarted_children++;
d_r_mutex_unlock(&info->child_lock);
}
if (TEST(CLONE_THREAD, flags) && os_itimers_thread_shared()) {
if (!info->shared_itimer) {
/* this is the start of a chain of sharing
* no synch needed here, child not created yet
*/
info->shared_itimer = true;
info->shared_itimer_refcount =
(int *)global_heap_alloc(sizeof(int) HEAPACCT(ACCT_OTHER));
*info->shared_itimer_refcount = 1;
info->shared_itimer_underDR =
(int *)global_heap_alloc(sizeof(int) HEAPACCT(ACCT_OTHER));
*info->shared_itimer_underDR = 1;
} /* else, some ancestor already created */
}
}
/* Returns false if should NOT issue syscall.
* In such a case, the result is in "result".
* If *result is non-zero, the syscall should fail.
* We could instead issue the syscall and expect it to fail, which would have a more
* accurate error code, but that risks missing a failure (e.g., RT on Android
* which in some cases returns success on bugus params).
* It seems better to err on the side of the wrong error code or failing when
* we shouldn't, than to think it failed when it didn't, which is more complex
* to deal with.
*/
bool
handle_sigaction(dcontext_t *dcontext, int sig, const kernel_sigaction_t *act,
prev_sigaction_t *oact, size_t sigsetsize, OUT uint *result)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
kernel_sigaction_t *save;
kernel_sigaction_t local_act;
if (sigsetsize != sizeof(kernel_sigset_t)) {
*result = EINVAL;
return false;
}
if (act != NULL) {
/* Linux checks readability before checking the signal number. */
if (!d_r_safe_read(act, sizeof(local_act), &local_act)) {
*result = EFAULT;
return false;
}
}
/* i#1135: app may pass invalid signum to find MAX_SIGNUM */
if (sig <= 0 || sig > MAX_SIGNUM || (act != NULL && !signal_is_interceptable(sig))) {
*result = EINVAL;
return false;
}
if (act != NULL) {
/* app is installing a new action */
while (info->num_unstarted_children > 0) {
/* must wait for children to start and copy our state
* before we modify it!
*/
os_thread_yield();
}
info->sigaction_param = act;
}
if (info->shared_app_sigaction) {
/* app_sigaction structure is shared */
d_r_mutex_lock(info->shared_lock);
}
if (oact != NULL) {
/* Keep a copy of the prior one for post-syscall to hand to the app. */
info->use_kernel_prior_sigaction = false;
if (info->app_sigaction[sig] == NULL) {
if (info->we_intercept[sig]) {
/* need to pretend there is no handler */
memset(&info->prior_app_sigaction, 0, sizeof(info->prior_app_sigaction));
info->prior_app_sigaction.handler = (handler_t)SIG_DFL;
} else {
info->use_kernel_prior_sigaction = true;
}
} else {
memcpy(&info->prior_app_sigaction, info->app_sigaction[sig],
sizeof(info->prior_app_sigaction));
}
}
if (act != NULL) {
if (local_act.handler == (handler_t)SIG_IGN ||
local_act.handler == (handler_t)SIG_DFL) {
LOG(THREAD, LOG_ASYNCH, 2, "app installed %s as sigaction for signal %d\n",
(local_act.handler == (handler_t)SIG_IGN) ? "SIG_IGN" : "SIG_DFL", sig);
if (!info->we_intercept[sig]) {
/* let the SIG_IGN/SIG_DFL go through, we want to remove our
* handler. we delete the stored app_sigaction in post_
*/
if (info->shared_app_sigaction)
d_r_mutex_unlock(info->shared_lock);
return true;
}
} else {
LOG(THREAD, LOG_ASYNCH, 2,
"app installed " PFX " as sigaction for signal %d\n", local_act.handler,
sig);
DOLOG(2, LOG_ASYNCH, {
LOG(THREAD, LOG_ASYNCH, 2, "signal mask for handler:\n");
dump_sigset(dcontext, (kernel_sigset_t *)&local_act.mask);
});
}
/* save app's entire sigaction struct */
save = (kernel_sigaction_t *)handler_alloc(dcontext, sizeof(kernel_sigaction_t));
memcpy(save, &local_act, sizeof(kernel_sigaction_t));
/* Remove the unblockable sigs */
kernel_sigdelset(&save->mask, SIGKILL);
kernel_sigdelset(&save->mask, SIGSTOP);
#ifdef X86
/* Remove flags not allowed to be passed to the kernel (this also zeroes
* the top 32 bits, like the kernel does: i#3681).
*/
save->flags &= ~(SA_IA32_ABI | SA_X32_ABI);
#endif
if (info->app_sigaction[sig] != NULL) {
/* go ahead and toss the old one, it's up to the app to store
* and then restore later if it wants to
*/
handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t));
}
info->app_sigaction[sig] = save;
LOG(THREAD, LOG_ASYNCH, 3, "\tflags = " PFX ", %s = " PFX "\n", local_act.flags,
IF_MACOS_ELSE("tramp", "restorer"),
IF_MACOS_ELSE(local_act.tramp, local_act.restorer));
/* clear cache */
info->restorer_valid[sig] = -1;
}
if (info->shared_app_sigaction)
d_r_mutex_unlock(info->shared_lock);
if (info->we_intercept[sig]) {
/* cancel the syscall */
*result = handle_post_sigaction(dcontext, true, sig, act, oact, sigsetsize);
return false;
}
if (act != NULL) {
/* Now hand kernel our master handler instead of app's. */
set_our_handler_sigact(&info->our_sigaction, sig);
set_syscall_param(dcontext, 1, (reg_t)&info->our_sigaction);
/* FIXME PR 297033: we don't support intercepting DEFAULT_STOP /
* DEFAULT_CONTINUE signals b/c we can't generate the default
* action: if the app registers a handler, though, we should work
* properly if we never see SIG_DFL.
*/
}
return true;
}
/* os.c thinks it's passing us struct_sigaction, really it's kernel_sigaction_t,
* which has fields in different order.
* Only called on success.
* Returns the desired app return value (caller will negate if nec).
*/
uint
handle_post_sigaction(dcontext_t *dcontext, bool success, int sig,
const kernel_sigaction_t *act, prev_sigaction_t *oact,
size_t sigsetsize)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
if (act != NULL) {
/* Restore app register value, in case we changed it. */
set_syscall_param(dcontext, 1, (reg_t)info->sigaction_param);
}
if (!success)
return 0; /* don't change return value */
ASSERT(sig <= MAX_SIGNUM && sig > 0);
if (oact != NULL) {
if (info->use_kernel_prior_sigaction) {
/* Real syscall succeeded with oact so it must be readable, barring races. */
ASSERT(oact->handler == (handler_t)SIG_IGN ||
oact->handler == (handler_t)SIG_DFL);
} else {
/* We may have skipped the syscall so we have to check writability */
#ifdef MACOS
/* On MacOS prev_sigaction_t is a different type (i#2105) */
bool fault = true;
TRY_EXCEPT(dcontext,
{
oact->handler = info->prior_app_sigaction.handler;
oact->mask = info->prior_app_sigaction.mask;
oact->flags = info->prior_app_sigaction.flags;
fault = false;
},
{
/* EXCEPT */
/* nothing: fault is already true */
});
if (fault)
return EFAULT;
#else
if (!safe_write_ex(oact, sizeof(*oact), &info->prior_app_sigaction, NULL)) {
/* We actually don't have to undo installing any passed action
* b/c the Linux kernel does that *before* checking oact perms.
*/
return EFAULT;
}
#endif
}
}
/* If installing IGN or DFL, delete ours.
* XXX: This is racy. We can't hold the lock across the syscall, though.
* What we should do is just drop support for -no_intercept_all_signals,
* which is off by default anyway and never turned off.
*/
if (act != NULL &&
/* De-ref here should work barring races: already racy and non-default so not
* bothering with safe_read.
*/
((act->handler == (handler_t)SIG_IGN || act->handler == (handler_t)SIG_DFL) &&
!info->we_intercept[sig]) &&
info->app_sigaction[sig] != NULL) {
if (info->shared_app_sigaction)
d_r_mutex_lock(info->shared_lock);
/* remove old stored app action */
handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t));
info->app_sigaction[sig] = NULL;
if (info->shared_app_sigaction)
d_r_mutex_unlock(info->shared_lock);
}
return 0;
}
#ifdef LINUX
static bool
convert_old_sigaction_to_kernel(dcontext_t *dcontext, kernel_sigaction_t *ks,
const old_sigaction_t *os)
{
bool res = false;
TRY_EXCEPT(dcontext,
{
ks->handler = os->handler;
ks->flags = os->flags;
ks->restorer = os->restorer;
kernel_sigemptyset(&ks->mask);
ks->mask.sig[0] = os->mask;
res = true;
},
{
/* EXCEPT */
/* nothing: res is already false */
});
return res;
}
static bool
convert_kernel_sigaction_to_old(dcontext_t *dcontext, old_sigaction_t *os,
const kernel_sigaction_t *ks)
{
bool res = false;
TRY_EXCEPT(dcontext,
{
os->handler = ks->handler;
os->flags = ks->flags;
os->restorer = ks->restorer;
os->mask = ks->mask.sig[0];
res = true;
},
{
/* EXCEPT */
/* nothing: res is already false */
});
return res;
}
/* Returns false (and "result") if should NOT issue syscall. */
bool
handle_old_sigaction(dcontext_t *dcontext, int sig, const old_sigaction_t *act,
old_sigaction_t *oact, OUT uint *result)
{
kernel_sigaction_t kact;
kernel_sigaction_t okact;
bool res;
if (act != NULL) {
if (!convert_old_sigaction_to_kernel(dcontext, &kact, act)) {
*result = EFAULT;
return false;
}
}
res = handle_sigaction(dcontext, sig, act == NULL ? NULL : &kact,
oact == NULL ? NULL : &okact, sizeof(kernel_sigset_t), result);
if (!res)
*result = handle_post_old_sigaction(dcontext, true, sig, act, oact);
return res;
}
/* Returns the desired app return value (caller will negate if nec). */
uint
handle_post_old_sigaction(dcontext_t *dcontext, bool success, int sig,
const old_sigaction_t *act, old_sigaction_t *oact)
{
kernel_sigaction_t kact;
kernel_sigaction_t okact;
ptr_uint_t res;
if (act != NULL && success) {
if (!convert_old_sigaction_to_kernel(dcontext, &kact, act)) {
ASSERT(!success);
return EFAULT;
}
}
if (oact != NULL && success) {
if (!convert_old_sigaction_to_kernel(dcontext, &okact, oact)) {
ASSERT(!success);
return EFAULT;
}
}
res = handle_post_sigaction(dcontext, success, sig, act == NULL ? NULL : &kact,
oact == NULL ? NULL : &okact, sizeof(kernel_sigset_t));
if (res == 0 && oact != NULL) {
if (!convert_kernel_sigaction_to_old(dcontext, oact, &okact)) {
return EFAULT;
}
}
return res;
}
#endif /* LINUX */
/* Returns false and sets *result if should NOT issue syscall.
* If *result is non-zero, the syscall should fail.
*/
bool
handle_sigaltstack(dcontext_t *dcontext, const stack_t *stack, stack_t *old_stack,
reg_t cur_xsp, OUT uint *result)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
stack_t local_stack;
if (old_stack != NULL) {
if (!safe_write_ex(old_stack, sizeof(*old_stack), &info->app_sigstack, NULL)) {
*result = EFAULT;
return false;
}
}
if (stack != NULL) {
/* Fail in the same way the kernel does. */
if (!d_r_safe_read(stack, sizeof(local_stack), &local_stack)) {
*result = EFAULT;
return false;
}
if (APP_HAS_SIGSTACK(info)) {
/* The app is not allowed to set a new altstack while on the current one. */
reg_t cur_sigstk = (reg_t)info->app_sigstack.ss_sp;
if (cur_xsp >= cur_sigstk &&
cur_xsp < cur_sigstk + info->app_sigstack.ss_size) {
*result = EPERM;
return false;
}
}
uint key_flag = local_stack.ss_flags & ~SS_FLAG_BITS;
if (key_flag != SS_DISABLE && key_flag != SS_ONSTACK && key_flag != 0) {
*result = EINVAL;
return false;
}
if (key_flag == SS_DISABLE) {
/* Zero the other params and don't even check them. */
local_stack.ss_sp = NULL;
local_stack.ss_size = 0;
} else {
if (local_stack.ss_size < MINSIGSTKSZ) {
*result = ENOMEM;
return false;
}
}
info->app_sigstack = local_stack;
LOG(THREAD, LOG_ASYNCH, 2, "Setting app signal stack to " PFX "-" PFX " %d=%s\n",
local_stack.ss_sp, local_stack.ss_sp + local_stack.ss_size - 1,
local_stack.ss_flags, (APP_HAS_SIGSTACK(info)) ? "enabled" : "disabled");
}
*result = 0;
return false; /* always cancel syscall */
}
/* Blocked signals:
* In general, we don't need to keep track of blocked signals.
* We only need to do so for those signals we intercept ourselves.
* Thus, info->app_sigblocked ONLY contains entries for signals
* we intercept ourselves.
* PR 304708: we now intercept all signals.
*/
static void
set_blocked(dcontext_t *dcontext, kernel_sigset_t *set, bool absolute)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int i;
if (absolute) {
/* discard current blocked signals, re-set from new mask */
kernel_sigemptyset(&info->app_sigblocked);
} /* else, OR in the new set */
for (i = 1; i <= MAX_SIGNUM; i++) {
if (EMULATE_SIGMASK(info, i) && kernel_sigismember(set, i)) {
kernel_sigaddset(&info->app_sigblocked, i);
}
}
#ifdef DEBUG
if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) {
LOG(THREAD, LOG_ASYNCH, 3, "blocked signals are now:\n");
dump_sigset(dcontext, &info->app_sigblocked);
}
#endif
}
void
signal_set_mask(dcontext_t *dcontext, kernel_sigset_t *sigset)
{
set_blocked(dcontext, sigset, true /*absolute*/);
}
void
signal_swap_mask(dcontext_t *dcontext, bool to_app)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
if (to_app) {
if (init_info.app_sigaction != NULL) {
/* This is the first execution of the app.
* We need to remove our own init-time handler and mask.
*/
unset_initial_crash_handlers(dcontext);
return;
}
sigprocmask_syscall(SIG_SETMASK, &info->app_sigblocked, NULL,
sizeof(info->app_sigblocked));
} else {
unblock_all_signals(&info->app_sigblocked);
DOLOG(2, LOG_ASYNCH, {
LOG(THREAD, LOG_ASYNCH, 2, "thread %d's initial app signal mask:\n",
d_r_get_thread_id());
dump_sigset(dcontext, &info->app_sigblocked);
});
}
}
/* Scans over info->sigpending to see if there are any unblocked, pending
* signals, and sets dcontext->signals_pending if there are. Do this after
* modifying the set of signals blocked by the application.
*/
void
check_signals_pending(dcontext_t *dcontext, thread_sig_info_t *info)
{
int i;
if (dcontext->signals_pending != 0)
return;
for (i = 1; i <= MAX_SIGNUM; i++) {
if (info->sigpending[i] != NULL &&
!kernel_sigismember(&info->app_sigblocked, i) && !dcontext->signals_pending) {
/* We only update the application's set of blocked signals from
* syscall handlers, so we know we'll go back to d_r_dispatch and see
* this flag right away.
*/
LOG(THREAD, LOG_ASYNCH, 3, "\tsetting signals_pending flag\n");
dcontext->signals_pending = 1;
break;
}
}
}
/* Returns whether to execute the syscall */
bool
handle_sigprocmask(dcontext_t *dcontext, int how, kernel_sigset_t *app_set,
kernel_sigset_t *oset, size_t sigsetsize)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int i;
kernel_sigset_t safe_set;
/* If we're intercepting all, we emulate the whole thing */
bool execute_syscall = !DYNAMO_OPTION(intercept_all_signals);
LOG(THREAD, LOG_ASYNCH, 2, "handle_sigprocmask\n");
if (oset != NULL)
info->pre_syscall_app_sigblocked = info->app_sigblocked;
if (app_set != NULL && d_r_safe_read(app_set, sizeof(safe_set), &safe_set)) {
if (execute_syscall) {
/* The syscall will execute, so remove from the set passed
* to it. We restore post-syscall.
* XXX i#1187: we could crash here touching app memory -- could
* use TRY, but the app could pass read-only memory and it
* would work natively! Better to swap in our own
* allocated data struct. There's a transparency issue w/
* races too if another thread looks at this memory. This
* won't happen by default b/c -intercept_all_signals is
* on by default so we don't try to solve all these
* issues.
*/
info->pre_syscall_app_sigprocmask = safe_set;
}
if (how == SIG_BLOCK) {
/* The set of blocked signals is the union of the current
* set and the set argument.
*/
for (i = 1; i <= MAX_SIGNUM; i++) {
if (EMULATE_SIGMASK(info, i) && kernel_sigismember(&safe_set, i)) {
kernel_sigaddset(&info->app_sigblocked, i);
if (execute_syscall)
kernel_sigdelset(app_set, i);
}
}
} else if (how == SIG_UNBLOCK) {
/* The signals in set are removed from the current set of
* blocked signals.
*/
for (i = 1; i <= MAX_SIGNUM; i++) {
if (EMULATE_SIGMASK(info, i) && kernel_sigismember(&safe_set, i)) {
kernel_sigdelset(&info->app_sigblocked, i);
if (execute_syscall)
kernel_sigdelset(app_set, i);
}
}
} else if (how == SIG_SETMASK) {
/* The set of blocked signals is set to the argument set. */
kernel_sigemptyset(&info->app_sigblocked);
for (i = 1; i <= MAX_SIGNUM; i++) {
if (EMULATE_SIGMASK(info, i) && kernel_sigismember(&safe_set, i)) {
kernel_sigaddset(&info->app_sigblocked, i);
if (execute_syscall)
kernel_sigdelset(app_set, i);
}
}
}
#ifdef DEBUG
if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) {
LOG(THREAD, LOG_ASYNCH, 3, "blocked signals are now:\n");
dump_sigset(dcontext, &info->app_sigblocked);
}
#endif
/* make sure we deliver pending signals that are now unblocked
* FIXME: consider signal #S, which we intercept ourselves.
* If S arrives, then app blocks it prior to our delivering it,
* we then won't deliver it until app unblocks it...is this a
* problem? Could have arrived a little later and then we would
* do same thing, but this way kernel may send one more than would
* get w/o dynamo? This goes away if we deliver signals
* prior to letting app do a syscall.
*/
check_signals_pending(dcontext, info);
}
if (!execute_syscall) {
handle_post_sigprocmask(dcontext, how, app_set, oset, sigsetsize);
return false; /* skip syscall */
} else
return true;
}
/* need to add in our signals that the app thinks are blocked */
void
handle_post_sigprocmask(dcontext_t *dcontext, int how, kernel_sigset_t *app_set,
kernel_sigset_t *oset, size_t sigsetsize)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int i;
if (!DYNAMO_OPTION(intercept_all_signals)) {
/* Restore app memory */
safe_write_ex(app_set, sizeof(*app_set), &info->pre_syscall_app_sigprocmask,
NULL);
}
if (oset != NULL) {
if (DYNAMO_OPTION(intercept_all_signals))
safe_write_ex(oset, sizeof(*oset), &info->pre_syscall_app_sigblocked, NULL);
else {
/* the syscall wrote to oset already, so just add any additional */
for (i = 1; i <= MAX_SIGNUM; i++) {
if (EMULATE_SIGMASK(info, i) &&
/* use the pre-syscall value: do not take into account changes
* from this syscall itself! (PR 523394)
*/
kernel_sigismember(&info->pre_syscall_app_sigblocked, i)) {
kernel_sigaddset(oset, i);
}
}
}
}
}
void
handle_sigsuspend(dcontext_t *dcontext, kernel_sigset_t *set, size_t sigsetsize)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int i;
ASSERT(set != NULL);
LOG(THREAD, LOG_ASYNCH, 2, "handle_sigsuspend\n");
info->in_sigsuspend = true;
info->app_sigblocked_save = info->app_sigblocked;
kernel_sigemptyset(&info->app_sigblocked);
for (i = 1; i <= MAX_SIGNUM; i++) {
if (EMULATE_SIGMASK(info, i) && kernel_sigismember(set, i)) {
kernel_sigaddset(&info->app_sigblocked, i);
kernel_sigdelset(set, i);
}
}
#ifdef DEBUG
if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) {
LOG(THREAD, LOG_ASYNCH, 3, "in sigsuspend, blocked signals are now:\n");
dump_sigset(dcontext, &info->app_sigblocked);
}
#endif
}
/**** utility routines ***********************************************/
#ifdef DEBUG
static void
dump_sigset(dcontext_t *dcontext, kernel_sigset_t *set)
{
int sig;
for (sig = 1; sig <= MAX_SIGNUM; sig++) {
if (kernel_sigismember(set, sig))
LOG(THREAD, LOG_ASYNCH, 1, "\t%d = blocked\n", sig);
}
}
#endif /* DEBUG */
/* PR 205795: to avoid lock problems w/ in_fcache (it grabs a lock, we
* could have interrupted someone holding that), we first check
* whereami --- if whereami is DR_WHERE_FCACHE we still check the pc
* to distinguish generated routines, but at least we're certain
* it's not in DR where it could own a lock.
* We can't use is_on_dstack() here b/c we need to handle clean call
* arg crashes -- which is too bad since checking client dll and DR dll is
* not sufficient due to calls to ntdll, libc, or pc being in gencode.
*/
static bool
safe_is_in_fcache(dcontext_t *dcontext, app_pc pc, app_pc xsp)
{
if (dcontext->whereami != DR_WHERE_FCACHE ||
IF_CLIENT_INTERFACE(is_in_client_lib(pc) ||) is_in_dynamo_dll(pc) ||
is_on_initstack(xsp))
return false;
/* Reasonably certain not in DR code, so no locks should be held */
return in_fcache(pc);
}
static bool
safe_is_in_coarse_stubs(dcontext_t *dcontext, app_pc pc, app_pc xsp)
{
if (dcontext->whereami != DR_WHERE_FCACHE ||
IF_CLIENT_INTERFACE(is_in_client_lib(pc) ||) is_in_dynamo_dll(pc) ||
is_on_initstack(xsp))
return false;
/* Reasonably certain not in DR code, so no locks should be held */
return in_coarse_stubs(pc);
}
static bool
is_on_alt_stack(dcontext_t *dcontext, byte *sp)
{
#ifdef HAVE_SIGALTSTACK
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
return (sp >= (byte *)info->sigstack.ss_sp &&
/* deliberate equality check since stacks often init to top */
sp <= (byte *)(info->sigstack.ss_sp + info->sigstack.ss_size));
#else
return false;
#endif
}
/* The caller must initialize ucxt, including its fpstate pointer for x86 Linux. */
static void
sig_full_initialize(sig_full_cxt_t *sc_full, kernel_ucontext_t *ucxt)
{
sc_full->sc = SIGCXT_FROM_UCXT(ucxt);
#ifdef X86
sc_full->fp_simd_state = NULL; /* we have a ptr inside sigcontext_t */
#elif defined(ARM)
sc_full->fp_simd_state = &ucxt->coproc.uc_vfp;
#elif defined(AARCH64)
sc_full->fp_simd_state = &ucxt->uc_mcontext.__reserved;
#else
ASSERT_NOT_IMPLEMENTED(false);
#endif
}
void
sigcontext_to_mcontext(priv_mcontext_t *mc, sig_full_cxt_t *sc_full,
dr_mcontext_flags_t flags)
{
sigcontext_t *sc = sc_full->sc;
ASSERT(mc != NULL && sc != NULL);
#ifdef X86
if (TEST(DR_MC_INTEGER, flags)) {
mc->xax = sc->SC_XAX;
mc->xbx = sc->SC_XBX;
mc->xcx = sc->SC_XCX;
mc->xdx = sc->SC_XDX;
mc->xsi = sc->SC_XSI;
mc->xdi = sc->SC_XDI;
mc->xbp = sc->SC_XBP;
# ifdef X64
mc->r8 = sc->SC_FIELD(r8);
mc->r9 = sc->SC_FIELD(r9);
mc->r10 = sc->SC_FIELD(r10);
mc->r11 = sc->SC_FIELD(r11);
mc->r12 = sc->SC_FIELD(r12);
mc->r13 = sc->SC_FIELD(r13);
mc->r14 = sc->SC_FIELD(r14);
mc->r15 = sc->SC_FIELD(r15);
# endif /* X64 */
}
if (TEST(DR_MC_CONTROL, flags)) {
mc->xsp = sc->SC_XSP;
mc->xflags = sc->SC_XFLAGS;
mc->pc = (app_pc)sc->SC_XIP;
}
#elif defined(AARCH64)
if (TEST(DR_MC_INTEGER, flags))
memcpy(&mc->r0, &sc->SC_FIELD(regs[0]), sizeof(mc->r0) * 31);
if (TEST(DR_MC_CONTROL, flags)) {
/* XXX i#2710: the link register should be under DR_MC_CONTROL */
mc->sp = sc->SC_FIELD(sp);
mc->pc = (void *)sc->SC_FIELD(pc);
mc->nzcv = sc->SC_FIELD(pstate);
}
#elif defined(ARM)
if (TEST(DR_MC_INTEGER, flags)) {
mc->r0 = sc->SC_FIELD(arm_r0);
mc->r1 = sc->SC_FIELD(arm_r1);
mc->r2 = sc->SC_FIELD(arm_r2);
mc->r3 = sc->SC_FIELD(arm_r3);
mc->r4 = sc->SC_FIELD(arm_r4);
mc->r5 = sc->SC_FIELD(arm_r5);
mc->r6 = sc->SC_FIELD(arm_r6);
mc->r7 = sc->SC_FIELD(arm_r7);
mc->r8 = sc->SC_FIELD(arm_r8);
mc->r9 = sc->SC_FIELD(arm_r9);
mc->r10 = sc->SC_FIELD(arm_r10);
mc->r11 = sc->SC_FIELD(arm_fp);
mc->r12 = sc->SC_FIELD(arm_ip);
/* XXX i#2710: the link register should be under DR_MC_CONTROL */
mc->r14 = sc->SC_FIELD(arm_lr);
}
if (TEST(DR_MC_CONTROL, flags)) {
mc->r13 = sc->SC_FIELD(arm_sp);
mc->r15 = sc->SC_FIELD(arm_pc);
mc->cpsr = sc->SC_FIELD(arm_cpsr);
}
# ifdef X64
# error NYI on AArch64
# endif /* X64 */
#endif /* X86/ARM */
if (TEST(DR_MC_MULTIMEDIA, flags))
sigcontext_to_mcontext_simd(mc, sc_full);
}
/* Note that unlike mcontext_to_context(), this routine does not fill in
* any state that is not present in the mcontext: in particular, it assumes
* the sigcontext already contains the native fpstate. If the caller
* is generating a synthetic sigcontext, the caller should call
* save_fpstate() before calling this routine.
*/
/* XXX: on ARM, sigreturn needs the T bit set in the sigcontext_t cpsr field in
* order to return to Thumb mode. But, our mcontext doesn't have the T bit (b/c
* usermode can't read it). Thus callers must either modify an mcontext
* obtained from sigcontext_to_mcontext() or must call set_pc_mode_in_cpsr() in
* order to create a proper sigcontext for sigreturn. All callers here do so.
* The only external non-Windows caller of thread_set_mcontext() is
* translate_from_synchall_to_dispatch() who first does a thread_get_mcontext()
* and tweaks that context, so cpsr should be there.
*/
void
mcontext_to_sigcontext(sig_full_cxt_t *sc_full, priv_mcontext_t *mc,
dr_mcontext_flags_t flags)
{
sigcontext_t *sc = sc_full->sc;
ASSERT(mc != NULL && sc != NULL);
#ifdef X86
if (TEST(DR_MC_INTEGER, flags)) {
sc->SC_XAX = mc->xax;
sc->SC_XBX = mc->xbx;
sc->SC_XCX = mc->xcx;
sc->SC_XDX = mc->xdx;
sc->SC_XSI = mc->xsi;
sc->SC_XDI = mc->xdi;
sc->SC_XBP = mc->xbp;
# ifdef X64
sc->SC_FIELD(r8) = mc->r8;
sc->SC_FIELD(r9) = mc->r9;
sc->SC_FIELD(r10) = mc->r10;
sc->SC_FIELD(r11) = mc->r11;
sc->SC_FIELD(r12) = mc->r12;
sc->SC_FIELD(r13) = mc->r13;
sc->SC_FIELD(r14) = mc->r14;
sc->SC_FIELD(r15) = mc->r15;
# endif /* X64 */
}
if (TEST(DR_MC_CONTROL, flags)) {
sc->SC_XSP = mc->xsp;
sc->SC_XFLAGS = mc->xflags;
sc->SC_XIP = (ptr_uint_t)mc->pc;
}
#elif defined(AARCH64)
if (TEST(DR_MC_INTEGER, flags)) {
memcpy(&sc->SC_FIELD(regs[0]), &mc->r0, sizeof(mc->r0) * 31);
}
if (TEST(DR_MC_CONTROL, flags)) {
/* XXX i#2710: the link register should be under DR_MC_CONTROL */
sc->SC_FIELD(sp) = mc->sp;
sc->SC_FIELD(pc) = (ptr_uint_t)mc->pc;
sc->SC_FIELD(pstate) = mc->nzcv;
}
#elif defined(ARM)
if (TEST(DR_MC_INTEGER, flags)) {
sc->SC_FIELD(arm_r0) = mc->r0;
sc->SC_FIELD(arm_r1) = mc->r1;
sc->SC_FIELD(arm_r2) = mc->r2;
sc->SC_FIELD(arm_r3) = mc->r3;
sc->SC_FIELD(arm_r4) = mc->r4;
sc->SC_FIELD(arm_r5) = mc->r5;
sc->SC_FIELD(arm_r6) = mc->r6;
sc->SC_FIELD(arm_r7) = mc->r7;
sc->SC_FIELD(arm_r8) = mc->r8;
sc->SC_FIELD(arm_r9) = mc->r9;
sc->SC_FIELD(arm_r10) = mc->r10;
sc->SC_FIELD(arm_fp) = mc->r11;
sc->SC_FIELD(arm_ip) = mc->r12;
/* XXX i#2710: the link register should be under DR_MC_CONTROL */
sc->SC_FIELD(arm_lr) = mc->r14;
}
if (TEST(DR_MC_CONTROL, flags)) {
sc->SC_FIELD(arm_sp) = mc->r13;
sc->SC_FIELD(arm_pc) = mc->r15;
sc->SC_FIELD(arm_cpsr) = mc->cpsr;
}
# ifdef X64
# error NYI on AArch64
# endif /* X64 */
#endif /* X86/ARM */
if (TEST(DR_MC_MULTIMEDIA, flags))
mcontext_to_sigcontext_simd(sc_full, mc);
}
static void
ucontext_to_mcontext(priv_mcontext_t *mc, kernel_ucontext_t *uc)
{
sig_full_cxt_t sc_full;
sig_full_initialize(&sc_full, uc);
sigcontext_to_mcontext(mc, &sc_full, DR_MC_ALL);
}
static void
mcontext_to_ucontext(kernel_ucontext_t *uc, priv_mcontext_t *mc)
{
sig_full_cxt_t sc_full;
sig_full_initialize(&sc_full, uc);
mcontext_to_sigcontext(&sc_full, mc, DR_MC_ALL);
}
#ifdef AARCHXX
static void
set_sigcxt_stolen_reg(sigcontext_t *sc, reg_t val)
{
*(&sc->SC_R0 + (dr_reg_stolen - DR_REG_R0)) = val;
}
static reg_t
get_sigcxt_stolen_reg(sigcontext_t *sc)
{
return *(&sc->SC_R0 + (dr_reg_stolen - DR_REG_R0));
}
# ifndef AARCH64
static dr_isa_mode_t
get_pc_mode_from_cpsr(sigcontext_t *sc)
{
return TEST(EFLAGS_T, sc->SC_XFLAGS) ? DR_ISA_ARM_THUMB : DR_ISA_ARM_A32;
}
static void
set_pc_mode_in_cpsr(sigcontext_t *sc, dr_isa_mode_t isa_mode)
{
if (isa_mode == DR_ISA_ARM_THUMB)
sc->SC_XFLAGS |= EFLAGS_T;
else
sc->SC_XFLAGS &= ~EFLAGS_T;
}
# endif
#endif
/* Returns whether successful. If avoid_failure, tries to translate
* at least pc if not successful. Pass f if known.
*/
static bool
translate_sigcontext(dcontext_t *dcontext, kernel_ucontext_t *uc, bool avoid_failure,
fragment_t *f)
{
bool success = false;
priv_mcontext_t mcontext;
sigcontext_t *sc = SIGCXT_FROM_UCXT(uc);
ucontext_to_mcontext(&mcontext, uc);
/* FIXME: if cannot find exact match, we're in trouble!
* probably ok to delay, since that indicates not a synchronous
* signal.
*/
/* FIXME : in_fcache() (called by recreate_app_state) grabs fcache
* fcache_unit_areas.lock, we could deadlock! Also on initexit_lock
* == PR 205795/1317
*/
/* For safe recreation we need to either be couldbelinking or hold the
* initexit lock (to keep someone from flushing current fragment), the
* initexit lock is easier
*/
d_r_mutex_lock(&thread_initexit_lock);
/* PR 214962: we assume we're going to relocate to this stored context,
* so we restore memory now
*/
if (translate_mcontext(dcontext->thread_record, &mcontext, true /*restore memory*/,
f)) {
mcontext_to_ucontext(uc, &mcontext);
success = true;
} else {
if (avoid_failure) {
ASSERT_NOT_REACHED(); /* is ok to break things, is UNIX :) */
/* FIXME : what to do? reg state might be wrong at least get pc */
if (safe_is_in_fcache(dcontext, (cache_pc)sc->SC_XIP, (app_pc)sc->SC_XSP)) {
sc->SC_XIP = (ptr_uint_t)recreate_app_pc(dcontext, mcontext.pc, f);
ASSERT(sc->SC_XIP != (ptr_uint_t)NULL);
} else {
/* FIXME : can't even get pc right, what do we do here? */
sc->SC_XIP = 0;
}
}
}
d_r_mutex_unlock(&thread_initexit_lock);
/* FIXME i#2095: restore the app's segment register value(s). */
LOG(THREAD, LOG_ASYNCH, 3,
"\ttranslate_sigcontext: just set frame's eip to " PFX "\n", sc->SC_XIP);
return success;
}
/* Takes an os-specific context */
void
thread_set_self_context(void *cxt)
{
#ifdef X86
if (!INTERNAL_OPTION(use_sigreturn_setcontext)) {
sigcontext_t *sc = (sigcontext_t *)cxt;
dr_jmp_buf_t buf;
buf.xbx = sc->SC_XBX;
buf.xcx = sc->SC_XCX;
buf.xdi = sc->SC_XDI;
buf.xsi = sc->SC_XSI;
buf.xbp = sc->SC_XBP;
/* XXX: this is not fully transparent: it assumes the target stack
* is valid and that we can clobber the slot beyond TOS.
* Using this instead of sigreturn is meant mainly as a diagnostic
* to help debug future issues with sigreturn (xref i#2080).
*/
buf.xsp = sc->SC_XSP - XSP_SZ; /* extra slot for retaddr */
buf.xip = sc->SC_XIP;
# ifdef X64
buf.r8 = sc->SC_R8;
buf.r9 = sc->SC_R9;
buf.r10 = sc->SC_R10;
buf.r11 = sc->SC_R11;
buf.r12 = sc->SC_R12;
buf.r13 = sc->SC_R13;
buf.r14 = sc->SC_R14;
buf.r15 = sc->SC_R15;
# endif
dr_longjmp(&buf, sc->SC_XAX);
return;
}
#endif
dcontext_t *dcontext = get_thread_private_dcontext();
/* Unlike Windows we can't say "only set this subset of the
* full machine state", so we need to get the rest of the state,
*/
sigframe_rt_t frame;
#if defined(LINUX) || defined(DEBUG)
sigcontext_t *sc = (sigcontext_t *)cxt;
#endif
app_pc xsp_for_sigreturn;
#ifdef VMX86_SERVER
ASSERT_NOT_IMPLEMENTED(false); /* PR 405694: can't use regular sigreturn! */
#endif
memset(&frame, 0, sizeof(frame));
#ifdef LINUX
# ifdef X86
byte *xstate = get_and_initialize_xstate_buffer(dcontext);
frame.uc.uc_mcontext.fpstate = &((kernel_xstate_t *)xstate)->fpstate;
# endif /* X86 */
frame.uc.uc_mcontext = *sc;
#endif
save_fpstate(dcontext, &frame);
/* The kernel calls do_sigaltstack on sys_rt_sigreturn primarily to ensure
* the frame is ok, but the side effect is we can mess up our own altstack
* settings if we're not careful. Having invalid ss_size looks good for
* kernel 2.6.23.9 at least so we leave frame.uc.uc_stack as all zeros.
*/
/* make sure sigreturn's mask setting doesn't change anything */
sigprocmask_syscall(SIG_SETMASK, NULL, (kernel_sigset_t *)&frame.uc.uc_sigmask,
sizeof(frame.uc.uc_sigmask));
LOG(THREAD_GET, LOG_ASYNCH, 2, "thread_set_self_context: pc=" PFX "\n", sc->SC_XIP);
LOG(THREAD_GET, LOG_ASYNCH, 3, "full sigcontext\n");
DOLOG(LOG_ASYNCH, 3,
{ dump_sigcontext(dcontext, get_sigcontext_from_rt_frame(&frame)); });
/* set up xsp to point at &frame + sizeof(char*) */
xsp_for_sigreturn = ((app_pc)&frame) + sizeof(char *);
#ifdef X86
asm("mov %0, %%" ASM_XSP : : "m"(xsp_for_sigreturn));
# ifdef MACOS
ASSERT_NOT_IMPLEMENTED(false && "need to pass 2 params to SYS_sigreturn");
asm("jmp _dynamorio_sigreturn");
# else
/* i#2632: recent clang for 32-bit annoyingly won't do the right thing for
* "jmp dynamorio_sigreturn" and leaves relocs so we ensure it's PIC:
*/
void (*asm_jmp_tgt)() = dynamorio_sigreturn;
asm("mov %0, %%" ASM_XCX : : "m"(asm_jmp_tgt));
asm("jmp *%" ASM_XCX);
# endif /* MACOS/LINUX */
#elif defined(AARCH64)
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
#elif defined(ARM)
asm("ldr " ASM_XSP ", %0" : : "m"(xsp_for_sigreturn));
asm("b dynamorio_sigreturn");
#endif /* X86/ARM */
ASSERT_NOT_REACHED();
}
static void
thread_set_segment_registers(sigcontext_t *sc)
{
#ifdef X86
/* Fill in the segment registers */
__asm__ __volatile__("mov %%cs, %%ax; mov %%ax, %0"
: "=m"(sc->SC_FIELD(cs))
:
: "eax");
# ifndef X64
__asm__ __volatile__("mov %%ss, %%ax; mov %%ax, %0"
: "=m"(sc->SC_FIELD(ss))
:
: "eax");
__asm__ __volatile__("mov %%ds, %%ax; mov %%ax, %0"
: "=m"(sc->SC_FIELD(ds))
:
: "eax");
__asm__ __volatile__("mov %%es, %%ax; mov %%ax, %0"
: "=m"(sc->SC_FIELD(es))
:
: "eax");
# endif
__asm__ __volatile__("mov %%fs, %%ax; mov %%ax, %0"
: "=m"(sc->SC_FIELD(fs))
:
: "eax");
__asm__ __volatile__("mov %%gs, %%ax; mov %%ax, %0"
: "=m"(sc->SC_FIELD(gs))
:
: "eax");
#endif
}
/* Takes a priv_mcontext_t */
void
thread_set_self_mcontext(priv_mcontext_t *mc)
{
kernel_ucontext_t ucxt;
sig_full_cxt_t sc_full;
sig_full_initialize(&sc_full, &ucxt);
#if defined(LINUX) && defined(X86)
sc_full.sc->fpstate = NULL; /* for mcontext_to_sigcontext */
#endif
mcontext_to_sigcontext(&sc_full, mc, DR_MC_ALL);
thread_set_segment_registers(sc_full.sc);
/* sigreturn takes the mode from cpsr */
IF_ARM(
set_pc_mode_in_cpsr(sc_full.sc, dr_get_isa_mode(get_thread_private_dcontext())));
/* thread_set_self_context will fill in the real fp/simd state for x86 */
thread_set_self_context((void *)sc_full.sc);
ASSERT_NOT_REACHED();
}
#ifdef LINUX
static bool
sig_has_restorer(thread_sig_info_t *info, int sig)
{
# ifdef VMX86_SERVER
/* vmkernel ignores SA_RESTORER (PR 405694) */
return false;
# endif
if (info->app_sigaction[sig] == NULL)
return false;
if (TEST(SA_RESTORER, info->app_sigaction[sig]->flags))
return true;
if (info->app_sigaction[sig]->restorer == NULL)
return false;
/* we cache the result due to the safe_read cost */
if (info->restorer_valid[sig] == -1) {
/* With older kernels, don't seem to need flag: if sa_restorer !=
* NULL kernel will use it. But with newer kernels that's not
* true, and sometimes libc does pass non-NULL.
*/
# ifdef X86
/* Signal restorer code for Ubuntu 7.04:
* 0xffffe420 <__kernel_sigreturn+0>: pop %eax
* 0xffffe421 <__kernel_sigreturn+1>: mov $0x77,%eax
* 0xffffe426 <__kernel_sigreturn+6>: int $0x80
*
* 0xffffe440 <__kernel_rt_sigreturn+0>: mov $0xad,%eax
* 0xffffe445 <__kernel_rt_sigreturn+5>: int $0x80
*/
static const byte SIGRET_NONRT[8] = { 0x58, 0xb8, 0x77, 0x00,
0x00, 0x00, 0xcd, 0x80 };
static const byte SIGRET_RT[8] = { 0xb8, 0xad, 0x00, 0x00, 0x00, 0xcd, 0x80 };
# elif defined(ARM)
static const byte SIGRET_NONRT[8] = { 0x77, 0x70, 0xa0, 0xe3,
0x00, 0x00, 0x00, 0xef };
static const byte SIGRET_RT[8] = {
0xad, 0x70, 0xa0, 0xe3, 0x00, 0x00, 0x00, 0xef
};
# elif defined(AARCH64)
static const byte SIGRET_NONRT[8] = { 0 }; /* unused */
static const byte SIGRET_RT[8] =
/* FIXME i#1569: untested */
/* mov w8, #139 ; svc #0 */
{ 0x68, 0x11, 0x80, 0x52, 0x01, 0x00, 0x00, 0xd4 };
# endif
byte buf[MAX(sizeof(SIGRET_NONRT), sizeof(SIGRET_RT))] = { 0 };
if (d_r_safe_read(info->app_sigaction[sig]->restorer, sizeof(buf), buf) &&
((IS_RT_FOR_APP(info, sig) &&
memcmp(buf, SIGRET_RT, sizeof(SIGRET_RT)) == 0) ||
(!IS_RT_FOR_APP(info, sig) &&
memcmp(buf, SIGRET_NONRT, sizeof(SIGRET_NONRT)) == 0))) {
LOG(THREAD_GET, LOG_ASYNCH, 2,
"sig_has_restorer %d: " PFX " looks like restorer, using w/o flag\n", sig,
info->app_sigaction[sig]->restorer);
info->restorer_valid[sig] = 1;
} else
info->restorer_valid[sig] = 0;
}
return (info->restorer_valid[sig] == 1);
}
#endif
/* Returns the size of the frame for delivering to the app.
* For x64 this does NOT include kernel_fpstate_t.
*/
static uint
get_app_frame_size(thread_sig_info_t *info, int sig)
{
if (IS_RT_FOR_APP(info, sig))
return sizeof(sigframe_rt_t);
#ifdef LINUX
else
return sizeof(sigframe_plain_t);
#endif
}
static kernel_ucontext_t *
get_ucontext_from_rt_frame(sigframe_rt_t *frame)
{
#if defined(MACOS) && !defined(X64)
/* Padding makes it unsafe to access uc on frame from kernel */
return frame->puc;
#else
return &frame->uc;
#endif
}
sigcontext_t *
get_sigcontext_from_rt_frame(sigframe_rt_t *frame)
{
return SIGCXT_FROM_UCXT(get_ucontext_from_rt_frame(frame));
}
static sigcontext_t *
get_sigcontext_from_app_frame(thread_sig_info_t *info, int sig, void *frame)
{
sigcontext_t *sc = NULL; /* initialize to satisfy Mac clang */
bool rtframe = IS_RT_FOR_APP(info, sig);
if (rtframe)
sc = get_sigcontext_from_rt_frame((sigframe_rt_t *)frame);
#ifdef LINUX
else {
# ifdef X86
sc = (sigcontext_t *)&(((sigframe_plain_t *)frame)->sc);
# elif defined(ARM)
sc = SIGCXT_FROM_UCXT(&(((sigframe_plain_t *)frame)->uc));
# else
ASSERT_NOT_REACHED();
# endif
}
#endif
return sc;
}
static sigcontext_t *
get_sigcontext_from_pending(thread_sig_info_t *info, int sig)
{
ASSERT(info->sigpending[sig] != NULL);
return get_sigcontext_from_rt_frame(&info->sigpending[sig]->rt_frame);
}
/* Returns the address on the appropriate signal stack where we should copy
* the frame.
* If frame is NULL, assumes signal happened while in DR and has been delayed,
* and thus we need to provide fpstate regardless of whether the original
* had it. If frame is non-NULL, matches frame's amount of fpstate.
*/
static byte *
get_sigstack_frame_ptr(dcontext_t *dcontext, int sig, sigframe_rt_t *frame)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
sigcontext_t *sc = (frame == NULL) ? get_sigcontext_from_pending(info, sig)
: get_sigcontext_from_rt_frame(frame);
byte *sp;
if (frame != NULL) {
/* signal happened while in cache, grab interrupted xsp */
sp = (byte *)sc->SC_XSP;
LOG(THREAD, LOG_ASYNCH, 3, "get_sigstack_frame_ptr: using frame's xsp " PFX "\n",
sp);
} else {
/* signal happened while in DR, use stored xsp */
sp = (byte *)get_mcontext(dcontext)->xsp;
LOG(THREAD, LOG_ASYNCH, 3, "get_sigstack_frame_ptr: using app xsp " PFX "\n", sp);
}
if (USE_APP_SIGSTACK(info, sig)) {
/* app has own signal stack which is enabled for this handler */
LOG(THREAD, LOG_ASYNCH, 3, "get_sigstack_frame_ptr: app has own stack " PFX "\n",
info->app_sigstack.ss_sp);
LOG(THREAD, LOG_ASYNCH, 3, "\tcur sp=" PFX " vs app stack " PFX "-" PFX "\n", sp,
info->app_sigstack.ss_sp,
info->app_sigstack.ss_sp + info->app_sigstack.ss_size);
if (sp > (byte *)info->app_sigstack.ss_sp &&
sp - (byte *)info->app_sigstack.ss_sp < info->app_sigstack.ss_size) {
/* we're currently in the alt stack, so use current xsp */
LOG(THREAD, LOG_ASYNCH, 3,
"\tinside alt stack, so using current xsp " PFX "\n", sp);
} else {
/* need to go to top, stack grows down */
sp = info->app_sigstack.ss_sp + info->app_sigstack.ss_size;
LOG(THREAD, LOG_ASYNCH, 3,
"\tnot inside alt stack, so using base xsp " PFX "\n", sp);
}
}
/* now get frame pointer: need to go down to first field of frame */
sp -= get_app_frame_size(info, sig);
#if defined(LINUX) && defined(X86)
if (frame == NULL) {
/* XXX i#641: we always include space for full xstate,
* even if we don't use it all, which does not match what the
* kernel does, but we're not tracking app actions to know whether
* we can skip lazy fpstate on the delay
*/
sp -= signal_frame_extra_size(true);
} else {
if (sc->fpstate != NULL) {
/* The kernel doesn't seem to lazily include avx, so we don't either,
* which simplifies all our frame copying: if YMM_ENABLED() and the
* fpstate pointer is non-NULL, then we assume there's space for
* full xstate
*/
sp -= signal_frame_extra_size(true);
DOCHECK(1, {
ASSERT(YMM_ENABLED() || !ZMM_ENABLED());
if (YMM_ENABLED()) {
ASSERT_CURIOSITY(sc->fpstate->sw_reserved.magic1 == FP_XSTATE_MAGIC1);
ASSERT(sc->fpstate->sw_reserved.extended_size <=
signal_frame_extra_size(true));
}
});
}
}
#endif /* LINUX && X86 */
/* PR 369907: don't forget the redzone */
sp -= REDZONE_SIZE;
/* Align to 16-bytes. The kernel does this for both 32 and 64-bit code
* these days, so we do as well.
*/
sp = (byte *)ALIGN_BACKWARD(sp, 16);
IF_X86(sp -= sizeof(reg_t)); /* Model retaddr. */
LOG(THREAD, LOG_ASYNCH, 3, "\tplacing frame at " PFX "\n", sp);
return sp;
}
#if defined(LINUX) && !defined(X64)
static void
convert_rt_mask_to_nonrt(sigframe_plain_t *f_plain, kernel_sigset_t *sigmask)
{
# ifdef X86
f_plain->sc.oldmask = sigmask->sig[0];
memcpy(&f_plain->extramask, &sigmask->sig[1], (_NSIG_WORDS - 1) * sizeof(uint));
# elif defined(ARM)
f_plain->uc.uc_mcontext.oldmask = sigmask->sig[0];
memcpy(&f_plain->uc.sigset_ex, &sigmask->sig[1], (_NSIG_WORDS - 1) * sizeof(uint));
# else
# error NYI
# endif
}
static void
convert_frame_to_nonrt(dcontext_t *dcontext, int sig, sigframe_rt_t *f_old,
sigframe_plain_t *f_new)
{
# ifdef X86
sigcontext_t *sc_old = get_sigcontext_from_rt_frame(f_old);
f_new->pretcode = f_old->pretcode;
f_new->sig = f_old->sig;
memcpy(&f_new->sc, get_sigcontext_from_rt_frame(f_old), sizeof(sigcontext_t));
if (sc_old->fpstate != NULL) {
/* up to caller to include enough space for fpstate at end */
byte *new_fpstate =
(byte *)ALIGN_FORWARD(((byte *)f_new) + sizeof(*f_new), XSTATE_ALIGNMENT);
memcpy(new_fpstate, sc_old->fpstate, signal_frame_extra_size(false));
f_new->sc.fpstate = (kernel_fpstate_t *)new_fpstate;
}
convert_rt_mask_to_nonrt(f_new, &f_old->uc.uc_sigmask);
memcpy(&f_new->retcode, &f_old->retcode, RETCODE_SIZE);
/* now fill in our extra field */
f_new->sig_noclobber = f_new->sig;
# elif defined(ARM)
memcpy(&f_new->uc, &f_old->uc, sizeof(f_new->uc));
memcpy(f_new->retcode, f_old->retcode, sizeof(f_new->retcode));
/* now fill in our extra field */
f_new->sig_noclobber = f_old->info.si_signo;
# endif /* X86 */
LOG(THREAD, LOG_ASYNCH, 3, "\tconverted sig=%d rt frame to non-rt frame\n",
f_new->sig_noclobber);
}
#endif
/* Exported for call from master_signal_handler asm routine.
* For the rt signal frame f_old that was copied to f_new, updates
* the intra-frame absolute pointers to point to the new addresses
* in f_new.
* Only updates the pretcode to the stored app restorer if for_app.
*/
void
fixup_rtframe_pointers(dcontext_t *dcontext, int sig, sigframe_rt_t *f_old,
sigframe_rt_t *f_new, bool for_app, size_t f_new_alloc_size)
{
if (dcontext == NULL)
dcontext = get_thread_private_dcontext();
ASSERT(dcontext != NULL);
#if defined(X86) && defined(LINUX)
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
bool has_restorer = sig_has_restorer(info, sig);
# ifdef DEBUG
uint level = 3;
# if !defined(HAVE_MEMINFO)
/* avoid logging every single TRY probe fault */
if (!dynamo_initialized)
level = 5;
# endif
# endif
if (has_restorer && for_app)
f_new->pretcode = (char *)info->app_sigaction[sig]->restorer;
else {
# ifdef VMX86_SERVER
/* PR 404712: skip kernel's restorer code */
if (for_app)
f_new->pretcode = (char *)dynamorio_sigreturn;
# else
# ifdef X64
ASSERT(!for_app || doing_detach); /* detach uses a frame to go native */
# else
/* only point at retcode if old one was -- with newer OS, points at
* vsyscall page and there is no restorer, yet stack restorer code left
* there for gdb compatibility
*/
if (f_old->pretcode == f_old->retcode)
f_new->pretcode = f_new->retcode;
/* else, pointing at vsyscall, or we set it to dynamorio_sigreturn in
* master_signal_handler
*/
LOG(THREAD, LOG_ASYNCH, level, "\tleaving pretcode with old value\n");
# endif
# endif
}
# ifndef X64
f_new->pinfo = &(f_new->info);
f_new->puc = &(f_new->uc);
# endif
if (f_old->uc.uc_mcontext.fpstate != NULL) {
uint frame_size = get_app_frame_size(info, sig);
byte *frame_end = ((byte *)f_new) + frame_size;
byte *tgt = (byte *)ALIGN_FORWARD(frame_end, XSTATE_ALIGNMENT);
size_t extra_size = signal_frame_extra_size(false);
ASSERT(extra_size == f_new->uc.uc_mcontext.fpstate->sw_reserved.extended_size);
/* XXX: It may be better to move this into memcpy_rt_frame (or another
* routine, since copy_frame_to_pending() wants them separate), since
* fixup_rtframe_pointers() was originally meant to just update a few
* pointers and not do a big memcpy. Compare to MACOS which calls it in
* copy_frame_to_pending(): if Linux did that we'd have memory clobbering.
*/
ASSERT(tgt + extra_size <= (byte *)f_new + f_new_alloc_size);
memcpy(tgt, f_new->uc.uc_mcontext.fpstate, extra_size);
f_new->uc.uc_mcontext.fpstate = (kernel_fpstate_t *)tgt;
LOG(THREAD, LOG_ASYNCH, level + 1, "\tfpstate old=" PFX " new=" PFX "\n",
f_old->uc.uc_mcontext.fpstate, f_new->uc.uc_mcontext.fpstate);
/* Be sure we're keeping both magic words. Failure to do so causes the
* kernel to only restore x87 and SSE state and zero out all AVX+ state
* (i#3812).
*/
ASSERT(f_new->uc.uc_mcontext.fpstate->sw_reserved.magic1 ==
f_old->uc.uc_mcontext.fpstate->sw_reserved.magic1);
ASSERT((f_new->uc.uc_mcontext.fpstate->sw_reserved.magic1 == 0 &&
f_new->uc.uc_mcontext.fpstate->sw_reserved.extended_size ==
sizeof(kernel_fpstate_t)) ||
(f_new->uc.uc_mcontext.fpstate->sw_reserved.magic1 == FP_XSTATE_MAGIC1 &&
*(int *)((byte *)f_new->uc.uc_mcontext.fpstate +
f_new->uc.uc_mcontext.fpstate->sw_reserved.extended_size -
FP_XSTATE_MAGIC2_SIZE) == FP_XSTATE_MAGIC2));
} else {
/* if fpstate is not set up, we're delivering signal immediately,
* and we shouldn't need an fpstate since DR code won't modify it;
* only if we delayed will we need it, and when delaying we make
* room and set up the pointer in copy_frame_to_pending.
* xref i#641.
*/
LOG(THREAD, LOG_ASYNCH, level + 1, "\tno fpstate needed\n");
}
LOG(THREAD, LOG_ASYNCH, level, "\tretaddr = " PFX "\n", f_new->pretcode);
# ifdef RETURN_AFTER_CALL
info->signal_restorer_retaddr = (app_pc)f_new->pretcode;
# endif
/* 32-bit kernel copies to aligned buf first */
IF_X64(ASSERT(ALIGNED(f_new->uc.uc_mcontext.fpstate, 16)));
#elif defined(MACOS)
# ifdef X64
/* Nothing to do. */
# else
f_new->pinfo = &(f_new->info);
f_new->puc = &(f_new->uc);
f_new->puc->uc_mcontext =
(IF_X64_ELSE(_STRUCT_MCONTEXT64, _STRUCT_MCONTEXT32) *)&f_new->mc;
LOG(THREAD, LOG_ASYNCH, 3, "\tf_new=" PFX ", &handler=" PFX "\n", f_new,
&f_new->handler);
ASSERT(!for_app || ALIGNED(&f_new->handler, 16));
# endif
#endif /* X86 && LINUX */
}
/* Only operates on rt frames, so call before converting to plain.
* Must be called *after* translating the sigcontext.
*/
static void
fixup_siginfo(dcontext_t *dcontext, int sig, sigframe_rt_t *frame)
{
/* For some signals, si_addr is a PC which we must translate. */
if (sig != SIGILL && sig != SIGTRAP && sig != SIGFPE)
return; /* nothing to do */
sigcontext_t *sc = get_sigcontext_from_rt_frame(frame);
kernel_siginfo_t *siginfo = SIGINFO_FROM_RT_FRAME(frame);
LOG(THREAD, LOG_ASYNCH, 3, "%s: updating si_addr from " PFX " to " PFX "\n",
__FUNCTION__, siginfo->si_addr, sc->SC_XIP);
siginfo->si_addr = (void *)sc->SC_XIP;
#ifdef LINUX
siginfo->si_addr_lsb = sc->SC_XIP & 0x1;
#endif
}
static void
memcpy_rt_frame(sigframe_rt_t *frame, byte *dst, bool from_pending)
{
#if defined(MACOS) && !defined(X64)
if (!from_pending) {
/* The kernel puts padding in the middle. We collapse that padding here
* and re-align when we copy to the app stack.
* We should not reference fields from mc onward in what the kernel put
* on the stack, as our sigframe_rt_t layout does not match the kernel's
* variable mid-struct padding.
*/
sigcontext_t *sc = SIGCXT_FROM_UCXT(frame->puc);
memcpy(dst, frame, offsetof(sigframe_rt_t, puc) + sizeof(frame->puc));
memcpy(&((sigframe_rt_t *)dst)->mc, sc,
sizeof(sigframe_rt_t) - offsetof(sigframe_rt_t, mc));
return;
}
#endif
memcpy(dst, frame, sizeof(sigframe_rt_t));
}
/* Copies frame to sp.
* PR 304708: we now leave in rt form right up until we copy to the
* app stack, so that we can deliver to a client at a safe spot
* in rt form, so this routine now converts to a plain frame if necessary.
* If no restorer, touches up pretcode
* (and if rt_frame, touches up pinfo and puc)
* Also touches up fpstate pointer
*/
static void
copy_frame_to_stack(dcontext_t *dcontext, int sig, sigframe_rt_t *frame, byte *sp,
bool from_pending)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
bool rtframe = IS_RT_FOR_APP(info, sig);
uint frame_size = get_app_frame_size(info, sig);
#if defined(LINUX) && defined(X86_32)
bool has_restorer = sig_has_restorer(info, sig);
#endif
byte *flush_pc;
bool stack_unwritable = false;
uint size = frame_size;
#if defined(LINUX) && defined(X86)
sigcontext_t *sc = get_sigcontext_from_rt_frame(frame);
size += (sc->fpstate == NULL ? 0 : signal_frame_extra_size(true));
#endif /* LINUX && X86 */
LOG(THREAD, LOG_ASYNCH, 3, "copy_frame_to_stack: rt=%d, src=" PFX ", sp=" PFX "\n",
rtframe, frame, sp);
fixup_siginfo(dcontext, sig, frame);
/* We avoid querying memory as it incurs global contended locks. */
flush_pc = is_executable_area_writable_overlap(sp, sp + size);
if (flush_pc != NULL) {
LOG(THREAD, LOG_ASYNCH, 2,
"\tcopy_frame_to_stack: part of stack is unwritable-by-us @" PFX "\n",
flush_pc);
flush_fragments_and_remove_region(dcontext, flush_pc, sp + size - flush_pc,
false /* don't own initexit_lock */,
false /* keep futures */);
}
TRY_EXCEPT(dcontext, /* try */
{
if (rtframe) {
ASSERT(frame_size == sizeof(*frame));
memcpy_rt_frame(frame, sp, from_pending);
}
IF_NOT_X64(
IF_LINUX(else convert_frame_to_nonrt(dcontext, sig, frame,
(sigframe_plain_t *)sp);));
},
/* except */ { stack_unwritable = true; });
if (stack_unwritable) {
/* Override the no-nested check in record_pending_signal(): it's ok b/c
* receive_pending_signal() calls to here at a consistent point,
* and we won't return there.
*/
info->nested_pending_ok = true;
/* Just throw away this signal and deliver SIGSEGV instead with the
* same sigcontext, like the kernel does.
*/
free_pending_signal(info, sig);
os_forge_exception(0, UNREADABLE_MEMORY_EXECUTION_EXCEPTION);
ASSERT_NOT_REACHED();
}
kernel_sigset_t *mask_to_restore = NULL;
if (info->pre_syscall_app_sigprocmask_valid) {
mask_to_restore = &info->pre_syscall_app_sigprocmask;
info->pre_syscall_app_sigprocmask_valid = false;
} else {
mask_to_restore = &info->app_sigblocked;
}
/* if !has_restorer we do NOT add the restorer code to the exec list here,
* to avoid removal problems (if handler never returns) and consistency problems
* (would have to mark as selfmod right now if on stack).
* for PROGRAM_SHEPHERDING we recognize as a pattern, and for consistency we
* allow entire region once try to execute -- not a performance worry since should
* very rarely be on the stack: should either be libc restorer code or with recent
* OS in rx vsyscall page.
*/
/* fix up pretcode, pinfo, puc, fpstate */
if (rtframe) {
sigframe_rt_t *f_new = (sigframe_rt_t *)sp;
fixup_rtframe_pointers(dcontext, sig, frame, f_new, true /*for app*/, size);
#ifdef HAVE_SIGALTSTACK
/* Make sure the frame's sigstack reflects the app stack, both for transparency
* of the app examining it and for correctness if we detach mid-handler.
*/
LOG(THREAD, LOG_ASYNCH, 3, "updated uc_stack @" PFX " to " PFX "\n",
&f_new->uc.uc_stack, info->app_sigstack.ss_sp);
f_new->uc.uc_stack = info->app_sigstack;
#endif
/* Store the prior mask, for restoring in sigreturn. */
memcpy(&f_new->uc.uc_sigmask, mask_to_restore, sizeof(info->app_sigblocked));
} else {
#ifdef X64
ASSERT_NOT_REACHED();
#endif
#if defined(LINUX) && !defined(X64)
sigframe_plain_t *f_new = (sigframe_plain_t *)sp;
# ifdef X86
# ifndef VMX86_SERVER
sigframe_plain_t *f_old = (sigframe_plain_t *)frame;
# endif
if (has_restorer)
f_new->pretcode = (char *)info->app_sigaction[sig]->restorer;
else {
# ifdef VMX86_SERVER
/* PR 404712: skip kernel's restorer code */
f_new->pretcode = (char *)dynamorio_nonrt_sigreturn;
# else
/* see comments in rt case above */
if (f_old->pretcode == f_old->retcode)
f_new->pretcode = f_new->retcode;
else {
/* whether we set to dynamorio_sigreturn in master_signal_handler
* or it's still vsyscall page, we have to convert to non-rt
*/
f_new->pretcode = (char *)dynamorio_nonrt_sigreturn;
} /* else, pointing at vsyscall most likely */
LOG(THREAD, LOG_ASYNCH, 3, "\tleaving pretcode with old value\n");
# endif
}
/* convert_frame_to_nonrt*() should have updated fpstate pointer.
* The inlined fpstate is no longer used on new kernels, and we do that
* as well on older kernels.
*/
ASSERT(f_new->sc.fpstate != &f_new->fpstate);
/* 32-bit kernel copies to aligned buf so no assert on fpstate alignment */
LOG(THREAD, LOG_ASYNCH, 3, "\tretaddr = " PFX "\n", f_new->pretcode);
/* There is no stored alt stack in a plain frame to update. */
# ifdef RETURN_AFTER_CALL
info->signal_restorer_retaddr = (app_pc)f_new->pretcode;
# endif
# endif /* X86 */
/* Store the prior mask, for restoring in sigreturn. */
convert_rt_mask_to_nonrt(f_new, mask_to_restore);
#endif /* LINUX && !X64 */
}
#if defined(MACOS) && !defined(X64)
/* Update handler field, which is passed to the libc trampoline, to app */
ASSERT(info->app_sigaction[sig] != NULL);
((sigframe_rt_t *)sp)->handler = (app_pc)info->app_sigaction[sig]->handler;
#endif
}
/* Copies frame to pending slot.
* PR 304708: we now leave in rt form right up until we copy to the
* app stack, so that we can deliver to a client at a safe spot
* in rt form.
*/
static void
copy_frame_to_pending(dcontext_t *dcontext, int sig,
sigframe_rt_t *frame _IF_CLIENT(byte *access_address))
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
sigframe_rt_t *dst = &(info->sigpending[sig]->rt_frame);
memcpy_rt_frame(frame, (byte *)dst, false /*!already pending*/);
#if defined(LINUX) && defined(X86)
/* For lazy fpstate, it's possible there was no fpstate when the kernel
* sent us the frame, but in between then and now the app executed some
* fp or xmm/ymm instrs. Today we always add fpstate just in case.
* XXX i#641 optimization: track whether any fp/xmm/ymm
* instrs happened and avoid this.
*/
/* we'll fill in updated fpstate at delivery time, but we go ahead and
* copy now in case our own retrieval somehow misses some fields
*/
if (frame->uc.uc_mcontext.fpstate != NULL) {
size_t extra_size = signal_frame_extra_size(false);
ASSERT(extra_size == frame->uc.uc_mcontext.fpstate->sw_reserved.extended_size);
memcpy(&info->sigpending[sig]->xstate, frame->uc.uc_mcontext.fpstate, extra_size);
}
/* we must set the pointer now so that later save_fpstate, etc. work */
dst->uc.uc_mcontext.fpstate = (kernel_fpstate_t *)&info->sigpending[sig]->xstate;
#endif /* LINUX && X86 */
#ifdef CLIENT_INTERFACE
info->sigpending[sig]->access_address = access_address;
#endif
info->sigpending[sig]->use_sigcontext = false;
#ifdef MACOS
/* We rely on puc to find sc to we have to fix it up */
fixup_rtframe_pointers(dcontext, sig, frame, dst, false /*!for app*/, sizeof(*dst));
#endif
LOG(THREAD, LOG_ASYNCH, 3, "copy_frame_to_pending from " PFX "\n", frame);
DOLOG(3, LOG_ASYNCH, {
LOG(THREAD, LOG_ASYNCH, 3, "sigcontext:\n");
dump_sigcontext(dcontext, get_sigcontext_from_rt_frame(dst));
});
}
/**** real work ***********************************************/
/* transfer control from signal handler to fcache return routine */
static void
transfer_from_sig_handler_to_fcache_return(dcontext_t *dcontext, kernel_ucontext_t *uc,
sigcontext_t *sc_interrupted, int sig,
app_pc next_pc, linkstub_t *last_exit,
bool is_kernel_xfer)
{
sigcontext_t *sc = SIGCXT_FROM_UCXT(uc);
#ifdef CLIENT_INTERFACE
if (is_kernel_xfer) {
sig_full_cxt_t sc_interrupted_full = { sc_interrupted, NULL /*not provided*/ };
sig_full_cxt_t sc_full;
sig_full_initialize(&sc_full, uc);
sc->SC_XIP = (ptr_uint_t)next_pc;
if (instrument_kernel_xfer(dcontext, DR_XFER_SIGNAL_DELIVERY, sc_interrupted_full,
NULL, NULL, next_pc, sc->SC_XSP, sc_full, NULL, sig))
next_pc = canonicalize_pc_target(dcontext, (app_pc)sc->SC_XIP);
}
#endif
dcontext->next_tag = canonicalize_pc_target(dcontext, next_pc);
IF_ARM(dr_set_isa_mode(dcontext, get_pc_mode_from_cpsr(sc), NULL));
/* Set our sigreturn context to point to fcache_return!
* Then we'll go back through kernel, appear in fcache_return,
* and go through d_r_dispatch & interp, without messing up dynamo stack.
* Note that even if this is a write in the shared cache, we
* still go to the private fcache_return for simplicity.
*/
sc->SC_XIP = (ptr_uint_t)fcache_return_routine(dcontext);
#ifdef AARCHXX
/* We do not have to set dr_reg_stolen in dcontext's mcontext here
* because dcontext's mcontext is stale and we used the mcontext
* created from recreate_app_state_internal with the original sigcontext.
*/
/* We restore dr_reg_stolen's app value in recreate_app_state_internal,
* so now we need set dr_reg_stolen to hold DR's TLS before sigreturn
* from DR's handler.
*/
ASSERT(get_sigcxt_stolen_reg(sc) != (reg_t)*get_dr_tls_base_addr());
set_sigcxt_stolen_reg(sc, (reg_t)*get_dr_tls_base_addr());
# ifndef AARCH64
/* We're going to our fcache_return gencode which uses DEFAULT_ISA_MODE */
set_pc_mode_in_cpsr(sc, DEFAULT_ISA_MODE);
# endif
#endif
#if defined(X64) || defined(ARM)
/* x64 always uses shared gencode */
get_local_state_extended()->spill_space.IF_X86_ELSE(xax, r0) =
sc->IF_X86_ELSE(SC_XAX, SC_R0);
# ifdef AARCH64
/* X1 needs to be spilled because of br x1 in exit stubs. */
get_local_state_extended()->spill_space.r1 = sc->SC_R1;
# endif
#else
get_mcontext(dcontext)->IF_X86_ELSE(xax, r0) = sc->IF_X86_ELSE(SC_XAX, SC_R0);
#endif
LOG(THREAD, LOG_ASYNCH, 2, "\tsaved xax " PFX "\n", sc->IF_X86_ELSE(SC_XAX, SC_R0));
sc->IF_X86_ELSE(SC_XAX, SC_R0) = (ptr_uint_t)last_exit;
LOG(THREAD, LOG_ASYNCH, 2, "\tset next_tag to " PFX ", resuming in fcache_return\n",
next_pc);
LOG(THREAD, LOG_ASYNCH, 3, "transfer_from_sig_handler_to_fcache_return\n");
DOLOG(3, LOG_ASYNCH, {
LOG(THREAD, LOG_ASYNCH, 3, "sigcontext @" PFX ":\n", sc);
dump_sigcontext(dcontext, sc);
});
}
#ifdef CLIENT_INTERFACE
static dr_signal_action_t
send_signal_to_client(dcontext_t *dcontext, int sig, sigframe_rt_t *frame,
sigcontext_t *raw_sc, byte *access_address, bool blocked,
fragment_t *fragment)
{
kernel_ucontext_t *uc = get_ucontext_from_rt_frame(frame);
dr_siginfo_t si;
dr_signal_action_t action;
/* XXX #1615: we need a full ucontext to store pre-xl8 simd values.
* Right now we share the same simd values with post-xl8.
*/
sig_full_cxt_t raw_sc_full;
sig_full_initialize(&raw_sc_full, uc);
raw_sc_full.sc = raw_sc;
if (!dr_signal_hook_exists())
return DR_SIGNAL_DELIVER;
LOG(THREAD, LOG_ASYNCH, 2, "sending signal to client\n");
si.sig = sig;
si.drcontext = (void *)dcontext;
/* It's safe to allocate since we do not send signals that interrupt DR.
* With priv_mcontext_t x2 that's a little big for stack alloc.
*/
si.mcontext = heap_alloc(dcontext, sizeof(*si.mcontext) HEAPACCT(ACCT_OTHER));
si.raw_mcontext = heap_alloc(dcontext, sizeof(*si.raw_mcontext) HEAPACCT(ACCT_OTHER));
dr_mcontext_init(si.mcontext);
dr_mcontext_init(si.raw_mcontext);
/* i#207: fragment tag and fcache start pc on fault. */
si.fault_fragment_info.tag = NULL;
si.fault_fragment_info.cache_start_pc = NULL;
/* i#182/PR 449996: we provide the pre-translation context */
if (raw_sc != NULL) {
fragment_t wrapper;
si.raw_mcontext_valid = true;
sigcontext_to_mcontext(dr_mcontext_as_priv_mcontext(si.raw_mcontext),
&raw_sc_full, si.raw_mcontext->flags);
/* i#207: fragment tag and fcache start pc on fault. */
/* FIXME: we should avoid the fragment_pclookup since it is expensive
* and since we already did the work of a lookup when translating
*/
if (fragment == NULL)
fragment = fragment_pclookup(dcontext, si.raw_mcontext->pc, &wrapper);
if (fragment != NULL && !hide_tag_from_client(fragment->tag)) {
si.fault_fragment_info.tag = fragment->tag;
si.fault_fragment_info.cache_start_pc = FCACHE_ENTRY_PC(fragment);
si.fault_fragment_info.is_trace = TEST(FRAG_IS_TRACE, fragment->flags);
si.fault_fragment_info.app_code_consistent =
!TESTANY(FRAG_WAS_DELETED | FRAG_SELFMOD_SANDBOXED, fragment->flags);
}
} else
si.raw_mcontext_valid = false;
/* The client has no way to calculate this when using
* instrumentation that deliberately faults (to shift a rare event
* out of the fastpath) so we provide it. When raw_mcontext is
* available the client can calculate it, but we provide it as a
* convenience anyway.
*/
si.access_address = access_address;
si.blocked = blocked;
ucontext_to_mcontext(dr_mcontext_as_priv_mcontext(si.mcontext), uc);
/* We disallow the client calling dr_redirect_execution(), so we
* will not leak si
*/
action = instrument_signal(dcontext, &si);
if (action == DR_SIGNAL_DELIVER || action == DR_SIGNAL_REDIRECT) {
/* propagate client changes */
CLIENT_ASSERT(si.mcontext->flags == DR_MC_ALL,
"signal mcontext flags cannot be changed");
mcontext_to_ucontext(uc, dr_mcontext_as_priv_mcontext(si.mcontext));
} else if (action == DR_SIGNAL_SUPPRESS && raw_sc != NULL) {
/* propagate client changes */
CLIENT_ASSERT(si.raw_mcontext->flags == DR_MC_ALL,
"signal mcontext flags cannot be changed");
mcontext_to_sigcontext(&raw_sc_full,
dr_mcontext_as_priv_mcontext(si.raw_mcontext),
si.raw_mcontext->flags);
}
heap_free(dcontext, si.mcontext, sizeof(*si.mcontext) HEAPACCT(ACCT_OTHER));
heap_free(dcontext, si.raw_mcontext, sizeof(*si.raw_mcontext) HEAPACCT(ACCT_OTHER));
return action;
}
/* Returns false if caller should exit */
static bool
handle_client_action_from_cache(dcontext_t *dcontext, int sig, dr_signal_action_t action,
sigframe_rt_t *our_frame, sigcontext_t *sc_orig,
sigcontext_t *sc_interrupted, bool blocked)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
kernel_ucontext_t *uc = get_ucontext_from_rt_frame(our_frame);
sigcontext_t *sc = SIGCXT_FROM_UCXT(uc);
/* in order to pass to the client, we come all the way here for signals
* the app has no handler for
*/
if (action == DR_SIGNAL_REDIRECT) {
/* send_signal_to_client copied mcontext into our
* master_signal_handler frame, so we set up for fcache_return w/
* our frame's state
*/
transfer_from_sig_handler_to_fcache_return(
dcontext, uc, sc_interrupted, sig, (app_pc)sc->SC_XIP,
(linkstub_t *)get_asynch_linkstub(), true);
if (is_building_trace(dcontext)) {
LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n");
trace_abort(dcontext);
}
return false;
} else if (action == DR_SIGNAL_SUPPRESS ||
(!blocked && info->app_sigaction[sig] != NULL &&
info->app_sigaction[sig]->handler == (handler_t)SIG_IGN)) {
LOG(THREAD, LOG_ASYNCH, 2, "%s: not delivering!\n",
(action == DR_SIGNAL_SUPPRESS) ? "client suppressing signal"
: "app signal handler is SIG_IGN");
/* restore original (untranslated) sc */
*get_sigcontext_from_rt_frame(our_frame) = *sc_orig;
return false;
} else if (!blocked && /* no BYPASS for blocked */
(action == DR_SIGNAL_BYPASS ||
(info->app_sigaction[sig] == NULL ||
info->app_sigaction[sig]->handler == (handler_t)SIG_DFL))) {
LOG(THREAD, LOG_ASYNCH, 2, "%s: executing default action\n",
(action == DR_SIGNAL_BYPASS) ? "client forcing default"
: "app signal handler is SIG_DFL");
if (execute_default_from_cache(dcontext, sig, our_frame, sc_orig, false)) {
/* if we haven't terminated, restore original (untranslated) sc
* on request.
*/
*get_sigcontext_from_rt_frame(our_frame) = *sc_orig;
LOG(THREAD, LOG_ASYNCH, 2, "%s: restored xsp=" PFX ", xip=" PFX "\n",
__FUNCTION__, get_sigcontext_from_rt_frame(our_frame)->SC_XSP,
get_sigcontext_from_rt_frame(our_frame)->SC_XIP);
}
return false;
}
CLIENT_ASSERT(action == DR_SIGNAL_DELIVER, "invalid signal event return value");
return true;
}
#endif
static void
abort_on_fault(dcontext_t *dcontext, uint dumpcore_flag, app_pc pc, byte *target, int sig,
sigframe_rt_t *frame, const char *prefix, const char *signame,
const char *where)
{
kernel_ucontext_t *ucxt = &frame->uc;
sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt);
bool stack_overflow = (sig == SIGSEGV && is_stack_overflow(dcontext, target));
#if defined(STATIC_LIBRARY) && defined(LINUX)
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
uint orig_dumpcore_flag = dumpcore_flag;
if (init_info.app_sigaction != NULL)
info = &init_info; /* use init-time handler */
ASSERT(info->app_sigaction != NULL);
#endif
const char *fmt = "%s %s at PC " PFX "\n"
"Received SIG%s at%s pc " PFX " in thread " TIDFMT "\n"
"Base: " PFX "\n"
"Registers:"
#ifdef X86
"eax=" PFX " ebx=" PFX " ecx=" PFX " edx=" PFX "\n"
"\tesi=" PFX " edi=" PFX " esp=" PFX " ebp=" PFX "\n"
# ifdef X64
"\tr8 =" PFX " r9 =" PFX " r10=" PFX " r11=" PFX "\n"
"\tr12=" PFX " r13=" PFX " r14=" PFX " r15=" PFX "\n"
# endif /* X64 */
#elif defined(ARM)
# ifndef X64
" r0 =" PFX " r1 =" PFX " r2 =" PFX " r3 =" PFX "\n"
"\tr4 =" PFX " r5 =" PFX " r6 =" PFX " r7 =" PFX "\n"
"\tr8 =" PFX " r9 =" PFX " r10=" PFX " r11=" PFX "\n"
"\tr12=" PFX " r13=" PFX " r14=" PFX " r15=" PFX "\n"
# else
# error NYI on AArch64
# endif
#endif /* X86/ARM */
"\teflags=" PFX;
#if defined(STATIC_LIBRARY) && defined(LINUX)
/* i#2119: if we're invoking an app handler, disable a fatal coredump. */
if (INTERNAL_OPTION(invoke_app_on_crash) && info->app_sigaction[sig] != NULL &&
IS_RT_FOR_APP(info, sig) && TEST(dumpcore_flag, DYNAMO_OPTION(dumpcore_mask)) &&
!DYNAMO_OPTION(live_dump))
dumpcore_flag = 0;
#endif
report_dynamorio_problem(
dcontext, dumpcore_flag | (stack_overflow ? DUMPCORE_STACK_OVERFLOW : 0), pc,
(app_pc)sc->SC_FP, fmt, prefix, stack_overflow ? STACK_OVERFLOW_NAME : CRASH_NAME,
pc, signame, where, pc, d_r_get_thread_id(), get_dynamorio_dll_start(),
#ifdef X86
sc->SC_XAX, sc->SC_XBX, sc->SC_XCX, sc->SC_XDX, sc->SC_XSI, sc->SC_XDI,
sc->SC_XSP, sc->SC_XBP,
# ifdef X64
sc->SC_FIELD(r8), sc->SC_FIELD(r9), sc->SC_FIELD(r10), sc->SC_FIELD(r11),
sc->SC_FIELD(r12), sc->SC_FIELD(r13), sc->SC_FIELD(r14), sc->SC_FIELD(r15),
# endif /* X86 */
#elif defined(ARM)
# ifndef X64
sc->SC_FIELD(arm_r0), sc->SC_FIELD(arm_r1), sc->SC_FIELD(arm_r2),
sc->SC_FIELD(arm_r3), sc->SC_FIELD(arm_r4), sc->SC_FIELD(arm_r5),
sc->SC_FIELD(arm_r6), sc->SC_FIELD(arm_r7), sc->SC_FIELD(arm_r8),
sc->SC_FIELD(arm_r9), sc->SC_FIELD(arm_r10), sc->SC_FIELD(arm_fp),
sc->SC_FIELD(arm_ip), sc->SC_FIELD(arm_sp), sc->SC_FIELD(arm_lr),
sc->SC_FIELD(arm_pc),
# else
# error NYI on AArch64
# endif /* X64 */
#endif /* X86/ARM */
sc->SC_XFLAGS);
#if defined(STATIC_LIBRARY) && defined(LINUX)
/* i#2119: For static DR, the surrounding app's handler may well be
* safe to invoke even when DR state is messed up: it's worth a try, as it
* likely has useful reporting features for users of the app.
* We limit to Linux and RT for simplicity: it can be expanded later if static
* library use expands.
*/
if (INTERNAL_OPTION(invoke_app_on_crash) && info->app_sigaction[sig] != NULL &&
IS_RT_FOR_APP(info, sig)) {
SYSLOG(SYSLOG_WARNING, INVOKING_APP_HANDLER, 2, get_application_name(),
get_application_pid());
(*info->app_sigaction[sig]->handler)(sig, &frame->info, ucxt);
/* If the app handler didn't terminate, now get a fatal core. */
if (TEST(orig_dumpcore_flag, DYNAMO_OPTION(dumpcore_mask)) &&
!DYNAMO_OPTION(live_dump))
os_dump_core("post-app-handler attempt at core dump");
}
#endif
os_terminate(dcontext, TERMINATE_PROCESS);
ASSERT_NOT_REACHED();
}
static void
abort_on_DR_fault(dcontext_t *dcontext, app_pc pc, byte *target, int sig,
sigframe_rt_t *frame, const char *signame, const char *where)
{
abort_on_fault(dcontext, DUMPCORE_INTERNAL_EXCEPTION, pc, target, sig, frame,
exception_label_core, signame, where);
ASSERT_NOT_REACHED();
}
/* Returns whether unlinked or mangled syscall.
* Restored in receive_pending_signal.
*/
static bool
unlink_fragment_for_signal(dcontext_t *dcontext, fragment_t *f,
byte *pc /*interruption pc*/)
{
/* We only come here if we interrupted a fragment in the cache,
* or interrupted transition gencode (i#2019),
* which means that this thread's DR state is safe, and so it
* should be ok to acquire a lock. xref PR 596069.
*
* There is a race where if two threads hit a signal in the same
* shared fragment, the first could re-link after the second
* un-links but before the second exits, and the second could then
* execute the syscall, resulting in arbitrary delay prior to
* signal delivery. We don't want to allocate global memory,
* but we could use a static array of counters (since should
* be small # of interrupted shared fragments at any one time)
* used as refcounts so we only unlink when all are done.
* Not bothering to implement now: going to live w/ chance of
* long signal delays. xref PR 596069.
*/
bool changed = false;
bool waslinking = is_couldbelinking(dcontext);
if (!waslinking)
enter_couldbelinking(dcontext, NULL, false);
/* may not be linked if trace_relink or something */
if (TEST(FRAG_COARSE_GRAIN, f->flags)) {
/* XXX PR 213040: we don't support unlinking coarse, so we try
* not to come here, but for indirect branch and other spots
* where we don't yet support translation (since can't fault)
* we end up w/ no bound on delivery...
*/
} else if (TEST(FRAG_LINKED_OUTGOING, f->flags)) {
LOG(THREAD, LOG_ASYNCH, 3, "\tunlinking outgoing for interrupted F%d\n", f->id);
SHARED_FLAGS_RECURSIVE_LOCK(f->flags, acquire, change_linking_lock);
// Double-check flags to ensure some other thread didn't unlink
// while we waited for the change_linking_lock.
if (TEST(FRAG_LINKED_OUTGOING, f->flags)) {
unlink_fragment_outgoing(dcontext, f);
changed = true;
}
SHARED_FLAGS_RECURSIVE_LOCK(f->flags, release, change_linking_lock);
} else {
LOG(THREAD, LOG_ASYNCH, 3, "\toutgoing already unlinked for interrupted F%d\n",
f->id);
}
if (TEST(FRAG_HAS_SYSCALL, f->flags)) {
/* Syscalls are signal barriers!
* Make sure the next syscall (if any) in f is not executed!
* instead go back to d_r_dispatch right before the syscall
*/
/* syscall mangling does a bunch of decodes but only one write,
* changing the target of a short jmp, which is atomic
* since a one-byte write, so we don't need the change_linking_lock.
*/
if (mangle_syscall_code(dcontext, f, pc, false /*do not skip exit cti*/))
changed = true;
}
if (!waslinking)
enter_nolinking(dcontext, NULL, false);
return changed;
}
static void
relink_interrupted_fragment(dcontext_t *dcontext, thread_sig_info_t *info)
{
if (info->interrupted == NULL)
return;
/* i#2066: if we were building a trace, it may already be re-linked */
if (!TEST(FRAG_LINKED_OUTGOING, info->interrupted->flags)) {
LOG(THREAD, LOG_ASYNCH, 3, "\tre-linking outgoing for interrupted F%d\n",
info->interrupted->id);
SHARED_FLAGS_RECURSIVE_LOCK(info->interrupted->flags, acquire,
change_linking_lock);
/* Double-check flags to ensure some other thread didn't link
* while we waited for the change_linking_lock.
*/
if (!TEST(FRAG_LINKED_OUTGOING, info->interrupted->flags)) {
link_fragment_outgoing(dcontext, info->interrupted, false);
}
SHARED_FLAGS_RECURSIVE_LOCK(info->interrupted->flags, release,
change_linking_lock);
}
if (TEST(FRAG_HAS_SYSCALL, info->interrupted->flags)) {
/* restore syscall (they're a barrier to signals, so signal
* handler has cur frag exit before it does a syscall)
*/
if (info->interrupted_pc != NULL) {
mangle_syscall_code(dcontext, info->interrupted, info->interrupted_pc,
true /*skip exit cti*/);
}
}
info->interrupted = NULL;
info->interrupted_pc = NULL;
}
static bool
interrupted_inlined_syscall(dcontext_t *dcontext, fragment_t *f,
byte *pc /*interruption pc*/)
{
bool pre_or_post_syscall = false;
if (TEST(FRAG_HAS_SYSCALL, f->flags)) {
/* PR 596147: if the thread is currently in an inlined
* syscall when a signal comes in, we can't delay and bound the
* delivery time: we need to deliver now. Should decode
* backward and see if syscall. We assume our translation of
* the interruption state is fine to re-start: i.e., the syscall
* is complete if kernel has pc at post-syscall point, and
* kernel set EINTR in eax if necessary.
*/
/* Interrupted fcache, so ok to alloc memory for decode */
instr_t instr;
byte *nxt_pc;
instr_init(dcontext, &instr);
nxt_pc = decode(dcontext, pc, &instr);
if (nxt_pc != NULL && instr_valid(&instr) && instr_is_syscall(&instr)) {
/* pre-syscall but post-jmp so can't skip syscall */
pre_or_post_syscall = true;
} else {
size_t syslen = syscall_instr_length(FRAG_ISA_MODE(f->flags));
instr_reset(dcontext, &instr);
nxt_pc = decode(dcontext, pc - syslen, &instr);
if (nxt_pc != NULL && instr_valid(&instr) && instr_is_syscall(&instr)) {
#if defined(X86) && !defined(MACOS)
/* decoding backward so check for exit cti jmp prior
* to syscall to ensure no mismatch
*/
instr_reset(dcontext, &instr);
nxt_pc = decode(dcontext, pc - syslen - JMP_LONG_LENGTH, &instr);
if (nxt_pc != NULL && instr_valid(&instr) &&
instr_get_opcode(&instr) == OP_jmp) {
/* post-inlined-syscall */
pre_or_post_syscall = true;
}
#else
/* On Mac and ARM we have some TLS spills in between so we just
* trust that this is a syscall (esp on ARM w/ aligned instrs).
*/
pre_or_post_syscall = true;
#endif
}
}
instr_free(dcontext, &instr);
}
return pre_or_post_syscall;
}
/* i#1145: auto-restart syscalls interrupted by signals */
static bool
adjust_syscall_for_restart(dcontext_t *dcontext, thread_sig_info_t *info, int sig,
sigcontext_t *sc, fragment_t *f, reg_t orig_retval_reg)
{
byte *pc = (byte *)sc->SC_XIP;
int sys_inst_len;
if (sc->IF_X86_ELSE(SC_XAX, SC_R0) != -EINTR) {
/* The syscall succeeded, so no reason to interrupt.
* Some syscalls succeed on a signal coming in.
* E.g., SYS_wait4 on SIGCHLD, or reading from a slow device.
* XXX: Now that we pass SA_RESTART we should never get here?
*/
return false;
}
/* Don't restart if the app's handler says not to */
if (info->app_sigaction[sig] != NULL &&
!TEST(SA_RESTART, info->app_sigaction[sig]->flags)) {
return false;
}
/* XXX i#1145: some syscalls are never restarted when interrupted by a signal.
* We check those that are simple to distinguish below, but not all are. We have
* this under an option so it can be disabled if necessary.
*/
if (!DYNAMO_OPTION(restart_syscalls))
return false;
/* Now that we use SA_RESTART we rely on that and ignore our own
* inaccurate check sysnum_is_not_restartable(sysnum).
* SA_RESTART also means we can just be passed in the register value to restore.
*/
LOG(THREAD, LOG_ASYNCH, 2, "%s: restored xax/r0 to %ld\n", __FUNCTION__,
orig_retval_reg);
#ifdef X86
sc->SC_XAX = orig_retval_reg;
#elif defined(AARCHXX)
sc->SC_R0 = orig_retval_reg;
#else
# error NYI
#endif
/* Now adjust the pc to point at the syscall instruction instead of after it,
* so when we resume we'll go back to the syscall.
* Adjusting solves transparency as well: natively the kernel adjusts
* the pc before setting up the signal frame.
* We don't pass in the post-syscall pc provided by the kernel because
* we want the app pc, not the raw pc.
*/
dr_isa_mode_t isa_mode;
if (is_after_syscall_address(dcontext, pc) || pc == vsyscall_sysenter_return_pc) {
isa_mode = dr_get_isa_mode(dcontext);
} else {
/* We're going to walk back in the fragment, not gencode */
ASSERT(f != NULL);
isa_mode = FRAG_ISA_MODE(f->flags);
}
sys_inst_len = syscall_instr_length(isa_mode);
if (pc == vsyscall_sysenter_return_pc) {
#ifdef X86
sc->SC_XIP = (ptr_uint_t)(vsyscall_syscall_end_pc - sys_inst_len);
/* To restart sysenter we must re-copy xsp into xbp, as xbp is
* clobbered by the kernel.
* XXX: The kernel points at the int 0x80 in vsyscall on a restart
* and so doesn't have to do this: should we do that too? If so we'll
* have to avoid interpreting our own hook which is right after the
* int 0x80.
*/
sc->SC_XBP = sc->SC_XSP;
#else
ASSERT_NOT_REACHED();
#endif
} else if (is_after_syscall_address(dcontext, pc)) {
/* We're at do_syscall: point at app syscall instr. We want an app
* address b/c this signal will be delayed and the delivery will use
* a direct app context: no translation from the cache.
* The caller sets info->sigpending[sig]->use_sigcontext for us.
*/
sc->SC_XIP = (ptr_uint_t)(dcontext->asynch_target - sys_inst_len);
DODEBUG({
instr_t instr;
dr_isa_mode_t old_mode;
dr_set_isa_mode(dcontext, isa_mode, &old_mode);
instr_init(dcontext, &instr);
ASSERT(decode(dcontext, (app_pc)sc->SC_XIP, &instr) != NULL &&
instr_is_syscall(&instr));
instr_free(dcontext, &instr);
dr_set_isa_mode(dcontext, old_mode, NULL);
});
} else {
ASSERT_NOT_REACHED(); /* Inlined syscalls no longer come here. */
}
LOG(THREAD, LOG_ASYNCH, 2, "%s: sigreturn pc is now " PFX "\n", __FUNCTION__,
sc->SC_XIP);
return true;
}
/* XXX: Better to get this code inside arch/ but we'd have to convert to an mcontext
* which seems overkill.
*/
static fragment_t *
find_next_fragment_from_gencode(dcontext_t *dcontext, sigcontext_t *sc)
{
fragment_t *f = NULL;
fragment_t wrapper;
byte *pc = (byte *)sc->SC_XIP;
if (in_clean_call_save(dcontext, pc) || in_clean_call_restore(dcontext, pc)) {
#ifdef AARCHXX
f = fragment_pclookup(dcontext, (cache_pc)sc->SC_LR, &wrapper);
#elif defined(X86)
cache_pc retaddr = NULL;
/* Get the retaddr. We assume this is the adjustment used by
* insert_out_of_line_context_switch().
*/
byte *ra_slot =
dcontext->dstack - get_clean_call_switch_stack_size() - sizeof(retaddr);
/* The extra x86 slot is only there for save. */
if (in_clean_call_save(dcontext, pc))
ra_slot -= get_clean_call_temp_stack_size();
if (d_r_safe_read(ra_slot, sizeof(retaddr), &retaddr))
f = fragment_pclookup(dcontext, retaddr, &wrapper);
#else
# error Unsupported arch.
#endif
} else if (in_indirect_branch_lookup_code(dcontext, pc)) {
/* Try to find the target if the signal arrived in the IBL.
* We could try to be a lot more precise by hardcoding the IBL
* sequence here but that would make the code less maintainable.
* Instead we try the registers that hold the target app address.
*/
/* First check for the jmp* on the hit path: that is the only place
* in the ibl where the target tag is not sitting in a register.
*/
#if defined(X86) && defined(X64)
/* Optimization for the common case of targeting a prefix on x86_64:
* ff 61 08 jmp 0x08(%rcx)[8byte]
* The tag is in 0x0(%rcx) so we avoid a decode and pclookup.
*/
if (*pc == 0xff && *(pc + 1) == 0x61 && *(pc + 2) == 0x08) {
f = fragment_lookup(dcontext, *(app_pc *)sc->SC_XCX);
}
#endif
if (f == NULL) {
instr_t instr;
instr_init(dcontext, &instr);
decode_cti(dcontext, pc, &instr);
if (instr_is_ibl_hit_jump(&instr)) {
priv_mcontext_t mc;
sig_full_cxt_t sc_full = { sc, NULL /*not provided*/ };
sigcontext_to_mcontext(&mc, &sc_full, DR_MC_INTEGER | DR_MC_CONTROL);
byte *target;
if (opnd_is_memory_reference(instr_get_target(&instr))) {
target = instr_compute_address_priv(&instr, &mc);
ASSERT(target != NULL);
if (target != NULL)
target = *(byte **)target;
} else {
ASSERT(opnd_is_reg(instr_get_target(&instr)));
target = (byte *)reg_get_value_priv(
opnd_get_reg(instr_get_target(&instr)), &mc);
}
ASSERT(target != NULL);
if (target != NULL)
f = fragment_pclookup(dcontext, target, &wrapper);
/* I tried to hit this case running client.cleancallsig in a loop
* and while I could on x86 and x86_64 I never did on ARM or
* AArch64. We can remove this once someone hits it and it works.
*/
IF_AARCHXX(ASSERT_NOT_TESTED());
}
instr_free(dcontext, &instr);
}
#ifdef AARCHXX
/* The target is in r2 the whole time, w/ or w/o Thumb LSB. */
if (f == NULL && sc->SC_R2 != 0)
f = fragment_lookup(dcontext, ENTRY_PC_TO_DECODE_PC(sc->SC_R2));
#elif defined(X86)
/* The target is initially in xcx but is then copied to xbx. */
if (f == NULL && sc->SC_XBX != 0)
f = fragment_lookup(dcontext, (app_pc)sc->SC_XBX);
if (f == NULL && sc->SC_XCX != 0)
f = fragment_lookup(dcontext, (app_pc)sc->SC_XCX);
#else
# error Unsupported arch.
#endif
} else {
/* If in fcache_enter or do_syscall*, we stored the next_tag in asynch_target
* in d_r_dispatch. But, we need to avoid using the asynch_target for the
* fragment we just exited if we're in fcache_return.
*/
if (dcontext->asynch_target != NULL && !in_fcache_return(dcontext, pc))
f = fragment_lookup(dcontext, dcontext->asynch_target);
}
return f;
}
static void
record_pending_signal(dcontext_t *dcontext, int sig, kernel_ucontext_t *ucxt,
sigframe_rt_t *frame, bool forged _IF_CLIENT(byte *access_address))
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt);
/* XXX #1615: we need a full ucontext to store pre-xl8 simd values */
sigcontext_t sc_orig;
byte *pc = (byte *)sc->SC_XIP;
byte *xsp = (byte *)sc->SC_XSP;
bool receive_now = false;
bool blocked = false;
bool handled = false;
bool at_auto_restart_syscall = false;
int syslen = 0;
reg_t orig_retval_reg = sc->IF_X86_ELSE(SC_XAX, SC_R0);
sigpending_t *pend;
fragment_t *f = NULL;
fragment_t wrapper;
/* We no longer block SUSPEND_SIGNAL (i#184/PR 450670) or SIGSEGV (i#193/PR 287309).
* But we can have re-entrancy issues in this routine if the app uses the same
* SUSPEND_SIGNAL, or the nested SIGSEGV needs to be sent to the app. The
* latter shouldn't happen unless the app sends SIGSEGV via SYS_kill().
*/
if (ostd->processing_signal > 0 ||
/* If we interrupted receive_pending_signal() we can't prepend a new
* pending or delete an old b/c we might mess up the state so we
* just drop this one: should only happen for alarm signal
*/
(info->accessing_sigpending && !info->nested_pending_ok &&
/* we do want to report a crash in receive_pending_signal() */
(can_always_delay[sig] ||
is_sys_kill(dcontext, pc, (byte *)sc->SC_XSP, &frame->info)))) {
LOG(THREAD, LOG_ASYNCH, 1, "nested signal %d\n", sig);
ASSERT(ostd->processing_signal == 0 || sig == SUSPEND_SIGNAL || sig == SIGSEGV);
ASSERT(can_always_delay[sig] ||
is_sys_kill(dcontext, pc, (byte *)sc->SC_XSP, &frame->info));
/* To avoid re-entrant execution of special_heap_alloc() and of
* prepending to the pending list we just drop this signal.
* FIXME i#194/PR 453996: do better.
*/
STATS_INC(num_signals_dropped);
SYSLOG_INTERNAL_WARNING_ONCE("dropping nested signal");
return;
}
ostd->processing_signal++; /* no need for atomicity: thread-private */
/* First, check whether blocked, before we restore for sigsuspend (i#1340). */
if (kernel_sigismember(&info->app_sigblocked, sig))
blocked = true;
if (info->in_sigsuspend) {
/* sigsuspend ends when a signal is received, so restore the
* old blocked set
*/
info->app_sigblocked = info->app_sigblocked_save;
info->in_sigsuspend = false;
/* update the set to restore to post-signal-delivery */
#ifdef MACOS
ucxt->uc_sigmask = *(__darwin_sigset_t *)&info->app_sigblocked;
#else
ucxt->uc_sigmask = info->app_sigblocked;
#endif
#ifdef DEBUG
if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) {
LOG(THREAD, LOG_ASYNCH, 3, "after sigsuspend, blocked signals are now:\n");
dump_sigset(dcontext, &info->app_sigblocked);
}
#endif
}
if (get_at_syscall(dcontext))
syslen = syscall_instr_length(dr_get_isa_mode(dcontext));
if (info->app_sigaction[sig] != NULL &&
info->app_sigaction[sig]->handler ==
(handler_t)SIG_IGN
/* If a client registered a handler, put this in the queue.
* Races between registering, queueing, and delivering are fine.
*/
IF_CLIENT_INTERFACE(&&!dr_signal_hook_exists())) {
LOG(THREAD, LOG_ASYNCH, 3,
"record_pending_signal (%d at pc " PFX "): action is SIG_IGN!\n", sig, pc);
ostd->processing_signal--;
return;
} else if (blocked) {
/* signal is blocked by app, so just record it, don't receive now */
LOG(THREAD, LOG_ASYNCH, 2,
"record_pending_signal(%d at pc " PFX "): signal is currently blocked\n", sig,
pc);
IF_LINUX(handled = notify_signalfd(dcontext, info, sig, frame));
} else if (safe_is_in_fcache(dcontext, pc, xsp)) {
LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d) from cache pc " PFX "\n",
sig, pc);
if (forged || can_always_delay[sig]) {
/* to make translation easier, want to delay if can until d_r_dispatch
* unlink cur frag, wait for d_r_dispatch
*/
/* check for coarse first to avoid cost of coarse pclookup */
if (get_fcache_coarse_info(pc) != NULL) {
/* PR 213040: we can't unlink coarse. If we fail to translate
* we'll switch back to delaying, below.
*/
if (sig_is_alarm_signal(sig) && info->sigpending[sig] != NULL &&
info->sigpending[sig]->next != NULL && info->skip_alarm_xl8 > 0) {
/* Translating coarse fragments is very expensive so we
* avoid doing it when we're having trouble keeping up w/
* the alarm frequency (PR 213040), but we make sure we try
* every once in a while to avoid unbounded signal delay
*/
info->skip_alarm_xl8--;
STATS_INC(num_signals_coarse_delayed);
} else {
if (sig_is_alarm_signal(sig))
info->skip_alarm_xl8 = SKIP_ALARM_XL8_MAX;
receive_now = true;
LOG(THREAD, LOG_ASYNCH, 2,
"signal interrupted coarse fragment so delivering now\n");
}
} else {
f = fragment_pclookup(dcontext, pc, &wrapper);
ASSERT(f != NULL);
ASSERT(!TEST(FRAG_COARSE_GRAIN, f->flags)); /* checked above */
LOG(THREAD, LOG_ASYNCH, 2, "\tdelaying until exit F%d\n", f->id);
if (interrupted_inlined_syscall(dcontext, f, pc)) {
/* PR 596147: if delayable signal arrives after syscall-skipping
* jmp, either at syscall or post-syscall, we deliver
* immediately, since we can't bound the delay
*/
receive_now = true;
LOG(THREAD, LOG_ASYNCH, 2,
"signal interrupted pre/post syscall itself so delivering now\n");
/* We don't set at_auto_restart_syscall because we just leave
* the SA_RESTART kernel-supplied resumption point: with no
* post-syscall handler to worry about we have no need to
* change anything.
*/
} else {
/* could get another signal but should be in same fragment */
ASSERT(info->interrupted == NULL || info->interrupted == f);
if (info->interrupted != f) {
/* Just in case there's a prior, avoid leaving it unlinked. */
relink_interrupted_fragment(dcontext, info);
if (unlink_fragment_for_signal(dcontext, f, pc)) {
info->interrupted = f;
info->interrupted_pc = pc;
} else {
/* either was unlinked for trace creation, or we got another
* signal before exiting cache to handle 1st
*/
ASSERT(info->interrupted == NULL || info->interrupted == f);
}
}
}
}
} else {
/* the signal interrupted code cache => run handler now! */
receive_now = true;
LOG(THREAD, LOG_ASYNCH, 2, "\tnot certain can delay so handling now\n");
}
} else if (in_generated_routine(dcontext, pc) ||
/* XXX: should also check fine stubs */
safe_is_in_coarse_stubs(dcontext, pc, xsp)) {
/* Assumption: dynamo errors have been caught already inside
* the master_signal_handler, thus any error in a generated routine
* is an asynch signal that can be delayed
*/
LOG(THREAD, LOG_ASYNCH, 2,
"record_pending_signal(%d) from gen routine or stub " PFX "\n", sig, pc);
if (get_at_syscall(dcontext)) {
/* i#1206: the syscall was interrupted, so we can go back to d_r_dispatch
* and don't need to receive it now (which complicates post-syscall handling)
* w/o any extra delay.
*/
/* i#2659: we now use SA_RESTART to handle interrupting native
* auto-restart syscalls. That means we have to adjust do_syscall
* interruption to give us control so we can deliver the signal. Due to
* needing to run post-syscall handlers (we don't want to get into nested
* dcontexts like on Windows) it's simplest to go back to d_r_dispatch, which
* is most easily done by emulating the non-SA_RESTART behavior.
* XXX: This all seems backward: we should revisit this model and see if
* we can get rid of this emulation and the auto-restart emulation.
*/
/* The get_at_syscall() check above distinguishes from just having
* arrived at the syscall instr, but with SA_RESTART we can't distinguish
* not-yet-executed-syscall from syscall-was-interrupted-in-the-kernel.
* This matters for sigreturn (i#2995), whose asynch_target points somewhere
* other than right after the syscall, so we exclude it (it can't be
* interrupted so we know we haven't executed it yet).
*/
if (is_after_syscall_address(dcontext, pc + syslen) &&
!is_sigreturn_syscall_number(sc->SC_SYSNUM_REG)) {
LOG(THREAD, LOG_ASYNCH, 2,
"Adjusting interrupted auto-restart syscall from " PFX " to " PFX
"\n",
pc, pc + syslen);
at_auto_restart_syscall = true;
sc->SC_XIP += syslen;
sc->IF_X86_ELSE(SC_XAX, SC_R0) = -EINTR;
pc = (byte *)sc->SC_XIP;
}
}
/* This could come from another thread's SYS_kill (via our gen do_syscall) */
DOLOG(1, LOG_ASYNCH, {
if (!is_after_syscall_address(dcontext, pc) && !forged &&
!can_always_delay[sig]) {
LOG(THREAD, LOG_ASYNCH, 1,
"WARNING: signal %d in gen routine: may cause problems!\n", sig);
}
});
/* i#2019: for a signal arriving in gencode before entry to a fragment,
* we need to unlink the fragment just like for a signal arriving inside
* the fragment itself.
* Multiple signals should all have the same asynch_target so we should
* only need a single info->interrupted.
*/
if (info->interrupted == NULL && !get_at_syscall(dcontext)) {
f = find_next_fragment_from_gencode(dcontext, sc);
if (f != NULL && !TEST(FRAG_COARSE_GRAIN, f->flags)) {
if (unlink_fragment_for_signal(dcontext, f, FCACHE_ENTRY_PC(f))) {
info->interrupted = f;
info->interrupted_pc = FCACHE_ENTRY_PC(f);
}
}
}
} else if (get_at_syscall(dcontext) && pc == vsyscall_sysenter_return_pc - syslen &&
/* See i#2995 comment above: rule out sigreturn */
!is_sigreturn_syscall_number(sc->SC_SYSNUM_REG)) {
LOG(THREAD, LOG_ASYNCH, 2,
"record_pending_signal(%d) from restart-vsyscall " PFX "\n", sig, pc);
/* While the kernel points at int 0x80 for a restart, we leverage our
* existing sysenter restart mechanism.
*/
at_auto_restart_syscall = true;
sc->SC_XIP = (reg_t)vsyscall_sysenter_return_pc;
sc->IF_X86_ELSE(SC_XAX, SC_R0) = -EINTR;
pc = (byte *)sc->SC_XIP;
} else if (pc == vsyscall_sysenter_return_pc) {
LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d) from vsyscall " PFX "\n",
sig, pc);
/* i#1206: the syscall was interrupted but is not auto-restart, so we can go
* back to d_r_dispatch and don't need to receive it now (which complicates
* post-syscall handling)
*/
} else if (thread_synch_check_state(dcontext, THREAD_SYNCH_NO_LOCKS) &&
/* Avoid grabbing locks for xl8 while in a suspended state (i#3026). */
ksynch_get_value(&ostd->suspended) == 0) {
/* The signal interrupted DR or the client but it's at a safe spot so
* deliver it now.
*/
receive_now = true;
} else {
/* the signal interrupted DR itself => do not run handler now! */
LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d) from DR at pc " PFX "\n",
sig, pc);
if (!forged && !can_always_delay[sig] &&
!is_sys_kill(dcontext, pc, (byte *)sc->SC_XSP, &frame->info)) {
/* i#195/PR 453964: don't re-execute if will just re-fault.
* Our checks for dstack, etc. in master_signal_handler should
* have accounted for everything
*/
ASSERT_NOT_REACHED();
abort_on_DR_fault(dcontext, pc, NULL, sig, frame,
(sig == SIGSEGV) ? "SEGV" : "other", " unknown");
}
}
LOG(THREAD, LOG_ASYNCH, 3, "\taction is not SIG_IGN\n");
#if defined(X86) && defined(LINUX)
LOG(THREAD, LOG_ASYNCH, 3, "\tretaddr = " PFX "\n",
frame->pretcode); /* pretcode has same offs for plain */
#endif
if (receive_now) {
/* we need to translate sc before we know whether client wants to
* suppress, so we need a backup copy
*/
bool xl8_success;
ASSERT(!at_auto_restart_syscall); /* only used for delayed delivery */
sc_orig = *sc;
ASSERT(!forged);
/* cache the fragment since pclookup is expensive for coarse (i#658) */
f = fragment_pclookup(dcontext, (cache_pc)sc->SC_XIP, &wrapper);
xl8_success = translate_sigcontext(dcontext, ucxt, !can_always_delay[sig], f);
if (can_always_delay[sig] && !xl8_success) {
/* delay: we expect this for coarse fragments if alarm arrives
* in middle of ind branch region or sthg (PR 213040)
*/
LOG(THREAD, LOG_ASYNCH, 2,
"signal is in un-translatable spot in coarse fragment: delaying\n");
receive_now = false;
}
}
if (receive_now) {
/* N.B.: since we abandon the old context for synchronous signals,
* we do not need to mark this fragment as FRAG_CANNOT_DELETE
*/
#ifdef DEBUG
if (d_r_stats->loglevel >= 2 && (d_r_stats->logmask & LOG_ASYNCH) != 0 &&
safe_is_in_fcache(dcontext, pc, xsp)) {
ASSERT(f != NULL);
LOG(THREAD, LOG_ASYNCH, 2, "Got signal at pc " PFX " in this fragment:\n",
pc);
disassemble_fragment(dcontext, f, false);
}
#endif
LOG(THREAD, LOG_ASYNCH, 2, "Going to receive signal now\n");
/* If we end up executing the default action, we'll go native
* since we translated the context. If there's a handler,
* we'll copy the context to the app stack and then adjust the
* original on our stack so we take over.
*/
execute_handler_from_cache(dcontext, sig, frame, &sc_orig,
f _IF_CLIENT(access_address));
} else if (!handled) {
#ifdef CLIENT_INTERFACE
/* i#182/PR 449996: must let client act on blocked non-delayable signals to
* handle instrumentation faults. Make sure we're at a safe spot: i.e.,
* only raise for in-cache faults. Checking forged and no-delay
* to avoid the in-cache check for delayable signals => safer.
*/
if (blocked && !forged && !can_always_delay[sig] &&
safe_is_in_fcache(dcontext, pc, xsp)) {
dr_signal_action_t action;
/* cache the fragment since pclookup is expensive for coarse (i#658) */
f = fragment_pclookup(dcontext, (cache_pc)sc->SC_XIP, &wrapper);
sc_orig = *sc;
translate_sigcontext(dcontext, ucxt, true /*shouldn't fail*/, f);
/* make a copy before send_signal_to_client() tweaks it */
sigcontext_t sc_interrupted = *sc;
action = send_signal_to_client(dcontext, sig, frame, &sc_orig, access_address,
true /*blocked*/, f);
/* For blocked signal early event we disallow BYPASS (xref i#182/PR 449996) */
CLIENT_ASSERT(action != DR_SIGNAL_BYPASS,
"cannot bypass a blocked signal event");
if (!handle_client_action_from_cache(dcontext, sig, action, frame, &sc_orig,
&sc_interrupted, true /*blocked*/)) {
ostd->processing_signal--;
return;
}
/* restore original (untranslated) sc */
*get_sigcontext_from_rt_frame(frame) = sc_orig;
}
#endif
/* i#196/PR 453847: avoid infinite loop of signals if try to re-execute */
if (blocked && !can_always_delay[sig] &&
!is_sys_kill(dcontext, pc, (byte *)sc->SC_XSP, &frame->info)) {
ASSERT(default_action[sig] == DEFAULT_TERMINATE ||
default_action[sig] == DEFAULT_TERMINATE_CORE);
LOG(THREAD, LOG_ASYNCH, 1,
"blocked fatal signal %d cannot be delayed: terminating\n", sig);
sc_orig = *sc;
/* If forged we're likely couldbelinking, and we don't need to xl8. */
if (forged)
ASSERT(is_couldbelinking(dcontext));
else
translate_sigcontext(dcontext, ucxt, true /*shouldn't fail*/, NULL);
/* the process should be terminated */
execute_default_from_cache(dcontext, sig, frame, &sc_orig, forged);
ASSERT_NOT_REACHED();
}
/* Happened in DR, do not translate context. Record for later processing
* at a safe point with a clean app state.
*/
if (!blocked || sig >= OFFS_RT || (blocked && info->sigpending[sig] == NULL)) {
/* only have 1 pending for blocked non-rt signals */
/* to avoid accumulating signals if we're slow in presence of
* a high-rate itimer we only keep 2 alarm signals (PR 596768)
*/
if (sig_is_alarm_signal(sig)) {
if (info->sigpending[sig] != NULL &&
info->sigpending[sig]->next != NULL) {
ASSERT(info->sigpending[sig]->next->next == NULL);
/* keep the oldest, replace newer w/ brand-new one, for
* more spread-out alarms
*/
sigpending_t *temp = info->sigpending[sig];
info->sigpending[sig] = temp->next;
special_heap_free(info->sigheap, temp);
info->num_pending--;
LOG(THREAD, LOG_ASYNCH, 2, "3rd pending alarm %d => dropping 2nd\n",
sig);
STATS_INC(num_signals_dropped);
SYSLOG_INTERNAL_WARNING_ONCE("dropping 3rd pending alarm signal");
}
}
/* special heap alloc always uses sizeof(sigpending_t) blocks */
pend = special_heap_alloc(info->sigheap);
ASSERT(sig > 0 && sig <= MAX_SIGNUM);
info->num_pending++;
if (info->num_pending > DYNAMO_OPTION(max_pending_signals) &&
!info->multiple_pending_units)
info->multiple_pending_units = true;
if (info->num_pending >= DYNAMO_OPTION(max_pending_signals)) {
/* We're at the limit of our special heap: one more and it will try to
* allocate a new unit, which is unsafe as it acquires locks. We take
* several steps: we notify the user; we check for this on delivery as
* well and proactively allocate a new unit in a safer context.
* XXX: Perhaps we should drop some signals here?
*/
DO_ONCE({
char max_string[32];
snprintf(max_string, BUFFER_SIZE_ELEMENTS(max_string), "%d",
DYNAMO_OPTION(max_pending_signals));
NULL_TERMINATE_BUFFER(max_string);
SYSLOG(SYSLOG_WARNING, MAX_PENDING_SIGNALS, 3, get_application_name(),
get_application_pid(), max_string);
});
}
pend->next = info->sigpending[sig];
info->sigpending[sig] = pend;
pend->unblocked = !blocked;
/* FIXME: note that for asynchronous signals we don't need to
* bother to record exact machine context, even entire frame,
* since don't want to pass dynamo pc context to app handler.
* only copy frame for synchronous signals? those only
* happen while in cache? but for asynch, we would have to
* construct our own frame...kind of a pain.
*/
copy_frame_to_pending(dcontext, sig, frame _IF_CLIENT(access_address));
/* i#1145: check whether we should auto-restart an interrupted syscall */
if (at_auto_restart_syscall) {
/* Adjust the pending frame to restart the syscall, if applicable */
sigframe_rt_t *frame = &(info->sigpending[sig]->rt_frame);
sigcontext_t *sc_pend = get_sigcontext_from_rt_frame(frame);
if (adjust_syscall_for_restart(dcontext, info, sig, sc_pend, f,
orig_retval_reg)) {
/* We're going to re-start this syscall after we go
* back to d_r_dispatch, run the post-syscall handler (for -EINTR),
* and deliver the signal. We've adjusted the sigcontext
* for re-start on the sigreturn, but we need to tell
* execute_handler_from_dispatch() to use our sigcontext
* and not the mcontext.
* A client will see a second set of pre + post handlers for
* the restart, which seems reasonable, given the signal in
* between.
*/
info->sigpending[sig]->use_sigcontext = true;
}
}
} else {
/* For clients, we document that we do not pass to them
* unless we're prepared to deliver to app. We would have
* to change our model to pass them non-final-translated
* contexts for delayable signals in order to give them
* signals as soon as they come in. Xref i#182/PR 449996.
*/
LOG(THREAD, LOG_ASYNCH, 3,
"\tnon-rt signal already in queue, ignoring this one!\n");
}
if (!blocked && !dcontext->signals_pending)
dcontext->signals_pending = 1;
}
ostd->processing_signal--;
}
/* Distinguish SYS_kill-generated from instruction-generated signals.
* If sent from another process we can't tell, but if sent from this
* thread the interruption point should be our own post-syscall.
* FIXME PR 368277: for other threads in same process we should set a flag
* and identify them as well.
* FIXME: for faults like SIGILL we could examine the interrupted pc
* to see whether it is capable of generating such a fault (see code
* used in handle_nudge_signal()).
*/
static bool
is_sys_kill(dcontext_t *dcontext, byte *pc, byte *xsp, kernel_siginfo_t *info)
{
#if !defined(VMX86_SERVER) && !defined(MACOS) /* does not use SI_KERNEL */
/* i#133: use si_code to distinguish user-sent signals.
* Even 2.2 Linux kernel supports <=0 meaning user-sent (except
* SIGIO) so we assume we can rely on it.
*/
if (info->si_code <= 0)
return true;
#endif
return (is_at_do_syscall(dcontext, pc, xsp) &&
(dcontext->sys_num == SYS_kill ||
#ifdef LINUX
dcontext->sys_num == SYS_tkill || dcontext->sys_num == SYS_tgkill ||
dcontext->sys_num == SYS_rt_sigqueueinfo
#elif defined(MACOS)
dcontext->sys_num == SYS___pthread_kill
#endif
));
}
static byte *
compute_memory_target(dcontext_t *dcontext, cache_pc instr_cache_pc,
kernel_ucontext_t *uc, kernel_siginfo_t *si, bool *write)
{
sigcontext_t *sc = SIGCXT_FROM_UCXT(uc);
byte *target = NULL;
instr_t instr;
priv_mcontext_t mc;
uint memopidx, memoppos, memopsize;
opnd_t memop;
bool found_target = false;
bool in_maps;
bool use_allmem = false;
uint prot;
IF_ARM(dr_isa_mode_t old_mode;)
LOG(THREAD, LOG_ALL, 2,
"computing memory target for " PFX " causing SIGSEGV, kernel claims it is " PFX
"\n",
instr_cache_pc, (byte *)si->si_addr);
/* ARM's sigcontext_t has a "fault_address" field but it also seems unreliable */
IF_ARM(LOG(THREAD, LOG_ALL, 2, "fault_address: " PFX "\n", sc->fault_address));
/* We used to do a memory query to check if instr_cache_pc is readable, but
* now we use TRY/EXCEPT because we don't have the instr length and the OS
* query is expensive. If decoding faults, the signal handler will longjmp
* out before it calls us recursively.
*/
instr_init(dcontext, &instr);
IF_ARM({
/* Be sure to use the interrupted mode and not the last-dispatch mode */
dr_set_isa_mode(dcontext, get_pc_mode_from_cpsr(sc), &old_mode);
});
TRY_EXCEPT(dcontext, { decode(dcontext, instr_cache_pc, &instr); },
{
return NULL; /* instr_cache_pc was unreadable */
});
IF_ARM(dr_set_isa_mode(dcontext, old_mode, NULL));
if (!instr_valid(&instr)) {
LOG(THREAD, LOG_ALL, 2,
"WARNING: got SIGSEGV for invalid instr at cache pc " PFX "\n",
instr_cache_pc);
ASSERT_NOT_REACHED();
instr_free(dcontext, &instr);
return NULL;
}
ucontext_to_mcontext(&mc, uc);
ASSERT(write != NULL);
/* i#1009: If si_addr is plausibly one of the memory operands of the
* faulting instruction, assume the target was si_addr. If none of the
* memops match, fall back to checking page protections, which can be racy.
* For si_addr == NULL, we fall back to the protection check because it's
* too likely to be a valid memop and we can live with a race on a page that
* is typically unmapped.
*/
if (si->si_code == SEGV_ACCERR && si->si_addr != NULL) {
for (memopidx = 0; instr_compute_address_ex_priv(&instr, &mc, memopidx, &target,
write, &memoppos);
memopidx++) {
/* i#1045: check whether operand and si_addr overlap */
memop = *write ? instr_get_dst(&instr, memoppos)
: instr_get_src(&instr, memoppos);
memopsize = opnd_size_in_bytes(opnd_get_size(memop));
LOG(THREAD, LOG_ALL, 2, "memory operand %u has address " PFX " and size %u\n",
memopidx, target, memopsize);
if ((byte *)si->si_addr >= target &&
(byte *)si->si_addr < target + memopsize) {
target = (byte *)si->si_addr;
found_target = true;
break;
}
}
}
/* For fcache faults, use all_memory_areas, which is faster but acquires
* locks. If it's possible we're in DR, go to the OS to avoid deadlock.
*/
if (DYNAMO_OPTION(use_all_memory_areas)) {
use_allmem = safe_is_in_fcache(dcontext, instr_cache_pc, (byte *)sc->SC_XSP);
}
if (!found_target) {
if (si->si_addr != NULL) {
LOG(THREAD, LOG_ALL, 3, "%s: falling back to racy protection checks\n",
__FUNCTION__);
}
/* i#115/PR 394984: consider all memops */
for (memopidx = 0;
instr_compute_address_ex_priv(&instr, &mc, memopidx, &target, write, NULL);
memopidx++) {
if (use_allmem) {
in_maps = get_memory_info(target, NULL, NULL, &prot);
} else {
in_maps = get_memory_info_from_os(target, NULL, NULL, &prot);
}
if ((!in_maps || !TEST(MEMPROT_READ, prot)) ||
(*write && !TEST(MEMPROT_WRITE, prot))) {
found_target = true;
break;
}
}
}
if (!found_target) {
/* probably an NX fault: how tell whether kernel enforcing? */
in_maps = get_memory_info_from_os(instr_cache_pc, NULL, NULL, &prot);
if (!in_maps || !TEST(MEMPROT_EXEC, prot)) {
target = instr_cache_pc;
found_target = true;
}
}
/* we may still not find target, e.g. for SYS_kill(SIGSEGV) */
if (!found_target)
target = NULL;
DOLOG(2, LOG_ALL, {
LOG(THREAD, LOG_ALL, 2,
"For SIGSEGV at cache pc " PFX ", computed target %s " PFX "\n",
instr_cache_pc, *write ? "write" : "read", target);
d_r_loginst(dcontext, 2, &instr, "\tfaulting instr");
});
instr_free(dcontext, &instr);
return target;
}
/* If native_state is true, assumes the fault is not in the cache and thus
* does not need translation but rather should always be re-executed.
*/
static bool
check_for_modified_code(dcontext_t *dcontext, cache_pc instr_cache_pc,
kernel_ucontext_t *uc, byte *target, bool native_state)
{
/* special case: we expect a seg fault for executable regions
* that were writable and marked read-only by us.
* have to figure out the target address!
* unfortunately the OS doesn't tell us, nor whether it's a write.
* FIXME: if sent from SYS_kill(SIGSEGV), the pc will be post-syscall,
* and if that post-syscall instr is a write that could have faulted,
* how can we tell the difference?
*/
if (was_executable_area_writable(target)) {
/* translate instr_cache_pc to original app pc
* DO NOT use translate_sigcontext, don't want to change the
* signal frame or else we'll lose control when we try to
* return to signal pc!
*/
app_pc next_pc, translated_pc = NULL;
fragment_t *f = NULL;
fragment_t wrapper;
ASSERT((cache_pc)SIGCXT_FROM_UCXT(uc)->SC_XIP == instr_cache_pc);
if (!native_state) {
/* For safe recreation we need to either be couldbelinking or hold
* the initexit lock (to keep someone from flushing current
* fragment), the initexit lock is easier
*/
d_r_mutex_lock(&thread_initexit_lock);
/* cache the fragment since pclookup is expensive for coarse units (i#658) */
f = fragment_pclookup(dcontext, instr_cache_pc, &wrapper);
translated_pc = recreate_app_pc(dcontext, instr_cache_pc, f);
ASSERT(translated_pc != NULL);
d_r_mutex_unlock(&thread_initexit_lock);
}
next_pc =
handle_modified_code(dcontext, instr_cache_pc, translated_pc, target, f);
if (!native_state) {
/* going to exit from middle of fragment (at the write) so will mess up
* trace building
*/
if (is_building_trace(dcontext)) {
LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n");
trace_abort(dcontext);
}
}
if (next_pc == NULL) {
/* re-execute the write -- just have master_signal_handler return */
return true;
} else {
ASSERT(!native_state);
/* Do not resume execution in cache, go back to d_r_dispatch. */
transfer_from_sig_handler_to_fcache_return(
dcontext, uc, NULL, SIGSEGV, next_pc,
(linkstub_t *)get_selfmod_linkstub(), false);
/* now have master_signal_handler return */
return true;
}
}
return false;
}
#ifndef HAVE_SIGALTSTACK
/* The exact layout of this struct is relied on in master_signal_handler()
* in x86.asm.
*/
struct clone_and_swap_args {
byte *stack;
byte *tos;
};
/* Helper function for swapping handler to dstack */
bool
sig_should_swap_stack(struct clone_and_swap_args *args, kernel_ucontext_t *ucxt)
{
byte *cur_esp;
dcontext_t *dcontext = get_thread_private_dcontext();
if (dcontext == NULL)
return false;
GET_STACK_PTR(cur_esp);
if (!is_on_dstack(dcontext, cur_esp)) {
sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt);
/* Pass back the proper args to clone_and_swap_stack: we want to
* copy to dstack from the tos at the signal interruption point.
*/
args->stack = dcontext->dstack;
/* leave room for fpstate */
args->stack -= signal_frame_extra_size(true);
args->stack = (byte *)ALIGN_BACKWARD(args->stack, XSTATE_ALIGNMENT);
args->tos = (byte *)sc->SC_XSP;
return true;
} else
return false;
}
#endif
/* Helper that takes over the current thread signaled via SUSPEND_SIGNAL. Kept
* separate mostly to keep the priv_mcontext_t allocation out of
* master_signal_handler_C.
* If it returns, it returns false, and the signal should be squashed.
*/
static bool
sig_take_over(kernel_ucontext_t *uc)
{
priv_mcontext_t mc;
ucontext_to_mcontext(&mc, uc);
/* We don't want our own blocked signals: we want the app's, stored in the frame. */
if (!os_thread_take_over(&mc, SIGMASK_FROM_UCXT(uc)))
return false;
ASSERT_NOT_REACHED(); /* shouldn't return */
return true; /* make compiler happy */
}
static bool
is_safe_read_ucxt(kernel_ucontext_t *ucxt)
{
app_pc pc = (app_pc)SIGCXT_FROM_UCXT(ucxt)->SC_XIP;
return is_safe_read_pc(pc);
}
/* the master signal handler
* WARNING: behavior varies with different versions of the kernel!
* sigaction support was only added with 2.2
*/
#ifndef X86_32
/* stub in x86.asm passes our xsp to us */
# ifdef MACOS
void
master_signal_handler_C(handler_t handler, int style, int sig, kernel_siginfo_t *siginfo,
kernel_ucontext_t *ucxt, byte *xsp)
# else
void
master_signal_handler_C(int sig, kernel_siginfo_t *siginfo, kernel_ucontext_t *ucxt,
byte *xsp)
# endif
#else
/* On ia32, adding a parameter disturbs the frame we're trying to capture, so we
* add an intermediate frame and read the normal params off the stack directly.
*/
void
master_signal_handler_C(byte *xsp)
#endif
{
#ifdef MACOS64
/* The kernel aligns to 16 after setting up the frame, so we instead compute
* from the siginfo pointer.
* XXX: 32-bit does the same thing: how was it working?!?
*/
sigframe_rt_t *frame = (sigframe_rt_t *)((byte *)siginfo - sizeof(frame->mc));
/* The kernel's method of aligning overshoots. */
# define KERNEL_ALIGN_BACK(val, align) (((val)-align) & -(align))
/* If this assert fails, we may be seeing an AVX512 frame. */
ASSERT(KERNEL_ALIGN_BACK((ptr_uint_t)frame, 16) - 8 == (ptr_uint_t)xsp &&
"AVX512 frames not yet supported");
#else
sigframe_rt_t *frame = (sigframe_rt_t *)xsp;
#endif
#ifdef X86_32
/* Read the normal arguments from the frame. */
int sig = frame->sig;
kernel_siginfo_t *siginfo = frame->pinfo;
kernel_ucontext_t *ucxt = frame->puc;
#endif /* !X64 */
sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt);
thread_record_t *tr;
#ifdef DEBUG
uint level = 2;
# if !defined(HAVE_MEMINFO)
/* avoid logging every single TRY probe fault */
if (!dynamo_initialized)
level = 5;
# endif
#endif
bool local;
#if defined(MACOS) && !defined(X64)
/* The kernel clears fs, so we have to re-instate our selector, if
* it was set in the first place.
*/
if (sc->__ss.__fs != 0)
tls_reinstate_selector(sc->__ss.__fs);
#endif
#ifdef X86
/* i#2089: For is_thread_tls_initialized() we need a safe_read path that does not
* do any logging or call get_thread_private_dcontext() as those will recurse.
* This path is global so there's no SELF_PROTECT_LOCAL and we also bypass
* the ENTERING_DR() for this short path.
*/
if (sig == SIGSEGV && sc->SC_XIP == (ptr_uint_t)safe_read_tls_magic) {
sc->SC_RETURN_REG = 0;
sc->SC_XIP = (reg_t)safe_read_tls_magic_recover;
return;
} else if (sig == SIGSEGV && sc->SC_XIP == (ptr_uint_t)safe_read_tls_self) {
sc->SC_RETURN_REG = 0;
sc->SC_XIP = (reg_t)safe_read_tls_self_recover;
return;
} else if (sig == SIGSEGV && sc->SC_XIP == (ptr_uint_t)safe_read_tls_app_self) {
sc->SC_RETURN_REG = 0;
sc->SC_XIP = (reg_t)safe_read_tls_app_self_recover;
return;
}
#endif
/* We are dropping asynchronous signals during detach. The thread may already have
* lost its TLS (xref i#3535). A safe read may result in a crash if DR's SIGSEGV
* handler is removed before the safe read's SIGSEGV is delivered.
*
* Note that besides dropping potentially important signals, there is still a small
* race window if the signal gets delivered after the detach has finished, i.e.
* doing detach is false. This is an issue in particular if the app has started
* re-attaching.
*
* Signals that are not clearly asynchronous may hit corner case(s) of i#3535.
* (xref i#26).
*/
if (doing_detach && can_always_delay[sig]) {
DOLOG(1, LOG_ASYNCH, { dump_sigcontext(GLOBAL_DCONTEXT, sc); });
SYSLOG_INTERNAL_ERROR("ERROR: master_signal_handler with unreliable dcontext "
"during detach. Signal will be dropped and we're continuing"
" (i#3535?): tid=%d, sig=%d",
get_sys_thread_id(), sig);
return;
}
dcontext_t *dcontext = get_thread_private_dcontext();
#ifdef MACOS
# ifdef X64
ASSERT((YMM_ENABLED() && ucxt->uc_mcsize == sizeof(_STRUCT_MCONTEXT_AVX64)) ||
(!YMM_ENABLED() && ucxt->uc_mcsize == sizeof(_STRUCT_MCONTEXT64)));
# else
ASSERT((YMM_ENABLED() && ucxt->uc_mcsize == sizeof(_STRUCT_MCONTEXT_AVX32)) ||
(!YMM_ENABLED() && ucxt->uc_mcsize == sizeof(_STRUCT_MCONTEXT)));
# endif
#endif
/* i#350: To support safe_read or TRY_EXCEPT without a dcontext, use the
* global dcontext
* when handling safe_read faults. This lets us pass the check for a
* dcontext below and causes us to use the global log.
*/
if (dcontext == NULL && (sig == SIGSEGV || sig == SIGBUS) &&
(is_safe_read_ucxt(ucxt) ||
(!dynamo_initialized && global_try_except.try_except_state != NULL))) {
dcontext = GLOBAL_DCONTEXT;
}
if (dynamo_exited && d_r_get_num_threads() > 1 && sig == SIGSEGV) {
/* PR 470957: this is almost certainly a race so just squelch it.
* We live w/ the risk that it was holding a lock our release-build
* exit code needs.
*/
exit_thread_syscall(1);
}
/* FIXME: ensure the path for recording a pending signal does not grab any DR locks
* that could have been interrupted
* e.g., synchronize_dynamic_options grabs the stats_lock!
*/
if (sig == SUSPEND_SIGNAL) {
if (proc_get_vendor() == VENDOR_AMD) {
/* i#3356: Work around an AMD processor bug where it does not clear the
* hidden gs base when the gs selector is written. Pre-4.7 Linux kernels
* leave the prior thread's base in place on a switch due to this.
* We can thus come here and get the wrong dcontext on attach; worse,
* we can get NULL here but the wrong one later during init. It's
* safest to just set a non-zero value (the kernel ignores zero) for all
* unknown threads here. There are no problems for non-attach takeover.
*/
if (dcontext == NULL || dcontext->owning_thread != get_sys_thread_id()) {
/* tls_thread_preinit() further rules out a temp-native dcontext
* and avoids clobbering it, to preserve the thread_lookup() case
* below (which we do not want to run first as we could swap to
* the incorrect dcontext midway through it).
*/
if (!tls_thread_preinit()) {
SYSLOG_INTERNAL_ERROR_ONCE("ERROR: Failed to work around AMD context "
"switch bug #3356: crashes or "
"hangs may ensue...");
}
dcontext = NULL;
}
}
}
if (dcontext == NULL &&
/* Check for a temporarily-native thread we're synch-ing with. */
(sig == SUSPEND_SIGNAL
#ifdef X86
|| (INTERNAL_OPTION(safe_read_tls_init) &&
/* Check for whether this is a thread with its invalid sentinel magic set.
* In this case, we assume that it is either a thread that is currently
* temporarily-native via API like DR_EMIT_GO_NATIVE, or a thread in the
* clone window. We know by inspection of our own code that it is safe to
* call thread_lookup for either case thread makes a clone or was just
* cloned. i.e. thread_lookup requires a lock that must not be held by the
* calling thread (i#2921).
* XXX: what is ARM doing, any special case w/ dcontext == NULL?
*/
safe_read_tls_magic() == TLS_MAGIC_INVALID)
#endif
)) {
tr = thread_lookup(get_sys_thread_id());
if (tr != NULL)
dcontext = tr->dcontext;
}
if (dcontext == NULL ||
(dcontext != GLOBAL_DCONTEXT &&
(dcontext->signal_field == NULL ||
!((thread_sig_info_t *)dcontext->signal_field)->fully_initialized))) {
/* FIXME: || !intercept_asynch, or maybe !under_our_control */
/* FIXME i#26: this could be a signal arbitrarily sent to this thread.
* We could try to route it to another thread, using a global queue
* of pending signals. But what if it was targeted to this thread
* via SYS_{tgkill,tkill}? Can we tell the difference, even if
* we watch the kill syscalls: could come from another process?
*/
if (sig_is_alarm_signal(sig)) {
/* assuming an alarm during thread exit or init (xref PR 596127,
* i#359): suppressing is fine
*/
} else if (sig == SUSPEND_SIGNAL && dcontext == NULL) {
/* We sent SUSPEND_SIGNAL to a thread we don't control (no
* dcontext), which means we want to take over.
*/
ASSERT(!doing_detach);
if (!sig_take_over(ucxt))
return;
ASSERT_NOT_REACHED(); /* else, shouldn't return */
} else {
/* Using global dcontext because dcontext is NULL here. */
DOLOG(1, LOG_ASYNCH, { dump_sigcontext(GLOBAL_DCONTEXT, sc); });
SYSLOG_INTERNAL_ERROR("ERROR: master_signal_handler with no siginfo "
"(i#26?): tid=%d, sig=%d",
get_sys_thread_id(), sig);
}
/* see FIXME comments above.
* workaround for now: suppressing is better than dying.
*/
if (can_always_delay[sig])
return;
REPORT_FATAL_ERROR_AND_EXIT(FAILED_TO_HANDLE_SIGNAL, 2, get_application_name(),
get_application_pid());
}
/* we may be entering dynamo from code cache! */
/* Note that this is unsafe if -single_thread_in_DR => we grab a lock =>
* hang if signal interrupts DR: but we don't really support that option
*/
ENTERING_DR();
if (dcontext == GLOBAL_DCONTEXT) {
local = false;
tr = thread_lookup(get_sys_thread_id());
} else {
tr = dcontext->thread_record;
local = local_heap_protected(dcontext);
if (local)
SELF_PROTECT_LOCAL(dcontext, WRITABLE);
}
/* i#1921: For proper native execution with re-takeover we need to propagate
* signals to app handlers while native. For now we do not support re-takeover
* and we give up our handlers via signal_remove_handlers().
*/
ASSERT(tr == NULL || tr->under_dynamo_control || IS_CLIENT_THREAD(dcontext) ||
sig == SUSPEND_SIGNAL);
LOG(THREAD, LOG_ASYNCH, level,
"\nmaster_signal_handler: thread=%d, sig=%d, xsp=" PFX ", retaddr=" PFX "\n",
get_sys_thread_id(), sig, xsp, *((byte **)xsp));
LOG(THREAD, LOG_ASYNCH, level + 1,
"siginfo: sig = %d, pid = %d, status = %d, errno = %d, si_code = %d\n",
siginfo->si_signo, siginfo->si_pid, siginfo->si_status, siginfo->si_errno,
siginfo->si_code);
DOLOG(level + 1, LOG_ASYNCH, { dump_sigcontext(dcontext, sc); });
#if defined(X86_32) && !defined(VMX86_SERVER) && defined(LINUX)
/* FIXME case 6700: 2.6.9 (FC3) kernel sets up our frame with a pretcode
* of 0x440. This happens if our restorer is unspecified (though 2.6.9
* src code shows setting the restorer to a default value in that case...)
* or if we explicitly point at dynamorio_sigreturn. I couldn't figure
* out why it kept putting 0x440 there. So we fix the issue w/ this
* hardcoded return.
* This hack causes vmkernel to kill the process on sigreturn due to
* vmkernel's non-standard sigreturn semantics. PR 404712.
*/
*((byte **)xsp) = (byte *)dynamorio_sigreturn;
#endif
/* N.B.:
* ucontext_t is defined in two different places. The one we get
* included is /usr/include/sys/ucontext.h, which would have us
* doing this:
* void *pc = (void *) ucxt->uc_mcontext.gregs[EIP];
* However, EIP is not defined for us (used to be in older
* RedHat version) unless we define __USE_GNU, which we don't want to do
* for other reasons, so we'd have to also say:
* #define EIP 14
* Instead we go by the ucontext_t definition in
* /usr/include/asm/ucontext.h, which has it containing a sigcontext struct,
* defined in /usr/include/asm/sigcontext.h. This is the definition used
* by the kernel. The two definitions are field-for-field
* identical except that the sys one has an fpstate struct at the end --
* but the next field in the frame is an fpstate. The only mystery
* is why the rt frame is declared as ucontext instead of sigcontext.
* The kernel's version of ucontext must be the asm one!
* And the sys one grabs the next field of the frame.
* Also note that mcontext_t.fpregs == sigcontext.fpstate is NULL if
* floating point operations have not been used (lazy fp state saving).
* Also, sigset_t has different sizes according to kernel (8 bytes) vs.
* glibc (128 bytes?).
*/
switch (sig) {
case SIGBUS: /* PR 313665: look for DR crashes on unaligned memory or mmap bounds */
case SIGSEGV: {
/* Older kernels do NOT fill out the signal-specific fields of siginfo,
* except for SIGCHLD. Thus we cannot do this:
* void *pc = (void*) siginfo->si_addr;
* Thus we must use the third argument, which is a ucontext_t (see above)
*/
void *pc = (void *)sc->SC_XIP;
bool syscall_signal = false; /* signal came from syscall? */
bool is_write = false;
byte *target;
bool is_DR_exception = false;
#ifdef SIDELINE
if (dcontext == NULL) {
SYSLOG_INTERNAL_ERROR("seg fault in sideline thread -- NULL dcontext!");
ASSERT_NOT_REACHED();
}
#endif
if (is_safe_read_ucxt(ucxt) ||
(!dynamo_initialized && global_try_except.try_except_state != NULL) ||
dcontext->try_except.try_except_state != NULL) {
/* handle our own TRY/EXCEPT */
try_except_context_t *try_cxt;
#ifdef HAVE_MEMINFO
/* our probe produces many of these every run */
/* since we use for safe_*, making a _ONCE */
SYSLOG_INTERNAL_WARNING_ONCE("(1+x) Handling our fault in a TRY at " PFX, pc);
#endif
LOG(THREAD, LOG_ALL, level, "TRY fault at " PFX "\n", pc);
if (TEST(DUMPCORE_TRY_EXCEPT, DYNAMO_OPTION(dumpcore_mask)))
os_dump_core("try/except fault");
if (is_safe_read_ucxt(ucxt)) {
sc->SC_XIP = (reg_t)safe_read_resume_pc();
/* Break out to log the normal return from the signal handler.
*/
break;
}
try_cxt = (dcontext != NULL) ? dcontext->try_except.try_except_state
: global_try_except.try_except_state;
ASSERT(try_cxt != NULL);
/* The exception interception code did an ENTER so we must EXIT here */
EXITING_DR();
/* Since we have no sigreturn we have to restore the mask
* manually, just like siglongjmp(). i#226/PR 492568: we rely
* on the kernel storing the prior mask in ucxt, so we do not
* need to store it on every setjmp.
*/
/* Verify that there's no scenario where the mask gets changed prior
* to a fault inside a try. This relies on dr_setjmp_sigmask() filling
* in the mask, which we only bother to do in debug build.
*/
ASSERT(memcmp(&try_cxt->context.sigmask, &ucxt->uc_sigmask,
sizeof(ucxt->uc_sigmask)) == 0);
sigprocmask_syscall(SIG_SETMASK, SIGMASK_FROM_UCXT(ucxt), NULL,
sizeof(ucxt->uc_sigmask));
DR_LONGJMP(&try_cxt->context, LONGJMP_EXCEPTION);
ASSERT_NOT_REACHED();
}
target = compute_memory_target(dcontext, pc, ucxt, siginfo, &is_write);
#ifdef CLIENT_INTERFACE
if (CLIENTS_EXIST() && is_in_client_lib(pc)) {
/* i#1354: client might write to a page we made read-only.
* If so, handle the fault and re-execute it, if it's safe to do so
* (we document these criteria under DR_MEMPROT_PRETEND_WRITE).
*/
if (is_write && !is_couldbelinking(dcontext) && OWN_NO_LOCKS(dcontext) &&
check_for_modified_code(dcontext, pc, ucxt, target, true /*native*/))
break;
abort_on_fault(dcontext, DUMPCORE_CLIENT_EXCEPTION, pc, target, sig, frame,
exception_label_client, (sig == SIGSEGV) ? "SEGV" : "BUS",
" client library");
ASSERT_NOT_REACHED();
}
#endif
/* For !HAVE_MEMINFO, we cannot compute the target until
* after the try/except check b/c compute_memory_target()
* calls get_memory_info_from_os() which does a probe: and the
* try/except could be from a probe itself. A try/except that
* triggers a stack overflow should recover on the longjmp, so
* this order should be fine.
*/
/* FIXME: share code with Windows callback.c */
/* FIXME PR 205795: in_fcache and is_dynamo_address do grab locks! */
if ((is_on_dstack(dcontext, (byte *)sc->SC_XSP)
/* PR 302951: clean call arg processing => pass to app/client.
* Rather than call the risky in_fcache we check whereami. */
IF_CLIENT_INTERFACE(&&(dcontext->whereami != DR_WHERE_FCACHE))) ||
is_on_alt_stack(dcontext, (byte *)sc->SC_XSP) ||
is_on_initstack((byte *)sc->SC_XSP)) {
/* Checks here need to cover everything that record_pending_signal()
* thinks is non-fcache, non-gencode: else that routine will kill
* process since can't delay or re-execute (i#195/PR 453964).
*/
is_DR_exception = true;
} else if (!safe_is_in_fcache(dcontext, pc, (byte *)sc->SC_XSP) &&
(in_generated_routine(dcontext, pc) ||
is_at_do_syscall(dcontext, pc, (byte *)sc->SC_XSP) ||
is_dynamo_address(pc))) {
#ifdef CLIENT_INTERFACE
if (!in_generated_routine(dcontext, pc) &&
!is_at_do_syscall(dcontext, pc, (byte *)sc->SC_XSP)) {
/* PR 451074: client needs a chance to handle exceptions in its
* own gencode. client_exception_event() won't return if client
* wants to re-execute faulting instr.
*/
sigcontext_t sc_interrupted = *get_sigcontext_from_rt_frame(frame);
dr_signal_action_t action = send_signal_to_client(
dcontext, sig, frame, sc, target, false /*!blocked*/, NULL);
if (action != DR_SIGNAL_DELIVER && /* for delivery, continue below */
!handle_client_action_from_cache(dcontext, sig, action, frame, sc,
&sc_interrupted,
false /*!blocked*/)) {
/* client handled fault */
break;
}
}
#endif
is_DR_exception = true;
}
if (is_DR_exception) {
/* kill(getpid(), SIGSEGV) looks just like a SIGSEGV in the store of eax
* to mcontext after the syscall instr in do_syscall -- try to distinguish:
*/
if (is_sys_kill(dcontext, pc, (byte *)sc->SC_XSP, siginfo)) {
LOG(THREAD, LOG_ALL, 2,
"assuming SIGSEGV at post-do-syscall is kill, not our write fault\n");
syscall_signal = true;
}
if (!syscall_signal) {
if (check_in_last_thread_vm_area(dcontext, target)) {
/* See comments in callback.c as well.
* FIXME: try to share code
*/
SYSLOG_INTERNAL_WARNING("(decode) exception in last area, "
"DR pc=" PFX ", app pc=" PFX,
pc, target);
STATS_INC(num_exceptions_decode);
if (is_building_trace(dcontext)) {
LOG(THREAD, LOG_ASYNCH, 2,
"intercept_exception: "
"squashing old trace\n");
trace_abort(dcontext);
}
/* we do get faults when not building a bb: e.g.,
* ret_after_call_check does decoding (case 9396) */
if (dcontext->bb_build_info != NULL) {
/* must have been building a bb at the time */
bb_build_abort(dcontext, true /*clean vm area*/, true /*unlock*/);
}
/* Since we have no sigreturn we have to restore the mask manually */
unblock_all_signals(NULL);
/* Let's pass it back to the application - memory is unreadable */
if (TEST(DUMPCORE_FORGE_UNREAD_EXEC, DYNAMO_OPTION(dumpcore_mask)))
os_dump_core("Warning: Racy app execution (decode unreadable)");
os_forge_exception(target, UNREADABLE_MEMORY_EXECUTION_EXCEPTION);
ASSERT_NOT_REACHED();
} else {
abort_on_DR_fault(dcontext, pc, target, sig, frame,
(sig == SIGSEGV) ? "SEGV" : "BUS",
in_generated_routine(dcontext, pc) ? " generated"
: "");
}
}
}
/* if get here, pass the signal to the app */
ASSERT(pc != 0); /* shouldn't get here */
if (sig == SIGSEGV && !syscall_signal /*only for in-cache signals*/) {
/* special case: we expect a seg fault for executable regions
* that were writable and marked read-only by us.
*/
if (is_write &&
check_for_modified_code(dcontext, pc, ucxt, target, false /*!native*/)) {
/* it was our signal, so don't pass to app -- return now */
break;
}
}
/* pass it to the application (or client) */
LOG(THREAD, LOG_ALL, 1,
"** Received SIG%s at cache pc " PFX " in thread " TIDFMT "\n",
(sig == SIGSEGV) ? "SEGV" : "BUS", pc, d_r_get_thread_id());
ASSERT(syscall_signal || safe_is_in_fcache(dcontext, pc, (byte *)sc->SC_XSP));
/* we do not call trace_abort() here since we may need to
* translate from a temp private bb (i#376): but all paths
* that deliver the signal or redirect will call it
*/
record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(target));
break;
}
/* PR 212090: the signal we use to suspend threads */
case SUSPEND_SIGNAL:
if (handle_suspend_signal(dcontext, ucxt, frame)) {
/* i#1921: see comment above */
ASSERT(tr == NULL || tr->under_dynamo_control || IS_CLIENT_THREAD(dcontext));
record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(NULL));
}
/* else, don't deliver to app */
break;
/* i#61/PR 211530: the signal we use for nudges */
case NUDGESIG_SIGNUM:
if (handle_nudge_signal(dcontext, siginfo, ucxt))
record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(NULL));
/* else, don't deliver to app */
break;
case SIGALRM:
case SIGVTALRM:
case SIGPROF:
if (handle_alarm(dcontext, sig, ucxt))
record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(NULL));
/* else, don't deliver to app */
break;
#ifdef SIDELINE
case SIGCHLD: {
int status = siginfo->si_status;
if (siginfo->si_pid == 0) {
/* FIXME: with older versions of linux the sigchld fields of
* siginfo are not filled in properly!
* This is my attempt to handle that, pid seems to be 0
*/
break;
}
if (status != 0) {
LOG(THREAD, LOG_ALL, 0, "*** Child thread died with error %d\n", status);
ASSERT_NOT_REACHED();
}
break;
}
#endif
default: {
record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(NULL));
break;
}
} /* end switch */
LOG(THREAD, LOG_ASYNCH, level,
"\tmaster_signal_handler %d returning now to " PFX "\n\n", sig, sc->SC_XIP);
/* Ensure we didn't get the app's sigstack into our frame. On Mac, the kernel
* doesn't use the frame's uc_stack, so we limit this to Linux.
* The pointers may be different if a thread is on its way to exit, and the app's
* sigstack was already restored (i#3369).
*/
IF_LINUX(ASSERT(dcontext == NULL || dcontext == GLOBAL_DCONTEXT ||
dcontext->is_exiting ||
frame->uc.uc_stack.ss_sp ==
((thread_sig_info_t *)dcontext->signal_field)->sigstack.ss_sp));
/* restore protections */
if (local)
SELF_PROTECT_LOCAL(dcontext, READONLY);
EXITING_DR();
}
static bool
execute_handler_from_cache(dcontext_t *dcontext, int sig, sigframe_rt_t *our_frame,
sigcontext_t *sc_orig,
fragment_t *f _IF_CLIENT(byte *access_address))
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
/* we want to modify the sc in DR's frame */
kernel_ucontext_t *uc = get_ucontext_from_rt_frame(our_frame);
sigcontext_t *sc = SIGCXT_FROM_UCXT(uc);
kernel_sigset_t blocked;
/* Need to get xsp now before get new dcontext.
* This is the translated xsp, so we avoid PR 306410 (cleancall arg fault
* on dstack => handler run on dstack) that Windows hit.
*/
byte *xsp = get_sigstack_frame_ptr(dcontext, sig,
our_frame/* take xsp from (translated)
* interruption point */);
#ifdef CLIENT_INTERFACE
sigcontext_t sc_interrupted = *sc;
dr_signal_action_t action = send_signal_to_client(
dcontext, sig, our_frame, sc_orig, access_address, false /*not blocked*/, f);
if (!handle_client_action_from_cache(dcontext, sig, action, our_frame, sc_orig,
&sc_interrupted, false /*!blocked*/))
return false;
#else
if (info->app_sigaction[sig] == NULL ||
info->app_sigaction[sig]->handler == (handler_t)SIG_DFL) {
LOG(THREAD, LOG_ASYNCH, 3, "\taction is SIG_DFL\n");
if (execute_default_from_cache(dcontext, sig, our_frame, sc_orig, false)) {
/* if we haven't terminated, restore original (untranslated) sc
* on request.
* XXX i#1615: this doesn't restore SIMD regs, if client translated them!
*/
*get_sigcontext_from_rt_frame(our_frame) = *sc_orig;
}
return false;
}
ASSERT(info->app_sigaction[sig] != NULL &&
info->app_sigaction[sig]->handler != (handler_t)SIG_IGN &&
info->app_sigaction[sig]->handler != (handler_t)SIG_DFL);
#endif
LOG(THREAD, LOG_ASYNCH, 2, "execute_handler_from_cache for signal %d\n", sig);
RSTATS_INC(num_signals);
/* now that we know it's not a client-involved fault, dump as app fault */
report_app_problem(dcontext, APPFAULT_FAULT, (byte *)sc->SC_XIP, (byte *)sc->SC_FP,
"\nSignal %d delivered to application handler.\n", sig);
LOG(THREAD, LOG_ASYNCH, 3, "\txsp is " PFX "\n", xsp);
/* copy frame to appropriate stack and convert to non-rt if necessary */
copy_frame_to_stack(dcontext, sig, our_frame, (void *)xsp, false /*!pending*/);
LOG(THREAD, LOG_ASYNCH, 3, "\tcopied frame from " PFX " to " PFX "\n", our_frame,
xsp);
sigcontext_t *app_sc = get_sigcontext_from_app_frame(info, sig, (void *)xsp);
/* Because of difficulties determining when/if a signal handler
* returns, we do what the kernel does: abandon all of our current
* state, copy what we might need to the handler frame if we come back,
* and then it's ok if the handler doesn't return.
* If it does, we start interpreting afresh when we see sigreturn().
* This routine assumes anything needed to return has been put in the
* frame (only needed for signals queued up while in dynamo), and goes
* ahead and trashes the current dcontext.
*/
/* if we were building a trace, kill it */
if (is_building_trace(dcontext)) {
LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n");
trace_abort(dcontext);
}
/* add to set of blocked signals those in sigaction mask */
blocked = info->app_sigaction[sig]->mask;
/* SA_NOMASK says whether to block sig itself or not */
if ((info->app_sigaction[sig]->flags & SA_NOMASK) == 0)
kernel_sigaddset(&blocked, sig);
set_blocked(dcontext, &blocked, false /*relative: OR these in*/);
/* Doesn't matter what most app registers are, signal handler doesn't
* expect anything except the frame on the stack. We do need to set xsp,
* only because if app wants special signal stack we need to point xsp
* there. (If no special signal stack, this is a nop.)
*/
sc->SC_XSP = (ptr_uint_t)xsp;
/* Set up args to handler: int sig, kernel_siginfo_t *siginfo,
* kernel_ucontext_t *ucxt.
*/
#ifdef X86_64
sc->SC_XDI = sig;
sc->SC_XSI = (reg_t) & ((sigframe_rt_t *)xsp)->info;
sc->SC_XDX = (reg_t) & ((sigframe_rt_t *)xsp)->uc;
#elif defined(AARCHXX)
sc->SC_R0 = sig;
if (IS_RT_FOR_APP(info, sig)) {
sc->SC_R1 = (reg_t) & ((sigframe_rt_t *)xsp)->info;
sc->SC_R2 = (reg_t) & ((sigframe_rt_t *)xsp)->uc;
}
if (sig_has_restorer(info, sig))
sc->SC_LR = (reg_t)info->app_sigaction[sig]->restorer;
else
sc->SC_LR = (reg_t)dynamorio_sigreturn;
# ifndef AARCH64
/* We're going to our fcache_return gencode which uses DEFAULT_ISA_MODE */
set_pc_mode_in_cpsr(sc, DEFAULT_ISA_MODE);
# endif
#endif
/* Set our sigreturn context (NOT for the app: we already copied the
* translated context to the app stack) to point to fcache_return!
* Then we'll go back through kernel, appear in fcache_return,
* and go through d_r_dispatch & interp, without messing up DR stack.
*/
transfer_from_sig_handler_to_fcache_return(
dcontext, uc, app_sc, sig,
/* Make sure handler is next thing we execute */
(app_pc)SIGACT_PRIMARY_HANDLER(info->app_sigaction[sig]),
(linkstub_t *)get_asynch_linkstub(), true);
if ((info->app_sigaction[sig]->flags & SA_ONESHOT) != 0) {
/* clear handler now -- can't delete memory since sigreturn,
* others may look at sigaction struct, so we just set to default
*/
info->app_sigaction[sig]->handler = (handler_t)SIG_DFL;
}
LOG(THREAD, LOG_ASYNCH, 3, "\tset next_tag to handler " PFX ", xsp to " PFX "\n",
SIGACT_PRIMARY_HANDLER(info->app_sigaction[sig]), xsp);
return true;
}
static bool
execute_handler_from_dispatch(dcontext_t *dcontext, int sig)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
byte *xsp = get_sigstack_frame_ptr(dcontext, sig, NULL);
sigframe_rt_t *frame = &(info->sigpending[sig]->rt_frame);
priv_mcontext_t *mcontext = get_mcontext(dcontext);
sigcontext_t *sc;
kernel_ucontext_t *uc;
kernel_sigset_t blocked;
#ifdef CLIENT_INTERFACE
dr_signal_action_t action;
#else
if (info->app_sigaction[sig] == NULL ||
info->app_sigaction[sig]->handler == (handler_t)SIG_DFL) {
LOG(THREAD, LOG_ASYNCH, 3, "\taction is SIG_DFL\n");
execute_default_from_dispatch(dcontext, sig, frame);
return true;
}
ASSERT(info->app_sigaction[sig] != NULL &&
info->app_sigaction[sig]->handler != (handler_t)SIG_IGN &&
info->app_sigaction[sig]->handler != (handler_t)SIG_DFL);
#endif
LOG(THREAD, LOG_ASYNCH, 2, "execute_handler_from_dispatch for signal %d\n", sig);
RSTATS_INC(num_signals);
/* modify the rtframe before copying to stack so we can pass final
* version to client, and propagate its mods
*/
uc = get_ucontext_from_rt_frame(frame);
sc = SIGCXT_FROM_UCXT(uc);
/* Because of difficulties determining when/if a signal handler
* returns, we do what the kernel does: abandon all of our current
* state, copy what we might need to the handler frame if we come back,
* and then it's ok if the handler doesn't return.
* If it does, we start interpreting afresh when we see sigreturn().
*/
#ifdef DEBUG
if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) {
LOG(THREAD, LOG_ASYNCH, 3, "original sigcontext " PFX ":\n", sc);
dump_sigcontext(dcontext, sc);
}
#endif
if (info->sigpending[sig]->use_sigcontext) {
LOG(THREAD, LOG_ASYNCH, 2,
"%s: using sigcontext, not mcontext (syscall restart)\n", __FUNCTION__);
} else {
/* copy currently-interrupted-context to frame's context, so we can
* abandon the currently-interrupted context.
*/
mcontext_to_ucontext(uc, mcontext);
}
/* Sigreturn needs the target ISA mode to be set in the T bit in cpsr.
* Since we came from d_r_dispatch, the post-signal target's mode is in dcontext.
*/
IF_ARM(set_pc_mode_in_cpsr(sc, dr_get_isa_mode(dcontext)));
/* mcontext does not contain fp or mmx or xmm state, which may have
* changed since the frame was created (while finishing up interrupted
* fragment prior to returning to d_r_dispatch). Since DR does not touch
* this state except for xmm on x64, we go ahead and copy the
* current state into the frame, and then touch up xmm for x64.
*/
/* FIXME: should this be done for all pending as soon as reach
* d_r_dispatch? what if get two asynch inside same frag prior to exiting
* cache? have issues with fpstate, but also prob with next_tag? FIXME
*/
/* FIXME: we should clear fpstate for app handler itself as that's
* how our own handler is executed.
*/
#if defined(LINUX) && defined(X86)
ASSERT(sc->fpstate != NULL); /* not doing i#641 yet */
save_fpstate(dcontext, frame);
#endif /* LINUX && X86 */
#ifdef DEBUG
if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) {
LOG(THREAD, LOG_ASYNCH, 3, "new sigcontext " PFX ":\n", sc);
dump_sigcontext(dcontext, sc);
LOG(THREAD, LOG_ASYNCH, 3, "\n");
}
#endif
/* FIXME: other state? debug regs?
* if no syscall allowed between master_ (when frame created) and
* receiving, then don't have to worry about debug regs, etc.
* check for syscall when record pending, if it exists, try to
* receive in pre_system_call or something? what if ignorable? FIXME!
*/
if (!info->sigpending[sig]->use_sigcontext) {
/* for the pc we want the app pc not the cache pc */
sc->SC_XIP = (ptr_uint_t)dcontext->next_tag;
LOG(THREAD, LOG_ASYNCH, 3, "\tset frame's eip to " PFX "\n", sc->SC_XIP);
}
#ifdef CLIENT_INTERFACE
sigcontext_t sc_interrupted = *sc;
action = send_signal_to_client(dcontext, sig, frame, NULL,
info->sigpending[sig]->access_address,
false /*not blocked*/, NULL);
/* in order to pass to the client, we come all the way here for signals
* the app has no handler for
*/
if (action == DR_SIGNAL_REDIRECT) {
/* send_signal_to_client copied mcontext into frame's sc */
priv_mcontext_t *mcontext = get_mcontext(dcontext);
ucontext_to_mcontext(mcontext, uc);
dcontext->next_tag = canonicalize_pc_target(dcontext, (app_pc)sc->SC_XIP);
if (is_building_trace(dcontext)) {
LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n");
trace_abort(dcontext);
}
IF_ARM(dr_set_isa_mode(dcontext, get_pc_mode_from_cpsr(sc), NULL));
mcontext->pc = dcontext->next_tag;
sig_full_cxt_t sc_interrupted_full = { &sc_interrupted, NULL /*not provided*/ };
if (instrument_kernel_xfer(dcontext, DR_XFER_CLIENT_REDIRECT, sc_interrupted_full,
NULL, NULL, dcontext->next_tag, mcontext->xsp,
osc_empty, mcontext, sig))
dcontext->next_tag = canonicalize_pc_target(dcontext, mcontext->pc);
return true; /* don't try another signal */
} else if (action == DR_SIGNAL_SUPPRESS ||
(info->app_sigaction[sig] != NULL &&
info->app_sigaction[sig]->handler == (handler_t)SIG_IGN)) {
LOG(THREAD, LOG_ASYNCH, 2, "%s: not delivering!\n",
(action == DR_SIGNAL_SUPPRESS) ? "client suppressing signal"
: "app signal handler is SIG_IGN");
return false;
} else if (action == DR_SIGNAL_BYPASS ||
(info->app_sigaction[sig] == NULL ||
info->app_sigaction[sig]->handler == (handler_t)SIG_DFL)) {
LOG(THREAD, LOG_ASYNCH, 2, "%s: executing default action\n",
(action == DR_SIGNAL_BYPASS) ? "client forcing default"
: "app signal handler is SIG_DFL");
if (info->sigpending[sig]->use_sigcontext) {
/* after the default action we want to go to the sigcontext */
dcontext->next_tag = canonicalize_pc_target(dcontext, (app_pc)sc->SC_XIP);
ucontext_to_mcontext(get_mcontext(dcontext), uc);
IF_ARM(dr_set_isa_mode(dcontext, get_pc_mode_from_cpsr(sc), NULL));
}
execute_default_from_dispatch(dcontext, sig, frame);
return true;
}
CLIENT_ASSERT(action == DR_SIGNAL_DELIVER, "invalid signal event return value");
#endif
/* now that we've made all our changes and given the client a
* chance to make changes, copy the frame to the appropriate stack
* location and convert to non-rt if necessary
*/
copy_frame_to_stack(dcontext, sig, frame, xsp, true /*pending*/);
/* now point at the app's frame */
sc = get_sigcontext_from_app_frame(info, sig, (void *)xsp);
ASSERT(info->app_sigaction[sig] != NULL);
/* add to set of blocked signals those in sigaction mask */
blocked = info->app_sigaction[sig]->mask;
/* SA_NOMASK says whether to block sig itself or not */
if ((info->app_sigaction[sig]->flags & SA_NOMASK) == 0)
kernel_sigaddset(&blocked, sig);
set_blocked(dcontext, &blocked, false /*relative: OR these in*/);
/* if we were building a trace, kill it */
if (is_building_trace(dcontext)) {
LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n");
trace_abort(dcontext);
}
/* Doesn't matter what most app registers are, signal handler doesn't
* expect anything except the frame on the stack. We do need to set xsp.
*/
mcontext->xsp = (ptr_uint_t)xsp;
/* Set up args to handler: int sig, kernel_siginfo_t *siginfo,
* kernel_ucontext_t *ucxt.
*/
#ifdef MACOS64
mcontext->xdi = (reg_t)info->app_sigaction[sig]->handler;
int infostyle = TEST(SA_SIGINFO, info->app_sigaction[sig]->flags)
? SIGHAND_STYLE_UC_FLAVOR
: SIGHAND_STYLE_UC_TRAD;
mcontext->xsi = infostyle;
mcontext->xdx = sig;
mcontext->xcx = (reg_t) & ((sigframe_rt_t *)xsp)->info;
mcontext->r8 = (reg_t) & ((sigframe_rt_t *)xsp)->uc;
#elif defined(X86_64)
mcontext->xdi = sig;
mcontext->xsi = (reg_t) & ((sigframe_rt_t *)xsp)->info;
mcontext->xdx = (reg_t) & ((sigframe_rt_t *)xsp)->uc;
#elif defined(AARCHXX)
mcontext->r0 = sig;
if (IS_RT_FOR_APP(info, sig)) {
mcontext->r1 = (reg_t) & ((sigframe_rt_t *)xsp)->info;
mcontext->r2 = (reg_t) & ((sigframe_rt_t *)xsp)->uc;
}
if (sig_has_restorer(info, sig))
mcontext->lr = (reg_t)info->app_sigaction[sig]->restorer;
else
mcontext->lr = (reg_t)dynamorio_sigreturn;
#endif
#ifdef X86
/* Clear eflags DF (signal handler should match function entry ABI) */
mcontext->xflags &= ~EFLAGS_DF;
#endif
/* Make sure handler is next thing we execute */
dcontext->next_tag = canonicalize_pc_target(
dcontext, (app_pc)SIGACT_PRIMARY_HANDLER(info->app_sigaction[sig]));
if ((info->app_sigaction[sig]->flags & SA_ONESHOT) != 0) {
/* clear handler now -- can't delete memory since sigreturn,
* others may look at sigaction struct, so we just set to default
*/
info->app_sigaction[sig]->handler = (handler_t)SIG_DFL;
}
#ifdef CLIENT_INTERFACE
mcontext->pc = dcontext->next_tag;
sig_full_cxt_t sc_full = { sc, NULL /*not provided*/ };
if (instrument_kernel_xfer(dcontext, DR_XFER_SIGNAL_DELIVERY, sc_full, NULL, NULL,
dcontext->next_tag, mcontext->xsp, osc_empty, mcontext,
sig))
dcontext->next_tag = canonicalize_pc_target(dcontext, mcontext->pc);
#endif
LOG(THREAD, LOG_ASYNCH, 3, "\tset xsp to " PFX "\n", xsp);
return true;
}
/* The arg to SYS_kill, i.e., the signal number, should be in dcontext->sys_param0 */
/* This routine unblocks signals, but the caller must set the handler to default. */
static void
terminate_via_kill(dcontext_t *dcontext)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
ASSERT(dcontext == get_thread_private_dcontext());
/* Enure signal_thread_exit() will not re-block */
memset(&info->app_sigblocked, 0, sizeof(info->app_sigblocked));
/* FIXME PR 541760: there can be multiple thread groups and thus
* this may not exit all threads in the address space
*/
block_cleanup_and_terminate(
dcontext, SYS_kill,
/* Pass -pid in case main thread has exited
* in which case will get -ESRCH
*/
IF_VMX86(os_in_vmkernel_userworld() ? -(int)get_process_id() :) get_process_id(),
dcontext->sys_param0, true, 0, 0);
ASSERT_NOT_REACHED();
}
bool
is_currently_on_sigaltstack(dcontext_t *dcontext)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
byte *cur_esp;
GET_STACK_PTR(cur_esp);
return (cur_esp >= (byte *)info->sigstack.ss_sp &&
cur_esp < (byte *)info->sigstack.ss_sp + info->sigstack.ss_size);
}
static void
terminate_via_kill_from_anywhere(dcontext_t *dcontext, int sig)
{
dcontext->sys_param0 = sig; /* store arg to SYS_kill */
if (is_currently_on_sigaltstack(dcontext)) {
/* We can't clean up our sigstack properly when we're on it
* (i#1160) so we terminate on the dstack.
*/
call_switch_stack(dcontext, dcontext->dstack,
(void (*)(void *))terminate_via_kill, NULL /*!d_r_initstack */,
false /*no return */);
} else {
terminate_via_kill(dcontext);
}
ASSERT_NOT_REACHED();
}
/* xref os_request_fatal_coredump() */
void
os_terminate_via_signal(dcontext_t *dcontext, terminate_flags_t flags, int sig)
{
if (signal_is_interceptable(sig)) {
bool set_action = false;
#if defined(STATIC_LIBRARY) && defined(LINUX)
if (INTERNAL_OPTION(invoke_app_on_crash)) {
/* We come here for asserts. Faults already bypass this routine. */
dcontext_t *my_dc = get_thread_private_dcontext();
if (my_dc != NULL) {
thread_sig_info_t *info = (thread_sig_info_t *)my_dc->signal_field;
if (info != NULL && info->app_sigaction[sig] != NULL &&
IS_RT_FOR_APP(info, sig)) {
set_action = true;
sigaction_syscall(sig, info->app_sigaction[sig], NULL);
}
}
}
#endif
if (!set_action) {
DEBUG_DECLARE(bool res =)
set_default_signal_action(sig);
ASSERT(res);
}
}
if (TEST(TERMINATE_CLEANUP, flags)) {
/* we enter from several different places, so rewind until top-level kstat */
KSTOP_REWIND_UNTIL(thread_measured);
ASSERT(dcontext != NULL);
dcontext->sys_param0 = sig;
/* XXX: the comment in the else below implies some systems have SYS_kill
* of SIGSEGV w/ no handler on oneself actually return.
* cleanup_and_terminate won't return to us and will use global_do_syscall
* to invoke SYS_kill, which in debug will do an inf loop (good!) but
* in release will do SYS_exit_group -- oh well, the systems I'm testing
* on do an immediate exit.
*/
terminate_via_kill_from_anywhere(dcontext, sig);
} else {
/* general clean up is unsafe: just remove .1config file */
d_r_config_exit();
dynamorio_syscall(SYS_kill, 2, get_process_id(), sig);
/* We try both the SYS_kill and the immediate crash since on some platforms
* the SIGKILL is delayed and on others the *-1 is hanging(?): should investigate
*/
if (sig == SIGSEGV) /* make doubly-sure */
*((int *)PTR_UINT_MINUS_1) = 0;
while (true) {
/* in case signal delivery is delayed we wait...forever */
os_thread_yield();
}
}
ASSERT_NOT_REACHED();
}
static bool
execute_default_action(dcontext_t *dcontext, int sig, sigframe_rt_t *frame,
sigcontext_t *sc_orig, bool from_dispatch, bool forged)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
sigcontext_t *sc = get_sigcontext_from_rt_frame(frame);
byte *pc = (byte *)sc->SC_XIP;
LOG(THREAD, LOG_ASYNCH, 3, "execute_default_action for signal %d\n", sig);
/* should only come here for signals we catch, or signal with ONESHOT
* that didn't sigreturn
*/
ASSERT(info->we_intercept[sig] ||
(info->app_sigaction[sig]->flags & SA_ONESHOT) != 0);
if (info->app_sigaction[sig] != NULL &&
(info->app_sigaction[sig]->flags & SA_ONESHOT) != 0) {
if (!info->we_intercept[sig]) {
handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t));
info->app_sigaction[sig] = NULL;
}
}
/* FIXME PR 205310: we can't always perfectly emulate the default
* behavior. To execute the default action, we have to un-register our
* handler, if we have one, for signals whose default action is not
* ignore or that will just be re-raised upon returning to the
* interrupted context -- FIXME: are any of the ignores repeated?
* SIGURG?
*
* If called from execute_handler_from_cache(), our master_signal_handler()
* is going to return directly to the translated context: which means we
* go native to re-execute the instr, which if it does in fact generate
* the signal again means we have a nice transparent core dump.
*
* If called from execute_handler_from_dispatch(), we need to generate
* the signal ourselves.
*/
if (default_action[sig] != DEFAULT_IGNORE) {
DEBUG_DECLARE(bool ok =)
set_default_signal_action(sig);
ASSERT(ok);
/* FIXME: to avoid races w/ shared handlers should set a flag to
* prevent another thread from re-enabling.
* Perhaps worse: what if this signal arrives for another thread
* in the meantime (and the default is not terminate)?
*/
if (info->shared_app_sigaction) {
LOG(THREAD, LOG_ASYNCH, 1,
"WARNING: having to install SIG_DFL for thread " TIDFMT ", but will be "
"shared!\n",
d_r_get_thread_id());
}
if (default_action[sig] == DEFAULT_TERMINATE ||
default_action[sig] == DEFAULT_TERMINATE_CORE) {
report_app_problem(dcontext, APPFAULT_CRASH, pc, (byte *)sc->SC_FP,
"\nSignal %d delivered to application as default "
"action.\n",
sig);
/* App may call sigaction to set handler SIG_DFL (unnecessary but legal),
* in which case DR will put a handler in info->app_sigaction[sig].
* We must clear it, otherwise, signal_thread_exit may cleanup the
* handler and set it to SIG_IGN instead.
*/
if (info->app_sigaction[sig] != NULL) {
ASSERT(info->we_intercept[sig]);
handler_free(dcontext, info->app_sigaction[sig],
sizeof(kernel_sigaction_t));
info->app_sigaction[sig] = NULL;
}
/* N.B.: we don't have to restore our handler because the
* default action is for the process (entire thread group for NPTL) to die!
*/
if (from_dispatch || can_always_delay[sig] || forged ||
is_sys_kill(dcontext, pc, (byte *)sc->SC_XSP, &frame->info)) {
/* This must have come from SYS_kill rather than raised by
* a faulting instruction. Thus we can't go re-execute the
* instr in order to re-raise the signal (if from_dispatch,
* we delayed and can't re-execute anyway). Instead we
* re-generate via SYS_kill. An alternative, if we don't
* care about generating a core dump, is to use SYS_exit
* and pass the right exit code to indicate the signal
* number: that would avoid races w/ the sigaction.
*
* FIXME: should have app make the syscall to get a more
* transparent core dump!
*/
LOG(THREAD, LOG_ASYNCH, 1, "Terminating via kill\n");
if (!from_dispatch && !forged)
KSTOP_NOT_MATCHING_NOT_PROPAGATED(fcache_default);
KSTOP_NOT_MATCHING_NOT_PROPAGATED(dispatch_num_exits);
if (is_couldbelinking(dcontext)) /* won't be for SYS_kill (i#1159) */
enter_nolinking(dcontext, NULL, false);
/* we could be on sigstack so call this version: */
terminate_via_kill_from_anywhere(dcontext, sig);
ASSERT_NOT_REACHED();
} else {
/* We assume that re-executing the interrupted instr will
* re-raise the fault. We could easily be wrong:
* xref PR 363811 infinite loop due to memory we
* thought was unreadable and thus thought would raise
* a signal; xref PR 368277 to improve is_sys_kill(), and the
* "forged" parameter that puts us in the if() above.
* FIXME PR 205310: we should check whether we come out of
* the cache when we expected to terminate!
*
* An alternative is to abandon transparent core dumps and
* do the same explicit SYS_kill we do for from_dispatch.
* That would let us clean up DR as well.
* FIXME: currently we do not clean up DR for a synchronous
* signal death, but we do for asynch.
*/
/* i#552: cleanup and raise client exit event */
int instr_sz = 0;
thread_sig_info_t *info;
/* We are on the sigstack now, so assign it to NULL to avoid being
* freed during process exit cleanup
*/
info = (thread_sig_info_t *)dcontext->signal_field;
info->sigstack.ss_sp = NULL;
/* We enter from several different places, so rewind until
* top-level kstat.
*/
KSTOP_REWIND_UNTIL(thread_measured);
/* We try to raise the same signal in app's context so a correct
* coredump can be generated. However, the client might change
* the code in a way that the corresponding app code won't
* raise the signal, so we first check if the app instr is the
* same as instr in the cache, and raise the signal (by return).
* Otherwise, we kill the process instead.
* XXX: if the PC is unreadable we'll just crash here...should check
* for readability safely.
*/
ASSERT(sc_orig != NULL);
instr_sz = decode_sizeof(dcontext, (byte *)sc_orig->SC_XIP,
NULL _IF_X86_64(NULL));
if (instr_sz != 0 &&
pc != NULL && /* avoid crash on xl8 failure (i#1699) */
instr_sz == decode_sizeof(dcontext, pc, NULL _IF_X86_64(NULL)) &&
memcmp(pc, (byte *)sc_orig->SC_XIP, instr_sz) == 0) {
/* the app instr matches the cache instr; cleanup and raise the
* the signal in the app context
*/
LOG(THREAD, LOG_ASYNCH, 1, "Raising signal by re-executing\n");
dynamo_process_exit();
/* we cannot re-enter the cache, which is freed by now */
ASSERT(!from_dispatch);
return false;
} else {
/* mismatch, cleanup and terminate */
LOG(THREAD, LOG_ASYNCH, 1, "Terminating via kill\n");
dcontext->sys_param0 = sig;
terminate_via_kill(dcontext);
ASSERT_NOT_REACHED();
}
}
} else {
/* FIXME PR 297033: in order to intercept DEFAULT_STOP /
* DEFAULT_CONTINUE signals, we need to set sigcontext to point
* to some kind of regain-control routine, so that when our
* thread gets to run again we can reset our handler. So far
* we have no signals that fall here that we intercept.
*/
CLIENT_ASSERT(false, "STOP/CONT signals not supported");
}
#if defined(DEBUG) && defined(INTERNAL)
if (sig == SIGSEGV && !dynamo_exited) {
/* pc should be an app pc at this point (it was translated) --
* check for bad cases here
*/
if (safe_is_in_fcache(dcontext, pc, (byte *)sc->SC_XSP)) {
fragment_t wrapper;
fragment_t *f;
LOG(THREAD, LOG_ALL, 1,
"Received SIGSEGV at pc " PFX " in thread " TIDFMT "\n", pc,
d_r_get_thread_id());
f = fragment_pclookup(dcontext, pc, &wrapper);
if (f)
disassemble_fragment(dcontext, f, false);
ASSERT_NOT_REACHED();
} else if (in_generated_routine(dcontext, pc)) {
LOG(THREAD, LOG_ALL, 1,
"Received SIGSEGV at generated non-code-cache pc " PFX "\n", pc);
ASSERT_NOT_REACHED();
}
}
#endif
}
/* now continue at the interruption point and re-raise the signal */
return true;
}
static bool
execute_default_from_cache(dcontext_t *dcontext, int sig, sigframe_rt_t *frame,
sigcontext_t *sc_orig, bool forged)
{
return execute_default_action(dcontext, sig, frame, sc_orig, false, forged);
}
static void
execute_default_from_dispatch(dcontext_t *dcontext, int sig, sigframe_rt_t *frame)
{
execute_default_action(dcontext, sig, frame, NULL, true, false);
}
void
receive_pending_signal(dcontext_t *dcontext)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
sigpending_t *temp;
int sig;
LOG(THREAD, LOG_ASYNCH, 3, "receive_pending_signal\n");
if (info->interrupted != NULL) {
relink_interrupted_fragment(dcontext, info);
}
/* grab first pending signal
* XXX: start with real-time ones?
*/
/* "lock" the array to prevent a new signal that interrupts this bit of
* code from prepended or deleting from the array while we're accessing it
*/
info->accessing_sigpending = true;
/* barrier to prevent compiler from moving the above write below the loop */
__asm__ __volatile__("" : : : "memory");
if (!info->multiple_pending_units &&
info->num_pending + 2 >= DYNAMO_OPTION(max_pending_signals)) {
/* We're close to the limit: proactively get a new unit while it's safe
* to acquire locks. We do that by pushing over the edge.
* We assume that filling up a 2nd unit is too pathological to plan for.
*/
info->multiple_pending_units = true;
SYSLOG_INTERNAL_WARNING("many pending signals: asking for 2nd special unit");
sigpending_t *temp1 = special_heap_alloc(info->sigheap);
sigpending_t *temp2 = special_heap_alloc(info->sigheap);
sigpending_t *temp3 = special_heap_alloc(info->sigheap);
special_heap_free(info->sigheap, temp1);
special_heap_free(info->sigheap, temp2);
special_heap_free(info->sigheap, temp3);
}
for (sig = 1; sig <= MAX_SIGNUM; sig++) {
if (info->sigpending[sig] != NULL) {
bool executing = true;
/* We do not re-check whether blocked if it was unblocked at
* receive time, to properly handle sigsuspend (i#1340).
*/
if (!info->sigpending[sig]->unblocked &&
kernel_sigismember(&info->app_sigblocked, sig)) {
LOG(THREAD, LOG_ASYNCH, 3, "\tsignal %d is blocked!\n", sig);
continue;
}
LOG(THREAD, LOG_ASYNCH, 3, "\treceiving signal %d\n", sig);
/* execute_handler_from_dispatch()'s call to copy_frame_to_stack() is
* allowed to remove the front entry from info->sigpending[sig] and
* jump to d_r_dispatch.
*/
executing = execute_handler_from_dispatch(dcontext, sig);
temp = info->sigpending[sig];
info->sigpending[sig] = temp->next;
special_heap_free(info->sigheap, temp);
info->num_pending--;
/* only one signal at a time! */
if (executing) {
/* Make negative so our fcache_enter check makes progress but
* our C code still considers there to be pending signals.
*/
dcontext->signals_pending = -1;
break;
}
}
}
/* barrier to prevent compiler from moving the below write above the loop */
__asm__ __volatile__("" : : : "memory");
info->accessing_sigpending = false;
/* we only clear this on a call to us where we find NO pending signals */
if (sig > MAX_SIGNUM) {
LOG(THREAD, LOG_ASYNCH, 3, "\tclearing signals_pending flag\n");
dcontext->signals_pending = 0;
}
}
/* Returns false if should NOT issue syscall. */
bool
#ifdef LINUX
handle_sigreturn(dcontext_t *dcontext, bool rt)
#else
handle_sigreturn(dcontext_t *dcontext, void *ucxt_param, int style)
#endif
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
sigcontext_t *sc = NULL; /* initialize to satisfy Mac clang */
kernel_ucontext_t *ucxt = NULL;
int sig = 0;
app_pc next_pc;
/* xsp was put in mcontext prior to pre_system_call() */
reg_t xsp = get_mcontext(dcontext)->xsp;
#ifdef MACOS
bool rt = true;
#endif
LOG(THREAD, LOG_ASYNCH, 3, "%ssigreturn()\n", rt ? "rt_" : "");
LOG(THREAD, LOG_ASYNCH, 3, "\txsp is " PFX "\n", xsp);
#ifdef PROGRAM_SHEPHERDING
/* if (!sig_has_restorer, region was never added to exec list,
* allowed as pattern only and kicked off at first write via
* selfmod detection or otherwise if vsyscall, so no worries
* about having to remove it here
*/
#endif
/* The easiest way to set all the non-GPR state that DR does not separately
* preserve is to actually execute the sigreturn syscall, so we set up to do
* that. We do not want to change DR's signal state, however, so we set it
* back to DR's values after processing the state for the app.
*/
kernel_sigset_t our_mask;
sigprocmask_syscall(SIG_SETMASK, NULL, &our_mask, sizeof(our_mask));
/* get sigframe: it's the top thing on the stack, except the ret
* popped off pretcode.
* WARNING: handler for tcsh's window_change (SIGWINCH) clobbers its
* signal # arg, so don't use frame->sig! (kernel doesn't look at sig
* so app can get away with it)
*/
if (rt) {
#ifdef LINUX
sigframe_rt_t *frame = (sigframe_rt_t *)(xsp IF_X86(-sizeof(char *)));
/* use si_signo instead of sig, less likely to be clobbered by app */
sig = frame->info.si_signo;
# ifdef X86_32
LOG(THREAD, LOG_ASYNCH, 3, "\tsignal was %d (did == param %d)\n", sig,
frame->sig);
if (frame->sig != sig)
LOG(THREAD, LOG_ASYNCH, 1, "WARNING: app sig handler clobbered sig param\n");
# endif
sc = get_sigcontext_from_app_frame(info, sig, (void *)frame);
ucxt = &frame->uc;
/* Check again for the magic words. See the i#3812 comment above. */
IF_X86(ASSERT(
(sc->fpstate->sw_reserved.magic1 == 0 &&
sc->fpstate->sw_reserved.extended_size == sizeof(kernel_fpstate_t)) ||
(sc->fpstate->sw_reserved.magic1 == FP_XSTATE_MAGIC1 &&
*(int *)((byte *)sc->fpstate + sc->fpstate->sw_reserved.extended_size -
FP_XSTATE_MAGIC2_SIZE) == FP_XSTATE_MAGIC2)));
#elif defined(MACOS)
ucxt = (kernel_ucontext_t *)ucxt_param;
if (ucxt == NULL) {
/* On Mac the kernel seems to store state on whether the process is
* on the altstack, so longjmp calls _sigunaltstack() which issues a
* sigreturn syscall telling the kernel about the altstack change,
* with a NULL context.
*/
LOG(THREAD, LOG_ASYNCH, 3, "\tsigunalstack sigreturn: no context\n");
return true;
}
# ifdef X64
kernel_siginfo_t *siginfo = (kernel_siginfo_t *)ucxt - 1;
sig = siginfo->si_signo;
# else
/* The initial frame fields on the stack are messed up due to
* params to handler from tramp, so use params to syscall.
* XXX: we don't have signal # though: so we have to rely on app
* not clobbering the sig param field.
*/
sig = *(int *)xsp;
# endif
LOG(THREAD, LOG_ASYNCH, 3, "\tsignal was %d\n", sig);
sc = SIGCXT_FROM_UCXT(ucxt);
#endif
ASSERT(sig > 0 && sig <= MAX_SIGNUM && IS_RT_FOR_APP(info, sig));
/* Re-set sigstack from the value stored in the frame. Silently ignore failure,
* just like the kernel does.
*/
uint ignored;
/* The kernel checks for being on the stack *after* swapping stacks, so pass
* sc->SC_XSP as the current stack.
*/
handle_sigaltstack(dcontext, &ucxt->uc_stack, NULL, sc->SC_XSP, &ignored);
/* Restore DR's so sigreturn syscall won't change it. */
ucxt->uc_stack = info->sigstack;
/* FIXME: what if handler called sigaction and requested rt
* when itself was non-rt?
*/
/* Discard blocked signals, re-set from prev mask stored in frame. */
set_blocked(dcontext, SIGMASK_FROM_UCXT(ucxt), true /*absolute*/);
/* Restore DR's so sigreturn syscall won't change it. */
*SIGMASK_FROM_UCXT(ucxt) = our_mask;
}
#if defined(LINUX) && !defined(X64)
else {
/* FIXME: libc's restorer pops prior to calling sigreturn, I have
* no idea why, but kernel asks for xsp-8 not xsp-4...weird!
*/
kernel_sigset_t prevset;
sigframe_plain_t *frame = (sigframe_plain_t *)(xsp IF_X86(-8));
/* We don't trust frame->sig (app sometimes clobbers it), and for
* plain frame there's no other place that sig is stored,
* so as a hack we added a new frame!
* FIXME: this means we won't support nonstandard use of SYS_sigreturn,
* e.g., as NtContinue, if frame didn't come from a real signal and so
* wasn't copied to stack by us.
*/
sig = frame->sig_noclobber;
LOG(THREAD, LOG_ASYNCH, 3, "\tsignal was %d (did == param %d)\n", sig,
IF_X86_ELSE(frame->sig, 0));
# ifdef X86_32
if (frame->sig != sig)
LOG(THREAD, LOG_ASYNCH, 1, "WARNING: app sig handler clobbered sig param\n");
# endif
ASSERT(sig > 0 && sig <= MAX_SIGNUM && !IS_RT_FOR_APP(info, sig));
sc = get_sigcontext_from_app_frame(info, sig, (void *)frame);
/* discard blocked signals, re-set from prev mask stored in frame */
prevset.sig[0] = frame->IF_X86_ELSE(sc.oldmask, uc.uc_mcontext.oldmask);
if (_NSIG_WORDS > 1) {
memcpy(&prevset.sig[1], &frame->IF_X86_ELSE(extramask, uc.sigset_ex),
sizeof(prevset.sig[1]));
}
# ifdef ARM
ucxt = &frame->uc; /* we leave ucxt NULL for x86: not needed there */
# endif
set_blocked(dcontext, &prevset, true /*absolute*/);
/* Restore DR's so sigreturn syscall won't change it. */
convert_rt_mask_to_nonrt(frame, &our_mask);
}
#endif /* LINUX */
/* Make sure we deliver pending signals that are now unblocked.
*/
check_signals_pending(dcontext, info);
/* if we were building a trace, kill it */
if (is_building_trace(dcontext)) {
LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n");
trace_abort(dcontext);
}
/* Defensively check for NULL.
* XXX i#3182: It did happen but it is not clear how.
*/
if (info->app_sigaction[sig] != NULL &&
TEST(SA_ONESHOT, info->app_sigaction[sig]->flags)) {
ASSERT(info->app_sigaction[sig]->handler == (handler_t)SIG_DFL);
if (!info->we_intercept[sig]) {
/* let kernel do default independent of us */
handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t));
info->app_sigaction[sig] = NULL;
}
}
ASSERT(!safe_is_in_fcache(dcontext, (app_pc)sc->SC_XIP, (byte *)sc->SC_XSP));
#ifdef CLIENT_INTERFACE
sig_full_cxt_t sc_full = { sc, NULL /*not provided*/ };
get_mcontext(dcontext)->pc = dcontext->next_tag;
instrument_kernel_xfer(dcontext, DR_XFER_SIGNAL_RETURN, osc_empty, NULL,
get_mcontext(dcontext), (app_pc)sc->SC_XIP, sc->SC_XSP,
sc_full, NULL, sig);
#endif
#ifdef DEBUG
if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_ASYNCH) != 0) {
LOG(THREAD, LOG_ASYNCH, 3, "returning-to sigcontext " PFX ":\n", sc);
dump_sigcontext(dcontext, sc);
}
#endif
/* XXX i#1206: if we interrupted a non-ignorable syscall to run the app's
* handler, and we set up to restart the syscall, we'll come here with the
* translated syscall pc -- thus we can't distinguish from a signal interrupting
* the prior app instr. So we can't simply point at do_syscall and call
* set_at_syscall -- we have to re-interpret the syscall and re-run the
* pre-syscall handler. Hopefully all our pre-syscall handlers can handle that.
*/
/* set up for d_r_dispatch */
/* we have to use a different slot since next_tag ends up holding the do_syscall
* entry when entered from d_r_dispatch (we're called from
* pre_syscall, prior to entering cache)
*/
dcontext->asynch_target = canonicalize_pc_target(
dcontext, (app_pc)(sc->SC_XIP IF_ARM(| (TEST(EFLAGS_T, sc->SC_XFLAGS) ? 1 : 0))));
next_pc = dcontext->asynch_target;
#ifdef VMX86_SERVER
/* PR 404712: kernel only restores gp regs so we do it ourselves and avoid
* complexities of kernel's non-linux-like sigreturn semantics
*/
sig_full_cxt_t sc_full = { sc, NULL }; /* non-ARM so NULL ok */
sigcontext_to_mcontext(get_mcontext(dcontext), &sc_full, DR_MC_ALL);
#else
/* HACK to get eax put into mcontext AFTER do_syscall */
dcontext->next_tag = (app_pc)sc->IF_X86_ELSE(SC_XAX, SC_R0);
/* use special linkstub so we know why we came out of the cache */
sc->IF_X86_ELSE(SC_XAX, SC_R0) = (ptr_uint_t)get_asynch_linkstub();
/* set our sigreturn context to point to fcache_return */
/* We don't need PC_AS_JMP_TGT b/c the kernel uses EFLAGS_T for the mode */
sc->SC_XIP = (ptr_uint_t)fcache_return_routine(dcontext);
/* if we overlaid inner frame on nested signal, will end up with this
* error -- disable in release build since this is often app's fault (stack
* too small)
* FIXME: how make this transparent? what ends up happening is that we
* get a segfault when we start interpreting d_r_dispatch, we want to make it
* look like whatever would happen to the app...
*/
ASSERT((app_pc)sc->SC_XIP != next_pc);
# ifdef AARCHXX
set_stolen_reg_val(get_mcontext(dcontext), get_sigcxt_stolen_reg(sc));
set_sigcxt_stolen_reg(sc, (reg_t)*get_dr_tls_base_addr());
# ifdef AARCH64
/* On entry to the do_syscall gencode, we save X1 into TLS_REG1_SLOT.
* Then the sigreturn would redirect the flow to the fcache_return gencode.
* In fcache_return it recovers the values of x0 and x1 from TLS_SLOT 0 and 1.
*/
get_mcontext(dcontext)->r1 = sc->regs[1];
# else
/* We're going to our fcache_return gencode which uses DEFAULT_ISA_MODE */
set_pc_mode_in_cpsr(sc, DEFAULT_ISA_MODE);
# endif
# endif
#endif
LOG(THREAD, LOG_ASYNCH, 3, "set next tag to " PFX ", sc->SC_XIP to " PFX "\n",
next_pc, sc->SC_XIP);
return IF_VMX86_ELSE(false, true);
}
bool
is_signal_restorer_code(byte *pc, size_t *len)
{
/* is this a sigreturn pattern placed by kernel on the stack or vsyscall page?
* for non-rt frame:
* 0x58 popl %eax
* 0xb8 <sysnum> movl SYS_sigreturn, %eax
* 0xcd 0x80 int 0x80
* for rt frame:
* 0xb8 <sysnum> movl SYS_rt_sigreturn, %eax
* 0xcd 0x80 int 0x80
*/
/* optimized we only need two uint reads, but we have to do
* some little-endian byte-order reverses to get the right result
*/
#define reverse(x) \
((((x)&0xff) << 24) | (((x)&0xff00) << 8) | (((x)&0xff0000) >> 8) | \
(((x)&0xff000000) >> 24))
#ifdef MACOS
# define SYS_RT_SIGRET SYS_sigreturn
#else
# define SYS_RT_SIGRET SYS_rt_sigreturn
#endif
#ifndef X64
/* 58 b8 s4 s3 s2 s1 cd 80 */
static const uint non_rt_1w = reverse(0x58b80000 | (reverse(SYS_sigreturn) >> 16));
static const uint non_rt_2w = reverse((reverse(SYS_sigreturn) << 16) | 0xcd80);
#endif
/* b8 s4 s3 s2 s1 cd 80 XX */
static const uint rt_1w = reverse(0xb8000000 | (reverse(SYS_RT_SIGRET) >> 8));
static const uint rt_2w = reverse((reverse(SYS_RT_SIGRET) << 24) | 0x00cd8000);
/* test rt first as it's the most common
* only 7 bytes here so we ignore the last one (becomes msb since little-endian)
*/
if (*((uint *)pc) == rt_1w && (*((uint *)(pc + 4)) & 0x00ffffff) == rt_2w) {
if (len != NULL)
*len = 7;
return true;
}
#ifndef X64
if (*((uint *)pc) == non_rt_1w && *((uint *)(pc + 4)) == non_rt_2w) {
if (len != NULL)
*len = 8;
return true;
}
#endif
return false;
}
void
os_forge_exception(app_pc target_pc, dr_exception_type_t type)
{
/* PR 205136:
* We want to deliver now, and the caller expects us not to return.
* We have two alternatives:
* 1) Emulate stack frame, and call transfer_to_dispatch() for delivery. We
* may not know how to fill out every field of the frame (cr2, etc.). Plus,
* we have problems w/ default actions (PR 205310) but we have to solve
* those long-term anyway. We also have to create different frames based on
* whether app intercepts via rt or not.
* 2) Call SYS_tgkill from a special location that our handler can
* recognize and know it's a signal meant for the app and that the
* interrupted DR can be discarded. We'd then essentially repeat 1,
* but modifying the kernel-generated frame. We'd have to always
* intercept SIGILL.
* I'm going with #1 for now b/c the common case is simpler.
*/
dcontext_t *dcontext = get_thread_private_dcontext();
#if defined(LINUX) && defined(X86)
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
#endif
char frame_no_xstate[sizeof(sigframe_rt_t)];
sigframe_rt_t *frame = (sigframe_rt_t *)frame_no_xstate;
int sig;
dr_where_am_i_t cur_whereami = dcontext->whereami;
kernel_ucontext_t *uc = get_ucontext_from_rt_frame(frame);
sigcontext_t *sc = SIGCXT_FROM_UCXT(uc);
switch (type) {
case ILLEGAL_INSTRUCTION_EXCEPTION: sig = SIGILL; break;
case UNREADABLE_MEMORY_EXECUTION_EXCEPTION: sig = SIGSEGV; break;
case SINGLE_STEP_EXCEPTION: ASSERT_NOT_IMPLEMENTED(false); /* FIXME: i#2144 */
case IN_PAGE_ERROR_EXCEPTION: /* fall-through: Windows only */
default:
ASSERT_NOT_REACHED();
sig = SIGSEGV;
break;
}
LOG(GLOBAL, LOG_ASYNCH, 1, "os_forge_exception sig=%d\n", sig);
/* Since we always delay delivery, we always want an rt frame. we'll convert
* to a plain frame on delivery.
*/
memset(frame, 0, sizeof(*frame));
frame->info.si_signo = sig;
/* Set si_code to match what would happen natively. We also need this to
* avoid the !is_sys_kill() check in record_pending_signal() to avoid an
* infinite loop (i#3171).
*/
frame->info.si_code = IF_LINUX_ELSE(SI_KERNEL, 0);
frame->info.si_addr = target_pc;
#ifdef X86_32
frame->sig = sig;
frame->pinfo = &frame->info;
frame->puc = (void *)&frame->uc;
#endif
#if defined(LINUX) && defined(X86)
/* We use a TLS buffer to avoid too much stack space here. */
sc->fpstate = (kernel_fpstate_t *)get_and_initialize_xstate_buffer(dcontext);
#endif
mcontext_to_ucontext(uc, get_mcontext(dcontext));
sc->SC_XIP = (reg_t)target_pc;
/* We'll fill in fpstate at delivery time.
* We fill in segment registers to their current values and assume they won't
* change and that these are the right values.
*
* FIXME i#2095: restore the app's segment register value(s).
*
* XXX: it seems to work w/o filling in the other state:
* I'm leaving cr2 and other fields all zero.
* If this gets problematic we could switch to approach #2.
*/
thread_set_segment_registers(sc);
#if defined(X86) && defined(LINUX)
if (sig_has_restorer(info, sig))
frame->pretcode = (char *)info->app_sigaction[sig]->restorer;
else
frame->pretcode = (char *)dynamorio_sigreturn;
#endif
/* We assume that we do not need to translate the context when forged.
* If we did, we'd move this below enter_nolinking() (and update
* record_pending_signal() to do the translation).
*/
record_pending_signal(dcontext, sig, &frame->uc, frame,
true /*forged*/
_IF_CLIENT(NULL));
/* For most callers this is not necessary and we only do it to match
* the Windows usage model: but for forging from our own handler,
* this is good b/c it resets us to the base of dstack.
*/
/* tell d_r_dispatch() why we're coming there */
dcontext->whereami = DR_WHERE_TRAMPOLINE;
KSTART(dispatch_num_exits);
set_last_exit(dcontext, (linkstub_t *)get_asynch_linkstub());
if (is_couldbelinking(dcontext))
enter_nolinking(dcontext, NULL, false);
transfer_to_dispatch(
dcontext, get_mcontext(dcontext),
cur_whereami != DR_WHERE_FCACHE && cur_whereami != DR_WHERE_SIGNAL_HANDLER
/*full_DR_state*/);
ASSERT_NOT_REACHED();
}
void
os_request_fatal_coredump(const char *msg)
{
/* To enable getting a coredump just make sure that rlimits are
* not preventing getting one, e.g. ulimit -c unlimited
*/
SYSLOG_INTERNAL_ERROR("Crashing the process deliberately for a core dump!");
os_terminate_via_signal(NULL, 0 /*no cleanup*/, SIGSEGV);
ASSERT_NOT_REACHED();
}
void
os_request_live_coredump(const char *msg)
{
#ifdef VMX86_SERVER
if (os_in_vmkernel_userworld()) {
vmk_request_live_coredump(msg);
return;
}
#endif
LOG(GLOBAL, LOG_ASYNCH, 1,
"LiveCoreDump unsupported (PR 365105). "
"Continuing execution without a core.\n");
return;
}
void
os_dump_core(const char *msg)
{
/* FIXME Case 3408: fork stack dump crashes on 2.6 kernel, so moving the getchar
* ahead to aid in debugging */
if (TEST(DUMPCORE_WAIT_FOR_DEBUGGER, dynamo_options.dumpcore_mask)) {
SYSLOG_INTERNAL_ERROR("looping so you can use gdb to attach to pid %s",
get_application_pid());
IF_CLIENT_INTERFACE(SYSLOG(SYSLOG_CRITICAL, WAITING_FOR_DEBUGGER, 2,
get_application_name(), get_application_pid()));
/* getchar() can hit our own vsyscall hook (from PR 212570); typically we
* want to attach and not continue anyway, so doing an infinite loop:
*/
while (true)
os_thread_yield();
}
if (DYNAMO_OPTION(live_dump)) {
os_request_live_coredump(msg);
}
if (TEST(DUMPCORE_INCLUDE_STACKDUMP, dynamo_options.dumpcore_mask)) {
/* fork, dump core, then use gdb to get a stack dump
* we can get into an infinite loop if there's a seg fault
* in the process of doing this -- so we have a do-once test,
* and if it failed we do the no-symbols dr callstack dump
*/
static bool tried_stackdump = false;
if (!tried_stackdump) {
tried_stackdump = true;
d_r_stackdump();
} else {
static bool tried_calldump = false;
if (!tried_calldump) {
tried_calldump = true;
dump_dr_callstack(STDERR);
}
}
}
if (!DYNAMO_OPTION(live_dump)) {
os_request_fatal_coredump(msg);
ASSERT_NOT_REACHED();
}
}
#ifdef RETURN_AFTER_CALL
bool
at_known_exception(dcontext_t *dcontext, app_pc target_pc, app_pc source_fragment)
{
/* There is a known exception in signal restorers and the Linux
* dynamic symbol resoulution.
* The latter we assume it is the only other recurring known exception,
* so the first time we pattern match to help make sure it is indeed
* _dl_runtime_resolve (since with LD_BIND_NOW it will never be called).
* After that we compare with the known value.
*/
static app_pc known_exception = 0;
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
LOG(THREAD, LOG_INTERP, 1, "RCT: testing for KNOWN exception " PFX " " PFX "\n",
target_pc, source_fragment);
/* Check if this is a signal return.
FIXME: we should really get that from the frame itself.
Since currently grabbing restorer only when copying a frame,
this will work with nested signals only if they all have same restorer
(I haven't seen restorers other than the one in libc)
*/
if (target_pc == info->signal_restorer_retaddr) {
LOG(THREAD, LOG_INTERP, 1,
"RCT: KNOWN exception this is a signal restorer --ok \n");
STATS_INC(ret_after_call_signal_restorer);
return true;
}
if (source_fragment == known_exception) {
LOG(THREAD, LOG_INTERP, 1,
"RCT: KNOWN exception again _dl_runtime_resolve --ok\n");
return true;
}
if (known_exception == 0) {
int ret_imm;
return at_dl_runtime_resolve_ret(dcontext, source_fragment, &ret_imm);
}
return false;
}
#endif /* RETURN_AFTER_CALL */
/***************************************************************************
* ITIMERS
*
* We support combining an app itimer with a DR itimer for each of the 3 types
* (PR 204556).
*/
static inline uint64
timeval_to_usec(struct timeval *t1)
{
return ((uint64)(t1->tv_sec)) * 1000000 + t1->tv_usec;
}
static inline void
usec_to_timeval(uint64 usec, struct timeval *t1)
{
t1->tv_sec = (long)usec / 1000000;
t1->tv_usec = (long)usec % 1000000;
}
static void
init_itimer(dcontext_t *dcontext, bool first)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int i;
ASSERT(info != NULL);
ASSERT(!info->shared_itimer); /* else inherit */
LOG(THREAD, LOG_ASYNCH, 2, "thread has private itimers%s\n",
os_itimers_thread_shared() ? " (for now)" : "");
if (os_itimers_thread_shared()) {
/* we have to allocate now even if no itimer is installed until later,
* so that all child threads point to the same data
*/
info->itimer = (thread_itimer_info_t(*)[NUM_ITIMERS])global_heap_alloc(
sizeof(*info->itimer) HEAPACCT(ACCT_OTHER));
} else {
/* for simplicity and parallel w/ shared we allocate proactively */
info->itimer = (thread_itimer_info_t(*)[NUM_ITIMERS])heap_alloc(
dcontext, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER));
}
memset(info->itimer, 0, sizeof(*info->itimer));
for (i = 0; i < NUM_ITIMERS; i++) {
ASSIGN_INIT_RECURSIVE_LOCK_FREE((*info->itimer)[i].lock, shared_itimer_lock);
}
if (first) {
/* see if app has set up an itimer before we were loaded */
struct itimerval prev;
int rc;
int which;
for (which = 0; which < NUM_ITIMERS; which++) {
rc = getitimer_syscall(which, &prev);
ASSERT(rc == SUCCESS);
(*info->itimer)[which].app.interval = timeval_to_usec(&prev.it_interval);
(*info->itimer)[which].app.value = timeval_to_usec(&prev.it_value);
}
}
}
/* Up to caller to hold lock for shared itimers */
static bool
set_actual_itimer(dcontext_t *dcontext, int which, thread_sig_info_t *info, bool enable)
{
struct itimerval val;
int rc;
ASSERT(info != NULL && info->itimer != NULL);
ASSERT(which >= 0 && which < NUM_ITIMERS);
if (enable) {
LOG(THREAD, LOG_ASYNCH, 2,
"installing itimer %d interval=" INT64_FORMAT_STRING
", value=" INT64_FORMAT_STRING "\n",
which, (*info->itimer)[which].actual.interval,
(*info->itimer)[which].actual.value);
/* i#2907: we have no signal handlers until we start the app (i#2335)
* so we can't set up an itimer until then.
*/
ASSERT(dynamo_initialized);
ASSERT(!info->shared_itimer ||
self_owns_recursive_lock(&(*info->itimer)[which].lock));
usec_to_timeval((*info->itimer)[which].actual.interval, &val.it_interval);
usec_to_timeval((*info->itimer)[which].actual.value, &val.it_value);
} else {
LOG(THREAD, LOG_ASYNCH, 2, "disabling itimer %d\n", which);
memset(&val, 0, sizeof(val));
(*info->itimer)[which].actual.value = 0;
(*info->itimer)[which].actual.interval = 0;
}
rc = setitimer_syscall(which, &val, NULL);
return (rc == SUCCESS);
}
/* Caller should hold lock */
static bool
itimer_new_settings(dcontext_t *dcontext, int which, bool app_changed)
{
struct itimerval val;
bool res = true;
int rc;
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
ASSERT(info != NULL && info->itimer != NULL);
ASSERT(which >= 0 && which < NUM_ITIMERS);
ASSERT(!info->shared_itimer ||
self_owns_recursive_lock(&(*info->itimer)[which].lock));
/* the general strategy is to set the actual value to the smaller,
* update the larger on each signal, and when the larger becomes
* smaller do a one-time swap for the remaining
*/
if ((*info->itimer)[which].dr.interval > 0 &&
((*info->itimer)[which].app.interval == 0 ||
(*info->itimer)[which].dr.interval < (*info->itimer)[which].app.interval))
(*info->itimer)[which].actual.interval = (*info->itimer)[which].dr.interval;
else
(*info->itimer)[which].actual.interval = (*info->itimer)[which].app.interval;
if ((*info->itimer)[which].actual.value > 0) {
if ((*info->itimer)[which].actual.interval == 0 &&
(*info->itimer)[which].dr.value == 0 &&
(*info->itimer)[which].app.value == 0) {
(*info->itimer)[which].actual.value = 0;
res = set_actual_itimer(dcontext, which, info, false /*disabled*/);
} else {
/* one of app or us has an in-flight timer which we should not interrupt.
* but, we already set the new requested value (for app or us), so we
* need to update the actual value so we subtract properly.
*/
rc = getitimer_syscall(which, &val);
ASSERT(rc == SUCCESS);
uint64 left = timeval_to_usec(&val.it_value);
if (!app_changed &&
(*info->itimer)[which].actual.value == (*info->itimer)[which].app.value)
(*info->itimer)[which].app.value = left;
if (app_changed &&
(*info->itimer)[which].actual.value == (*info->itimer)[which].dr.value)
(*info->itimer)[which].dr.value = left;
(*info->itimer)[which].actual.value = left;
}
} else {
if ((*info->itimer)[which].dr.value > 0 &&
((*info->itimer)[which].app.value == 0 ||
(*info->itimer)[which].dr.value < (*info->itimer)[which].app.value))
(*info->itimer)[which].actual.value = (*info->itimer)[which].dr.value;
else {
(*info->itimer)[which].actual.value = (*info->itimer)[which].app.value;
}
res = set_actual_itimer(dcontext, which, info, true /*enable*/);
}
return res;
}
bool
set_itimer_callback(dcontext_t *dcontext, int which, uint millisec,
void (*func)(dcontext_t *, priv_mcontext_t *),
void (*func_api)(dcontext_t *, dr_mcontext_t *))
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
bool rc;
if (which < 0 || which >= NUM_ITIMERS) {
CLIENT_ASSERT(false, "invalid itimer type");
return false;
}
if (func == NULL && func_api == NULL && millisec != 0) {
CLIENT_ASSERT(false, "invalid function");
return false;
}
ASSERT(info != NULL && info->itimer != NULL);
if (info->shared_itimer)
acquire_recursive_lock(&(*info->itimer)[which].lock);
(*info->itimer)[which].dr.interval = ((uint64)millisec) * 1000;
(*info->itimer)[which].dr.value = (*info->itimer)[which].dr.interval;
(*info->itimer)[which].cb = func;
(*info->itimer)[which].cb_api = func_api;
if (!dynamo_initialized) {
/* i#2907: we have no signal handlers until we start the app (i#2335)
* so we can't set up an itimer until then. start_itimer() called
* from os_thread_under_dynamo() will enable it.
*/
LOG(THREAD, LOG_ASYNCH, 2, "delaying itimer until attach\n");
rc = true;
} else
rc = itimer_new_settings(dcontext, which, false /*us*/);
if (info->shared_itimer)
release_recursive_lock(&(*info->itimer)[which].lock);
return rc;
}
uint
get_itimer_frequency(dcontext_t *dcontext, int which)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
uint ms = 0;
if (which < 0 || which >= NUM_ITIMERS) {
CLIENT_ASSERT(false, "invalid itimer type");
return 0;
}
ASSERT(info != NULL && info->itimer != NULL);
if (info->shared_itimer)
acquire_recursive_lock(&(*info->itimer)[which].lock);
ms = (*info->itimer)[which].dr.interval / 1000;
if (info->shared_itimer)
release_recursive_lock(&(*info->itimer)[which].lock);
return ms;
}
static int
signal_to_itimer_type(int sig)
{
if (sig == SIGALRM)
return ITIMER_REAL;
else if (sig == SIGVTALRM)
return ITIMER_VIRTUAL;
else if (sig == SIGPROF)
return ITIMER_PROF;
else
return -1;
}
static bool
alarm_signal_has_DR_only_itimer(dcontext_t *dcontext, int signal)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
int which = signal_to_itimer_type(signal);
if (which == -1)
return false;
if (info->shared_itimer)
acquire_recursive_lock(&(*info->itimer)[which].lock);
bool DR_only =
((*info->itimer)[which].dr.value > 0 || (*info->itimer)[which].dr.interval > 0) &&
(*info->itimer)[which].app.value == 0 && (*info->itimer)[which].app.interval == 0;
if (info->shared_itimer)
release_recursive_lock(&(*info->itimer)[which].lock);
return DR_only;
}
static bool
handle_alarm(dcontext_t *dcontext, int sig, kernel_ucontext_t *ucxt)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
ASSERT(info != NULL && info->itimer != NULL);
int which = 0;
bool invoke_cb = false, pass_to_app = false, reset_timer_manually = false;
bool should_release_lock = false;
/* i#471: suppress alarms coming in after exit */
if (dynamo_exited)
return pass_to_app;
which = signal_to_itimer_type(sig);
ASSERT(which != -1);
LOG(THREAD, LOG_ASYNCH, 2, "received alarm %d @" PFX "\n", which,
SIGCXT_FROM_UCXT(ucxt)->SC_XIP);
/* This alarm could have interrupted an app thread making an itimer syscall,
* which is why we don't want to block on a lock here.
* It can't interrupt this same thread handling a prior alarm (b/c we block
* the signal in our handler). It could arrive in thread B while thread A
* is still handling a prior alarm if the alarm frequency is high and the
* processing is slow, which is why we split the locks to be per-itimer-type.
* We also avoid new thread setup code acquiring these itimer locks by using
* atomic increments instead for the refcounts. Xref i#2993.
*/
if (info->shared_itimer) {
#ifdef DEADLOCK_AVOIDANCE
/* i#2061: in debug build we can get an alarm while in deadlock handling
* code that holds innermost_lock. We just drop such alarms.
*/
if (OWN_MUTEX(&innermost_lock))
return pass_to_app;
#endif
if (self_owns_recursive_lock(&(*info->itimer)[which].lock)) {
/* What can we do? We just go ahead and hope conflicting writes work out.
* We don't re-acquire in case app was in middle of acquiring.
*/
} else {
#define ALARM_LOCK_MAX_TRIES 4
int i;
for (i = 0; i < ALARM_LOCK_MAX_TRIES; ++i) {
if (try_recursive_lock(&(*info->itimer)[which].lock)) {
should_release_lock = true;
break;
}
os_thread_yield();
}
if (!should_release_lock) {
/* Heuristic: if fail N times then assume interrupted lock routine
* while processing an app syscall (see above: we ruled out other
* scenarios). What can we do? Just continue and hope conflicting
* writes work out.
*/
}
}
}
if ((*info->itimer)[which].app.value > 0) {
/* Alarm could have been on its way when app value changed */
if ((*info->itimer)[which].app.value >= (*info->itimer)[which].actual.value) {
(*info->itimer)[which].app.value -= (*info->itimer)[which].actual.value;
LOG(THREAD, LOG_ASYNCH, 2, "\tapp value is now %d\n",
(*info->itimer)[which].app.value);
if ((*info->itimer)[which].app.value == 0) {
pass_to_app = true;
(*info->itimer)[which].app.value = (*info->itimer)[which].app.interval;
} else
reset_timer_manually = true;
}
}
if ((*info->itimer)[which].dr.value > 0) {
/* Alarm could have been on its way when DR value changed */
if ((*info->itimer)[which].dr.value >= (*info->itimer)[which].actual.value) {
(*info->itimer)[which].dr.value -= (*info->itimer)[which].actual.value;
LOG(THREAD, LOG_ASYNCH, 2, "\tdr value is now %d\n",
(*info->itimer)[which].dr.value);
if ((*info->itimer)[which].dr.value == 0) {
invoke_cb = true;
(*info->itimer)[which].dr.value = (*info->itimer)[which].dr.interval;
} else
reset_timer_manually = true;
}
}
/* for efficiency we let the kernel reset the value to interval if
* there's only one timer
*/
if (reset_timer_manually) {
(*info->itimer)[which].actual.value = 0;
itimer_new_settings(dcontext, which, true /*doesn't matter: actual.value==0*/);
} else
(*info->itimer)[which].actual.value = (*info->itimer)[which].actual.interval;
if (invoke_cb) {
/* invoke after setting new itimer value */
/* we save stack space by allocating superset dr_mcontext_t */
dr_mcontext_t dmc;
dr_mcontext_init(&dmc);
priv_mcontext_t *mc = dr_mcontext_as_priv_mcontext(&dmc);
ucontext_to_mcontext(mc, ucxt);
void (*cb)(dcontext_t *, priv_mcontext_t *) = (*info->itimer)[which].cb;
void (*cb_api)(dcontext_t *, dr_mcontext_t *) = (*info->itimer)[which].cb_api;
if (which == ITIMER_VIRTUAL && info->shared_itimer && should_release_lock) {
release_recursive_lock(&(*info->itimer)[which].lock);
should_release_lock = false;
}
if (cb != NULL) {
cb(dcontext, mc);
} else {
cb_api(dcontext, &dmc);
}
}
if (info->shared_itimer && should_release_lock)
release_recursive_lock(&(*info->itimer)[which].lock);
return pass_to_app;
}
/* Starts itimer if stopped, or increases refcount of existing itimer if already
* started. It is *not* safe to call this more than once for the same thread,
* since it will inflate the refcount and prevent cleanup.
*/
void
start_itimer(dcontext_t *dcontext)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
ASSERT(info != NULL && info->itimer != NULL);
bool start = false;
if (info->shared_itimer) {
/* i#2993: We avoid acquiring the lock as an alarm signal can arrive during
* the lock routine (esp in debug build) and cause problems.
*/
int new_count =
atomic_add_exchange_int((volatile int *)info->shared_itimer_underDR, 1);
start = (new_count == 1);
} else
start = true;
if (start) {
/* Enable all DR itimers b/c at least one thread in this set of threads
* sharing itimers is under DR control
*/
int which;
LOG(THREAD, LOG_ASYNCH, 2, "starting DR itimers from thread " TIDFMT "\n",
d_r_get_thread_id());
for (which = 0; which < NUM_ITIMERS; which++) {
if (info->shared_itimer)
acquire_recursive_lock(&(*info->itimer)[which].lock);
/* May have already been set up with the start delayed (i#2907). */
if ((*info->itimer)[which].dr.interval > 0) {
(*info->itimer)[which].dr.value = (*info->itimer)[which].dr.interval;
itimer_new_settings(dcontext, which, false /*!app*/);
}
if (info->shared_itimer)
release_recursive_lock(&(*info->itimer)[which].lock);
}
}
}
/* Decrements the itimer refcount, and turns off the itimer once there are no
* more threads listening for it. It is not safe to call this more than once on
* the same thread.
*/
void
stop_itimer(dcontext_t *dcontext)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
ASSERT(info != NULL && info->itimer != NULL);
bool stop = false;
if (info->shared_itimer) {
ASSERT(*info->shared_itimer_underDR > 0);
int new_count =
atomic_add_exchange_int((volatile int *)info->shared_itimer_underDR, -1);
stop = (new_count == 0);
} else
stop = true;
if (stop) {
/* Disable all DR itimers b/c this set of threads sharing this
* itimer is now completely native
*/
int which;
LOG(THREAD, LOG_ASYNCH, 2, "stopping DR itimers from thread " TIDFMT "\n",
d_r_get_thread_id());
for (which = 0; which < NUM_ITIMERS; which++) {
if (info->shared_itimer)
acquire_recursive_lock(&(*info->itimer)[which].lock);
if ((*info->itimer)[which].dr.value > 0) {
(*info->itimer)[which].dr.value = 0;
if ((*info->itimer)[which].app.value > 0) {
(*info->itimer)[which].actual.interval =
(*info->itimer)[which].app.interval;
} else
set_actual_itimer(dcontext, which, info, false /*disable*/);
}
if (info->shared_itimer)
release_recursive_lock(&(*info->itimer)[which].lock);
}
}
}
/* handle app itimer syscalls */
/* handle_pre_alarm also calls this function and passes NULL as prev_timer */
void
handle_pre_setitimer(dcontext_t *dcontext, int which, const struct itimerval *new_timer,
struct itimerval *prev_timer)
{
if (new_timer == NULL || which < 0 || which >= NUM_ITIMERS)
return;
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
ASSERT(info != NULL && info->itimer != NULL);
struct itimerval val;
if (d_r_safe_read(new_timer, sizeof(val), &val)) {
if (info->shared_itimer)
acquire_recursive_lock(&(*info->itimer)[which].lock);
/* save a copy in case the syscall fails */
(*info->itimer)[which].app_saved = (*info->itimer)[which].app;
(*info->itimer)[which].app.interval = timeval_to_usec(&val.it_interval);
(*info->itimer)[which].app.value = timeval_to_usec(&val.it_value);
LOG(THREAD, LOG_ASYNCH, 2,
"app setitimer type=%d interval=" SZFMT " value=" SZFMT "\n", which,
(*info->itimer)[which].app.interval, (*info->itimer)[which].app.value);
itimer_new_settings(dcontext, which, true /*app*/);
if (info->shared_itimer)
release_recursive_lock(&(*info->itimer)[which].lock);
}
}
void
handle_post_setitimer(dcontext_t *dcontext, bool success, int which,
const struct itimerval *new_timer, struct itimerval *prev_timer)
{
if (new_timer == NULL || which < 0 || which >= NUM_ITIMERS) {
ASSERT(new_timer == NULL || !success);
return;
}
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
ASSERT(info != NULL && info->itimer != NULL);
ASSERT(which >= 0 && which < NUM_ITIMERS);
if (!success && new_timer != NULL) {
if (info->shared_itimer)
acquire_recursive_lock(&(*info->itimer)[which].lock);
/* restore saved pre-syscall settings */
(*info->itimer)[which].app = (*info->itimer)[which].app_saved;
itimer_new_settings(dcontext, which, true /*app*/);
if (info->shared_itimer)
release_recursive_lock(&(*info->itimer)[which].lock);
}
if (success && prev_timer != NULL)
handle_post_getitimer(dcontext, success, which, prev_timer);
}
void
handle_post_getitimer(dcontext_t *dcontext, bool success, int which,
struct itimerval *cur_timer)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
ASSERT(info != NULL && info->itimer != NULL);
if (success) {
/* write succeeded for kernel but we're user and can have races */
struct timeval val;
DEBUG_DECLARE(bool ok;)
ASSERT(which >= 0 && which < NUM_ITIMERS);
ASSERT(cur_timer != NULL);
if (info->shared_itimer)
acquire_recursive_lock(&(*info->itimer)[which].lock);
usec_to_timeval((*info->itimer)[which].app.interval, &val);
IF_DEBUG(ok =)
safe_write_ex(&cur_timer->it_interval, sizeof(val), &val, NULL);
ASSERT(ok);
if (d_r_safe_read(&cur_timer->it_value, sizeof(val), &val)) {
/* subtract the difference between last-asked-for value
* and current value to reflect elapsed time
*/
uint64 left = (*info->itimer)[which].app.value -
((*info->itimer)[which].actual.value - timeval_to_usec(&val));
usec_to_timeval(left, &val);
IF_DEBUG(ok =)
safe_write_ex(&cur_timer->it_value, sizeof(val), &val, NULL);
ASSERT(ok);
} else
ASSERT_NOT_REACHED();
if (info->shared_itimer)
release_recursive_lock(&(*info->itimer)[which].lock);
}
}
/* handle app alarm syscall */
/* alarm uses the same itimer and could be defined in terms of setitimer */
void
handle_pre_alarm(dcontext_t *dcontext, unsigned int sec)
{
struct itimerval val;
val.it_interval.tv_usec = 0;
val.it_interval.tv_sec = 0;
val.it_value.tv_usec = 0;
val.it_value.tv_sec = sec;
handle_pre_setitimer(dcontext, ITIMER_REAL, &val, NULL);
}
void
handle_post_alarm(dcontext_t *dcontext, bool success, unsigned int sec)
{
/* alarm is always successful, so do nothing in post */
ASSERT(success);
return;
}
/***************************************************************************
* Internal DR communication
*/
typedef struct _sig_detach_info_t {
KSYNCH_TYPE *detached;
byte *sigframe_xsp;
#ifdef HAVE_SIGALTSTACK
stack_t *app_sigstack;
#endif
} sig_detach_info_t;
/* xsp is only set for X86 */
static void
notify_and_jmp_without_stack(KSYNCH_TYPE *notify_var, byte *continuation, byte *xsp)
{
if (ksynch_kernel_support()) {
/* Can't use dstack once we signal so in asm we do:
* futex/semaphore = 1;
* %xsp = xsp;
* dynamorio_condvar_wake_and_jmp(notify_var, continuation);
*/
#ifdef MACOS
ASSERT(sizeof(notify_var->sem) == 4);
#endif
#ifdef X86
# ifndef MACOS
/* i#2632: recent clang for 32-bit annoyingly won't do the right thing for
* "jmp dynamorio_condvar_wake_and_jmp" and leaves relocs so we ensure it's PIC.
* We do this first as it may end up clobbering a scratch reg like xax.
*/
void (*asm_jmp_tgt)() = dynamorio_condvar_wake_and_jmp;
asm("mov %0, %%" ASM_XDX : : "m"(asm_jmp_tgt));
# endif
asm("mov %0, %%" ASM_XAX : : "m"(notify_var));
asm("mov %0, %%" ASM_XCX : : "m"(continuation));
asm("mov %0, %%" ASM_XSP : : "m"(xsp));
# ifdef MACOS
asm("movl $1,4(%" ASM_XAX ")");
asm("jmp _dynamorio_condvar_wake_and_jmp");
# else
asm("movl $1,(%" ASM_XAX ")");
asm("jmp *%" ASM_XDX);
# endif
#elif defined(AARCHXX)
asm("ldr " ASM_R0 ", %0" : : "m"(notify_var));
asm("mov " ASM_R1 ", #1");
asm("str " ASM_R1 ",[" ASM_R0 "]");
asm("ldr " ASM_R1 ", %0" : : "m"(continuation));
asm("b dynamorio_condvar_wake_and_jmp");
#endif
} else {
ksynch_set_value(notify_var, 1);
#ifdef X86
asm("mov %0, %%" ASM_XSP : : "m"(xsp));
asm("mov %0, %%" ASM_XAX : : "m"(continuation));
asm("jmp *%" ASM_XAX);
#elif defined(AARCHXX)
asm("ldr " ASM_R0 ", %0" : : "m"(continuation));
asm(ASM_INDJMP " " ASM_R0);
#endif /* X86/ARM */
}
}
/* Go native from detach. This is executed on the app stack. */
static void
sig_detach_go_native(sig_detach_info_t *info)
{
byte *xsp = info->sigframe_xsp;
#ifdef HAVE_SIGALTSTACK
/* Restore the app signal stack, though sigreturn will overwrite this with the
* uc_stack in the frame's ucontext anyway (which we already set for the app).
*/
DEBUG_DECLARE(int rc =)
sigaltstack_syscall(info->app_sigstack, NULL);
ASSERT(rc == 0);
#endif
#ifdef X86
/* Skip pretcode */
xsp += sizeof(char *);
#endif
notify_and_jmp_without_stack(info->detached, (byte *)dynamorio_sigreturn, xsp);
ASSERT_NOT_REACHED();
}
/* Sets this (slave) thread to detach by directly returning from the signal. */
static void
sig_detach(dcontext_t *dcontext, sigframe_rt_t *frame, KSYNCH_TYPE *detached)
{
thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field;
byte *xsp;
sig_detach_info_t detach_info;
LOG(THREAD, LOG_ASYNCH, 1, "%s: detaching\n", __FUNCTION__);
/* Update the mask of the signal frame so that the later sigreturn will
* restore the app signal mask.
*/
memcpy(&frame->uc.uc_sigmask, &info->app_sigblocked, sizeof(info->app_sigblocked));
/* Copy the signal frame to the app stack.
* XXX: We live with the transparency risk of storing the signal frame on
* the app stack: we assume the app stack is writable where we need it to be,
* and that we're not clobbering any app data beyond TOS.
*/
xsp = get_sigstack_frame_ptr(dcontext, SUSPEND_SIGNAL, frame);
copy_frame_to_stack(dcontext, SUSPEND_SIGNAL, frame, xsp, false /*!pending*/);
#ifdef HAVE_SIGALTSTACK
/* Make sure the frame's sigstack reflects the app stack.
* copy_frame_to_stack() should have done this for us.
*/
ASSERT(((sigframe_rt_t *)xsp)->uc.uc_stack.ss_sp == info->app_sigstack.ss_sp);
#endif
/* Restore app segment registers. */
os_thread_not_under_dynamo(dcontext);
os_tls_thread_exit(dcontext->local_state);
#ifdef HAVE_SIGALTSTACK
/* We can't restore the app's sigstack here as that will invalidate the
* sigstack we're currently on.
*/
detach_info.app_sigstack = &info->app_sigstack;
#endif
detach_info.detached = detached;
detach_info.sigframe_xsp = xsp;
call_switch_stack(&detach_info, xsp, (void (*)(void *))sig_detach_go_native,
false /*free_initstack*/, false /*do not return*/);
ASSERT_NOT_REACHED();
}
/* Returns whether to pass on to app */
static bool
handle_suspend_signal(dcontext_t *dcontext, kernel_ucontext_t *ucxt, sigframe_rt_t *frame)
{
os_thread_data_t *ostd = (os_thread_data_t *)dcontext->os_field;
kernel_sigset_t prevmask;
sig_full_cxt_t sc_full;
ASSERT(ostd != NULL);
if (ostd->terminate) {
/* PR 297902: exit this thread, without using the dstack */
/* For MacOS, we need a stack as 32-bit syscalls take args on the stack.
* We go ahead and use it for x86 too for simpler sysenter return.
* We don't have a lot of options: we're terminating, so we go ahead
* and use the app stack.
*/
byte *app_xsp;
if (IS_CLIENT_THREAD(dcontext))
app_xsp = (byte *)SIGCXT_FROM_UCXT(ucxt)->SC_XSP;
else
app_xsp = (byte *)get_mcontext(dcontext)->xsp;
LOG(THREAD, LOG_ASYNCH, 2, "handle_suspend_signal: exiting\n");
ASSERT(app_xsp != NULL);
notify_and_jmp_without_stack(&ostd->terminated, (byte *)dynamorio_sys_exit,
app_xsp);
ASSERT_NOT_REACHED();
return false;
}
if (!doing_detach && is_thread_currently_native(dcontext->thread_record) &&
!IS_CLIENT_THREAD(dcontext) IF_APP_EXPORTS(&&!dr_api_exit)) {
if (!sig_take_over(ucxt))
return false;
ASSERT_NOT_REACHED(); /* else, shouldn't return */
}
/* If suspend_count is 0, we are not trying to suspend this thread
* (os_thread_resume() may have already decremented suspend_count to 0, but
* os_thread_suspend() will not send a signal until this thread unsets
* ostd->suspended, so not having a lock around the suspend_count read is
* ok), so pass signal to app.
* If we are trying or have already suspended this thread, our own
* os_thread_suspend() will not send a 2nd suspend signal until we are
* completely resumed, so we can distinguish app uses of SUSPEND_SIGNAL. We
* can't have a race between the read and write of suspended_sigcxt b/c
* signals are blocked. It's fine to have a race and reorder the app's
* signal w/ DR's.
*/
if (ostd->suspend_count == 0)
return true; /* pass to app */
ASSERT(ostd->suspended_sigcxt == NULL);
/* XXX: we're not setting DR_WHERE_SIGNAL_HANDLER in enough places.
* It's trickier than other whereamis b/c we want to resume the
* prior whereami when we return from the handler, but there are
* complex control paths that do not always return.
* We try to at least do it for the ksynch_wait here.
*/
dr_where_am_i_t prior_whereami = dcontext->whereami;
dcontext->whereami = DR_WHERE_SIGNAL_HANDLER;
sig_full_initialize(&sc_full, ucxt);
ostd->suspended_sigcxt = &sc_full;
LOG(THREAD, LOG_ASYNCH, 2, "handle_suspend_signal: suspended now\n");
/* We cannot use mutexes here as we have interrupted DR at an
* arbitrary point! Thus we can't use the event_t routines.
* However, the existing synch and check above prevent any
* re-entrance here, and our cond vars target just a single thread,
* so we can get away w/o a mutex.
*/
/* Notify os_thread_suspend that it can now return, as this thread is
* officially suspended now and is ready for thread_{get,set}_mcontext.
*/
ASSERT(ksynch_get_value(&ostd->suspended) == 0);
ksynch_set_value(&ostd->suspended, 1);
ksynch_wake_all(&ostd->suspended);
/* We're sitting on our sigaltstack w/ all signals blocked. We're
* going to stay here but unblock all signals so we don't lose any
* delivered while we're waiting. We're at a safe enough point (now
* that we've set ostd->suspended: i#5779) to re-enter
* master_signal_handler(). We use a mutex in thread_{suspend,resume} to
* prevent our own re-suspension signal from arriving before we've
* re-blocked on the resume.
*/
sigprocmask_syscall(SIG_SETMASK, SIGMASK_FROM_UCXT(ucxt), &prevmask,
sizeof(ucxt->uc_sigmask));
/* i#96/PR 295561: use futex(2) if available */
while (ksynch_get_value(&ostd->wakeup) == 0) {
/* Waits only if the wakeup flag is not set as 1. Return value
* doesn't matter because the flag will be re-checked.
*/
ksynch_wait(&ostd->wakeup, 0, 0);
if (ksynch_get_value(&ostd->wakeup) == 0) {
/* If it still has to wait, give up the cpu. */
os_thread_yield();
}
}
LOG(THREAD, LOG_ASYNCH, 2, "handle_suspend_signal: awake now\n");
/* re-block so our exit from master_signal_handler is not interrupted */
sigprocmask_syscall(SIG_SETMASK, &prevmask, NULL, sizeof(prevmask));
ostd->suspended_sigcxt = NULL;
/* Notify os_thread_resume that it can return now, which (assuming
* suspend_count is back to 0) means it's then safe to re-suspend.
*/
ksynch_set_value(&ostd->suspended, 0); /*reset prior to signalling os_thread_resume*/
ksynch_set_value(&ostd->resumed, 1);
ksynch_wake_all(&ostd->resumed);
dcontext->whereami = prior_whereami;
if (ostd->retakeover) {
ostd->retakeover = false;
sig_take_over(ucxt); /* shouldn't return for this case */
ASSERT_NOT_REACHED();
} else if (ostd->do_detach) {
ostd->do_detach = false;
sig_detach(dcontext, frame, &ostd->detached); /* no return */
ASSERT_NOT_REACHED();
}
return false; /* do not pass to app */
}
/* PR 206278: for try/except we need to save the signal mask */
void
dr_setjmp_sigmask(dr_jmp_buf_t *buf)
{
/* i#226/PR 492568: we rely on the kernel storing the prior mask in the
* signal frame, so we do not need to store it on every setjmp, which
* can be a performance hit.
*/
#ifdef DEBUG
sigprocmask_syscall(SIG_SETMASK, NULL, &buf->sigmask, sizeof(buf->sigmask));
#endif
}
/* i#61/PR 211530: nudge on Linux.
* Determines whether this is a nudge signal, and if so queues up a nudge,
* or is an app signal. Returns whether to pass the signal on to the app.
*/
static bool
handle_nudge_signal(dcontext_t *dcontext, kernel_siginfo_t *siginfo,
kernel_ucontext_t *ucxt)
{
sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt);
nudge_arg_t *arg = (nudge_arg_t *)siginfo;
instr_t instr;
char buf[MAX_INSTR_LENGTH];
/* Distinguish a nudge from an app signal. An app using libc sigqueue()
* will never have its signal mistaken as libc does not expose the kernel_siginfo_t
* and always passes 0 for si_errno, so we're only worried beyond our
* si_code check about an app using a raw syscall that is deliberately
* trying to fool us.
* While there is a lot of padding space in kernel_siginfo_t, the kernel doesn't
* copy it through on SYS_rt_sigqueueinfo so we don't have room for any
* dedicated magic numbers. The client id could function as a magic
* number for client nudges, but I don't think we want to kill the app
* if an external nudger types the client id wrong.
*/
LOG(THREAD, LOG_ASYNCH, 2, "%s: sig=%d code=%d errno=%d\n", __FUNCTION__,
siginfo->si_signo, siginfo->si_code, siginfo->si_errno);
if (siginfo->si_signo !=
NUDGESIG_SIGNUM
/* PR 477454: remove the IF_NOT_VMX86 once we have nudge-arg support */
IF_NOT_VMX86(|| siginfo->si_code != SI_QUEUE || siginfo->si_errno == 0)) {
return true; /* pass to app */
}
#if defined(CLIENT_INTERFACE) && !defined(VMX86_SERVER)
DODEBUG({
if (TEST(NUDGE_GENERIC(client), arg->nudge_action_mask) &&
!is_valid_client_id(arg->client_id)) {
SYSLOG_INTERNAL_WARNING("received client nudge for invalid id=0x%x",
arg->client_id);
}
});
#endif
if (dynamo_exited || !dynamo_initialized || dcontext == NULL) {
/* Ignore the nudge: too early, or too late.
* Xref Windows handling of such cases in nudge.c: old case 5702, etc.
* We do this before the illegal-instr check b/c it's unsafe to decode
* if too early or too late.
*/
SYSLOG_INTERNAL_WARNING("too-early or too-late nudge: ignoring");
return false; /* do not pass to app */
}
/* As a further check, try to detect whether this was raised synchronously
* from a real illegal instr: though si_code for that should not be
* SI_QUEUE. It's possible a nudge happened to come at a bad instr before
* it faulted, or maybe the instr after a syscall or other wait spot is
* illegal, but we'll live with that risk.
*/
ASSERT(NUDGESIG_SIGNUM == SIGILL); /* else this check makes no sense */
instr_init(dcontext, &instr);
if (d_r_safe_read((byte *)sc->SC_XIP, sizeof(buf), buf) &&
(decode(dcontext, (byte *)buf, &instr) == NULL ||
/* check for ud2 (xref PR 523161) */
instr_is_undefined(&instr))) {
LOG(THREAD, LOG_ASYNCH, 2, "%s: real illegal instr @" PFX "\n", __FUNCTION__,
sc->SC_XIP);
DOLOG(2, LOG_ASYNCH,
{ disassemble_with_bytes(dcontext, (byte *)sc->SC_XIP, THREAD); });
instr_free(dcontext, &instr);
return true; /* pass to app */
}
instr_free(dcontext, &instr);
#ifdef VMX86_SERVER
/* Treat as a client nudge until we have PR 477454 */
if (siginfo->si_errno == 0) {
arg->version = NUDGE_ARG_CURRENT_VERSION;
arg->flags = 0;
arg->nudge_action_mask = NUDGE_GENERIC(client);
arg->client_id = 0;
arg->client_arg = 0;
}
#endif
LOG(THREAD, LOG_ASYNCH, 1,
"received nudge version=%u flags=0x%x mask=0x%x id=0x%08x "
"arg=0x" ZHEX64_FORMAT_STRING "\n",
arg->version, arg->flags, arg->nudge_action_mask, arg->client_id,
arg->client_arg);
SYSLOG_INTERNAL_INFO("received nudge mask=0x%x id=0x%08x arg=0x" ZHEX64_FORMAT_STRING,
arg->nudge_action_mask, arg->client_id, arg->client_arg);
/* We need to handle the nudge at a safe, nolinking spot */
if (safe_is_in_fcache(dcontext, (byte *)sc->SC_XIP, (byte *)sc->SC_XSP) &&
dcontext->interrupted_for_nudge == NULL) {
/* We unlink the interrupted fragment and skip any inlined syscalls to
* bound the nudge delivery time. If we already unlinked one we assume
* that's sufficient.
*/
fragment_t wrapper;
fragment_t *f = fragment_pclookup(dcontext, (byte *)sc->SC_XIP, &wrapper);
if (f != NULL) {
if (unlink_fragment_for_signal(dcontext, f, (byte *)sc->SC_XIP))
dcontext->interrupted_for_nudge = f;
}
}
/* No lock is needed since thread-private and this signal is blocked now */
nudge_add_pending(dcontext, arg);
return false; /* do not pass to app */
}
| 1 | 19,089 | Why did you not add the signals to the call of block_all_signals_except() and instead baked them into the function? Ok, if you had a good reason for it, otherwise I would add it to the except list of the function call, since that's what it was meant for. | DynamoRIO-dynamorio | c |
@@ -0,0 +1,13 @@
+package de.danoeh.antennapod.core.storage;
+
+import android.support.annotation.NonNull;
+
+import de.danoeh.antennapod.core.feed.FeedFile;
+
+public interface FeedFileDownloadStatusRequesterInterface {
+ /**
+ * @return {@code true} if the named feedfile is in the downloads list
+ */
+ boolean isDownloadingFile(@NonNull FeedFile item);
+
+} | 1 | 1 | 13,932 | Could this be done by mocking objects instead? I feel like this is changing too much of the actual logic just for the tests. | AntennaPod-AntennaPod | java |
|
@@ -27,6 +27,7 @@ public class ManifestFileBean implements ManifestFile {
private String path = null;
private Long length = null;
private Integer partitionSpecId = null;
+ private Integer content = null;
private Long addedSnapshotId = null;
public String getPath() { | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iceberg.actions;
import java.util.List;
import org.apache.iceberg.ManifestContent;
import org.apache.iceberg.ManifestFile;
public class ManifestFileBean implements ManifestFile {
private String path = null;
private Long length = null;
private Integer partitionSpecId = null;
private Long addedSnapshotId = null;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Long getLength() {
return length;
}
public void setLength(Long length) {
this.length = length;
}
public Integer getPartitionSpecId() {
return partitionSpecId;
}
public void setPartitionSpecId(Integer partitionSpecId) {
this.partitionSpecId = partitionSpecId;
}
public Long getAddedSnapshotId() {
return addedSnapshotId;
}
public void setAddedSnapshotId(Long addedSnapshotId) {
this.addedSnapshotId = addedSnapshotId;
}
@Override
public String path() {
return path;
}
@Override
public long length() {
return length;
}
@Override
public int partitionSpecId() {
return partitionSpecId;
}
@Override
public ManifestContent content() {
return ManifestContent.DATA;
}
@Override
public long sequenceNumber() {
return 0;
}
@Override
public long minSequenceNumber() {
return 0;
}
@Override
public Long snapshotId() {
return addedSnapshotId;
}
@Override
public Integer addedFilesCount() {
return null;
}
@Override
public Long addedRowsCount() {
return null;
}
@Override
public Integer existingFilesCount() {
return null;
}
@Override
public Long existingRowsCount() {
return null;
}
@Override
public Integer deletedFilesCount() {
return null;
}
@Override
public Long deletedRowsCount() {
return null;
}
@Override
public List<PartitionFieldSummary> partitions() {
return null;
}
@Override
public ManifestFile copy() {
throw new UnsupportedOperationException("Cannot copy");
}
}
| 1 | 36,698 | why not just use `ManifestContent` instead of `Integer`? | apache-iceberg | java |
@@ -260,8 +260,16 @@ namespace Nethermind.TxPool
}
Metrics.PendingTransactionsReceived++;
-
- if (!_validator.IsWellFormed(tx, _specProvider.GetSpec()))
+
+ IReleaseSpec releaseSpec = _specProvider.GetSpec();
+ if (tx.Type == TxType.AccessList && !releaseSpec.IsEip2930Enabled)
+ {
+ Metrics.PendingTransactionsDiscarded++;
+ if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, wrong transaction type {tx.Type}.");
+ return AddTxResult.Invalid;
+ }
+
+ if (!_validator.IsWellFormed(tx, releaseSpec))
{
// It may happen that other nodes send us transactions that were signed for another chain or don't have enough gas.
Metrics.PendingTransactionsDiscarded++; | 1 | // Copyright (c) 2021 Demerzel Solutions Limited
// This file is part of the Nethermind library.
//
// The Nethermind 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 3 of the License, or
// (at your option) any later version.
//
// The Nethermind library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Nethermind.Core;
using Nethermind.Core.Caching;
using Nethermind.Core.Crypto;
using Nethermind.Core.Specs;
using Nethermind.Crypto;
using Nethermind.Int256;
using Nethermind.Logging;
using Nethermind.State;
using Nethermind.TxPool.Collections;
using Timer = System.Timers.Timer;
[assembly: InternalsVisibleTo("Nethermind.Blockchain.Test")]
namespace Nethermind.TxPool
{
/// <summary>
/// Stores all pending transactions. These will be used by block producer if this node is a miner / validator
/// or simply for broadcasting and tracing in other cases.
/// </summary>
public class TxPool : ITxPool, IDisposable
{
public static IComparer<Transaction> DefaultComparer { get; } =
CompareTxByGasPrice.Instance
.ThenBy(CompareTxByTimestamp.Instance)
.ThenBy(CompareTxByPoolIndex.Instance)
.ThenBy(CompareTxByGasLimit.Instance);
private readonly object _locker = new();
private readonly Dictionary<Address, AddressNonces> _nonces =
new();
private readonly LruKeyCache<Keccak> _hashCache = new(MemoryAllowance.TxHashCacheSize,
Math.Min(1024 * 16, MemoryAllowance.TxHashCacheSize), "tx hashes");
/// <summary>
/// Number of blocks after which own transaction will not be resurrected any more
/// </summary>
private const long FadingTimeInBlocks = 64;
/// <summary>
/// Notification threshold randomizer seed
/// </summary>
private static int _seed = Environment.TickCount;
/// <summary>
/// Random number generator for peer notification threshold - no need to be securely random.
/// </summary>
private static readonly ThreadLocal<Random> Random =
new(() => new Random(Interlocked.Increment(ref _seed)));
private readonly SortedPool<Keccak, Transaction, Address> _transactions;
private readonly IChainHeadSpecProvider _specProvider;
private readonly ITxPoolConfig _txPoolConfig;
private readonly IReadOnlyStateProvider _stateProvider;
private readonly ITxValidator _validator;
private readonly IEthereumEcdsa _ecdsa;
protected readonly ILogger _logger;
/// <summary>
/// Transactions published locally (initiated by this node users) or reorganised.
/// </summary>
private readonly SortedPool<Keccak, Transaction, Address> _persistentBroadcastTransactions;
/// <summary>
/// Long term storage for pending transactions.
/// </summary>
private readonly ITxStorage _txStorage;
/// <summary>
/// Connected peers that can be notified about transactions.
/// </summary>
private readonly ConcurrentDictionary<PublicKey, ITxPoolPeer> _peers =
new();
/// <summary>
/// Timer for rebroadcasting pending own transactions.
/// </summary>
private readonly Timer _ownTimer;
/// <summary>
/// Indexes transactions
/// </summary>
private ulong _txIndex;
/// <summary>
/// This class stores all known pending transactions that can be used for block production
/// (by miners or validators) or simply informing other nodes about known pending transactions (broadcasting).
/// </summary>
/// <param name="txStorage">Tx storage used to reject known transactions.</param>
/// <param name="ecdsa">Used to recover sender addresses from transaction signatures.</param>
/// <param name="specProvider">Used for retrieving information on EIPs that may affect tx signature scheme.</param>
/// <param name="txPoolConfig"></param>
/// <param name="stateProvider"></param>
/// <param name="validator"></param>
/// <param name="logManager"></param>
/// <param name="comparer"></param>
public TxPool(ITxStorage txStorage,
IEthereumEcdsa ecdsa,
IChainHeadSpecProvider specProvider,
ITxPoolConfig txPoolConfig,
IReadOnlyStateProvider stateProvider,
ITxValidator validator,
ILogManager? logManager,
IComparer<Transaction>? comparer = null)
{
_ecdsa = ecdsa ?? throw new ArgumentNullException(nameof(ecdsa));
_logger = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
_txStorage = txStorage ?? throw new ArgumentNullException(nameof(txStorage));
_specProvider = specProvider ?? throw new ArgumentNullException(nameof(specProvider));
_txPoolConfig = txPoolConfig;
_stateProvider = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider));
_validator = validator ?? throw new ArgumentNullException(nameof(validator));
MemoryAllowance.MemPoolSize = txPoolConfig.Size;
ThisNodeInfo.AddInfo("Mem est tx :",
$"{(LruCache<Keccak, object>.CalculateMemorySize(32, MemoryAllowance.TxHashCacheSize) + LruCache<Keccak, Transaction>.CalculateMemorySize(4096, MemoryAllowance.MemPoolSize)) / 1000 / 1000}MB"
.PadLeft(8));
_transactions = new TxDistinctSortedPool(MemoryAllowance.MemPoolSize, logManager, comparer ?? DefaultComparer);
_persistentBroadcastTransactions = new TxDistinctSortedPool(MemoryAllowance.MemPoolSize, logManager, comparer ?? DefaultComparer);
_ownTimer = new Timer(500);
_ownTimer.Elapsed += OwnTimerOnElapsed;
_ownTimer.AutoReset = false;
_ownTimer.Start();
}
public uint FutureNonceRetention => _txPoolConfig.FutureNonceRetention;
public long? BlockGasLimit { get; set; } = null;
public Transaction[] GetPendingTransactions() => _transactions.GetSnapshot();
public int GetPendingTransactionsCount() => _transactions.Count;
public IDictionary<Address, Transaction[]> GetPendingTransactionsBySender() =>
_transactions.GetBucketSnapshot();
public Transaction[] GetOwnPendingTransactions() => _persistentBroadcastTransactions.GetSnapshot();
public void AddPeer(ITxPoolPeer peer)
{
PeerInfo peerInfo = new(peer);
if (_peers.TryAdd(peer.Id, peerInfo))
{
foreach (var transaction in _transactions.GetSnapshot())
{
Notify(peerInfo, transaction, false);
}
if (_logger.IsTrace) _logger.Trace($"Added a peer to TX pool: {peer}");
}
}
public void RemovePeer(PublicKey nodeId)
{
if (!_peers.TryRemove(nodeId, out _))
{
return;
}
if (_logger.IsTrace) _logger.Trace($"Removed a peer from TX pool: {nodeId}");
}
public AddTxResult AddTransaction(Transaction tx, TxHandlingOptions handlingOptions)
{
if (tx.Hash is null)
{
throw new ArgumentException($"{nameof(tx.Hash)} not set on {nameof(Transaction)}");
}
tx.PoolIndex = Interlocked.Increment(ref _txIndex);
NewDiscovered?.Invoke(this, new TxEventArgs(tx));
bool managedNonce = (handlingOptions & TxHandlingOptions.ManagedNonce) == TxHandlingOptions.ManagedNonce;
bool isPersistentBroadcast = (handlingOptions & TxHandlingOptions.PersistentBroadcast) ==
TxHandlingOptions.PersistentBroadcast;
bool isReorg = (handlingOptions & TxHandlingOptions.Reorganisation) == TxHandlingOptions.Reorganisation;
if (_logger.IsTrace)
_logger.Trace(
$"Adding transaction {tx.ToString(" ")} - managed nonce: {managedNonce} | persistent broadcast {isPersistentBroadcast}");
return FilterTransaction(tx, managedNonce) ?? AddCore(tx, isPersistentBroadcast, isReorg);
}
private AddTxResult AddCore(Transaction tx, bool isPersistentBroadcast, bool isReorg)
{
if (tx.Hash is null)
{
return AddTxResult.Invalid;
}
// !!! do not change it to |=
bool isKnown = !isReorg && _hashCache.Get(tx.Hash);
/*
* we need to make sure that the sender is resolved before adding to the distinct tx pool
* as the address is used in the distinct value calculation
*/
if (!isKnown)
{
lock (_locker)
{
isKnown |= !_transactions.TryInsert(tx.Hash, tx);
}
}
if (!isKnown)
{
isKnown |= !isReorg && (_txStorage.Get(tx.Hash) is not null);
}
if (isKnown)
{
// If transaction is a bit older and already known then it may be stored in the persistent storage.
Metrics.PendingTransactionsKnown++;
if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, already known.");
return AddTxResult.AlreadyKnown;
}
_hashCache.Set(tx.Hash);
HandleOwnTransaction(tx, isPersistentBroadcast);
NotifySelectedPeers(tx);
StoreTx(tx);
NewPending?.Invoke(this, new TxEventArgs(tx));
return AddTxResult.Added;
}
protected virtual AddTxResult? FilterTransaction(Transaction tx, in bool managedNonce)
{
if (tx.Hash is null)
{
return AddTxResult.Invalid;
}
Metrics.PendingTransactionsReceived++;
if (!_validator.IsWellFormed(tx, _specProvider.GetSpec()))
{
// It may happen that other nodes send us transactions that were signed for another chain or don't have enough gas.
Metrics.PendingTransactionsDiscarded++;
if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, invalid transaction.");
return AddTxResult.Invalid;
}
var gasLimit = Math.Min(BlockGasLimit ?? long.MaxValue, _txPoolConfig.GasLimit ?? long.MaxValue);
if (tx.GasLimit > gasLimit)
{
if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, gas limit exceeded.");
return AddTxResult.GasLimitExceeded;
}
/* We have encountered multiple transactions that do not resolve sender address properly.
* We need to investigate what these txs are and why the sender address is resolved to null.
* Then we need to decide whether we really want to broadcast them.
*/
if (tx.SenderAddress is null)
{
tx.SenderAddress = _ecdsa.RecoverAddress(tx);
if (tx.SenderAddress is null)
{
if (_logger.IsTrace) _logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, no sender.");
return AddTxResult.PotentiallyUseless;
}
}
// As we have limited number of transaction that we store in mem pool its fairly easy to fill it up with
// high-priority garbage transactions. We need to filter them as much as possible to use the tx pool space
// efficiently. One call to get account from state is not that costly and it only happens after previous checks.
// This was modeled by OpenEthereum behavior.
var account = _stateProvider.GetAccount(tx.SenderAddress);
var currentNonce = account?.Nonce ?? UInt256.Zero;
if (tx.Nonce < currentNonce)
{
if (_logger.IsTrace)
_logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, nonce already used.");
return AddTxResult.OldNonce;
}
if (tx.Nonce > currentNonce + FutureNonceRetention)
{
if (_logger.IsTrace)
_logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, nonce in far future.");
return AddTxResult.FutureNonce;
}
bool overflow = UInt256.MultiplyOverflow(tx.GasPrice, (UInt256) tx.GasLimit, out UInt256 cost);
overflow |= UInt256.AddOverflow(cost, tx.Value, out cost);
if (overflow)
{
if (_logger.IsTrace)
_logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, cost overflow.");
return AddTxResult.BalanceOverflow;
}
else if ((account?.Balance ?? UInt256.Zero) < cost)
{
if (_logger.IsTrace)
_logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, insufficient funds.");
return AddTxResult.InsufficientFunds;
}
if (managedNonce && CheckOwnTransactionAlreadyUsed(tx, currentNonce))
{
if (_logger.IsTrace)
_logger.Trace($"Skipped adding transaction {tx.ToString(" ")}, nonce already used.");
return AddTxResult.OwnNonceAlreadyUsed;
}
return null;
}
private void HandleOwnTransaction(Transaction tx, bool isOwn)
{
if (isOwn)
{
lock (_locker)
{
_persistentBroadcastTransactions.TryInsert(tx.Hash, tx);
}
_ownTimer.Enabled = true;
if (_logger.IsDebug) _logger.Debug($"Broadcasting own transaction {tx.Hash} to {_peers.Count} peers");
if (_logger.IsTrace) _logger.Trace($"Broadcasting transaction {tx.ToString(" ")}");
}
}
private bool CheckOwnTransactionAlreadyUsed(Transaction transaction, UInt256 currentNonce)
{
Address address = transaction.SenderAddress;
lock (_locker)
{
if (!_nonces.TryGetValue(address, out var addressNonces))
{
addressNonces = new AddressNonces(currentNonce);
_nonces.TryAdd(address, addressNonces);
}
if (!addressNonces.Nonces.TryGetValue(transaction.Nonce, out var nonce))
{
nonce = new Nonce(transaction.Nonce);
addressNonces.Nonces.TryAdd(transaction.Nonce, new Nonce(transaction.Nonce));
}
if (!(nonce.TransactionHash is null && nonce.TransactionHash != transaction.Hash))
{
// Nonce conflict
if (_logger.IsDebug)
_logger.Debug(
$"Nonce: {nonce.Value} was already used in transaction: '{nonce.TransactionHash}' and cannot be reused by transaction: '{transaction.Hash}'.");
return true;
}
nonce.SetTransactionHash(transaction.Hash!);
}
return false;
}
public void RemoveTransaction(Keccak hash, bool removeBelowThisTxNonce = false)
{
ICollection<Transaction>? bucket;
ICollection<Transaction>? persistentBucket = null;
Transaction transaction;
lock (_locker)
{
if (_transactions.TryRemove(hash, out transaction, out bucket))
{
Address address = transaction.SenderAddress;
if (_nonces.TryGetValue(address, out AddressNonces addressNonces))
{
addressNonces.Nonces.TryRemove(transaction.Nonce, out _);
if (addressNonces.Nonces.IsEmpty)
{
_nonces.Remove(address, out _);
}
}
RemovedPending?.Invoke(this, new TxEventArgs(transaction));
}
if (_persistentBroadcastTransactions.Count != 0)
{
bool ownIncluded = _persistentBroadcastTransactions.TryRemove(hash, out Transaction _, out persistentBucket);
if (ownIncluded)
{
if (_logger.IsInfo)
_logger.Trace($"Transaction {hash} created on this node was included in the block");
}
}
}
_txStorage.Delete(hash);
if (_logger.IsTrace) _logger.Trace($"Deleted a transaction: {hash}");
if (bucket != null && removeBelowThisTxNonce)
{
lock (_locker)
{
Transaction? txWithSmallestNonce = bucket.FirstOrDefault();
while (txWithSmallestNonce != null && txWithSmallestNonce.Nonce <= transaction.Nonce)
{
RemoveTransaction(txWithSmallestNonce.Hash!);
txWithSmallestNonce = bucket.FirstOrDefault();
}
if (persistentBucket != null)
{
txWithSmallestNonce = persistentBucket.FirstOrDefault();
while (txWithSmallestNonce != null && txWithSmallestNonce.Nonce <= transaction.Nonce)
{
persistentBucket.Remove(txWithSmallestNonce);
txWithSmallestNonce = persistentBucket.FirstOrDefault();
}
}
}
}
}
public bool TryGetPendingTransaction(Keccak hash, out Transaction transaction)
{
lock (_locker)
{
if (!_transactions.TryGetValue(hash, out transaction))
{
// commented out as it puts too much pressure on the database
// and it not really required in any scenario
// * tx recovery usually will fetch from pending
// * get tx via RPC usually will fetch from block or from pending
// * internal tx pool scenarios are handled directly elsewhere
// transaction = _txStorage.Get(hash);
}
}
return transaction != null;
}
// TODO: Ensure that nonce is always valid in case of sending own transactions from different nodes.
public UInt256 ReserveOwnTransactionNonce(Address address)
{
lock (_locker)
{
if (!_nonces.TryGetValue(address, out var addressNonces))
{
var currentNonce = _stateProvider.GetNonce(address);
addressNonces = new AddressNonces(currentNonce);
_nonces.TryAdd(address, addressNonces);
return currentNonce;
}
Nonce incrementedNonce = addressNonces.ReserveNonce();
return incrementedNonce.Value;
}
}
public void Dispose()
{
_ownTimer.Dispose();
}
public event EventHandler<TxEventArgs>? NewDiscovered;
public event EventHandler<TxEventArgs>? NewPending;
public event EventHandler<TxEventArgs>? RemovedPending;
private void Notify(ITxPoolPeer peer, Transaction tx, bool isPriority)
{
try
{
if (peer.SendNewTransaction(tx, isPriority))
{
Metrics.PendingTransactionsSent++;
if (_logger.IsTrace) _logger.Trace($"Notified {peer} about a transaction: {tx.Hash}");
}
}
catch (Exception e)
{
if (_logger.IsError) _logger.Error($"Failed to notify {peer} about a transaction: {tx.Hash}", e);
}
}
private void NotifyAllPeers(Transaction tx)
{
Task.Run(() =>
{
foreach ((_, ITxPoolPeer peer) in _peers)
{
Notify(peer, tx, true);
}
});
}
private void NotifySelectedPeers(Transaction tx)
{
Task.Run(() =>
{
foreach ((_, ITxPoolPeer peer) in _peers)
{
if (tx.DeliveredBy == null)
{
Notify(peer, tx, true);
continue;
}
if (tx.DeliveredBy.Equals(peer.Id))
{
continue;
}
if (_txPoolConfig.PeerNotificationThreshold < Random.Value.Next(1, 100))
{
continue;
}
Notify(peer, tx, 3 < Random.Value.Next(1, 10));
}
});
}
private void StoreTx(Transaction tx)
{
_txStorage.Add(tx);
if (_logger.IsTrace) _logger.Trace($"Added a transaction: {tx.Hash}");
}
private void OwnTimerOnElapsed(object sender, ElapsedEventArgs e)
{
if (_persistentBroadcastTransactions.Count > 0)
{
foreach (Transaction tx in _persistentBroadcastTransactions.GetSnapshot())
{
NotifyAllPeers(tx);
}
// we only reenable the timer if there are any transaction pending
// otherwise adding own transaction will reenable the timer anyway
_ownTimer.Enabled = true;
}
}
private class AddressNonces
{
private Nonce _currentNonce;
public ConcurrentDictionary<UInt256, Nonce> Nonces { get; } = new();
public AddressNonces(UInt256 startNonce)
{
_currentNonce = new Nonce(startNonce);
Nonces.TryAdd(_currentNonce.Value, _currentNonce);
}
public Nonce ReserveNonce()
{
var nonce = _currentNonce.Increment();
Interlocked.Exchange(ref _currentNonce, nonce);
Nonces.TryAdd(nonce.Value, nonce);
return nonce;
}
}
private class Nonce
{
public UInt256 Value { get; }
public Keccak? TransactionHash { get; private set; }
public Nonce(UInt256 value)
{
Value = value;
}
public void SetTransactionHash(Keccak transactionHash)
{
TransactionHash = transactionHash;
}
public Nonce Increment() => new(Value + 1);
}
private class PeerInfo : ITxPoolPeer
{
private ITxPoolPeer Peer { get; }
private LruKeyCache<Keccak> NotifiedTransactions { get; } = new(MemoryAllowance.MemPoolSize, "notifiedTransactions");
public PeerInfo(ITxPoolPeer peer)
{
Peer = peer;
}
public PublicKey Id => Peer.Id;
public bool SendNewTransaction(Transaction tx, bool isPriority)
{
if (!NotifiedTransactions.Get(tx.Hash))
{
NotifiedTransactions.Set(tx.Hash);
return Peer.SendNewTransaction(tx, isPriority);
}
return false;
}
public override string ToString() => Peer.Enode;
}
}
}
| 1 | 25,154 | can we do that in TxValidator? | NethermindEth-nethermind | .cs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.