text
stringlengths
1
1.05M
; A193248: Truncated dodecahedron, and truncated icosahedron with faces of centered polygons. ; 1,93,455,1267,2709,4961,8203,12615,18377,25669,34671,45563,58525,73737,91379,111631,134673,160685,189847,222339,258341,298033,341595,389207,441049,497301,558143,623755,694317,770009,851011,937503,1029665,1127677,1231719,1341971,1458613,1581825,1711787,1848679,1992681,2143973,2302735,2469147,2643389,2825641,3016083,3214895,3422257,3638349,3863351,4097443,4340805,4593617,4856059,5128311,5410553,5702965,6005727,6319019,6643021,6977913,7323875,7681087,8049729,8429981,8822023,9226035,9642197,10070689,10511691,10965383,11431945,11911557,12404399,12910651,13430493,13964105,14511667,15073359,15649361,16239853,16845015,17465027,18100069,18750321,19415963,20097175,20794137,21507029,22236031,22981323,23743085,24521497,25316739,26128991,26958433,27805245,28669607,29551699,30451701,31369793,32306155,33260967,34234409,35226661,36237903,37268315,38318077,39387369,40476371,41585263,42714225,43863437,45033079,46223331,47434373,48666385,49919547,51194039,52490041,53807733,55147295,56508907,57892749,59299001,60727843,62179455,63654017,65151709,66672711,68217203,69785365,71377377,72993419,74633671,76298313,77987525,79701487,81440379,83204381,84993673,86808435,88648847,90515089,92407341,94325783,96270595,98241957,100240049,102265051,104317143,106396505,108503317,110637759,112800011,114990253,117208665,119455427,121730719,124034721,126367613,128729575,131120787,133541429,135991681,138471723,140981735,143521897,146092389,148693391,151325083,153987645,156681257,159406099,162162351,164950193,167769805,170621367,173505059,176421061,179369553,182350715,185364727,188411769,191492021,194605663,197752875,200933837,204148729,207397731,210681023,213998785,217351197,220738439,224160691,227618133,231110945,234639307,238203399,241803401,245439493,249111855,252820667,256566109,260348361,264167603,268024015,271917777,275849069,279818071,283824963,287869925,291953137,296074779,300235031,304434073,308672085,312949247,317265739,321621741,326017433,330452995,334928607,339444449,344000701,348597543,353235155,357913717,362633409,367394411,372196903,377041065,381927077,386855119,391825371,396838013,401893225,406991187,412132079,417316081,422543373,427814135,433128547,438486789,443889041,449335483,454826295,460361657,465941749 mov $4,$0 pow $0,3 mov $1,30 mul $1,$0 add $1,1 mov $2,$4 mul $2,17 add $1,$2 mov $3,$4 mul $3,$4 mov $2,$3 mul $2,45 add $1,$2
; A193732: Connell-like sequence. ; Submitted by Jamie Morken(s2) ; 1,3,4,6,8,9,11,13,15,17,18,20,22,24,26,28,30,31,33,35,37,39,41,43,45,47,49,51,52,54,56,58,60,62,64,66,68,70,72,74,76,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,147,149,151,153,155,157,159,161,163,165,167,169,171,173,175,177,179,181,183,185,187,189,191 mov $5,$0 add $5,1 mov $7,$0 lpb $5 mov $0,$7 sub $5,1 sub $0,$5 mov $1,1 mov $2,1 lpb $0 mov $3,$2 lpb $3 add $2,1 mov $4,$1 gcd $4,$2 cmp $4,1 cmp $4,0 sub $3,$4 lpe sub $0,$2 sub $0,1 add $2,1 mul $1,$2 lpe lpb $0 mov $0,1 lpe add $0,1 add $6,$0 lpe mov $0,$6
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt /* This example program shows how to use dlib's implementation of the paper: One Millisecond Face Alignment with an Ensemble of Regression Trees by Vahid Kazemi and Josephine Sullivan, CVPR 2014 In particular, we will train a face landmarking model based on a small dataset and then evaluate it. If you want to visualize the output of the trained model on some images then you can run the face_landmark_detection_ex.cpp example program with sp.dat as the input model. It should also be noted that this kind of model, while often used for face landmarking, is quite general and can be used for a variety of shape prediction tasks. But here we demonstrate it only on a simple face landmarking task. */ #include <dlib/image_processing.h> #include <dlib/data_io.h> #include <dlib/global_optimization.h> #include <dlib/logger.h> #include <dlib/cmd_line_parser.h> #include <dlib/cmd_line_parser/get_option.h> #include <iostream> using namespace dlib; using namespace std; // ---------------------------------------------------------------------------------------- std::vector<std::vector<double> > get_interocular_distances( const std::vector<std::vector<full_object_detection> >& objects ); /*! ensures - returns an object D such that: - D[i][j] == the distance, in pixels, between the eyes for the face represented by objects[i][j]. !*/ // ---------------------------------------------------------------------------------------- void writeConfigToFile(std::string configFile, shape_predictor_trainer trainer) { ofstream file; file.open(configFile); file << "Landmarks trainer configuration used\n"; file << "---------------------------------------------------------------------------\n"; file << "Cascade depth: " << trainer.get_cascade_depth() << "\n"; file << "Feature pool region padding: " << trainer.get_feature_pool_region_padding() << "\n"; file << "Feature pool size: " << trainer.get_feature_pool_size() << "\n"; file << "Lambda: " << trainer.get_lambda() << "\n"; file << "Nu: " << trainer.get_nu() << "\n"; file << "Num test splits: " << trainer.get_num_test_splits() << "\n"; file << "Num threads: " << trainer.get_num_threads() << "\n"; file << "Num trees per cascade level: " << trainer.get_num_trees_per_cascade_level() << "\n"; file << "Oversampling amount: " << trainer.get_oversampling_amount() << "\n"; file << "Oversampling translation jitter: " << trainer.get_oversampling_translation_jitter() << "\n"; file << "Padding mode: " << trainer.get_padding_mode() << "\n"; file << "Random seed: " << trainer.get_random_seed() << "\n"; file << "Tree depth: " << trainer.get_tree_depth() << "\n"; file.close(); } /** This method obtain the best hyper parameters by using the method */ void autotuneHyperParams(const std::string &datasetPath, const unsigned int threads) { // Configure logger ofstream fileStream; fileStream.open("autotune.log"); logger log("autotune"); log.set_level(dlib::LINFO); log.set_output_stream(fileStream); dlib::array<array2d<unsigned char> > images_train, images_test; std::vector<std::vector<full_object_detection> > faces_train, faces_test; // Now we load the data. These XML files list the images in each // dataset and also contain the positions of the face boxes and // landmarks (called parts in the XML file). Obviously you can use any // kind of input format you like so long as you store the data into // images_train and faces_train. But for convenience dlib comes with // tools for creating and loading XML image dataset files. Here you see // how to load the data. To create the XML files you can use the imglab // tool which can be found in the tools/imglab folder. It is a simple // graphical tool for labeling objects in images. To see how to use it // read the tools/imglab/README.txt file. cout << "Loading training images" << endl; log << LINFO << "Loading training images"; load_image_dataset(images_train, faces_train, datasetPath + "/training_with_face_landmarks.xml"); cout << "Loading testing images" << endl; log << LINFO << "Loading testing images"; load_image_dataset(images_test, faces_test, datasetPath + "/testing_with_face_landmarks.xml"); log << LINFO << "Creating train score function"; auto trainer_score = [&](const unsigned int oversampling, const double nu, const unsigned int treeDepth, const unsigned int cascade, const unsigned int testSplits, const unsigned int featurePoolSize) { shape_predictor_trainer trainer; // This algorithm has a bunch of parameters you can mess with. The // documentation for the shape_predictor_trainer explains all of them. // You should also read Kazemi's paper which explains all the parameters // in great detail. However, here I'm just setting three of them // differently than their default values. I'm doing this because we // have a very small dataset. In particular, setting the oversampling // to a high amount (300) effectively boosts the training set size, so // that helps this example. trainer.set_oversampling_amount(oversampling); // I'm also reducing the capacity of the model by explicitly increasing // the regularization (making nu smaller) and by using trees with // smaller depths. trainer.set_nu(nu); trainer.set_tree_depth(treeDepth); trainer.set_cascade_depth(cascade); trainer.set_num_test_splits(testSplits); trainer.set_feature_pool_size(featurePoolSize); // some parts of training process can be parallelized. // Trainer will use this count of threads when possible trainer.set_num_threads(threads); // Tell the trainer to print status messages to the console so we can // see how long the training will take. trainer.be_verbose(); // Now finally generate the shape model shape_predictor sp = trainer.train(images_train, faces_train); return test_shape_predictor(sp, images_test, faces_test, get_interocular_distances(faces_test)); }; // Call optimization method cout << "Calling optimization process ..." << endl; log << LINFO << "Calling optimization process ..."; auto result = find_min_global(trainer_score, { 5, 0.01, 2, 6, 20, 200 }, // lower bound constraints on gamma, c1, and c2, respectively { 30, 0.99, 8, 18, 300, 800}, // upper bound constraints on gamma, c1, and c2, respectively { true, false, true, true, true, true }, max_function_calls(10)); shape_predictor_trainer best; int oversampling = result.x(0); double nu = result.x(1); int tree_depth = result.x(2); int cascasde_depth = result.x(3); int test_splits = result.x(4); int feature_pool_size = result.x(5); // Write results to console cout << "Results" << endl; cout << "Oversampling " << oversampling << endl; cout << "Nu " << nu << endl; cout << "Tree depth " << tree_depth << endl; cout << "Cascade depth " << cascasde_depth << endl; cout << "Test splits " << test_splits << endl; cout << "Feature pool size " << feature_pool_size << endl; log << LINFO << "Results"; log << LINFO << "Oversampling " << oversampling; log << LINFO << "Nu " << nu; log << LINFO << "Tree depth " << tree_depth; log << LINFO << "Cascade depth " << cascasde_depth; log << LINFO << "Test splits " << test_splits; log << LINFO << "Feature pool size " << feature_pool_size; best.set_oversampling_amount(oversampling); best.set_nu(nu); best.set_tree_depth(tree_depth); best.set_cascade_depth(cascasde_depth); best.set_num_test_splits(test_splits); best.set_feature_pool_size(feature_pool_size); writeConfigToFile("best_config_obtained.cfg", best); } int main(int argc, char** argv) { try { command_line_parser parser; parser.add_option("dataset", "Directory containing the dataset.", 1); parser.add_option("td", "Depth used in trees generated for training. More depth more accuracy in preditions (also model size increase).", 1); parser.add_option("threads", "Number of threads used in training.", 1); parser.add_option("oversampling", "Number of oversampling amount needed", 1); parser.add_option("cascade", "Cascade Depth is the number of cascades used to train the model. This parameter affect either the size and accuracy of a model.", 1); parser.add_option("nu", "Nu is the regularization parameter. It determines the ability of the model to generalize and learn patterns instead of fixed-data.", 1); parser.add_option("test-splits", "Is the number of split features sampled at each node. This parameter is responsible for selecting the best features at each cascade during the training process. The parameter affects the training speed and the model accuracy.", 1); parser.add_option("features-pool-size", "Feature Pool Size denotes the number of pixels used to generate the features for the random trees at each cascade. Larger amount of pixels will lead the algorithm to be more robust and accurate but to execute slower.", 1); parser.add_option("save-to", "Save model to fillename expecified.", 1); parser.add_option("autotune", "This option enables the autotune algorithm to find best hyperparameters of this machine learning algorithm."); parser.add_option("h", "Display this help message."); // now I will parse the command line parser.parse(argc, argv); // check if the -h option was given on the command line if (parser.option("h") || argc < 2) { // display all the command line options cout << "Usage: " << argv[0] << " --dataset path_to_dataset --td (Trees depht: default 2) --threads (Number of threads for training: default 2)\n"; // This function prints out a nicely formatted list of // all the options the parser has parser.print_options(); return 0; } std::string dataset_directory; if (parser.option("dataset")) { dataset_directory = parser.option("dataset").argument(); } else { cout << "Error in arguments: You must supply dataset location path." << endl; return -1; } std::string modelFilename; if (parser.option("save-to")) { modelFilename = parser.option("save-to").argument(); } else { modelFilename = "sp.dat"; } // We obtain the params or its default values int treeDepthParam = get_option(parser, "td", 2); int threadsParam = get_option(parser, "threads", 2); double nu = get_option(parser, "nu", 0.1); int oversampling = get_option(parser, "oversampling", 20); int cascade = get_option(parser, "cascade", 10); int testSplitsParam = get_option(parser, "test-splits", 20); int featuresPoolSizeParam = get_option(parser, "features-pool-size", 400); if (treeDepthParam < 2) treeDepthParam = 2; if (threadsParam < 2) threadsParam = 2; // Check if autotune is enabled if (parser.option("autotune")) { // Call autotune process autotuneHyperParams(dataset_directory, threadsParam); // After autotuning exit return 0; } // The faces directory contains a training dataset and a separate // testing dataset. The training data consists of 4 images, each // annotated with rectangles that bound each human face along with 68 // face landmarks on each face. The idea is to use this training data // to learn to identify the position of landmarks on human faces in new // images. // // Once you have trained a shape_predictor it is always important to // test it on data it wasn't trained on. Therefore, we will also load // a separate testing set of 5 images. Once we have a shape_predictor // created from the training data we will see how well it works by // running it on the testing images. // // So here we create the variables that will hold our dataset. // images_train will hold the 4 training images and faces_train holds // the locations and poses of each face in the training images. So for // example, the image images_train[0] has the faces given by the // full_object_detections in faces_train[0]. dlib::array<array2d<unsigned char> > images_train, images_test; std::vector<std::vector<full_object_detection> > faces_train, faces_test; // Now we load the data. These XML files list the images in each // dataset and also contain the positions of the face boxes and // landmarks (called parts in the XML file). Obviously you can use any // kind of input format you like so long as you store the data into // images_train and faces_train. But for convenience dlib comes with // tools for creating and loading XML image dataset files. Here you see // how to load the data. To create the XML files you can use the imglab // tool which can be found in the tools/imglab folder. It is a simple // graphical tool for labeling objects in images. To see how to use it // read the tools/imglab/README.txt file. cout << "Loading training images" << endl; load_image_dataset(images_train, faces_train, dataset_directory + "/training_with_face_landmarks.xml"); cout << "Loading testing images" << endl; load_image_dataset(images_test, faces_test, dataset_directory + "/testing_with_face_landmarks.xml"); // Now make the object responsible for training the model. shape_predictor_trainer trainer; // This algorithm has a bunch of parameters you can mess with. The // documentation for the shape_predictor_trainer explains all of them. // You should also read Kazemi's paper which explains all the parameters // in great detail. However, here I'm just setting three of them // differently than their default values. I'm doing this because we // have a very small dataset. In particular, setting the oversampling // to a high amount (300) effectively boosts the training set size, so // that helps this example. trainer.set_oversampling_amount(oversampling); // I'm also reducing the capacity of the model by explicitly increasing // the regularization (making nu smaller) and by using trees with // smaller depths. trainer.set_nu(nu); trainer.set_tree_depth(treeDepthParam); trainer.set_cascade_depth(cascade); trainer.set_num_test_splits(testSplitsParam); trainer.set_feature_pool_size(featuresPoolSizeParam); // some parts of training process can be parallelized. // Trainer will use this count of threads when possible trainer.set_num_threads(threadsParam); // Tell the trainer to print status messages to the console so we can // see how long the training will take. trainer.be_verbose(); // Now finally generate the shape model shape_predictor sp = trainer.train(images_train, faces_train); // Now that we have a model we can test it. This function measures the // average distance between a face landmark output by the // shape_predictor and where it should be according to the truth data. // Note that there is an optional 4th argument that lets us rescale the // distances. Here we are causing the output to scale each face's // distances by the interocular distance, as is customary when // evaluating face landmarking systems. cout << "mean training error: " << test_shape_predictor(sp, images_train, faces_train, get_interocular_distances(faces_train)) << endl; // The real test is to see how well it does on data it wasn't trained // on. We trained it on a very small dataset so the accuracy is not // extremely high, but it's still doing quite good. Moreover, if you // train it on one of the large face landmarking datasets you will // obtain state-of-the-art results, as shown in the Kazemi paper. cout << "mean testing error: " << test_shape_predictor(sp, images_test, faces_test, get_interocular_distances(faces_test)) << endl; // Finally, we save the model to disk so we can use it later. serialize(modelFilename) << sp; // Write also configuration writeConfigToFile(modelFilename + ".cfg", trainer); } catch (exception& e) { cout << "\nexception thrown!" << endl; cout << e.what() << endl; } } // ---------------------------------------------------------------------------------------- double interocular_distance( const full_object_detection& det ) { dlib::vector<double, 2> l, r; double cnt = 0; // Find the center of the left eye by averaging the points around // the eye. for (unsigned long i = 36; i <= 41; ++i) { l += det.part(i); ++cnt; } l /= cnt; // Find the center of the right eye by averaging the points around // the eye. cnt = 0; for (unsigned long i = 42; i <= 47; ++i) { r += det.part(i); ++cnt; } r /= cnt; // Now return the distance between the centers of the eyes return length(l - r); } std::vector<std::vector<double> > get_interocular_distances( const std::vector<std::vector<full_object_detection> >& objects ) { std::vector<std::vector<double> > temp(objects.size()); for (unsigned long i = 0; i < objects.size(); ++i) { for (unsigned long j = 0; j < objects[i].size(); ++j) { temp[i].push_back(interocular_distance(objects[i][j])); } } return temp; } // ----------------------------------------------------------------------------------------
//===- PredicateTree.cpp - Predicate tree merging -------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "PredicateTree.h" #include "mlir/Dialect/PDL/IR/PDL.h" #include "mlir/Dialect/PDL/IR/PDLTypes.h" #include "mlir/Dialect/PDLInterp/IR/PDLInterp.h" #include "mlir/IR/Module.h" #include "mlir/Interfaces/InferTypeOpInterface.h" using namespace mlir; using namespace mlir::pdl_to_pdl_interp; //===----------------------------------------------------------------------===// // Predicate List Building //===----------------------------------------------------------------------===// /// Compares the depths of two positions. static bool comparePosDepth(Position *lhs, Position *rhs) { return lhs->getIndex().size() < rhs->getIndex().size(); } /// Collect the tree predicates anchored at the given value. static void getTreePredicates(std::vector<PositionalPredicate> &predList, Value val, PredicateBuilder &builder, DenseMap<Value, Position *> &inputs, Position *pos) { // Make sure this input value is accessible to the rewrite. auto it = inputs.try_emplace(val, pos); // If this is an input value that has been visited in the tree, add a // constraint to ensure that both instances refer to the same value. if (!it.second && isa<pdl::AttributeOp, pdl::InputOp, pdl::TypeOp>(val.getDefiningOp())) { auto minMaxPositions = std::minmax(pos, it.first->second, comparePosDepth); predList.emplace_back(minMaxPositions.second, builder.getEqualTo(minMaxPositions.first)); return; } // Check for a per-position predicate to apply. switch (pos->getKind()) { case Predicates::AttributePos: { assert(val.getType().isa<pdl::AttributeType>() && "expected attribute type"); pdl::AttributeOp attr = cast<pdl::AttributeOp>(val.getDefiningOp()); predList.emplace_back(pos, builder.getIsNotNull()); // If the attribute has a type, add a type constraint. if (Value type = attr.type()) { getTreePredicates(predList, type, builder, inputs, builder.getType(pos)); // Check for a constant value of the attribute. } else if (Optional<Attribute> value = attr.value()) { predList.emplace_back(pos, builder.getAttributeConstraint(*value)); } break; } case Predicates::OperandPos: { assert(val.getType().isa<pdl::ValueType>() && "expected value type"); // Prevent traversal into a null value. predList.emplace_back(pos, builder.getIsNotNull()); // If this is a typed input, add a type constraint. if (auto in = val.getDefiningOp<pdl::InputOp>()) { if (Value type = in.type()) { getTreePredicates(predList, type, builder, inputs, builder.getType(pos)); } // Otherwise, recurse into the parent node. } else if (auto parentOp = val.getDefiningOp<pdl::OperationOp>()) { getTreePredicates(predList, parentOp.op(), builder, inputs, builder.getParent(cast<OperandPosition>(pos))); } break; } case Predicates::OperationPos: { assert(val.getType().isa<pdl::OperationType>() && "expected operation"); pdl::OperationOp op = cast<pdl::OperationOp>(val.getDefiningOp()); OperationPosition *opPos = cast<OperationPosition>(pos); // Ensure getDefiningOp returns a non-null operation. if (!opPos->isRoot()) predList.emplace_back(pos, builder.getIsNotNull()); // Check that this is the correct root operation. if (Optional<StringRef> opName = op.name()) predList.emplace_back(pos, builder.getOperationName(*opName)); // Check that the operation has the proper number of operands and results. OperandRange operands = op.operands(); ResultRange results = op.results(); predList.emplace_back(pos, builder.getOperandCount(operands.size())); predList.emplace_back(pos, builder.getResultCount(results.size())); // Recurse into any attributes, operands, or results. for (auto it : llvm::zip(op.attributeNames(), op.attributes())) { getTreePredicates( predList, std::get<1>(it), builder, inputs, builder.getAttribute(opPos, std::get<0>(it).cast<StringAttr>().getValue())); } for (auto operandIt : llvm::enumerate(operands)) getTreePredicates(predList, operandIt.value(), builder, inputs, builder.getOperand(opPos, operandIt.index())); // Only recurse into results that are not referenced in the source tree. for (auto resultIt : llvm::enumerate(results)) { getTreePredicates(predList, resultIt.value(), builder, inputs, builder.getResult(opPos, resultIt.index())); } break; } case Predicates::ResultPos: { assert(val.getType().isa<pdl::ValueType>() && "expected value type"); pdl::OperationOp parentOp = cast<pdl::OperationOp>(val.getDefiningOp()); // Prevent traversing a null value. predList.emplace_back(pos, builder.getIsNotNull()); // Traverse the type constraint. unsigned resultNo = cast<ResultPosition>(pos)->getResultNumber(); getTreePredicates(predList, parentOp.types()[resultNo], builder, inputs, builder.getType(pos)); break; } case Predicates::TypePos: { assert(val.getType().isa<pdl::TypeType>() && "expected value type"); pdl::TypeOp typeOp = cast<pdl::TypeOp>(val.getDefiningOp()); // Check for a constraint on a constant type. if (Optional<Type> type = typeOp.type()) predList.emplace_back(pos, builder.getTypeConstraint(*type)); break; } default: llvm_unreachable("unknown position kind"); } } /// Collect all of the predicates related to constraints within the given /// pattern operation. static void collectConstraintPredicates( pdl::PatternOp pattern, std::vector<PositionalPredicate> &predList, PredicateBuilder &builder, DenseMap<Value, Position *> &inputs) { for (auto op : pattern.body().getOps<pdl::ApplyConstraintOp>()) { OperandRange arguments = op.args(); ArrayAttr parameters = op.constParamsAttr(); std::vector<Position *> allPositions; allPositions.reserve(arguments.size()); for (Value arg : arguments) allPositions.push_back(inputs.lookup(arg)); // Push the constraint to the furthest position. Position *pos = *std::max_element(allPositions.begin(), allPositions.end(), comparePosDepth); PredicateBuilder::Predicate pred = builder.getConstraint(op.name(), std::move(allPositions), parameters); predList.emplace_back(pos, pred); } } /// Given a pattern operation, build the set of matcher predicates necessary to /// match this pattern. static void buildPredicateList(pdl::PatternOp pattern, PredicateBuilder &builder, std::vector<PositionalPredicate> &predList, DenseMap<Value, Position *> &valueToPosition) { getTreePredicates(predList, pattern.getRewriter().root(), builder, valueToPosition, builder.getRoot()); collectConstraintPredicates(pattern, predList, builder, valueToPosition); } //===----------------------------------------------------------------------===// // Pattern Predicate Tree Merging //===----------------------------------------------------------------------===// namespace { /// This class represents a specific predicate applied to a position, and /// provides hashing and ordering operators. This class allows for computing a /// frequence sum and ordering predicates based on a cost model. struct OrderedPredicate { OrderedPredicate(const std::pair<Position *, Qualifier *> &ip) : position(ip.first), question(ip.second) {} OrderedPredicate(const PositionalPredicate &ip) : position(ip.position), question(ip.question) {} /// The position this predicate is applied to. Position *position; /// The question that is applied by this predicate onto the position. Qualifier *question; /// The first and second order benefit sums. /// The primary sum is the number of occurrences of this predicate among all /// of the patterns. unsigned primary = 0; /// The secondary sum is a squared summation of the primary sum of all of the /// predicates within each pattern that contains this predicate. This allows /// for favoring predicates that are more commonly shared within a pattern, as /// opposed to those shared across patterns. unsigned secondary = 0; /// A map between a pattern operation and the answer to the predicate question /// within that pattern. DenseMap<Operation *, Qualifier *> patternToAnswer; /// Returns true if this predicate is ordered before `other`, based on the /// cost model. bool operator<(const OrderedPredicate &other) const { // Sort by: // * first and secondary order sums // * lower depth // * position dependency // * predicate dependency. auto *otherPos = other.position; return std::make_tuple(other.primary, other.secondary, otherPos->getIndex().size(), otherPos->getKind(), other.question->getKind()) > std::make_tuple(primary, secondary, position->getIndex().size(), position->getKind(), question->getKind()); } }; /// A DenseMapInfo for OrderedPredicate based solely on the position and /// question. struct OrderedPredicateDenseInfo { using Base = DenseMapInfo<std::pair<Position *, Qualifier *>>; static OrderedPredicate getEmptyKey() { return Base::getEmptyKey(); } static OrderedPredicate getTombstoneKey() { return Base::getTombstoneKey(); } static bool isEqual(const OrderedPredicate &lhs, const OrderedPredicate &rhs) { return lhs.position == rhs.position && lhs.question == rhs.question; } static unsigned getHashValue(const OrderedPredicate &p) { return llvm::hash_combine(p.position, p.question); } }; /// This class wraps a set of ordered predicates that are used within a specific /// pattern operation. struct OrderedPredicateList { OrderedPredicateList(pdl::PatternOp pattern) : pattern(pattern) {} pdl::PatternOp pattern; DenseSet<OrderedPredicate *> predicates; }; } // end anonymous namespace /// Returns true if the given matcher refers to the same predicate as the given /// ordered predicate. This means that the position and questions of the two /// match. static bool isSamePredicate(MatcherNode *node, OrderedPredicate *predicate) { return node->getPosition() == predicate->position && node->getQuestion() == predicate->question; } /// Get or insert a child matcher for the given parent switch node, given a /// predicate and parent pattern. std::unique_ptr<MatcherNode> &getOrCreateChild(SwitchNode *node, OrderedPredicate *predicate, pdl::PatternOp pattern) { assert(isSamePredicate(node, predicate) && "expected matcher to equal the given predicate"); auto it = predicate->patternToAnswer.find(pattern); assert(it != predicate->patternToAnswer.end() && "expected pattern to exist in predicate"); return node->getChildren().insert({it->second, nullptr}).first->second; } /// Build the matcher CFG by "pushing" patterns through by sorted predicate /// order. A pattern will traverse as far as possible using common predicates /// and then either diverge from the CFG or reach the end of a branch and start /// creating new nodes. static void propagatePattern(std::unique_ptr<MatcherNode> &node, OrderedPredicateList &list, std::vector<OrderedPredicate *>::iterator current, std::vector<OrderedPredicate *>::iterator end) { if (current == end) { // We've hit the end of a pattern, so create a successful result node. node = std::make_unique<SuccessNode>(list.pattern, std::move(node)); // If the pattern doesn't contain this predicate, ignore it. } else if (list.predicates.find(*current) == list.predicates.end()) { propagatePattern(node, list, std::next(current), end); // If the current matcher node is invalid, create a new one for this // position and continue propagation. } else if (!node) { // Create a new node at this position and continue node = std::make_unique<SwitchNode>((*current)->position, (*current)->question); propagatePattern( getOrCreateChild(cast<SwitchNode>(&*node), *current, list.pattern), list, std::next(current), end); // If the matcher has already been created, and it is for this predicate we // continue propagation to the child. } else if (isSamePredicate(node.get(), *current)) { propagatePattern( getOrCreateChild(cast<SwitchNode>(&*node), *current, list.pattern), list, std::next(current), end); // If the matcher doesn't match the current predicate, insert a branch as // the common set of matchers has diverged. } else { propagatePattern(node->getFailureNode(), list, current, end); } } /// Fold any switch nodes nested under `node` to boolean nodes when possible. /// `node` is updated in-place if it is a switch. static void foldSwitchToBool(std::unique_ptr<MatcherNode> &node) { if (!node) return; if (SwitchNode *switchNode = dyn_cast<SwitchNode>(&*node)) { SwitchNode::ChildMapT &children = switchNode->getChildren(); for (auto &it : children) foldSwitchToBool(it.second); // If the node only contains one child, collapse it into a boolean predicate // node. if (children.size() == 1) { auto childIt = children.begin(); node = std::make_unique<BoolNode>( node->getPosition(), node->getQuestion(), childIt->first, std::move(childIt->second), std::move(node->getFailureNode())); } } else if (BoolNode *boolNode = dyn_cast<BoolNode>(&*node)) { foldSwitchToBool(boolNode->getSuccessNode()); } foldSwitchToBool(node->getFailureNode()); } /// Insert an exit node at the end of the failure path of the `root`. static void insertExitNode(std::unique_ptr<MatcherNode> *root) { while (*root) root = &(*root)->getFailureNode(); *root = std::make_unique<ExitNode>(); } /// Given a module containing PDL pattern operations, generate a matcher tree /// using the patterns within the given module and return the root matcher node. std::unique_ptr<MatcherNode> MatcherNode::generateMatcherTree(ModuleOp module, PredicateBuilder &builder, DenseMap<Value, Position *> &valueToPosition) { // Collect the set of predicates contained within the pattern operations of // the module. SmallVector<std::pair<pdl::PatternOp, std::vector<PositionalPredicate>>, 16> patternsAndPredicates; for (pdl::PatternOp pattern : module.getOps<pdl::PatternOp>()) { std::vector<PositionalPredicate> predicateList; buildPredicateList(pattern, builder, predicateList, valueToPosition); patternsAndPredicates.emplace_back(pattern, std::move(predicateList)); } // Associate a pattern result with each unique predicate. DenseSet<OrderedPredicate, OrderedPredicateDenseInfo> uniqued; for (auto &patternAndPredList : patternsAndPredicates) { for (auto &predicate : patternAndPredList.second) { auto it = uniqued.insert(predicate); it.first->patternToAnswer.try_emplace(patternAndPredList.first, predicate.answer); } } // Associate each pattern to a set of its ordered predicates for later lookup. std::vector<OrderedPredicateList> lists; lists.reserve(patternsAndPredicates.size()); for (auto &patternAndPredList : patternsAndPredicates) { OrderedPredicateList list(patternAndPredList.first); for (auto &predicate : patternAndPredList.second) { OrderedPredicate *orderedPredicate = &*uniqued.find(predicate); list.predicates.insert(orderedPredicate); // Increment the primary sum for each reference to a particular predicate. ++orderedPredicate->primary; } lists.push_back(std::move(list)); } // For a particular pattern, get the total primary sum and add it to the // secondary sum of each predicate. Square the primary sums to emphasize // shared predicates within rather than across patterns. for (auto &list : lists) { unsigned total = 0; for (auto *predicate : list.predicates) total += predicate->primary * predicate->primary; for (auto *predicate : list.predicates) predicate->secondary += total; } // Sort the set of predicates now that the cost primary and secondary sums // have been computed. std::vector<OrderedPredicate *> ordered; ordered.reserve(uniqued.size()); for (auto &ip : uniqued) ordered.push_back(&ip); std::stable_sort( ordered.begin(), ordered.end(), [](OrderedPredicate *lhs, OrderedPredicate *rhs) { return *lhs < *rhs; }); // Build the matchers for each of the pattern predicate lists. std::unique_ptr<MatcherNode> root; for (OrderedPredicateList &list : lists) propagatePattern(root, list, ordered.begin(), ordered.end()); // Collapse the graph and insert the exit node. foldSwitchToBool(root); insertExitNode(&root); return root; } //===----------------------------------------------------------------------===// // MatcherNode //===----------------------------------------------------------------------===// MatcherNode::MatcherNode(TypeID matcherTypeID, Position *p, Qualifier *q, std::unique_ptr<MatcherNode> failureNode) : position(p), question(q), failureNode(std::move(failureNode)), matcherTypeID(matcherTypeID) {} //===----------------------------------------------------------------------===// // BoolNode //===----------------------------------------------------------------------===// BoolNode::BoolNode(Position *position, Qualifier *question, Qualifier *answer, std::unique_ptr<MatcherNode> successNode, std::unique_ptr<MatcherNode> failureNode) : MatcherNode(TypeID::get<BoolNode>(), position, question, std::move(failureNode)), answer(answer), successNode(std::move(successNode)) {} //===----------------------------------------------------------------------===// // SuccessNode //===----------------------------------------------------------------------===// SuccessNode::SuccessNode(pdl::PatternOp pattern, std::unique_ptr<MatcherNode> failureNode) : MatcherNode(TypeID::get<SuccessNode>(), /*position=*/nullptr, /*question=*/nullptr, std::move(failureNode)), pattern(pattern) {} //===----------------------------------------------------------------------===// // SwitchNode //===----------------------------------------------------------------------===// SwitchNode::SwitchNode(Position *position, Qualifier *question) : MatcherNode(TypeID::get<SwitchNode>(), position, question) {}
; A010130: Continued fraction for sqrt(32). ; 5,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1,1,1,10,1 lpb $0,1 trn $0,3 mov $2,$0 trn $0,1 mov $3,7 mov $4,6 lpe mov $1,$3 add $1,5 pow $2,$4 pow $1,$2 add $1,$2 mul $1,3 div $1,4 add $1,1
; *************************************************************************** ; *************************************************************************** ; ; lzsa2_6502.s ; ; NMOS 6502 decompressor for data stored in Emmanuel Marty's LZSA2 format. ; ; This code is written for the ACME assembler. ; ; Optional code is presented for two minor 6502 optimizations that break ; compatibility with the current LZSA2 format standard. ; ; The code is 241 bytes for the small version, and 267 bytes for the normal. ; ; Copyright John Brandwood 2019. ; ; Distributed under the Boost Software License, Version 1.0. ; (See accompanying file LICENSE_1_0.txt or copy at ; http://www.boost.org/LICENSE_1_0.txt) ; ; *************************************************************************** ; *************************************************************************** ; *************************************************************************** ; *************************************************************************** ; ; Decompression Options & Macros ; ; ; Choose size over space (within sane limits)? ; LZSA_SMALL_SIZE = 0 ; ; Remove code inlining to save space? ; ; This saves 15 bytes of code at the cost of 7% speed. ; !if LZSA_SMALL_SIZE { LZSA_NO_INLINE = 1 } else { LZSA_NO_INLINE = 0 } ; ; Use smaller code for copying literals? ; ; This saves 11 bytes of code at the cost of 5% speed. ; !if LZSA_SMALL_SIZE { LZSA_SHORT_CP = 1 } else { LZSA_SHORT_CP = 0 } ; ; We will read from or write to $FFFF. This prevents the ; use of the "INC ptrhi / BNE" trick and reduces speed. ; LZSA_USE_FFFF = 0 ; ; Macro to increment the source pointer to the next page. ; !macro LZSA_INC_PAGE { inc <lzsa_srcptr + 1 } ; ; Macro to read a byte from the compressed source data. ; !if LZSA_NO_INLINE { !macro LZSA_GET_SRC { jsr lzsa2_get_byte } } else { !macro LZSA_GET_SRC { lda (lzsa_srcptr),y inc <lzsa_srcptr + 0 bne .skip +LZSA_INC_PAGE .skip: } } ; ; Macro to speed up reading 50% of nibbles. ; ; This seems to save very few cycles compared to the ; increase in code size, and it isn't recommended. ; LZSA_SLOW_NIBL = 1 !if (LZSA_SLOW_NIBL + LZSA_SMALL_SIZE) { !macro LZSA_GET_NIBL { jsr lzsa2_get_nibble ; Always call a function. } } else { !macro LZSA_GET_NIBL { lsr <lzsa_nibflg ; Is there a nibble waiting? lda <lzsa_nibble ; Extract the lo-nibble. bcs .skip jsr lzsa2_new_nibble ; Extract the hi-nibble. .skip: ora #$F0 } } ; *************************************************************************** ; *************************************************************************** ; ; Data usage is last 11 bytes of zero-page. ; lzsa_cmdbuf = $F5 ; 1 byte. lzsa_nibflg = $F6 ; 1 byte. lzsa_nibble = $F7 ; 1 byte. lzsa_offset = $F8 ; 1 word. lzsa_winptr = $FA ; 1 word. lzsa_srcptr = $FC ; 1 word. lzsa_dstptr = $FE ; 1 word. lzsa_length = lzsa_winptr ; 1 word. LZSA_SRC_LO = $FC LZSA_SRC_HI = $FD LZSA_DST_LO = $FE LZSA_DST_HI = $FF ; *************************************************************************** ; *************************************************************************** ; ; lzsa2_unpack - Decompress data stored in Emmanuel Marty's LZSA2 format. ; ; Args: lzsa_srcptr = ptr to compessed data ; Args: lzsa_dstptr = ptr to output buffer ; Uses: lots! ; DECOMPRESS_LZSA2_FAST: lzsa2_unpack: ldy #0 ; Initialize source index. sty <lzsa_nibflg ; Initialize nibble buffer. !if (LZSA_NO_INLINE | LZSA_USE_FFFF) = 0 { beq .cp_length ; always taken .incsrc1: inc <lzsa_srcptr + 1 bne .resume_src1 ; always taken !if LZSA_SHORT_CP { .incsrc2: inc <lzsa_srcptr + 1 bne .resume_src2 ; always taken .incdst: inc <lzsa_dstptr + 1 bne .resume_dst ; always taken } } ; ; Copy bytes from compressed source data. ; .cp_length: ldx #$00 ; Hi-byte of length or offset. !if (LZSA_NO_INLINE | LZSA_USE_FFFF) { +LZSA_GET_SRC } else { lda (lzsa_srcptr),y inc <lzsa_srcptr + 0 beq .incsrc1 } .resume_src1: sta <lzsa_cmdbuf ; Preserve this for later. and #$18 ; Extract literal length. beq .lz_offset ; Skip directly to match? lsr ; Get 2-bit literal length. lsr lsr cmp #$03 ; Extended length? bne .got_cp_len jsr .get_length ; X=0 table index for literals. !if LZSA_SHORT_CP { .got_cp_len: cmp #0 ; Check the lo-byte of length. beq .put_cp_len inx ; Increment # of pages to copy. .put_cp_len: stx <lzsa_length tax .cp_page: lda (lzsa_srcptr),y sta (lzsa_dstptr),y inc <lzsa_srcptr + 0 !if (LZSA_NO_INLINE | LZSA_USE_FFFF) { bne .skip1 inc <lzsa_srcptr + 1 .skip1: inc <lzsa_dstptr + 0 bne .skip2 inc <lzsa_dstptr + 1 .skip2: } else { beq .incsrc2 .resume_src2: inc <lzsa_dstptr + 0 beq .incdst .resume_dst: } dex bne .cp_page dec <lzsa_length ; Any full pages left to copy? bne .cp_page } else { .got_cp_len: tay ; Check the lo-byte of length. beq .cp_page inx ; Increment # of pages to copy. .get_cp_src: clc ; Calc address of partial page. adc <lzsa_srcptr + 0 sta <lzsa_srcptr + 0 bcs .get_cp_dst dec <lzsa_srcptr + 1 .get_cp_dst: tya clc ; Calc address of partial page. adc <lzsa_dstptr + 0 sta <lzsa_dstptr + 0 bcs .get_cp_idx dec <lzsa_dstptr + 1 .get_cp_idx: tya ; Negate the lo-byte of length. eor #$FF tay iny .cp_page: lda (lzsa_srcptr),y sta (lzsa_dstptr),y iny bne .cp_page inc <lzsa_srcptr + 1 inc <lzsa_dstptr + 1 dex ; Any full pages left to copy? bne .cp_page } ; ================================ ; xyz ; 00z 5-bit offset ; 01z 9-bit offset ; 10z 13-bit offset ; 110 16-bit offset ; 111 repeat offset .lz_offset: lda <lzsa_cmdbuf asl bcs .get_13_16_rep asl bcs .get_9_bits .get_5_bits: dex ; X=$FF .get_13_bits: asl php +LZSA_GET_NIBL ; Always returns with CS. plp rol ; Shift into position, set C. eor #$01 cpx #$00 ; X=$FF for a 5-bit offset. bne .set_offset sbc #2 ; Subtract 512 because 13-bit ; offset starts at $FE00. bne .get_low8x ; Always NZ from previous SBC. .get_9_bits: dex ; X=$FF if CS, X=$FE if CC. asl bcc .get_low8 dex bcs .get_low8 ; Always VS from previous BIT. .get_13_16_rep: asl bcc .get_13_bits ; Shares code with 5-bit path. .get_16_rep: bmi .lz_length ; Repeat previous offset. ; ; Copy bytes from decompressed window. ; ; N.B. X=0 is expected and guaranteed when we get here. ; .get_16_bits: jsr lzsa2_get_byte ; Get hi-byte of offset. .get_low8x: tax .get_low8: !if (LZSA_NO_INLINE | LZSA_USE_FFFF) { +LZSA_GET_SRC ; Get lo-byte of offset. } else { lda (lzsa_srcptr),y inc <lzsa_srcptr + 0 beq .incsrc3 .resume_src3: } .set_offset: stx <lzsa_offset + 1 ; Save new offset. sta <lzsa_offset + 0 .lz_length: ldx #$00 ; Hi-byte of length. lda <lzsa_cmdbuf and #$07 clc adc #$02 cmp #$09 ; Extended length? bne .got_lz_len inx jsr .get_length ; X=1 table index for match. .got_lz_len: eor #$FF ; Negate the lo-byte of length tay ; and check for zero. iny beq .calc_lz_addr eor #$FF inx ; Increment # of pages to copy. clc ; Calc destination for partial adc <lzsa_dstptr + 0 ; page. sta <lzsa_dstptr + 0 bcs .calc_lz_addr dec <lzsa_dstptr + 1 .calc_lz_addr: clc ; Calc address of match. lda <lzsa_dstptr + 0 ; N.B. Offset is negative! adc <lzsa_offset + 0 sta <lzsa_winptr + 0 lda <lzsa_dstptr + 1 adc <lzsa_offset + 1 sta <lzsa_winptr + 1 .lz_page: lda (lzsa_winptr),y sta (lzsa_dstptr),y iny bne .lz_page inc <lzsa_winptr + 1 inc <lzsa_dstptr + 1 dex ; Any full pages left to copy? bne .lz_page jmp .cp_length ; Loop around to the beginning. !if (LZSA_NO_INLINE | LZSA_USE_FFFF) = 0 { .incsrc3: inc <lzsa_srcptr + 1 bne .resume_src3 ; always taken } ; ; Lookup tables to differentiate literal and match lengths. ; .nibl_len_tbl: !byte 3 + $10 ; 0+3 (for literal). !byte 9 + $10 ; 2+7 (for match). .byte_len_tbl: !byte 18 - 1 ; 0+3+15 - CS (for literal). !byte 24 - 1 ; 2+7+15 - CS (for match). ; ; Get 16-bit length in X:A register pair. ; .get_length: +LZSA_GET_NIBL cmp #$FF ; Extended length? bcs .byte_length adc .nibl_len_tbl,x ; Always CC from previous CMP. .got_length: ldx #$00 ; Set hi-byte of 4 & 8 bit rts ; lengths. .byte_length: jsr lzsa2_get_byte ; So rare, this can be slow! adc .byte_len_tbl,x ; Always CS from previous CMP. bcc .got_length beq .finished .word_length: jsr lzsa2_get_byte ; So rare, this can be slow! pha jsr lzsa2_get_byte ; So rare, this can be slow! tax pla rts lzsa2_get_byte: lda (lzsa_srcptr),y ; Subroutine version for when inc <lzsa_srcptr + 0 ; inlining isn't advantageous. beq lzsa2_next_page rts lzsa2_next_page: inc <lzsa_srcptr + 1 ; Inc & test for bank overflow. rts .finished: pla ; Decompression completed, pop pla ; return address. rts ; ; Get a nibble value from compressed data in A. ; !if (LZSA_SLOW_NIBL | LZSA_SMALL_SIZE) { lzsa2_get_nibble: lsr <lzsa_nibflg ; Is there a nibble waiting? lda <lzsa_nibble ; Extract the lo-nibble. bcs .got_nibble inc <lzsa_nibflg ; Reset the flag. !if (LZSA_NO_INLINE | LZSA_USE_FFFF) { +LZSA_GET_SRC } else { lda (lzsa_srcptr),y inc <lzsa_srcptr + 0 beq .incsrc4 .resume_src4: } sta <lzsa_nibble ; Preserve for next time. lsr ; Extract the hi-nibble. lsr lsr lsr .got_nibble: ora #$F0 rts } else { lzsa2_new_nibble: inc <lzsa_nibflg ; Reset the flag. !if (LZSA_NO_INLINE | LZSA_USE_FFFF) { +LZSA_GET_SRC } else { lda (lzsa_srcptr),y inc <lzsa_srcptr + 0 beq .incsrc4 .resume_src4: } sta <lzsa_nibble ; Preserve for next time. lsr ; Extract the hi-nibble. lsr lsr lsr rts } !if (LZSA_NO_INLINE | LZSA_USE_FFFF) = 0 { .incsrc4: inc <lzsa_srcptr + 1 bne .resume_src4 ; always taken }
; --------------------------------------------------------------------- ; The bootloader for Jazz (github.com/coditva/Jazz) ; Author: Utkarsh Maheshwari ; vi:filetype=nasm ; --------------------------------------------------------------------- bits 16 org 0x7c00 boot: mov ax, 0x2401 int 0x15 ; enable A20 bit mov ax, 0x3 ; set text-mode to 3 int 0x10 ; set VGA text-mode ; --------------------------------------------------------------------- ; we will enter 32bit protected mode now ; but first, gotta setup a Global Descriptor Table (GDT) lgdt [gdt_pointer] ; load the gdt table mov eax, cr0 ; set protected mode or eax, 0x1 ; on special mov cr0, eax ; CPU reg cr0 jmp CODE_SEG:boot2 ; long jump to the code segment ; --------------------------------------------------------------------- ; define the data structure for a GDT gdt_start: dq 0x0 gdt_code: dw 0xFFFF dw 0x0 db 0x0 db 10011010b db 11001111b db 0x0 gdt_data: dw 0xFFFF dw 0x0 db 0x0 db 10010010b db 11001111b db 0x0 gdt_end: ; --------------------------------------------------------------------- ; setup the data structure for the gdt_pointer gdt_pointer: dw gdt_end - gdt_start dd gdt_start ; --------------------------------------------------------------------- ; define segments CODE_SEG equ gdt_code - gdt_start DATA_SEG equ gdt_data - gdt_start ; --------------------------------------------------------------------- ; setup complete, let's get into 32bit! bits 32 boot2: mov ax, DATA_SEG ; setup segment registers mov ds, ax mov es, ax mov fs, ax mov gs, ax mov ss, ax ; --------------------------------------------------------------------- ; let's print something using VGA text mov ebx, 0xb8000 ; the VGA buffer is located at 0xb8000 ; we will be sending all text to this mov esi, hello ; load the string to be printed .loop: lodsb ; load a byte add al, 0x0 ; check if it is zero jz halt ; halt if it is or eax, 0x0200 ; add formatting info mov word [ebx], ax ; send to VGA add ebx, 2 ; increment address jmp .loop halt: cli ; clear interrupts flag (block interrupts) hlt ; hlt hello: db "I love OSDev. My bootloader is awesome!", 0 ; --------------------------------------------------------------------- ; mark this as bootable times 510-($-$$) db 0 ; fill the remaining memory with 0 dw 0xaa55 ; add the magic number
SECTION code_clib SECTION code_fp_math48 PUBLIC asm_dmul10a EXTERN am48_dmul10a defc asm_dmul10a = am48_dmul10a
; global descriptor table describes segments of memory for processor ; This is the hardest part about switching the CPU from 16-bit real mode into 32-bit ; protected mode. We must prepare the GDT, an in-memory complex data structure ; that defines memory segments and their protected-mode attributes gdt_start: ; don't remove the labels, they're needed to compute sizes and jumps ; the GDT starts with a null 8-byte dd 0x0 ; 4 byte dd 0x0 ; 4 byte ; GDT for code segment. base = 0x00000000, length = 0xfffff ; for flags, refer to os-dev.pdf document, page 36 gdt_code: dw 0xffff ; segment length, bits 0-15 dw 0x0 ; segment base, bits 0-15 db 0x0 ; segment base, bits 16-23 db 10011010b ; flags (8 bits) db 11001111b ; flags (4 bits) + segment length, bits 16-19 db 0x0 ; segment base, bits 24-31 ; GDT for data segment. base and length identical to code segment ; some flags changed, again, refer to os-dev.pdf gdt_data: dw 0xffff dw 0x0 db 0x0 db 10010010b db 11001111b db 0x0 gdt_end: ; GDT descriptor gdt_descriptor: dw gdt_end - gdt_start - 1 ; size (16 bit), always one less of its true size dd gdt_start ; address (32 bit) ; define some constants for later use CODE_SEG equ gdt_code - gdt_start DATA_SEG equ gdt_data - gdt_start
; A027775: a(n) = (n+1)*binomial(n+1, 15). ; 15,256,2312,14688,73644,310080,1139544,3751968,11277222,31380096,81719000,200880160,469364220,1048380480,2249204040,4653525600,9316746045,18103127040,34226224560,63102895680,113678010600,200444492160,346475391120,587908889280,980492785740,1609013802240,2600723270736,4144241959872,6515904237928,10116111150464,15519034151280,23539982985024,35325966313803,52476483808512,77203454426616,112541478756000,162622436802420,233031833128640,331268430798760,467333693376480,654483528918450,910181971923840,1257304943359080,1725652317201120,2353838446777860,3191645351563200,4302939258393720,5769270495035040,7694299259003385 mov $1,$0 add $1,15 bin $1,$0 add $0,15 mul $1,$0
#!/usr/bin/sisa16_asm -run .ZERO_STACK_POINTER: astp;popa; section 0x40000; :ascii_spinny: ..asciz:-\|/ .ascii_spinny_len:4 .ITER_REGION:3 ..(ITER_REGION): bytes 0,0,0,0; .ld_iter: farllda %&@&% .ld_iterb: farlldb %&@&% .st_iter: farstla %&@&% //..include"libc.hasm" ..include"libc_pre.hasm" ..(2): ..dinclude"libc_pre.bin" .line_length: 90 .line_length_plus_1: 91 .num_lines: 20 .wait_time: 50 ..main(3): lrx0 %/0x70000%; proc_krenel; halt; ..(7): asm_begin_region_restriction; la '\r'; putchar; la 0; st_iter; alpush; //our loop! asciifun_looptop: la ' '; putchar; alpop; aincr; alpush; lb ascii_spinny_len;mod; sc %4%; lb %~ascii_spinny%; add; ba; farilda; putchar; la '\r'; putchar; la '\n'; interrupt; la %~wait_time%; alpush; proc_wait; alpop; sc %asciifun_looptop%;jmp; asciifun_loopout: la 7; putchar; halt; asm_end_restriction;
.size 8000 .text@48 jp lstatint .text@100 jp lbegin .data@143 80 .text@150 lbegin: ld c, 41 ld b, 03 ld d, 03 lbegin_waitm3: ldff a, (c) and a, d cmp a, b jrnz lbegin_waitm3 ld a, 20 ldff(c), a xor a, a ldff(0f), a ld a, 02 ldff(ff), a ei ld hl, 8000 ld a, 01 .text@1000 lstatint: nop nop nop nop nop nop nop nop nop nop ld(hl), a .text@1048 ld a, (hl) and a, 07 jp lprint_a .text@7000 lprint_a: push af ld b, 91 call lwaitly_b xor a, a ldff(40), a pop af ld(9800), a ld bc, 7a00 ld hl, 8000 ld d, a0 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles ld a, c0 ldff(47), a ld a, 80 ldff(68), a ld a, ff ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a xor a, a ldff(69), a ldff(69), a ldff(43), a ld a, 91 ldff(40), a lprint_limbo: jr lprint_limbo .text@7400 lwaitly_b: ld c, 44 lwaitly_b_loop: ldff a, (c) cmp a, b jrnz lwaitly_b_loop ret .data@7a00 00 00 7f 7f 41 41 41 41 41 41 41 41 41 41 7f 7f 00 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 00 7f 7f 01 01 01 01 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 01 01 01 01 3f 3f 01 01 01 01 7f 7f 00 00 41 41 41 41 41 41 7f 7f 01 01 01 01 01 01 00 00 7f 7f 40 40 40 40 7e 7e 01 01 01 01 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 41 41 41 41 7f 7f 00 00 7f 7f 01 01 02 02 04 04 08 08 10 10 10 10 00 00 3e 3e 41 41 41 41 3e 3e 41 41 41 41 3e 3e 00 00 7f 7f 41 41 41 41 7f 7f 01 01 01 01 7f 7f
; A171445: Sequence whose G.f is given by f(z)=(1+z)^(24)/(1-z). ; 1,25,301,2325,12951,55455,190051,536155,1271626,2579130,4540386,7036530,9740686,12236830,14198086,15505590,16241061,16587165,16721761,16764265,16774891,16776915,16777191,16777215,16777216,16777216 lpb $0 mov $2,$0 sub $0,1 seq $2,10940 ; Binomial coefficient C(24,n). add $1,$2 lpe add $1,1 mov $0,$1
;------------------------------------------------------------------------------ ; ; EnableInterrupts() for AArch64 ; ; Copyright (c) 2006 - 2009, Intel Corporation. All rights reserved.<BR> ; Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR> ; Portions copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.<BR> ; SPDX-License-Identifier: BSD-2-Clause-Patent ; ;------------------------------------------------------------------------------ EXPORT EnableInterrupts AREA BaseLib_LowLevel, CODE, READONLY DAIF_WR_IRQ_BIT EQU (1 << 1) ;/** ; Enables CPU interrupts. ; ;**/ ;VOID ;EFIAPI ;EnableInterrupts ( ; VOID ; ); ; EnableInterrupts msr daifclr, #DAIF_WR_IRQ_BIT ret END
; A087810: First differences of A029931. ; 1,1,1,0,1,1,1,-2,1,1,1,0,1,1,1,-5,1,1,1,0,1,1,1,-2,1,1,1,0,1,1,1,-9,1,1,1,0,1,1,1,-2,1,1,1,0,1,1,1,-5,1,1,1,0,1,1,1,-2,1,1,1,0,1,1,1,-14,1,1,1,0,1,1,1,-2,1,1,1,0,1,1,1,-5,1,1,1,0,1,1,1,-2,1,1,1,0,1,1,1,-9,1,1,1,0 mov $1,1 mov $2,1 lpb $0 sub $0,1 mul $0,2 dif $0,4 sub $2,1 add $1,$2 lpe mov $0,$1
// Copyright (c) 2012-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientversion.h" #include "tinyformat.h" #include <string> /** * Name of client reported in the 'version' message. Report the same name * for both bitcoind and bitcoin-core, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("VENTASCore"); /** * Client version number */ #define CLIENT_VERSION_SUFFIX "" /** * The following part of the code determines the CLIENT_BUILD variable. * Several mechanisms are used for this: * * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is * generated by the build environment, possibly containing the output * of git-describe in a macro called BUILD_DESC * * secondly, if this is an exported version of the code, GIT_ARCHIVE will * be defined (automatically using the export-subst git attribute), and * GIT_COMMIT will contain the commit id. * * then, three options exist for determining CLIENT_BUILD: * * if BUILD_DESC is defined, use that literally (output of git-describe) * * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] * * otherwise, use v[maj].[min].[rev].[build]-unk * finally CLIENT_VERSION_SUFFIX is added */ //! First, include build.h if requested #ifdef HAVE_BUILD_INFO #include "build.h" #endif //! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE #define GIT_COMMIT_ID "$Format:%h$" #define GIT_COMMIT_DATE "$Format:%cD$" #endif #define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix) #define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC #ifdef BUILD_SUFFIX #define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX) #elif defined(GIT_COMMIT_ID) #define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) #else #define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) #endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); static std::string FormatVersion(int nVersion) { if (nVersion % 100 == 0) return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100); else return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { return CLIENT_BUILD; } /** * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); }
; A004448: Nimsum n + 7. ; 7,6,5,4,3,2,1,0,15,14,13,12,11,10,9,8,23,22,21,20,19,18,17,16,31,30,29,28,27,26,25,24,39,38,37,36,35,34,33,32,47,46,45,44,43,42,41,40,55,54,53,52,51,50,49,48,63,62,61,60,59,58,57,56,71,70,69,68,67,66,65,64,79,78,77,76,75,74,73,72,87,86,85,84,83,82,81,80,95,94,93,92,91,90,89,88,103,102,101,100,99,98,97,96,111,110,109,108,107,106,105,104,119,118,117,116,115,114,113,112,127,126,125,124,123,122,121,120,135,134,133,132,131,130,129,128,143,142,141,140,139,138,137,136,151,150,149,148,147,146,145,144,159,158,157,156,155,154,153,152,167,166,165,164,163,162,161,160,175,174,173,172,171,170,169,168,183,182,181,180,179,178,177,176,191,190,189,188,187,186,185,184,199,198,197,196,195,194,193,192,207,206,205,204,203,202,201,200,215,214,213,212,211,210,209,208,223,222,221,220,219,218,217,216,231,230,229,228,227,226,225,224,239,238,237,236,235,234,233,232,247,246,245,244,243,242,241,240,255,254 add $0,9 mov $3,$0 lpb $0,1 sub $0,7 mov $1,$4 add $1,3 mov $2,$1 sub $2,9 mov $1,$2 mov $4,12 sub $4,$0 trn $0,1 mul $1,2 add $1,$3 add $4,5 lpe sub $1,20
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/spanner/internal/metadata_spanner_stub.h" #include "google/cloud/spanner/database.h" #include "google/cloud/spanner/testing/mock_spanner_stub.h" #include "google/cloud/internal/api_client_header.h" #include "google/cloud/testing_util/status_matchers.h" #include "google/cloud/testing_util/validate_metadata.h" #include <gmock/gmock.h> #include <grpcpp/grpcpp.h> namespace google { namespace cloud { namespace spanner_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace { using ::google::cloud::testing_util::ValidateMetadataFixture; using ::testing::Contains; using ::testing::Not; using ::testing::Pair; // This ugly macro and the supporting template member function refactor most // of this test to one-liners. #define SESSION_TEST(X, Y) \ ExpectSession(EXPECT_CALL(*mock_, X), Y(), #X, &MetadataSpannerStub::X) class MetadataSpannerStubTest : public ::testing::Test { protected: void SetUp() override { mock_ = std::make_shared<spanner_testing::MockSpannerStub>(); } void TearDown() override {} static Status TransientError() { return Status(StatusCode::kUnavailable, "try-again"); } template <typename T> static void ExpectTransientError(StatusOr<T> const& status) { EXPECT_EQ(TransientError(), status.status()); } static void ExpectTransientError(Status const& status) { EXPECT_EQ(TransientError(), status); } Status IsContextMDValid(grpc::ClientContext& context, std::string const& method) { return validate_metadata_fixture_.IsContextMDValid( context, method, google::cloud::internal::ApiClientHeader(), db_.FullName()); } std::multimap<std::string, std::string> GetMetadata( grpc::ClientContext& context) { return validate_metadata_fixture_.GetMetadata(context); } template <typename MockCall, typename Request, typename MemberFunction> void ExpectSession(MockCall& call, Request const&, std::string const& rpc_name, MemberFunction member_function) { call.WillOnce( [this, rpc_name](grpc::ClientContext& context, Request const&) { EXPECT_STATUS_OK(IsContextMDValid( context, "google.spanner.v1.Spanner." + rpc_name)); return TransientError(); }); MetadataSpannerStub stub(mock_, db_.FullName()); grpc::ClientContext context; Request request; request.set_session( google::cloud::spanner::Database( google::cloud::spanner::Instance( google::cloud::Project("test-project-id"), "test-instance-id"), "test-database-id") .FullName() + "/sessions/test-session-id"); auto result = (stub.*member_function)(context, request); ExpectTransientError(result); } std::shared_ptr<spanner_testing::MockSpannerStub> mock_; spanner::Database db_{"test-project", "test-instance", "test-database"}; private: ValidateMetadataFixture validate_metadata_fixture_; }; TEST_F(MetadataSpannerStubTest, UserProject) { EXPECT_CALL(*mock_, CreateSession) .WillOnce([this](grpc::ClientContext& context, google::spanner::v1::CreateSessionRequest const&) { auto metadata = GetMetadata(context); EXPECT_THAT(metadata, Not(Contains(Pair("x-goog-user-project", ::testing::_)))); return TransientError(); }) .WillOnce([this](grpc::ClientContext& context, google::spanner::v1::CreateSessionRequest const&) { auto metadata = GetMetadata(context); EXPECT_THAT(metadata, Contains(Pair("x-goog-user-project", "test-project"))); return TransientError(); }); MetadataSpannerStub stub(mock_, db_.FullName()); google::spanner::v1::CreateSessionRequest request; request.set_database(db_.FullName()); { internal::OptionsSpan span(Options{}); grpc::ClientContext context; auto status = stub.CreateSession(context, request); EXPECT_EQ(TransientError(), status.status()); } { internal::OptionsSpan span( Options{}.set<UserProjectOption>("test-project")); grpc::ClientContext context; auto status = stub.CreateSession(context, request); EXPECT_EQ(TransientError(), status.status()); } } TEST_F(MetadataSpannerStubTest, CreateSession) { EXPECT_CALL(*mock_, CreateSession) .WillOnce([this](grpc::ClientContext& context, google::spanner::v1::CreateSessionRequest const&) { EXPECT_STATUS_OK(IsContextMDValid( context, "google.spanner.v1.Spanner.CreateSession")); return TransientError(); }); MetadataSpannerStub stub(mock_, db_.FullName()); grpc::ClientContext context; google::spanner::v1::CreateSessionRequest request; request.set_database(db_.FullName()); auto status = stub.CreateSession(context, request); EXPECT_EQ(TransientError(), status.status()); } TEST_F(MetadataSpannerStubTest, BatchCreateSessions) { EXPECT_CALL(*mock_, BatchCreateSessions) .WillOnce([this](grpc::ClientContext& context, google::spanner::v1::BatchCreateSessionsRequest const&) { EXPECT_STATUS_OK(IsContextMDValid( context, "google.spanner.v1.Spanner.BatchCreateSessions")); return TransientError(); }); MetadataSpannerStub stub(mock_, db_.FullName()); grpc::ClientContext context; google::spanner::v1::BatchCreateSessionsRequest request; request.set_database(db_.FullName()); request.set_session_count(3); auto status = stub.BatchCreateSessions(context, request); EXPECT_EQ(TransientError(), status.status()); } TEST_F(MetadataSpannerStubTest, GetSession) { EXPECT_CALL(*mock_, GetSession) .WillOnce([this](grpc::ClientContext& context, google::spanner::v1::GetSessionRequest const&) { EXPECT_STATUS_OK( IsContextMDValid(context, "google.spanner.v1.Spanner.GetSession")); return TransientError(); }); MetadataSpannerStub stub(mock_, db_.FullName()); grpc::ClientContext context; google::spanner::v1::GetSessionRequest request; request.set_name( google::cloud::spanner::Database( google::cloud::spanner::Instance( google::cloud::Project("test-project-id"), "test-instance-id"), "test-database-id") .FullName() + "/sessions/test-session-id"); auto status = stub.GetSession(context, request); EXPECT_EQ(TransientError(), status.status()); } TEST_F(MetadataSpannerStubTest, ListSessions) { EXPECT_CALL(*mock_, ListSessions) .WillOnce([this](grpc::ClientContext& context, google::spanner::v1::ListSessionsRequest const&) { EXPECT_STATUS_OK(IsContextMDValid( context, "google.spanner.v1.Spanner.ListSessions")); return TransientError(); }); MetadataSpannerStub stub(mock_, db_.FullName()); grpc::ClientContext context; google::spanner::v1::ListSessionsRequest request; request.set_database(db_.FullName()); auto status = stub.ListSessions(context, request); EXPECT_EQ(TransientError(), status.status()); } TEST_F(MetadataSpannerStubTest, DeleteSession) { EXPECT_CALL(*mock_, DeleteSession) .WillOnce([this](grpc::ClientContext& context, google::spanner::v1::DeleteSessionRequest const&) { EXPECT_STATUS_OK(IsContextMDValid( context, "google.spanner.v1.Spanner.DeleteSession")); return TransientError(); }); MetadataSpannerStub stub(mock_, db_.FullName()); grpc::ClientContext context; google::spanner::v1::DeleteSessionRequest request; request.set_name( google::cloud::spanner::Database( google::cloud::spanner::Instance( google::cloud::Project("test-project-id"), "test-instance-id"), "test-database-id") .FullName() + "/sessions/test-session-id"); auto status = stub.DeleteSession(context, request); EXPECT_EQ(TransientError(), status); } TEST_F(MetadataSpannerStubTest, ExecuteSql) { SESSION_TEST(ExecuteSql, google::spanner::v1::ExecuteSqlRequest); } TEST_F(MetadataSpannerStubTest, ExecuteStreamingSql) { EXPECT_CALL(*mock_, ExecuteStreamingSql) .WillOnce([this](grpc::ClientContext& context, google::spanner::v1::ExecuteSqlRequest const&) { EXPECT_STATUS_OK(IsContextMDValid( context, "google.spanner.v1.Spanner.ExecuteStreamingSql")); return std::unique_ptr<grpc::ClientReaderInterface< google::spanner::v1::PartialResultSet>>{}; }); MetadataSpannerStub stub(mock_, db_.FullName()); grpc::ClientContext context; google::spanner::v1::ExecuteSqlRequest request; request.set_session( google::cloud::spanner::Database( google::cloud::spanner::Instance( google::cloud::Project("test-project-id"), "test-instance-id"), "test-database-id") .FullName() + "/sessions/test-session-id"); auto result = stub.ExecuteStreamingSql(context, request); EXPECT_FALSE(result); } TEST_F(MetadataSpannerStubTest, ExecuteBatchDml) { SESSION_TEST(ExecuteBatchDml, google::spanner::v1::ExecuteBatchDmlRequest); } TEST_F(MetadataSpannerStubTest, StreamingRead) { EXPECT_CALL(*mock_, StreamingRead) .WillOnce([this](grpc::ClientContext& context, google::spanner::v1::ReadRequest const&) { EXPECT_STATUS_OK(IsContextMDValid( context, "google.spanner.v1.Spanner.StreamingRead")); return std::unique_ptr<grpc::ClientReaderInterface< google::spanner::v1::PartialResultSet>>{}; }); MetadataSpannerStub stub(mock_, db_.FullName()); grpc::ClientContext context; google::spanner::v1::ReadRequest request; request.set_session( google::cloud::spanner::Database( google::cloud::spanner::Instance( google::cloud::Project("test-project-id"), "test-instance-id"), "test-database-id") .FullName() + "/sessions/test-session-id"); auto result = stub.StreamingRead(context, request); EXPECT_FALSE(result); } TEST_F(MetadataSpannerStubTest, BeginTransaction) { SESSION_TEST(BeginTransaction, google::spanner::v1::BeginTransactionRequest); } TEST_F(MetadataSpannerStubTest, Commit) { SESSION_TEST(Commit, google::spanner::v1::CommitRequest); } TEST_F(MetadataSpannerStubTest, Rollback) { SESSION_TEST(Rollback, google::spanner::v1::RollbackRequest); } TEST_F(MetadataSpannerStubTest, PartitionQuery) { SESSION_TEST(PartitionQuery, google::spanner::v1::PartitionQueryRequest); } TEST_F(MetadataSpannerStubTest, PartitionRead) { SESSION_TEST(PartitionRead, google::spanner::v1::PartitionReadRequest); } } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace spanner_internal } // namespace cloud } // namespace google
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r15 push %r8 push %rbp push %rcx push %rdi push %rsi lea addresses_WT_ht+0x1a1ba, %r12 nop nop nop nop dec %r8 mov (%r12), %di nop nop sub %rsi, %rsi lea addresses_UC_ht+0x3113, %r10 nop nop nop nop nop add %rsi, %rsi mov (%r10), %rbp nop nop nop nop add $35271, %r12 lea addresses_WC_ht+0x4623, %r10 sub %r15, %r15 movups (%r10), %xmm7 vpextrq $1, %xmm7, %rdi sub $40827, %rbp lea addresses_D_ht+0x16913, %rsi lea addresses_UC_ht+0x3413, %rdi nop nop nop nop nop cmp $49879, %rbp mov $53, %rcx rep movsl cmp $32269, %rdi lea addresses_D_ht+0x3013, %r10 nop nop nop nop nop and %rcx, %rcx vmovups (%r10), %ymm7 vextracti128 $0, %ymm7, %xmm7 vpextrq $0, %xmm7, %r8 nop nop nop nop nop and %r12, %r12 lea addresses_WC_ht+0x7c72, %rsi lea addresses_D_ht+0x19013, %rdi nop nop nop nop nop sub $47555, %r8 mov $107, %rcx rep movsw nop nop nop nop nop xor $53029, %rcx lea addresses_WC_ht+0x15aaf, %r8 clflush (%r8) nop nop nop xor %r12, %r12 mov (%r8), %r10 nop nop nop nop sub $14948, %r8 lea addresses_WT_ht+0xa913, %rbp nop nop nop nop nop and %rdi, %rdi mov $0x6162636465666768, %r15 movq %r15, (%rbp) nop sub %rsi, %rsi pop %rsi pop %rdi pop %rcx pop %rbp pop %r8 pop %r15 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r14 push %r9 push %rax push %rcx push %rdi push %rsi // Faulty Load lea addresses_UC+0x18113, %r14 nop nop nop nop nop and %r9, %r9 movb (%r14), %al lea oracles, %r9 and $0xff, %rax shlq $12, %rax mov (%r9,%rax,1), %rax pop %rsi pop %rdi pop %rcx pop %rax pop %r9 pop %r14 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': True, 'type': 'addresses_UC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'NT': True, 'AVXalign': True, 'size': 2, 'congruent': 0, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'src': {'NT': True, 'AVXalign': False, 'size': 8, 'congruent': 11, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 2, 'same': True, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_D_ht'}, 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'} {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 8, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 0, 'same': False, 'type': 'addresses_WC_ht'}, 'dst': {'congruent': 8, 'same': True, 'type': 'addresses_D_ht'}, 'OP': 'REPM'} {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 2, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 11, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'37': 21829} 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 */
; A061282: Minimal number of steps to get from 0 to n by (a) adding 1 or (b) multiplying by 3. A stopping problem: begin with n and at each stage if a multiple of 3 divide by 3, otherwise subtract 1. ; 0,1,2,2,3,4,3,4,5,3,4,5,4,5,6,5,6,7,4,5,6,5,6,7,6,7,8,4,5,6,5,6,7,6,7,8,5,6,7,6,7,8,7,8,9,6,7,8,7,8,9,8,9,10,5,6,7,6,7,8,7,8,9,6,7,8,7,8,9,8,9,10,7,8,9,8,9,10,9,10,11,5,6,7,6,7,8,7,8,9,6,7,8,7,8,9,8,9,10,7,8,9,8,9,10,9,10,11,6,7,8,7,8,9,8,9,10,7,8,9,8,9,10,9,10,11,8,9,10,9,10,11,10,11,12,7,8,9,8,9,10,9,10,11,8,9,10,9,10,11,10,11,12,9,10,11,10,11,12,11,12,13,6,7,8,7,8,9,8,9,10,7,8,9,8,9,10,9,10,11,8,9,10,9,10,11,10,11,12,7,8,9,8,9,10,9,10,11,8,9,10,9,10,11,10,11,12,9,10,11,10,11,12,11,12,13,8,9,10,9,10,11,10,11,12,9,10,11,10,11,12,11,12,13,10,11,12,11,12,13,12,13,14,6,7,8,7,8,9,8 mov $1,5 add $1,$0 mov $2,$0 lpb $2,1 lpb $1,1 div $2,3 mov $3,$1 sub $1,$2 mul $1,2 add $1,1 sub $1,$3 lpe lpe sub $1,5
// -- Include rang before any os headers. #include "../rang_include.hpp" // -- #include "backend/generator.hpp" #include "compiler.hpp" #include "config.hpp" #include "frontend/analysis.hpp" #include "frontend/source.hpp" #include "novasm/serialization.hpp" #include "opt/opt.hpp" #include "utilities.hpp" #include <algorithm> #include <chrono> #include <fstream> namespace novc { using Clock = std::chrono::high_resolution_clock; using Duration = std::chrono::duration<double>; static auto operator<<(std::ostream& out, const Duration& rhs) -> std::ostream&; static auto msgHeader(std::ostream& out) -> std::ostream&; static auto infHeader(std::ostream& out) -> std::ostream&; auto compile(const CompileOptions& options) -> bool { std::cout << rang::style::bold << "--- Novus compiler [" PROJECT_VER "] ---\n" << rang::style::reset; auto validateOnly = options.destPath.empty(); if (validateOnly) { msgHeader(std::cout) << "Validate: " << options.srcPath << '\n'; } else { msgHeader(std::cout) << "Compile: " << options.srcPath << '\n'; } // Load the source file. const auto absSrcPath = filesystem::canonical(filesystem::absolute(options.srcPath)); auto srcFilestream = std::ifstream{absSrcPath.string()}; if (!srcFilestream.good()) { msgHeader(std::cerr) << rang::style::bold << rang::bg::red << "Failed to read source file\n" << rang::style::reset; return false; } const auto compileStartTime = Clock::now(); // Parse the source. const auto src = frontend::buildSource( absSrcPath.filename().string(), absSrcPath, std::istreambuf_iterator<char>{srcFilestream}, std::istreambuf_iterator<char>{}); // Build a program out of the source. const auto frontendOut = frontend::analyze(src, options.searchPaths); const auto compileEndTime = Clock::now(); const auto compileDur = std::chrono::duration_cast<Duration>(compileEndTime - compileStartTime); if (!frontendOut.isSuccess()) { msgHeader(std::cout) << rang::style::bold << rang::bg::red << "Compilation failed, errors:\n"; for (auto diagItr = frontendOut.beginDiags(); diagItr != frontendOut.endDiags(); ++diagItr) { diagItr->print(std::cerr, frontendOut.getSourceTable()); std::cerr << '\n'; } std::cerr << rang::style::reset; return false; } const auto numFiles = 1u + std::distance(frontendOut.getImportedSources().begin(), frontendOut.getImportedSources().end()); msgHeader(std::cout) << "Analyzed program in: " << compileDur << '\n'; infHeader(std::cout) << "Files: " << numFiles << '\n'; infHeader(std::cout) << "Types: " << frontendOut.getProg().getTypeCount() << '\n'; infHeader(std::cout) << "Functions: " << frontendOut.getProg().getFuncCount() << '\n'; infHeader(std::cout) << "Execute statements: " << frontendOut.getProg().getExecStmtCount() << '\n'; if (validateOnly) { msgHeader(std::cout) << "Successfully validated program\n"; return true; } auto optProg = prog::Program{}; if (options.optimize) { msgHeader(std::cout) << "Optimize program\n"; const auto optStartTime = Clock::now(); optProg = opt::optimize(frontendOut.getProg()); const auto optEndTime = Clock::now(); const auto optDur = std::chrono::duration_cast<Duration>(optEndTime - optStartTime); msgHeader(std::cout) << "Finished optimizing program in: " << optDur << '\n'; infHeader(std::cout) << "Types: " << optProg.getTypeCount() << '\n'; infHeader(std::cout) << "Functions: " << optProg.getFuncCount() << '\n'; infHeader(std::cout) << "Execute statements: " << optProg.getExecStmtCount() << '\n'; } const auto& prog = options.optimize ? optProg : frontendOut.getProg(); // Generate novus assembly representation. msgHeader(std::cout) << "Generate novus assembly\n"; const auto asmStartTime = Clock::now(); const auto asmOutput = backend::generate(prog); const auto asmEndTime = Clock::now(); const auto asmDur = std::chrono::duration_cast<Duration>(asmEndTime - asmStartTime); msgHeader(std::cout) << "Finished generating novus assembly in: " << asmDur << '\n'; infHeader(std::cout) << "Instructions: " << asmOutput.first.getInstructions().size() << '\n'; // Write executable to disk. auto destFilestream = std::ofstream{options.destPath.string(), std::ios::binary}; if (!destFilestream.good()) { msgHeader(std::cerr) << rang::style::bold << rang::bg::red << "Failed to write to output path\n" << rang::style::reset; return false; } novasm::serialize(asmOutput.first, std::ostreambuf_iterator<char>{destFilestream}); if (!setOutputFilePermissions(options.destPath)) { msgHeader(std::cerr) << rang::style::bold << rang::bg::red << "Failed to set output file permissions\n" << rang::style::reset; return false; } msgHeader(std::cout) << "Successfully compiled executable to: " << options.destPath << '\n'; return true; } static auto msgHeader(std::ostream& out) -> std::ostream& { return out << rang::style::bold << rang::fg::green << "* " << rang::style::reset << rang::fg::reset; } static auto infHeader(std::ostream& out) -> std::ostream& { return out << rang::style::dim << rang::fg::gray << " * " << rang::style::reset << rang::fg::reset; } static auto operator<<(std::ostream& out, const Duration& rhs) -> std::ostream& { auto s = rhs.count(); if (s < .000001) { // NOLINT: Magic numbers out << s * 1000000000 << " ns"; // NOLINT: Magic numbers } else if (s < .001) { // NOLINT: Magic numbers out << s * 1000000 << " us"; // NOLINT: Magic numbers } else if (s < 1) { // NOLINT: Magic numbers out << s * 1000 << " ms"; // NOLINT: Magic numbers } else { out << s << " s"; } return out; } } // namespace novc
/* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "oneflow/core/framework/framework.h" #include "oneflow/core/common/balanced_splitter.h" #include "oneflow/user/image/image_util.h" namespace oneflow { REGISTER_CPU_ONLY_USER_OP("crop_mirror_normalize_from_tensorbuffer") .Input("in") .OptionalInput("mirror") .Output("out") .Attr<std::string>("color_space", "BGR") .Attr<std::string>("output_layout", "NCHW") .Attr<std::vector<float>>("mean", {0.0}) .Attr<std::vector<float>>("std", {1.0}) .Attr<int64_t>("crop_h", 0) .Attr<int64_t>("crop_w", 0) .Attr<float>("crop_pos_x", 0.5) .Attr<float>("crop_pos_y", 0.5) .Attr<DataType>("output_dtype", DataType::kFloat) .SetTensorDescInferFn([](user_op::InferContext* ctx) -> Maybe<void> { user_op::TensorDesc* in_tensor = ctx->TensorDesc4ArgNameAndIndex("in", 0); user_op::TensorDesc* mirror_tensor = ctx->TensorDesc4ArgNameAndIndex("mirror", 0); if (mirror_tensor) { CHECK_OR_RETURN(mirror_tensor->shape().NumAxes() == 1 && in_tensor->shape().At(0) == mirror_tensor->shape().At(0)); CHECK_EQ_OR_RETURN(mirror_tensor->data_type(), DataType::kInt8); } user_op::TensorDesc* out_tensor = ctx->TensorDesc4ArgNameAndIndex("out", 0); int64_t N = in_tensor->shape().At(0); int64_t H = ctx->Attr<int64_t>("crop_h"); int64_t W = ctx->Attr<int64_t>("crop_w"); std::string color_space = ctx->Attr<std::string>("color_space"); int64_t C = ImageUtil::IsColor(color_space) ? 3 : 1; CHECK_EQ_OR_RETURN(in_tensor->data_type(), DataType::kTensorBuffer); CHECK_OR_RETURN(H != 0 && W != 0); CHECK_OR_RETURN(in_tensor->shape().NumAxes() == 1); std::string output_layout = ctx->Attr<std::string>("output_layout"); if (output_layout == "NCHW") { *out_tensor->mut_shape() = Shape({N, C, H, W}); } else if (output_layout == "NHWC") { *out_tensor->mut_shape() = Shape({N, H, W, C}); } else { return Error::CheckFailedError() << "output_layout: " << output_layout << " is not supported"; } DataType output_dtype = ctx->Attr<DataType>("output_dtype"); CHECK_EQ_OR_RETURN(output_dtype, DataType::kFloat); // only support float now; for float16 in future *out_tensor->mut_data_type() = output_dtype; return Maybe<void>::Ok(); }) .SetGetSbpFn([](user_op::SbpContext* ctx) -> Maybe<void> { ctx->NewBuilder().Split(ctx->inputs(), 0).Split(ctx->outputs(), 0).Build(); return Maybe<void>::Ok(); }); REGISTER_USER_OP("crop_mirror_normalize_from_uint8") .Input("in") .OptionalInput("mirror") .Output("out") .Attr<std::string>("color_space", "BGR") .Attr<std::string>("output_layout", "NCHW") .Attr<std::vector<float>>("mean", {0.0}) .Attr<std::vector<float>>("std", {1.0}) .Attr<int64_t>("crop_h", 0) .Attr<int64_t>("crop_w", 0) .Attr<float>("crop_pos_x", 0.5) .Attr<float>("crop_pos_y", 0.5) .Attr<DataType>("output_dtype", DataType::kFloat) .SetTensorDescInferFn([](user_op::InferContext* ctx) -> Maybe<void> { user_op::TensorDesc* in_tensor = ctx->TensorDesc4ArgNameAndIndex("in", 0); user_op::TensorDesc* mirror_tensor = ctx->TensorDesc4ArgNameAndIndex("mirror", 0); if (mirror_tensor) { CHECK_OR_RETURN(mirror_tensor->shape().NumAxes() == 1 && in_tensor->shape().At(0) == mirror_tensor->shape().At(0)); CHECK_EQ_OR_RETURN(mirror_tensor->data_type(), DataType::kInt8); } user_op::TensorDesc* out_tensor = ctx->TensorDesc4ArgNameAndIndex("out", 0); int64_t N = in_tensor->shape().At(0); int64_t H = ctx->Attr<int64_t>("crop_h"); int64_t W = ctx->Attr<int64_t>("crop_w"); std::string color_space = ctx->Attr<std::string>("color_space"); int64_t C = ImageUtil::IsColor(color_space) ? 3 : 1; CHECK_EQ_OR_RETURN(in_tensor->data_type(), DataType::kUInt8); CHECK_EQ_OR_RETURN(in_tensor->shape().NumAxes(), 4); // {N, H, W, C} CHECK_EQ_OR_RETURN(in_tensor->shape().At(3), C); if (H == 0 || W == 0) { H = in_tensor->shape().At(1); W = in_tensor->shape().At(2); } else { H = std::min(H, in_tensor->shape().At(1)); W = std::min(W, in_tensor->shape().At(2)); } std::string output_layout = ctx->Attr<std::string>("output_layout"); if (output_layout == "NCHW") { *out_tensor->mut_shape() = Shape({N, C, H, W}); } else if (output_layout == "NHWC") { *out_tensor->mut_shape() = Shape({N, H, W, C}); } else { return Error::CheckFailedError() << "output_layout: " << output_layout << " is not supported"; } DataType output_dtype = ctx->Attr<DataType>("output_dtype"); CHECK_EQ_OR_RETURN(output_dtype, DataType::kFloat); // only support float now; for float16 in future *out_tensor->mut_data_type() = output_dtype; return Maybe<void>::Ok(); }) .SetGetSbpFn([](user_op::SbpContext* ctx) -> Maybe<void> { ctx->NewBuilder().Split(ctx->inputs(), 0).Split(ctx->outputs(), 0).Build(); return Maybe<void>::Ok(); }); REGISTER_CPU_ONLY_USER_OP("coin_flip") .Output("out") .Attr<float>("probability", 0.5) .Attr<int64_t>("batch_size") .Attr<int64_t>("seed", -1) .Attr<bool>("has_seed", false) .SetLogicalTensorDescInferFn([](user_op::InferContext* ctx) -> Maybe<void> { user_op::TensorDesc* out_tensor = ctx->TensorDesc4ArgNameAndIndex("out", 0); int64_t batch_size = ctx->Attr<int64_t>("batch_size"); *out_tensor->mut_shape() = Shape({batch_size}); *out_tensor->mut_data_type() = DataType::kInt8; return Maybe<void>::Ok(); }) .SetPhysicalTensorDescInferFn([](user_op::InferContext* ctx) -> Maybe<void> { user_op::TensorDesc* out_tensor = ctx->TensorDesc4ArgNameAndIndex("out", 0); int64_t batch_size = ctx->Attr<int64_t>("batch_size"); const ParallelContext& parallel_ctx = ctx->parallel_ctx(); const SbpParallel& out_sbp = ctx->SbpParallel4ArgNameAndIndex("out", 0); if (parallel_ctx.parallel_num() > 1 && out_sbp.has_split_parallel()) { BalancedSplitter bs(batch_size, parallel_ctx.parallel_num()); *out_tensor->mut_shape() = Shape({bs.At(parallel_ctx.parallel_id()).size()}); } else { *out_tensor->mut_shape() = Shape({batch_size}); } *out_tensor->mut_data_type() = DataType::kInt8; return Maybe<void>::Ok(); }) .SetGetSbpFn([](user_op::SbpContext* ctx) -> Maybe<void> { ctx->NewBuilder().Split(user_op::OpArg("out", 0), 0).Build(); return Maybe<void>::Ok(); }); REGISTER_CPU_ONLY_USER_OP("image_random_crop") .Input("in") .Output("out") .Attr<int32_t>("num_attempts", 10) .Attr<int64_t>("seed", -1) .Attr<bool>("has_seed", false) .Attr<std::vector<float>>("random_area", {0.08, 1.0}) .Attr<std::vector<float>>("random_aspect_ratio", {0.75, 1.333333}) .SetTensorDescInferFn([](user_op::InferContext* ctx) -> Maybe<void> { user_op::TensorDesc* in_tensor = ctx->TensorDesc4ArgNameAndIndex("in", 0); user_op::TensorDesc* out_tensor = ctx->TensorDesc4ArgNameAndIndex("out", 0); CHECK_OR_RETURN(in_tensor->data_type() == DataType::kTensorBuffer); *out_tensor = *in_tensor; return Maybe<void>::Ok(); }) .SetGetSbpFn(user_op::GetSbpFnUtil::SplitForEachAxis) .SetInputArgModifyFn([](user_op::GetInputArgModifier GetInputArgModifierFn, const user_op::UserOpConfWrapper&) { user_op::InputArgModifier* in_modifier = GetInputArgModifierFn("in", 0); CHECK_NOTNULL(in_modifier); in_modifier->set_requires_grad(false); }); } // namespace oneflow
/* [auto_generated] boost/numeric/odeint/stepper/generation/make_dense_output.hpp [begin_description] Factory function to simplify the creation of dense output steppers from error steppers. [end_description] Copyright 2011-2012 Karsten Ahnert Copyright 2011-2012 Mario Mulansky Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_NUMERIC_ODEINT_STEPPER_GENERATION_MAKE_DENSE_OUTPUT_HPP_INCLUDED #define BOOST_NUMERIC_ODEINT_STEPPER_GENERATION_MAKE_DENSE_OUTPUT_HPP_INCLUDED namespace boost { namespace numeric { namespace odeint { // default template for the dense output template< class Stepper > struct get_dense_output { }; // default dense output factory template< class Stepper , class DenseOutput > struct dense_output_factory { DenseOutput operator()( typename Stepper::value_type abs_error , typename Stepper::value_type rel_error , const Stepper &stepper ) { return DenseOutput( abs_error , rel_error , stepper ); } DenseOutput operator()( typename Stepper::value_type abs_error , typename Stepper::value_type rel_error , typename Stepper::time_type max_dt , const Stepper &stepper ) { return DenseOutput( abs_error , rel_error , max_dt , stepper ); } }; namespace result_of { template< class Stepper > struct make_dense_output { typedef typename get_dense_output< Stepper >::type type; }; } template< class Stepper > typename result_of::make_dense_output< Stepper >::type make_dense_output( typename Stepper::value_type abs_error , typename Stepper::value_type rel_error , const Stepper &stepper = Stepper() ) { typedef Stepper stepper_type; typedef typename result_of::make_dense_output< stepper_type >::type dense_output_type; typedef dense_output_factory< stepper_type , dense_output_type > factory_type; factory_type factory; return factory( abs_error , rel_error , stepper ); } template< class Stepper > typename result_of::make_dense_output< Stepper >::type make_dense_output( typename Stepper::value_type abs_error , typename Stepper::value_type rel_error , typename Stepper::time_type max_dt , const Stepper &stepper = Stepper() ) { typedef Stepper stepper_type; typedef typename result_of::make_dense_output< stepper_type >::type dense_output_type; typedef dense_output_factory< stepper_type , dense_output_type > factory_type; factory_type factory; return factory( abs_error , rel_error , max_dt, stepper ); } } // odeint } // numeric } // boost #endif // BOOST_NUMERIC_ODEINT_STEPPER_GENERATION_MAKE_DENSE_OUTPUT_HPP_INCLUDED
// Copyright 2020 The Fuchsia Authors // // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT #include <lib/unittest/unittest.h> #include <string.h> #include <ktl/limits.h> #include <ktl/string_view.h> namespace { bool CreateFromCArray() { BEGIN_TEST; constexpr char kStr[] = "1"; ktl::string_view v_str(kStr); EXPECT_FALSE(v_str.empty()); EXPECT_EQ(kStr, v_str.data()); EXPECT_EQ(strlen(kStr), v_str.length()); END_TEST; } bool CreateFromConstChar() { BEGIN_TEST; const char* kStr = "1"; ktl::string_view v_str(kStr); EXPECT_FALSE(v_str.empty()); EXPECT_EQ(kStr, v_str.data()); EXPECT_EQ(strlen(kStr), v_str.length()); END_TEST; } bool CreateFromStringView() { BEGIN_TEST; ktl::string_view str_view("12345"); ktl::string_view v_str(str_view); EXPECT_FALSE(v_str.empty()); EXPECT_EQ(str_view.data(), v_str.data()); EXPECT_EQ(str_view.length(), v_str.length()); END_TEST; } bool CreateFromConstexprStringView() { BEGIN_TEST; constexpr ktl::string_view kLiteral = "12345"; ktl::string_view v_str(kLiteral); EXPECT_EQ(kLiteral.data(), v_str.data()); EXPECT_EQ(kLiteral.length(), v_str.length()); END_TEST; } bool CreateFromConstexprStringViewConstructor() { BEGIN_TEST; constexpr ktl::string_view kLiteral("12345"); EXPECT_EQ(size_t{5}, kLiteral.size()); EXPECT_EQ(size_t{5}, kLiteral.length()); END_TEST; } bool CreateFromStringViewLiteral() { BEGIN_TEST; constexpr ktl::string_view kLiteral = "12345"sv; EXPECT_EQ(size_t{5}, kLiteral.size()); EXPECT_EQ(size_t{5}, kLiteral.length()); END_TEST; } bool SizeIsSameAsLength() { BEGIN_TEST; constexpr ktl::string_view kLiteral = "12345"; EXPECT_EQ(size_t{5}, kLiteral.size()); EXPECT_EQ(size_t{5}, kLiteral.length()); END_TEST; } bool ArrayAccessOperator() { BEGIN_TEST; // Need static duration to enforce subobject constexpr, otherwise it is not allowed. constexpr static char const kLiteral[] = "12345"; constexpr ktl::string_view kSvLiteral(kLiteral); for (size_t i = 0; i < kSvLiteral.size(); ++i) { EXPECT_EQ(kLiteral[i], kSvLiteral[i], "Array access returned wrong value."); EXPECT_EQ(&kLiteral[i], &kSvLiteral[i], "Array access returned value at different address."); } END_TEST; } bool BeginPointsToFirstElement() { BEGIN_TEST; constexpr ktl::string_view kLiteral = "12345"; EXPECT_EQ(&kLiteral[0], &(*kLiteral.begin())); EXPECT_EQ(&kLiteral[4], &(*kLiteral.rbegin())); END_TEST; } bool EndPointsOnePastLastElement() { BEGIN_TEST; constexpr ktl::string_view kLiteral = "12345"; EXPECT_EQ(&kLiteral[4], &(*(kLiteral.end() - 1))); EXPECT_EQ(&kLiteral[0], &(*(kLiteral.rend() - 1))); END_TEST; } bool EndPointsPastLastElement() { BEGIN_TEST; constexpr ktl::string_view kLiteral = "12345"; EXPECT_EQ(kLiteral.begin() + 5, kLiteral.end()); EXPECT_TRUE(kLiteral.rbegin() + 5 == kLiteral.rend()); END_TEST; } bool WhenEmptyBeginIsSameAsEnd() { BEGIN_TEST; constexpr ktl::string_view kLiteral = ""; EXPECT_EQ(kLiteral.begin(), kLiteral.end()); EXPECT_TRUE(kLiteral.rbegin() == kLiteral.rend()); END_TEST; } bool FrontReturnsRefToFirstElement() { BEGIN_TEST; constexpr ktl::string_view kLiteral = "12345"; EXPECT_EQ(&(*kLiteral.begin()), &kLiteral.front()); END_TEST; } bool BackReturnsRefToLastElement() { BEGIN_TEST; constexpr ktl::string_view kLiteral = "12345"; EXPECT_EQ(&(*(kLiteral.begin() + 4)), &kLiteral.back()); END_TEST; } bool EmptyIsTrueForEmptyString() { BEGIN_TEST; constexpr ktl::string_view kStr; ASSERT_TRUE(kStr.empty()); ASSERT_EQ(size_t{0}, kStr.size()); ASSERT_EQ(size_t{0}, kStr.length()); END_TEST; } bool AtReturnsElementAtIndex() { BEGIN_TEST; // Need static duration to enforce subobject constexpr, otherwise it is not allowed. constexpr static char const kLiteral[] = "12345"; constexpr ktl::string_view kSvLiteral(kLiteral); for (size_t i = 0; i < kSvLiteral.size(); ++i) { EXPECT_EQ(kLiteral[i], kSvLiteral.at(i), "Array access returned wrong value."); EXPECT_EQ(&kLiteral[i], &kSvLiteral.at(i), "Array access returned value at different address."); } END_TEST; } #if DEATH_TESTS bool AtThrowsExceptionWhenIndexIsOOR() { BEGIN_TEST; ASSERT_DEATH([] { constexpr ktl::string_view kSvLiteral("12345"); kSvLiteral.at(5); }); END_TEST; } #endif // Even though we use a custom compare implementation, because we lack a constexpr compare // function, we use this test to verify that the expectations are equivalent. bool CompareVerification() { BEGIN_TEST; constexpr ktl::string_view kStr1 = "1234"; // Same string { constexpr ktl::string_view kStr2 = "1234"; constexpr ktl::string_view kStr3 = "01234"; EXPECT_EQ(0, ktl::string_view::traits_type::compare(kStr1.data(), kStr2.data(), 4)); EXPECT_EQ(0, kStr1.compare(kStr2)); EXPECT_EQ(0, kStr3.compare(1, kStr3.length() - 1, kStr2)); EXPECT_EQ(0, kStr1.compare(1, kStr1.length() - 2, kStr2, 1, kStr2.length() - 2)); EXPECT_EQ(0, kStr1.compare("1234")); EXPECT_EQ(0, kStr1.compare(1, kStr1.length() - 1, "234")); EXPECT_EQ(0, kStr1.compare(2, kStr1.length() - 2, "234", 1, 2)); } // Same Length higher character { constexpr ktl::string_view kStr2 = "1235"; EXPECT_LT(ktl::string_view::traits_type::compare(kStr1.data(), kStr2.data(), 4), 0); EXPECT_LT(kStr1.compare(kStr2), 0); EXPECT_LT(kStr1.compare(0, kStr1.length(), kStr2), 0); EXPECT_LT(kStr1.compare(1, kStr1.length() - 2, kStr2, 1, kStr2.length() - 1), 0); EXPECT_LT(kStr1.compare("1235"), 0); EXPECT_LT(kStr1.compare(1, kStr1.length() - 1, "235"), 0); EXPECT_LT(kStr1.compare(1, kStr1.length() - 2, "1235", 1, 3), 0); } // Same Length lower character { constexpr ktl::string_view kStr2 = "1232"; EXPECT_GT(ktl::string_view::traits_type::compare(kStr1.data(), kStr2.data(), 4), 0); EXPECT_GT(kStr1.compare(kStr2), 0); EXPECT_GT(kStr2.compare(1, kStr2.length() - 1, kStr1), 0); EXPECT_GT(kStr1.compare(1, kStr1.length() - 1, kStr2, 1, kStr2.length() - 1), 0); EXPECT_GT(kStr1.compare("1232"), 0); EXPECT_GT(kStr1.compare(1, kStr1.length() - 1, "232"), 0); EXPECT_GT(kStr1.compare(1, kStr1.length() - 2, "22", 1, kStr2.length() - 2), 0); } // Greater Length { constexpr ktl::string_view kStr2 = "12345"; constexpr ktl::string_view kStr3 = "2345"; EXPECT_LT(kStr1.compare(kStr2), 0); EXPECT_LT(kStr1.compare(1, kStr1.length() - 1, kStr3), 0); EXPECT_LT(kStr1.compare(1, kStr1.length() - 1, kStr2, 1, kStr2.length() - 1), 0); EXPECT_LT(kStr1.compare(kStr2.data()), 0); EXPECT_LT(kStr1.compare(1, kStr1.length() - 1, kStr3.data()), 0); EXPECT_LT(kStr1.compare(1, kStr1.length() - 1, kStr2.data(), 1, kStr2.length() - 1), 0); } // Shorter Length { constexpr ktl::string_view kStr2 = "123"; constexpr ktl::string_view kStr3 = "23"; EXPECT_GT(kStr1.compare(kStr2), 0); EXPECT_GT(kStr1.compare(1, kStr1.length() - 1, kStr3), 0); EXPECT_GT(kStr1.compare(1, kStr1.length() - 1, kStr2, 1, kStr2.length() - 1), 0); EXPECT_GT(kStr1.compare(kStr2.data()), 0); EXPECT_GT(kStr1.compare(1, kStr1.length() - 1, kStr3.data()), 0); EXPECT_GT(kStr1.compare(1, kStr1.length() - 1, kStr2.data(), 1, kStr2.length() - 1), 0); } END_TEST; } // Check that they calls are equivalent to what the standard expects. bool CompareOverloadCheck() { BEGIN_TEST; constexpr ktl::string_view kString1 = "123"; constexpr ktl::string_view kString2 = "1234"; { ktl::string_view expected = kString1.substr(1, 2); EXPECT_EQ(kString1.substr(1, 2).compare(expected), kString1.compare(1, 2, expected)); } { EXPECT_EQ(kString1.substr(1, 2).compare(kString2.substr(1, 2)), kString1.compare(1, 2, kString2, 1, 2)); } { EXPECT_EQ(kString1.compare(ktl::string_view("123")), kString1.compare("123")); } { EXPECT_EQ(kString1.substr(1, 2).compare(ktl::string_view("123")), kString1.compare(1, 2, "123")); } { EXPECT_EQ(kString1.substr(1, 2).compare(ktl::string_view("123")), kString1.compare(1, 2, "123")); } END_TEST; } bool OperatorEq() { BEGIN_TEST; constexpr ktl::string_view kStrView = "Self1234"; EXPECT_TRUE(kStrView == kStrView); EXPECT_TRUE(kStrView == ktl::string_view("Self1234")); EXPECT_TRUE(kStrView == ktl::string_view("Self12345").substr(0, kStrView.length())); EXPECT_TRUE(kStrView == "Self1234"); EXPECT_TRUE("Self1234" == kStrView); END_TEST; } bool OperatorNe() { BEGIN_TEST; constexpr ktl::string_view kStrView = "Self1234"; EXPECT_TRUE(kStrView != ktl::string_view()); EXPECT_TRUE(kStrView != ktl::string_view("Self12345")); EXPECT_TRUE(kStrView != "Self12345"); EXPECT_TRUE("Self12345" != kStrView); END_TEST; } bool OperatorLess() { BEGIN_TEST; constexpr ktl::string_view kStrView = "Self1234"; EXPECT_TRUE(kStrView < "Self12345"); EXPECT_TRUE("Self123" < kStrView); EXPECT_TRUE(kStrView < ktl::string_view("Self12345")); END_TEST; } bool OperatorLessOrEq() { BEGIN_TEST; constexpr ktl::string_view kStrView = "Self1234"; EXPECT_TRUE(kStrView <= "Self12345"); EXPECT_TRUE("Self123" <= kStrView); EXPECT_TRUE(kStrView <= ktl::string_view("Self12345")); EXPECT_TRUE(kStrView <= ktl::string_view("Self1234")); END_TEST; } bool OperatorGreater() { BEGIN_TEST; constexpr ktl::string_view kStrView = "Self1234"; EXPECT_TRUE(kStrView > "Self123"); EXPECT_TRUE("Self12345" > kStrView); EXPECT_TRUE(kStrView > ktl::string_view("Self123")); END_TEST; } bool OperatorGreaterOrEq() { BEGIN_TEST; constexpr ktl::string_view kStrView = "Self1234"; EXPECT_TRUE(kStrView >= "Self123"); EXPECT_TRUE("Self12345" >= kStrView); EXPECT_TRUE(kStrView >= ktl::string_view("Self123")); EXPECT_TRUE(kStrView >= ktl::string_view("Self1234")); END_TEST; } bool RemovePrefix() { BEGIN_TEST; constexpr ktl::string_view kPrefixWithSuffix = "PrefixSuffix"; ktl::string_view str_view = kPrefixWithSuffix; str_view.remove_prefix(6); EXPECT_EQ(kPrefixWithSuffix.length() - 6, str_view.length()); auto no_suffix = kPrefixWithSuffix.substr(6, kPrefixWithSuffix.length() - 6); EXPECT_TRUE(no_suffix == str_view); EXPECT_TRUE("Suffix" == str_view); END_TEST; } bool RemoveSuffix() { BEGIN_TEST; constexpr ktl::string_view kPrefixWithSuffix = "PrefixSuffix"; ktl::string_view str_view = kPrefixWithSuffix; str_view.remove_suffix(6); EXPECT_EQ(kPrefixWithSuffix.length() - 6, str_view.length()); auto no_suffix = kPrefixWithSuffix.substr(0, kPrefixWithSuffix.length() - 6); EXPECT_TRUE(no_suffix == str_view); EXPECT_TRUE("Prefix" == str_view); END_TEST; } bool SubstrNoArgsAreEqual() { BEGIN_TEST; constexpr ktl::string_view kLiteral = "12345"; EXPECT_TRUE(kLiteral == kLiteral.substr()); END_TEST; } bool SubstrWithPosIsMatchesSubstring() { BEGIN_TEST; constexpr ktl::string_view kLiteral = "12345"; constexpr ktl::string_view kExpectedLiteral = "345"; EXPECT_TRUE(kExpectedLiteral == kLiteral.substr(2)); END_TEST; } bool SubstrWithPosAndCountIsMatchesSubstring() { BEGIN_TEST; constexpr ktl::string_view kLiteral = "12345"; constexpr ktl::string_view kExpectedLiteral = "34"; EXPECT_TRUE(kExpectedLiteral == kLiteral.substr(2, 2)); END_TEST; } bool Swap() { BEGIN_TEST; ktl::string_view str_1 = "12345"; ktl::string_view str_2 = "34"; str_1.swap(str_2); EXPECT_TRUE("34" == str_1); EXPECT_TRUE("12345" == str_2); END_TEST; } bool Copy() { BEGIN_TEST; constexpr ktl::string_view kBase = "Base"; constexpr ktl::string_view::size_type kSize = 2; ktl::string_view::value_type dest[kSize + 1] = {'\0'}; ktl::string_view::value_type dest_traits[kSize + 1] = {'\0'}; EXPECT_EQ(kSize, kBase.copy(dest, kSize, 0)); EXPECT_EQ(dest_traits, ktl::string_view::traits_type::copy(dest_traits, kBase.data(), kSize)); EXPECT_EQ(0, strcmp(dest_traits, dest)); END_TEST; } #if DEATH_TESTS bool CopyThrowsExceptionOnOOR() { BEGIN_TEST; ASSERT_DEATH([]() { constexpr ktl::string_view v_str = "Base"; ktl::string_view::value_type dest[v_str.length() + 2] = {}; memset(dest, '\0', v_str.length() + 1); v_str.copy(dest, v_str.length(), v_str.length()); }); END_TEST; } #endif bool MaxSizeIsMaxAddressableSize() { BEGIN_TEST; ktl::string_view str_view("12345"); EXPECT_EQ(ktl::numeric_limits<ktl::string_view::size_type>::max(), str_view.max_size()); END_TEST; } bool FindReturnsFirstCharTypeMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "12345678901234567890"; EXPECT_EQ(size_t{0}, kString.find('1')); EXPECT_EQ(size_t{1}, kString.find('2')); EXPECT_EQ(size_t{2}, kString.find('3')); EXPECT_EQ(size_t{3}, kString.find('4')); EXPECT_EQ(size_t{4}, kString.find('5')); EXPECT_EQ(size_t{5}, kString.find('6')); EXPECT_EQ(size_t{6}, kString.find('7')); EXPECT_EQ(size_t{7}, kString.find('8')); EXPECT_EQ(size_t{8}, kString.find('9')); EXPECT_EQ(size_t{9}, kString.find('0')); END_TEST; } bool FindWithPosReturnsFirstCharTypeMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "12345678901234567890"; EXPECT_EQ(size_t{10}, kString.find('1', 10)); EXPECT_EQ(size_t{11}, kString.find('2', 10)); EXPECT_EQ(size_t{12}, kString.find('3', 10)); EXPECT_EQ(size_t{13}, kString.find('4', 10)); EXPECT_EQ(size_t{14}, kString.find('5', 10)); EXPECT_EQ(size_t{15}, kString.find('6', 10)); EXPECT_EQ(size_t{16}, kString.find('7', 10)); EXPECT_EQ(size_t{17}, kString.find('8', 10)); EXPECT_EQ(size_t{18}, kString.find('9', 10)); EXPECT_EQ(size_t{19}, kString.find('0', 10)); END_TEST; } bool FindReturnsNposWhenNoCharTypeMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "123456789123456789"; EXPECT_EQ(ktl::string_view::npos, kString.find('0')); END_TEST; } bool FindReturnsFirstMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "12345678901234567890"; EXPECT_EQ(size_t{0}, kString.find("")); EXPECT_EQ(size_t{0}, kString.find("12")); EXPECT_EQ(size_t{1}, kString.find("23")); EXPECT_EQ(size_t{2}, kString.find("34")); EXPECT_EQ(size_t{3}, kString.find("45")); EXPECT_EQ(size_t{4}, kString.find("56")); EXPECT_EQ(size_t{5}, kString.find("67")); EXPECT_EQ(size_t{6}, kString.find("78")); EXPECT_EQ(size_t{7}, kString.find("89")); EXPECT_EQ(size_t{8}, kString.find("90")); EXPECT_EQ(size_t{9}, kString.find("01")); EXPECT_EQ(size_t{9}, kString.find("01234")); END_TEST; } bool FindWithPosReturnsFirstMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "12345678901234567890"; EXPECT_EQ(size_t{10}, kString.find("", 10)); EXPECT_EQ(size_t{10}, kString.find("1", 10)); EXPECT_EQ(size_t{11}, kString.find("2", 10)); EXPECT_EQ(size_t{12}, kString.find("3", 10)); EXPECT_EQ(size_t{13}, kString.find("4", 10)); EXPECT_EQ(size_t{14}, kString.find("5", 10)); EXPECT_EQ(size_t{15}, kString.find("6", 10)); EXPECT_EQ(size_t{16}, kString.find("7", 10)); EXPECT_EQ(size_t{17}, kString.find("8", 10)); EXPECT_EQ(size_t{18}, kString.find("9", 10)); EXPECT_EQ(size_t{19}, kString.find("0", 10)); // String of size > 1. EXPECT_EQ(size_t{13}, kString.find("456", 10)); END_TEST; } bool FindReturnsNposWhenNoMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "12345678901234567890"; // String of size > 1. EXPECT_EQ(ktl::string_view::npos, kString.find("A")); EXPECT_EQ(ktl::string_view::npos, kString.find("02")); EXPECT_EQ(ktl::string_view::npos, kString.find("42321")); END_TEST; } bool FindReturnsNposWhenNeedleIsBiggerThanHaystack() { BEGIN_TEST; constexpr ktl::string_view kString = "123"; // String of size > 1. EXPECT_EQ(ktl::string_view::npos, kString.find("1234")); END_TEST; } bool RrfindReturnsFirstCharTypeMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "12345678901234567890"; EXPECT_EQ(size_t{10}, kString.rfind('1')); EXPECT_EQ(size_t{11}, kString.rfind('2')); EXPECT_EQ(size_t{12}, kString.rfind('3')); EXPECT_EQ(size_t{13}, kString.rfind('4')); EXPECT_EQ(size_t{14}, kString.rfind('5')); EXPECT_EQ(size_t{15}, kString.rfind('6')); EXPECT_EQ(size_t{16}, kString.rfind('7')); EXPECT_EQ(size_t{17}, kString.rfind('8')); EXPECT_EQ(size_t{18}, kString.rfind('9')); EXPECT_EQ(size_t{19}, kString.rfind('0')); END_TEST; } bool RrfindWithPosReturnsFirstCharTypeMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "12345678901234567890"; EXPECT_EQ(size_t{10}, kString.rfind('1', 10)); EXPECT_EQ(size_t{11}, kString.rfind('2', 11)); EXPECT_EQ(size_t{12}, kString.rfind('3', 12)); EXPECT_EQ(size_t{13}, kString.rfind('4', 13)); EXPECT_EQ(size_t{14}, kString.rfind('5', 14)); EXPECT_EQ(size_t{15}, kString.rfind('6', 15)); EXPECT_EQ(size_t{16}, kString.rfind('7', 16)); EXPECT_EQ(size_t{17}, kString.rfind('8', 17)); EXPECT_EQ(size_t{18}, kString.rfind('9', 18)); EXPECT_EQ(size_t{19}, kString.rfind('0', 19)); END_TEST; } bool RrfindReturnsNposWhenNoCharTypeMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "123456789123456789"; EXPECT_EQ(ktl::string_view::npos, kString.rfind('0')); END_TEST; } bool RrfindReturnsFirstMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "12345678901234567890"; EXPECT_EQ(size_t{10}, kString.rfind("12")); EXPECT_EQ(size_t{11}, kString.rfind("23")); EXPECT_EQ(size_t{12}, kString.rfind("34")); EXPECT_EQ(size_t{13}, kString.rfind("45")); EXPECT_EQ(size_t{14}, kString.rfind("56")); EXPECT_EQ(size_t{15}, kString.rfind("67")); EXPECT_EQ(size_t{16}, kString.rfind("78")); EXPECT_EQ(size_t{17}, kString.rfind("89")); EXPECT_EQ(size_t{18}, kString.rfind("90")); EXPECT_EQ(size_t{9}, kString.rfind("01")); EXPECT_EQ(size_t{9}, kString.rfind("01234")); END_TEST; } bool RrfindWithPosReturnsFirstMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "12345678901234567890"; EXPECT_EQ(size_t{10}, kString.rfind("1", 10)); EXPECT_EQ(size_t{11}, kString.rfind("2", 11)); EXPECT_EQ(size_t{12}, kString.rfind("3", 12)); EXPECT_EQ(size_t{13}, kString.rfind("4", 13)); EXPECT_EQ(size_t{14}, kString.rfind("5", 14)); EXPECT_EQ(size_t{15}, kString.rfind("6", 15)); EXPECT_EQ(size_t{16}, kString.rfind("7", 16)); EXPECT_EQ(size_t{17}, kString.rfind("8", 17)); EXPECT_EQ(size_t{18}, kString.rfind("9", 18)); EXPECT_EQ(size_t{19}, kString.rfind("0", 19)); // String of size > 1. EXPECT_EQ(size_t{13}, kString.rfind("456", 13)); END_TEST; } bool RrfindReturnsNposWhenNoMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "12345678901234567890"; EXPECT_EQ(ktl::string_view::npos, kString.rfind("A")); EXPECT_EQ(ktl::string_view::npos, kString.rfind("02")); EXPECT_EQ(ktl::string_view::npos, kString.rfind("42321")); EXPECT_EQ(ktl::string_view::npos, kString.rfind('A')); END_TEST; } bool RfindReturnsNposWhenNeedleIsBiggerThanHaystack() { BEGIN_TEST; constexpr ktl::string_view kString = "123"; // String of size > 1. EXPECT_EQ(ktl::string_view::npos, kString.rfind("1234")); EXPECT_EQ(ktl::string_view::npos, ktl::string_view().find('1')); END_TEST; } bool FindFirstOfReturnsFirstMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "ABCDE1234ABCDE1234"; constexpr ktl::string_view kMatchers = "123"; // Verify that order of chartacters in |s| does not change first match. EXPECT_EQ(size_t{5}, kString.find_first_of("321")); EXPECT_EQ(size_t{5}, kString.find_first_of("123")); EXPECT_EQ(size_t{5}, kString.find_first_of("231")); EXPECT_EQ(size_t{5}, kString.find_first_of("213")); EXPECT_EQ(size_t{5}, kString.find_first_of(kMatchers)); EXPECT_EQ(size_t{6}, kString.find_first_of('2')); END_TEST; } bool FindFirstOfWithPosReturnsFirstMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "ABCDE1234ABCDE1234"; constexpr ktl::string_view kMatchers = "123"; // Verify that order of chartacters in |s| does not change first match. EXPECT_EQ(size_t{14}, kString.find_first_of("321", 9)); EXPECT_EQ(size_t{14}, kString.find_first_of("123", 9)); EXPECT_EQ(size_t{14}, kString.find_first_of("231", 9)); EXPECT_EQ(size_t{14}, kString.find_first_of("213", 9)); EXPECT_EQ(size_t{14}, kString.find_first_of(kMatchers, 9)); EXPECT_EQ(size_t{5}, kString.find_first_of('1')); END_TEST; } bool FindFirstOfWithPosAndCountReturnsFirstMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "ABCDE1234ABCDE1234"; // Verify that order of chartacters in |s| does not change first match. EXPECT_EQ(size_t{14}, kString.find_first_of("123", 9, 1)); EXPECT_EQ(size_t{15}, kString.find_first_of("231", 9, 1)); EXPECT_EQ(size_t{15}, kString.find_first_of("213", 9, 1)); EXPECT_EQ(size_t{16}, kString.find_first_of("321", 9, 1)); END_TEST; } bool FindFirstOfReturnsNposWhenNoMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "ABCDE1234ABCDE1234"; // Verify that order of chartacters in |s| does not change first match. EXPECT_EQ(ktl::string_view::npos, kString.find_first_of("GHIJK")); EXPECT_EQ(ktl::string_view::npos, kString.find_first_of("G")); EXPECT_EQ(ktl::string_view::npos, kString.find_first_of('G')); END_TEST; } bool FindLastOfReturnsLastMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "ABCDE1234ABCDE1234"; constexpr ktl::string_view kMatchers = "123"; // Verify that order of chartacters in |s| does not change last match. EXPECT_EQ(size_t{16}, kString.find_last_of("321")); EXPECT_EQ(size_t{16}, kString.find_last_of("123")); EXPECT_EQ(size_t{16}, kString.find_last_of("231")); EXPECT_EQ(size_t{16}, kString.find_last_of("213")); EXPECT_EQ(size_t{16}, kString.find_last_of(kMatchers)); EXPECT_EQ(size_t{15}, kString.find_last_of('2')); END_TEST; } bool FindLastOfWithPosReturnsLastMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "ABCDE1234ABCDE1234"; constexpr ktl::string_view kMatchers = "123"; // Verify that order of chartacters in |s| does not change last match. EXPECT_EQ(size_t{7}, kString.find_last_of("321", 9)); EXPECT_EQ(size_t{7}, kString.find_last_of("123", 9)); EXPECT_EQ(size_t{7}, kString.find_last_of("231", 9)); EXPECT_EQ(size_t{7}, kString.find_last_of("213", 9)); EXPECT_EQ(size_t{7}, kString.find_last_of(kMatchers, 9)); EXPECT_EQ(size_t{5}, kString.find_last_of('1', 9)); END_TEST; } bool FindLastOfWithPosAndCountReturnsLastMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "ABCDE1234ABCDE1234"; // Verify that order of chartacters in |s| does not change last match. EXPECT_EQ(size_t{5}, kString.find_last_of("123", 9, 1)); EXPECT_EQ(size_t{6}, kString.find_last_of("231", 9, 1)); EXPECT_EQ(size_t{6}, kString.find_last_of("213", 9, 1)); EXPECT_EQ(size_t{7}, kString.find_last_of("321", 9, 1)); END_TEST; } bool FindLastOfReturnsNposWhenNoMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "ABCDE1234ABCDE1234"; // Verify that order of chartacters in |s| does not change last match. EXPECT_EQ(ktl::string_view::npos, kString.find_last_of("GHIJK")); EXPECT_EQ(ktl::string_view::npos, kString.find_last_of("G")); EXPECT_EQ(ktl::string_view::npos, kString.find_last_of('G')); END_TEST; } bool FindFirstNofOfReturnsFirstNonMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "123ABC123"; constexpr ktl::string_view kMatchers = "123"; // Verify that order of chartacters in |s| does not change first match. EXPECT_EQ(size_t{0}, kString.find_first_not_of("")); EXPECT_EQ(size_t{3}, kString.find_first_not_of("321")); EXPECT_EQ(size_t{3}, kString.find_first_not_of("123")); EXPECT_EQ(size_t{3}, kString.find_first_not_of("231")); EXPECT_EQ(size_t{3}, kString.find_first_not_of("213")); EXPECT_EQ(size_t{3}, kString.find_first_not_of(kMatchers)); EXPECT_EQ(size_t{1}, kString.find_first_not_of('1')); END_TEST; } bool FindFirstNofOfWithPosReturnsFirstNonMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "123ABC123A"; constexpr ktl::string_view kMatchers = "123"; // Verify that order of chartacters in |s| does not change first match. EXPECT_EQ(size_t{6}, kString.find_first_not_of("", 6)); EXPECT_EQ(size_t{9}, kString.find_first_not_of("321", 6)); EXPECT_EQ(size_t{9}, kString.find_first_not_of("123", 6)); EXPECT_EQ(size_t{9}, kString.find_first_not_of("231", 6)); EXPECT_EQ(size_t{9}, kString.find_first_not_of("213", 6)); EXPECT_EQ(size_t{9}, kString.find_first_not_of(kMatchers, 9)); EXPECT_EQ(size_t{7}, kString.find_first_not_of('1', 6)); END_TEST; } bool FindFirstNofOfWithPosAndCountReturnsFirstNofMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "123ABC123A"; // Verify that order of chartacters in |s| does not change first match. EXPECT_EQ(size_t{7}, kString.find_first_not_of("123", 6, 1)); EXPECT_EQ(size_t{6}, kString.find_first_not_of("231", 6, 1)); EXPECT_EQ(size_t{6}, kString.find_first_not_of("213", 6, 1)); EXPECT_EQ(size_t{6}, kString.find_first_not_of("321", 6, 1)); END_TEST; } bool FindFirstNofOfReturnsNposWhenNoMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "GGGGGGGGGGGGG"; // Verify that order of chartacters in |s| does not change first match. EXPECT_EQ(ktl::string_view::npos, kString.find_first_not_of("ABCG")); EXPECT_EQ(ktl::string_view::npos, kString.find_first_not_of("G")); EXPECT_EQ(ktl::string_view::npos, kString.find_first_not_of('G')); END_TEST; } bool FindLastNotOfReturnsLastMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "ABCDE1234ABCDE1234"; constexpr ktl::string_view kMatchers = "1234"; // Verify that order of chartacters in |s| does not change last_not match. EXPECT_EQ(size_t{13}, kString.find_last_not_of("3214")); EXPECT_EQ(size_t{13}, kString.find_last_not_of("1234")); EXPECT_EQ(size_t{13}, kString.find_last_not_of("2314")); EXPECT_EQ(size_t{13}, kString.find_last_not_of("2134")); EXPECT_EQ(size_t{13}, kString.find_last_not_of(kMatchers)); EXPECT_EQ(size_t{16}, kString.find_last_not_of('4')); END_TEST; } bool FindLastNotOfWithPosReturnsLastMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "ABCDE1234ABCDE1234"; constexpr ktl::string_view kMatchers = "1234"; // Verify that order of chartacters in |s| does not change last_not match. EXPECT_EQ(size_t{4}, kString.find_last_not_of("3214", 8)); EXPECT_EQ(size_t{4}, kString.find_last_not_of("1234", 8)); EXPECT_EQ(size_t{4}, kString.find_last_not_of("2314", 8)); EXPECT_EQ(size_t{4}, kString.find_last_not_of("2134", 8)); EXPECT_EQ(size_t{4}, kString.find_last_not_of(kMatchers, 8)); EXPECT_EQ(size_t{7}, kString.find_last_not_of('4', 8)); END_TEST; } bool FindLastNotOfWithPosAndCountReturnsLastMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "ABCDE1234ABCDE1234"; // Verify that order of chartacters in |s| does not change last_not match. EXPECT_EQ(size_t{8}, kString.find_last_not_of("1234", 8, 1)); EXPECT_EQ(size_t{8}, kString.find_last_not_of("2314", 8, 2)); EXPECT_EQ(size_t{5}, kString.find_last_not_of("4321", 8, 3)); EXPECT_EQ(size_t{4}, kString.find_last_not_of("3214", 8, 4)); END_TEST; } bool FindLastNotOfReturnsNposWhenNoMatch() { BEGIN_TEST; constexpr ktl::string_view kString = "GGGGGGG"; // Verify that order of chartacters in |s| does not change last_not match. EXPECT_EQ(ktl::string_view::npos, kString.find_last_not_of("GHIJK")); EXPECT_EQ(ktl::string_view::npos, kString.find_last_not_of("G")); EXPECT_EQ(ktl::string_view::npos, kString.find_last_not_of('G')); END_TEST; } bool StartsWith() { BEGIN_TEST; constexpr ktl::string_view kString = "foobar"; // string_view argument. EXPECT_TRUE(ktl::starts_with(kString, "foo"sv)); EXPECT_FALSE(ktl::starts_with(kString, "bar"sv)); // char argument. EXPECT_TRUE(ktl::starts_with(kString, 'f')); EXPECT_FALSE(ktl::starts_with(kString, 'b')); // C string (const char*) argument. EXPECT_TRUE(ktl::starts_with(kString, "foo")); EXPECT_FALSE(ktl::starts_with(kString, "bar")); END_TEST; } bool EndsWith() { BEGIN_TEST; constexpr ktl::string_view kString = "foobar"; // string_view argument. EXPECT_TRUE(ktl::ends_with(kString, "bar"sv)); EXPECT_FALSE(ktl::ends_with(kString, "foo"sv)); // char argument. EXPECT_TRUE(ktl::ends_with(kString, 'r')); EXPECT_FALSE(ktl::ends_with(kString, 'f')); // C string (const char*) argument. EXPECT_TRUE(ktl::ends_with(kString, "bar")); EXPECT_FALSE(ktl::ends_with(kString, "foo")); END_TEST; } } // namespace UNITTEST_START_TESTCASE(string_view_tests) UNITTEST("CreateFromCArray", CreateFromCArray) UNITTEST("CreateFromConstChar", CreateFromConstChar) UNITTEST("CreateFromStringView", CreateFromStringView) UNITTEST("CreateFromConstexprStringView", CreateFromConstexprStringView) UNITTEST("CreateFromConstexprStringViewConstructor", CreateFromConstexprStringViewConstructor) UNITTEST("CreateFromStringViewLiteral", CreateFromStringViewLiteral) UNITTEST("SizeIsSameAsLength", SizeIsSameAsLength) UNITTEST("ArrayAccessOperator", ArrayAccessOperator) UNITTEST("BeginPointsToFirstElement", BeginPointsToFirstElement) UNITTEST("EndPointsOnePastLastElement", EndPointsOnePastLastElement) UNITTEST("EndPointsPastLastElement", EndPointsPastLastElement) UNITTEST("WhenEmptyBeginIsSameAsEnd", WhenEmptyBeginIsSameAsEnd) UNITTEST("FrontReturnsRefToFirstElement", FrontReturnsRefToFirstElement) UNITTEST("BackReturnsRefToLastElement", BackReturnsRefToLastElement) UNITTEST("EmptyIsTrueForEmptyString", EmptyIsTrueForEmptyString) UNITTEST("AtReturnsElementAtIndex", AtReturnsElementAtIndex) UNITTEST("CompareVerification", CompareVerification) UNITTEST("CompareOverloadCheck", CompareOverloadCheck) UNITTEST("OperatorEq", OperatorEq) UNITTEST("OperatorNe", OperatorNe) UNITTEST("OperatorLess", OperatorLess) UNITTEST("OperatorLessOrEq", OperatorLessOrEq) UNITTEST("OperatorGreater", OperatorGreater) UNITTEST("OperatorGreaterOrEq", OperatorGreaterOrEq) UNITTEST("RemovePrefix", RemovePrefix) UNITTEST("RemoveSuffix", RemoveSuffix) UNITTEST("SubstrNoArgsAreEqual", SubstrNoArgsAreEqual) UNITTEST("SubstrWithPosIsMatchesSubstring", SubstrWithPosIsMatchesSubstring) UNITTEST("SubstrWithPosAndCountIsMatchesSubstring", SubstrWithPosAndCountIsMatchesSubstring) UNITTEST("Swap", Swap) UNITTEST("Copy", Copy) UNITTEST("MaxSizeIsMaxAddressableSize", MaxSizeIsMaxAddressableSize) UNITTEST("FindReturnsFirstCharTypeMatch", FindReturnsFirstCharTypeMatch) UNITTEST("FindWithPosReturnsFirstCharTypeMatch", FindWithPosReturnsFirstCharTypeMatch) UNITTEST("FindReturnsNposWhenNoCharTypeMatch", FindReturnsNposWhenNoCharTypeMatch) UNITTEST("FindReturnsFirstMatch", FindReturnsFirstMatch) UNITTEST("FindWithPosReturnsFirstMatch", FindWithPosReturnsFirstMatch) UNITTEST("FindReturnsNposWhenNoMatch", FindReturnsNposWhenNoMatch) UNITTEST("FindReturnsNposWhenNeedleIsBiggerThanHaystack", FindReturnsNposWhenNeedleIsBiggerThanHaystack) UNITTEST("RrfindReturnsFirstCharTypeMatch", RrfindReturnsFirstCharTypeMatch) UNITTEST("RrfindWithPosReturnsFirstCharTypeMatch", RrfindWithPosReturnsFirstCharTypeMatch) UNITTEST("RrfindReturnsNposWhenNoCharTypeMatch", RrfindReturnsNposWhenNoCharTypeMatch) UNITTEST("RrfindReturnsFirstMatch", RrfindReturnsFirstMatch) UNITTEST("RrfindWithPosReturnsFirstMatch", RrfindWithPosReturnsFirstMatch) UNITTEST("RrfindReturnsNposWhenNoMatch", RrfindReturnsNposWhenNoMatch) UNITTEST("RfindReturnsNposWhenNeedleIsBiggerThanHaystack", RfindReturnsNposWhenNeedleIsBiggerThanHaystack) UNITTEST("FindFirstOfReturnsFirstMatch", FindFirstOfReturnsFirstMatch) UNITTEST("FindFirstOfWithPosReturnsFirstMatch", FindFirstOfWithPosReturnsFirstMatch) UNITTEST("FindFirstOfWithPosAndCountReturnsFirstMatch", FindFirstOfWithPosAndCountReturnsFirstMatch) UNITTEST("FindFirstOfReturnsNposWhenNoMatch", FindFirstOfReturnsNposWhenNoMatch) UNITTEST("FindLastOfReturnsLastMatch", FindLastOfReturnsLastMatch) UNITTEST("FindLastOfWithPosReturnsLastMatch", FindLastOfWithPosReturnsLastMatch) UNITTEST("FindLastOfWithPosAndCountReturnsLastMatch", FindLastOfWithPosAndCountReturnsLastMatch) UNITTEST("FindLastOfReturnsNposWhenNoMatch", FindLastOfReturnsNposWhenNoMatch) UNITTEST("FindFirstNofOfReturnsFirstNonMatch", FindFirstNofOfReturnsFirstNonMatch) UNITTEST("FindFirstNofOfWithPosReturnsFirstNonMatch", FindFirstNofOfWithPosReturnsFirstNonMatch) UNITTEST("FindFirstNofOfWithPosAndCountReturnsFirstNofMatch", FindFirstNofOfWithPosAndCountReturnsFirstNofMatch) UNITTEST("FindFirstNofOfReturnsNposWhenNoMatch", FindFirstNofOfReturnsNposWhenNoMatch) UNITTEST("FindLastNotOfReturnsLastMatch", FindLastNotOfReturnsLastMatch) UNITTEST("FindLastNotOfWithPosReturnsLastMatch", FindLastNotOfWithPosReturnsLastMatch) UNITTEST("FindLastNotOfWithPosAndCountReturnsLastMatch", FindLastNotOfWithPosAndCountReturnsLastMatch) UNITTEST("FindLastNotOfReturnsNposWhenNoMatch", FindLastNotOfReturnsNposWhenNoMatch) UNITTEST("StartsWith", StartsWith) UNITTEST("EndsWith", EndsWith) UNITTEST_END_TESTCASE(string_view_tests, "string_view", "ktl::string_view tests")
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r14 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_WC_ht+0x8c45, %rsi lea addresses_A_ht+0x1ef7, %rdi and %rbx, %rbx mov $21, %rcx rep movsl nop nop nop sub %rbx, %rbx lea addresses_D_ht+0x194ec, %rsi lea addresses_normal_ht+0x174d, %rdi nop nop nop nop nop inc %rbp mov $56, %rcx rep movsb dec %rdi lea addresses_A_ht+0x17e8d, %rsi lea addresses_UC_ht+0x17ad5, %rdi nop nop nop nop nop cmp %r14, %r14 mov $64, %rcx rep movsl nop cmp $61885, %rsi lea addresses_normal_ht+0x6585, %rbp dec %r14 mov (%rbp), %di nop add %rcx, %rcx lea addresses_normal_ht+0x86fd, %rbp add %r14, %r14 mov (%rbp), %rsi nop nop sub $61011, %rbp lea addresses_WC_ht+0x5d45, %rsi clflush (%rsi) nop dec %rbx mov $0x6162636465666768, %rdi movq %rdi, (%rsi) nop xor %rdi, %rdi lea addresses_WT_ht+0x10fd, %rsi lea addresses_A_ht+0x19acd, %rdi nop nop nop nop and $11364, %rbx mov $91, %rcx rep movsb nop nop nop and $47540, %rbp lea addresses_D_ht+0xa34d, %rdi nop nop nop nop nop and %r11, %r11 mov $0x6162636465666768, %rbp movq %rbp, %xmm4 vmovups %ymm4, (%rdi) nop nop dec %rcx pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r14 pop %r11 ret .global s_faulty_load s_faulty_load: push %r15 push %r9 push %rbx push %rdx push %rsi // Faulty Load lea addresses_normal+0x15b4d, %rbx nop inc %rdx mov (%rbx), %r15w lea oracles, %rsi and $0xff, %r15 shlq $12, %r15 mov (%rsi,%r15,1), %r15 pop %rsi pop %rdx pop %rbx pop %r9 pop %r15 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_normal', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 3}, 'dst': {'same': False, 'type': 'addresses_A_ht', 'congruent': 1}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_D_ht', 'congruent': 0}, 'dst': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 10}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 6}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 2}} {'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 2}} {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 4}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 2}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 3}, 'dst': {'same': False, 'type': 'addresses_A_ht', 'congruent': 7}} {'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_D_ht', 'same': True, 'AVXalign': False, 'congruent': 8}} {'34': 21829} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
; A053835: Sum of digits of n written in base 15. ; 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,5,6,7,8,9,10,11,12,13 mov $1,$0 add $0,1 lpb $0,1 sub $0,1 sub $1,$3 sub $2,$2 add $2,9 mov $3,5 add $3,$2 trn $0,$3 lpe
;; potentially useful macros for asm development ;; long-nop instructions: nopX inserts a nop of X bytes ;; see "Table 4-12. Recommended Multi-Byte Sequence of NOP Instruction" in ;; "Intel® 64 and IA-32 Architectures Software Developer’s Manual" (325383-061US) %define nop1 nop ; just a nop, included for completeness %define nop2 db 0x66, 0x90 ; 66 NOP %define nop3 db 0x0F, 0x1F, 0x00 ; NOP DWORD ptr [EAX] %define nop4 db 0x0F, 0x1F, 0x40, 0x00 ; NOP DWORD ptr [EAX + 00H] %define nop5 db 0x0F, 0x1F, 0x44, 0x00, 0x00 ; NOP DWORD ptr [EAX + EAX*1 + 00H] %define nop6 db 0x66, 0x0F, 0x1F, 0x44, 0x00, 0x00 ; 66 NOP DWORD ptr [EAX + EAX*1 + 00H] %define nop7 db 0x0F, 0x1F, 0x80, 0x00, 0x00, 0x00, 0x00 ; NOP DWORD ptr [EAX + 00000000H] %define nop8 db 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00 ; NOP DWORD ptr [EAX + EAX*1 + 00000000H] %define nop9 db 0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00 ; 66 NOP DWORD ptr [EAX + EAX*1 + 00000000H] ;; push the 6 callee-saved registers defined in the the SysV C ABI %macro push_callee_saved 0 push rbp push rbx push r12 push r13 push r14 push r15 %endmacro ;; pop the 6 callee-saved registers in the order compatible with push_callee_saved %macro pop_callee_saved 0 pop r15 pop r14 pop r13 pop r12 pop rbx pop rbp %endmacro EXTERN nasm_util_assert_failed ; place the string value of a tken in .rodata using %defstr ; arg1 - the token to make into a string ; arg2 - label which will point to the string %macro make_string_tok 2 %ifdef __YASM_MAJOR__ ; yasm has no support for defstr so we just use a fixed string for now ; see https://github.com/travisdowns/nasm-utils/issues/1 make_string 'make_string_tok yasm bug', %2 %else %defstr make_string_temp %1 make_string make_string_temp, %2 %endif %endmacro %macro make_string 2 [section .rodata] %2: db %1,0 ; restore the previous section __SECT__ %endmacro %macro nasm_util_assert_boilerplate 0 make_string __FILE__, parent_filename %define ASSERT_BOILERPLATE 1 %endmacro %macro check_assert_boilerplate 0 %ifndef ASSERT_BOILERPLATE %error "To use asserts, you must include a call to nasm_util_assert_boilerplate once in each file" %endif %endmacro ;; assembly level asserts ;; if the assert occurs, termination is assumed so control never passes back to the caller ;; and registers are not preserved %macro assert_eq 2 check_assert_boilerplate cmp %1, %2 je %%assert_ok make_string_tok %1, %%assert_string1 make_string_tok %2, %%assert_string2 lea rdi, [%%assert_string1] lea rsi, [%%assert_string2] lea rdx, [parent_filename] mov rcx, __LINE__ jmp nasm_util_assert_failed %%assert_ok: %endmacro ;; boilerplate needed once when abi_checked_function is used %macro thunk_boilerplate 0 ; this function is defined by the C helper code EXTERN nasm_util_die_on_reg_clobber boil1 rbp, 1 boil1 rbx, 2 boil1 r12, 3 boil1 r13, 4 boil1 r14, 5 boil1 r15, 6 %endmacro ;; By default, the "assert-like" features that can be conditionally enabled key off the value of the ;; NDEBUG macro: if it is defined, the slower, more heavily checked paths are enabled, otherwise they ;; are omitted (usually resulting in zero additional cost). ;; ;; If you don't want to rely on NDEBUG can specifically enable or disable the debug mode with the ;; NASM_ENABLE_DEBUG set to 0 (equivalent to NDEBUG set) or 1 (equivalent to NDEBUG not set) %ifndef NASM_ENABLE_DEBUG %ifdef NDEBUG %define NASM_ENABLE_DEBUG 0 %else %define NASM_ENABLE_DEBUG 1 %endif %elif (NASM_ENABLE_DEBUG != 0) && (NASM_ENABLE_DEBUG != 1) %error bad value for 'NASM_ENABLE_DEBUG': should be 0 or 1 but was NASM_ENABLE_DEBUG %endif ;; This macro supports declaring a "ABI-checked" function in asm ;; An ABI-checked function will checked at each invocation for compliance with the SysV ABI ;; rules about callee saved registers. In particular, from the ABI cocument we have the following: ;; ;; Registers %rbp, %rbx and %r12 through %r15 “belong” to the calling function ;; and the called function is required to preserve their values. ;; (from "System V Application Binary Interface, AMD64 Architecture Processor Supplement") ;; ;; %macro abi_checked_function 1 GLOBAL %1:function %1: %if NASM_ENABLE_DEBUG != 0 ;%warning compiling ABI checks ; save all the callee-saved regs push_callee_saved push rax ; dummy push to align the stack (before we have rsp % 16 == 8) call %1_inner add rsp, 8 ; undo dummy push ; load the function name (ok to clobber rdi since it's callee-saved) mov rdi, %1_thunk_fn_name ; now check whether any regs were clobbered cmp rbp, [rsp + 40] jne bad_rbp cmp rbx, [rsp + 32] jne bad_rbx cmp r12, [rsp + 24] jne bad_r12 cmp r13, [rsp + 16] jne bad_r13 cmp r14, [rsp + 8] jne bad_r14 cmp r15, [rsp] jne bad_r15 add rsp, 6 * 8 ret ; here we store strings needed by the failure cases, in the .rodata section [section .rodata] %1_thunk_fn_name: %ifdef __YASM_MAJOR__ ; yasm doesn't support defstr, so for now just use an unknown name db "unknown (see yasm issue #95)",0 %else %defstr fname %1 db fname,0 %endif ; restore the previous section __SECT__ %1_inner: %endif ; debug off, just assemble the function as-is without any checks %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; IMPLEMENTATION FOLLOWS ;; below you find internal macros needed for the implementation of the above macros ;;;;;;;;;;;;;;;;;;;;;;;;;;; ; generate the stubs for the bad_reg functions called from the check-abi thunk %macro boil1 2 bad_%1: ; A thunk has determined that a reg was clobbered ; each reg has their own bad_ function which moves the function name (in rdx) into ; rdi and loads a constant indicating which reg was involved and calls a C routine ; that will do the rest (abort the program generall). We follow up with an ud2 in case ; the C routine returns, since this mechanism is not designed for recovery. mov rsi, %2 ; here we set up a stack frame - this gives a meaningful backtrace in any core file produced by the abort ; first we need to pop the saved regs off the stack so the rbp chain is consistent add rsp, 6 * 8 push rbp mov rbp, rsp call nasm_util_die_on_reg_clobber ud2 %endmacro
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r13 push %rcx push %rdi push %rdx push %rsi lea addresses_UC_ht+0x98f2, %rsi lea addresses_D_ht+0x1592, %rdi nop nop nop and $20474, %r11 mov $124, %rcx rep movsw nop nop sub $53759, %r13 lea addresses_normal_ht+0x1c3f2, %rsi lea addresses_WC_ht+0x1b372, %rdi mfence mov $1, %rcx rep movsq nop nop add $23149, %rcx lea addresses_WC_ht+0xd0b2, %rsi lea addresses_WC_ht+0x6172, %rdi nop nop nop nop add %r12, %r12 mov $23, %rcx rep movsb inc %r11 lea addresses_WC_ht+0xf6fe, %r11 clflush (%r11) nop nop nop add $34558, %rdx movw $0x6162, (%r11) and %r11, %r11 lea addresses_WC_ht+0x98aa, %rcx dec %r12 movb $0x61, (%rcx) nop nop nop add $34122, %rdx lea addresses_normal_ht+0x126f2, %r12 nop nop sub $53235, %rdi mov $0x6162636465666768, %rcx movq %rcx, %xmm6 movups %xmm6, (%r12) nop nop sub $54477, %rdi lea addresses_A_ht+0x4572, %rdx and $6636, %r11 vmovups (%rdx), %ymm1 vextracti128 $1, %ymm1, %xmm1 vpextrq $0, %xmm1, %r13 nop and $39224, %rsi lea addresses_WC_ht+0x13572, %r12 nop nop nop cmp $36980, %r13 movb $0x61, (%r12) nop nop cmp $23769, %r11 pop %rsi pop %rdx pop %rdi pop %rcx pop %r13 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r8 push %r9 push %rdi push %rdx push %rsi // Faulty Load lea addresses_A+0xf972, %rdi nop nop nop nop cmp %rsi, %rsi movups (%rdi), %xmm4 vpextrq $1, %xmm4, %rdx lea oracles, %r8 and $0xff, %rdx shlq $12, %rdx mov (%r8,%rdx,1), %rdx pop %rsi pop %rdx pop %rdi pop %r9 pop %r8 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_A'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_A'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 3, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 6, 'same': True, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': True, 'size': 1, 'NT': False, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_normal_ht'}} {'src': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WC_ht'}} {'44': 12, '45': 1, '48': 174, '00': 21642} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; char *itoa(int num, char *buf, int radix) SECTION code_clib SECTION code_stdlib PUBLIC itoa_callee EXTERN asm_itoa itoa_callee: pop hl pop bc pop de ex (sp),hl jp asm_itoa ; SDCC bridge for Classic IF __CLASSIC PUBLIC _itoa_callee defc _itoa_callee = itoa_callee ENDIF
; int puts(const char *s) INCLUDE "clib_cfg.asm" SECTION code_stdio ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $02 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC _puts_fastcall EXTERN asm_puts _puts_fastcall: push ix call asm_puts pop ix ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC _puts_fastcall EXTERN _puts_unlocked_fastcall defc _puts_fastcall = _puts_unlocked_fastcall ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
.global s_prepare_buffers s_prepare_buffers: push %r9 push %rcx push %rdi push %rsi lea addresses_UC_ht+0xaeb0, %rsi lea addresses_D_ht+0x18ab0, %rdi nop nop cmp $7795, %r9 mov $42, %rcx rep movsb nop nop inc %rcx pop %rsi pop %rdi pop %rcx pop %r9 ret .global s_faulty_load s_faulty_load: push %r13 push %r15 push %r8 push %r9 push %rax push %rbx push %rsi // Load lea addresses_RW+0x7ab0, %r9 clflush (%r9) nop nop nop nop and $65415, %rsi mov (%r9), %rbx sub $60197, %r15 // Store lea addresses_WT+0x1dcf0, %rax inc %r13 movw $0x5152, (%rax) nop nop nop nop xor $7815, %rax // Faulty Load lea addresses_RW+0x7ab0, %rsi nop nop inc %r13 mov (%rsi), %r15d lea oracles, %rsi and $0xff, %r15 shlq $12, %r15 mov (%rsi,%r15,1), %r15 pop %rsi pop %rbx pop %rax pop %r9 pop %r8 pop %r15 pop %r13 ret /* <gen_faulty_load> [REF] {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_RW', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_RW', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_WT', 'size': 2, 'AVXalign': False}} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_RW', 'size': 4, 'AVXalign': True}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}} {'32': 21829} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
#include "reserved.h" #include <cassert> using namespace std; std::unordered_map<NamePool::Id, Meaningful, NamePool::Id::Hasher> meaningfuls; std::unordered_map<NamePool::Id, Keyword, NamePool::Id::Hasher> keywords; std::unordered_map<NamePool::Id, Oper, NamePool::Id::Hasher> opers; const unordered_map<Oper, OperInfo> operInfos = { {Oper::ASGN, {.binary=true}}, {Oper::NOT, {.unary=true}}, {Oper::BIT_NOT, {.unary=true}}, {Oper::EQ, {.binary=true, .comparison=true}}, {Oper::NE, {.binary=true, .comparison=true}}, {Oper::LT, {.binary=true, .comparison=true}}, {Oper::LE, {.binary=true, .comparison=true}}, {Oper::GT, {.binary=true, .comparison=true}}, {Oper::GE, {.binary=true, .comparison=true}}, {Oper::ADD, {.unary=true, .binary=true}}, {Oper::SUB, {.unary=true, .binary=true}}, {Oper::MUL, {.unary=true, .binary=true}}, {Oper::DIV, {.binary=true}}, {Oper::REM, {.binary=true}}, {Oper::BIT_AND, {.unary=true, .binary=true}}, {Oper::BIT_OR, {.binary=true}}, {Oper::BIT_XOR, {.binary=true}}, {Oper::SHL, {.binary=true}}, {Oper::SHR, {.unary=true, .binary=true}}, {Oper::IND, {.binary=true}} }; bool isMeaningful(NamePool::Id name) { return meaningfuls.find(name) != meaningfuls.end(); } optional<Meaningful> getMeaningful(NamePool::Id name) { auto loc = meaningfuls.find(name); if (loc == meaningfuls.end()) return nullopt; return loc->second; } NamePool::Id getMeaningfulNameId(Meaningful m) { for (const auto &it : meaningfuls) { if (it.second == m) return it.first; } assert(false && "getMeaningfulNameId failed to find!"); return NamePool::Id(); } bool isMeaningful(NamePool::Id name, Meaningful m) { optional<Meaningful> opt = getMeaningful(name); return opt.has_value() && opt.value() == m; } bool isKeyword(NamePool::Id name) { return keywords.find(name) != keywords.end(); } optional<Keyword> getKeyword(NamePool::Id name) { auto loc = keywords.find(name); if (loc == keywords.end()) return nullopt; return loc->second; } NamePool::Id getKeywordNameId(Keyword k) { for (const auto &it : keywords) { if (it.second == k) return it.first; } assert(false && "getKeywordNameId failed to find!"); return NamePool::Id(); } bool isKeyword(NamePool::Id name, Keyword k) { optional<Keyword> opt = getKeyword(name); return opt.has_value() && opt.value() == k; } bool isOper(NamePool::Id name) { return opers.find(name) != opers.end(); } optional<Oper> getOper(NamePool::Id name) { auto loc = opers.find(name); if (loc == opers.end()) return nullopt; return loc->second; } NamePool::Id getOperNameId(Oper o) { for (const auto &it : opers) { if (it.second == o) return it.first; } assert(false && "getOperNameId failed to find!"); return NamePool::Id(); } bool isOper(NamePool::Id name, Oper o) { optional<Oper> opt = getOper(name); return opt.has_value() && opt.value() == o; } bool isReserved(NamePool::Id name) { return isKeyword(name) || isOper(name) || isTypeDescrDecor(name); } bool isTypeDescrDecor(Meaningful m) { return m == Meaningful::CN || m == Meaningful::ASTERISK || m == Meaningful::SQUARE; } bool isTypeDescrDecor(NamePool::Id name) { optional<Meaningful> m = getMeaningful(name); if (!m.has_value()) return false; return isTypeDescrDecor(m.value()); }
; A074837: Numbers n such that the penultimate 3 divisors of n sum to n. ; 6,18,42,54,66,78,102,114,126,138,162,174,186,198,222,234,246,258,282,294,306,318,342,354,366,378,402,414,426,438,462,474,486,498,522,534,546,558,582,594,606,618,642,654,666,678,702,714,726,738,762,774,786,798,822,834,846,858,882,894,906,918,942,954,966,978,1002,1014,1026,1038,1062,1074,1086,1098,1122,1134,1146,1158,1182,1194,1206,1218,1242,1254,1266,1278,1302,1314,1326,1338,1362,1374,1386,1398,1422,1434,1446,1458,1482,1494,1506,1518,1542,1554,1566,1578,1602,1614,1626,1638,1662,1674,1686,1698,1722,1734,1746,1758,1782,1794,1806,1818,1842,1854,1866,1878,1902,1914,1926,1938,1962,1974,1986,1998,2022,2034,2046,2058,2082,2094,2106,2118,2142,2154,2166,2178,2202,2214,2226,2238,2262,2274,2286,2298,2322,2334,2346,2358,2382,2394,2406,2418,2442,2454,2466,2478,2502,2514,2526,2538,2562,2574,2586,2598,2622,2634,2646,2658,2682,2694,2706,2718,2742,2754,2766,2778,2802,2814,2826,2838,2862,2874,2886,2898,2922,2934,2946,2958,2982,2994,3006,3018,3042,3054,3066,3078,3102,3114,3126,3138,3162,3174,3186,3198,3222,3234,3246,3258,3282,3294,3306,3318,3342,3354,3366,3378,3402,3414,3426,3438,3462,3474,3486,3498,3522,3534,3546,3558,3582,3594,3606,3618,3642,3654,3666,3678,3702,3714,3726,3738 mov $1,$0 mul $1,5 add $1,2 div $1,4 mul $1,12 add $1,6
; A280021: Expansion of phi_{11, 2}(x) where phi_{r, s}(x) = Sum_{n, m>0} m^r * n^s * x^{m*n}. ; Submitted by Jamie Morken(s2) ; 0,1,2052,177156,4202512,48828150,363524112,1977326792,8606744640,31382654013,100195363800,285311670732,744500215872,1792160394206,4057474577184,8650199741400,17626613022976,34271896307922,64397206034676,116490258898580,205200886312800,350295305163552,585459548342064,952809757914456,1524736453443840,2384187011719375,3677513128910712,5559343010441640,8309739571301504,12200509765706670,17750209869352800,25408476896405792,36099303471055872,50544674340198192,70325931223855944,96549209198794800 mov $2,$0 seq $0,282254 ; Coefficients in q-expansion of (3*E_4^3 + 2*E_6^2 - 5*E_2*E_4*E_6)/1584, where E_2, E_4, E_6 are the Eisenstein series shown in A006352, A004009, A013973, respectively. mul $0,$2
; SMP AP startup trampoline ; This is where other cores start their execution. ; Stack must not be used here. %include "src/asm_routines/constants.asm" %define CODE_SEG 0x0008 %define DATA_SEG 0x0010 [BITS 16] [ORG 0x2000] ; todo: constantify? ap_startup: jmp 0x0000:.flush_cs ; reload CS to zero .flush_cs: ; initialize segment registers xor ax, ax mov ds, ax mov es, ax mov ss, ax lidt [IDT] ; Load a zero length IDT ; Enter long mode. mov eax, 10100000b ; Set the PAE and PGE bit. mov cr4, eax mov edx, PAGE_TABLES_LOCATION ; Point CR3 at the PML4. mov cr3, edx mov ecx, 0xC0000080 ; Read from the EFER MSR. rdmsr or eax, 0x00000900 ; Set the LME & NXE bit. wrmsr mov ebx, cr0 ; Activate long mode by enabling or ebx,0x80000001 ; paging and protection simultaneously mov cr0, ebx lgdt [GDT.Pointer] ; Load GDT.Pointer defined below. jmp CODE_SEG:long_mode ; Load CS with 64 bit segment and flush the instruction cache ; Global Descriptor Table ALIGN 4 GDT: .Null: dq 0x0000000000000000 ; Null Descriptor - should be present. .Code: dq 0x00209A0000000000 ; 64-bit code descriptor (exec/read). dq 0x0000920000000000 ; 64-bit data descriptor (read/write). ALIGN 4 dw 0 ; Padding to make the "address of the GDT" field aligned on a 4-byte boundary .Pointer: dw $ - GDT - 1 ; 16-bit Size (Limit) of GDT. dd GDT ; 32-bit Base Address of GDT. (CPU will zero extend to 64-bit) ALIGN 4 IDT: .Length dw 0 .Base dd 0 [BITS 64] long_mode: mov ax, DATA_SEG mov ds, ax mov es, ax mov fs, ax mov gs, ax mov ss, ax mov rcx, 1 ; set rcx = 1 to mark AP cpu jmp 0x100_0000 ; TODO: constantify
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r13 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_A_ht+0x9f81, %rsi clflush (%rsi) nop nop nop cmp $33590, %rcx vmovups (%rsi), %ymm4 vextracti128 $0, %ymm4, %xmm4 vpextrq $1, %xmm4, %rdx nop nop nop nop add %rax, %rax lea addresses_WC_ht+0x2d81, %r12 nop nop cmp %r10, %r10 movw $0x6162, (%r12) cmp %rsi, %rsi lea addresses_normal_ht+0x2561, %r10 clflush (%r10) nop nop nop nop sub %r13, %r13 movw $0x6162, (%r10) nop nop nop nop nop cmp %rax, %rax lea addresses_WC_ht+0x9581, %r13 nop nop nop nop nop add $51065, %rdx mov (%r13), %ax nop nop nop cmp %rdx, %rdx lea addresses_A_ht+0x18581, %rsi lea addresses_normal_ht+0x9c97, %rdi nop and $29904, %r13 mov $41, %rcx rep movsq mfence pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r13 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r15 push %r9 push %rax push %rbp push %rdi push %rdx push %rsi // Store lea addresses_WC+0x20e1, %r9 nop nop nop cmp %r15, %r15 mov $0x5152535455565758, %rbp movq %rbp, %xmm7 vmovups %ymm7, (%r9) nop nop nop nop cmp %rbp, %rbp // Load lea addresses_WC+0x15995, %rdi nop nop cmp $6157, %r15 mov (%rdi), %r9d nop nop xor %rax, %rax // Store lea addresses_WT+0x1cbc1, %r15 nop nop nop sub %rsi, %rsi mov $0x5152535455565758, %rdx movq %rdx, (%r15) nop nop nop nop nop cmp $54340, %rdx // Load lea addresses_normal+0x18581, %r9 xor %rdi, %rdi movb (%r9), %dl nop nop cmp $58693, %rax // Faulty Load lea addresses_PSE+0x1ad81, %rdx nop nop nop nop nop xor $35840, %rsi movntdqa (%rdx), %xmm4 vpextrq $0, %xmm4, %r15 lea oracles, %rdi and $0xff, %r15 shlq $12, %r15 mov (%rdi,%r15,1), %r15 pop %rsi pop %rdx pop %rdi pop %rbp pop %rax pop %r9 pop %r15 ret /* <gen_faulty_load> [REF] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_PSE', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 3, 'NT': False, 'type': 'addresses_WC', 'size': 32, 'AVXalign': False}} {'src': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_WC', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_WT', 'size': 8, 'AVXalign': False}} {'src': {'same': False, 'congruent': 11, 'NT': False, 'type': 'addresses_normal', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': True, 'type': 'addresses_PSE', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_A_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_normal_ht', 'size': 2, 'AVXalign': False}} {'src': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 1, 'same': False}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Geoworks 1994 -- All Rights Reserved PROJECT: PC/GEOS MODULE: Power Drivers FILE: apmCustom.asm AUTHOR: Todd Stumpf, Aug 1, 1994 REVISION HISTORY: Name Date Description ---- ---- ----------- TS 8/ 1/94 Initial revision DESCRIPTION: List of files that must be customized $Id: apmCustom.asm,v 1.1 97/04/18 11:48:26 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ Resident segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% APMReadRTC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get current value from RTC CALLED BY: APMUpdateClocks PASS: ds -> dgroup RETURN: dh <- seconds dl <- minutes ch <- hours bl <- month bh <- day ax <- century + year DESTROYED: nothing SIDE EFFECTS: Reads from RTC PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- TS 8/ 1/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ APMReadRTC proc near .enter .leave ret APMReadRTC endp if HAS_RTC_INTERRUPT COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% APMSendRTCAck %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: ACK the RTC hardware for the device CALLED BY: APMStrategy PASS: ds -> dgroup RETURN: nothing DESTROYED: nothing SIDE EFFECTS: Presumably, it does an EOI and possibly some other stuff as well. PSEUDO CODE/STRATEGY: Dance the polka. See if anyone else wants to dance the polka. Notice no one does. Notice they're all pointing and staring. Sit down. Look sheepish. Desire to crawl under rock and die. Look sheepish. REVISION HISTORY: Name Date Description ---- ---- ----------- TS 8/ 1/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ APMSendRTCAck proc near ret APMSendRTCAck endp endif Resident ends Movable segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% APMCheckForOnOffPress %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Determine if request came from ON-OFF button CALLED BY: APMGetStatusWarnings PASS: ds -> dgroup RETURN: carry set if request not on-off press DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- TS 8/ 1/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ APMCheckForOnOffPress proc near .enter if HAS_COMPLEX_ON_OFF_BUTTON test ds:[miscState], mask MS_ON_OFF_PRESS ; clears carry auto. jz done ; => wasn't on-off andnf ds:[miscState], not (mask MS_ON_OFF_PRESS) ; clear state bit stc ; mark asON-OFF done: cmc else %out HEY! FILL THIS OUT OKAY? endif .leave ret APMCheckForOnOffPress endp Movable ends Resident segment resource if HAS_DETACHABLE_KEYBOARD COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% APMCheckKeyboard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: CALLED BY: PASS: RETURN: DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- TS 8/ 1/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ APMCheckKeyboard proc near uses ax,bx,cx,dx,si,di,bp .enter .leave ret APMCheckKeyboard endp endif Resident ends
; A083023: a(n) = number of partitions of n into a pair of parts n=p+q, p>=q>=0, with p-q equal to a square >= 0. ; 1,1,1,2,1,2,1,2,2,2,2,2,2,2,2,3,2,3,2,3,2,3,2,3,3,3,3,3,3,3,3,3,3,3,3,4,3,4,3,4,3,4,3,4,3,4,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,4,5,4,5,4,5,4,5,4,5,4,5,4,5,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,5,6 cal $0,256244 ; a(n) = sqrt(n + 2*A256243(n)). div $0,2 mov $1,$0
; $Id: bit_close.asm,v 1.3 2016/06/16 20:23:51 dom Exp $ ; ; Galaksija 1 bit sound functions ; ; void bit_click(); ; ; Stefano Bodrato ; SECTION code_clib PUBLIC bit_close PUBLIC _bit_close .bit_close ._bit_close ret
;================================================= ; Name: Moya, Branden ; Username: bmoya001@ucr.edu ; ; Lab: lab 6.1 ; Lab section: 021 ; TA: Bryan Marsh ; ;================================================= .ORIG x3000 ;INSTRUCTIONS LD R3, ONE_CHECK START AND R1,R1,#0 AND R5,R5,#0 ;RESETS VALUES AND R6,R6,#0 LEA R0, PROMPT ;OUPUTS PROMPT PUTS GET_INPUT ;GETS INPUT AND CONVERTS IT TO A SINGLE NUMBER IN R1 GETC OUT BR TEST_INPUT BACK LD R4, NINE ADD R6,R1,#0 ;SETS R6 TO R0 FOR MULTIPLICATION INNER ADD R1,R1,R6 ADD R4,R4,#-1 BRp INNER ADD R0,R0,R3 ADD R1,R1,R0 ;ADDS THE NEXT NUMBER ADD R6,R6,#2 BR GET_INPUT TEST_INPUT LD R2, ENTER ;CHECKS FOR ENTER BAR ADD R2,R2,R0 BRz LAST_CHECK ADD R2,R6,#-1 BRzp NUM_CHECK LD R2, MINUS ;CHECKS FOR '-' ADD R2,R2,R0 BRz NEGATIVE LD R2, PLUS ;CHECKS FOR '+' ADD R2,R2,R0 BRz POSITIVE NUM_CHECK LD R2, ONE_CHECK ;CHECKS FOR < 1 ADD R2,R2,R0 BRn ERROR LD R2, NINE_CHECK ;CHECKS FOR > 9 ADD R2,R2,R0 BRp ERROR BR BACK NEGATIVE ;IF '-' ADD R5,R5,#-1 ADD R6,R6,#1 BR GET_INPUT POSITIVE ;IF '+' ADD R5,R5,#1 ADD R6,R6,#1 BR GET_INPUT NEGATE ;NEGATES R1 IF NEGATIVE SIGN WAS ENTERED NOT R1,R1 ADD R1,R1,#1 BR FINISH LAST_CHECK ADD R2,R6,#-1 BRn ERROR AND R5,R5,R5 BRnp LAST_LAST_CHECK BR FINISH LAST_LAST_CHECK ADD R2,R6,#-2 BRn ERROR AND R5,R5,R5 BRn NEGATE BR FINISH ERROR ;ERROR OUTPUT/REASK FOR NUMBERS LD R2, ENTER ADD R2,R2,R0 BRnp NEW_LINE BACK_TO_ERROR LEA R0, WRONG PUTS BR START NEW_LINE AND R0,R0,#0 ADD R0,R0,#10 OUT BR BACK_TO_ERROR FINISH ADD R1,R1,#1 JSR OUTPUT_3200 HALT ;LOCAL DATA PROMPT .STRINGZ "Input a positive or negative decimal number (max 5 digits), followed by ENTER\n" WRONG .STRINGZ "ERROR INVALID INPUT\n" PLUS .FILL #-43 MINUS .FILL #-45 ENTER .FILL #-10 ONE_CHECK .FILL #-48 ;TEST IF CHAR IS POSITIVE AFTER NINE_CHECK .FILL #-57 ;TEST IF CHAR IS NEGATIVE AFTER ONE .FILL #1 NINE .FILL #9 ;================================================= ;subroutine:PRINT IN decinmal ;input:R2 TO BE PRINTED IN decimal ;post condition:OUTPUT ;return values:NONE .Orig x3200 OUTPUT_3200 ;NAME ST R7, R7_3200 ;STORES R7,R5,R2 VALUES FOR BACKUP LD R3, POINTER LD R4, NUM_TO_CHAR AND R5,R5,#0 ADD R5,R5,#5 ;COUNTER AND R6,R6,#0 LOOP1 LDR R2,R3,#0 AND R0,R0,#0 LOOP2 ADD R1,R1,R2 BRn SKIP ADD R0,R0,#1 ADD R6,R6,#1 BR LOOP2 SKIP AND R6,R6,R6 BRz SKIP2 ADD R0,R0,R4 OUT SKIP2 NOT R2,R2 ADD R2,R2,#1 ADD R1,R1,R2 ADD R3,R3,#1 ADD R5,R5,#-1 BRp LOOP1 LD R7, R7_3200 ;RESETS VAULES RET ;Subroutine data R7_3200 .FILL #0 NUM_TO_CHAR .FILL x30 POINTER .FILL x3300 .ORIG x3300 TEN_THOUSAND .FILL #-10000 THOUSAND .FILL #-1000 HOUNDRED .FILL #-100 TEN .FILL #-10 SDFSDFS .FILL #-1 .END
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r15 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0xde40, %r15 add %rbp, %rbp mov (%r15), %r11 nop nop nop nop nop dec %r15 lea addresses_WT_ht+0x3b23, %r15 nop nop add %rdx, %rdx mov $0x6162636465666768, %rdi movq %rdi, (%r15) nop nop xor $43184, %rbp lea addresses_D_ht+0x16a40, %r13 nop nop nop nop nop dec %r15 mov $0x6162636465666768, %rdx movq %rdx, (%r13) dec %r15 lea addresses_normal_ht+0x93c0, %rsi lea addresses_A_ht+0x10860, %rdi clflush (%rsi) nop nop nop inc %r15 mov $42, %rcx rep movsb nop nop nop nop xor %rdi, %rdi lea addresses_A_ht+0x1cb40, %r11 add %r15, %r15 mov (%r11), %cx nop dec %r13 lea addresses_WC_ht+0xf3f8, %rbp nop nop nop and $36326, %r11 mov (%rbp), %dx nop nop nop nop add $46559, %r11 lea addresses_WT_ht+0xa922, %rdi nop nop nop and %rcx, %rcx movl $0x61626364, (%rdi) lfence lea addresses_UC_ht+0x17cc0, %rdx nop nop add %rsi, %rsi movl $0x61626364, (%rdx) nop nop nop sub $1130, %rbp lea addresses_normal_ht+0x10e40, %rcx nop nop nop nop and $15620, %r13 mov (%rcx), %r11 and %rdi, %rdi lea addresses_WC_ht+0xd6d0, %rcx xor %r11, %r11 movw $0x6162, (%rcx) nop nop nop nop nop and %rdx, %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r15 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r13 push %r15 push %r8 push %rcx // Store mov $0x3cd0e70000000ca0, %r13 add $36754, %r12 mov $0x5152535455565758, %r15 movq %r15, %xmm0 vmovups %ymm0, (%r13) nop nop nop nop nop add %r8, %r8 // Faulty Load lea addresses_A+0xb640, %rcx nop sub %r15, %r15 vmovups (%rcx), %ymm2 vextracti128 $1, %ymm2, %xmm2 vpextrq $1, %xmm2, %r12 lea oracles, %r15 and $0xff, %r12 shlq $12, %r12 mov (%r15,%r12,1), %r12 pop %rcx pop %r8 pop %r15 pop %r13 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 3, 'size': 32, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 10, 'size': 8, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 10, 'size': 8, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 8, 'size': 2, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 2, 'size': 2, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 1, 'size': 4, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 5, 'size': 4, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 9, 'size': 8, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 4, 'size': 2, 'same': False, 'NT': False}} {'00': 7} 00 00 00 00 00 00 00 */
;-------------------------------------; ; GPIO POOLING FOR ATMEL328p ; ; ; ; Por: Prof. Carlo Requiao ; ; 13/Oct/2021 ; ;-------------------------------------; .device ATmega328P ;-------------------------------------; ; MACROS ; ;-------------------------------------; .macro initstack ldi R16,low(RAMEND) out spl,R16 ldi R16,high(RAMEND) out sph,R16 .endmacro ;-------------------------------------; ; DEFINITIONS ; ;-------------------------------------; .def geral1=R18 .def geral2=R19 ;-------------------------------------; ; MEMORY SEGMENTS ; ;-------------------------------------; .dseg .cseg .org 0x00 ; Program starts at 0x00 rjmp INICIO ;-------------------------------------; ; CODE ; ;-------------------------------------; INICIO: initstack in R16,MCUCR ori R16,(1<<PUD) out MCUCR,R16 ; Disable pull-up sbi DDRB,5 ; On-board LED is output cbi DDRB,0 ; GPIO8 (PB0) is input LOOP: sbi PORTB,5 ; Turn LED on L1: sbic PINB,0 ; Skip if PB[0] == 0 rjmp L1 cbi PORTB,5 ; Turn LED off L2: sbis PINB,0 ; Skip if PB[0] == 1 rjmp L2 rjmp LOOP
; ; Small C+ Compiler ; ; The Maths Routines (essential ones!) ; ; All maths routines are now in a library except for these ; small ones (which will always be used) ; ; If -doublestr is defined then we can link with whatever ; library we feel like ; ; djm 7/12/98 ; ; $Id: float.asm,v 1.8 2002/08/20 13:58:08 dom Exp $ ;------------------------------------------------- ; Some scope defintionons for the crt0 float stuff ;------------------------------------------------- XDEF fp_seed XDEF extra XDEF fa XDEF fasign XDEF dstore XDEF dload XDEF dldpsh XDEF dpush XDEF dpush2 XDEF __atof2 LIB atof ;needed for __atof2 ;------------------------------------------- ; Unused code from the generic z80 maths lib ;------------------------------------------- ; ;DIVZERO CALL GRIPE ; DEFB 'can''t /0',0 ;OFLOW CALL GRIPE ; DEFB 'Arithmetic overflow',0 ;GRIPE CALL QERR ;top word on stack points to message ; JP 0 ;error was fatal ; ; FA = (hl) ; ;-------------- ; Copy FA to de ;-------------- .dstore ld de,fa ld bc,6 ex de,hl ldir ex de,hl ret ;---------------- ; Load FA from hl ;---------------- .dload ld de,fa ld bc,6 ldir ret ;----------------------------------------- ; Load FA from (hl) and push FA onto stack ;----------------------------------------- .dldpsh ld de,fa ld bc,6 ldir ;------------------------------------------ ; Push FA onto stack (under return address) ;------------------------------------------ .dpush pop de ld hl,(fa+4) push hl ld hl,(fa+2) push hl ld hl,(fa) push hl ex de,hl jp (hl) ;------------------------------------------------------ ; Push FA onto stack under ret address and stacked word ;------------------------------------------------------ .dpush2 pop de ;save return address pop bc ;save next word ld hl,(fa+4) push hl ld hl,(fa+2) push hl ld hl,(fa) push hl ex de,hL push bc ;restore next word jp (hl) ;return IF DEFINED_math_atof ;--------------------------------------------------------- ; Convert string to FP number in FA calls the library atof ;--------------------------------------------------------- .__atof2 push hl call atof pop bc ret ENDIF
;------------------------------------------------------------------------------ ; ; Copyright (c) 2014 - 2016, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Abstract: ; ; Provide FSP API entry points. ; ;------------------------------------------------------------------------------ section .text ; ; Following are fixed PCDs ; extern ASM_PFX(_gPcd_FixedAtBuild_PcdTemporaryRamBase) extern ASM_PFX(_gPcd_FixedAtBuild_PcdTemporaryRamSize) extern ASM_PFX(_gPcd_FixedAtBuild_PcdFspTemporaryRamSize) extern ASM_PFX(_gPcd_FixedAtBuild_PcdFspAreaSize) ; ; Following functions will be provided in C ; extern ASM_PFX(SecStartup) extern ASM_PFX(FspApiCallingCheck) extern ASM_PFX(TempRamExitApi) extern ASM_PFX(FspSiliconInitApi) extern ASM_PFX(NotifyPhaseApi) ; ; Following functions will be provided in PlatformSecLib ; extern ASM_PFX(AsmGetFspBaseAddress) extern ASM_PFX(AsmGetFspInfoHeader) extern ASM_PFX(GetBootFirmwareVolumeOffset) extern ASM_PFX(Loader2PeiSwitchStack) ; ; Define the data length that we saved on the stack top ; DATA_LEN_OF_PER0 equ 0x018 DATA_LEN_OF_MCUD equ 0x018 DATA_LEN_AT_STACK_TOP equ (DATA_LEN_OF_PER0 + DATA_LEN_OF_MCUD + 4) ;---------------------------------------------------------------------------- ; TempRamInit API ; ; TempRamInit API is an empty API since Quark SoC does not support CAR. ; ;---------------------------------------------------------------------------- global ASM_PFX(TempRamInitApi) ASM_PFX(TempRamInitApi): ; ; Check Parameter ; mov eax, [esp+4] cmp eax, 0 mov eax, 0x80000002 jz TempRamInitExit ; ; Set ECX/EDX to the bootloader temporary memory range ; mov ecx, [ASM_PFX(PcdGet32 (PcdTemporaryRamBase))] mov edx, ecx add edx, [ASM_PFX(PcdGet32 (PcdTemporaryRamSize))] sub edx, [ASM_PFX(PcdGet32 (PcdFspTemporaryRamSize))] ; EAX - error flag xor eax, eax TempRamInitExit: ret ;---------------------------------------------------------------------------- ; FspInit API ; ; This FSP API will perform the processor and chipset initialization. ; This API will not return. Instead, it transfers the control to the ; ContinuationFunc provided in the parameter. ; ;---------------------------------------------------------------------------- global ASM_PFX(FspInitApi) ASM_PFX(FspInitApi): mov eax, 1 jmp FspApiCommon ;---------------------------------------------------------------------------- ; FspMemoryInit API ; ; This FSP API is called after TempRamInit and initializes the memory. ; ;---------------------------------------------------------------------------- global ASM_PFX(FspMemoryInitApi) ASM_PFX(FspMemoryInitApi): ; ; Save stack address in ecx ; pushad mov ecx, esp ; ; Enable FSP STACK ; mov esp, [ASM_PFX(PcdGet32 (PcdTemporaryRamBase))] add esp, [ASM_PFX(PcdGet32 (PcdTemporaryRamSize))] push DATA_LEN_OF_MCUD ; Size of the data region push 0x4455434D ; Signature of the data region 'MCUD' push 0x00800000 ; Code size push 0xff800000 ; Code base push 0 ; Microcode size, 0, no ucode for Quark push 0 ; Microcode base, 0, no ucode for Quark ; ; Save API entry/exit timestamp into stack ; push DATA_LEN_OF_PER0 ; Size of the data region push 0x30524550 ; Signature of the data region 'PER0' xor edx, edx push edx xor eax, eax push eax rdtsc push edx push eax ; ; Terminator for the data on stack ; push 0 ; ; Restore stack address ; mov esp, ecx popad ; ; Call MemoryInit ; mov eax, 3 jmp FspApiCommon ;---------------------------------------------------------------------------- ; FspApiCommon API ; ; This is the FSP API common entry point to resume the FSP execution ; ;---------------------------------------------------------------------------- FspApiCommon: ; ; EAX holds the API index ; ; ; Stack must be ready ; push eax add esp, 4 cmp eax, [esp-4] jz FspApiCommonL0 mov eax, 0x80000003 jmp FspApiCommonExit FspApiCommonL0: ; ; Verify the calling condition ; pushad push dword [esp+(4*8)+4] ; push ApiParam push eax ; push ApiIdx call ASM_PFX(FspApiCallingCheck) add esp, 8 cmp eax, 0 jz FspApiCommonL1 mov [esp+(4*7)], eax popad ret FspApiCommonL1: popad cmp eax, 1 ; FspInit API jz FspApiCommonL2 cmp eax, 3 ; FspMemoryInit API jz FspApiCommonL2 call ASM_PFX(AsmGetFspInfoHeader) jmp ASM_PFX(Loader2PeiSwitchStack) FspApiCommonL2: ; ; FspInit and FspMemoryInit APIs, setup the initial stack frame ; ; ; Place holder to store the FspInfoHeader pointer ; push eax ; ; Update the FspInfoHeader pointer ; push eax call ASM_PFX(AsmGetFspInfoHeader) mov [esp+4], eax pop eax ; ; Create a Task Frame in the stack for the Boot Loader ; pushfd ; 2 pushf for 4 byte alignment cli pushad ; ; Reserve 8 bytes for IDT save/restore ; sub esp, 8 sidt [esp] ; ; Setup new FSP stack ; mov edi, esp mov esp, [ASM_PFX(PcdGet32(PcdTemporaryRamBase))] add esp, [ASM_PFX(PcdGet32(PcdTemporaryRamSize))] sub esp, (DATA_LEN_AT_STACK_TOP + 0x40) ; ; Pass the API Idx to SecStartup ; push eax ; ; Pass the BootLoader stack to SecStartup ; push edi ; ; Pass entry point of the PEI core ; call ASM_PFX(AsmGetFspBaseAddress) mov edi, eax add edi, [ASM_PFX(PcdGet32(PcdFspAreaSize))] sub edi, 0x20 add eax, [ds:edi] push eax ; ; Pass BFV into the PEI Core ; It uses relative address to calucate the actual boot FV base ; For FSP implementation with single FV, PcdFspBootFirmwareVolumeBase and ; PcdFspAreaBaseAddress are the same. For FSP with mulitple FVs, ; they are different. The code below can handle both cases. ; call ASM_PFX(AsmGetFspBaseAddress) mov edi, eax call ASM_PFX(GetBootFirmwareVolumeOffset) add eax, edi push eax ; ; Pass stack base and size into the PEI Core ; mov eax, [ASM_PFX(PcdGet32(PcdTemporaryRamBase))] add eax, [ASM_PFX(PcdGet32(PcdTemporaryRamSize))] sub eax, [ASM_PFX(PcdGet32(PcdFspTemporaryRamSize))] push eax push dword [ASM_PFX(PcdGet32(PcdFspTemporaryRamSize))] ; ; Pass Control into the PEI Core ; call ASM_PFX(SecStartup) add esp, 4 FspApiCommonExit: ret ;---------------------------------------------------------------------------- ; ; Procedure: _ModuleEntryPoint ; ; Input: None ; ; Output: None ; ; Destroys: Assume all registers ; ; Description: ; ; Transition to non-paged flat-model protected mode from a ; hard-coded GDT that provides exactly two descriptors. ; This is a bare bones transition to protected mode only ; used for a while in PEI and possibly DXE. ; ; After enabling protected mode, a far jump is executed to ; transfer to PEI using the newly loaded GDT. ; ; Return: None ; ;---------------------------------------------------------------------------- global ASM_PFX(_ModuleEntryPoint) ASM_PFX(_ModuleEntryPoint): jmp $ ; ; Reference the routines to get the linker to pull them in ; jmp ASM_PFX(TempRamInitApi) jmp ASM_PFX(FspInitApi) jmp ASM_PFX(TempRamExitApi) jmp ASM_PFX(FspSiliconInitApi) jmp ASM_PFX(NotifyPhaseApi)
.export div .include "utils/reg.inc" ; r0L - value ; r1L - divisor ; when finished gREG::r0H will contain the mod value .proc div DIV = REG::r0L; MOD = REG::r0H; DIVISOR = REG::r1L; stz MOD clc ldx #8 @loop: rol DIV rol MOD lda MOD sec sbc DIVISOR bcc @ignore ; carry clear indicates that MOD is less than DIVISOR sta MOD @ignore: dex bne @loop rol DIV rts .endproc
name "I/O Strign program" ; add your code here .model small db 30,?, 30 dup(' ') name db $,<' '> .data input_msg db 0ah,0dh,"your sring is:$" msg db 60 dup(?) ;60 place empty array outt db 0ah,0dh,"your string is:$" .code call main main proc mov ax,@data mov ds,ax lea dx,outt mov ah,09H int 21H mov si,offset msg input: ;take input from user mov ah,1H int 21H ;check for enter char and disply input msg if ture cmp al,13 je display ;move input char to memory mov [si],al inc si jmp input display: ;display interactive string lea dx,outt mov ah,09H int 21H ;put end char at the end of input string and load address to DI register mov [si],'$' mov di,offset msg ;print new line and set cruser at the start of the line mov dl,13 mov ah,2 int 21H mov dl,10 mov ah,2 int 21h again: cmp [di],'$' ;check for end of string je last cmp [di],32 ;check for space je next ;print current char to the prompt mov dl,[di] mov ah,2h int 21H inc di ;inc to next char in string jmp again next: mov dl,13 mov ah,2h int 21H mov dl,10 mov ah,2h int 21H inc di jmp again last: mov ah,4ch int 21h end ret
.include "defines.inc" .include "global.inc" .segment "BANK0" Stars2: .byte 16 ; number of OAM tile entries ; y+offset, tile number, palette & object attribute, x+offset ; code from NEXXT ; first quadrant .byte -48+64,$83,3|16, 16+64 .byte -24+64,$80,0|16,-32+64 .byte -16+64,$81,2|16, 32+64 .byte 16+64,$82,2|16,-16+64 .byte 32+64,$80,0|16, 0+64 ; second quadrant .byte -32+64,$82,2|16, 0+192 .byte 8+64,$82,3|16,-64+192 .byte 24+64,$83,3|16, 32+192 .byte 56+64,$80,0|16,-53+192 .byte 56+64,$82,2|16, 16+192 ; third quadrant .byte -48+192,$82,2|16, 32+64 .byte -32+192,$82,3|16,-32+64 .byte 24+192,$80,0|16, 48+64 .byte 32+192,$81,3|16, 0+64 ; fourth quadrant .byte -16+192,$81,3|16,-48+192 .byte 0+192,$82,2|16, 0+192 Stars1: .byte 8 ; first quadrant .byte -64+64,$80,0|16, 48+64 .byte -40+64,$80,0|16,-16+64 .byte 24+64,$80,2|16, 8+64 .byte 56+64,$80,0|16, 48+64 ; second quadrant .byte -24+64,$80,2|16, 48+192 .byte 24+64,$80,0|16,-24+192 .byte 40+64,$80,2|16,-40+192 ; third quadrant .byte -40+192,$80,0|16,-40+64 ; fourth quadrant .byte 0+192,$80,0|16, 8+192 ; initialize/update a metasprite ; temp_16_0: address of sprite data ; temp_8_0: num_hardware_sprites ; temp_8_1: x_offset ; temp_8_2: y_offset ; OAM_RAM_start: which OAM entry to start, saves as .proc load_sprite num_hardware_sprites := temp_8_0 x_offset:= temp_8_1 y_offset:= temp_8_2 ; first byte of metasprite is number of entries LDY #0 LDA (temp_16_0), y STA num_hardware_sprites INY LDX OAM_RAM_start : CLC LDA (temp_16_0), y ; sprite offset y ADC y_offset STA $0200, x INY INX LDA (temp_16_0), y ; sprite tile STA $0200, x INY INX LDA (temp_16_0), y ; sprite attribute STA $0200, x INY INX CLC LDA (temp_16_0), y ; sprite offset x ADC x_offset STA $0200, x INY INX DEC num_hardware_sprites BNE :- RTS .endproc
# Author: Leonardo Benitez # Date: 20/03/2019 # Brief: little calculator using floating point # Variables map # $f12: acumulator # $f11: temporary result # $f0: result from syscall read float # Coments # The user input is generally a float, but in case "sum" it was done with int for pedagogical purposes .data Smenu: .asciiz "\n\n------------------\nChoose an option:\n1)Show acumulator\n2)Clean acumulator\n3)Sum\n4)Subtraction\n5)Division\n6)Multiplication\n7)Exit program\n" SshowAC: .asciiz "\n\nThe acumulator value is: " ScleanAC: .asciiz "\n\nThe acumulator was clear" Ssum: .asciiz "\n\nEnter the number to sum with the acumulator: " Ssubb: .asciiz "\n\nEnter the number to subtract with the acumulator: " Sdivv: .asciiz "\n\nEnter the number to divide the acumulator by: " Smultt: .asciiz "\n\nEnter the number to multiply with the acumulator: " Sexit: .asciiz "\n\nI hope you enyoed the software, byebye." Sdef: .asciiz "\n\nInvalid option, sorry." Jtable: .word menu, showAC, cleanAC, sum, subb, divv, multt, exit .text menu: # Print header addi $v0, $zero, 4 # print string service la $a0, Smenu # service parameter syscall # Read awnser addi $v0, $zero, 5 # read integer service (result in $v0) syscall #check bounds ble $v0, $zero def # if read>=0, default addi $t0, $zero, 7 bgt $v0, $t0, def # if read>7, default #translate case la $t0, Jtable mul $t1, $v0, 4 add $t0, $t0, $t1 lw $t2, 0 ($t0) jr $t2 ## END OF MAIN LOOP ## showAC: # Print header addi $v0, $zero, 4 # print string service la $a0, SshowAC # service parameter syscall addi $v0, $zero, 2 # print float service syscall j menu cleanAC: # Print header addi $v0, $zero, 4 # print string service la $a0, ScleanAC # service parameter syscall mtc1 $zero, $f12 j menu sum: # Print header addi $v0, $zero, 4 # print string service la $a0, Ssum # service parameter syscall # Read awnser (integer) addi $v0, $zero, 5 # read integer service (result in $v0) syscall # sum imput mtc1 $v0, $f11 cvt.s.w $f11, $f11 add.s $f12, $f12, $f11 j menu subb: # Print header addi $v0, $zero, 4 # print string service la $a0, Ssubb # service parameter syscall # Read awnser addi $v0, $zero, 6 # read float service (result in $f0) syscall #operation sub.s $f12, $f12, $f0 j menu divv: # Print header addi $v0, $zero, 4 # print string service la $a0, Sdivv # service parameter syscall # Read awnser addi $v0, $zero, 6 # read float service (result in $f0) syscall #operation div.s $f12, $f12, $f0 j menu multt: # Print header addi $v0, $zero, 4 # print string service la $a0, Smultt # service parameter syscall # Read awnser addi $v0, $zero, 6 # read float service (result in $f0) syscall #operation mul.s $f12, $f12, $f0 j menu exit: # Print header addi $v0, $zero, 4 # print string service la $a0, Sexit # service parameter syscall addi $v0, $zero, 10 syscall def: # Print header addi $v0, $zero, 4 # print string service la $a0, Sdef # service parameter syscall j menu
/* * Copyright 2006-2016 zorba.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "stdafx.h" #include <iostream> #include <string> #include <zorba/internal/cxx_util.h> #include "util/mem_sizeof.h" using namespace std; using namespace zorba; /////////////////////////////////////////////////////////////////////////////// static int failures; static bool assert_true( char const *expr, int line, bool result ) { if ( !result ) { cout << "FAILED, line " << line << ": " << expr << endl; ++failures; } return result; } #define ASSERT_TRUE( EXPR ) assert_true( #EXPR, __LINE__, !!(EXPR) ) /////////////////////////////////////////////////////////////////////////////// static void test_int() { int i; ASSERT_TRUE( ztd::mem_sizeof( i ) == sizeof( i ) ); } /////////////////////////////////////////////////////////////////////////////// static void test_map_string_int() { typedef map<string,int> map_type; map_type m; string const key( "a" ); m[ key ] = 1; size_t const expected_size = sizeof( m ) + sizeof( map_type::value_type ) + key.capacity() + 1 + sizeof( void* ) * 2; ASSERT_TRUE( ztd::mem_sizeof( m ) == expected_size ); } /////////////////////////////////////////////////////////////////////////////// struct point { int x, y, z; }; static void test_pod() { point p; ASSERT_TRUE( ztd::mem_sizeof( p ) == sizeof( p ) ); } /////////////////////////////////////////////////////////////////////////////// static void test_pointer() { int *p = nullptr; ASSERT_TRUE( ztd::mem_sizeof( p ) == sizeof( p ) ); p = new int; ASSERT_TRUE( ztd::mem_sizeof( p ) == sizeof( p ) + sizeof( int ) ); delete p; } /////////////////////////////////////////////////////////////////////////////// template<class StringType> static void test_string_empty() { StringType const s; ASSERT_TRUE( ztd::mem_sizeof( s ) == sizeof( s ) + 1 ); } template<> void test_string_empty<zstring>() { zstring const s; ASSERT_TRUE( ztd::mem_sizeof( s ) == sizeof( s ) + 1 + sizeof( zstring::rep_type ) ); } template<class StringType> static void test_string_not_empty() { StringType const s( "hello" ); ASSERT_TRUE( ztd::mem_sizeof( s ) == sizeof( s ) + s.capacity() + 1 ); } template<> void test_string_not_empty<zstring>() { zstring const s( "hello" ); ASSERT_TRUE( ztd::mem_sizeof( s ) == sizeof( s ) + sizeof( zstring::rep_type ) + s.capacity() + 1 ); } /////////////////////////////////////////////////////////////////////////////// static void test_vector_int() { typedef vector<int> vector_type; vector_type v; v.push_back( 1 ); size_t const expected_size = sizeof( v ) + v.size() * sizeof( vector_type::value_type ) + (v.capacity() - v.size()) * sizeof( vector_type::value_type ); ASSERT_TRUE( ztd::mem_sizeof( v ) == expected_size ); } /////////////////////////////////////////////////////////////////////////////// struct my_base { virtual size_t alloc_size() const { return ztd::alloc_sizeof( b1_ ) + ztd::alloc_sizeof( b2_ ); } virtual size_t dynamic_size() const { return sizeof( *this ); } string b1_, b2_; }; struct my_derived : my_base { my_derived( string const &s ) : d1_( s ) { } size_t alloc_size() const { return my_base::alloc_size() + ztd::alloc_sizeof( d1_ ); } virtual size_t dynamic_size() const { return sizeof( *this ); } string d1_; }; static void test_base_empty() { my_base b; ASSERT_TRUE( ztd::mem_sizeof( b ) == sizeof( b ) + b.b1_.capacity() + 1 + b.b2_.capacity() + 1 ); } static void test_derived_not_empty() { string const s( "hello" ); my_derived d( s ); ASSERT_TRUE( ztd::mem_sizeof( d ) == sizeof( d ) + d.b1_.capacity() + 1 + d.b2_.capacity() + 1 + d.d1_.capacity() + 1 ); } /////////////////////////////////////////////////////////////////////////////// namespace zorba { namespace UnitTests { int test_mem_sizeof( int, char*[] ) { test_int(); test_pointer(); test_pod(); test_string_empty<string>(); test_string_not_empty<string>(); test_string_empty<zstring>(); test_string_not_empty<zstring>(); test_map_string_int(); test_vector_int(); test_base_empty(); test_derived_not_empty(); cout << failures << " test(s) failed\n"; return failures ? 1 : 0; } /////////////////////////////////////////////////////////////////////////////// } // namespace UnitTests } // namespace zorba /* vim:set et sw=2 ts=2: */
_mkdir: 檔案格式 elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 57 push %edi e: 56 push %esi f: 53 push %ebx 10: 51 push %ecx 11: bf 01 00 00 00 mov $0x1,%edi 16: 83 ec 08 sub $0x8,%esp 19: 8b 31 mov (%ecx),%esi 1b: 8b 59 04 mov 0x4(%ecx),%ebx 1e: 83 c3 04 add $0x4,%ebx int i; if(argc < 2){ 21: 83 fe 01 cmp $0x1,%esi 24: 7e 3e jle 64 <main+0x64> 26: 8d 76 00 lea 0x0(%esi),%esi 29: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi printf(2, "Usage: mkdir files...\n"); exit(); } for(i = 1; i < argc; i++){ if(mkdir(argv[i]) < 0){ 30: 83 ec 0c sub $0xc,%esp 33: ff 33 pushl (%ebx) 35: e8 f0 02 00 00 call 32a <mkdir> 3a: 83 c4 10 add $0x10,%esp 3d: 85 c0 test %eax,%eax 3f: 78 0f js 50 <main+0x50> if(argc < 2){ printf(2, "Usage: mkdir files...\n"); exit(); } for(i = 1; i < argc; i++){ 41: 83 c7 01 add $0x1,%edi 44: 83 c3 04 add $0x4,%ebx 47: 39 fe cmp %edi,%esi 49: 75 e5 jne 30 <main+0x30> printf(2, "mkdir: %s failed to create\n", argv[i]); break; } } exit(); 4b: e8 72 02 00 00 call 2c2 <exit> exit(); } for(i = 1; i < argc; i++){ if(mkdir(argv[i]) < 0){ printf(2, "mkdir: %s failed to create\n", argv[i]); 50: 50 push %eax 51: ff 33 pushl (%ebx) 53: 68 57 07 00 00 push $0x757 58: 6a 02 push $0x2 5a: e8 c1 03 00 00 call 420 <printf> break; 5f: 83 c4 10 add $0x10,%esp 62: eb e7 jmp 4b <main+0x4b> main(int argc, char *argv[]) { int i; if(argc < 2){ printf(2, "Usage: mkdir files...\n"); 64: 52 push %edx 65: 52 push %edx 66: 68 40 07 00 00 push $0x740 6b: 6a 02 push $0x2 6d: e8 ae 03 00 00 call 420 <printf> exit(); 72: e8 4b 02 00 00 call 2c2 <exit> 77: 66 90 xchg %ax,%ax 79: 66 90 xchg %ax,%ax 7b: 66 90 xchg %ax,%ax 7d: 66 90 xchg %ax,%ax 7f: 90 nop 00000080 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 80: 55 push %ebp 81: 89 e5 mov %esp,%ebp 83: 53 push %ebx 84: 8b 45 08 mov 0x8(%ebp),%eax 87: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) 8a: 89 c2 mov %eax,%edx 8c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 90: 83 c1 01 add $0x1,%ecx 93: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 97: 83 c2 01 add $0x1,%edx 9a: 84 db test %bl,%bl 9c: 88 5a ff mov %bl,-0x1(%edx) 9f: 75 ef jne 90 <strcpy+0x10> ; return os; } a1: 5b pop %ebx a2: 5d pop %ebp a3: c3 ret a4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi aa: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000000b0 <strcmp>: int strcmp(const char *p, const char *q) { b0: 55 push %ebp b1: 89 e5 mov %esp,%ebp b3: 56 push %esi b4: 53 push %ebx b5: 8b 55 08 mov 0x8(%ebp),%edx b8: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) bb: 0f b6 02 movzbl (%edx),%eax be: 0f b6 19 movzbl (%ecx),%ebx c1: 84 c0 test %al,%al c3: 75 1e jne e3 <strcmp+0x33> c5: eb 29 jmp f0 <strcmp+0x40> c7: 89 f6 mov %esi,%esi c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; d0: 83 c2 01 add $0x1,%edx } int strcmp(const char *p, const char *q) { while(*p && *p == *q) d3: 0f b6 02 movzbl (%edx),%eax p++, q++; d6: 8d 71 01 lea 0x1(%ecx),%esi } int strcmp(const char *p, const char *q) { while(*p && *p == *q) d9: 0f b6 59 01 movzbl 0x1(%ecx),%ebx dd: 84 c0 test %al,%al df: 74 0f je f0 <strcmp+0x40> e1: 89 f1 mov %esi,%ecx e3: 38 d8 cmp %bl,%al e5: 74 e9 je d0 <strcmp+0x20> p++, q++; return (uchar)*p - (uchar)*q; e7: 29 d8 sub %ebx,%eax } e9: 5b pop %ebx ea: 5e pop %esi eb: 5d pop %ebp ec: c3 ret ed: 8d 76 00 lea 0x0(%esi),%esi } int strcmp(const char *p, const char *q) { while(*p && *p == *q) f0: 31 c0 xor %eax,%eax p++, q++; return (uchar)*p - (uchar)*q; f2: 29 d8 sub %ebx,%eax } f4: 5b pop %ebx f5: 5e pop %esi f6: 5d pop %ebp f7: c3 ret f8: 90 nop f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000100 <strlen>: uint strlen(char *s) { 100: 55 push %ebp 101: 89 e5 mov %esp,%ebp 103: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 106: 80 39 00 cmpb $0x0,(%ecx) 109: 74 12 je 11d <strlen+0x1d> 10b: 31 d2 xor %edx,%edx 10d: 8d 76 00 lea 0x0(%esi),%esi 110: 83 c2 01 add $0x1,%edx 113: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 117: 89 d0 mov %edx,%eax 119: 75 f5 jne 110 <strlen+0x10> ; return n; } 11b: 5d pop %ebp 11c: c3 ret uint strlen(char *s) { int n; for(n = 0; s[n]; n++) 11d: 31 c0 xor %eax,%eax ; return n; } 11f: 5d pop %ebp 120: c3 ret 121: eb 0d jmp 130 <memset> 123: 90 nop 124: 90 nop 125: 90 nop 126: 90 nop 127: 90 nop 128: 90 nop 129: 90 nop 12a: 90 nop 12b: 90 nop 12c: 90 nop 12d: 90 nop 12e: 90 nop 12f: 90 nop 00000130 <memset>: void* memset(void *dst, int c, uint n) { 130: 55 push %ebp 131: 89 e5 mov %esp,%ebp 133: 57 push %edi 134: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 137: 8b 4d 10 mov 0x10(%ebp),%ecx 13a: 8b 45 0c mov 0xc(%ebp),%eax 13d: 89 d7 mov %edx,%edi 13f: fc cld 140: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 142: 89 d0 mov %edx,%eax 144: 5f pop %edi 145: 5d pop %ebp 146: c3 ret 147: 89 f6 mov %esi,%esi 149: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000150 <strchr>: char* strchr(const char *s, char c) { 150: 55 push %ebp 151: 89 e5 mov %esp,%ebp 153: 53 push %ebx 154: 8b 45 08 mov 0x8(%ebp),%eax 157: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 15a: 0f b6 10 movzbl (%eax),%edx 15d: 84 d2 test %dl,%dl 15f: 74 1d je 17e <strchr+0x2e> if(*s == c) 161: 38 d3 cmp %dl,%bl 163: 89 d9 mov %ebx,%ecx 165: 75 0d jne 174 <strchr+0x24> 167: eb 17 jmp 180 <strchr+0x30> 169: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 170: 38 ca cmp %cl,%dl 172: 74 0c je 180 <strchr+0x30> } char* strchr(const char *s, char c) { for(; *s; s++) 174: 83 c0 01 add $0x1,%eax 177: 0f b6 10 movzbl (%eax),%edx 17a: 84 d2 test %dl,%dl 17c: 75 f2 jne 170 <strchr+0x20> if(*s == c) return (char*)s; return 0; 17e: 31 c0 xor %eax,%eax } 180: 5b pop %ebx 181: 5d pop %ebp 182: c3 ret 183: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 189: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000190 <gets>: char* gets(char *buf, int max) { 190: 55 push %ebp 191: 89 e5 mov %esp,%ebp 193: 57 push %edi 194: 56 push %esi 195: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 196: 31 f6 xor %esi,%esi cc = read(0, &c, 1); 198: 8d 7d e7 lea -0x19(%ebp),%edi return 0; } char* gets(char *buf, int max) { 19b: 83 ec 1c sub $0x1c,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 19e: eb 29 jmp 1c9 <gets+0x39> cc = read(0, &c, 1); 1a0: 83 ec 04 sub $0x4,%esp 1a3: 6a 01 push $0x1 1a5: 57 push %edi 1a6: 6a 00 push $0x0 1a8: e8 2d 01 00 00 call 2da <read> if(cc < 1) 1ad: 83 c4 10 add $0x10,%esp 1b0: 85 c0 test %eax,%eax 1b2: 7e 1d jle 1d1 <gets+0x41> break; buf[i++] = c; 1b4: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 1b8: 8b 55 08 mov 0x8(%ebp),%edx 1bb: 89 de mov %ebx,%esi if(c == '\n' || c == '\r') 1bd: 3c 0a cmp $0xa,%al for(i=0; i+1 < max; ){ cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; 1bf: 88 44 1a ff mov %al,-0x1(%edx,%ebx,1) if(c == '\n' || c == '\r') 1c3: 74 1b je 1e0 <gets+0x50> 1c5: 3c 0d cmp $0xd,%al 1c7: 74 17 je 1e0 <gets+0x50> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1c9: 8d 5e 01 lea 0x1(%esi),%ebx 1cc: 3b 5d 0c cmp 0xc(%ebp),%ebx 1cf: 7c cf jl 1a0 <gets+0x10> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1d1: 8b 45 08 mov 0x8(%ebp),%eax 1d4: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 1d8: 8d 65 f4 lea -0xc(%ebp),%esp 1db: 5b pop %ebx 1dc: 5e pop %esi 1dd: 5f pop %edi 1de: 5d pop %ebp 1df: c3 ret break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1e0: 8b 45 08 mov 0x8(%ebp),%eax gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1e3: 89 de mov %ebx,%esi break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1e5: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 1e9: 8d 65 f4 lea -0xc(%ebp),%esp 1ec: 5b pop %ebx 1ed: 5e pop %esi 1ee: 5f pop %edi 1ef: 5d pop %ebp 1f0: c3 ret 1f1: eb 0d jmp 200 <stat> 1f3: 90 nop 1f4: 90 nop 1f5: 90 nop 1f6: 90 nop 1f7: 90 nop 1f8: 90 nop 1f9: 90 nop 1fa: 90 nop 1fb: 90 nop 1fc: 90 nop 1fd: 90 nop 1fe: 90 nop 1ff: 90 nop 00000200 <stat>: int stat(char *n, struct stat *st) { 200: 55 push %ebp 201: 89 e5 mov %esp,%ebp 203: 56 push %esi 204: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 205: 83 ec 08 sub $0x8,%esp 208: 6a 00 push $0x0 20a: ff 75 08 pushl 0x8(%ebp) 20d: e8 f0 00 00 00 call 302 <open> if(fd < 0) 212: 83 c4 10 add $0x10,%esp 215: 85 c0 test %eax,%eax 217: 78 27 js 240 <stat+0x40> return -1; r = fstat(fd, st); 219: 83 ec 08 sub $0x8,%esp 21c: ff 75 0c pushl 0xc(%ebp) 21f: 89 c3 mov %eax,%ebx 221: 50 push %eax 222: e8 f3 00 00 00 call 31a <fstat> 227: 89 c6 mov %eax,%esi close(fd); 229: 89 1c 24 mov %ebx,(%esp) 22c: e8 b9 00 00 00 call 2ea <close> return r; 231: 83 c4 10 add $0x10,%esp 234: 89 f0 mov %esi,%eax } 236: 8d 65 f8 lea -0x8(%ebp),%esp 239: 5b pop %ebx 23a: 5e pop %esi 23b: 5d pop %ebp 23c: c3 ret 23d: 8d 76 00 lea 0x0(%esi),%esi int fd; int r; fd = open(n, O_RDONLY); if(fd < 0) return -1; 240: b8 ff ff ff ff mov $0xffffffff,%eax 245: eb ef jmp 236 <stat+0x36> 247: 89 f6 mov %esi,%esi 249: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000250 <atoi>: return r; } int atoi(const char *s) { 250: 55 push %ebp 251: 89 e5 mov %esp,%ebp 253: 53 push %ebx 254: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 257: 0f be 11 movsbl (%ecx),%edx 25a: 8d 42 d0 lea -0x30(%edx),%eax 25d: 3c 09 cmp $0x9,%al 25f: b8 00 00 00 00 mov $0x0,%eax 264: 77 1f ja 285 <atoi+0x35> 266: 8d 76 00 lea 0x0(%esi),%esi 269: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 270: 8d 04 80 lea (%eax,%eax,4),%eax 273: 83 c1 01 add $0x1,%ecx 276: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 27a: 0f be 11 movsbl (%ecx),%edx 27d: 8d 5a d0 lea -0x30(%edx),%ebx 280: 80 fb 09 cmp $0x9,%bl 283: 76 eb jbe 270 <atoi+0x20> n = n*10 + *s++ - '0'; return n; } 285: 5b pop %ebx 286: 5d pop %ebp 287: c3 ret 288: 90 nop 289: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000290 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 290: 55 push %ebp 291: 89 e5 mov %esp,%ebp 293: 56 push %esi 294: 53 push %ebx 295: 8b 5d 10 mov 0x10(%ebp),%ebx 298: 8b 45 08 mov 0x8(%ebp),%eax 29b: 8b 75 0c mov 0xc(%ebp),%esi char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 29e: 85 db test %ebx,%ebx 2a0: 7e 14 jle 2b6 <memmove+0x26> 2a2: 31 d2 xor %edx,%edx 2a4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 2a8: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 2ac: 88 0c 10 mov %cl,(%eax,%edx,1) 2af: 83 c2 01 add $0x1,%edx { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 2b2: 39 da cmp %ebx,%edx 2b4: 75 f2 jne 2a8 <memmove+0x18> *dst++ = *src++; return vdst; } 2b6: 5b pop %ebx 2b7: 5e pop %esi 2b8: 5d pop %ebp 2b9: c3 ret 000002ba <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 2ba: b8 01 00 00 00 mov $0x1,%eax 2bf: cd 40 int $0x40 2c1: c3 ret 000002c2 <exit>: SYSCALL(exit) 2c2: b8 02 00 00 00 mov $0x2,%eax 2c7: cd 40 int $0x40 2c9: c3 ret 000002ca <wait>: SYSCALL(wait) 2ca: b8 03 00 00 00 mov $0x3,%eax 2cf: cd 40 int $0x40 2d1: c3 ret 000002d2 <pipe>: SYSCALL(pipe) 2d2: b8 04 00 00 00 mov $0x4,%eax 2d7: cd 40 int $0x40 2d9: c3 ret 000002da <read>: SYSCALL(read) 2da: b8 05 00 00 00 mov $0x5,%eax 2df: cd 40 int $0x40 2e1: c3 ret 000002e2 <write>: SYSCALL(write) 2e2: b8 10 00 00 00 mov $0x10,%eax 2e7: cd 40 int $0x40 2e9: c3 ret 000002ea <close>: SYSCALL(close) 2ea: b8 15 00 00 00 mov $0x15,%eax 2ef: cd 40 int $0x40 2f1: c3 ret 000002f2 <kill>: SYSCALL(kill) 2f2: b8 06 00 00 00 mov $0x6,%eax 2f7: cd 40 int $0x40 2f9: c3 ret 000002fa <exec>: SYSCALL(exec) 2fa: b8 07 00 00 00 mov $0x7,%eax 2ff: cd 40 int $0x40 301: c3 ret 00000302 <open>: SYSCALL(open) 302: b8 0f 00 00 00 mov $0xf,%eax 307: cd 40 int $0x40 309: c3 ret 0000030a <mknod>: SYSCALL(mknod) 30a: b8 11 00 00 00 mov $0x11,%eax 30f: cd 40 int $0x40 311: c3 ret 00000312 <unlink>: SYSCALL(unlink) 312: b8 12 00 00 00 mov $0x12,%eax 317: cd 40 int $0x40 319: c3 ret 0000031a <fstat>: SYSCALL(fstat) 31a: b8 08 00 00 00 mov $0x8,%eax 31f: cd 40 int $0x40 321: c3 ret 00000322 <link>: SYSCALL(link) 322: b8 13 00 00 00 mov $0x13,%eax 327: cd 40 int $0x40 329: c3 ret 0000032a <mkdir>: SYSCALL(mkdir) 32a: b8 14 00 00 00 mov $0x14,%eax 32f: cd 40 int $0x40 331: c3 ret 00000332 <chdir>: SYSCALL(chdir) 332: b8 09 00 00 00 mov $0x9,%eax 337: cd 40 int $0x40 339: c3 ret 0000033a <dup>: SYSCALL(dup) 33a: b8 0a 00 00 00 mov $0xa,%eax 33f: cd 40 int $0x40 341: c3 ret 00000342 <getpid>: SYSCALL(getpid) 342: b8 0b 00 00 00 mov $0xb,%eax 347: cd 40 int $0x40 349: c3 ret 0000034a <sbrk>: SYSCALL(sbrk) 34a: b8 0c 00 00 00 mov $0xc,%eax 34f: cd 40 int $0x40 351: c3 ret 00000352 <sleep>: SYSCALL(sleep) 352: b8 0d 00 00 00 mov $0xd,%eax 357: cd 40 int $0x40 359: c3 ret 0000035a <uptime>: SYSCALL(uptime) 35a: b8 0e 00 00 00 mov $0xe,%eax 35f: cd 40 int $0x40 361: c3 ret 00000362 <cps>: SYSCALL(cps) 362: b8 16 00 00 00 mov $0x16,%eax 367: cd 40 int $0x40 369: c3 ret 0000036a <chpr>: SYSCALL(chpr) 36a: b8 17 00 00 00 mov $0x17,%eax 36f: cd 40 int $0x40 371: c3 ret 372: 66 90 xchg %ax,%ax 374: 66 90 xchg %ax,%ax 376: 66 90 xchg %ax,%ax 378: 66 90 xchg %ax,%ax 37a: 66 90 xchg %ax,%ax 37c: 66 90 xchg %ax,%ax 37e: 66 90 xchg %ax,%ax 00000380 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 380: 55 push %ebp 381: 89 e5 mov %esp,%ebp 383: 57 push %edi 384: 56 push %esi 385: 53 push %ebx 386: 89 c6 mov %eax,%esi 388: 83 ec 3c sub $0x3c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 38b: 8b 5d 08 mov 0x8(%ebp),%ebx 38e: 85 db test %ebx,%ebx 390: 74 7e je 410 <printint+0x90> 392: 89 d0 mov %edx,%eax 394: c1 e8 1f shr $0x1f,%eax 397: 84 c0 test %al,%al 399: 74 75 je 410 <printint+0x90> neg = 1; x = -xx; 39b: 89 d0 mov %edx,%eax int i, neg; uint x; neg = 0; if(sgn && xx < 0){ neg = 1; 39d: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) x = -xx; 3a4: f7 d8 neg %eax 3a6: 89 75 c0 mov %esi,-0x40(%ebp) } else { x = xx; } i = 0; 3a9: 31 ff xor %edi,%edi 3ab: 8d 5d d7 lea -0x29(%ebp),%ebx 3ae: 89 ce mov %ecx,%esi 3b0: eb 08 jmp 3ba <printint+0x3a> 3b2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi do{ buf[i++] = digits[x % base]; 3b8: 89 cf mov %ecx,%edi 3ba: 31 d2 xor %edx,%edx 3bc: 8d 4f 01 lea 0x1(%edi),%ecx 3bf: f7 f6 div %esi 3c1: 0f b6 92 7c 07 00 00 movzbl 0x77c(%edx),%edx }while((x /= base) != 0); 3c8: 85 c0 test %eax,%eax x = xx; } i = 0; do{ buf[i++] = digits[x % base]; 3ca: 88 14 0b mov %dl,(%ebx,%ecx,1) }while((x /= base) != 0); 3cd: 75 e9 jne 3b8 <printint+0x38> if(neg) 3cf: 8b 45 c4 mov -0x3c(%ebp),%eax 3d2: 8b 75 c0 mov -0x40(%ebp),%esi 3d5: 85 c0 test %eax,%eax 3d7: 74 08 je 3e1 <printint+0x61> buf[i++] = '-'; 3d9: c6 44 0d d8 2d movb $0x2d,-0x28(%ebp,%ecx,1) 3de: 8d 4f 02 lea 0x2(%edi),%ecx 3e1: 8d 7c 0d d7 lea -0x29(%ebp,%ecx,1),%edi 3e5: 8d 76 00 lea 0x0(%esi),%esi 3e8: 0f b6 07 movzbl (%edi),%eax #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 3eb: 83 ec 04 sub $0x4,%esp 3ee: 83 ef 01 sub $0x1,%edi 3f1: 6a 01 push $0x1 3f3: 53 push %ebx 3f4: 56 push %esi 3f5: 88 45 d7 mov %al,-0x29(%ebp) 3f8: e8 e5 fe ff ff call 2e2 <write> buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 3fd: 83 c4 10 add $0x10,%esp 400: 39 df cmp %ebx,%edi 402: 75 e4 jne 3e8 <printint+0x68> putc(fd, buf[i]); } 404: 8d 65 f4 lea -0xc(%ebp),%esp 407: 5b pop %ebx 408: 5e pop %esi 409: 5f pop %edi 40a: 5d pop %ebp 40b: c3 ret 40c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; if(sgn && xx < 0){ neg = 1; x = -xx; } else { x = xx; 410: 89 d0 mov %edx,%eax static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 412: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 419: eb 8b jmp 3a6 <printint+0x26> 41b: 90 nop 41c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00000420 <printf>: } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 420: 55 push %ebp 421: 89 e5 mov %esp,%ebp 423: 57 push %edi 424: 56 push %esi 425: 53 push %ebx int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 426: 8d 45 10 lea 0x10(%ebp),%eax } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 429: 83 ec 2c sub $0x2c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 42c: 8b 75 0c mov 0xc(%ebp),%esi } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 42f: 8b 7d 08 mov 0x8(%ebp),%edi int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 432: 89 45 d0 mov %eax,-0x30(%ebp) 435: 0f b6 1e movzbl (%esi),%ebx 438: 83 c6 01 add $0x1,%esi 43b: 84 db test %bl,%bl 43d: 0f 84 b0 00 00 00 je 4f3 <printf+0xd3> 443: 31 d2 xor %edx,%edx 445: eb 39 jmp 480 <printf+0x60> 447: 89 f6 mov %esi,%esi 449: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 450: 83 f8 25 cmp $0x25,%eax 453: 89 55 d4 mov %edx,-0x2c(%ebp) state = '%'; 456: ba 25 00 00 00 mov $0x25,%edx state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 45b: 74 18 je 475 <printf+0x55> #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 45d: 8d 45 e2 lea -0x1e(%ebp),%eax 460: 83 ec 04 sub $0x4,%esp 463: 88 5d e2 mov %bl,-0x1e(%ebp) 466: 6a 01 push $0x1 468: 50 push %eax 469: 57 push %edi 46a: e8 73 fe ff ff call 2e2 <write> 46f: 8b 55 d4 mov -0x2c(%ebp),%edx 472: 83 c4 10 add $0x10,%esp 475: 83 c6 01 add $0x1,%esi int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 478: 0f b6 5e ff movzbl -0x1(%esi),%ebx 47c: 84 db test %bl,%bl 47e: 74 73 je 4f3 <printf+0xd3> c = fmt[i] & 0xff; if(state == 0){ 480: 85 d2 test %edx,%edx uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; 482: 0f be cb movsbl %bl,%ecx 485: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 488: 74 c6 je 450 <printf+0x30> if(c == '%'){ state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 48a: 83 fa 25 cmp $0x25,%edx 48d: 75 e6 jne 475 <printf+0x55> if(c == 'd'){ 48f: 83 f8 64 cmp $0x64,%eax 492: 0f 84 f8 00 00 00 je 590 <printf+0x170> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 498: 81 e1 f7 00 00 00 and $0xf7,%ecx 49e: 83 f9 70 cmp $0x70,%ecx 4a1: 74 5d je 500 <printf+0xe0> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 4a3: 83 f8 73 cmp $0x73,%eax 4a6: 0f 84 84 00 00 00 je 530 <printf+0x110> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 4ac: 83 f8 63 cmp $0x63,%eax 4af: 0f 84 ea 00 00 00 je 59f <printf+0x17f> putc(fd, *ap); ap++; } else if(c == '%'){ 4b5: 83 f8 25 cmp $0x25,%eax 4b8: 0f 84 c2 00 00 00 je 580 <printf+0x160> #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 4be: 8d 45 e7 lea -0x19(%ebp),%eax 4c1: 83 ec 04 sub $0x4,%esp 4c4: c6 45 e7 25 movb $0x25,-0x19(%ebp) 4c8: 6a 01 push $0x1 4ca: 50 push %eax 4cb: 57 push %edi 4cc: e8 11 fe ff ff call 2e2 <write> 4d1: 83 c4 0c add $0xc,%esp 4d4: 8d 45 e6 lea -0x1a(%ebp),%eax 4d7: 88 5d e6 mov %bl,-0x1a(%ebp) 4da: 6a 01 push $0x1 4dc: 50 push %eax 4dd: 57 push %edi 4de: 83 c6 01 add $0x1,%esi 4e1: e8 fc fd ff ff call 2e2 <write> int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 4e6: 0f b6 5e ff movzbl -0x1(%esi),%ebx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 4ea: 83 c4 10 add $0x10,%esp } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 4ed: 31 d2 xor %edx,%edx int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 4ef: 84 db test %bl,%bl 4f1: 75 8d jne 480 <printf+0x60> putc(fd, c); } state = 0; } } } 4f3: 8d 65 f4 lea -0xc(%ebp),%esp 4f6: 5b pop %ebx 4f7: 5e pop %esi 4f8: 5f pop %edi 4f9: 5d pop %ebp 4fa: c3 ret 4fb: 90 nop 4fc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); 500: 83 ec 0c sub $0xc,%esp 503: b9 10 00 00 00 mov $0x10,%ecx 508: 6a 00 push $0x0 50a: 8b 5d d0 mov -0x30(%ebp),%ebx 50d: 89 f8 mov %edi,%eax 50f: 8b 13 mov (%ebx),%edx 511: e8 6a fe ff ff call 380 <printint> ap++; 516: 89 d8 mov %ebx,%eax 518: 83 c4 10 add $0x10,%esp } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 51b: 31 d2 xor %edx,%edx if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); ap++; 51d: 83 c0 04 add $0x4,%eax 520: 89 45 d0 mov %eax,-0x30(%ebp) 523: e9 4d ff ff ff jmp 475 <printf+0x55> 528: 90 nop 529: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi } else if(c == 's'){ s = (char*)*ap; 530: 8b 45 d0 mov -0x30(%ebp),%eax 533: 8b 18 mov (%eax),%ebx ap++; 535: 83 c0 04 add $0x4,%eax 538: 89 45 d0 mov %eax,-0x30(%ebp) if(s == 0) s = "(null)"; 53b: b8 73 07 00 00 mov $0x773,%eax 540: 85 db test %ebx,%ebx 542: 0f 44 d8 cmove %eax,%ebx while(*s != 0){ 545: 0f b6 03 movzbl (%ebx),%eax 548: 84 c0 test %al,%al 54a: 74 23 je 56f <printf+0x14f> 54c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 550: 88 45 e3 mov %al,-0x1d(%ebp) #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 553: 8d 45 e3 lea -0x1d(%ebp),%eax 556: 83 ec 04 sub $0x4,%esp 559: 6a 01 push $0x1 ap++; if(s == 0) s = "(null)"; while(*s != 0){ putc(fd, *s); s++; 55b: 83 c3 01 add $0x1,%ebx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 55e: 50 push %eax 55f: 57 push %edi 560: e8 7d fd ff ff call 2e2 <write> } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 565: 0f b6 03 movzbl (%ebx),%eax 568: 83 c4 10 add $0x10,%esp 56b: 84 c0 test %al,%al 56d: 75 e1 jne 550 <printf+0x130> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 56f: 31 d2 xor %edx,%edx 571: e9 ff fe ff ff jmp 475 <printf+0x55> 576: 8d 76 00 lea 0x0(%esi),%esi 579: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 580: 83 ec 04 sub $0x4,%esp 583: 88 5d e5 mov %bl,-0x1b(%ebp) 586: 8d 45 e5 lea -0x1b(%ebp),%eax 589: 6a 01 push $0x1 58b: e9 4c ff ff ff jmp 4dc <printf+0xbc> } else { putc(fd, c); } } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); 590: 83 ec 0c sub $0xc,%esp 593: b9 0a 00 00 00 mov $0xa,%ecx 598: 6a 01 push $0x1 59a: e9 6b ff ff ff jmp 50a <printf+0xea> 59f: 8b 5d d0 mov -0x30(%ebp),%ebx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 5a2: 83 ec 04 sub $0x4,%esp 5a5: 8b 03 mov (%ebx),%eax 5a7: 6a 01 push $0x1 5a9: 88 45 e4 mov %al,-0x1c(%ebp) 5ac: 8d 45 e4 lea -0x1c(%ebp),%eax 5af: 50 push %eax 5b0: 57 push %edi 5b1: e8 2c fd ff ff call 2e2 <write> 5b6: e9 5b ff ff ff jmp 516 <printf+0xf6> 5bb: 66 90 xchg %ax,%ax 5bd: 66 90 xchg %ax,%ax 5bf: 90 nop 000005c0 <free>: static Header base; static Header *freep; void free(void *ap) { 5c0: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5c1: a1 20 0a 00 00 mov 0xa20,%eax static Header base; static Header *freep; void free(void *ap) { 5c6: 89 e5 mov %esp,%ebp 5c8: 57 push %edi 5c9: 56 push %esi 5ca: 53 push %ebx 5cb: 8b 5d 08 mov 0x8(%ebp),%ebx Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5ce: 8b 10 mov (%eax),%edx void free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; 5d0: 8d 4b f8 lea -0x8(%ebx),%ecx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5d3: 39 c8 cmp %ecx,%eax 5d5: 73 19 jae 5f0 <free+0x30> 5d7: 89 f6 mov %esi,%esi 5d9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 5e0: 39 d1 cmp %edx,%ecx 5e2: 72 1c jb 600 <free+0x40> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5e4: 39 d0 cmp %edx,%eax 5e6: 73 18 jae 600 <free+0x40> static Header base; static Header *freep; void free(void *ap) { 5e8: 89 d0 mov %edx,%eax Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5ea: 39 c8 cmp %ecx,%eax if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5ec: 8b 10 mov (%eax),%edx free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5ee: 72 f0 jb 5e0 <free+0x20> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5f0: 39 d0 cmp %edx,%eax 5f2: 72 f4 jb 5e8 <free+0x28> 5f4: 39 d1 cmp %edx,%ecx 5f6: 73 f0 jae 5e8 <free+0x28> 5f8: 90 nop 5f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi break; if(bp + bp->s.size == p->s.ptr){ 600: 8b 73 fc mov -0x4(%ebx),%esi 603: 8d 3c f1 lea (%ecx,%esi,8),%edi 606: 39 d7 cmp %edx,%edi 608: 74 19 je 623 <free+0x63> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 60a: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 60d: 8b 50 04 mov 0x4(%eax),%edx 610: 8d 34 d0 lea (%eax,%edx,8),%esi 613: 39 f1 cmp %esi,%ecx 615: 74 23 je 63a <free+0x7a> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 617: 89 08 mov %ecx,(%eax) freep = p; 619: a3 20 0a 00 00 mov %eax,0xa20 } 61e: 5b pop %ebx 61f: 5e pop %esi 620: 5f pop %edi 621: 5d pop %ebp 622: c3 ret bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ bp->s.size += p->s.ptr->s.size; 623: 03 72 04 add 0x4(%edx),%esi 626: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 629: 8b 10 mov (%eax),%edx 62b: 8b 12 mov (%edx),%edx 62d: 89 53 f8 mov %edx,-0x8(%ebx) } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ 630: 8b 50 04 mov 0x4(%eax),%edx 633: 8d 34 d0 lea (%eax,%edx,8),%esi 636: 39 f1 cmp %esi,%ecx 638: 75 dd jne 617 <free+0x57> p->s.size += bp->s.size; 63a: 03 53 fc add -0x4(%ebx),%edx p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; freep = p; 63d: a3 20 0a 00 00 mov %eax,0xa20 bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ p->s.size += bp->s.size; 642: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 645: 8b 53 f8 mov -0x8(%ebx),%edx 648: 89 10 mov %edx,(%eax) } else p->s.ptr = bp; freep = p; } 64a: 5b pop %ebx 64b: 5e pop %esi 64c: 5f pop %edi 64d: 5d pop %ebp 64e: c3 ret 64f: 90 nop 00000650 <malloc>: return freep; } void* malloc(uint nbytes) { 650: 55 push %ebp 651: 89 e5 mov %esp,%ebp 653: 57 push %edi 654: 56 push %esi 655: 53 push %ebx 656: 83 ec 0c sub $0xc,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 659: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 65c: 8b 15 20 0a 00 00 mov 0xa20,%edx malloc(uint nbytes) { Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 662: 8d 78 07 lea 0x7(%eax),%edi 665: c1 ef 03 shr $0x3,%edi 668: 83 c7 01 add $0x1,%edi if((prevp = freep) == 0){ 66b: 85 d2 test %edx,%edx 66d: 0f 84 a3 00 00 00 je 716 <malloc+0xc6> 673: 8b 02 mov (%edx),%eax 675: 8b 48 04 mov 0x4(%eax),%ecx base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 678: 39 cf cmp %ecx,%edi 67a: 76 74 jbe 6f0 <malloc+0xa0> 67c: 81 ff 00 10 00 00 cmp $0x1000,%edi 682: be 00 10 00 00 mov $0x1000,%esi 687: 8d 1c fd 00 00 00 00 lea 0x0(,%edi,8),%ebx 68e: 0f 43 f7 cmovae %edi,%esi 691: ba 00 80 00 00 mov $0x8000,%edx 696: 81 ff ff 0f 00 00 cmp $0xfff,%edi 69c: 0f 46 da cmovbe %edx,%ebx 69f: eb 10 jmp 6b1 <malloc+0x61> 6a1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 6a8: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 6aa: 8b 48 04 mov 0x4(%eax),%ecx 6ad: 39 cf cmp %ecx,%edi 6af: 76 3f jbe 6f0 <malloc+0xa0> p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 6b1: 39 05 20 0a 00 00 cmp %eax,0xa20 6b7: 89 c2 mov %eax,%edx 6b9: 75 ed jne 6a8 <malloc+0x58> char *p; Header *hp; if(nu < 4096) nu = 4096; p = sbrk(nu * sizeof(Header)); 6bb: 83 ec 0c sub $0xc,%esp 6be: 53 push %ebx 6bf: e8 86 fc ff ff call 34a <sbrk> if(p == (char*)-1) 6c4: 83 c4 10 add $0x10,%esp 6c7: 83 f8 ff cmp $0xffffffff,%eax 6ca: 74 1c je 6e8 <malloc+0x98> return 0; hp = (Header*)p; hp->s.size = nu; 6cc: 89 70 04 mov %esi,0x4(%eax) free((void*)(hp + 1)); 6cf: 83 ec 0c sub $0xc,%esp 6d2: 83 c0 08 add $0x8,%eax 6d5: 50 push %eax 6d6: e8 e5 fe ff ff call 5c0 <free> return freep; 6db: 8b 15 20 0a 00 00 mov 0xa20,%edx } freep = prevp; return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) 6e1: 83 c4 10 add $0x10,%esp 6e4: 85 d2 test %edx,%edx 6e6: 75 c0 jne 6a8 <malloc+0x58> return 0; 6e8: 31 c0 xor %eax,%eax 6ea: eb 1c jmp 708 <malloc+0xb8> 6ec: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ if(p->s.size == nunits) 6f0: 39 cf cmp %ecx,%edi 6f2: 74 1c je 710 <malloc+0xc0> prevp->s.ptr = p->s.ptr; else { p->s.size -= nunits; 6f4: 29 f9 sub %edi,%ecx 6f6: 89 48 04 mov %ecx,0x4(%eax) p += p->s.size; 6f9: 8d 04 c8 lea (%eax,%ecx,8),%eax p->s.size = nunits; 6fc: 89 78 04 mov %edi,0x4(%eax) } freep = prevp; 6ff: 89 15 20 0a 00 00 mov %edx,0xa20 return (void*)(p + 1); 705: 83 c0 08 add $0x8,%eax } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } } 708: 8d 65 f4 lea -0xc(%ebp),%esp 70b: 5b pop %ebx 70c: 5e pop %esi 70d: 5f pop %edi 70e: 5d pop %ebp 70f: c3 ret base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ if(p->s.size == nunits) prevp->s.ptr = p->s.ptr; 710: 8b 08 mov (%eax),%ecx 712: 89 0a mov %ecx,(%edx) 714: eb e9 jmp 6ff <malloc+0xaf> Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; 716: c7 05 20 0a 00 00 24 movl $0xa24,0xa20 71d: 0a 00 00 720: c7 05 24 0a 00 00 24 movl $0xa24,0xa24 727: 0a 00 00 base.s.size = 0; 72a: b8 24 0a 00 00 mov $0xa24,%eax 72f: c7 05 28 0a 00 00 00 movl $0x0,0xa28 736: 00 00 00 739: e9 3e ff ff ff jmp 67c <malloc+0x2c>
/* mmap_trie_concurrency_test.cc Jeremy Barnes, 7 September 2011 Copyright (c) 2011 Datacratic. All rights reserved. Test for concurrency with the memory mapped trie. */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include "mmap_test.h" #include "mmap/memory_tracker.h" #include "mmap/mmap_file.h" #include "mmap/mmap_trie.h" #include "mmap/mmap_trie_node.h" #include "mmap/mmap_trie_terminal_nodes.h" #include "mmap/mmap_trie_sparse_nodes.h" #include "mmap/mmap_trie_binary_nodes.h" #include "mmap/mmap_trie_compressed_nodes.h" #include "mmap/mmap_trie_large_key_nodes.h" #include "jml/arch/atomic_ops.h" #include "jml/utils/smart_ptr_utils.h" #include "jml/utils/string_functions.h" #include "jml/arch/atomic_ops.h" #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> #include <boost/thread/barrier.hpp> #include <boost/function.hpp> #include <iostream> #include <limits> #include <array> #include <future> #include <map> #include <set> using namespace std; using namespace Datacratic; using namespace Datacratic::MMap; using namespace ML; void checkTrieMemory(Trie& trie, MMapFile& area, MutableTrieVersion& current) { cerr << "memory usage for " << current.size() << " values is " << current.memUsage() << " at " << (1.0 * current.memUsage() / current.size()) << " bytes/value" << endl; cerr << "allocated " << area.bytesAllocated() << " deallocated " << area.bytesDeallocated() << " outstanding " << area.bytesOutstanding() << " total used bytes " << area.nodeAlloc.usedSize() << endl; // Make sure that no memory is leaked uint64_t memUsage = current.memUsage(); if (NodeAllocSentinels) memUsage *= 3; BOOST_CHECK_EQUAL(area.nodeAlloc.bytesOutstanding(), memUsage); current.clear(); current.reset(); trie.gc().deferBarrier(); // Make sure that all memory is reclaimed BOOST_CHECK_EQUAL(BinaryNodeOps::allocated - BinaryNodeOps::deallocated, 0); BOOST_CHECK_EQUAL( BasicKeyedTerminalOps::allocated - BasicKeyedTerminalOps::deallocated, 0); BOOST_CHECK_EQUAL(SparseNodeOps::allocated - SparseNodeOps::deallocated, 0); BOOST_CHECK_EQUAL( CompressedNodeOps::allocated - CompressedNodeOps::deallocated, 0); BOOST_CHECK_EQUAL( LargeKeyNodeOps::allocated - LargeKeyNodeOps::deallocated, 0); if (trieMemoryCheck) trieMemoryTracker.dumpLeaks(); } void dumpTrieStats() { cerr << "setRootSuccesses = " << setRootSuccesses << endl; cerr << "setRootFailures = " << setRootFailures << endl; cerr << "overheadRatio = " << (100.0 * setRootFailures / (setRootSuccesses + setRootFailures)) << "%" << endl; setRootSuccesses = 0; setRootFailures = 0; } BOOST_AUTO_TEST_CASE( test_concurrent_access ) { cerr << endl << "ACCESS ============================================================" << endl; trieDebug = true; for (unsigned i = 0; i < 10; ++i) { enum { TrieId = 42 }; MMapFile area(RES_CREATE); area.trieAlloc.allocate(TrieId); Trie trie = area.trie(TrieId); int nthreads = 4; int n = 1000; boost::barrier barrier(nthreads); int num_errors = 0; int nFinished = 0; auto doWritingThread = [&] (int threadNum) -> int { for (unsigned i = 0; i < n; ++i) { uint64_t key = i * nthreads + threadNum; uint64_t value = key; auto current = *trie; current.insert(key, value); TrieIterator it = current.find(key); if (!it.valid() || it.value() != value) { cerr << "error: value " << value << " value2 " << it.value() << endl; ML::atomic_add(num_errors, 1); } } ML::atomic_inc(nFinished); return 0; }; auto doReadingThread = [&] (int threadNum) -> int { while (nFinished < nthreads) { auto current = *trie; //auto mem = area.pin(); try { TrieIterator it, end; boost::tie(it, end) = current.beginEnd(); for (; it != end; ++it) { uint64_t key = it.key().cast<uint64_t>(); uint64_t value = it.value(); if (key != value) { ML::atomic_add(num_errors, 1); cerr << "read: key and value not equal: " << key << " != " << value << endl; cerr << "inEpoch: " << trie.gc().lockedInEpoch() << endl; trie.gc().dump(); } if (key > n * nthreads + nthreads) { ML::atomic_add(num_errors, 1); cerr << "too many values in trie" << endl; cerr << "inEpoch: " << trie.gc().lockedInEpoch() << endl; trie.gc().dump(); } } } catch (...) { cerr << "inEpoch: " << trie.gc().lockedInEpoch() << endl; cerr << "size = " << trie.current().size() << endl; trie.gc().dump(); ML::atomic_inc(num_errors); } } return 0; }; ThreadedTest test; test.start(doWritingThread, nthreads, 0); test.start(doReadingThread, nthreads, 1); test.joinAll(); trie.gc().deferBarrier(); auto current = *trie; BOOST_CHECK_EQUAL(num_errors, 0); BOOST_CHECK_EQUAL(current.size(), n * nthreads); for (uint64_t i = 0; i < n * nthreads; ++i) BOOST_CHECK_EQUAL(current[i], i); checkTrieMemory(trie, area, current); area.trieAlloc.deallocate(TrieId); } dumpTrieStats(); } BOOST_AUTO_TEST_CASE( test_concurrent_remove_test ) { cerr << endl << "REMOVE ============================================================" << endl; enum { readThreads = 2, writeThreads = 2, writeCount = 50, repeatCount = 50, }; enum { TrieId = 42 }; MMapFile area(RES_CREATE); area.trieAlloc.allocate(TrieId); Trie trie = area.trie(TrieId); auto wrongValError = [] ( string msg, uint64_t key, uint64_t value, uint64_t expectedValue) { stringstream ss; ss << msg << " - " << "key=" << key << ", value=" << value << ", expectedValue=" << expectedValue << endl; cerr << ss.str(); }; int writesFinished = 0; /** The write thread will repeatively insert the values from 0 to writeCount on random keys and remove these values in the reverse order they were added. This means that from the readers point of view, if the value i is detected for a giventhread, then the values from 0 to i should all be visible in the trie even if we're in the process of removing them. */ auto doWriteThread = [&] (int id) -> int { int errCount = 0; mt19937 engine (id); uniform_int_distribution<uint64_t> keyDist( numeric_limits<uint64_t>::min(), numeric_limits<uint64_t>::max()); for (int i = 0; i < repeatCount; ++i) { vector<uint64_t> keyList; auto current = *trie; for (int j = 0; j < writeCount; ++j) { uint64_t key = keyDist(engine); // Squeeze the id of the thread and the value in a 64b word. uint64_t value = ((uint64_t)j) | (((uint64_t)id) << 32); keyList.push_back(key); uint64_t oldValue = current.insert(key, value).first.value(); if (oldValue != value) { wrongValError("Collision", key, oldValue, value); errCount++; } } current = *trie; while(!keyList.empty()) { uint64_t key = keyList.back(); bool keyFound; uint64_t value; tie(keyFound, value) = current.remove(key); if (!keyFound) { wrongValError("Key not found", key, value, 0); errCount++; continue; } int valueId = value >> 32; int valueIndex = value & 0xFFFFFFFF; keyList.pop_back(); if (valueId != id) { wrongValError("Invalid value id", key, value, valueId); errCount++; } if (valueIndex >= writeCount) { wrongValError("Invalid value index", key, writeCount, valueIndex); errCount++; } } // stringstream ss; ss << "W " << id << " - i=" << i // << ", err=" << errCount << endl; // cerr << ss.str(); } ML::atomic_inc(writesFinished); return errCount; }; /** Scans the entire trie and gathers all the values added by each threads. We then sum these values and check them against the expected sum calculated from from the largest value we found for that thread. Note that we don't keep track of duplicate values so these won't affect the result. */ auto doReadThread = [&](int id) -> int { int errCount = 0; while (writesFinished < writeThreads) { map<int, set<int> > indexMap; // Scan the trie and gather all the values in it. auto current = *trie; TrieIterator it, end; boost::tie(it, end) = current.beginEnd(); for (; it != end; ++it) { uint64_t value = it.value(); int valueId = value >> 32; int valueIndex = value & 0xFFFFFFFF; indexMap[valueId].insert(valueIndex); } current.reset(); // Detect holes in a sets by summing all the indexes encountered for(auto it = indexMap.begin(), end = indexMap.end(); it != end; ++it) { int id = it->first; auto& indexSet = it->second; int sum = accumulate(indexSet.begin(), indexSet.end(), 0); int max = *(indexSet.rbegin()); int expectedSum = (max * (max+1))/2; if (expectedSum != sum) { wrongValError("Invalid sum", id, sum, expectedSum); errCount++; } } // stringstream ss; ss << "R " << id // << " - err=" << errCount << endl; // cerr << ss.str(); } return errCount; }; // Start the test. ThreadedTest test; test.start(doReadThread, readThreads, 0); test.start(doWriteThread, writeThreads, 1); int errSum = test.joinAll(10000); // Make sure everything is gc-ed trie.gc().deferBarrier(); // Make some final checks on the trie. auto current = *trie; BOOST_CHECK_EQUAL(current.size(), 0); checkTrieMemory(trie, area, current); area.trieAlloc.deallocate(TrieId); dumpTrieStats(); BOOST_REQUIRE_MESSAGE(errSum == 0, "Errors were detected durring the test."); } BOOST_AUTO_TEST_CASE( test_concurrent_cas_test ) { cerr << endl << "CAS ===============================================================" << endl; enum { TrieId = 42, threadCount = 8, incCount = 50, fillerNodes = 100 }; MMapFile area(RES_CREATE); area.trieAlloc.allocate(TrieId); Trie trie = area.trie(TrieId); uint64_t key = random(); { // add some random noise into the trie to complicate the structure a bit auto current = *trie; for (uint64_t i = 0; i < fillerNodes; ++i) current.insert(random(), random()); // Init our key to 0. current.insert(key, 0); } auto runThread = [&](int id) -> int { auto current = *trie; uint64_t oldValue = 0; for (int i = 0; i < incCount; ++i) { uint64_t newValue; do { newValue = oldValue+1; bool keyFound; tie(keyFound, oldValue) = current.compareAndSwap(key, oldValue, newValue); ExcAssert(keyFound); } while (oldValue+1 != newValue); } return 0; }; ThreadedTest test; test.start(runThread, threadCount); test.joinAll(); auto current = *trie; uint64_t value = current[key]; BOOST_REQUIRE_EQUAL(value, threadCount * incCount); current = *trie; BOOST_CHECK_EQUAL(current.size(), fillerNodes+1); checkTrieMemory(trie, area, current); area.trieAlloc.deallocate(TrieId); } BOOST_AUTO_TEST_CASE( test_concurrent_large_keys ) { cerr << endl << "LARGE KEYS ========================================================" << endl; enum { TrieId = 42, threadCount = 2, opCount = 20, repeatCount = 20, keySize = 64, }; MMapFile area(RES_CREATE); area.trieAlloc.allocate(TrieId); Trie trie = area.trie(TrieId); array<array<array<string, opCount>, repeatCount>, threadCount> testSet; { // generate all the keys discarding collisions. set<string> keyPool; while (keyPool.size() < threadCount * repeatCount * opCount) keyPool.insert(randomString(random() % keySize + 1)); // Split the keys into test sets. auto keyIt = keyPool.begin(); for (int i = 0; i < threadCount; ++i) for (int j = 0; j < repeatCount; ++j) for (int k = 0; k < opCount; ++k, ++keyIt) testSet[i][j][k] = *keyIt; } auto runThread = [&](int id) -> int { int errCount = 0; for (int repeat = 0; repeat < repeatCount; ++repeat) { // stringstream ss; // ss << "[" << id << "] - ATTEMPT(" << repeat << ")" << endl; // cerr << ss.str(); map<string, uint64_t> valMap; auto current = *trie; for (int i = 0; i < opCount; ++i) { string key = testSet[id][repeat][i]; uint64_t value = id; // stringstream ss; // ss << "[" << id << "] - INSERT(" << i << ") - " // << "key=" << key // << endl; // cerr << ss.str(); TrieIterator it; bool inserted; tie(it, inserted) = current.insert(key, value); if (!inserted) { cerr << "key collision\n"; errCount++; } valMap[key] = value; } current = *trie; for (auto it = valMap.begin(), end = valMap.end(); it != end; ++it){ // stringstream ss; // ss << "[" << id << "] - FIND - " // << "key=" << it->first // << endl; // cerr << ss.str(); if (current.find(it->first).value() != it->second) { cerr << "invalid value on find\n"; errCount++; } } current = *trie; for (auto it = valMap.begin(), end = valMap.end(); it != end; ++it){ // stringstream ss; // ss << "[" << id << "] - REMOVE - " // << "key=" << it->first // << endl; // cerr << ss.str(); bool keyFound; uint64_t oldValue; tie(keyFound, oldValue) = current.remove(it->first); if (!keyFound) { cerr << "key not found\n"; errCount++; } if (oldValue != it->second) { cerr << "invalid value on remove\n"; errCount++; } } } return errCount; }; ThreadedTest test; test.start(runThread, threadCount); int errSum = test.joinAll(100000); // Make some final checks on the trie. auto current = *trie; BOOST_CHECK_EQUAL(current.size(), 0); checkTrieMemory(trie, area, current); area.trieAlloc.deallocate(TrieId); dumpTrieStats(); BOOST_REQUIRE_MESSAGE(errSum == 0, "Errors were detected durring the test."); }
; ; ; Z88 Maths Routines ; ; C Interface for Small C+ Compiler ; ; 7/12/98 djm ;double floor(double) ;Number in FA.. SECTION code_fp INCLUDE "target/z88/def/fpp.def" PUBLIC floor EXTERN fsetup EXTERN stkequ2 .floor call fsetup fpp(FP_INT) ;floor it (round down!) jp stkequ2
0x0000 (0x000000) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x0001 (0x000002) 0x291A- f:00024 d: 282 | OR[282] = A 0x0002 (0x000004) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x0003 (0x000006) 0x291B- f:00024 d: 283 | OR[283] = A 0x0004 (0x000008) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x0005 (0x00000A) 0x291C- f:00024 d: 284 | OR[284] = A 0x0006 (0x00000C) 0x7441- f:00072 d: 65 | R = P + 65 (0x0047) 0x0007 (0x00000E) 0x211C- f:00020 d: 284 | A = OR[284] 0x0008 (0x000010) 0x1408- f:00012 d: 8 | A = A + 8 (0x0008) 0x0009 (0x000012) 0x291D- f:00024 d: 285 | OR[285] = A 0x000A (0x000014) 0x2119- f:00020 d: 281 | A = OR[281] 0x000B (0x000016) 0x1402- f:00012 d: 2 | A = A + 2 (0x0002) 0x000C (0x000018) 0x291E- f:00024 d: 286 | OR[286] = A 0x000D (0x00001A) 0x211D- f:00020 d: 285 | A = OR[285] 0x000E (0x00001C) 0x1401- f:00012 d: 1 | A = A + 1 (0x0001) 0x000F (0x00001E) 0x2913- f:00024 d: 275 | OR[275] = A 0x0010 (0x000020) 0x211E- f:00020 d: 286 | A = OR[286] 0x0011 (0x000022) 0x290D- f:00024 d: 269 | OR[269] = A 0x0012 (0x000024) 0x2113- f:00020 d: 275 | A = OR[275] 0x0013 (0x000026) 0x290E- f:00024 d: 270 | OR[270] = A 0x0014 (0x000028) 0x1008- f:00010 d: 8 | A = 8 (0x0008) 0x0015 (0x00002A) 0x290F- f:00024 d: 271 | OR[271] = A 0x0016 (0x00002C) 0x7006- f:00070 d: 6 | P = P + 6 (0x001C) 0x0017 (0x00002E) 0x310D- f:00030 d: 269 | A = (OR[269]) 0x0018 (0x000030) 0x390E- f:00034 d: 270 | (OR[270]) = A 0x0019 (0x000032) 0x2D0D- f:00026 d: 269 | OR[269] = OR[269] + 1 0x001A (0x000034) 0x2D0E- f:00026 d: 270 | OR[270] = OR[270] + 1 0x001B (0x000036) 0x2F0F- f:00027 d: 271 | OR[271] = OR[271] - 1 0x001C (0x000038) 0x210F- f:00020 d: 271 | A = OR[271] 0x001D (0x00003A) 0x8E06- f:00107 d: 6 | P = P - 6 (0x0017), A # 0 0x001E (0x00003C) 0x2119- f:00020 d: 281 | A = OR[281] 0x001F (0x00003E) 0x140A- f:00012 d: 10 | A = A + 10 (0x000A) 0x0020 (0x000040) 0x291F- f:00024 d: 287 | OR[287] = A 0x0021 (0x000042) 0x211D- f:00020 d: 285 | A = OR[285] 0x0022 (0x000044) 0x1409- f:00012 d: 9 | A = A + 9 (0x0009) 0x0023 (0x000046) 0x2913- f:00024 d: 275 | OR[275] = A 0x0024 (0x000048) 0x211F- f:00020 d: 287 | A = OR[287] 0x0025 (0x00004A) 0x290D- f:00024 d: 269 | OR[269] = A 0x0026 (0x00004C) 0x2113- f:00020 d: 275 | A = OR[275] 0x0027 (0x00004E) 0x290E- f:00024 d: 270 | OR[270] = A 0x0028 (0x000050) 0x1008- f:00010 d: 8 | A = 8 (0x0008) 0x0029 (0x000052) 0x290F- f:00024 d: 271 | OR[271] = A 0x002A (0x000054) 0x7006- f:00070 d: 6 | P = P + 6 (0x0030) 0x002B (0x000056) 0x310D- f:00030 d: 269 | A = (OR[269]) 0x002C (0x000058) 0x390E- f:00034 d: 270 | (OR[270]) = A 0x002D (0x00005A) 0x2D0D- f:00026 d: 269 | OR[269] = OR[269] + 1 0x002E (0x00005C) 0x2D0E- f:00026 d: 270 | OR[270] = OR[270] + 1 0x002F (0x00005E) 0x2F0F- f:00027 d: 271 | OR[271] = OR[271] - 1 0x0030 (0x000060) 0x210F- f:00020 d: 271 | A = OR[271] 0x0031 (0x000062) 0x8E06- f:00107 d: 6 | P = P - 6 (0x002B), A # 0 0x0032 (0x000064) 0x311D- f:00030 d: 285 | A = (OR[285]) 0x0033 (0x000066) 0x0E02- f:00007 d: 2 | A = A << 2 (0x0002) 0x0034 (0x000068) 0x0A01- f:00005 d: 1 | A = A < 1 (0x0001) 0x0035 (0x00006A) 0x1401- f:00012 d: 1 | A = A + 1 (0x0001) 0x0036 (0x00006C) 0x0C03- f:00006 d: 3 | A = A >> 3 (0x0003) 0x0037 (0x00006E) 0x391D- f:00034 d: 285 | (OR[285]) = A 0x0038 (0x000070) 0x211B- f:00020 d: 283 | A = OR[283] 0x0039 (0x000072) 0x8602- f:00103 d: 2 | P = P + 2 (0x003B), A # 0 0x003A (0x000074) 0x7002- f:00070 d: 2 | P = P + 2 (0x003C) 0x003B (0x000076) 0x7485- f:00072 d: 133 | R = P + 133 (0x00C0) 0x003C (0x000078) 0x2005- f:00020 d: 5 | A = OR[5] 0x003D (0x00007A) 0x1406- f:00012 d: 6 | A = A + 6 (0x0006) 0x003E (0x00007C) 0x2908- f:00024 d: 264 | OR[264] = A 0x003F (0x00007E) 0x211A- f:00020 d: 282 | A = OR[282] 0x0040 (0x000080) 0x3908- f:00034 d: 264 | (OR[264]) = A 0x0041 (0x000082) 0x102A- f:00010 d: 42 | A = 42 (0x002A) 0x0042 (0x000084) 0x2923- f:00024 d: 291 | OR[291] = A 0x0043 (0x000086) 0x1123- f:00010 d: 291 | A = 291 (0x0123) 0x0044 (0x000088) 0x5800- f:00054 d: 0 | B = A 0x0045 (0x00008A) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x0046 (0x00008C) 0x7C09- f:00076 d: 9 | R = OR[9] 0x0047 (0x00008E) 0x2119- f:00020 d: 281 | A = OR[281] 0x0048 (0x000090) 0x1401- f:00012 d: 1 | A = A + 1 (0x0001) 0x0049 (0x000092) 0x2908- f:00024 d: 264 | OR[264] = A 0x004A (0x000094) 0x3108- f:00030 d: 264 | A = (OR[264]) 0x004B (0x000096) 0x2920- f:00024 d: 288 | OR[288] = A 0x004C (0x000098) 0x2120- f:00020 d: 288 | A = OR[288] 0x004D (0x00009A) 0x290D- f:00024 d: 269 | OR[269] = A 0x004E (0x00009C) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x004F (0x00009E) 0x290E- f:00024 d: 270 | OR[270] = A 0x0050 (0x0000A0) 0x2006- f:00020 d: 6 | A = OR[6] 0x0051 (0x0000A2) 0x2910- f:00024 d: 272 | OR[272] = A 0x0052 (0x0000A4) 0x1028- f:00010 d: 40 | A = 40 (0x0028) 0x0053 (0x0000A6) 0x2923- f:00024 d: 291 | OR[291] = A 0x0054 (0x0000A8) 0x1800-0x00A9 f:00014 d: 0 | A = 169 (0x00A9) 0x0056 (0x0000AC) 0x2924- f:00024 d: 292 | OR[292] = A 0x0057 (0x0000AE) 0x1800-0x444B f:00014 d: 0 | A = 17483 (0x444B) 0x0059 (0x0000B2) 0x2925- f:00024 d: 293 | OR[293] = A 0x005A (0x0000B4) 0x210D- f:00020 d: 269 | A = OR[269] 0x005B (0x0000B6) 0x2926- f:00024 d: 294 | OR[294] = A 0x005C (0x0000B8) 0x1003- f:00010 d: 3 | A = 3 (0x0003) 0x005D (0x0000BA) 0x2927- f:00024 d: 295 | OR[295] = A 0x005E (0x0000BC) 0x210E- f:00020 d: 270 | A = OR[270] 0x005F (0x0000BE) 0x2928- f:00024 d: 296 | OR[296] = A 0x0060 (0x0000C0) 0x210F- f:00020 d: 271 | A = OR[271] 0x0061 (0x0000C2) 0x2929- f:00024 d: 297 | OR[297] = A 0x0062 (0x0000C4) 0x2110- f:00020 d: 272 | A = OR[272] 0x0063 (0x0000C6) 0x292A- f:00024 d: 298 | OR[298] = A 0x0064 (0x0000C8) 0x100F- f:00010 d: 15 | A = 15 (0x000F) 0x0065 (0x0000CA) 0x292B- f:00024 d: 299 | OR[299] = A 0x0066 (0x0000CC) 0x1123- f:00010 d: 291 | A = 291 (0x0123) 0x0067 (0x0000CE) 0x5800- f:00054 d: 0 | B = A 0x0068 (0x0000D0) 0x1800-0x1718 f:00014 d: 0 | A = 5912 (0x1718) 0x006A (0x0000D4) 0x7C09- f:00076 d: 9 | R = OR[9] 0x006B (0x0000D6) 0x291A- f:00024 d: 282 | OR[282] = A 0x006C (0x0000D8) 0x211A- f:00020 d: 282 | A = OR[282] 0x006D (0x0000DA) 0x8602- f:00103 d: 2 | P = P + 2 (0x006F), A # 0 0x006E (0x0000DC) 0x7002- f:00070 d: 2 | P = P + 2 (0x0070) 0x006F (0x0000DE) 0x7077- f:00070 d: 119 | P = P + 119 (0x00E6) 0x0070 (0x0000E0) 0x2119- f:00020 d: 281 | A = OR[281] 0x0071 (0x0000E2) 0x1402- f:00012 d: 2 | A = A + 2 (0x0002) 0x0072 (0x0000E4) 0x291E- f:00024 d: 286 | OR[286] = A 0x0073 (0x0000E6) 0x2119- f:00020 d: 281 | A = OR[281] 0x0074 (0x0000E8) 0x140A- f:00012 d: 10 | A = A + 10 (0x000A) 0x0075 (0x0000EA) 0x291F- f:00024 d: 287 | OR[287] = A 0x0076 (0x0000EC) 0x1028- f:00010 d: 40 | A = 40 (0x0028) 0x0077 (0x0000EE) 0x2923- f:00024 d: 291 | OR[291] = A 0x0078 (0x0000F0) 0x1800-0x00E7 f:00014 d: 0 | A = 231 (0x00E7) 0x007A (0x0000F4) 0x2924- f:00024 d: 292 | OR[292] = A 0x007B (0x0000F6) 0x211B- f:00020 d: 283 | A = OR[283] 0x007C (0x0000F8) 0x2925- f:00024 d: 293 | OR[293] = A 0x007D (0x0000FA) 0x211E- f:00020 d: 286 | A = OR[286] 0x007E (0x0000FC) 0x2926- f:00024 d: 294 | OR[294] = A 0x007F (0x0000FE) 0x211F- f:00020 d: 287 | A = OR[287] 0x0080 (0x000100) 0x2927- f:00024 d: 295 | OR[295] = A 0x0081 (0x000102) 0x1010- f:00010 d: 16 | A = 16 (0x0010) 0x0082 (0x000104) 0x2928- f:00024 d: 296 | OR[296] = A 0x0083 (0x000106) 0x1015- f:00010 d: 21 | A = 21 (0x0015) 0x0084 (0x000108) 0x2929- f:00024 d: 297 | OR[297] = A 0x0085 (0x00010A) 0x1016- f:00010 d: 22 | A = 22 (0x0016) 0x0086 (0x00010C) 0x292A- f:00024 d: 298 | OR[298] = A 0x0087 (0x00010E) 0x1123- f:00010 d: 291 | A = 291 (0x0123) 0x0088 (0x000110) 0x5800- f:00054 d: 0 | B = A 0x0089 (0x000112) 0x1800-0x1718 f:00014 d: 0 | A = 5912 (0x1718) 0x008B (0x000116) 0x7C09- f:00076 d: 9 | R = OR[9] 0x008C (0x000118) 0x291A- f:00024 d: 282 | OR[282] = A 0x008D (0x00011A) 0x211A- f:00020 d: 282 | A = OR[282] 0x008E (0x00011C) 0x1E00-0x0444 f:00017 d: 0 | A = A - 1092 (0x0444) 0x0090 (0x000120) 0x8402- f:00102 d: 2 | P = P + 2 (0x0092), A = 0 0x0091 (0x000122) 0x7004- f:00070 d: 4 | P = P + 4 (0x0095) 0x0092 (0x000124) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x0093 (0x000126) 0x291A- f:00024 d: 282 | OR[282] = A 0x0094 (0x000128) 0x700A- f:00070 d: 10 | P = P + 10 (0x009E) 0x0095 (0x00012A) 0x211A- f:00020 d: 282 | A = OR[282] 0x0096 (0x00012C) 0x8402- f:00102 d: 2 | P = P + 2 (0x0098), A = 0 0x0097 (0x00012E) 0x7006- f:00070 d: 6 | P = P + 6 (0x009D) 0x0098 (0x000130) 0x1800-0x0445 f:00014 d: 0 | A = 1093 (0x0445) 0x009A (0x000134) 0x291A- f:00024 d: 282 | OR[282] = A 0x009B (0x000136) 0x7263- f:00071 d: 99 | P = P - 99 (0x0038) 0x009C (0x000138) 0x7002- f:00070 d: 2 | P = P + 2 (0x009E) 0x009D (0x00013A) 0x7049- f:00070 d: 73 | P = P + 73 (0x00E6) 0x009E (0x00013C) 0x2118- f:00020 d: 280 | A = OR[280] 0x009F (0x00013E) 0x1402- f:00012 d: 2 | A = A + 2 (0x0002) 0x00A0 (0x000140) 0x291E- f:00024 d: 286 | OR[286] = A 0x00A1 (0x000142) 0x2118- f:00020 d: 280 | A = OR[280] 0x00A2 (0x000144) 0x140A- f:00012 d: 10 | A = A + 10 (0x000A) 0x00A3 (0x000146) 0x291F- f:00024 d: 287 | OR[287] = A 0x00A4 (0x000148) 0x1028- f:00010 d: 40 | A = 40 (0x0028) 0x00A5 (0x00014A) 0x2923- f:00024 d: 291 | OR[291] = A 0x00A6 (0x00014C) 0x1800-0x00E7 f:00014 d: 0 | A = 231 (0x00E7) 0x00A8 (0x000150) 0x2924- f:00024 d: 292 | OR[292] = A 0x00A9 (0x000152) 0x211B- f:00020 d: 283 | A = OR[283] 0x00AA (0x000154) 0x2925- f:00024 d: 293 | OR[293] = A 0x00AB (0x000156) 0x211E- f:00020 d: 286 | A = OR[286] 0x00AC (0x000158) 0x2926- f:00024 d: 294 | OR[294] = A 0x00AD (0x00015A) 0x211F- f:00020 d: 287 | A = OR[287] 0x00AE (0x00015C) 0x2927- f:00024 d: 295 | OR[295] = A 0x00AF (0x00015E) 0x1010- f:00010 d: 16 | A = 16 (0x0010) 0x00B0 (0x000160) 0x2928- f:00024 d: 296 | OR[296] = A 0x00B1 (0x000162) 0x1015- f:00010 d: 21 | A = 21 (0x0015) 0x00B2 (0x000164) 0x2929- f:00024 d: 297 | OR[297] = A 0x00B3 (0x000166) 0x1016- f:00010 d: 22 | A = 22 (0x0016) 0x00B4 (0x000168) 0x292A- f:00024 d: 298 | OR[298] = A 0x00B5 (0x00016A) 0x1123- f:00010 d: 291 | A = 291 (0x0123) 0x00B6 (0x00016C) 0x5800- f:00054 d: 0 | B = A 0x00B7 (0x00016E) 0x1800-0x1718 f:00014 d: 0 | A = 5912 (0x1718) 0x00B9 (0x000172) 0x7C09- f:00076 d: 9 | R = OR[9] 0x00BA (0x000174) 0x291A- f:00024 d: 282 | OR[282] = A 0x00BB (0x000176) 0x211A- f:00020 d: 282 | A = OR[282] 0x00BC (0x000178) 0x8602- f:00103 d: 2 | P = P + 2 (0x00BE), A # 0 0x00BD (0x00017A) 0x7002- f:00070 d: 2 | P = P + 2 (0x00BF) 0x00BE (0x00017C) 0x7028- f:00070 d: 40 | P = P + 40 (0x00E6) 0x00BF (0x00017E) 0x0200- f:00001 d: 0 | EXIT 0x00C0 (0x000180) 0x211C- f:00020 d: 284 | A = OR[284] 0x00C1 (0x000182) 0x8602- f:00103 d: 2 | P = P + 2 (0x00C3), A # 0 0x00C2 (0x000184) 0x7013- f:00070 d: 19 | P = P + 19 (0x00D5) 0x00C3 (0x000186) 0x1028- f:00010 d: 40 | A = 40 (0x0028) 0x00C4 (0x000188) 0x2923- f:00024 d: 291 | OR[291] = A 0x00C5 (0x00018A) 0x1800-0x00E8 f:00014 d: 0 | A = 232 (0x00E8) 0x00C7 (0x00018E) 0x2924- f:00024 d: 292 | OR[292] = A 0x00C8 (0x000190) 0x211B- f:00020 d: 283 | A = OR[283] 0x00C9 (0x000192) 0x2925- f:00024 d: 293 | OR[293] = A 0x00CA (0x000194) 0x211C- f:00020 d: 284 | A = OR[284] 0x00CB (0x000196) 0x2926- f:00024 d: 294 | OR[294] = A 0x00CC (0x000198) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x00CD (0x00019A) 0x2927- f:00024 d: 295 | OR[295] = A 0x00CE (0x00019C) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x00CF (0x00019E) 0x2928- f:00024 d: 296 | OR[296] = A 0x00D0 (0x0001A0) 0x1123- f:00010 d: 291 | A = 291 (0x0123) 0x00D1 (0x0001A2) 0x5800- f:00054 d: 0 | B = A 0x00D2 (0x0001A4) 0x1800-0x1718 f:00014 d: 0 | A = 5912 (0x1718) 0x00D4 (0x0001A8) 0x7C09- f:00076 d: 9 | R = OR[9] 0x00D5 (0x0001AA) 0x1006- f:00010 d: 6 | A = 6 (0x0006) 0x00D6 (0x0001AC) 0x290D- f:00024 d: 269 | OR[269] = A 0x00D7 (0x0001AE) 0x1028- f:00010 d: 40 | A = 40 (0x0028) 0x00D8 (0x0001B0) 0x2923- f:00024 d: 291 | OR[291] = A 0x00D9 (0x0001B2) 0x1800-0x00A5 f:00014 d: 0 | A = 165 (0x00A5) 0x00DB (0x0001B6) 0x2924- f:00024 d: 292 | OR[292] = A 0x00DC (0x0001B8) 0x211B- f:00020 d: 283 | A = OR[283] 0x00DD (0x0001BA) 0x2925- f:00024 d: 293 | OR[293] = A 0x00DE (0x0001BC) 0x210D- f:00020 d: 269 | A = OR[269] 0x00DF (0x0001BE) 0x2926- f:00024 d: 294 | OR[294] = A 0x00E0 (0x0001C0) 0x1123- f:00010 d: 291 | A = 291 (0x0123) 0x00E1 (0x0001C2) 0x5800- f:00054 d: 0 | B = A 0x00E2 (0x0001C4) 0x1800-0x1718 f:00014 d: 0 | A = 5912 (0x1718) 0x00E4 (0x0001C8) 0x7C09- f:00076 d: 9 | R = OR[9] 0x00E5 (0x0001CA) 0x0200- f:00001 d: 0 | EXIT 0x00E6 (0x0001CC) 0x211A- f:00020 d: 282 | A = OR[282] 0x00E7 (0x0001CE) 0x1605- f:00013 d: 5 | A = A - 5 (0x0005) 0x00E8 (0x0001D0) 0x8402- f:00102 d: 2 | P = P + 2 (0x00EA), A = 0 0x00E9 (0x0001D2) 0x7005- f:00070 d: 5 | P = P + 5 (0x00EE) 0x00EA (0x0001D4) 0x1800-0x0646 f:00014 d: 0 | A = 1606 (0x0646) 0x00EC (0x0001D8) 0x291A- f:00024 d: 282 | OR[282] = A 0x00ED (0x0001DA) 0x7023- f:00070 d: 35 | P = P + 35 (0x0110) 0x00EE (0x0001DC) 0x211A- f:00020 d: 282 | A = OR[282] 0x00EF (0x0001DE) 0x160A- f:00013 d: 10 | A = A - 10 (0x000A) 0x00F0 (0x0001E0) 0x8402- f:00102 d: 2 | P = P + 2 (0x00F2), A = 0 0x00F1 (0x0001E2) 0x7005- f:00070 d: 5 | P = P + 5 (0x00F6) 0x00F2 (0x0001E4) 0x1800-0x064E f:00014 d: 0 | A = 1614 (0x064E) 0x00F4 (0x0001E8) 0x291A- f:00024 d: 282 | OR[282] = A 0x00F5 (0x0001EA) 0x701B- f:00070 d: 27 | P = P + 27 (0x0110) 0x00F6 (0x0001EC) 0x211A- f:00020 d: 282 | A = OR[282] 0x00F7 (0x0001EE) 0x1608- f:00013 d: 8 | A = A - 8 (0x0008) 0x00F8 (0x0001F0) 0x8402- f:00102 d: 2 | P = P + 2 (0x00FA), A = 0 0x00F9 (0x0001F2) 0x7005- f:00070 d: 5 | P = P + 5 (0x00FE) 0x00FA (0x0001F4) 0x1800-0x0649 f:00014 d: 0 | A = 1609 (0x0649) 0x00FC (0x0001F8) 0x291A- f:00024 d: 282 | OR[282] = A 0x00FD (0x0001FA) 0x7013- f:00070 d: 19 | P = P + 19 (0x0110) 0x00FE (0x0001FC) 0x211A- f:00020 d: 282 | A = OR[282] 0x00FF (0x0001FE) 0x1609- f:00013 d: 9 | A = A - 9 (0x0009) 0x0100 (0x000200) 0x8402- f:00102 d: 2 | P = P + 2 (0x0102), A = 0 0x0101 (0x000202) 0x7005- f:00070 d: 5 | P = P + 5 (0x0106) 0x0102 (0x000204) 0x1800-0x064D f:00014 d: 0 | A = 1613 (0x064D) 0x0104 (0x000208) 0x291A- f:00024 d: 282 | OR[282] = A 0x0105 (0x00020A) 0x700B- f:00070 d: 11 | P = P + 11 (0x0110) 0x0106 (0x00020C) 0x211A- f:00020 d: 282 | A = OR[282] 0x0107 (0x00020E) 0x1602- f:00013 d: 2 | A = A - 2 (0x0002) 0x0108 (0x000210) 0x8405- f:00102 d: 5 | P = P + 5 (0x010D), A = 0 0x0109 (0x000212) 0x211A- f:00020 d: 282 | A = OR[282] 0x010A (0x000214) 0x1603- f:00013 d: 3 | A = A - 3 (0x0003) 0x010B (0x000216) 0x8402- f:00102 d: 2 | P = P + 2 (0x010D), A = 0 0x010C (0x000218) 0x7004- f:00070 d: 4 | P = P + 4 (0x0110) 0x010D (0x00021A) 0x1800-0x064C f:00014 d: 0 | A = 1612 (0x064C) 0x010F (0x00021E) 0x291A- f:00024 d: 282 | OR[282] = A 0x0110 (0x000220) 0x72D8- f:00071 d: 216 | P = P - 216 (0x0038) 0x0111 (0x000222) 0x0000- f:00000 d: 0 | PASS 0x0112 (0x000224) 0x0000- f:00000 d: 0 | PASS 0x0113 (0x000226) 0x0000- f:00000 d: 0 | PASS
; void SMS_addTwoAdjoiningSprites(unsigned char x, unsigned char y, unsigned char tile) SECTION code_clib SECTION code_SMSlib PUBLIC SMSlib_addTwoAdjoiningSprites_callee EXTERN asm_SMSlib_addTwoAdjoiningSprites SMSlib_addTwoAdjoiningSprites_callee: pop af pop hl pop de pop bc push af ld b,l ld d,e jp asm_SMSlib_addTwoAdjoiningSprites
; A034830: a(n) = n-th sept-factorial number divided by 3. ; 1,10,170,4080,126480,4806240,216280800,11246601600,663549494400,43794266630400,3196981464019200,255758517121536000,22250990989573632000,2091593153019921408000,211250908455012062208000,22815098113141302718464000,2623736283011249812623360000,320095826527372477140049920000,41292361622031049551066439680000,5615761180596222738945035796480000,803053848825259851669140118896640000,120458077323788977750371017834496000000,18911918139834869506808249800015872000000 mov $1,1 mov $2,3 lpb $0 sub $0,1 add $2,7 mul $1,$2 lpe mov $0,$1
; A183861: n-1+ceiling((-1+n^2)/3); complement of A183860. ; 1,2,5,8,12,17,22,28,35,42,50,59,68,78,89,100,112,125,138,152,167,182,198,215,232,250,269,288,308,329,350,372,395,418,442,467,492,518,545,572,600,629,658,688,719,750,782,815,848,882,917,952,988,1025,1062,1100,1139,1178,1218,1259,1300,1342,1385,1428,1472,1517,1562,1608,1655,1702 mov $1,5 add $1,$0 mul $1,$0 sub $1,2 div $1,3 add $1,1 mov $0,$1
<% from pwnlib.shellcraft.thumb.linux import syscall %> <%page args="fdout, iov, count, flags"/> <%docstring> Invokes the syscall vmsplice. See 'man 2 vmsplice' for more information. Arguments: fdout(int): fdout iov(iovec): iov count(size_t): count flags(unsigned): flags </%docstring> ${syscall('SYS_vmsplice', fdout, iov, count, flags)}
; A174522: Expansion of 1/(1 - x - x^4 + x^6). ; Submitted by Christian Krause ; 1,1,1,1,2,3,3,3,4,6,7,7,8,11,14,15,16,20,26,30,32,37,47,57,63,70,85,105,121,134,156,191,227,256,291,348,419,484,548,640,768,904,1033,1189,1409,1673,1938,2223,2599,3083,3612,4162,4823,5683,6696,7775,8986 lpb $0 mov $2,$0 sub $0,1 seq $2,17827 ; a(n) = a(n-4) + a(n-5), with a(0)=1, a(1)=a(2)=a(3)=0, a(4)=1. add $1,$2 lpe mov $0,$1 add $0,1
; A020723: n+9. ; 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81 add $0,9
; A001363: Primes in ternary. ; 2,10,12,21,102,111,122,201,212,1002,1011,1101,1112,1121,1202,1222,2012,2021,2111,2122,2201,2221,10002,10022,10121,10202,10211,10222,11001,11012,11201,11212,12002,12011,12112,12121,12211,20001,20012,20102,20122,20201,21002,21011,21022,21101,21211,22021,22102,22111,22122,22212,22221,100022,100112,100202,100222,101001,101021,101102,101111,101212,102101,102112,102121,102202,110021,110111,110212,110221,111002,111022,111121,111211,112001,112012,112102,112201,112212,120011,120112,120121,120222,121001,121021,121102,121122,121221,122002,122011,122022,122202,200001,200012,200111,200122,200212,201022,201101,202001 seq $0,40 ; The prime numbers. seq $0,7089 ; Numbers in base 3.
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %rax push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x7b09, %rsi nop nop add $26867, %rbp vmovups (%rsi), %ymm0 vextracti128 $0, %ymm0, %xmm0 vpextrq $1, %xmm0, %r13 nop sub $24815, %r13 lea addresses_D_ht+0x14b61, %rdx nop nop nop and %rdi, %rdi vmovups (%rdx), %ymm5 vextracti128 $0, %ymm5, %xmm5 vpextrq $0, %xmm5, %r10 nop xor $18874, %rsi lea addresses_normal_ht+0x3281, %rbp nop nop and $50750, %rax mov $0x6162636465666768, %rdi movq %rdi, %xmm1 movups %xmm1, (%rbp) and %r10, %r10 lea addresses_D_ht+0x19a1, %rsi lea addresses_UC_ht+0x10b1f, %rdi nop nop nop and %rdx, %rdx mov $87, %rcx rep movsl nop nop nop nop and %rcx, %rcx lea addresses_UC_ht+0xbbe1, %rcx nop inc %rdx mov (%rcx), %rsi nop nop nop nop xor %rdx, %rdx lea addresses_UC_ht+0x8061, %rsi nop add $43978, %r10 mov (%rsi), %dx nop nop nop nop add %rdx, %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %rax pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %rax push %rbx push %rdx // Store lea addresses_WT+0x1761, %r12 nop nop and %r10, %r10 mov $0x5152535455565758, %rax movq %rax, %xmm2 and $0xffffffffffffffc0, %r12 movntdq %xmm2, (%r12) nop nop nop nop nop dec %rax // Load lea addresses_WC+0x13861, %r10 nop nop nop inc %rdx mov (%r10), %rax nop nop nop nop sub %r10, %r10 // Faulty Load lea addresses_WC+0x13861, %rbx nop nop nop nop nop sub %r12, %r12 movups (%rbx), %xmm6 vpextrq $0, %xmm6, %rax lea oracles, %r12 and $0xff, %rax shlq $12, %rax mov (%r12,%rax,1), %rax pop %rdx pop %rbx pop %rax pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WC'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': True, 'type': 'addresses_WT'}} {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 8, 'NT': False, 'type': 'addresses_WC'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_WC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_normal_ht'}} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_UC_ht'}} {'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A075137: Numerator of the generalized harmonic number H(n,5,1). ; Submitted by Jon Maiga ; 1,7,83,697,1685,22521,714167,6551627,273085171,6372562445,109738148749,111017326363,6843690854527,6909897986791,494972427791585,9482037783487391,85993305141830183,3724238207261666261 mov $1,1 lpb $0 mov $2,$0 sub $0,1 mul $2,5 add $2,1 mul $3,$2 add $3,$1 mul $1,$2 lpe add $1,$3 gcd $3,$1 div $1,$3 mov $0,$1 mul $0,4 sub $0,4 div $0,4 add $0,1
// MIT License // Copyright (c) 2021 Florian Eigentler // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <stdlib.h> #include <iostream> #include <fstream> #include <omp.h> #define PROJECT_FILE PROJECT ".ppm" #define PROJECT_IMAGE "convert " PROJECT_FILE " " PROJECT ".png; rm " PROJECT_FILE #include <raytracing/raytracing.h> #include <raytracing/utils.h> #include <raytracing/color.h> #include <raytracing/hitable_list.h> #include <raytracing/sphere.h> #include <raytracing/camera.h> Color ray_color(const Ray &r, const Hitable &world) { HitRecord rec; if (world.hit(r, 0, infinity, rec)) { return 0.5 * (rec.normal + Color{1}); } Vector3 unit_direction = normalize_Vector3(r.direction()); auto t = 0.5 * (unit_direction.y() + 1.0); return (1.0 - t) * Color{1} + t * Color{0.5, 0.7, 1}; } int main(int argc, char const *argv[]) { // Image const auto aspect_ratio = ASPECT_RATIO; const int image_width = IMAGE_WIDTH; const int image_height = static_cast<int>(image_width / aspect_ratio); // World HitableList world; world.add(std::make_shared<Sphere>(Point3{0, 0, -1}, 0.5)); world.add(std::make_shared<Sphere>(Point3{0, -100.5, -1}, 100)); // Camera auto viewport_height = 2.0; auto viewport_width = aspect_ratio * viewport_height; auto focal_length = 1.0; auto origin = Point3{0}; auto horizontal = Vector3{viewport_width, 0, 0}; auto vertical = Vector3{0, viewport_height, 0}; auto lower_left_corner = origin - horizontal / 2 - vertical / 2 - Vector3{0, 0, focal_length}; // Render Color *pixel = (Color *)malloc(sizeof(Color) * image_width * image_height); int row_counter = image_height; #pragma omp parallel for for (int j = image_height - 1; j >= 0; --j) { --row_counter; std::cout << (ParallelStream() << "\rScanlines remaining: " << row_counter << ' ').toString() << std::flush; for (int i = 0; i < image_width; ++i) { auto u = double(i) / (image_width - 1); auto v = double(j) / (image_height - 1); Ray r(origin, lower_left_corner + u * horizontal + v * vertical - origin); pixel[j * image_width + i] = ray_color(r, world); } } // Output std::ofstream file; file.open(PROJECT_FILE); file << "P3\n" << image_width << " " << image_height << "\n255\n"; for (int j = image_height - 1; j >= 0; --j) for (int i = 0; i < image_width; ++i) write_color(file, pixel[j * image_width + i], 1, 1); file << "\n"; file.close(); system(PROJECT_IMAGE); // Finalize free(pixel); std::cout << "\nDone.\n"; return 0; }
/*************************************************************************/ /* camera_win.cpp */ /*************************************************************************/ /* This file is part of: */ /* Valjang Engine */ /* http://Valjang.fr */ /*************************************************************************/ /* Copyright (c) 2007-2020 Valjang. */ /* Copyright (c) 2014-2020 Valjang Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "camera_win.h" ///@TODO sorry guys, I got about 80% through implementing this using DirectShow only // to find out Microsoft deprecated half the API and its replacement is as confusing // as they could make it. Joey suggested looking into libuvc which offers a more direct // route to webcams over USB and this is very promising but it wouldn't compile on // windows for me...I've gutted the classes I implemented DirectShow in just to have // a skeleton for someone to work on, mail me for more details or if you want a copy.... ////////////////////////////////////////////////////////////////////////// // CameraFeedWindows - Subclass for our camera feed on windows /// @TODO need to implement this class CameraFeedWindows : public CameraFeed { private: protected: public: CameraFeedWindows(); virtual ~CameraFeedWindows(); bool activate_feed(); void deactivate_feed(); }; CameraFeedWindows::CameraFeedWindows() { ///@TODO implement this, should store information about our available camera } CameraFeedWindows::~CameraFeedWindows() { // make sure we stop recording if we are! if (is_active()) { deactivate_feed(); }; ///@TODO free up anything used by this }; bool CameraFeedWindows::activate_feed() { ///@TODO this should activate our camera and start the process of capturing frames return true; }; ///@TODO we should probably have a callback method here that is being called by the // camera API which provides frames and call back into the CameraServer to update our texture void CameraFeedWindows::deactivate_feed() { ///@TODO this should deactivate our camera and stop the process of capturing frames } ////////////////////////////////////////////////////////////////////////// // CameraWindows - Subclass for our camera server on windows void CameraWindows::add_active_cameras() { ///@TODO scan through any active cameras and create CameraFeedWindows objects for them } CameraWindows::CameraWindows() { // Find cameras active right now add_active_cameras(); // need to add something that will react to devices being connected/removed... };
dnl SPARC v8 mpn_submul_1 -- Multiply a limb vector with a limb and dnl subtract the result from a second limb vector. dnl Copyright (C) 1992, 1993, 1994, 2000 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of the GNU Library General Public License as published dnl by the Free Software Foundation; either version 2 of the License, or (at dnl your option) any later version. dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public dnl License for more details. dnl You should have received a copy of the GNU Library General Public License dnl along with the GNU MP Library; see the file COPYING.LIB. If not, write to dnl the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, dnl MA 02111-1307, USA. include(`../config.m4') C INPUT PARAMETERS C res_ptr o0 C s1_ptr o1 C size o2 C s2_limb o3 ASM_START() PROLOGUE(mpn_submul_1) sub %g0,%o2,%o2 C negate ... sll %o2,2,%o2 C ... and scale size sub %o1,%o2,%o1 C o1 is offset s1_ptr sub %o0,%o2,%g1 C g1 is offset res_ptr mov 0,%o0 C clear cy_limb L(loop): ld [%o1+%o2],%o4 ld [%g1+%o2],%g2 umul %o4,%o3,%o5 rd %y,%g3 addcc %o5,%o0,%o5 addx %g3,0,%o0 subcc %g2,%o5,%g2 addx %o0,0,%o0 st %g2,[%g1+%o2] addcc %o2,4,%o2 bne L(loop) nop retl nop EPILOGUE(mpn_submul_1)
// Standard Library includes #include <iostream> #include <fstream> #include <istream> #include <ostream> #include <string> #include <vector> #include "CaesarCipher.hpp" #include "ProcessCommandLine.hpp" #include "TransformChar.hpp" // Main function of the mpags-cipher program int main(int argc, char* argv[]) { // Convert the command-line arguments into a more easily usable form const std::vector<std::string> cmdLineArgs {argv, argv+argc}; // Options that might be set by the command-line arguments bool helpRequested {false}; bool versionRequested {false}; std::string inputFile {""}; std::string outputFile {""}; bool decrypt {false}; unsigned int key {0}; if ( ! processCommandLine(cmdLineArgs, helpRequested, versionRequested, inputFile, outputFile, decrypt, key) ) return 1; // Error indication // Handle help, if requested if (helpRequested) { // Line splitting for readability std::cout << "Usage: mpags-cipher [-i <file>] [-o <file>] [-m <encrypt/decrypt>] -k <keylength>\n\n" << "Encrypts/Decrypts input alphanumeric text using classical ciphers\n\n" << "Available options:\n\n" << " -h|--help Print this help message and exit\n\n" << " --version Print version information\n\n" << " -i FILE Read text to be processed from FILE\n" << " Stdin will be used if not supplied\n\n" << " -o FILE Write processed text to FILE\n" << " Stdout will be used if not supplied\n\n" << " -m encrypt/decrypt Mode - encrypt or decrypt/n" << " encrypt if not supplied\n\n" << " -k keylength Length of the key to use\n\n" ; // Help requires no further action, so return from main // with 0 used to indicate success return 0; } // Handle version, if requested // Like help, requires no further action, // so return from main with zero to indicate success if (versionRequested) { std::cout << "0.1.0" << std::endl; return 0; } // Initialise variables for processing input text char inputChar {'x'}; std::string inputText {""}; // This will only be used if the input and output are both connected to stdin/stdout - otherwise we will write as we read // Read in user input from stdin/file // we'll cover better ways of doing this later than raw pointers (or tempates if you're feeling brave!) :) std::istream *input; std::ifstream infile; if ( inputFile.empty() ) input = &std::cin; else { infile.open(inputFile); input = &infile; } std::ostream *output; std::ofstream outfile; if ( outputFile.empty() ) output = &std::cout; else { outfile.open(outputFile); output = &outfile; } if ( ! input->good() || ! output->good() ) { std::cerr << "Problem with input or output file" << std::endl; return 1; } // Loop over each character from user input // (until Return then CTRL-D (EOF) pressed) while(*input >> inputChar) { std::string encrypted_char = runCaesarCipher(transformChar(inputChar), key, !decrypt); if ( inputFile.empty() && outputFile.empty() ) inputText += encrypted_char; else *output << encrypted_char; // Stream output if not reading/writing from stdin/out } // Output the transliterated text to stdout if buffered in memory because we were reading from stdin if (inputFile.empty() && outputFile.empty()) *output << inputText; *output << std::endl; // Finish with a newline // No requirement to return from main, but we do so for clarity // and for consistency with other functions return 0; }
;----------------------------------------------------------------------------- ;FILENAME: CHORD.SOURCE Chord buster Translation ;----------------------------------------------------------------------------- ;This source file contains code for the Stereo Editor translation of Jerry ;Roth's "Super Chord Buster". It is coded as a transient application. ;Transient applications load at $C000. Transient applications may use only the ;memory between $C000 and $CFFF, and zero page locations 100-131. Return with ;carry set ONLY if sid file needs to be saved after this application. .org $c000 .obj "016" ;-- Main Editor Interface storage -- start_heap = $7000 end_heap = $bf00 voice_start = 2 voice_end = 16 voice_pos = 30 nq_count = $bf10 nq_hot = $bf11 nq_app = $bf12 nq_name = $bf13 note_queue = $bf33 ;-- NEW Kernal routine equates -- setirq = $e000 print = $e003 lprint = $e006 printchar = $e009 printbyte = $e00c printword = $e00f select_string = $e012 save_screen = $e015 recall_screen = $e018 getrom = $e01b clear_screen = $e01e menudef = $e021 menuset = $e024 select = $e027 select_0 = $e02a headerdef = $e02d sizedef = $e030 s_itemx = $e033 s_itemy = $e036 s_itemlen = $e039 s_itemvecl = $e03c s_itemvech = $e03f s_itemvarl = $e042 s_itemvarh = $e045 s_itemmin = $e048 s_itemmax = $e04b s_itemtype = $e04e read_item = $e051 cursor_on = $e054 cursor_off = $e057 move_up = $e05a move_down = $e05d read_prdir = $e060 init_drive = $e063 load_prfile = $e066 preparef = $e069 releasef = $e06c setlfs = $e06f setnam = $e072 open = $e075 close = $e078 chkin = $e07b chkout = $e07e clrchn = $e081 chrin = $e084 chrout = $e087 getin = $e08a set_item = $e08d get_adr = $e090 backspace = $e093 read_err = $e096 read_error = $e099 ;-- Zero-page start of storage equate -- zp = 100 ;Start of zero page storage for this module ;-- Constants used by Kernal routines -- screen = $f400 s_base = screen s = s_base vic = $d000 c_base = $d800 c = c_base col_f1 = s_base-c_base col_factor = 65535-col_f1+1/256 kernal_in = %00000110 kernal_out = %00000101 eof = 1 def = 2 tab = 3 rvs = 4 rvsoff = 5 defl = 6 defr = 7 clr = 8 fkey = 10 box = 12 xx = 96 col = 176 yy = 224 eot = 255 dispatch = 1 service = 2 numeric = 3 string = 4 null'item = 5 eom = 0 ;-- Major storage -- base_note = $cf00 chord_type = $cf01 cur_item = $cf02 ;4 bytes ;-- Zero-page usage -- ptr = zp ;General-use pointer mod_flag = zp+4 ;1=SID in memory modified, 0=not r0 = zp+6 r1 = zp+8 r2 = zp+10 r3 = zp+12 heap_ptr = zp+14 item_ptr = zp+16 txtptr = $e0 ;Kernal interface variable colptr = $e2 ;Kernal interface variable start_m = $e2 ;Start of block to be moved end_m = $e4 ;End of block dest_m = $e6 ;Destination address for block ;-- Transient application ID text -- .asc "sid/app" .byte 016 ;File number .word init ;Starting address return_vec .word $ffff ;Filled in by main program - Return location stack_save .byte $fa ;-- Exit application -- exit = * ldx stack_save txs lsr mod_flag jmp (return_vec) ;-- Set flag indicating file modified -- modify = * lda #1 sta mod_flag rts ;-- Clear bottom of screen only (leave top logo alone). -- clear_bot = * ldy #0 lda #32 - sta s_base+200,y sta s_base+200+256,y sta s_base+200+512,y sta s_base+768-24,y iny bne - rts ;----------------------------------------------------------------------------- ; MAIN PROGRAM ;----------------------------------------------------------------------------- init = * tsx stx stack_save lda #0 sta mod_flag jsr print .byte clr,box,9,0,31,4,7,col+1,xx+11,yy+1 .asc "Super Chord Buster" .byte col+15,xx+10,yy+2 .asc "By Jerry Roth (Dr. J)" .byte xx+13,yy+3 .asc "Copyright 1988" .byte eot main_menu = * jsr clear_bot jsr print .byte box,6,9,33,16,6 .byte col+13,xx+10,yy+7 .asc "Choose base of chord:" .byte xx+4,yy+18,col+5 .asc "Commonly used chords in key of C:" .byte xx+7,yy+20,col+13 .asc "C F G C7 G7 A7 E7 D7" .byte xx+16,yy+21 .asc "Am Dm Em" .byte xx+9,yy+23,col+11 .asc "Press F5 to return to" .byte xx+13,yy+24 .asc "Stereo Editor" .byte eot ldx #yy+10 - txa jsr printchar jsr print .byte xx+12 .asc "................" .byte eot inx cpx #yy+16 bcc - jsr menudef .byte 4,3,1 .word exit,0,0,0 .byte dispatch,7,10,5 .word csel .asc "C" .byte dispatch,7,11,5 .word csel .asc "C#/Db" .byte dispatch,7,12,5 .word csel .asc "D" .byte dispatch,7,13,5 .word csel .asc "D#/Eb" .byte dispatch,7,14,5 .word csel .asc "E" .byte dispatch,7,15,5 .word csel .asc "F" .byte dispatch,28,10,5 .word csel .asc "F#/Gb" .byte dispatch,28,11,5 .word csel .asc "G" .byte dispatch,28,12,5 .word csel .asc "G#/Ab" .byte dispatch,28,13,5 .word csel .asc "A" .byte dispatch,28,14,5 .word csel .asc "A#/Bb" .byte dispatch,28,15,5 .word csel .asc "B" .byte eom jmp select ;-- Chord table. -- chord_tab = * .byte 1,5,8,0,0,0,0 .byte 1,4,8,0,0,0,0 .byte 1,5,9,0,0,0,0 .byte 1,4,7,0,0,0,0 .byte 1,5,8,10,0,0,0 .byte 1,4,8,10,0,0,0 .byte 1,5,8,10,3,0,0 .byte 1,5,8,11,0,0,0 .byte 1,5,9,11,0,0,0 .byte 1,5,7,11,0,0,0 .byte 1,5,8,12,0,0,0 .byte 1,4,8,11,0,0,0 .byte 1,4,9,11,0,0,0 .byte 1,4,7,11,0,0,0 .byte 1,4,7,10,0,0,0 .byte 1,5,8,11,3,0,0 .byte 1,5,9,11,3,0,0 .byte 1,5,7,11,3,0,0 .byte 1,5,8,12,3,0,0 .byte 1,4,8,11,3,0,0 .byte 1,4,9,11,3,0,0 .byte 1,4,7,11,3,0,0 .byte 1,5,8,11,3,6,0 .byte 1,5,8,11,3,6,10 ;-- Names of notes. -- note_tab = * .asc "C" .byte eot .asc "C#/Db" .byte eot .asc "D" .byte eot .asc "D#/Eb" .byte eot .asc "E" .byte eot .asc "F" .byte eot .asc "F#/Gb" .byte eot .asc "G" .byte eot .asc "G#/Ab" .byte eot .asc "A" .byte eot .asc "A#/Bb" .byte eot .asc "B" .byte eot ;-- Ordinal numbers. -- ordinal = * .asc "1st " .byte eot .asc "3rd " .byte eot .asc "5th " .byte eot .asc "7th " .byte eot .asc "9th " .byte eot .asc "11th" .byte eot .asc "13th" .byte eot ;-- The base chord has been selected. -- csel = * jsr read_item sta base_note c_reenter = * jsr clear_bot jsr print .byte box,3,9,37,22,6,def,40,0,7,13 .asc "Choose type of chord (" .byte eot lda #<note_tab sta txtptr lda #>note_tab sta txtptr+1 lda base_note jsr select_string jsr lprint jsr print .asc "):" .byte eof,col+11,eot ldx #yy+10 - txa jsr printchar jsr print .byte xx+18 .asc "....." .byte eot inx cpx #yy+22 bcc - jsr menudef .byte 5,3,1 .word main_menu,0,0,0 .byte dispatch,4,10,14 .word tsel .asc "Major" .byte dispatch,4,11,14 .word tsel .asc "Minor" .byte dispatch,4,12,14 .word tsel .asc "Augmented (+5)" .byte dispatch,4,13,14 .word tsel .asc "Diminished" .byte dispatch,4,14,14 .word tsel .asc "6th" .byte dispatch,4,15,14 .word tsel .asc "Minor 6th" .byte dispatch,4,16,14 .word tsel .asc "6th,9" .byte dispatch,4,17,14 .word tsel .asc "7th" .byte dispatch,4,18,14 .word tsel .asc "7th+5" .byte dispatch,4,19,14 .word tsel .asc "7th-5" .byte dispatch,4,20,14 .word tsel .asc "Major 7th" .byte dispatch,4,21,14 .word tsel .asc "Minor 7th" .byte dispatch,23,10,14 .word tsel .asc "Minor 7th+5" .byte dispatch,23,11,14 .word tsel .asc "Minor 7th-5" .byte dispatch,23,12,14 .word tsel .asc "Diminished 7th" .byte dispatch,23,13,14 .word tsel .asc "9th" .byte dispatch,23,14,14 .word tsel .asc "9th+5" .byte dispatch,23,15,14 .word tsel .asc "9th-5" .byte dispatch,23,16,14 .word tsel .asc "Major 9th" .byte dispatch,23,17,14 .word tsel .asc "Minor 9th" .byte dispatch,23,18,14 .word tsel .asc "Minor 9th+5" .byte dispatch,23,19,14 .word tsel .asc "Minor 9th-5" .byte dispatch,23,20,14 .word tsel .asc "11th" .byte dispatch,23,21,14 .word tsel .asc "13th" .byte eom jmp select ;-- Type of chord has been selected. -- tsel = * jsr read_item sta chord_type asl ; Multiply by 7 asl adc chord_type adc chord_type adc chord_type adc #<chord_tab sta r0 lda #>chord_tab adc #0 sta r0+1 jsr print .byte box,14,13,26,21,2,col+15,yy+14,eot jsr init_queue ldy #0 ts1 sty r2 lda #xx+15 jsr printchar lda (r0),y bne + jmp ts9 + clc adc base_note cmp #13 bcc ts2 sbc #12 ts2 sec sbc #1 sta r1 cpy #3 bne ts4 lda chord_type cmp #4 beq ts3 cmp #5 beq ts3 cmp #6 bne ts4 ts3 jsr print .asc "6th " .byte eot lda #"6" jsr add_heap lda #"t" jsr add_heap lda #"h" jsr add_heap lda #32 jsr add_heap ldy r2 jmp ts5 ts4 lda #<ordinal sta txtptr lda #>ordinal sta txtptr+1 tya jsr select_string jsr ladd_heap jsr lprint ts5 jsr print .byte "-"," ",eot lda #"-" jsr add_heap lda #" " jsr add_heap lda #<note_tab sta txtptr lda #>note_tab sta txtptr+1 lda r1 jsr select_string jsr ladd_heap jsr lprint lda #13 jsr printchar lda #"$" jsr add_heap lda #5 sta cur_item lda r1 sta cur_item+1 jsr add_note ts9 ldy r2 iny cpy #7 bcs tsa jmp ts1 tsa lda #<remove_opt sta txtptr lda #>remove_opt sta txtptr+1 jsr ladd_heap lda #4 sta cur_item jsr add_note - jsr getin beq - jmp c_reenter ;-- Initialize (clear) note queue. -- init_queue = * ldx #<our_name ldy #>our_name jsr set_util lda #0 sta nq_count sta nq_hot lda #16 sta nq_app lda #<note_queue+32 sta heap_ptr lda #>note_queue sta heap_ptr+1 sta item_ptr+1 lda #<note_queue sta item_ptr rts ;-- Add byte in .A to note_queue text heap. -- add_heap = * sty aqy+1 ldy #0 sta (heap_ptr),y inc heap_ptr aqy ldy #0 rts ;-- Add EOT-terminated text at txtptr to note_queue text heap. -- ladd_heap = * ldy #0 - lda (txtptr),y cmp #eot beq + jsr add_heap iny bne - + rts ;-- Add 4 bytes to note info table. -- add_note = * ldy #3 - lda cur_item,y sta (item_ptr),y dey bpl - lda item_ptr clc adc #4 sta item_ptr inc nq_count rts ;-- Set the utility menu name to the EOT-terminated string at .X and .Y -- set_util = * stx txtptr sty txtptr+1 ldy #0 - lda (txtptr),y sta nq_name,y cmp #eot beq + iny bne - + rts ;-- Util name. -- our_name .asc "ADD CHORD NOTES" .byte eot remove_opt .asc "Remove Menu$" .byte eot
#include "common.h" std::string g_log_tag;
#include <asio.hpp> #include <iostream> #include <memory> #include <map> #include <thread> #include "CollabVM.h" #ifndef _WIN32 #include "StackTrace.hpp" #define STACKTRACE PrintStackTrace(); #endif std::shared_ptr<CollabVMServer> server_; asio::io_service service_; std::unique_ptr<asio::io_service::work> work(new asio::io_service::work(service_)); bool stopping = false; void SignalHandler() { if (stopping) return; stopping = true; try { try { std::cout << "\nShutting down..." << std::endl; work.reset(); server_->Stop(); } catch (const websocketpp::exception& ex) { std::cout << "A websocketpp exception was thrown: " << ex.what() << std::endl; throw; } catch (const std::exception& ex) { std::cout << "An exception was thrown: " << ex.what() << std::endl; throw; } catch (...) { std::cout << "An unknown exception occurred\n"; throw; } } catch (...) { server_->Stop(); #ifndef _WIN32 PrintStackTrace(); #endif } } #ifdef _WIN32 BOOL CtrlHandler(DWORD fdwCtrlType) { switch (fdwCtrlType) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: case CTRL_CLOSE_EVENT: SignalHandler(); return TRUE; } return FALSE; } #endif static void SegFaultHandler(int signum) { std::cout << "A segmentation fault occured\n"; #ifndef _WIN32 PrintStackTrace(); #endif exit(-1); } template<typename F> void WorkerThread(F func) { try { try { func(); } catch (const websocketpp::exception& ex) { std::cout << "A websocketpp exception was thrown: " << ex.what() << std::endl; throw; } catch (const std::exception& ex) { std::cout << "An exception was thrown: " << ex.what() << std::endl; throw; } catch (...) { std::cout << "An unknown exception occurred\n"; throw; } } catch (...) { #ifndef _WIN32 PrintStackTrace(); #endif } server_->Stop(); work.reset(); } #ifndef UNIT_TEST int main(int argc, char* argv[]) { try { if (argc < 2 || argc > 3) { std::cout << "Usage: [Port] [HTTP dir]\n"; std::cout << "Port - the port to listen on for websocket and http requests\n"; std::cout << "HTTP dir (optional) - the directory to serve HTTP files from. defaults to \"http\"" " in the current directory\n"; std::cout << "\tEx: 80 web" << std::endl; return -1; } std::string s(argv[1]); size_t i; int port = stoi(s, &i); if (i != s.length() || !(port > 0 && port <= UINT16_MAX)) { std::cout << "Invalid port for websocket server_." << std::endl; return -1; } std::cout << "Collab VM Server started" << std::endl; // Set up Ctrl+C handler #ifdef _WIN32 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE)) std::cout << "Error setting console control handler." << std::endl << "Ctrl+C will not exit cleanly." << std::endl; #else struct sigaction sa; sa.sa_handler = &SegFaultHandler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGSEGV, &sa, NULL) == -1) std::cout << "Failed to set segmentation violation signal handler" << std::endl; asio::signal_set interruptSignal(service_, SIGINT, SIGTERM); interruptSignal.async_wait(std::bind(&SignalHandler)); #endif server_ = std::make_shared<CollabVMServer>(service_); std::thread t([] { WorkerThread([] { service_.run(); }); }); WorkerThread([&] { server_->Run(port, argc > 2 ? argv[2] : "http"); }); t.join(); } catch (websocketpp::exception const & e) { std::cout << "An exception was thrown:" << std::endl; std::cout << e.what() << std::endl; #ifndef _WIN32 PrintStackTrace(); #endif #ifdef _DEBUG throw; #endif return -1; } catch (...) { #ifdef _DEBUG throw; #endif return -1; } return 0; } #endif
#include "Sort_internal.hpp" #include "algo/algo_internal_interface.hpp" #include <iostream> #include <algorithm> #ifdef UNI_OMP #include <omp.h> #endif namespace cytnx{ namespace algo_internal{ bool _compare_c128(cytnx_complex128 a, cytnx_complex128 b) { if (real(a) == real(b)) return imag(a) < imag(b); return real(a) < real(b); } void Sort_internal_cd(boost::intrusive_ptr<Storage_base> & out, const cytnx_uint64 &stride, const cytnx_uint64 &Nelem){ cytnx_complex128 *p = (cytnx_complex128*)out->Mem; cytnx_uint64 Niter = Nelem/stride; for(cytnx_uint64 i=0;i<Niter;i++) std::sort(p+i*stride,p+i*stride+stride,_compare_c128); } bool _compare_c64(cytnx_complex64 a, cytnx_complex64 b) { if (real(a) == real(b)) return imag(a) < imag(b); return real(a) < real(b); } void Sort_internal_cf(boost::intrusive_ptr<Storage_base> & out, const cytnx_uint64 &stride, const cytnx_uint64 &Nelem){ cytnx_complex64 *p = (cytnx_complex64*)out->Mem; cytnx_uint64 Niter = Nelem/stride; for(cytnx_uint64 i=0;i<Niter;i++) std::sort(p+i*stride,p+i*stride+stride,_compare_c64); } void Sort_internal_d(boost::intrusive_ptr<Storage_base> & out, const cytnx_uint64 &stride, const cytnx_uint64 &Nelem){ double *p = (double*)out->Mem; cytnx_uint64 Niter = Nelem/stride; for(cytnx_uint64 i=0;i<Niter;i++) std::sort(p+i*stride,p+i*stride+stride); } void Sort_internal_f(boost::intrusive_ptr<Storage_base> & out, const cytnx_uint64 &stride, const cytnx_uint64 &Nelem){ float *p = (float*)out->Mem; cytnx_uint64 Niter = Nelem/stride; for(cytnx_uint64 i=0;i<Niter;i++) std::sort(p+i*stride,p+i*stride+stride); } void Sort_internal_u64(boost::intrusive_ptr<Storage_base> & out, const cytnx_uint64 &stride, const cytnx_uint64 &Nelem){ cytnx_uint64 *p = (cytnx_uint64*)out->Mem; cytnx_uint64 Niter = Nelem/stride; for(cytnx_uint64 i=0;i<Niter;i++) std::sort(p+i*stride,p+i*stride+stride); } void Sort_internal_i64(boost::intrusive_ptr<Storage_base> & out, const cytnx_uint64 &stride, const cytnx_uint64 &Nelem){ cytnx_int64 *p = (cytnx_int64*)out->Mem; cytnx_uint64 Niter = Nelem/stride; for(cytnx_uint64 i=0;i<Niter;i++) std::sort(p+i*stride,p+i*stride+stride); } void Sort_internal_u32(boost::intrusive_ptr<Storage_base> & out, const cytnx_uint64 &stride, const cytnx_uint64 &Nelem){ cytnx_uint32 *p = (cytnx_uint32*)out->Mem; cytnx_uint64 Niter = Nelem/stride; for(cytnx_uint64 i=0;i<Niter;i++) std::sort(p+i*stride,p+i*stride+stride); } void Sort_internal_i32(boost::intrusive_ptr<Storage_base> & out, const cytnx_uint64 &stride, const cytnx_uint64 &Nelem){ cytnx_int32 *p = (cytnx_int32*)out->Mem; cytnx_uint64 Niter = Nelem/stride; for(cytnx_uint64 i=0;i<Niter;i++) std::sort(p+i*stride,p+i*stride+stride); } void Sort_internal_u16(boost::intrusive_ptr<Storage_base> & out, const cytnx_uint64 &stride, const cytnx_uint64 &Nelem){ cytnx_uint16 *p = (cytnx_uint16*)out->Mem; cytnx_uint64 Niter = Nelem/stride; for(cytnx_uint64 i=0;i<Niter;i++) std::sort(p+i*stride,p+i*stride+stride); } void Sort_internal_i16(boost::intrusive_ptr<Storage_base> & out, const cytnx_uint64 &stride, const cytnx_uint64 &Nelem){ cytnx_int16 *p = (cytnx_int16*)out->Mem; cytnx_uint64 Niter = Nelem/stride; for(cytnx_uint64 i=0;i<Niter;i++) std::sort(p+i*stride,p+i*stride+stride); } void Sort_internal_b(boost::intrusive_ptr<Storage_base> & out, const cytnx_uint64 &stride, const cytnx_uint64 &Nelem){ /* cytnx_bool *p = (cytnx_bool*)out->Mem; cytnx_uint64 Niter = Nelem/stride; for(cytnx_uint64 i=0;i<Niter;i++) std::sort(p+i*stride,p+i*stride+stride); */ cytnx_error_msg(true,"[ERROR] cytnx currently does not have bool type sort.%s","\n"); } } }
bootblock.o: file format elf32-i386 Disassembly of section .text: 00007c00 <start>: # with %cs=0 %ip=7c00. .code16 # Assemble for 16-bit mode .globl start start: cli # BIOS enabled interrupts; disable 7c00: fa cli # Zero data segment registers DS, ES, and SS. xorw %ax,%ax # Set %ax to zero 7c01: 31 c0 xor %eax,%eax movw %ax,%ds # -> Data Segment 7c03: 8e d8 mov %eax,%ds movw %ax,%es # -> Extra Segment 7c05: 8e c0 mov %eax,%es movw %ax,%ss # -> Stack Segment 7c07: 8e d0 mov %eax,%ss 00007c09 <seta20.1>: # Physical address line A20 is tied to zero so that the first PCs # with 2 MB would run software that assumed 1 MB. Undo that. seta20.1: inb $0x64,%al # Wait for not busy 7c09: e4 64 in $0x64,%al testb $0x2,%al 7c0b: a8 02 test $0x2,%al jnz seta20.1 7c0d: 75 fa jne 7c09 <seta20.1> movb $0xd1,%al # 0xd1 -> port 0x64 7c0f: b0 d1 mov $0xd1,%al outb %al,$0x64 7c11: e6 64 out %al,$0x64 00007c13 <seta20.2>: seta20.2: inb $0x64,%al # Wait for not busy 7c13: e4 64 in $0x64,%al testb $0x2,%al 7c15: a8 02 test $0x2,%al jnz seta20.2 7c17: 75 fa jne 7c13 <seta20.2> movb $0xdf,%al # 0xdf -> port 0x60 7c19: b0 df mov $0xdf,%al outb %al,$0x60 7c1b: e6 60 out %al,$0x60 # Switch from real to protected mode. Use a bootstrap GDT that makes # virtual addresses map directly to physical addresses so that the # effective memory map doesn't change during the transition. lgdt gdtdesc 7c1d: 0f 01 16 lgdtl (%esi) 7c20: 78 7c js 7c9e <readsect+0xc> movl %cr0, %eax 7c22: 0f 20 c0 mov %cr0,%eax orl $CR0_PE, %eax 7c25: 66 83 c8 01 or $0x1,%ax movl %eax, %cr0 7c29: 0f 22 c0 mov %eax,%cr0 //PAGEBREAK! # Complete transition to 32-bit protected mode by using long jmp # to reload %cs and %eip. The segment descriptors are set up with no # translation, so that the mapping is still the identity mapping. ljmp $(SEG_KCODE<<3), $start32 7c2c: ea 31 7c 08 00 66 b8 ljmp $0xb866,$0x87c31 00007c31 <start32>: .code32 # Tell assembler to generate 32-bit code now. start32: # Set up the protected-mode data segment registers movw $(SEG_KDATA<<3), %ax # Our data segment selector 7c31: 66 b8 10 00 mov $0x10,%ax movw %ax, %ds # -> DS: Data Segment 7c35: 8e d8 mov %eax,%ds movw %ax, %es # -> ES: Extra Segment 7c37: 8e c0 mov %eax,%es movw %ax, %ss # -> SS: Stack Segment 7c39: 8e d0 mov %eax,%ss movw $0, %ax # Zero segments not ready for use 7c3b: 66 b8 00 00 mov $0x0,%ax movw %ax, %fs # -> FS 7c3f: 8e e0 mov %eax,%fs movw %ax, %gs # -> GS 7c41: 8e e8 mov %eax,%gs # Set up the stack pointer and call into C. movl $start, %esp 7c43: bc 00 7c 00 00 mov $0x7c00,%esp call bootmain 7c48: e8 e4 00 00 00 call 7d31 <bootmain> # If bootmain returns (it shouldn't), trigger a Bochs # breakpoint if running under Bochs, then loop. movw $0x8a00, %ax # 0x8a00 -> port 0x8a00 7c4d: 66 b8 00 8a mov $0x8a00,%ax movw %ax, %dx 7c51: 66 89 c2 mov %ax,%dx outw %ax, %dx 7c54: 66 ef out %ax,(%dx) movw $0x8ae0, %ax # 0x8ae0 -> port 0x8a00 7c56: 66 b8 e0 8a mov $0x8ae0,%ax outw %ax, %dx 7c5a: 66 ef out %ax,(%dx) 00007c5c <spin>: spin: jmp spin 7c5c: eb fe jmp 7c5c <spin> 7c5e: 66 90 xchg %ax,%ax 00007c60 <gdt>: ... 7c68: ff (bad) 7c69: ff 00 incl (%eax) 7c6b: 00 00 add %al,(%eax) 7c6d: 9a cf 00 ff ff 00 00 lcall $0x0,$0xffff00cf 7c74: 00 92 cf 00 17 00 add %dl,0x1700cf(%edx) 00007c78 <gdtdesc>: 7c78: 17 pop %ss 7c79: 00 60 7c add %ah,0x7c(%eax) 7c7c: 00 00 add %al,(%eax) 7c7e: 66 90 xchg %ax,%ax 00007c80 <waitdisk>: entry(); } void waitdisk(void) { 7c80: 55 push %ebp 7c81: 89 e5 mov %esp,%ebp static inline uchar inb(ushort port) { uchar data; asm volatile("in %1,%0" : "=a" (data) : "d" (port)); 7c83: ba f7 01 00 00 mov $0x1f7,%edx 7c88: ec in (%dx),%al // Wait for disk ready. while((inb(0x1F7) & 0xC0) != 0x40) 7c89: 83 e0 c0 and $0xffffffc0,%eax 7c8c: 3c 40 cmp $0x40,%al 7c8e: 75 f8 jne 7c88 <waitdisk+0x8> ; } 7c90: 5d pop %ebp 7c91: c3 ret 00007c92 <readsect>: // Read a single sector at offset into dst. void readsect(void *dst, uint offset) { 7c92: 55 push %ebp 7c93: 89 e5 mov %esp,%ebp 7c95: 57 push %edi 7c96: 53 push %ebx 7c97: 8b 5d 0c mov 0xc(%ebp),%ebx // Issue command. waitdisk(); 7c9a: e8 e1 ff ff ff call 7c80 <waitdisk> } static inline void outb(ushort port, uchar data) { asm volatile("out %0,%1" : : "a" (data), "d" (port)); 7c9f: ba f2 01 00 00 mov $0x1f2,%edx 7ca4: b8 01 00 00 00 mov $0x1,%eax 7ca9: ee out %al,(%dx) 7caa: b2 f3 mov $0xf3,%dl 7cac: 89 d8 mov %ebx,%eax 7cae: ee out %al,(%dx) 7caf: 0f b6 c7 movzbl %bh,%eax 7cb2: b2 f4 mov $0xf4,%dl 7cb4: ee out %al,(%dx) outb(0x1F2, 1); // count = 1 outb(0x1F3, offset); outb(0x1F4, offset >> 8); outb(0x1F5, offset >> 16); 7cb5: 89 d8 mov %ebx,%eax 7cb7: c1 e8 10 shr $0x10,%eax 7cba: b2 f5 mov $0xf5,%dl 7cbc: ee out %al,(%dx) outb(0x1F6, (offset >> 24) | 0xE0); 7cbd: c1 eb 18 shr $0x18,%ebx 7cc0: 89 d8 mov %ebx,%eax 7cc2: 83 c8 e0 or $0xffffffe0,%eax 7cc5: b2 f6 mov $0xf6,%dl 7cc7: ee out %al,(%dx) 7cc8: b2 f7 mov $0xf7,%dl 7cca: b8 20 00 00 00 mov $0x20,%eax 7ccf: ee out %al,(%dx) outb(0x1F7, 0x20); // cmd 0x20 - read sectors // Read data. waitdisk(); 7cd0: e8 ab ff ff ff call 7c80 <waitdisk> } static inline void insl(int port, void *addr, int cnt) { asm volatile("cld; rep insl" : 7cd5: 8b 7d 08 mov 0x8(%ebp),%edi 7cd8: b9 80 00 00 00 mov $0x80,%ecx 7cdd: ba f0 01 00 00 mov $0x1f0,%edx 7ce2: fc cld 7ce3: f3 6d rep insl (%dx),%es:(%edi) insl(0x1F0, dst, SECTSIZE/4); } 7ce5: 5b pop %ebx 7ce6: 5f pop %edi 7ce7: 5d pop %ebp 7ce8: c3 ret 00007ce9 <readseg>: // Read 'count' bytes at 'offset' from kernel into physical address 'pa'. // Might copy more than asked. void readseg(uchar* pa, uint count, uint offset) { 7ce9: 55 push %ebp 7cea: 89 e5 mov %esp,%ebp 7cec: 57 push %edi 7ced: 56 push %esi 7cee: 53 push %ebx 7cef: 83 ec 08 sub $0x8,%esp 7cf2: 8b 5d 08 mov 0x8(%ebp),%ebx 7cf5: 8b 75 10 mov 0x10(%ebp),%esi uchar* epa; epa = pa + count; 7cf8: 89 df mov %ebx,%edi 7cfa: 03 7d 0c add 0xc(%ebp),%edi // Round down to sector boundary. pa -= offset % SECTSIZE; 7cfd: 89 f0 mov %esi,%eax 7cff: 25 ff 01 00 00 and $0x1ff,%eax 7d04: 29 c3 sub %eax,%ebx // Translate from bytes to sectors; kernel starts at sector 1. offset = (offset / SECTSIZE) + 1; 7d06: c1 ee 09 shr $0x9,%esi 7d09: 83 c6 01 add $0x1,%esi // If this is too slow, we could read lots of sectors at a time. // We'd write more to memory than asked, but it doesn't matter -- // we load in increasing order. for(; pa < epa; pa += SECTSIZE, offset++) 7d0c: 39 df cmp %ebx,%edi 7d0e: 76 19 jbe 7d29 <readseg+0x40> readsect(pa, offset); 7d10: 89 74 24 04 mov %esi,0x4(%esp) 7d14: 89 1c 24 mov %ebx,(%esp) 7d17: e8 76 ff ff ff call 7c92 <readsect> offset = (offset / SECTSIZE) + 1; // If this is too slow, we could read lots of sectors at a time. // We'd write more to memory than asked, but it doesn't matter -- // we load in increasing order. for(; pa < epa; pa += SECTSIZE, offset++) 7d1c: 81 c3 00 02 00 00 add $0x200,%ebx 7d22: 83 c6 01 add $0x1,%esi 7d25: 39 df cmp %ebx,%edi 7d27: 77 e7 ja 7d10 <readseg+0x27> readsect(pa, offset); } 7d29: 83 c4 08 add $0x8,%esp 7d2c: 5b pop %ebx 7d2d: 5e pop %esi 7d2e: 5f pop %edi 7d2f: 5d pop %ebp 7d30: c3 ret 00007d31 <bootmain>: void readseg(uchar*, uint, uint); void bootmain(void) { 7d31: 55 push %ebp 7d32: 89 e5 mov %esp,%ebp 7d34: 57 push %edi 7d35: 56 push %esi 7d36: 53 push %ebx 7d37: 83 ec 1c sub $0x1c,%esp uchar* pa; elf = (struct elfhdr*)0x10000; // scratch space // Read 1st page off disk readseg((uchar*)elf, 4096, 0); 7d3a: c7 44 24 08 00 00 00 movl $0x0,0x8(%esp) 7d41: 00 7d42: c7 44 24 04 00 10 00 movl $0x1000,0x4(%esp) 7d49: 00 7d4a: c7 04 24 00 00 01 00 movl $0x10000,(%esp) 7d51: e8 93 ff ff ff call 7ce9 <readseg> // Is this an ELF executable? if(elf->magic != ELF_MAGIC) 7d56: 81 3d 00 00 01 00 7f cmpl $0x464c457f,0x10000 7d5d: 45 4c 46 7d60: 75 57 jne 7db9 <bootmain+0x88> return; // let bootasm.S handle error // Load each program segment (ignores ph flags). ph = (struct proghdr*)((uchar*)elf + elf->phoff); 7d62: a1 1c 00 01 00 mov 0x1001c,%eax 7d67: 8d 98 00 00 01 00 lea 0x10000(%eax),%ebx eph = ph + elf->phnum; 7d6d: 0f b7 35 2c 00 01 00 movzwl 0x1002c,%esi 7d74: c1 e6 05 shl $0x5,%esi 7d77: 01 de add %ebx,%esi for(; ph < eph; ph++){ 7d79: 39 f3 cmp %esi,%ebx 7d7b: 73 36 jae 7db3 <bootmain+0x82> pa = (uchar*)ph->paddr; 7d7d: 8b 7b 0c mov 0xc(%ebx),%edi readseg(pa, ph->filesz, ph->off); 7d80: 8b 43 04 mov 0x4(%ebx),%eax 7d83: 89 44 24 08 mov %eax,0x8(%esp) 7d87: 8b 43 10 mov 0x10(%ebx),%eax 7d8a: 89 44 24 04 mov %eax,0x4(%esp) 7d8e: 89 3c 24 mov %edi,(%esp) 7d91: e8 53 ff ff ff call 7ce9 <readseg> if(ph->memsz > ph->filesz) 7d96: 8b 4b 14 mov 0x14(%ebx),%ecx 7d99: 8b 43 10 mov 0x10(%ebx),%eax 7d9c: 39 c1 cmp %eax,%ecx 7d9e: 76 0c jbe 7dac <bootmain+0x7b> stosb(pa + ph->filesz, 0, ph->memsz - ph->filesz); 7da0: 01 c7 add %eax,%edi 7da2: 29 c1 sub %eax,%ecx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 7da4: b8 00 00 00 00 mov $0x0,%eax 7da9: fc cld 7daa: f3 aa rep stos %al,%es:(%edi) return; // let bootasm.S handle error // Load each program segment (ignores ph flags). ph = (struct proghdr*)((uchar*)elf + elf->phoff); eph = ph + elf->phnum; for(; ph < eph; ph++){ 7dac: 83 c3 20 add $0x20,%ebx 7daf: 39 de cmp %ebx,%esi 7db1: 77 ca ja 7d7d <bootmain+0x4c> } // Call the entry point from the ELF header. // Does not return! entry = (void(*)(void))(elf->entry); entry(); 7db3: ff 15 18 00 01 00 call *0x10018 } 7db9: 83 c4 1c add $0x1c,%esp 7dbc: 5b pop %ebx 7dbd: 5e pop %esi 7dbe: 5f pop %edi 7dbf: 5d pop %ebp 7dc0: c3 ret
; A102592: a(n) = Sum_{k=0..n} binomial(2n+1, 2k)*5^(n-k). ; 1,8,80,832,8704,91136,954368,9994240,104660992,1096024064,11477712896,120196169728,1258710630400,13181388849152,138037296103424,1445545331654656,15137947242201088,158526641599938560 mul $0,2 add $0,3 seq $0,87205 ; a(n) = -2*a(n-1) + 4*a(n-2), a(0)=1, a(1)=2. div $0,8
CGADiamondJ label byte word C_BLACK Bitmap <67,41,0,BMF_MONO> db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 db 0x07, 0xe0, 0x00, 0x3b, 0x76, 0xd0, 0x00, 0x0e, 0x00 db 0x01, 0x80, 0x00, 0x6d, 0x8d, 0xb4, 0x03, 0x34, 0x00 db 0x01, 0x9f, 0xff, 0xeb, 0x79, 0x6f, 0xfe, 0xea, 0x00 db 0x01, 0x90, 0x70, 0x1f, 0xff, 0xf0, 0x05, 0xb4, 0x00 db 0x01, 0x91, 0xac, 0x14, 0x05, 0x50, 0x06, 0x8e, 0x00 db 0x31, 0x93, 0x56, 0x15, 0x9a, 0xa8, 0x05, 0x80, 0x00 db 0x1f, 0x16, 0xab, 0x34, 0x42, 0xa8, 0xc6, 0x8c, 0x00 db 0x00, 0x13, 0x56, 0x54, 0x82, 0xa8, 0x7d, 0xf8, 0x00 db 0x00, 0x11, 0xac, 0x34, 0x42, 0xbc, 0x1f, 0xe0, 0x00 db 0x00, 0x10, 0x70, 0x56, 0x05, 0x6a, 0x05, 0x80, 0x00 db 0x00, 0x10, 0x00, 0x7b, 0xeb, 0xdc, 0x06, 0x80, 0x00 db 0x00, 0x10, 0x07, 0xe0, 0x1e, 0x0f, 0x05, 0x80, 0x00 db 0x00, 0x18, 0x7e, 0xbc, 0x00, 0x71, 0xde, 0x80, 0x00 db 0x00, 0x35, 0xf7, 0x5b, 0xff, 0x86, 0x2f, 0x80, 0x00 db 0x00, 0x2f, 0xc7, 0xac, 0x03, 0x1a, 0x28, 0x60, 0x00 db 0x00, 0x34, 0x1c, 0xd6, 0x0c, 0x74, 0x28, 0x20, 0x00 db 0x00, 0x2f, 0xf6, 0x6b, 0x39, 0x9a, 0x24, 0x20, 0x00 db 0x00, 0x35, 0x71, 0x35, 0xfe, 0x4d, 0x1f, 0xc0, 0x00 db 0x00, 0x2c, 0xac, 0x9b, 0xfb, 0x26, 0xa6, 0x80, 0x00 db 0x00, 0x7f, 0x16, 0x4f, 0xf5, 0x91, 0xd5, 0x80, 0x00 db 0x00, 0x84, 0x8b, 0x33, 0x9a, 0xcd, 0xfe, 0x80, 0x00 db 0x00, 0x82, 0x85, 0xc6, 0x0d, 0x67, 0x05, 0x80, 0x00 db 0x00, 0xc2, 0x8b, 0x18, 0x06, 0xbc, 0x7e, 0x80, 0x00 db 0x00, 0x3e, 0x8c, 0x3f, 0xfb, 0x5d, 0xf5, 0x80, 0x00 db 0x00, 0x2f, 0x71, 0xc0, 0x07, 0xaf, 0xc3, 0x00, 0x00 db 0x00, 0x34, 0x1e, 0x0f, 0x00, 0xfc, 0x01, 0x00, 0x00 db 0x00, 0x2c, 0x07, 0x7a, 0xfb, 0xc0, 0x01, 0x00, 0x00 db 0x00, 0x34, 0x0a, 0xd4, 0x0d, 0x41, 0xc1, 0x00, 0x00 db 0x00, 0xff, 0x07, 0xa8, 0x45, 0x86, 0xb1, 0x00, 0x00 db 0x03, 0xf7, 0xc2, 0xa8, 0x25, 0x4d, 0x59, 0x00, 0x00 db 0x06, 0x2c, 0x62, 0xa8, 0x45, 0x9a, 0xad, 0x1f, 0x00 db 0x00, 0x34, 0x02, 0xab, 0x35, 0x0d, 0x59, 0x31, 0x80 db 0x0e, 0x2c, 0x01, 0x54, 0x05, 0x06, 0xb1, 0x30, 0x00 db 0x05, 0xb4, 0x01, 0xff, 0xff, 0x01, 0xc1, 0x30, 0x00 db 0x0a, 0xef, 0xfe, 0xd3, 0xda, 0xff, 0xff, 0x30, 0x00 db 0x05, 0x98, 0x05, 0xb6, 0x36, 0xc0, 0x00, 0x30, 0x00 db 0x0e, 0x00, 0x01, 0x6d, 0xdb, 0x80, 0x00, 0xfc, 0x00 db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
; A164463: Number of binary strings of length n with no substrings equal to 0001 0100 or 0110 ; Submitted by Christian Krause ; 13,20,31,50,82,134,217,350,565,914,1480,2396,3877,6272,10147,16418,26566,42986,69553,112538,182089,294626,476716,771344,1248061,2019404,3267463,5286866,8554330,13841198,22395529,36236726,58632253,94868978,153501232,248370212,401871445,650241656,1052113099,1702354754,2754467854,4456822610,7211290465,11668113074,18879403537,30547516610,49426920148,79974436760,129401356909,209375793668,338777150575,548152944242,886930094818,1435083039062,2322013133881,3757096172942,6079109306821,9836205479762 add $0,2 mov $2,1 mov $3,1 lpb $0 sub $0,1 add $3,1 add $5,2 add $5,$1 mov $1,$3 add $1,1 sub $3,$4 mov $4,$2 mov $2,$3 add $2,$4 sub $2,$1 add $5,$4 mov $3,$5 add $3,2 lpe mov $0,$5 add $0,5
/* * Copyright (c) 2018-2021 Arm Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "src/gpu/cl/operators/ClWinogradConv2d.h" #include "arm_compute/core/CL/ICLTensor.h" #include "arm_compute/core/Utils.h" #include "arm_compute/core/Validate.h" #include "arm_compute/core/experimental/Types.h" #include "arm_compute/core/utils/misc/ShapeCalculator.h" #include "arm_compute/runtime/CL/CLScheduler.h" #include "src/core/CL/kernels/CLFillBorderKernel.h" #include "src/core/CL/kernels/CLFillBorderKernel.h" #include "src/core/helpers/MemoryHelpers.h" #include "src/gpu/cl/kernels/ClWinogradFilterTransformKernel.h" #include "src/gpu/cl/kernels/ClWinogradInputTransformKernel.h" #include "src/gpu/cl/kernels/ClWinogradOutputTransformKernel.h" #include "src/gpu/cl/utils/ClAuxTensorHandler.h" #include "src/common/utils/Log.h" #include "support/Cast.h" using namespace arm_compute::experimental; namespace arm_compute { namespace opencl { namespace { Size2D winograd_output_tile(const Size2D &input_dims, const Size2D &kernel_dims, DataLayout data_layout) { Size2D output_tile = Size2D{}; const unsigned int kernel_max_dim = std::max(kernel_dims.width, kernel_dims.height); // Check if the input spatial dimensions are smaller than 4 const bool is_input_lt4_nchw = (input_dims.width <= 4 && input_dims.height <= 4) && (data_layout == DataLayout::NCHW); if(kernel_max_dim == 3U) { if(kernel_dims == Size2D(3U, 3U)) { output_tile = is_input_lt4_nchw ? Size2D(2U, 2U) : Size2D(4U, 4U); } else if(kernel_dims == Size2D(3U, 1U)) { output_tile = is_input_lt4_nchw ? Size2D(2U, 1U) : Size2D(4U, 1U); } else { output_tile = is_input_lt4_nchw ? Size2D(1U, 2U) : Size2D(1U, 4U); } } else if(kernel_max_dim == 5U) { output_tile = Size2D(kernel_dims.width == 1 ? 1U : 4U, kernel_dims.height == 1 ? 1U : 4U); } else if(kernel_max_dim == 7U) { output_tile = Size2D(kernel_dims.width == 1 ? 1U : 2U, kernel_dims.height == 1 ? 1U : 2U); } return output_tile; } bool check_support_fast_math(const Size2D &output_tile, const Size2D &kernel_size) { // Check if we want to configure a Winograd configuration which requires fast math using WinogradConfiguration = std::pair<std::pair<int, int>, std::pair<int, int>>; std::vector<WinogradConfiguration> fast_math_winograd = { WinogradConfiguration(std::pair<int, int>(4, 4), std::pair<int, int>(5, 5)), WinogradConfiguration(std::pair<int, int>(2, 2), std::pair<int, int>(7, 7)) }; auto p = std::make_pair(std::pair<int, int>(output_tile.width, output_tile.height), std::pair<int, int>(kernel_size.width, kernel_size.height)); return std::find(fast_math_winograd.begin(), fast_math_winograd.end(), p) != fast_math_winograd.end(); } Status validate_arguments(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const PadStrideInfo &conv_info, const ActivationLayerInfo &act_info, bool enable_fast_math) { // Get indeces for the width and height const size_t idx_width = get_data_layout_dimension_index(src->data_layout(), DataLayoutDimension::WIDTH); const size_t idx_height = get_data_layout_dimension_index(src->data_layout(), DataLayoutDimension::HEIGHT); // Input shape, kernel size and output tile const Size2D input_dims = Size2D(src->tensor_shape()[idx_width], src->tensor_shape()[idx_height]); const Size2D kernel_size = Size2D(weights->tensor_shape()[idx_width], weights->tensor_shape()[idx_height]); const Size2D output_tile = winograd_output_tile(input_dims, kernel_size, src->data_layout()); ARM_COMPUTE_RETURN_ERROR_ON_MSG(((conv_info.pad_left() > (kernel_size.x() / 2u)) || (conv_info.pad_right() > (kernel_size.x() / 2u))), "Winograd only supports padding up to half kernel size"); ARM_COMPUTE_RETURN_ERROR_ON_MSG(((conv_info.pad_top() > (kernel_size.y() / 2u)) || (conv_info.pad_bottom() > (kernel_size.y() / 2u))), "Winograd only supports padding up to half kernel size"); // Check if the Winograd configuration requires fast math if(!enable_fast_math) { ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::F32); //disable winograd for fp16 if fast math is false. ARM_COMPUTE_RETURN_ERROR_ON_MSG(check_support_fast_math(output_tile, kernel_size), "This Winograd configuration requires enable_fast_math=true"); } const WinogradInfo winograd_info = WinogradInfo(output_tile, kernel_size, input_dims, conv_info, src->data_layout()); // Validate input transform const TensorShape input0_shape = misc::shape_calculator::compute_winograd_input_transform_shape(*src, winograd_info); const TensorInfo input0 = src->clone()->set_tensor_shape(input0_shape); ARM_COMPUTE_RETURN_ON_ERROR(kernels::ClWinogradInputTransformKernel::validate(src, &input0, winograd_info)); // Validate filter transform const TensorShape input1_shape = misc::shape_calculator::compute_winograd_filter_transform_shape(*weights, winograd_info); const TensorInfo input1 = weights->clone()->set_tensor_shape(input1_shape); ARM_COMPUTE_RETURN_ON_ERROR(kernels::ClWinogradFilterTransformKernel::validate(weights, &input1, winograd_info)); // Validate batched matrix multiply TensorShape batched_mm_output_shape = input0.tensor_shape(); batched_mm_output_shape[0] = input1.tensor_shape()[0]; const TensorInfo batched_mm_output = input0.clone()->set_tensor_shape(batched_mm_output_shape); ARM_COMPUTE_RETURN_ON_ERROR(ClGemm::validate(&input0, &input1, nullptr, &batched_mm_output, 1.0f, 0.0f, GEMMInfo(false, false, true /* Reshape weights only for the first run*/, 0, false, false, GEMMLowpOutputStageInfo(), (src->data_type() == DataType::F16)))); // Configure output transform ARM_COMPUTE_RETURN_ON_ERROR(kernels::ClWinogradOutputTransformKernel::validate(&batched_mm_output, biases, dst, winograd_info, act_info)); return Status{}; } } // namespace ClWinogradConv2d::ClWinogradConv2d() : _batched_mm(), _input_transform(std::make_unique<kernels::ClWinogradInputTransformKernel>()), _filter_transform(std::make_unique<kernels::ClWinogradFilterTransformKernel>()), _output_transform(std::make_unique<kernels::ClWinogradOutputTransformKernel>()), _border_handler(), _input0(), _input1(), _batched_mm_output(), _is_prepared(false), _aux_mem() { } ClWinogradConv2d::~ClWinogradConv2d() = default; void ClWinogradConv2d::configure(const ClCompileContext &compile_context, ITensorInfo *src, ITensorInfo *weights, ITensorInfo *biases, ITensorInfo *dst, const PadStrideInfo &conv_info, const ActivationLayerInfo &act_info, bool enable_fast_math) { ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(src, weights, biases, dst, conv_info, act_info, enable_fast_math)); ARM_COMPUTE_LOG_PARAMS(src, weights, biases, dst, conv_info, act_info, enable_fast_math); // Get indices for the width and height const size_t idx_width = get_data_layout_dimension_index(src->data_layout(), DataLayoutDimension::WIDTH); const size_t idx_height = get_data_layout_dimension_index(src->data_layout(), DataLayoutDimension::HEIGHT); // Input shape, kernel size and output tile const Size2D input_dims = Size2D(src->tensor_shape()[idx_width], src->tensor_shape()[idx_height]); const Size2D kernel_size = Size2D(weights->tensor_shape()[idx_width], weights->tensor_shape()[idx_height]); const Size2D output_tile = winograd_output_tile(input_dims, kernel_size, src->data_layout()); // Check if the Winograd configuration requires fast math if(!enable_fast_math) { ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::F32); //disable winograd for fp16 if fast math is false. ARM_COMPUTE_ERROR_ON_MSG(check_support_fast_math(output_tile, kernel_size), "This Winograd configuration requires enable_fast_math=true"); } const WinogradInfo winograd_info = WinogradInfo(output_tile, kernel_size, input_dims, conv_info, src->data_layout()); _is_prepared = false; // Configure input transform _input_transform->configure(compile_context, src, &_input0, winograd_info); _border_handler.configure(compile_context, src, _input_transform->border_size(), BorderMode::CONSTANT, PixelValue()); // Configure filter transform _filter_transform->configure(compile_context, weights, &_input1, winograd_info); // Configure batched matrix multiply _batched_mm.configure(compile_context, &_input0, &_input1, nullptr, &_batched_mm_output, 1.0f, 0.0f, GEMMInfo(false, false, true /* Reshape weights only for the first run*/, 0, false, false, GEMMLowpOutputStageInfo(), (src->data_type() == DataType::F16))); // Configure output transform _output_transform->configure(compile_context, &_batched_mm_output, biases, dst, winograd_info, act_info); _aux_mem = _batched_mm.workspace(); const MemoryLifetime wino_wei_lifetm = std::any_of(std::begin(_aux_mem), std::end(_aux_mem), [](const auto & r) { return (r.lifetime == MemoryLifetime::Persistent) && (r.size > 0); }) ? MemoryLifetime::Prepare : MemoryLifetime::Persistent; _aux_mem.push_back(MemoryInfo(offset_int_vec(2), MemoryLifetime::Temporary, _input0.total_size())); _aux_mem.push_back(MemoryInfo(offset_int_vec(3), wino_wei_lifetm, _input1.total_size())); _aux_mem.push_back(MemoryInfo(offset_int_vec(4), MemoryLifetime::Temporary, _batched_mm_output.total_size())); } Status ClWinogradConv2d::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const PadStrideInfo &conv_info, const ActivationLayerInfo &act_info, bool enable_fast_math) { ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(src, weights, biases, dst, conv_info, act_info, enable_fast_math)); return Status{}; } void ClWinogradConv2d::run(ITensorPack &tensors) { const bool is_gemm_reshaped = _aux_mem[3].lifetime == MemoryLifetime::Prepare; auto src = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_0)); auto biases = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_2)); auto dst = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(TensorType::ACL_DST)); CLAuxTensorHandler input0(offset_int_vec(2), _input0, tensors, true); CLAuxTensorHandler input1(offset_int_vec(3), _input1, tensors, true, is_gemm_reshaped); CLAuxTensorHandler batched_mm_output(offset_int_vec(4), _batched_mm_output, tensors, true); prepare(tensors); // Run input transform ITensorPack pack_it { { TensorType::ACL_SRC, src }, { TensorType::ACL_DST, input0.get() }, }; CLScheduler::get().enqueue_op(_border_handler, pack_it, false); CLScheduler::get().enqueue_op(*_input_transform, pack_it, false); // Run batched matrix multiplication ITensorPack pack_mm = tensors; pack_mm.add_const_tensor(TensorType::ACL_SRC_0, input0.get()); pack_mm.add_tensor(TensorType::ACL_DST, batched_mm_output.get()); is_gemm_reshaped ? pack_mm.remove_tensor(TensorType::ACL_SRC_1) : pack_mm.add_const_tensor(TensorType::ACL_SRC_1, input1.get()); _batched_mm.run(pack_mm); // Run output transform ITensorPack pack_ot { { TensorType::ACL_SRC_0, batched_mm_output.get() }, { TensorType::ACL_SRC_1, biases }, { TensorType::ACL_DST, dst }, }; CLScheduler::get().enqueue_op(*_output_transform, pack_ot); } void ClWinogradConv2d::prepare(ITensorPack &tensors) { if(!_is_prepared) { auto weights = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_1)); ICLTensor *in1_aux = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(offset_int_vec(3))); CLAuxTensorHandler input1(_input1, *in1_aux); ITensorPack pack_ft { { TensorType::ACL_SRC, weights }, { TensorType::ACL_DST, input1.get() }, }; // Run filter transform and mark original weights as unused CLScheduler::get().enqueue_op(*_filter_transform, pack_ft, false); weights->mark_as_unused(); // Prepare GEMM and release reshaped weights if marked unused by ClGemm ITensorPack mm_prepare_pack = tensors; mm_prepare_pack.add_tensor(ACL_SRC_1, input1.get()); _batched_mm.prepare(mm_prepare_pack); CLScheduler::get().queue().finish(); _is_prepared = true; } } experimental::MemoryRequirements ClWinogradConv2d::workspace() const { return _aux_mem; } } // namespace opencl } // namespace arm_compute
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/directconnect/model/CreateDirectConnectGatewayAssociationResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::DirectConnect::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; CreateDirectConnectGatewayAssociationResult::CreateDirectConnectGatewayAssociationResult() { } CreateDirectConnectGatewayAssociationResult::CreateDirectConnectGatewayAssociationResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } CreateDirectConnectGatewayAssociationResult& CreateDirectConnectGatewayAssociationResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("directConnectGatewayAssociation")) { m_directConnectGatewayAssociation = jsonValue.GetObject("directConnectGatewayAssociation"); } return *this; }
// RUN: %clang_cc1 -triple arm64-none-linux -emit-llvm -w -o - %s | FileCheck -check-prefix=PCS %s // PCS: define{{.*}} void @{{.*}}(i8 %a struct s0 {}; void f0(s0 a) {}
Music_Dungeon2_Ch0:: tempo 144 volume 7, 7 duty 3 toggleperfectpitch vibrato 10, 1, 4 Music_Dungeon2_branch_7e892:: notetype 12, 11, 2 octave 4 E_ 4 E_ 4 E_ 4 E_ 4 A# 4 A# 4 A# 4 A# 4 E_ 4 E_ 4 E_ 4 E_ 4 octave 5 C# 4 C# 4 C# 4 C# 4 octave 3 E_ 4 E_ 4 E_ 4 E_ 4 A# 4 A# 4 A# 4 A# 4 octave 2 G_ 2 A# 4 G_ 2 octave 3 C# 4 octave 2 G_ 2 A# 2 B_ 2 G_ 2 octave 3 C# 4 octave 2 G_ 2 A_ 4 F# 2 loopchannel 2, Music_Dungeon2_branch_7e892 notetype 12, 1, 15 octave 3 E_ 16 C_ 16 D_ 16 octave 2 A# 16 rest 16 rest 16 rest 16 rest 16 rest 16 rest 16 rest 16 rest 16 loopchannel 0, Music_Dungeon2_branch_7e892 Music_Dungeon2_Ch1:: vibrato 11, 1, 5 Music_Dungeon2_branch_7e8db:: duty 3 notetype 12, 12, 2 octave 3 E_ 4 E_ 4 E_ 4 E_ 4 C_ 4 C_ 4 C_ 4 C_ 4 E_ 4 E_ 4 E_ 4 E_ 4 C_ 4 C_ 4 C_ 4 C_ 4 B_ 4 B_ 4 B_ 4 B_ 4 octave 4 F# 4 F# 4 F# 4 F# 4 D_ 4 D_ 4 D_ 4 D_ 4 G_ 4 G_ 4 G_ 4 F# 4 loopchannel 2, Music_Dungeon2_branch_7e8db octave 3 E_ 2 G_ 2 E_ 2 D# 2 E_ 2 E_ 2 octave 5 E_ 2 rest 2 D# 2 rest 2 D_ 2 rest 2 C# 2 C_ 2 octave 4 E_ 2 G_ 2 octave 3 A# 2 C# 2 A# 2 A_ 2 A# 2 G_ 2 octave 5 G_ 2 rest 2 F# 2 rest 2 F_ 2 rest 2 E_ 2 D# 2 D_ 2 C# 2 rest 16 rest 16 rest 16 rest 16 notetype 12, 12, 7 duty 1 octave 4 E_ 16 D_ 16 C_ 16 D_ 16 loopchannel 0, Music_Dungeon2_branch_7e8db Music_Dungeon2_Ch2:: notetype 12, 1, 3 vibrato 8, 2, 6 Music_Dungeon2_branch_7e940:: callchannel Music_Dungeon2_branch_7e9d1 loopchannel 16, Music_Dungeon2_branch_7e940 E_ 4 rest 4 rest 4 E_ 4 C_ 4 rest 4 rest 4 C_ 4 D_ 4 rest 4 rest 4 D_ 4 octave 3 A# 4 rest 4 rest 4 A# 4 Music_Dungeon2_branch_7e958:: octave 5 E_ 2 rest 2 B_ 2 rest 2 A# 2 rest 2 octave 6 D_ 2 rest 2 C# 2 rest 2 octave 5 G# 2 rest 2 G_ 2 rest 2 B_ 2 rest 2 A# 2 rest 2 E_ 2 rest 2 D# 2 rest 2 A_ 2 rest 2 G# 2 rest 2 E_ 2 rest 2 F# 2 rest 2 D# 2 rest 2 loopchannel 3, Music_Dungeon2_branch_7e958 octave 4 E_ 4 B_ 4 A# 4 octave 5 D_ 4 C# 4 octave 4 G# 4 G_ 4 B_ 4 A# 4 E_ 4 D# 4 A_ 4 G# 4 E_ 4 F# 4 D# 4 octave 3 E_ 16 C_ 16 D_ 16 octave 2 A# 16 octave 3 E_ 16 F_ 16 G_ 16 octave 3 B_ 16 rest 16 rest 16 rest 16 rest 16 callchannel Music_Dungeon2_branch_7e9d1 callchannel Music_Dungeon2_branch_7e9d1 callchannel Music_Dungeon2_branch_7e9d1 callchannel Music_Dungeon2_branch_7e9d1 callchannel Music_Dungeon2_branch_7e9d1 callchannel Music_Dungeon2_branch_7e9d1 callchannel Music_Dungeon2_branch_7e9d1 callchannel Music_Dungeon2_branch_7e9d1 loopchannel 0, Music_Dungeon2_branch_7e940 octave 2 G_ 2 A# 4 G_ 2 octave 3 C# 4 octave 2 G_ 2 A_ 2 A# 2 G_ 2 octave 3 C# 4 octave 2 G_ 2 A# 2 G_ 2 rest 2 endchannel Music_Dungeon2_branch_7e9d1:: octave 4 E_ 2 rest 4 octave 3 E_ 1 rest 3 E_ 1 rest 1 octave 4 F# 4 endchannel Music_Dungeon2_Ch3:: dspeed 12 Music_Dungeon2_branch_7e9dd:: cymbal1 4 cymbal2 4 cymbal1 4 snare8 4 cymbal1 4 cymbal2 4 snare9 4 snare7 4 loopchannel 0, Music_Dungeon2_branch_7e9dd
// -*- C++ -*- // // $Id: SHMIOP_Endpoint.inl 73791 2006-07-27 20:54:56Z wotte $ TAO_BEGIN_VERSIONED_NAMESPACE_DECL ACE_INLINE const char * TAO_SHMIOP_Endpoint::host (void) const { return this->host_.in (); } ACE_INLINE CORBA::UShort TAO_SHMIOP_Endpoint::port (void) const { return this->port_; } ACE_INLINE CORBA::UShort TAO_SHMIOP_Endpoint::port (CORBA::UShort p) { return this->port_ = p; } TAO_END_VERSIONED_NAMESPACE_DECL
; void fzx_state_init(struct fzx_state *fs, struct fzx_font *ff, struct r_Rect16 *window) SECTION code_font_fzx PUBLIC asm_fzx_state_init EXTERN __fzx_draw_xor, l_setmem_hl asm_fzx_state_init: ; initialize cross-platform portion of fzx_state ; ; enter : hl = struct fzx_state * ; bc = struct fzx_font * ; de = struct r_Rect16 * ; ; exit : hl = & fzx_state.left_margin + 2b ; ; uses : af, bc, de, hl ld (hl),195 inc hl ld (hl),__fzx_draw_xor % 256 inc hl ld (hl),__fzx_draw_xor / 256 inc hl ld (hl),c inc hl ld (hl),b inc hl xor a call l_setmem_hl - 8 ex de,hl ld bc,8 ldir ex de,hl ld (hl),3 inc hl jp l_setmem_hl - 8
bits 32 section .multiboot ;according to muiltiboot spec dd 0x1BADB002 ;Magic number for bootloader dd 0x0 ; set flags dd - (0x1BADB002 + 0x0) ; checksum section .text global start extern main ; defined in the C file start: cli ; block interrupts mov esp, stack_space ; set stack pointer call main hlt ; halt the CPU section .bss resb 8192 ; 8KB for the stack stack_space:
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/navcoin-config.h> #endif #include <net.h> #include <addrman.h> #include <chainparams.h> #include <clientversion.h> #include <consensus/consensus.h> #include <crypto/common.h> #include <crypto/sha256.h> #include <hash.h> #include <primitives/transaction.h> #include <scheduler.h> #include <ui_interface.h> #include <utilstrencodings.h> #ifdef WIN32 #include <string.h> #else #include <fcntl.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniupnpc.h> #include <miniupnpc/miniwget.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif #include <boost/filesystem.hpp> #include <boost/thread.hpp> #include <math.h> // Dump addresses to peers.dat and banlist.dat every 15 minutes (900s) #define DUMP_ADDRESSES_INTERVAL 900 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h. // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version. #ifdef WIN32 #ifndef PROTECTION_LEVEL_UNRESTRICTED #define PROTECTION_LEVEL_UNRESTRICTED 10 #endif #ifndef IPV6_PROTECTION_LEVEL #define IPV6_PROTECTION_LEVEL 23 #endif #endif namespace { const int MAX_OUTBOUND_CONNECTIONS = 8; struct ListenSocket { SOCKET socket; bool whitelisted; ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {} }; } const static std::string NET_MESSAGE_COMMAND_OTHER = "*other*"; /** Services this node implementation cares about */ ServiceFlags nRelevantServices = NODE_NETWORK; class AggregationSession; // // Global state variables // bool fDiscover = true; bool fListen = true; ServiceFlags nLocalServices = NODE_NETWORK; bool fRelayTxes = true; CCriticalSection cs_mapLocalHost; CCriticalSection cs_mapDandelionEmbargo; std::map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = nullptr; uint64_t nLocalHostNonce = 0; static std::vector<ListenSocket> vhListenSocket; CAddrMan addrman; int nMaxConnections = DEFAULT_MAX_PEER_CONNECTIONS; bool fAddressesInitialized = false; std::string strSubVersion; std::vector<CNode*> vNodes; CCriticalSection cs_vNodes; limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ); static std::deque<std::string> vOneShots; CCriticalSection cs_vOneShots; std::vector<std::string> vAddedNodes; CCriticalSection cs_vAddedNodes; NodeId nLastNodeId = 0; CCriticalSection cs_nLastNodeId; static CSemaphore *semOutbound = nullptr; boost::condition_variable messageHandlerCondition; // Public Dandelion field std::map<uint256, int64_t> mDandelionEmbargo; std::map<uint256, std::pair<AggregationSession*, int64_t>> mDandelionAggregationSessionEmbargo; std::map<EncryptedCandidateTransaction, int64_t> mDandelionEncryptedCandidateEmbargo; // Dandelion fields std::vector<CNode*> vDandelionInbound; std::vector<CNode*> vDandelionOutbound; std::vector<CNode*> vDandelionDestination; CNode* localDandelionDestination = nullptr; std::map<CNode*, CNode*> mDandelionRoutes; // Signals for message handling static CNodeSignals g_signals; CNodeSignals& GetNodeSignals() { return g_signals; } void AddOneShot(const std::string& strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", Params().GetDefaultPort())); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr *paddrPeer) { if (!fListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (std::map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } //! Convert the pnSeeds6 array into usable address objects. static std::vector<CAddress> convertSeed6(const std::vector<SeedSpec6> &vSeedsIn) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; std::vector<CAddress> vSeedsOut; vSeedsOut.reserve(vSeedsIn.size()); for (std::vector<SeedSpec6>::const_iterator i(vSeedsIn.begin()); i != vSeedsIn.end(); ++i) { struct in6_addr ip; memcpy(&ip, i->addr, sizeof(ip)); CAddress addr(CService(ip, i->port), NODE_NETWORK); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } return vSeedsOut; } // get best local address for a particular peer as a CAddress // Otherwise, return the unroutable 0.0.0.0 but filled in with // the normal parameters, since the IP may be changed to a useful // one by discovery. CAddress GetLocalAddress(const CNetAddr *paddrPeer) { CAddress ret(CService("0.0.0.0",GetListenPort()), NODE_NONE); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr, nLocalServices); } ret.nTime = GetAdjustedTime(); return ret; } int GetnScore(const CService& addr) { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == LOCAL_NONE) return 0; return mapLocalHost[addr].nScore; } // Is our peer's addrLocal potentially useful as an external IP source? bool IsPeerAddrLocalGood(CNode *pnode) { return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() && !IsLimited(pnode->addrLocal.GetNetwork()); } // pushes our own address to a peer void AdvertiseLocal(CNode *pnode) { if (fListen && pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); // If discovery is enabled, sometimes give our peer the address it // tells us that it sees us as in case it has a better idea of our // address than we do. if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() || GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0)) { addrLocal.SetIP(pnode->addrLocal); } if (addrLocal.IsRoutable()) { LogPrintf("AdvertiseLocal: advertising address %s\n", addrLocal.ToString()); pnode->PushAddress(addrLocal); } } } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo &info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } } return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } bool RemoveLocal(const CService& addr) { LOCK(cs_mapLocalHost); LogPrintf("RemoveLocal(%s)\n", addr.ToString()); mapLocalHost.erase(addr); return true; } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr &addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given network is one we can probably connect to */ bool IsReachable(enum Network net) { LOCK(cs_mapLocalHost); return !vfLimited[net]; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { enum Network net = addr.GetNetwork(); return IsReachable(net); } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } uint64_t CNode::nTotalBytesRecv = 0; uint64_t CNode::nTotalBytesSent = 0; CCriticalSection CNode::cs_totalBytesRecv; CCriticalSection CNode::cs_totalBytesSent; uint64_t CNode::nMaxOutboundLimit = 0; uint64_t CNode::nMaxOutboundTotalBytesSentInCycle = 0; uint64_t CNode::nMaxOutboundTimeframe = 60*60*24; //1 day uint64_t CNode::nMaxOutboundCycleStartTime = 0; CNode* FindNode(const CNetAddr& ip) { LOCK(cs_vNodes); for(CNode* pnode: vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); return nullptr; } CNode* FindNode(const CSubNet& subNet) { LOCK(cs_vNodes); for(CNode* pnode: vNodes) if (subNet.Match((CNetAddr)pnode->addr)) return (pnode); return nullptr; } CNode* FindNode(const std::string& addrName) { LOCK(cs_vNodes); for(CNode* pnode: vNodes) if (pnode->addrName == addrName) return (pnode); return nullptr; } CNode* FindNode(const CService& addr) { LOCK(cs_vNodes); for(CNode* pnode: vNodes) if ((CService)pnode->addr == addr) return (pnode); return nullptr; } //TODO: This is used in only one place in main, and should be removed CNode* FindNode(const NodeId nodeid) { LOCK(cs_vNodes); for(CNode* pnode: vNodes) if (pnode->GetId() == nodeid) return (pnode); return nullptr; } CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure) { if (pszDest == nullptr) { if (IsLocal(addrConnect)) return nullptr; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->AddRef(); return pnode; } } /// debug print LogPrint("net", "trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString(), pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); // Connect SOCKET hSocket; bool proxyConnectionFailed = false; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) : ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) { if (!IsSelectableSocket(hSocket)) { LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n"); CloseSocket(hSocket); return nullptr; } if (pszDest && addrConnect.IsValid()) { // It is possible that we already have a connection to the IP/port pszDest resolved to. // In that case, drop the connection that was just created, and return the existing CNode instead. // Also store the name we used to connect in that CNode, so that future FindNode() calls to that // name catch this early. CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->AddRef(); { LOCK(cs_vNodes); if (pnode->addrName.empty()) { pnode->addrName = std::string(pszDest); } } CloseSocket(hSocket); return pnode; } } addrman.Attempt(addrConnect, fCountFailure); // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); // Dandelion: new outbound connection vDandelionOutbound.push_back(pnode); if (vDandelionDestination.size()<DANDELION_MAX_DESTINATIONS) { vDandelionDestination.push_back(pnode); } LogPrint("dandelion", "Added outbound Dandelion connection:\n%s", GetDandelionRoutingDataDebugString()); // Dandelion service discovery uint256 dummyHash; dummyHash.SetHex("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); CInv dummyInv(MSG_DANDELION_TX, dummyHash); pnode->PushInventory(dummyInv); } pnode->nServicesExpected = ServiceFlags(addrConnect.nServices & nRelevantServices); pnode->nTimeConnected = GetTime(); return pnode; } else if (!proxyConnectionFailed) { // If connecting to the node failed, and failure is not caused by a problem connecting to // the proxy, mark this as an attempt. addrman.Attempt(addrConnect, fCountFailure); } return nullptr; } static void DumpBanlist() { CNode::SweepBanned(); // clean unused entries (if bantime has expired) if (!CNode::BannedSetIsDirty()) return; int64_t nStart = GetTimeMillis(); CBanDB bandb; banmap_t banmap; CNode::SetBannedSetDirty(false); CNode::GetBanned(banmap); if (!bandb.Write(banmap)) CNode::SetBannedSetDirty(true); LogPrint("net", "Flushed %d banned node ips/subnets to banlist.dat %dms\n", banmap.size(), GetTimeMillis() - nStart); } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { LogPrint("net", "disconnecting peer=%d\n", id); CloseSocket(hSocket); } // in case this fails, we'll empty the recv buffer when the CNode is deleted TRY_LOCK(cs_vRecvMsg, lockRecv); if (lockRecv) vRecvMsg.clear(); } void CNode::PushVersion() { int nBestHeight = GetNodeSignals().GetHeight().get_value_or(0); int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0", 0), addr.nServices)); CAddress addrMe = GetLocalAddress(&addr); GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); if (fLogIPs) LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id); else LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id); PushMessage(NetMsgType::VERSION, PROTOCOL_VERSION, (uint64_t)nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, strSubVersion, nBestHeight, ::fRelayTxes); } banmap_t CNode::setBanned; CCriticalSection CNode::cs_setBanned; bool CNode::setBannedIsDirty; void CNode::ClearBanned() { { LOCK(cs_setBanned); setBanned.clear(); setBannedIsDirty = true; } DumpBanlist(); //store banlist to disk uiInterface.BannedListChanged(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); for (banmap_t::iterator it = setBanned.begin(); it != setBanned.end(); it++) { CSubNet subNet = (*it).first; CBanEntry banEntry = (*it).second; if(subNet.Match(ip) && GetTime() < banEntry.nBanUntil) fResult = true; } } return fResult; } bool CNode::IsBanned(CSubNet subnet) { bool fResult = false; { LOCK(cs_setBanned); banmap_t::iterator i = setBanned.find(subnet); if (i != setBanned.end()) { CBanEntry banEntry = (*i).second; if (GetTime() < banEntry.nBanUntil) fResult = true; } } return fResult; } void CNode::Ban(const CNetAddr& addr, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) { CSubNet subNet(addr); Ban(subNet, banReason, bantimeoffset, sinceUnixEpoch); } void CNode::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) { CBanEntry banEntry(GetTime()); banEntry.banReason = banReason; if (bantimeoffset <= 0) { bantimeoffset = GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME); sinceUnixEpoch = false; } banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset; { LOCK(cs_setBanned); if (setBanned[subNet].nBanUntil < banEntry.nBanUntil) { setBanned[subNet] = banEntry; setBannedIsDirty = true; } else return; } uiInterface.BannedListChanged(); { LOCK(cs_vNodes); for(CNode* pnode: vNodes) { if (subNet.Match((CNetAddr)pnode->addr)) pnode->fDisconnect = true; } } if(banReason == BanReasonManuallyAdded) DumpBanlist(); //store banlist to disk immediately if user requested ban } bool CNode::Unban(const CNetAddr &addr) { CSubNet subNet(addr); return Unban(subNet); } bool CNode::Unban(const CSubNet &subNet) { { LOCK(cs_setBanned); if (!setBanned.erase(subNet)) return false; setBannedIsDirty = true; } uiInterface.BannedListChanged(); DumpBanlist(); //store banlist to disk immediately return true; } void CNode::GetBanned(banmap_t &banMap) { LOCK(cs_setBanned); banMap = setBanned; //create a thread safe copy } void CNode::SetBanned(const banmap_t &banMap) { LOCK(cs_setBanned); setBanned = banMap; setBannedIsDirty = true; } void CNode::SweepBanned() { int64_t now = GetTime(); LOCK(cs_setBanned); banmap_t::iterator it = setBanned.begin(); while(it != setBanned.end()) { CSubNet subNet = (*it).first; CBanEntry banEntry = (*it).second; if(now > banEntry.nBanUntil) { setBanned.erase(it++); setBannedIsDirty = true; LogPrint("net", "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__, subNet.ToString()); } else ++it; } } bool CNode::BannedSetIsDirty() { LOCK(cs_setBanned); return setBannedIsDirty; } void CNode::SetBannedSetDirty(bool dirty) { LOCK(cs_setBanned); //reuse setBanned lock for the isDirty flag setBannedIsDirty = dirty; } std::vector<CSubNet> CNode::vWhitelistedRange; CCriticalSection CNode::cs_vWhitelistedRange; bool CNode::IsWhitelistedRange(const CNetAddr &addr) { LOCK(cs_vWhitelistedRange); for(const CSubNet& subnet: vWhitelistedRange) { if (subnet.Match(addr)) return true; } return false; } void CNode::AddWhitelistedRange(const CSubNet &subnet) { LOCK(cs_vWhitelistedRange); vWhitelistedRange.push_back(subnet); } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { stats.nodeid = this->GetId(); X(nServices); X(fRelayTxes); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(nTimeOffset); X(addrName); X(nVersion); X(cleanSubVer); X(fInbound); X(nStartingHeight); X(nSendBytes); X(mapSendBytesPerMsgCmd); X(nRecvBytes); X(mapRecvBytesPerMsgCmd); X(fWhitelisted); // It is common for nodes with good ping times to suddenly become lagged, // due to a new block arriving or other large transfer. // Merely reporting pingtime might fool the caller into thinking the node was still responsive, // since pingtime does not update until the ping is complete, which might take a while. // So, if a ping is taking an unusually long time in flight, // the caller can immediately detect that this is happening. int64_t nPingUsecWait = 0; if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) { nPingUsecWait = GetTimeMicros() - nPingUsecStart; } // Raw ping time is in microseconds, but show it to user as whole seconds (Navcoin users should be well used to small numbers with many decimal places by now :) stats.dPingTime = (((double)nPingUsecTime) / 1e6); stats.dPingMin = (((double)nMinPingUsecTime) / 1e6); stats.dPingWait = (((double)nPingUsecWait) / 1e6); // Leave string empty if addrLocal invalid (not filled in yet) stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : ""; } #undef X // requires LOCK(cs_vRecvMsg) bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes) { while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK, nRecvVersion)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) { LogPrint("net", "Oversized message from peer=%i, disconnecting\n", GetId()); return false; } pch += handled; nBytes -= handled; if (msg.complete()) { //store received bytes per message command //to prevent a memory DOS, only allow valid commands mapMsgCmdSize::iterator i = mapRecvBytesPerMsgCmd.find(msg.hdr.pchCommand); if (i == mapRecvBytesPerMsgCmd.end()) i = mapRecvBytesPerMsgCmd.find(NET_MESSAGE_COMMAND_OTHER); assert(i != mapRecvBytesPerMsgCmd.end()); i->second += msg.hdr.nMessageSize + CMessageHeader::HEADER_SIZE; msg.nTime = GetTimeMicros(); messageHandlerCondition.notify_one(); } } return true; } int CNetMessage::readHeader(const char *pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (const std::exception&) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; return nCopy; } int CNetMessage::readData(const char *pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); if (vRecv.size() < nDataPos + nCopy) { // Allocate up to 256 KiB ahead, but never more than the total message size. vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024)); } memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } // requires LOCK(cs_vSend) void SocketSendData(CNode *pnode) { std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin(); while (it != pnode->vSendMsg.end()) { const CSerializeData &data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { pnode->nLastSend = GetTime(); pnode->nSendBytes += nBytes; pnode->nSendOffset += nBytes; pnode->RecordBytesSent(nBytes); if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { LogPrintf("socket send error %s\n", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } static std::list<CNode*> vNodesDisconnected; struct NodeEvictionCandidate { NodeId id; int64_t nTimeConnected; int64_t nMinPingUsecTime; int64_t nLastBlockTime; int64_t nLastTXTime; bool fNetworkNode; bool fRelayTxes; bool fBloomFilter; CAddress addr; uint64_t nKeyedNetGroup; }; static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) { return a.nMinPingUsecTime > b.nMinPingUsecTime; } static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) { return a.nTimeConnected > b.nTimeConnected; } static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) { return a.nKeyedNetGroup < b.nKeyedNetGroup; } static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) { // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block. if (a.nLastBlockTime != b.nLastBlockTime) return a.nLastBlockTime < b.nLastBlockTime; if (a.fNetworkNode != b.fNetworkNode) return b.fNetworkNode; return a.nTimeConnected > b.nTimeConnected; } static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) { // There is a fall-through here because it is common for a node to have more than a few peers that have not yet relayed txn. if (a.nLastTXTime != b.nLastTXTime) return a.nLastTXTime < b.nLastTXTime; if (a.fRelayTxes != b.fRelayTxes) return b.fRelayTxes; if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter; return a.nTimeConnected > b.nTimeConnected; } /** Try to find a connection to evict when the node is full. * Extreme care must be taken to avoid opening the node to attacker * triggered network partitioning. * The strategy used here is to protect a small number of peers * for each of several distinct characteristics which are difficult * to forge. In order to partition a node the attacker must be * simultaneously better at all of them than honest peers. */ static bool AttemptToEvictConnection() { std::vector<NodeEvictionCandidate> vEvictionCandidates; { LOCK(cs_vNodes); for(CNode *node: vNodes) { if (node->fWhitelisted) continue; if (!node->fInbound) continue; if (node->fDisconnect) continue; NodeEvictionCandidate candidate = {node->id, node->nTimeConnected, node->nMinPingUsecTime, node->nLastBlockTime, node->nLastTXTime, node->fNetworkNode, node->fRelayTxes, node->pfilter != nullptr, node->addr, node->nKeyedNetGroup}; vEvictionCandidates.push_back(candidate); } } if (vEvictionCandidates.empty()) return false; // Protect connections with certain characteristics // Deterministically select 4 peers to protect by netgroup. // An attacker cannot predict which netgroups will be protected std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNetGroupKeyed); vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end()); if (vEvictionCandidates.empty()) return false; // Protect the 8 nodes with the lowest minimum ping time. // An attacker cannot manipulate this metric without physically moving nodes closer to the target. std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeMinPingTime); vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(8, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end()); if (vEvictionCandidates.empty()) return false; // Protect 4 nodes that most recently sent us transactions. // An attacker cannot manipulate this metric without performing useful work. std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNodeTXTime); vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end()); if (vEvictionCandidates.empty()) return false; // Protect 4 nodes that most recently sent us blocks. // An attacker cannot manipulate this metric without performing useful work. std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNodeBlockTime); vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end()); if (vEvictionCandidates.empty()) return false; // Protect the half of the remaining nodes which have been connected the longest. // This replicates the non-eviction implicit behavior, and precludes attacks that start later. std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeTimeConnected); vEvictionCandidates.erase(vEvictionCandidates.end() - static_cast<int>(vEvictionCandidates.size() / 2), vEvictionCandidates.end()); if (vEvictionCandidates.empty()) return false; // Identify the network group with the most connections and youngest member. // (vEvictionCandidates is already sorted by reverse connect time) uint64_t naMostConnections; unsigned int nMostConnections = 0; int64_t nMostConnectionsTime = 0; std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapAddrCounts; for(const NodeEvictionCandidate &node: vEvictionCandidates) { mapAddrCounts[node.nKeyedNetGroup].push_back(node); int64_t grouptime = mapAddrCounts[node.nKeyedNetGroup][0].nTimeConnected; size_t groupsize = mapAddrCounts[node.nKeyedNetGroup].size(); if (groupsize > nMostConnections || (groupsize == nMostConnections && grouptime > nMostConnectionsTime)) { nMostConnections = groupsize; nMostConnectionsTime = grouptime; naMostConnections = node.nKeyedNetGroup; } } // Reduce to the network group with the most connections vEvictionCandidates = std::move(mapAddrCounts[naMostConnections]); // Disconnect from the network group with the most connections NodeId evicted = vEvictionCandidates.front().id; LOCK(cs_vNodes); for(std::vector<CNode*>::const_iterator it(vNodes.begin()); it != vNodes.end(); ++it) { if ((*it)->GetId() == evicted) { (*it)->fDisconnect = true; return true; } } return false; } static void AcceptConnection(const ListenSocket& hListenSocket) { struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; int nMaxInbound = nMaxConnections - MAX_OUTBOUND_CONNECTIONS; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) LogPrintf("Warning: Unknown socket family\n"); bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr); { LOCK(cs_vNodes); for(CNode* pnode: vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr)); return; } if (!IsSelectableSocket(hSocket)) { LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString()); CloseSocket(hSocket); return; } // According to the internet TCP_NODELAY is not carried into accepted sockets // on all platforms. Set it again here just to be sure. int set = 1; #ifdef WIN32 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int)); #else setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int)); #endif if (CNode::IsBanned(addr) && !whitelisted) { LogPrintf("connection from %s dropped (banned)\n", addr.ToString()); CloseSocket(hSocket); return; } if (nInbound >= nMaxInbound) { if (!AttemptToEvictConnection()) { // No connection to evict, disconnect the new connection LogPrint("net", "failed to find an eviction candidate - connection dropped (full)\n"); CloseSocket(hSocket); return; } } CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); pnode->fWhitelisted = whitelisted; LogPrint("net", "connection from %s accepted\n", addr.ToString()); { LOCK(cs_vNodes); vNodes.push_back(pnode); // Dandelion: new inbound connection vDandelionInbound.push_back(pnode); CNode* pto = SelectFromDandelionDestinations(); if (pto!=nullptr) { mDandelionRoutes.insert(std::make_pair(pnode, pto)); } LogPrint("dandelion", "Added inbound Dandelion connection:\n%s", GetDandelionRoutingDataDebugString()); } } void ThreadSocketHandler() { unsigned int nPrevNodeCount = 0; while (true) { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes std::vector<CNode*> vNodesCopy = vNodes; for(CNode* pnode: vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } } { // Delete disconnected nodes std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; for(CNode* pnode: vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } if (fDelete) { // Dandelion: close connection CloseDandelionConnections(pnode); LogPrint("dandelion", "Removed Dandelion connection:\n%s", GetDandelionRoutingDataDebugString()); vNodesDisconnected.remove(pnode); delete pnode; } } } } if(vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; for(const ListenSocket& hListenSocket: vhListenSocket) { FD_SET(hListenSocket.socket, &fdsetRecv); hSocketMax = std::max(hSocketMax, hListenSocket.socket); have_fds = true; } { LOCK(cs_vNodes); for(CNode* pnode: vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetError); hSocketMax = std::max(hSocketMax, pnode->hSocket); have_fds = true; // Implement the following logic: // * If there is data to send, select() for sending data. As this only // happens when optimistic write failed, we choose to first drain the // write buffer in this case before receiving more. This avoids // needlessly queueing received data, if the remote peer is not themselves // receiving data. This means properly utilizing TCP flow control signalling. // * Otherwise, if there is no (complete) message in the receive buffer, // or there is space left in the buffer, select() for receiving data. // * (if neither of the above applies, there is certainly one message // in the receiver buffer ready to be processed). // Together, that means that at least one of the following is always possible, // so we don't deadlock: // * We send some data. // * We wait for data to be received (and disconnect after timeout). // * We process a message in the buffer (message handler thread). { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend &&!pnode->vSendMsg.empty()) { FD_SET(pnode->hSocket, &fdsetSend); continue; } } { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv && ( pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() || pnode->GetTotalRecvSize() <= ReceiveFloodSize())) FD_SET(pnode->hSocket, &fdsetRecv); } } } int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); boost::this_thread::interruption_point(); if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); LogPrintf("socket select error %s\n", NetworkErrorString(nErr)); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec/1000); } // // Accept new connections // for(const ListenSocket& hListenSocket: vhListenSocket) { if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) { AcceptConnection(hListenSocket); } } // // Service each socket // std::vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; for(CNode* pnode: vNodesCopy) pnode->AddRef(); } for(CNode* pnode: vNodesCopy) { boost::this_thread::interruption_point(); // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) pnode->CloseSocketDisconnect(); pnode->nLastRecv = GetTime(); pnode->nRecvBytes += nBytes; pnode->RecordBytesRecv(nBytes); } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) LogPrint("net", "socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) LogPrintf("socket recv error %s\n", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SocketSendData(pnode); } // // Inactivity checking // int64_t nTime = GetTime(); if (nTime - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id); pnode->fDisconnect = true; } else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) { LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend); pnode->fDisconnect = true; } else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60)) { LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv); pnode->fDisconnect = true; } else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) { LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart)); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); for(CNode* pnode: vNodesCopy) pnode->Release(); } } } #ifdef USE_UPNP void ThreadMapPort() { std::string port = strprintf("%u", GetListenPort()); const char * multicastif = 0; const char * minissdpdpath = 0; struct UPNPDev * devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #elif MINIUPNPC_API_VERSION < 14 /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #else /* miniupnpc 1.9.20150730 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if(externalIPAddress[0]) { LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else LogPrintf("UPnP: GetExternalIPAddress failed.\n"); } } std::string strDesc = "Navcoin " + FormatFullVersion(); try { while (true) { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if(r!=UPNPCOMMAND_SUCCESS) LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port, port, lanaddr, r, strupnperror(r)); else LogPrintf("UPnP Port Mapping successful.\n"); MilliSleep(20*60*1000); // Refresh every 20 minutes } } catch (const boost::thread_interrupted&) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); throw; } } else { LogPrintf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); } } void MapPort(bool fUseUPnP) { static boost::thread* upnp_thread = nullptr; if (fUseUPnP) { if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; } upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort)); } else if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; upnp_thread = nullptr; } } #else void MapPort(bool) { // Intentionally left blank. } #endif bool IsDandelionInbound(const CNode* const pnode) { return (std::find(vDandelionInbound.begin(), vDandelionInbound.end(), pnode) != vDandelionInbound.end()); } bool IsDandelionOutbound(const CNode* const pnode) { return (std::find(vDandelionOutbound.begin(), vDandelionOutbound.end(), pnode) != vDandelionOutbound.end()); } bool IsLocalDandelionDestinationSet() { return (localDandelionDestination != nullptr); } bool SetLocalDandelionDestination() { if (!IsLocalDandelionDestinationSet()) { localDandelionDestination = SelectFromDandelionDestinations(); LogPrint("dandelion", "Set local Dandelion destination:\n%s", GetDandelionRoutingDataDebugString()); } return IsLocalDandelionDestinationSet(); } CNode* GetDandelionDestination(CNode* pfrom) { for (auto const& e : mDandelionRoutes) { if (pfrom==e.first) { return e.second; } } CNode* newPto = SelectFromDandelionDestinations(); if (newPto!=nullptr) { mDandelionRoutes.insert(std::make_pair(pfrom, newPto)); LogPrint("dandelion", "Added Dandelion route:\n%s", GetDandelionRoutingDataDebugString()); } return newPto; } bool LocalDandelionDestinationPushInventory(const CInv& inv) { if(IsLocalDandelionDestinationSet()) { localDandelionDestination->PushInventory(inv); return true; } else if (SetLocalDandelionDestination()) { localDandelionDestination->PushInventory(inv); return true; } else { return false; } } bool LocalDandelionDestinationPushEncryptedCandidate(const EncryptedCandidateTransaction& ec) { if(IsLocalDandelionDestinationSet()) { localDandelionDestination->PushMessage(NetMsgType::ENCRYPTEDCANDIDATE, ec); return true; } else if (SetLocalDandelionDestination()) { localDandelionDestination->PushMessage(NetMsgType::ENCRYPTEDCANDIDATE, ec); return true; } else { return false; } } bool LocalDandelionDestinationPushAggregationSession(const AggregationSession& ms) { if(IsLocalDandelionDestinationSet()) { localDandelionDestination->PushMessage(NetMsgType::AGGREGATIONSESSION, ms); return true; } else if (SetLocalDandelionDestination()) { localDandelionDestination->PushMessage(NetMsgType::AGGREGATIONSESSION, ms); return true; } else { return false; } } bool InsertDandelionEmbargo(const uint256& hash, const int64_t& embargo) { auto pair = mDandelionEmbargo.insert(std::make_pair(hash, embargo)); return pair.second; } bool IsTxDandelionEmbargoed(const uint256& hash) { auto pair = mDandelionEmbargo.find(hash); if (pair != mDandelionEmbargo.end()) { return true; } else { return false; } } bool RemoveDandelionEmbargo(const uint256& hash) { bool removed = false; for (auto iter=mDandelionEmbargo.begin(); iter!=mDandelionEmbargo.end();) { if (iter->first==hash) { iter = mDandelionEmbargo.erase(iter); removed = true; } else { iter++; } } return removed; } bool InsertDandelionAggregationSessionEmbargo(AggregationSession* ms, const int64_t& embargo) { LOCK(cs_mapDandelionEmbargo); auto pair = mDandelionAggregationSessionEmbargo.insert(std::make_pair(ms->GetHash(), std::make_pair(ms, embargo))); return pair.second; } bool IsDandelionAggregationSessionEmbargoed(const uint256& hash) { LOCK(cs_mapDandelionEmbargo); auto pair = mDandelionAggregationSessionEmbargo.find(hash); if (pair != mDandelionAggregationSessionEmbargo.end()) { return true; } else { return false; } } bool RemoveDandelionAggregationSessionEmbargo(const uint256& hash) { LOCK(cs_mapDandelionEmbargo); bool removed = false; for (auto iter=mDandelionAggregationSessionEmbargo.begin(); iter!=mDandelionAggregationSessionEmbargo.end();) { if (iter->first==hash) { iter = mDandelionAggregationSessionEmbargo.erase(iter); removed = true; } else { iter++; } } return removed; } bool InsertDandelionEncryptedCandidateEmbargo(const EncryptedCandidateTransaction &ec, const int64_t& embargo) { LOCK(cs_mapDandelionEmbargo); auto pair = mDandelionEncryptedCandidateEmbargo.insert(std::make_pair(ec, embargo)); return pair.second; } bool IsDandelionEncryptedCandidateEmbargoed(const EncryptedCandidateTransaction &ec) { LOCK(cs_mapDandelionEmbargo); auto pair = mDandelionEncryptedCandidateEmbargo.find(ec); if (pair != mDandelionEncryptedCandidateEmbargo.end()) { return true; } else { return false; } } bool RemoveDandelionEncryptedCandidateEmbargo(const EncryptedCandidateTransaction &ec) { LOCK(cs_mapDandelionEmbargo); bool removed = false; for (auto iter=mDandelionEncryptedCandidateEmbargo.begin(); iter!=mDandelionEncryptedCandidateEmbargo.end();) { if (iter->first==ec) { iter = mDandelionEncryptedCandidateEmbargo.erase(iter); removed = true; } else { iter++; } } return removed; } CNode* SelectFromDandelionDestinations() { std::map<CNode*,uint64_t> mDandelionDestinationCounts; for (size_t i=0; i<vDandelionDestination.size(); i++) { mDandelionDestinationCounts.insert(std::make_pair(vDandelionDestination.at(i),0)); } for (auto& e : mDandelionDestinationCounts) { for (auto const& f : mDandelionRoutes) { if (e.first == f.second) { e.second+=1; } } } unsigned int minNumConnections = vDandelionInbound.size(); for (auto const& e : mDandelionDestinationCounts) { if (e.second < minNumConnections) { minNumConnections = e.second; } } std::vector<CNode*> candidateDestinations; for (auto const& e : mDandelionDestinationCounts) { if (e.second == minNumConnections) { candidateDestinations.push_back(e.first); } } FastRandomContext rng; CNode* dandelionDestination = nullptr; if (candidateDestinations.size()>0) { dandelionDestination = candidateDestinations.at(rng.randrange(candidateDestinations.size())); } return dandelionDestination; } void CloseDandelionConnections(const CNode* const pnode) { // Remove pnode from vDandelionInbound, if present for (auto iter=vDandelionInbound.begin(); iter!=vDandelionInbound.end();) { if (*iter==pnode) { iter=vDandelionInbound.erase(iter); } else { iter++; } } // Remove pnode from vDandelionOutbound, if present for (auto iter=vDandelionOutbound.begin(); iter!=vDandelionOutbound.end();) { if (*iter==pnode) { iter=vDandelionOutbound.erase(iter); } else { iter++; } } // Remove pnode from vDandelionDestination, if present bool isDandelionDestination = false; for (auto iter=vDandelionDestination.begin(); iter!=vDandelionDestination.end();) { if (*iter==pnode) { isDandelionDestination = true; iter=vDandelionDestination.erase(iter); } else { iter++; } } // Generate a replacement Dandelion destination, if necessary if (isDandelionDestination) { // Gather a vector of candidate replacements (outbound peers that are not already destinations) std::vector<CNode*> candidateReplacements; for (auto iteri=vDandelionOutbound.begin(); iteri!=vDandelionOutbound.end();) { bool eligibleCandidate = true; for (auto iterj=vDandelionDestination.begin(); iterj!=vDandelionDestination.end();) { if (*iteri==*iterj) { eligibleCandidate = false; iterj = vDandelionDestination.end(); } else { iterj++; } } if (eligibleCandidate) { candidateReplacements.push_back(*iteri); } iteri++; } // Select a candidate to be the replacement destination FastRandomContext rng; CNode* replacementDestination = nullptr; if (candidateReplacements.size()>0) { replacementDestination = candidateReplacements.at(rng.randrange(candidateReplacements.size())); } if (replacementDestination!=nullptr) { vDandelionDestination.push_back(replacementDestination); } } // Generate a replacement pnode, to be used if necessary CNode* newPto = SelectFromDandelionDestinations(); // Remove from mDandelionRoutes, if present; if destination, try to replace for(auto iter=mDandelionRoutes.begin(); iter!=mDandelionRoutes.end();) { if (iter->first==pnode) { iter = mDandelionRoutes.erase(iter); } else if (iter->second==pnode) { if (newPto==nullptr) { iter = mDandelionRoutes.erase(iter); } else { iter->second = newPto; iter++; } } else { iter++; } } // Replace localDandelionDestination if equal to pnode if (localDandelionDestination==pnode) { localDandelionDestination = newPto; } } std::string GetDandelionRoutingDataDebugString() { std::string dandelionRoutingDataDebugString = ""; dandelionRoutingDataDebugString.append(" vDandelionInbound: "); for(auto const& e : vDandelionInbound) { dandelionRoutingDataDebugString.append(std::to_string(e->GetId())+" "); } dandelionRoutingDataDebugString.append("\n"); dandelionRoutingDataDebugString.append(" vDandelionOutbound: "); for(auto const& e : vDandelionOutbound) { dandelionRoutingDataDebugString.append(std::to_string(e->GetId())+" "); } dandelionRoutingDataDebugString.append("\n"); dandelionRoutingDataDebugString.append(" vDandelionDestination: "); for(auto const& e : vDandelionDestination) { dandelionRoutingDataDebugString.append(std::to_string(e->GetId())+" "); } dandelionRoutingDataDebugString.append("\n"); dandelionRoutingDataDebugString.append(" mDandelionRoutes: "); for(auto const& e : mDandelionRoutes) { dandelionRoutingDataDebugString.append("("+std::to_string(e.first->GetId())+","+std::to_string(e.second->GetId())+") "); } dandelionRoutingDataDebugString.append("\n"); dandelionRoutingDataDebugString.append(" localDandelionDestination: "); if(localDandelionDestination==nullptr) { dandelionRoutingDataDebugString.append("nullptr"); } else { dandelionRoutingDataDebugString.append(std::to_string(localDandelionDestination->GetId())); } dandelionRoutingDataDebugString.append("\n"); return dandelionRoutingDataDebugString; } void DandelionShuffle() { // Dandelion debug message LogPrint("dandelion", "Before Dandelion shuffle:\n%s", GetDandelionRoutingDataDebugString()); { // Lock node pointers LOCK(cs_vNodes); auto prevDestination = localDandelionDestination; // Iterate through mDandelionRoutes to facilitate bookkeeping for (auto iter=mDandelionRoutes.begin(); iter!=mDandelionRoutes.end();) { iter = mDandelionRoutes.erase(iter); } // Set localDandelionDestination to nulltpr and perform bookkeeping if (localDandelionDestination!=nullptr) { localDandelionDestination = nullptr; } // Clear vDandelionDestination // (bookkeeping already done while iterating through mDandelionRoutes) vDandelionDestination.clear(); // Repopulate vDandelionDestination while (vDandelionDestination.size()<DANDELION_MAX_DESTINATIONS && vDandelionDestination.size()<vDandelionOutbound.size()) { std::vector<CNode*> candidateDestinations; for (auto iteri=vDandelionOutbound.begin(); iteri!=vDandelionOutbound.end();) { bool eligibleCandidate = true; for (auto iterj=vDandelionDestination.begin(); iterj!=vDandelionDestination.end();) { if (*iteri==*iterj) { eligibleCandidate = false; iterj = vDandelionDestination.end(); } else { iterj++; } } if (eligibleCandidate) { candidateDestinations.push_back(*iteri); } iteri++; } FastRandomContext rng; if (candidateDestinations.size()>0) { vDandelionDestination.push_back(candidateDestinations.at(rng.randrange(candidateDestinations.size()))); } else { break; } } // Generate new routes for (auto pnode : vDandelionInbound) { CNode* pto = SelectFromDandelionDestinations(); if (pto != nullptr) { mDandelionRoutes.insert(std::make_pair(pnode, pto)); } } localDandelionDestination = SelectFromDandelionDestinations(); } // Dandelion debug message LogPrint("dandelion", "After Dandelion shuffle:\n%s", GetDandelionRoutingDataDebugString()); } void ThreadDandelionShuffle() { int64_t nCurrTime = GetTimeMicros(); int64_t nNextDandelionShuffle = PoissonNextSend(nCurrTime, DANDELION_SHUFFLE_INTERVAL); while (true) { nCurrTime = GetTimeMicros(); if (nCurrTime > nNextDandelionShuffle) { DandelionShuffle(); nNextDandelionShuffle = PoissonNextSend(nCurrTime, DANDELION_SHUFFLE_INTERVAL); // Sleep until the next shuffle time MilliSleep((nNextDandelionShuffle-nCurrTime)/1000); } boost::this_thread::interruption_point(); } } static std::string GetDNSHost(const CDNSSeedData& data, ServiceFlags* requiredServiceBits) { //use default host for non-filter-capable seeds or if we use the default service bits (NODE_NETWORK) if (!data.supportsServiceBitsFiltering || *requiredServiceBits == NODE_NETWORK) { *requiredServiceBits = NODE_NETWORK; return data.host; } return strprintf("x%x.%s", *requiredServiceBits, data.host); } void ThreadDNSAddressSeed() { // goal: only query DNS seeds if address need is acute if ((addrman.size() > 0) && (!GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED))) { MilliSleep(11 * 1000); LOCK(cs_vNodes); if (vNodes.size() >= 2) { LogPrintf("P2P peers available. Skipped DNS seeding.\n"); return; } } const std::vector<CDNSSeedData> &vSeeds = Params().DNSSeeds(); int found = 0; LogPrintf("Loading addresses from DNS seeds (could take a while)\n"); for(const CDNSSeedData &seed: vSeeds) { if (HaveNameProxy()) { AddOneShot(seed.host); } else { std::vector<CNetAddr> vIPs; std::vector<CAddress> vAdd; ServiceFlags requiredServiceBits = nRelevantServices; if (LookupHost(GetDNSHost(seed, &requiredServiceBits).c_str(), vIPs, 0, true)) { for(const CNetAddr& ip: vIPs) { int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } // TODO: The seed name resolve may fail, yielding an IP of [::], which results in // addrman assigning the same source to results from different seeds. // This should switch to a hard-coded stable dummy IP for each seed name, so that the // resolve is not required at all. if (!vIPs.empty()) { CService seedSource; Lookup(seed.name.c_str(), seedSource, 0, true); addrman.Add(vAdd, seedSource); } } } LogPrintf("%d addresses found from DNS seeds\n", found); } void DumpAddresses() { int64_t nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); LogPrint("net", "Flushed %d addresses to peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); } void DumpData() { DumpAddresses(); DumpBanlist(); } void static ProcessOneShot() { std::string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, false, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void ThreadOpenConnections() { // Connect to specific addresses if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64_t nLoop = 0;; nLoop++) { ProcessOneShot(); for(const std::string& strAddr: mapMultiArgs["-connect"]) { CAddress addr(CService(), NODE_NONE); OpenNetworkConnection(addr, false, nullptr, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { MilliSleep(500); } } MilliSleep(500); } } // Initiate network connections int64_t nStart = GetTime(); while (true) { ProcessOneShot(); MilliSleep(500); CSemaphoreGrant grant(*semOutbound); boost::this_thread::interruption_point(); // Add seed nodes if DNS seeds are all down (an infrastructure attack?). if (addrman.size() == 0 && (GetTime() - nStart > 60)) { static bool done = false; if (!done) { LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n"); addrman.Add(convertSeed6(Params().FixedSeeds()), CNetAddr("127.0.0.1")); done = true; } } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; std::set<std::vector<unsigned char> > setConnected; { LOCK(cs_vNodes); for(CNode* pnode: vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64_t nANow = GetAdjustedTime(); int nTries = 0; while (true) { CAddrInfo addr = addrman.Select(); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only connect to full nodes if ((addr.nServices & REQUIRED_SERVICES) != REQUIRED_SERVICES) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // only consider nodes missing relevant services after 40 failed attemps if ((addr.nServices & nRelevantServices) != nRelevantServices && nTries < 40) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant); } } std::vector<AddedNodeInfo> GetAddedNodeInfo() { std::vector<AddedNodeInfo> ret; std::list<std::string> lAddresses(0); { LOCK(cs_vAddedNodes); ret.reserve(vAddedNodes.size()); for(const std::string& strAddNode: vAddedNodes) lAddresses.push_back(strAddNode); } // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService std::map<CService, bool> mapConnected; std::map<std::string, std::pair<bool, CService>> mapConnectedByName; { LOCK(cs_vNodes); for (const CNode* pnode : vNodes) { if (pnode->addr.IsValid()) { mapConnected[pnode->addr] = pnode->fInbound; } if (!pnode->addrName.empty()) { mapConnectedByName[pnode->addrName] = std::make_pair(pnode->fInbound, static_cast<const CService&>(pnode->addr)); } } } for(const std::string& strAddNode: lAddresses) { CService service(strAddNode, Params().GetDefaultPort()); if (service.IsValid()) { // strAddNode is an IP:port auto it = mapConnected.find(service); if (it != mapConnected.end()) { ret.push_back(AddedNodeInfo{strAddNode, service, true, it->second}); } else { ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false}); } } else { // strAddNode is a name auto it = mapConnectedByName.find(strAddNode); if (it != mapConnectedByName.end()) { ret.push_back(AddedNodeInfo{strAddNode, it->second.second, true, it->second.first}); } else { ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false}); } } } return ret; } void ThreadOpenAddedConnections() { { LOCK(cs_vAddedNodes); vAddedNodes = mapMultiArgs["-addnode"]; } for (unsigned int i = 0; true; i++) { std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo(); for (const AddedNodeInfo& info : vInfo) { if (!info.fConnected) { CSemaphoreGrant grant(*semOutbound); // If strAddedNode is an IP/port, decode it immediately, so // OpenNetworkConnection can detect existing connections to that IP/port. CService service(info.strAddedNode, Params().GetDefaultPort()); OpenNetworkConnection(CAddress(service, NODE_NONE), false, &grant, info.strAddedNode.c_str(), false); MilliSleep(500); } } MilliSleep(120000); // Retry every 2 minutes } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot) { // // Initiate outbound network connection // boost::this_thread::interruption_point(); if (!pszDest) { if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort())) return false; } else if (FindNode(std::string(pszDest))) return false; CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure); boost::this_thread::interruption_point(); if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } void ThreadMessageHandler() { boost::mutex condition_mutex; boost::unique_lock<boost::mutex> lock(condition_mutex); while (true) { std::vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; for(CNode* pnode: vNodesCopy) { pnode->AddRef(); } } bool fSleep = true; for(CNode* pnode: vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { if (!GetNodeSignals().ProcessMessages(pnode)) pnode->CloseSocketDisconnect(); if (pnode->nSendSize < SendBufferSize()) { if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) { fSleep = false; } } } } boost::this_thread::interruption_point(); // Send messages { TRY_LOCK(pnode->cs_sendProcessing, lockSend); if (lockSend) GetNodeSignals().SendMessages(pnode); } boost::this_thread::interruption_point(); } { LOCK(cs_vNodes); for(CNode* pnode: vNodesCopy) pnode->Release(); } if (fSleep) messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100)); } } bool BindListenPort(const CService &addrBind, std::string& strError, bool fWhitelisted) { strError = ""; int nOne = 1; // Create socket for listening for incoming connections struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString()); LogPrintf("%s\n", strError); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); return false; } if (!IsSelectableSocket(hListenSocket)) { strError = "Error: Couldn't create a listenable socket for incoming connections"; LogPrintf("%s\n", strError); return false; } #ifndef WIN32 #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); // Disable Nagle's algorithm setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&nOne, sizeof(int)); setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&nOne, sizeof(int)); #endif // Set to non-blocking, incoming connections will also inherit this if (!SetSocketNonBlocking(hListenSocket, true)) { strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); return false; } // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED; setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int)); #endif } if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToString(), _(PACKAGE_NAME)); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr)); LogPrintf("%s\n", strError); CloseSocket(hListenSocket); return false; } LogPrintf("Bound to %s\n", addrBind.ToString()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); CloseSocket(hListenSocket); return false; } vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted)); if (addrBind.IsRoutable() && fDiscover && !fWhitelisted) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover(boost::thread_group& threadGroup) { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[256] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { std::vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr, 0, true)) { for(const CNetAddr &addr: vaddr) { if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString()); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next) { if (ifa->ifa_addr == nullptr) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString()); } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString()); } } freeifaddrs(myaddrs); } #endif } void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler) { uiInterface.InitMessage(_("Loading addresses...")); // Load addresses from peers.dat int64_t nStart = GetTimeMillis(); { CAddrDB adb; if (adb.Read(addrman)) LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); else { addrman.Clear(); // Addrman can be in an inconsistent state after failure, reset it LogPrintf("Invalid or missing peers.dat; recreating\n"); DumpAddresses(); } } uiInterface.InitMessage(_("Loading banlist...")); // Load addresses from banlist.dat nStart = GetTimeMillis(); CBanDB bandb; banmap_t banmap; if (bandb.Read(banmap)) { CNode::SetBanned(banmap); // thread save setter CNode::SetBannedSetDirty(false); // no need to write down, just read data CNode::SweepBanned(); // sweep out unused entries LogPrint("net", "Loaded %d banned node ips/subnets from banlist.dat %dms\n", banmap.size(), GetTimeMillis() - nStart); } else { LogPrintf("Invalid or missing banlist.dat; recreating\n"); CNode::SetBannedSetDirty(true); // force write DumpBanlist(); } fAddressesInitialized = true; if (semOutbound == nullptr) { // initialize semaphore int nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == nullptr) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(threadGroup); // // Start threads // if (!GetBoolArg("-dnsseed", true)) LogPrintf("DNS seeding disabled\n"); else threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed)); // Map ports with UPnP MapPort(GetBoolArg("-upnp", DEFAULT_UPNP)); // Send and receive from sockets, accept connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler)); // Initiate outbound connections from -addnode threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections)); // Initiate outbound connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections)); // Process messages threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler)); // Dandelion shuffle threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dandelion", &ThreadDandelionShuffle)); // Dump network addresses scheduler.scheduleEvery(&DumpData, DUMP_ADDRESSES_INTERVAL); } bool StopNode() { LogPrintf("StopNode()\n"); MapPort(false); if (semOutbound) for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); if (fAddressesInitialized) { DumpData(); fAddressesInitialized = false; } return true; } class CNetCleanup { public: CNetCleanup() {} ~CNetCleanup() { // Close sockets for(CNode* pnode: vNodes) if (pnode->hSocket != INVALID_SOCKET) CloseSocket(pnode->hSocket); for(ListenSocket& hListenSocket: vhListenSocket) if (hListenSocket.socket != INVALID_SOCKET) if (!CloseSocket(hListenSocket.socket)) LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError())); // clean up some globals (to help leak detection) for(CNode *pnode: vNodes) delete pnode; for(CNode *pnode: vNodesDisconnected) delete pnode; vNodes.clear(); vNodesDisconnected.clear(); vhListenSocket.clear(); delete semOutbound; semOutbound = nullptr; delete pnodeLocalHost; pnodeLocalHost = nullptr; #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void CExplicitNetCleanup::callCleanup() { // Explicit call to destructor of CNetCleanup because it's not implicitly called // when the wallet is restarted from within the wallet itself. CNetCleanup* tmp = new CNetCleanup(); delete tmp; // Stroustrup's gonna kill me for that } void RelayTransaction(const CTransaction& tx) { CInv inv(MSG_TX, tx.GetHash()); LOCK(cs_vNodes); for(CNode* pnode: vNodes) { pnode->PushInventory(inv); } } void RelayEncryptedCandidate(const EncryptedCandidateTransaction& ec) { LOCK(cs_vNodes); for(CNode* pnode: vNodes) { pnode->PushMessage(NetMsgType::ENCRYPTEDCANDIDATE, ec); } } void RelayAggregationSession(const AggregationSession& ms) { LOCK(cs_vNodes); for(CNode* pnode: vNodes) { pnode->PushMessage(NetMsgType::AGGREGATIONSESSION, ms); } } void CNode::RecordBytesRecv(uint64_t bytes) { LOCK(cs_totalBytesRecv); nTotalBytesRecv += bytes; } void CNode::RecordBytesSent(uint64_t bytes) { LOCK(cs_totalBytesSent); nTotalBytesSent += bytes; uint64_t now = GetTime(); if (nMaxOutboundCycleStartTime + nMaxOutboundTimeframe < now) { // timeframe expired, reset cycle nMaxOutboundCycleStartTime = now; nMaxOutboundTotalBytesSentInCycle = 0; } // TODO, exclude whitebind peers nMaxOutboundTotalBytesSentInCycle += bytes; } void CNode::SetMaxOutboundTarget(uint64_t limit) { LOCK(cs_totalBytesSent); uint64_t recommendedMinimum = (nMaxOutboundTimeframe / 600) * MAX_BLOCK_SERIALIZED_SIZE; nMaxOutboundLimit = limit; if (limit > 0 && limit < recommendedMinimum) LogPrintf("Max outbound target is very small (%s bytes) and will be overshot. Recommended minimum is %s bytes.\n", nMaxOutboundLimit, recommendedMinimum); } uint64_t CNode::GetMaxOutboundTarget() { LOCK(cs_totalBytesSent); return nMaxOutboundLimit; } uint64_t CNode::GetMaxOutboundTimeframe() { LOCK(cs_totalBytesSent); return nMaxOutboundTimeframe; } uint64_t CNode::GetMaxOutboundTimeLeftInCycle() { LOCK(cs_totalBytesSent); if (nMaxOutboundLimit == 0) return 0; if (nMaxOutboundCycleStartTime == 0) return nMaxOutboundTimeframe; uint64_t cycleEndTime = nMaxOutboundCycleStartTime + nMaxOutboundTimeframe; uint64_t now = GetTime(); return (cycleEndTime < now) ? 0 : cycleEndTime - GetTime(); } void CNode::SetMaxOutboundTimeframe(uint64_t timeframe) { LOCK(cs_totalBytesSent); if (nMaxOutboundTimeframe != timeframe) { // reset measure-cycle in case of changing // the timeframe nMaxOutboundCycleStartTime = GetTime(); } nMaxOutboundTimeframe = timeframe; } bool CNode::OutboundTargetReached(bool historicalBlockServingLimit) { LOCK(cs_totalBytesSent); if (nMaxOutboundLimit == 0) return false; if (historicalBlockServingLimit) { // keep a large enough buffer to at least relay each block once uint64_t timeLeftInCycle = GetMaxOutboundTimeLeftInCycle(); uint64_t buffer = timeLeftInCycle / 600 * MAX_BLOCK_SERIALIZED_SIZE; if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer) return true; } else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) return true; return false; } uint64_t CNode::GetOutboundTargetBytesLeft() { LOCK(cs_totalBytesSent); if (nMaxOutboundLimit == 0) return 0; return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle; } uint64_t CNode::GetTotalBytesRecv() { LOCK(cs_totalBytesRecv); return nTotalBytesRecv; } uint64_t CNode::GetTotalBytesSent() { LOCK(cs_totalBytesSent); return nTotalBytesSent; } void CNode::Fuzz(int nChance) { if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages switch (GetRand(3)) { case 0: // xor a random byte with a random value: if (!ssSend.empty()) { CDataStream::size_type pos = GetRand(ssSend.size()); ssSend[pos] ^= (unsigned char)(GetRand(256)); } break; case 1: // delete a random byte: if (!ssSend.empty()) { CDataStream::size_type pos = GetRand(ssSend.size()); ssSend.erase(ssSend.begin()+pos); } break; case 2: // insert a random byte at a random position { CDataStream::size_type pos = GetRand(ssSend.size()); char ch = (char)GetRand(256); ssSend.insert(ssSend.begin()+pos, ch); } break; } // Chance of more than one change half the time: // (more changes exponentially less likely): Fuzz(2); } // // CAddrDB // CAddrDB::CAddrDB() { pathAddr = GetDataDir() / "peers.dat"; } bool CAddrDB::Write(const CAddrMan& addr) { // Generate random temporary filename unsigned short randv = 0; GetRandBytes((unsigned char*)&randv, sizeof(randv)); std::string tmpfn = strprintf("peers.dat.%04x", randv); // serialize addresses, checksum data up to that point, then append csum CDataStream ssPeers(SER_DISK, CLIENT_VERSION); ssPeers << FLATDATA(Params().MessageStart()); ssPeers << addr; uint256 hash = Hash(ssPeers.begin(), ssPeers.end()); ssPeers << hash; // open temp output file, and associate with CAutoFile boost::filesystem::path pathTmp = GetDataDir() / tmpfn; FILE *file = fopen(pathTmp.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s: Failed to open file %s", __func__, pathTmp.string()); // Write and commit header, data try { fileout << ssPeers; } catch (const std::exception& e) { return error("%s: Serialize or I/O error - %s", __func__, e.what()); } FileCommit(fileout.Get()); fileout.fclose(); // replace existing peers.dat, if any, with new peers.dat.XXXX if (!RenameOver(pathTmp, pathAddr)) return error("%s: Rename-into-place failed", __func__); return true; } bool CAddrDB::Read(CAddrMan& addr) { // open input file, and associate with CAutoFile FILE *file = fopen(pathAddr.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error("%s: Failed to open file %s", __func__, pathAddr.string()); // use file size to size memory buffer uint64_t fileSize = boost::filesystem::file_size(pathAddr); uint64_t dataSize = 0; // Don't try to resize to a negative number if file is small if (fileSize >= sizeof(uint256)) dataSize = fileSize - sizeof(uint256); std::vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char *)&vchData[0], dataSize); filein >> hashIn; } catch (const std::exception& e) { return error("%s: Deserialize or I/O error - %s", __func__, e.what()); } filein.fclose(); CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end()); if (hashIn != hashTmp) return error("%s: Checksum mismatch, data corrupted", __func__); return Read(addr, ssPeers); } bool CAddrDB::Read(CAddrMan& addr, CDataStream& ssPeers) { unsigned char pchMsgTmp[4]; try { // de-serialize file header (network specific magic number) and .. ssPeers >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) return error("%s: Invalid network magic number", __func__); // de-serialize address data into one CAddrMan object ssPeers >> addr; } catch (const std::exception& e) { // de-serialization has failed, ensure addrman is left in a clean state addr.Clear(); return error("%s: Deserialize or I/O error - %s", __func__, e.what()); } return true; } unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER); } unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER); } CNode::CNode(SOCKET hSocketIn, const CAddress& addrIn, const std::string& addrNameIn, bool fInboundIn) : ssSend(SER_NETWORK, INIT_PROTO_VERSION), addr(addrIn), nKeyedNetGroup(CalculateKeyedNetGroup(addrIn)), addrKnown(5000, 0.001), filterInventoryKnown(50000, 0.000001) { nServices = NODE_NONE; nServicesExpected = NODE_NONE; hSocket = hSocketIn; nRecvVersion = INIT_PROTO_VERSION; nLastSend = 0; nLastRecv = 0; nSendBytes = 0; nRecvBytes = 0; nTimeConnected = GetTime(); nTimeOffset = 0; addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn; nVersion = 0; strSubVer = ""; fWhitelisted = false; fOneShot = false; fClient = false; // set by version message fInbound = fInboundIn; fNetworkNode = false; fSuccessfullyConnected = false; fDisconnect = false; nRefCount = 0; nSendSize = 0; nSendOffset = 0; hashContinue = uint256(); nStartingHeight = -1; filterInventoryKnown.reset(); fSendMempool = false; fGetAddr = false; nNextLocalAddrSend = 0; nNextAddrSend = 0; nNextInvSend = 0; fRelayTxes = false; fSentAddr = false; pfilter = new CBloomFilter(); timeLastMempoolReq = 0; nLastBlockTime = 0; nLastTXTime = 0; nPingNonceSent = 0; nPingUsecStart = 0; nPingUsecTime = 0; fPingQueued = false; nMinPingUsecTime = std::numeric_limits<int64_t>::max(); minFeeFilter = 0; lastSentFeeFilter = 0; nextSendTimeFeeFilter = 0; for(const std::string &msg: getAllNetMessageTypes()) mapRecvBytesPerMsgCmd[msg] = 0; mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0; { LOCK(cs_nLastNodeId); id = nLastNodeId++; } if (fLogIPs) LogPrint("net", "Added connection to %s peer=%d\n", addrName, id); else LogPrint("net", "Added connection peer=%d\n", id); // Be shy and don't send version until we hear if (hSocket != INVALID_SOCKET && !fInbound) PushVersion(); GetNodeSignals().InitializeNode(GetId(), this); } CNode::~CNode() { CloseSocket(hSocket); if (pfilter) delete pfilter; GetNodeSignals().FinalizeNode(GetId()); } void CNode::AskFor(const CInv& inv) { if (mapAskFor.size() > MAPASKFOR_MAX_SZ || setAskFor.size() > SETASKFOR_MAX_SZ) return; // a peer may not have multiple non-responded queue positions for a single inv item if (!setAskFor.insert(inv.hash).second) return; // We're using mapAskFor as a priority queue, // the key is the earliest time the request can be sent int64_t nRequestTime; limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv); if (it != mapAlreadyAskedFor.end()) nRequestTime = it->second; else nRequestTime = 0; LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id); // Make sure not to reuse time indexes to keep things in the same order int64_t nNow = GetTimeMicros() - 1000000; static int64_t nLastTime; ++nLastTime; nNow = std::max(nNow, nLastTime); nLastTime = nNow; // Each retry is 2 minutes after the last nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow); if (it != mapAlreadyAskedFor.end()) mapAlreadyAskedFor.update(it, nRequestTime); else mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime)); mapAskFor.insert(std::make_pair(nRequestTime, inv)); } void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend) { ENTER_CRITICAL_SECTION(cs_vSend); assert(ssSend.size() == 0); ssSend << CMessageHeader(Params().MessageStart(), pszCommand, 0); LogPrint("net", "sending: %s ", SanitizeString(pszCommand)); } void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend) { ssSend.clear(); LEAVE_CRITICAL_SECTION(cs_vSend); LogPrint("net", "(aborted)\n"); } void CNode::EndMessage(const char* pszCommand) UNLOCK_FUNCTION(cs_vSend) { // The -*messagestest options are intentionally not documented in the help message, // since they are only used during development to debug the networking code and are // not intended for end-users. if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0) { LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n"); AbortMessage(); return; } if (mapArgs.count("-fuzzmessagestest")) Fuzz(GetArg("-fuzzmessagestest", 10)); if (ssSend.size() == 0) { LEAVE_CRITICAL_SECTION(cs_vSend); return; } // Set the size unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE; WriteLE32((uint8_t*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], nSize); //log total amount of bytes per command mapSendBytesPerMsgCmd[std::string(pszCommand)] += nSize + CMessageHeader::HEADER_SIZE; // Set the checksum uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end()); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum)); memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum)); LogPrint("net", "(%d bytes) peer=%d\n", nSize, id); std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData()); ssSend.GetAndClear(*it); nSendSize += (*it).size(); // If write queue empty, attempt "optimistic write" if (it == vSendMsg.begin()) SocketSendData(this); LEAVE_CRITICAL_SECTION(cs_vSend); } // // CBanDB // CBanDB::CBanDB() { pathBanlist = GetDataDir() / "banlist.dat"; } bool CBanDB::Write(const banmap_t& banSet) { // Generate random temporary filename unsigned short randv = 0; GetRandBytes((unsigned char*)&randv, sizeof(randv)); std::string tmpfn = strprintf("banlist.dat.%04x", randv); // serialize banlist, checksum data up to that point, then append csum CDataStream ssBanlist(SER_DISK, CLIENT_VERSION); ssBanlist << FLATDATA(Params().MessageStart()); ssBanlist << banSet; uint256 hash = Hash(ssBanlist.begin(), ssBanlist.end()); ssBanlist << hash; // open temp output file, and associate with CAutoFile boost::filesystem::path pathTmp = GetDataDir() / tmpfn; FILE *file = fopen(pathTmp.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s: Failed to open file %s", __func__, pathTmp.string()); // Write and commit header, data try { fileout << ssBanlist; } catch (const std::exception& e) { return error("%s: Serialize or I/O error - %s", __func__, e.what()); } FileCommit(fileout.Get()); fileout.fclose(); // replace existing banlist.dat, if any, with new banlist.dat.XXXX if (!RenameOver(pathTmp, pathBanlist)) return error("%s: Rename-into-place failed", __func__); return true; } bool CBanDB::Read(banmap_t& banSet) { // open input file, and associate with CAutoFile FILE *file = fopen(pathBanlist.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error("%s: Failed to open file %s", __func__, pathBanlist.string()); // use file size to size memory buffer uint64_t fileSize = boost::filesystem::file_size(pathBanlist); uint64_t dataSize = 0; // Don't try to resize to a negative number if file is small if (fileSize >= sizeof(uint256)) dataSize = fileSize - sizeof(uint256); std::vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char *)&vchData[0], dataSize); filein >> hashIn; } catch (const std::exception& e) { return error("%s: Deserialize or I/O error - %s", __func__, e.what()); } filein.fclose(); CDataStream ssBanlist(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssBanlist.begin(), ssBanlist.end()); if (hashIn != hashTmp) return error("%s: Checksum mismatch, data corrupted", __func__); unsigned char pchMsgTmp[4]; try { // de-serialize file header (network specific magic number) and .. ssBanlist >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) return error("%s: Invalid network magic number", __func__); // de-serialize address data into one CAddrMan object ssBanlist >> banSet; } catch (const std::exception& e) { return error("%s: Deserialize or I/O error - %s", __func__, e.what()); } return true; } int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds) { return nNow + (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds * -1000000.0 + 0.5); } /* static */ uint64_t CNode::CalculateKeyedNetGroup(const CAddress& ad) { static const uint64_t k0 = GetRand(std::numeric_limits<uint64_t>::max()); static const uint64_t k1 = GetRand(std::numeric_limits<uint64_t>::max()); std::vector<unsigned char> vchNetGroup(ad.GetGroup()); return CSipHasher(k0, k1).Write(&vchNetGroup[0], vchNetGroup.size()).Finalize(); }
; size_t fread_callee(void *ptr, size_t size, size_t nmemb, FILE *stream) INCLUDE "clib_cfg.asm" SECTION code_stdio ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $02 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC _fread_callee EXTERN asm_fread _fread_callee: pop af pop de pop bc pop hl pop ix push af jp asm_fread ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC _fread_callee EXTERN _fread_unlocked_callee defc _fread_callee = _fread_unlocked_callee ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r8 push %rax push %rbp push %rcx push %rdi push %rsi lea addresses_WC_ht+0x13aff, %rsi lea addresses_normal_ht+0x18977, %rdi nop nop nop cmp %rax, %rax mov $14, %rcx rep movsw nop dec %r10 lea addresses_D_ht+0x144ff, %rsi lea addresses_normal_ht+0x17a4, %rdi nop nop nop nop nop sub %r8, %r8 mov $2, %rcx rep movsb nop nop nop cmp $43389, %rax lea addresses_D_ht+0x1dcff, %rsi lea addresses_UC_ht+0x16f7f, %rdi clflush (%rsi) cmp %rax, %rax mov $62, %rcx rep movsl nop nop and %r10, %r10 lea addresses_normal_ht+0x188ff, %rsi lea addresses_A_ht+0x10eef, %rdi nop nop nop add $63793, %r10 mov $80, %rcx rep movsq nop nop nop nop and $13796, %r8 lea addresses_D_ht+0x12cff, %rsi lea addresses_WC_ht+0x50ff, %rdi nop nop nop inc %rbp mov $27, %rcx rep movsq nop nop nop nop nop add $14619, %rbp lea addresses_normal_ht+0x66c7, %rsi lea addresses_WT_ht+0x9f7b, %rdi dec %rax mov $17, %rcx rep movsl nop sub $8648, %rcx lea addresses_D_ht+0x121ff, %rsi lea addresses_WC_ht+0x158af, %rdi clflush (%rsi) nop and %r11, %r11 mov $116, %rcx rep movsb nop nop nop sub %rax, %rax lea addresses_A_ht+0xeaff, %rsi nop nop add %r10, %r10 movl $0x61626364, (%rsi) nop nop nop nop nop and %rdi, %rdi lea addresses_UC_ht+0x5eb3, %rsi lea addresses_D_ht+0x325f, %rdi clflush (%rsi) nop nop nop nop nop and %rax, %rax mov $93, %rcx rep movsq nop nop xor %rax, %rax lea addresses_UC_ht+0x1efbf, %rsi lea addresses_WC_ht+0x18a3f, %rdi nop nop nop nop sub $39976, %r8 mov $17, %rcx rep movsb add $29276, %r8 lea addresses_A_ht+0xa0ff, %rsi lea addresses_WT_ht+0x19327, %rdi nop nop nop nop dec %rax mov $126, %rcx rep movsb nop nop nop nop cmp %r10, %r10 pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r8 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %rax push %rbp push %rbx push %rdx push %rsi // Load lea addresses_normal+0x90ff, %rsi nop nop nop nop nop and $45459, %rbx movups (%rsi), %xmm1 vpextrq $0, %xmm1, %r10 nop add $6568, %r11 // Store lea addresses_PSE+0x11fff, %r10 nop nop nop nop nop inc %rsi mov $0x5152535455565758, %rbp movq %rbp, (%r10) nop nop nop add $29340, %r11 // Store lea addresses_WT+0x7b37, %rax nop nop cmp $60430, %rdx movb $0x51, (%rax) cmp %rax, %rax // Faulty Load mov $0x9d48c00000008ff, %rbx nop inc %r10 mov (%rbx), %bp lea oracles, %rdx and $0xff, %rbp shlq $12, %rbp mov (%rdx,%rbp,1), %rbp pop %rsi pop %rdx pop %rbx pop %rbp pop %rax pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 8, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 6, 'size': 8, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 2, 'size': 1, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': True}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': True}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': True}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 7, 'size': 4, 'same': False, 'NT': True}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 6, 'same': True}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A035344: Expansion of 1/((1 - x)*(1 - 4*x + 2 * x^2)). ; 1,5,19,67,231,791,2703,9231,31519,107615,367423,1254463,4283007,14623103,49926399,170459391,581984767,1987020287,6784111615,23162405887,79081400319,270000789503,921840357375 mov $1,2 lpb $0,1 sub $0,1 add $2,$1 mul $1,2 add $1,$2 lpe sub $1,1
; lzo1f_f1.asm -- lzo1f_decompress_asm_fast ; ; This file is part of the LZO real-time data compression library. ; ; Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer ; All Rights Reserved. ; ; The LZO library is free software; you can redistribute it and/or ; modify it under the terms of the GNU General Public License as ; published by the Free Software Foundation; either version 2 of ; the License, or (at your option) any later version. ; ; The LZO library is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with the LZO library; see the file COPYING. ; If not, write to the Free Software Foundation, Inc., ; 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ; ; Markus F.X.J. Oberhumer ; <markus@oberhumer.com> ; http://www.oberhumer.com/opensource/lzo/ ; ; /***** DO NOT EDIT - GENERATED AUTOMATICALLY *****/ include asminit.def public _lzo1f_decompress_asm_fast _lzo1f_decompress_asm_fast: db 85,87,86,83,81,82,131,236,12,252,139,116,36,40,139,124 db 36,48,189,3,0,0,0,144,49,192,138,6,70,60,31,119 db 51,8,192,137,193,117,19,138,6,70,8,192,117,8,129,193 db 255,0,0,0,235,241,141,76,8,31,136,200,193,233,2,243 db 165,36,3,116,8,139,30,1,198,137,31,1,199,138,6,70 db 60,31,118,88,60,223,15,135,132,0,0,0,137,193,193,232 db 2,141,87,255,36,7,193,233,5,137,195,138,6,141,4,195 db 70,41,194,131,193,2,135,214,131,249,6,114,16,131,248,4 db 114,11,136,200,193,233,2,243,165,36,3,136,193,243,164,137 db 214,138,78,254,131,225,3,15,132,123,255,255,255,139,6,1 db 206,137,7,1,207,49,192,138,6,70,235,164,193,232,2,141 db 151,255,247,255,255,137,193,138,6,70,141,4,193,41,194,139 db 2,137,7,131,199,3,235,201,138,6,70,8,192,117,8,129 db 193,255,0,0,0,235,241,141,76,8,31,235,9,141,118,0 db 36,31,137,193,116,226,137,250,102,139,6,131,198,2,193,232 db 2,15,133,122,255,255,255,131,249,1,15,149,192,139,84,36 db 40,3,84,36,44,57,214,119,38,114,29,43,124,36,48,139 db 84,36,52,137,58,247,216,131,196,12,90,89,91,94,95,93 db 195,184,1,0,0,0,235,227,184,8,0,0,0,235,220,184 db 4,0,0,0,235,213,141,118,0,141,188,39,0,0,0,0 end
; A159759: Decimal expansion of (83+18*sqrt(2))/79. ; Submitted by Christian Krause ; 1,3,7,2,8,5,8,7,8,6,3,6,3,4,9,0,0,1,1,1,1,9,3,7,2,1,1,4,3,7,6,8,9,3,2,3,3,0,9,1,8,2,3,9,7,1,6,0,4,8,7,4,2,4,4,5,2,1,2,6,8,8,0,1,0,6,1,1,7,9,5,5,2,0,5,4,6,5,7,2,9,9,9,9,1,2,2,7,5,3,9,4,6,7,0,5,7,5,7,3 bin $1,$0 mov $2,2 mov $3,$0 mul $3,4 lpb $3 add $5,$2 add $1,$5 add $2,$1 mov $1,$2 sub $3,1 lpe mul $1,2 add $2,$5 mov $4,10 pow $4,$0 add $5,$2 div $2,6 mul $2,15 add $2,$5 div $2,$4 div $1,$2 mov $0,$1 mod $0,10
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r8 push %rax push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_A_ht+0x6d3f, %rsi lea addresses_WT_ht+0x7fb5, %rdi nop nop nop nop nop xor $55641, %rbp mov $112, %rcx rep movsq nop nop nop nop cmp $19593, %rbx lea addresses_D_ht+0x79f9, %r8 nop dec %rax mov $0x6162636465666768, %rdi movq %rdi, %xmm7 movups %xmm7, (%r8) sub $59447, %r8 lea addresses_UC_ht+0xd75, %rsi lea addresses_WT_ht+0xca75, %rdi nop nop nop nop sub %r12, %r12 mov $56, %rcx rep movsl nop nop nop nop nop sub %rax, %rax pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r8 pop %r12 ret .global s_faulty_load s_faulty_load: push %r13 push %r14 push %r8 push %rbp push %rbx push %rdi push %rsi // Store lea addresses_WT+0x10f3e, %rbx nop nop nop nop nop xor $243, %rsi mov $0x5152535455565758, %rbp movq %rbp, %xmm7 vmovups %ymm7, (%rbx) nop nop nop add $19835, %rdi // Load lea addresses_A+0xe335, %rdi inc %r8 movntdqa (%rdi), %xmm2 vpextrq $0, %xmm2, %rbx // Exception!!! nop nop nop nop nop mov (0), %r13 nop nop and $4615, %r13 // Faulty Load lea addresses_RW+0xdb75, %rsi and $15341, %rbx movb (%rsi), %r14b lea oracles, %r8 and $0xff, %r14 shlq $12, %r14 mov (%r8,%r14,1), %r14 pop %rsi pop %rdi pop %rbx pop %rbp pop %r8 pop %r14 pop %r13 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_RW', 'same': False, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_WT', 'same': False, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_A', 'same': False, 'size': 16, 'congruent': 5, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_RW', 'same': True, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'} {'32': 6734} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
; A123194: a(n) = (n+1)*Fibonacci(n+2) + 3. ; 4,7,12,23,43,81,150,275,498,893,1587,2799,4904,8543,14808,25555,43931,75261,128538,218923,371934,630457,1066467,1800603,3034828,5106871,8580900,14398415,24129163,40388073,67527582,112786499,188195274,313733813,522562323,869681415,1446262256,2403347471,3991032048,6623205643,10984486139,18206766357,30160575522,49935739483,82634035638,136675893361,225953767875,373379618355,616727182228,1018250553703,1680515285052,2772447140999,4572181277419,7537528572033,12421828854438,20464376585075,33703343603106,55489877510381,91332516599283,150283846917663,247217111810744,406563159830207,668443221036552,1098731531364163,1805562852293723,2966407634048301,4872471836625450,8001494071347595 mov $3,1 add $3,$0 mov $4,$0 add $4,1 mov $1,$4 mov $5,$3 lpb $0 sub $0,1 mov $2,$5 mov $3,$1 mov $5,$1 mov $1,$2 add $1,$3 lpe add $1,3
#include "NumberList.h" #include <iostream> #define _CRT_SECURE_NO_WARNINGS int main() { NumberList nr; nr.Init(); nr.Add(3); nr.Add(9); nr.Add(1); nr.Add(6); nr.Add(5); nr.Add(8); nr.Add(2); nr.Add(0); nr.Add(4); nr.Add(16); nr.Add(15); nr.Sort(); nr.Print(); }
; A040273: Continued fraction for sqrt(291). ; 17,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34,17,34 pow $1,$0 sub $1,2 gcd $1,$0 mul $1,17 mov $0,$1
; ISR_example.asm: a) Increments/decrements a BCD variable every half second using ; an ISR for timer 2; b) Generates a 2kHz square wave at pin P3.7 using ; an ISR for timer 0; and c) in the 'main' loop it displays the variable ; incremented/decremented using the ISR for timer 0 on the LCD. Also resets it to ; zero if the 'BOOT' pushbutton connected to P4.5 is pressed. $NOLIST $MODLP52 $LIST CLK EQU 22118400 ; Microcontroller system crystal frequency in Hz TIMER0_RATE EQU 4096 ; 2048Hz squarewave (peak amplitude of CEM-1203 speaker) TIMER0_RELOAD EQU ((65536-(CLK/TIMER0_RATE))) TIMER2_RATE EQU 1000 ; 1000Hz, for a timer tick of 1ms TIMER2_RELOAD EQU ((65536-(CLK/TIMER2_RATE))) BOOT_BUTTON equ P4.5 SOUND_OUT equ P3.7 UPDOWN equ P0.0 ; Reset vector org 0000H ljmp main ; External interrupt 0 vector (not used in this code) org 0003H reti ; Timer/Counter 0 overflow interrupt vector org 000BH ljmp Timer0_ISR ; External interrupt 1 vector (not used in this code) org 0013H reti ; Timer/Counter 1 overflow interrupt vector (not used in this code) org 001BH reti ; Serial port receive/transmit interrupt vector (not used in this code) org 0023H reti ; Timer/Counter 2 overflow interrupt vector org 002BH ljmp Timer2_ISR dseg at 30h Count1ms: ds 2 ; Used to determine when half second has passed BCD_counter: ds 1 ; The BCD counter incrememted in the ISR and displayed in the main loop bseg half_seconds_flag: dbit 1 ; Set to one in the ISR every time 500 ms had passed cseg ; These 'equ' must match the wiring between the microcontroller and the LCD! LCD_RS equ P1.4 LCD_RW equ P1.5 LCD_E equ P1.6 LCD_D4 equ P3.2 LCD_D5 equ P3.3 LCD_D6 equ P3.4 LCD_D7 equ P3.5 $NOLIST $include(LCD_4bit.inc) ; A library of LCD related functions and utility macros $LIST ; 1234567890123456 <- This helps determine the position of the counter Initial_Message: db 'BCD_counter: xx', 0 ;---------------------------------; ; Routine to initialize the ISR ; ; for timer 0 ; ;---------------------------------; Timer0_Init: mov a, TMOD anl a, #0xf0 ; Clear the bits for timer 0 orl a, #0x01 ; Configure timer 0 as 16-timer mov TMOD, a mov TH0, #high(TIMER0_RELOAD) mov TL0, #low(TIMER0_RELOAD) ; Enable the timer and interrupts setb ET0 ; Enable timer 0 interrupt setb TR0 ; Start timer 0 setb EA ; Enable Global interrupts ret ;---------------------------------; ; ISR for timer 0. Set to execute; ; every 1/4096Hz to generate a ; ; 2048 Hz square wave at pin P3.7 ; ;---------------------------------; Timer0_ISR: ; Define a latency correction for the timer reload CORRECTION EQU (4+4+2+2+4+4) ; lcall+ljmp+clr+mov+mov+setb ; In mode 1 we need to reload the timer. clr TR0 mov TH0, #high(TIMER0_RELOAD+CORRECTION) mov TL0, #low(TIMER0_RELOAD+CORRECTION) setb TR0 cpl SOUND_OUT ; Connect speaker to P3.7! reti ;---------------------------------; ; Routine to initialize the ISR ; ; for timer 2 ; ;---------------------------------; Timer2_Init: mov T2CON, #0 ; Stop timer. Autoreload mode. ; One millisecond interrupt mov RCAP2H, #high(TIMER2_RELOAD) mov RCAP2L, #low(TIMER2_RELOAD) ; Set the 16-bit variable Count1ms to zero clr a mov Count1ms+0, a mov Count1ms+1, a ; Enable the timer and interrupts setb ET2 ; Enable timer 2 interrupt setb TR2 ; Enable timer 2 setb EA ; Enable Global interrupts ret ;---------------------------------; ; ISR for timer 2 ; ;---------------------------------; Timer2_ISR: clr TF2 ; Timer 2 doesn't clear TF2 automatically in ISR cpl P3.6 ; To check the interrupt rate with oscilloscope. It must be a 1 ms pulse. ; The two registers used in the ISR must be saved in the stack push acc push psw ; Increment the 16-bit counter inc Count1ms+0 ; Increment the low 8-bits first mov a, Count1ms+0 ; If the low 8-bits overflow, then increment high 8-bits jnz Inc_Done inc Count1ms+1 Inc_Done: ; Check if half second has passed mov a, Count1ms+0 cjne a, #low(1000), Timer2_ISR_done mov a, Count1ms+1 cjne a, #high(1000), Timer2_ISR_done ; 500 milliseconds have passed. Set a flag so the main program knows setb half_seconds_flag ; Let the main program know half second had passed cpl TR1 ; This line makes a beep-silence-beep-silence sound ; Reset the milli-seconds counter, it is a 16-bit variable clr a mov Count1ms+0, a mov Count1ms+1, a ; Increment the BCD counter mov a, BCD_counter jnb UPDOWN, Timer2_ISR_decrement add a, #0x01 sjmp Timer2_ISR_da Timer2_ISR_decrement: add a, #0x99 Timer2_ISR_da: da a mov BCD_counter, a Timer2_ISR_done: pop psw pop acc reti ;---------------------------------; ; Main program. Includes hardware ; ; initialization and 'forever' ; ; loop. ; ;---------------------------------; main: ; Initialization mov SP, #7FH mov PMOD, #0 ; Configure all ports in bidirectional mode lcall Timer0_Init lcall Timer2_Init lcall LCD_4BIT ; For convenience a few handy macros are included in 'LCD_4bit.inc': Set_Cursor(1, 1) Send_Constant_String(#Initial_Message) setb half_seconds_flag mov BCD_counter, #0x00 ; After initialization the program stays in this 'forever' loop loop: jb BOOT_BUTTON, loop_a ; if the 'BOOT' button is not pressed skip Wait_Milli_Seconds(#50) ; Debounce delay. This macro is also in 'LCD_4bit.inc' jb BOOT_BUTTON, loop_a ; if the 'BOOT' button is not pressed skip jnb BOOT_BUTTON, $ ; wait for button release ; A clean press of the 'BOOT' button has been detected, reset the BCD counter. ; But first stop the timer and reset the milli-seconds counter, to resync everything. clr TR0 clr a mov Count1ms+0, a mov Count1ms+1, a ; Now clear the BCD counter mov BCD_counter, #0x00 setb TR0 ; Re-enable the timer sjmp loop_b ; Display the new value loop_a: jnb half_seconds_flag, loop loop_b: clr half_seconds_flag ; We clear this flag in the main loop, but it is set in the ISR for timer 0 Set_Cursor(1, 14) ; the place in the LCD where we want the BCD counter value Display_BCD(BCD_counter) ; This macro is also in 'LCD_4bit.inc' ljmp loop END
; A211636: Number of ordered triples (w,x,y) with all terms in {1,...,n} and w^2>=x^2+y^2. ; Submitted by Christian Krause ; 0,0,1,5,13,28,50,80,121,175,244,327,425,544,683,845,1028,1236,1470,1733,2027,2349,2706,3096,3520,3985,4489,5034,5619,6247,6922,7641,8411,9230,10102,11030,12007,13043,14133,15288,16504,17778,19117 lpb $0 mov $2,$0 sub $0,1 seq $2,119677 ; a(n) is the number of complete squares that fit inside the circle with radius n, drawn on squared paper. add $3,$2 lpe mov $0,$3 div $0,4
; A192959: Coefficient of x in the reduction by x^2 -> x+1 of the polynomial p(n,x) defined at Comments. ; 0,1,0,3,10,27,60,121,228,411,718,1227,2064,3433,5664,9291,15178,24723,40188,65233,105780,171411,277630,449523,727680,1177777,1906080,3084531,4991338,8076651,13068828,21146377,34216164,55363563,89580814,144945531,234527568,379474393,614003328,993479163,1607484010,2600964771,4208450460,6809416993,11017869300,17827288227,28845159550,46672449891,75517611648,122190063841,197707677888,319897744227,517605424714,837503171643,1355108599164,2192611773721,3547720375908,5740332152763,9288052531918,15028384688043,24316437223440,39344821915081,63661259142240,103006081061163,166667340207370,269673421272627,436340761484220,706014182761201,1142354944249908,1848369127015731,2990724071270398,4839093198291027,7829817269566464 mov $1,$0 mov $3,$0 cal $0,192968 ; Coefficient of x in the reduction by x^2 -> x+1 of the polynomial p(n,x) defined at Comments. mul $1,2 sub $1,1 sub $3,$1 mov $1,$0 mov $2,92 add $2,$0 add $2,$3 add $1,$2 sub $1,93
; ***************************************************************************** ; ***************************************************************************** ; ; Name: miscellany.asm ; Purpose: Miscellaneous Commands ; Created: 3rd March 2020 ; Reviewed: 16th March 2020 ; Author: Paul Robson (paul@robsons.org.uk) ; ; ***************************************************************************** ; ***************************************************************************** ; ***************************************************************************** ; ; Stop Program ; ; ***************************************************************************** .Command_Stop ;; [stop] jmp #StopError ; ***************************************************************************** ; ; End Program ; ; ***************************************************************************** .Command_End ;; [end] jmp #WarmStart ; ***************************************************************************** ; ; Assert Handler ; ; ***************************************************************************** .CommandAssert ;; [assert] push link jsr #EvaluateInteger ; assert what ? sknz r0 jmp #AssertError ; failed. pop link ret ; ***************************************************************************** ; ; Poke a memory location ; ; ***************************************************************************** .CommandPoke ;; [poke] push link jsr #EvaluateInteger ; address to poke -> R1 mov r1,r0,#0 jsr #CheckComma jsr #EvaluateInteger ; data -> R0 stm r0,r1,#0 ; do the POKE pop link ret ; ***************************************************************************** ; ; Code for ' and REM comment handlers ; Can be REM or REM "comment", same for ' ; ; ***************************************************************************** .CommentCommand1 ;; ['] .CommentCommand2 ;; [rem] ldm r11,#currentLine ; get current line ldm r0,r11,#0 ; read offset of current line add r11,r0,#0 ; add to take to next line. dec r11 ; last token of line $0000 will force next line. ret ; ***************************************************************************** ; ; Move cursor ; ; ***************************************************************************** .Command_Cursor ;; [cursor] push link jsr #EvaluateInteger mov r1,r0,#0 sub r0,#CharWidth sklt jmp #BadNumberError jsr #CheckComma jsr #EvaluateInteger mov r2,r0,#0 sub r0,#CharHeight sklt jmp #BadNumberError ; stm r1,#xTextPos stm r2,#yTextPos pop link ret ; ***************************************************************************** ; ; Wait for a given number of 1/100 sec ; ; ***************************************************************************** .CommandWait ;; [wait] push link jsr #EvaluateInteger ; how long to wait ldm r1,#hwTimer ; add current value add r1,r0,#0 ._CWTLoop jsr #OSSystemManager ; keep stuff going skz r0 ; exit on break jmp #BreakError ; error if broken. ldm r0,#hwTimer sub r0,r1,#0 ; until timer >= end signed skp r0 jmp #_CWTLoop pop link ret ; ***************************************************************************** ; ; Code for colon, which does nothing ; ; ***************************************************************************** .ColonHandler ;; [:] ret ; ***************************************************************************** ; ; Randomise ; ; ***************************************************************************** .SeedHandler ;; [randomise] push link jsr #EvaluateInteger sknz r0 jmp #BadNumberError jsr #OSRandomSeed pop link ret ; ***************************************************************************** ; ; Call a M/C Routine ; ; ***************************************************************************** .CommandSys ;; [sys] push r1,r2,r3,r4,r5,r6,r7,r8,link jsr #EvaluateInteger ; address -> R6 mov r6,r0,#0 mov r7,#inputBuffer ; this is where R0,R1 etc .... go mov r8,r7,#0 ; copy to R8 stm r14,r7,#0 ; clear the values stm r14,r7,#1 stm r14,r7,#2 stm r14,r7,#3 stm r14,r7,#4 stm r14,r7,#5 ._CSLoop ldm r0,r11,#0 ; is there a comma xor r0,#TOK_COMMA skz r0 jmp #_CSCallCode inc r11 ; skip comma jsr #EvaluateInteger ; next parameter stm r0,r7,#0 ; save in workspace inc r7 ; next slot mov r0,r7,#0 ; maximum of 6 xor r0,#inputBuffer+6 skz r0 jmp #_CSLoop jmp #SyntaxError ; too many parameters ; ._CSCallCode ldm r0,r8,#0 ; get values ldm r1,r8,#1 ldm r2,r8,#2 ldm r3,r8,#3 ldm r4,r8,#4 ldm r5,r8,#5 mov r8,#tokenBufferEnd-1 ; set up R8 for RPL stack if an RPL function. push r11 ; R11 is the program position, don't want that changed. brl link,r6,#0 ; call the routine xor r8,#tokenBufferEnd-1 ; check the stack is clean skz r8 jmp #StackImbalanceError pop r11 pop r1,r2,r3,r4,r5,r6,r7,r8,link ret ; ***************************************************************************** ; ; Renumber program ; ; ***************************************************************************** .RenumberProgram ;; [renum] mov r1,#1000 ; current line number ldm r0,#programCode ; R0 is current program ._RPLoop ldm r2,r0,#0 ; read offset to R2 sknz r2 ; exit if offset zero ret stm r1,r0,#1 ; overwrite line number add r1,#10 ; update line number add r0,r2,#0 ; next line jmp #_RPLoop ; ***************************************************************************** ; ; Code for non-executable, stops the build squawking ; ; ***************************************************************************** .Dummy1 ;; [)] .Dummy2 ;; [,] .Dummy3 ;; [;] .Dummy4 ;; [to] .Dummy5 ;; [step] .Dummy6 ;; [then] .Dummy7 ;; [#] .Dummy9 ;; [flip] .Dummy110 ;; [on] .Dummy111 ;; [when] .Dummy112 ;; [default] .Dummy113 ;; [inport(] .Dummy114 ;; [outport] .Dummy115 ;; [case] .Dummy116 ;; [endcase] .Dummy119 ;; [^] ; ; This lot are not commands per se, but are handled in RUN as token values. ; .Dummy10 ;; [adc] .Dummy11 ;; [add] .Dummy12 ;; [brl] .Dummy13 ;; [ldm] .Dummy14 ;; [mov] .Dummy15 ;; [mult] .Dummy16 ;; [ror] .Dummy17 ;; [skcm] .Dummy18 ;; [skeq] .Dummy19 ;; [skne] .Dummy20 ;; [skse] .Dummy21 ;; [sksn] .Dummy22 ;; [stm] .Dummy23 ;; [sub] ; ; This lot are not yet implemented. ; .Dummy204 ;; [mon] jmp #SyntaxError
// 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. // // File: StubGen.cpp // // #include "common.h" #include "stubgen.h" #include "jitinterface.h" #include "ilstubcache.h" #include "sigbuilder.h" #include "formattype.h" #include "typestring.h" #include "field.h" // // ....[.....\xxxxx]..0... -> ....[xxxxx]..0... // ^ ^ ^ void DumpIL_RemoveFullPath(SString &strTokenFormatting) { STANDARD_VM_CONTRACT; if (strTokenFormatting.IsEmpty()) return; SString::Iterator begin = strTokenFormatting.Begin(); SString::Iterator end = strTokenFormatting.End(); SString::Iterator leftBracket = strTokenFormatting.Begin(); // Find the first '[' in the string. while ((leftBracket != end) && (*leftBracket != W('['))) { ++leftBracket; } if (leftBracket != end) { SString::Iterator lastSlash = strTokenFormatting.End() - 1; // Find the last '\\' in the string. while ((lastSlash != leftBracket) && (*lastSlash != W('\\'))) { --lastSlash; } if (leftBracket != lastSlash) { strTokenFormatting.Delete(leftBracket + 1, lastSlash - leftBracket); } } } void DumpIL_FormatToken(TokenLookupMap* pTokenMap, mdToken token, SString &strTokenFormatting, const SString &strStubTargetSig) { void* pvLookupRetVal = (void*)POISONC; _ASSERTE(strTokenFormatting.IsEmpty()); EX_TRY { if (TypeFromToken(token) == mdtMethodDef) { MethodDesc* pMD = pTokenMap->LookupMethodDef(token); pvLookupRetVal = pMD; CONSISTENCY_CHECK(CheckPointer(pMD)); pMD->GetFullMethodInfo(strTokenFormatting); } else if (TypeFromToken(token) == mdtTypeDef) { TypeHandle typeHnd = pTokenMap->LookupTypeDef(token); pvLookupRetVal = typeHnd.AsPtr(); CONSISTENCY_CHECK(!typeHnd.IsNull()); SString typeName; MethodTable *pMT = NULL; if (typeHnd.IsTypeDesc()) { TypeDesc *pTypeDesc = typeHnd.AsTypeDesc(); pMT = pTypeDesc->GetMethodTable(); } else { pMT = typeHnd.AsMethodTable(); } // AppendType handles NULL correctly TypeString::AppendType(typeName, TypeHandle(pMT)); if (pMT && typeHnd.IsNativeValueType()) typeName.Append(W("_NativeValueType")); strTokenFormatting.Set(typeName); } else if (TypeFromToken(token) == mdtFieldDef) { FieldDesc* pFD = pTokenMap->LookupFieldDef(token); pvLookupRetVal = pFD; CONSISTENCY_CHECK(CheckPointer(pFD)); SString typeName; TypeString::AppendType(typeName, TypeHandle(pFD->GetApproxEnclosingMethodTable())); SString strFieldName(SString::Utf8, pFD->GetName()); strTokenFormatting.Printf(W("%s::%s"), typeName.GetUnicode(), strFieldName.GetUnicode()); } else if (TypeFromToken(token) == mdtModule) { // Do nothing, because strTokenFormatting is already empty. } else if (TypeFromToken(token) == mdtSignature) { CONSISTENCY_CHECK(token == TOKEN_ILSTUB_TARGET_SIG); strTokenFormatting.Set(strStubTargetSig); } else { strTokenFormatting.Printf(W("%d"), token); } DumpIL_RemoveFullPath(strTokenFormatting); } EX_CATCH { strTokenFormatting.Printf(W("%d"), token); } EX_END_CATCH(SwallowAllExceptions) } void ILCodeStream::Emit(ILInstrEnum instr, INT16 iStackDelta, UINT_PTR uArg) { STANDARD_VM_CONTRACT; UINT idxCurInstr = 0; ILStubLinker::ILInstruction* pInstrBuffer = NULL; if (NULL == m_pqbILInstructions) { m_pqbILInstructions = new ILCodeStreamBuffer(); } idxCurInstr = m_uCurInstrIdx; m_uCurInstrIdx++; m_pqbILInstructions->ReSizeThrows(m_uCurInstrIdx * sizeof(ILStubLinker::ILInstruction)); pInstrBuffer = (ILStubLinker::ILInstruction*)m_pqbILInstructions->Ptr(); pInstrBuffer[idxCurInstr].uInstruction = static_cast<UINT16>(instr); pInstrBuffer[idxCurInstr].iStackDelta = iStackDelta; pInstrBuffer[idxCurInstr].uArg = uArg; } ILCodeLabel* ILStubLinker::NewCodeLabel() { STANDARD_VM_CONTRACT; ILCodeLabel* pCodeLabel = new ILCodeLabel(); pCodeLabel->m_pNext = m_pLabelList; pCodeLabel->m_pOwningStubLinker = this; pCodeLabel->m_pCodeStreamOfLabel = NULL; pCodeLabel->m_idxLabeledInstruction = -1; m_pLabelList = pCodeLabel; return pCodeLabel; } void ILCodeStream::EmitLabel(ILCodeLabel* pCodeLabel) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION_MSG(m_pOwner == pCodeLabel->m_pOwningStubLinker, "you can only use a code label in the ILStubLinker that created it!"); } CONTRACTL_END; pCodeLabel->m_pCodeStreamOfLabel = this; pCodeLabel->m_idxLabeledInstruction = m_uCurInstrIdx; Emit(CEE_CODE_LABEL, 0, (UINT_PTR)pCodeLabel); } static const BYTE s_rgbOpcodeSizes[] = { #define OPDEF(name,string,pop,push,oprType,opcType,l,s1,s2,ctrl) \ ((l) + (oprType)), #define InlineNone 0 #define ShortInlineVar 1 #define ShortInlineI 1 #define InlineI 4 #define InlineI8 8 #define ShortInlineR 4 #define InlineR 8 #define InlineMethod 4 #define InlineSig 4 #define ShortInlineBrTarget 1 #define InlineBrTarget 4 #define InlineSwitch -1 #define InlineType 4 #define InlineString 4 #define InlineField 4 #define InlineTok 4 #define InlineVar 2 #include "opcode.def" #undef OPDEF #undef InlineNone #undef ShortInlineVar #undef ShortInlineI #undef InlineI #undef InlineI8 #undef ShortInlineR #undef InlineR #undef InlineMethod #undef InlineSig #undef ShortInlineBrTarget #undef InlineBrTarget #undef InlineSwitch #undef InlineType #undef InlineString #undef InlineField #undef InlineTok #undef InlineVar }; struct ILOpcode { BYTE byte1; BYTE byte2; }; static const ILOpcode s_rgOpcodes[] = { #define OPDEF(name,string,pop,push,oprType,opcType,l,s1,s2,ctrl) \ { (s1), (s2) }, #include "opcode.def" #undef OPDEF }; ILCodeStream::ILInstrEnum ILCodeStream::LowerOpcode(ILInstrEnum instr, ILStubLinker::ILInstruction* pInstr) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(instr == (ILInstrEnum)pInstr->uInstruction); } CONTRACTL_END; // // NOTE: we do not lower branches to their smallest form because that // would introduce extra passes at link time, which isn't really // worth the savings in IL code size. // UINT_PTR uConst = pInstr->uArg; switch (instr) { case CEE_LDC_I8: { if (uConst == (UINT_PTR)-1) { instr = CEE_LDC_I4_M1; } else if (uConst < 9) { instr = (ILInstrEnum)((UINT_PTR)CEE_LDC_I4_0 + uConst); } else if (FitsInI1(uConst)) { instr = CEE_LDC_I4_S; } else if (FitsInI4(uConst)) { instr = CEE_LDC_I4; } break; } case CEE_LDARG: { if (uConst <= 3) { instr = (ILInstrEnum)((UINT_PTR)CEE_LDARG_0 + uConst); break; } goto lShortForm; } case CEE_LDLOC: { if (uConst <= 3) { instr = (ILInstrEnum)((UINT_PTR)CEE_LDLOC_0 + uConst); break; } goto lShortForm; } case CEE_STLOC: { if (uConst <= 3) { instr = (ILInstrEnum)((UINT_PTR)CEE_STLOC_0 + uConst); break; } lShortForm: if (FitsInI1(uConst)) { static const UINT_PTR c_uMakeShortDelta = ((UINT_PTR)CEE_LDARG - (UINT_PTR)CEE_LDARG_S); static_assert_no_msg(((UINT_PTR)CEE_LDARG - c_uMakeShortDelta) == (UINT_PTR)CEE_LDARG_S); static_assert_no_msg(((UINT_PTR)CEE_LDLOC - c_uMakeShortDelta) == (UINT_PTR)CEE_LDLOC_S); static_assert_no_msg(((UINT_PTR)CEE_STLOC - c_uMakeShortDelta) == (UINT_PTR)CEE_STLOC_S); instr = (ILInstrEnum)((UINT_PTR)instr - c_uMakeShortDelta); } break; } case CEE_LDARGA: case CEE_STARG: case CEE_LDLOCA: { if (FitsInI1(uConst)) { static const UINT_PTR c_uMakeShortDelta = ((UINT_PTR)CEE_LDARGA - (UINT_PTR)CEE_LDARGA_S); static_assert_no_msg(((UINT_PTR)CEE_LDARGA - c_uMakeShortDelta) == (UINT_PTR)CEE_LDARGA_S); static_assert_no_msg(((UINT_PTR)CEE_STARG - c_uMakeShortDelta) == (UINT_PTR)CEE_STARG_S); static_assert_no_msg(((UINT_PTR)CEE_LDLOCA - c_uMakeShortDelta) == (UINT_PTR)CEE_LDLOCA_S); instr = (ILInstrEnum)((UINT_PTR)instr - c_uMakeShortDelta); } break; } default: break; } pInstr->uInstruction = static_cast<UINT16>(instr); return instr; } void ILStubLinker::PatchInstructionArgument(ILCodeLabel* pLabel, UINT_PTR uNewArg DEBUG_ARG(UINT16 uExpectedInstruction)) { LIMITED_METHOD_CONTRACT; UINT idx = pLabel->m_idxLabeledInstruction; ILCodeStream* pLabelCodeStream = pLabel->m_pCodeStreamOfLabel; ILInstruction* pLabelInstrBuffer = (ILInstruction*)pLabelCodeStream->m_pqbILInstructions->Ptr(); CONSISTENCY_CHECK(pLabelInstrBuffer[idx].uInstruction == ILCodeStream::CEE_CODE_LABEL); CONSISTENCY_CHECK(pLabelInstrBuffer[idx].iStackDelta == 0); idx++; CONSISTENCY_CHECK(idx < pLabelCodeStream->m_uCurInstrIdx); CONSISTENCY_CHECK(pLabelInstrBuffer[idx].uInstruction == uExpectedInstruction); pLabelInstrBuffer[idx].uArg = uNewArg; } ILCodeLabel::ILCodeLabel() { m_pNext = NULL; m_pOwningStubLinker = NULL; m_pCodeStreamOfLabel = NULL; m_codeOffset = -1; m_idxLabeledInstruction = -1; } ILCodeLabel::~ILCodeLabel() { } size_t ILCodeLabel::GetCodeOffset() { LIMITED_METHOD_CONTRACT; CONSISTENCY_CHECK(m_codeOffset != (size_t)-1); return m_codeOffset; } void ILCodeLabel::SetCodeOffset(size_t codeOffset) { LIMITED_METHOD_CONTRACT; CONSISTENCY_CHECK((m_codeOffset == (size_t)-1) && (codeOffset != (size_t)-1)); m_codeOffset = codeOffset; } static const LPCSTR s_rgOpcodeNames[] = { #define OPDEF(name,string,pop,push,oprType,opcType,l,s1,s2,ctrl) \ string, #include "opcode.def" #undef OPDEF }; #include "openum.h" static const BYTE s_rgbOpcodeArgType[] = { #define OPDEF(name,string,pop,push,oprType,opcType,l,s1,s2,ctrl) \ oprType, #include "opcode.def" #undef OPDEF }; //--------------------------------------------------------------------------------------- // void ILStubLinker::LogILInstruction( size_t curOffset, bool isLabeled, INT iCurStack, ILInstruction * pInstruction, SString * pDumpILStubCode) { STANDARD_VM_CONTRACT; // // format label // SString strLabel; if (isLabeled) { strLabel.Printf(W("IL_%04x:"), curOffset); } else { strLabel.Set(W(" ")); } // // format opcode // SString strOpcode; ILCodeStream::ILInstrEnum instr = (ILCodeStream::ILInstrEnum)pInstruction->uInstruction; size_t cbOpcodeName = strlen(s_rgOpcodeNames[instr]); SString strOpcodeName; strOpcodeName.SetUTF8(s_rgOpcodeNames[instr]); // Set the width of the opcode to 15. strOpcode.Set(W(" ")); strOpcode.Replace(strOpcode.Begin(), (COUNT_T)cbOpcodeName, strOpcodeName); // // format argument // static const size_t c_cchPreallocateArgument = 512; SString strArgument; strArgument.Preallocate(c_cchPreallocateArgument); static const size_t c_cchPreallocateTokenName = 1024; SString strTokenName; strTokenName.Preallocate(c_cchPreallocateTokenName); if (ILCodeStream::IsBranchInstruction(instr)) { size_t branchDistance = (size_t)pInstruction->uArg; size_t targetOffset = curOffset + s_rgbOpcodeSizes[instr] + branchDistance; strArgument.Printf(W("IL_%04x"), targetOffset); } else if ((ILCodeStream::ILInstrEnum)CEE_NOP == instr) { SString strInstruction; strInstruction.Printf("%s", (char *)pInstruction->uArg); strInstruction.ConvertToUnicode(strArgument); } else { switch (s_rgbOpcodeArgType[instr]) { case InlineNone: break; case ShortInlineVar: case ShortInlineI: case InlineI: strArgument.Printf(W("0x%x"), pInstruction->uArg); break; case InlineI8: strArgument.Printf(W("0x%p"), (void *)pInstruction->uArg); break; case InlineMethod: case InlineField: case InlineType: case InlineString: case InlineSig: case InlineRVA: case InlineTok: // No token value when we dump IL for ETW if (pDumpILStubCode == NULL) strArgument.Printf(W("0x%08x"), pInstruction->uArg); LPUTF8 pszFormattedStubTargetSig = NULL; CQuickBytes qbTargetSig; if (TOKEN_ILSTUB_TARGET_SIG == pInstruction->uArg) { PCCOR_SIGNATURE pTargetSig; ULONG cTargetSig; CQuickBytes qbTempTargetSig; IMDInternalImport * pIMDI = MscorlibBinder::GetModule()->GetMDImport(); cTargetSig = GetStubTargetMethodSigSize(); pTargetSig = (PCCOR_SIGNATURE)qbTempTargetSig.AllocThrows(cTargetSig); GetStubTargetMethodSig((BYTE*)pTargetSig, cTargetSig); PrettyPrintSig(pTargetSig, cTargetSig, "", &qbTargetSig, pIMDI, NULL); pszFormattedStubTargetSig = (LPUTF8)qbTargetSig.Ptr(); } // Dump to szTokenNameBuffer if logging, otherwise dump to szArgumentBuffer to avoid an extra space because we are omitting the token _ASSERTE(FitsIn<mdToken>(pInstruction->uArg)); SString strFormattedStubTargetSig; strFormattedStubTargetSig.SetUTF8(pszFormattedStubTargetSig); if (pDumpILStubCode == NULL) DumpIL_FormatToken(&m_tokenMap, static_cast<mdToken>(pInstruction->uArg), strTokenName, strFormattedStubTargetSig); else DumpIL_FormatToken(&m_tokenMap, static_cast<mdToken>(pInstruction->uArg), strArgument, strFormattedStubTargetSig); break; } } // // log it! // if (pDumpILStubCode) { pDumpILStubCode->AppendPrintf(W("%s /*(%2d)*/ %s %s %s\n"), strLabel.GetUnicode(), iCurStack, strOpcode.GetUnicode(), strArgument.GetUnicode(), strTokenName.GetUnicode()); } else { StackScratchBuffer strLabelBuffer; StackScratchBuffer strOpcodeBuffer; StackScratchBuffer strArgumentBuffer; StackScratchBuffer strTokenNameBuffer; LOG((LF_STUBS, LL_INFO1000, "%s (%2d) %s %s %s\n", strLabel.GetUTF8(strLabelBuffer), iCurStack, \ strOpcode.GetUTF8(strOpcodeBuffer), strArgument.GetUTF8(strArgumentBuffer), strTokenName.GetUTF8(strTokenNameBuffer))); } } // ILStubLinker::LogILInstruction //--------------------------------------------------------------------------------------- // void ILStubLinker::LogILStubWorker( ILInstruction * pInstrBuffer, UINT numInstr, size_t * pcbCode, INT * piCurStack, SString * pDumpILStubCode) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pcbCode)); PRECONDITION(CheckPointer(piCurStack)); PRECONDITION(CheckPointer(pDumpILStubCode, NULL_OK)); } CONTRACTL_END; bool isLabeled = false; for (UINT i = 0; i < numInstr; i++) { ILCodeStream::ILInstrEnum instr = (ILCodeStream::ILInstrEnum)pInstrBuffer[i].uInstruction; CONSISTENCY_CHECK(ILCodeStream::IsSupportedInstruction(instr)); if (instr == ILCodeStream::CEE_CODE_LABEL) { isLabeled = true; continue; } LogILInstruction(*pcbCode, isLabeled, *piCurStack, &pInstrBuffer[i], pDumpILStubCode); isLabeled = false; // // calculate the code size // PREFIX_ASSUME((size_t)instr < sizeof(s_rgbOpcodeSizes)); *pcbCode += s_rgbOpcodeSizes[instr]; // // calculate curstack // *piCurStack += pInstrBuffer[i].iStackDelta; } // Be sure to log any trailing label that has no associated instruction. if (isLabeled) { if (pDumpILStubCode) { pDumpILStubCode->AppendPrintf(W("IL_%04x:\n"), *pcbCode); } else { LOG((LF_STUBS, LL_INFO1000, "IL_%04x:\n", *pcbCode)); } } } static inline void LogOneFlag(DWORD flags, DWORD flag, LPCSTR str, DWORD facility, DWORD level) { if (flags & flag) { LOG((facility, level, str)); } } static void LogJitFlags(DWORD facility, DWORD level, DWORD dwJitFlags) { CONTRACTL { STANDARD_VM_CHECK; } CONTRACTL_END; LOG((facility, level, "dwJitFlags: 0x%08x\n", dwJitFlags)); #define LOG_FLAG(name) LogOneFlag(dwJitFlags, name, " " #name "\n", facility, level); // these are all we care about at the moment LOG_FLAG(CORJIT_FLG_IL_STUB); LOG_FLAG(CORJIT_FLG_PUBLISH_SECRET_PARAM); #undef LOG_FLAGS DWORD dwKnownMask = CORJIT_FLG_IL_STUB | CORJIT_FLG_PUBLISH_SECRET_PARAM | NULL; DWORD dwUnknownFlags = dwJitFlags & ~dwKnownMask; if (0 != dwUnknownFlags) { LOG((facility, level, "UNKNOWN FLAGS: 0x%08x\n", dwUnknownFlags)); } } void ILStubLinker::LogILStub(DWORD dwJitFlags, SString *pDumpILStubCode) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pDumpILStubCode, NULL_OK)); } CONTRACTL_END; ILCodeStream* pCurrentStream = m_pCodeStreamList; size_t cbCode = 0; INT iCurStack = 0; if (pDumpILStubCode == NULL) LogJitFlags(LF_STUBS, LL_INFO1000, dwJitFlags); while (pCurrentStream) { if (pCurrentStream->m_pqbILInstructions) { if (pDumpILStubCode) pDumpILStubCode->AppendPrintf("// %s {\n", pCurrentStream->GetStreamDescription(pCurrentStream->GetStreamType())); else LOG((LF_STUBS, LL_INFO1000, "%s {\n", pCurrentStream->GetStreamDescription(pCurrentStream->GetStreamType()))); ILInstruction* pInstrBuffer = (ILInstruction*)pCurrentStream->m_pqbILInstructions->Ptr(); LogILStubWorker(pInstrBuffer, pCurrentStream->m_uCurInstrIdx, &cbCode, &iCurStack, pDumpILStubCode); if (pDumpILStubCode) pDumpILStubCode->AppendPrintf("// } %s \n", pCurrentStream->GetStreamDescription(pCurrentStream->GetStreamType())); else LOG((LF_STUBS, LL_INFO1000, "}\n")); } pCurrentStream = pCurrentStream->m_pNextStream; } } bool ILStubLinker::FirstPassLink(ILInstruction* pInstrBuffer, UINT numInstr, size_t* pcbCode, INT* piCurStack, UINT* puMaxStack) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(puMaxStack)); } CONTRACTL_END; bool fStackUnderflow = false; for (UINT i = 0; i < numInstr; i++) { ILCodeStream::ILInstrEnum instr = (ILCodeStream::ILInstrEnum)pInstrBuffer[i].uInstruction; CONSISTENCY_CHECK(ILCodeStream::IsSupportedInstruction(instr)); // // down-size instructions // instr = ILCodeStream::LowerOpcode(instr, &pInstrBuffer[i]); // // fill in code label offsets // if (instr == ILCodeStream::CEE_CODE_LABEL) { ILCodeLabel* pLabel = (ILCodeLabel*)(pInstrBuffer[i].uArg); pLabel->SetCodeOffset(*pcbCode); } // // calculate the code size // PREFIX_ASSUME((size_t)instr < sizeof(s_rgbOpcodeSizes)); *pcbCode += s_rgbOpcodeSizes[instr]; // // calculate maxstack // *piCurStack += pInstrBuffer[i].iStackDelta; if (*piCurStack > (INT)*puMaxStack) { *puMaxStack = *piCurStack; } #ifdef _DEBUG if (*piCurStack < 0) { fStackUnderflow = true; } #endif // _DEBUG } return fStackUnderflow; } void ILStubLinker::SecondPassLink(ILInstruction* pInstrBuffer, UINT numInstr, size_t* pCurCodeOffset) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pCurCodeOffset)); } CONTRACTL_END; for (UINT i = 0; i < numInstr; i++) { ILCodeStream::ILInstrEnum instr = (ILCodeStream::ILInstrEnum)pInstrBuffer[i].uInstruction; CONSISTENCY_CHECK(ILCodeStream::IsSupportedInstruction(instr)); *pCurCodeOffset += s_rgbOpcodeSizes[instr]; if (ILCodeStream::IsBranchInstruction(instr)) { ILCodeLabel* pLabel = (ILCodeLabel*) pInstrBuffer[i].uArg; CONSISTENCY_CHECK(this == pLabel->m_pOwningStubLinker); CONSISTENCY_CHECK(IsInCodeStreamList(pLabel->m_pCodeStreamOfLabel)); pInstrBuffer[i].uArg = pLabel->GetCodeOffset() - *pCurCodeOffset; } } } size_t ILStubLinker::Link(UINT* puMaxStack) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(puMaxStack)); } CONTRACTL_END; // // Pass1: calculate code size, lower instructions to smallest form, // fill in branch target offsets, and calculate maxstack // ILCodeStream* pCurrentStream = m_pCodeStreamList; size_t cbCode = 0; INT iCurStack = 0; UINT uMaxStack = 0; DEBUG_STMT(bool fStackUnderflow = false); while (pCurrentStream) { if (pCurrentStream->m_pqbILInstructions) { ILInstruction* pInstrBuffer = (ILInstruction*)pCurrentStream->m_pqbILInstructions->Ptr(); INDEBUG( fStackUnderflow = ) FirstPassLink(pInstrBuffer, pCurrentStream->m_uCurInstrIdx, &cbCode, &iCurStack, &uMaxStack); } pCurrentStream = pCurrentStream->m_pNextStream; } // // Pass2: go back and patch the branch instructions // pCurrentStream = m_pCodeStreamList; size_t curCodeOffset = 0; while (pCurrentStream) { if (pCurrentStream->m_pqbILInstructions) { ILInstruction* pInstrBuffer = (ILInstruction*)pCurrentStream->m_pqbILInstructions->Ptr(); SecondPassLink(pInstrBuffer, pCurrentStream->m_uCurInstrIdx, &curCodeOffset); } pCurrentStream = pCurrentStream->m_pNextStream; } #ifdef _DEBUG if (fStackUnderflow) { LogILStub(NULL); CONSISTENCY_CHECK_MSG(false, "IL stack underflow! -- see logging output"); } #endif // _DEBUG *puMaxStack = uMaxStack; return cbCode; } #ifdef _DEBUG static const PCSTR s_rgOpNames[] = { #define OPDEF(name,string,pop,push,oprType,opcType,l,s1,s2,ctrl) \ #name, #include "opcode.def" #undef OPDEF }; #endif // _DEBUG BYTE* ILStubLinker::GenerateCodeWorker(BYTE* pbBuffer, ILInstruction* pInstrBuffer, UINT numInstr, size_t* pcbCode) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pcbCode)); } CONTRACTL_END; for (UINT i = 0; i < numInstr; i++) { ILCodeStream::ILInstrEnum instr = (ILCodeStream::ILInstrEnum)pInstrBuffer[i].uInstruction; CONSISTENCY_CHECK(ILCodeStream::IsSupportedInstruction(instr)); // // copy the IL instructions from the various linkers into the given buffer // if (instr != ILCodeStream::CEE_CODE_LABEL) { const ILOpcode* pOpcode = &s_rgOpcodes[instr]; PREFIX_ASSUME((size_t)instr < sizeof(s_rgbOpcodeSizes)); int opSize = s_rgbOpcodeSizes[instr]; bool twoByteOp = (pOpcode->byte1 != 0xFF); int argSize = opSize - (twoByteOp ? 2 : 1); if (twoByteOp) { *pbBuffer++ = pOpcode->byte1; } *pbBuffer++ = pOpcode->byte2; switch (argSize) { case 0: break; case 1: *pbBuffer = (BYTE)pInstrBuffer[i].uArg; break; case 2: SET_UNALIGNED_VAL16(pbBuffer, pInstrBuffer[i].uArg); break; case 4: SET_UNALIGNED_VAL32(pbBuffer, pInstrBuffer[i].uArg); break; case 8: { UINT64 uVal = pInstrBuffer[i].uArg; #ifndef _WIN64 // We don't have room on 32-bit platforms to store the CLR_NAN_64 value, so // we use a special value to represent CLR_NAN_64 and then recreate it here. if ((instr == ILCodeStream::CEE_LDC_R8) && (((UINT32)uVal) == ILCodeStream::SPECIAL_VALUE_NAN_64_ON_32)) uVal = CLR_NAN_64; #endif // _WIN64 SET_UNALIGNED_VAL64(pbBuffer, uVal); } break; default: UNREACHABLE_MSG("unexpected il opcode argument size"); } pbBuffer += argSize; *pcbCode += opSize; } } return pbBuffer; } void ILStubLinker::GenerateCode(BYTE* pbBuffer, size_t cbBufferSize) { STANDARD_VM_CONTRACT; ILCodeStream* pCurrentStream = m_pCodeStreamList; size_t cbCode = 0; while (pCurrentStream) { if (pCurrentStream->m_pqbILInstructions) { ILInstruction* pInstrBuffer = (ILInstruction*)pCurrentStream->m_pqbILInstructions->Ptr(); pbBuffer = GenerateCodeWorker(pbBuffer, pInstrBuffer, pCurrentStream->m_uCurInstrIdx, &cbCode); } pCurrentStream = pCurrentStream->m_pNextStream; } CONSISTENCY_CHECK(cbCode <= cbBufferSize); } #ifdef _DEBUG bool ILStubLinker::IsInCodeStreamList(ILCodeStream* pcs) { LIMITED_METHOD_CONTRACT; ILCodeStream* pCurrentStream = m_pCodeStreamList; while (pCurrentStream) { if (pcs == pCurrentStream) { return true; } pCurrentStream = pCurrentStream->m_pNextStream; } return false; } // static bool ILCodeStream::IsSupportedInstruction(ILInstrEnum instr) { LIMITED_METHOD_CONTRACT; CONSISTENCY_CHECK_MSG(instr != CEE_SWITCH, "CEE_SWITCH is not supported currently due to InlineSwitch in s_rgbOpcodeSizes"); CONSISTENCY_CHECK_MSG(((instr >= CEE_BR_S) && (instr <= CEE_BLT_UN_S)) || (CEE_LEAVE), "we only use long-form branch opcodes"); return true; } #endif // _DEBUG LPCSTR ILCodeStream::GetStreamDescription(ILStubLinker::CodeStreamType streamType) { LIMITED_METHOD_CONTRACT; static LPCSTR lpszDescriptions[] = { "Initialize", "Marshal", "CallMethod", "UnmarshalReturn", "Unmarshal", "ExceptionCleanup", "Cleanup", "ExceptionHandler", }; #ifdef _DEBUG size_t len = sizeof(lpszDescriptions)/sizeof(LPCSTR); _ASSERT(streamType >= 0 && (size_t)streamType < len); #endif // _DEBUG return lpszDescriptions[streamType]; } void ILCodeStream::EmitADD() { WRAPPER_NO_CONTRACT; Emit(CEE_ADD, -1, 0); } void ILCodeStream::EmitADD_OVF() { WRAPPER_NO_CONTRACT; Emit(CEE_ADD_OVF, -1, 0); } void ILCodeStream::EmitAND() { WRAPPER_NO_CONTRACT; Emit(CEE_AND, -1, 0); } void ILCodeStream::EmitARGLIST() { WRAPPER_NO_CONTRACT; Emit(CEE_ARGLIST, 1, 0); } void ILCodeStream::EmitBEQ(ILCodeLabel* pCodeLabel) { WRAPPER_NO_CONTRACT; Emit(CEE_BEQ, -2, (UINT_PTR)pCodeLabel); } void ILCodeStream::EmitBGE(ILCodeLabel* pCodeLabel) { WRAPPER_NO_CONTRACT; Emit(CEE_BGE, -2, (UINT_PTR)pCodeLabel); } void ILCodeStream::EmitBGE_UN(ILCodeLabel* pCodeLabel) { WRAPPER_NO_CONTRACT; Emit(CEE_BGE_UN, -2, (UINT_PTR)pCodeLabel); } void ILCodeStream::EmitBGT(ILCodeLabel* pCodeLabel) { WRAPPER_NO_CONTRACT; Emit(CEE_BGT, -2, (UINT_PTR)pCodeLabel); } void ILCodeStream::EmitBLE(ILCodeLabel* pCodeLabel) { WRAPPER_NO_CONTRACT; Emit(CEE_BLE, -2, (UINT_PTR)pCodeLabel); } void ILCodeStream::EmitBLE_UN(ILCodeLabel* pCodeLabel) { WRAPPER_NO_CONTRACT; Emit(CEE_BLE_UN, -2, (UINT_PTR)pCodeLabel); } void ILCodeStream::EmitBLT(ILCodeLabel* pCodeLabel) { WRAPPER_NO_CONTRACT; Emit(CEE_BLT, -2, (UINT_PTR)pCodeLabel); } void ILCodeStream::EmitBR(ILCodeLabel* pCodeLabel) { WRAPPER_NO_CONTRACT; Emit(CEE_BR, 0, (UINT_PTR)pCodeLabel); } void ILCodeStream::EmitBREAK() { WRAPPER_NO_CONTRACT; Emit(CEE_BREAK, 0, 0); } void ILCodeStream::EmitBRFALSE(ILCodeLabel* pCodeLabel) { WRAPPER_NO_CONTRACT; Emit(CEE_BRFALSE, -1, (UINT_PTR)pCodeLabel); } void ILCodeStream::EmitBRTRUE(ILCodeLabel* pCodeLabel) { WRAPPER_NO_CONTRACT; Emit(CEE_BRTRUE, -1, (UINT_PTR)pCodeLabel); } void ILCodeStream::EmitCALL(int token, int numInArgs, int numRetArgs) { WRAPPER_NO_CONTRACT; Emit(CEE_CALL, (INT16)(numRetArgs - numInArgs), token); } void ILCodeStream::EmitCALLI(int token, int numInArgs, int numRetArgs) { WRAPPER_NO_CONTRACT; Emit(CEE_CALLI, (INT16)(numRetArgs - numInArgs - 1), token); } void ILCodeStream::EmitCEQ () { WRAPPER_NO_CONTRACT; Emit(CEE_CEQ, -1, 0); } void ILCodeStream::EmitCGT() { WRAPPER_NO_CONTRACT; Emit(CEE_CGT, -1, 0); } void ILCodeStream::EmitCGT_UN() { WRAPPER_NO_CONTRACT; Emit(CEE_CGT_UN, -1, 0); } void ILCodeStream::EmitCLT() { WRAPPER_NO_CONTRACT; Emit(CEE_CLT, -1, 0); } void ILCodeStream::EmitCLT_UN() { WRAPPER_NO_CONTRACT; Emit(CEE_CLT_UN, -1, 0); } void ILCodeStream::EmitCONV_I() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_I, 0, 0); } void ILCodeStream::EmitCONV_I1() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_I1, 0, 0); } void ILCodeStream::EmitCONV_I2() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_I2, 0, 0); } void ILCodeStream::EmitCONV_I4() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_I4, 0, 0); } void ILCodeStream::EmitCONV_I8() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_I8, 0, 0); } void ILCodeStream::EmitCONV_U() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_U, 0, 0); } void ILCodeStream::EmitCONV_U1() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_U1, 0, 0); } void ILCodeStream::EmitCONV_U2() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_U2, 0, 0); } void ILCodeStream::EmitCONV_U4() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_U4, 0, 0); } void ILCodeStream::EmitCONV_U8() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_U8, 0, 0); } void ILCodeStream::EmitCONV_R4() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_R4, 0, 0); } void ILCodeStream::EmitCONV_R8() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_R8, 0, 0); } void ILCodeStream::EmitCONV_OVF_I4() { WRAPPER_NO_CONTRACT; Emit(CEE_CONV_OVF_I4, 0, 0); } void ILCodeStream::EmitCONV_T(CorElementType t) { STANDARD_VM_CONTRACT; switch (t) { case ELEMENT_TYPE_U1: EmitCONV_U1(); break; case ELEMENT_TYPE_I1: EmitCONV_I1(); break; case ELEMENT_TYPE_U2: EmitCONV_U2(); break; case ELEMENT_TYPE_I2: EmitCONV_I2(); break; case ELEMENT_TYPE_U4: EmitCONV_U4(); break; case ELEMENT_TYPE_I4: EmitCONV_I4(); break; case ELEMENT_TYPE_U8: EmitCONV_U8(); break; case ELEMENT_TYPE_I8: EmitCONV_I8(); break; case ELEMENT_TYPE_R4: EmitCONV_R4(); break; case ELEMENT_TYPE_R8: EmitCONV_R8(); break; case ELEMENT_TYPE_I: EmitCONV_I(); break; case ELEMENT_TYPE_U: EmitCONV_U(); break; default: _ASSERTE(!"Invalid type for conversion"); break; } } void ILCodeStream::EmitCPBLK() { WRAPPER_NO_CONTRACT; Emit(CEE_CPBLK, -3, 0); } void ILCodeStream::EmitCPOBJ(int token) { WRAPPER_NO_CONTRACT; Emit(CEE_CPOBJ, -2, token); } void ILCodeStream::EmitDUP () { WRAPPER_NO_CONTRACT; Emit(CEE_DUP, 1, 0); } void ILCodeStream::EmitENDFINALLY() { WRAPPER_NO_CONTRACT; Emit(CEE_ENDFINALLY, 0, 0); } void ILCodeStream::EmitINITBLK() { WRAPPER_NO_CONTRACT; Emit(CEE_INITBLK, -3, 0); } void ILCodeStream::EmitINITOBJ(int token) { WRAPPER_NO_CONTRACT; Emit(CEE_INITOBJ, -1, token); } void ILCodeStream::EmitJMP(int token) { WRAPPER_NO_CONTRACT; Emit(CEE_JMP, 0, token); } void ILCodeStream::EmitLDARG (unsigned uArgIdx) { WRAPPER_NO_CONTRACT; if (m_pOwner->m_fHasThis) { uArgIdx++; } Emit(CEE_LDARG, 1, uArgIdx); } void ILCodeStream::EmitLDARGA (unsigned uArgIdx) { WRAPPER_NO_CONTRACT; if (m_pOwner->m_fHasThis) { uArgIdx++; } Emit(CEE_LDARGA, 1, uArgIdx); } void ILCodeStream::EmitLDC(DWORD_PTR uConst) { WRAPPER_NO_CONTRACT; Emit( #ifdef _WIN64 CEE_LDC_I8 #else CEE_LDC_I4 #endif , 1, uConst); } void ILCodeStream::EmitLDC_R4(UINT32 uConst) { WRAPPER_NO_CONTRACT; Emit(CEE_LDC_R4, 1, uConst); } void ILCodeStream::EmitLDC_R8(UINT64 uConst) { STANDARD_VM_CONTRACT; #ifndef _WIN64 // We don't have room on 32-bit platforms to stor the CLR_NAN_64 value, so // we use a special value to represent CLR_NAN_64 and then recreate it later. CONSISTENCY_CHECK(((UINT32)uConst) != SPECIAL_VALUE_NAN_64_ON_32); if (uConst == CLR_NAN_64) uConst = SPECIAL_VALUE_NAN_64_ON_32; else CONSISTENCY_CHECK(FitsInU4(uConst)); #endif // _WIN64 Emit(CEE_LDC_R8, 1, (UINT_PTR)uConst); } void ILCodeStream::EmitLDELEM_REF() { WRAPPER_NO_CONTRACT; Emit(CEE_LDELEM_REF, -1, 0); } void ILCodeStream::EmitLDFLD(int token) { WRAPPER_NO_CONTRACT; Emit(CEE_LDFLD, 0, token); } void ILCodeStream::EmitLDFLDA(int token) { WRAPPER_NO_CONTRACT; Emit(CEE_LDFLDA, 0, token); } void ILCodeStream::EmitLDFTN(int token) { WRAPPER_NO_CONTRACT; Emit(CEE_LDFTN, 1, token); } void ILCodeStream::EmitLDIND_I() { WRAPPER_NO_CONTRACT; Emit(CEE_LDIND_I, 0, 0); } void ILCodeStream::EmitLDIND_I1() { WRAPPER_NO_CONTRACT; Emit(CEE_LDIND_I1, 0, 0); } void ILCodeStream::EmitLDIND_I2() { WRAPPER_NO_CONTRACT; Emit(CEE_LDIND_I2, 0, 0); } void ILCodeStream::EmitLDIND_I4() { WRAPPER_NO_CONTRACT; Emit(CEE_LDIND_I4, 0, 0); } void ILCodeStream::EmitLDIND_I8() { WRAPPER_NO_CONTRACT; Emit(CEE_LDIND_I8, 0, 0); } void ILCodeStream::EmitLDIND_R4() { WRAPPER_NO_CONTRACT; Emit(CEE_LDIND_R4, 0, 0); } void ILCodeStream::EmitLDIND_R8() { WRAPPER_NO_CONTRACT; Emit(CEE_LDIND_R8, 0, 0); } void ILCodeStream::EmitLDIND_REF() { WRAPPER_NO_CONTRACT; Emit(CEE_LDIND_REF, 0, 0); } void ILCodeStream::EmitLDIND_T(LocalDesc* pType) { CONTRACTL { PRECONDITION(pType->cbType == 1); } CONTRACTL_END; switch (pType->ElementType[0]) { case ELEMENT_TYPE_I1: EmitLDIND_I1(); break; case ELEMENT_TYPE_BOOLEAN: // fall through case ELEMENT_TYPE_U1: EmitLDIND_U1(); break; case ELEMENT_TYPE_I2: EmitLDIND_I2(); break; case ELEMENT_TYPE_CHAR: // fall through case ELEMENT_TYPE_U2: EmitLDIND_U2(); break; case ELEMENT_TYPE_I4: EmitLDIND_I4(); break; case ELEMENT_TYPE_U4: EmitLDIND_U4(); break; case ELEMENT_TYPE_I8: EmitLDIND_I8(); break; case ELEMENT_TYPE_U8: EmitLDIND_I8(); break; case ELEMENT_TYPE_R4: EmitLDIND_R4(); break; case ELEMENT_TYPE_R8: EmitLDIND_R8(); break; case ELEMENT_TYPE_FNPTR: // same as ELEMENT_TYPE_I case ELEMENT_TYPE_I: EmitLDIND_I(); break; case ELEMENT_TYPE_U: EmitLDIND_I(); break; case ELEMENT_TYPE_STRING: // fall through case ELEMENT_TYPE_CLASS: // fall through case ELEMENT_TYPE_ARRAY: case ELEMENT_TYPE_SZARRAY: case ELEMENT_TYPE_OBJECT: EmitLDIND_REF(); break; case ELEMENT_TYPE_INTERNAL: { CONSISTENCY_CHECK_MSG(!(pType->InternalToken.GetMethodTable()->IsValueType()), "don't know how to handle value types here"); EmitLDIND_REF(); break; } default: UNREACHABLE_MSG("unexpected type passed to EmitLDIND_T"); break; } } void ILCodeStream::EmitLDIND_U1() { WRAPPER_NO_CONTRACT; Emit(CEE_LDIND_U1, 0, 0); } void ILCodeStream::EmitLDIND_U2() { WRAPPER_NO_CONTRACT; Emit(CEE_LDIND_U2, 0, 0); } void ILCodeStream::EmitLDIND_U4() { WRAPPER_NO_CONTRACT; Emit(CEE_LDIND_U4, 0, 0); } void ILCodeStream::EmitLDLEN() { WRAPPER_NO_CONTRACT; Emit(CEE_LDLEN, 0, 0); } void ILCodeStream::EmitLDLOC (DWORD dwLocalNum) { STANDARD_VM_CONTRACT; CONSISTENCY_CHECK(dwLocalNum != (DWORD)-1); CONSISTENCY_CHECK(dwLocalNum != (WORD)-1); Emit(CEE_LDLOC, 1, dwLocalNum); } void ILCodeStream::EmitLDLOCA (DWORD dwLocalNum) { WRAPPER_NO_CONTRACT; Emit(CEE_LDLOCA, 1, dwLocalNum); } void ILCodeStream::EmitLDNULL() { WRAPPER_NO_CONTRACT; Emit(CEE_LDNULL, 1, 0); } void ILCodeStream::EmitLDOBJ (int token) { WRAPPER_NO_CONTRACT; Emit(CEE_LDOBJ, 0, token); } void ILCodeStream::EmitLDSFLD(int token) { WRAPPER_NO_CONTRACT; Emit(CEE_LDSFLD, 1, token); } void ILCodeStream::EmitLDSFLDA(int token) { WRAPPER_NO_CONTRACT; Emit(CEE_LDSFLDA, 1, token); } void ILCodeStream::EmitLDTOKEN(int token) { WRAPPER_NO_CONTRACT; Emit(CEE_LDTOKEN, 1, token); } void ILCodeStream::EmitLEAVE(ILCodeLabel* pCodeLabel) { WRAPPER_NO_CONTRACT; Emit(CEE_LEAVE, 0, (UINT_PTR)pCodeLabel); } void ILCodeStream::EmitLOCALLOC() { WRAPPER_NO_CONTRACT; Emit(CEE_LOCALLOC, 0, 0); } void ILCodeStream::EmitMUL() { WRAPPER_NO_CONTRACT; Emit(CEE_MUL, -1, 0); } void ILCodeStream::EmitMUL_OVF() { WRAPPER_NO_CONTRACT; Emit(CEE_MUL_OVF, -1, 0); } void ILCodeStream::EmitNEWOBJ(int token, int numInArgs) { WRAPPER_NO_CONTRACT; Emit(CEE_NEWOBJ, (INT16)(1 - numInArgs), token); } void ILCodeStream::EmitNOP(LPCSTR pszNopComment) { WRAPPER_NO_CONTRACT; Emit(CEE_NOP, 0, (UINT_PTR)pszNopComment); } void ILCodeStream::EmitPOP() { WRAPPER_NO_CONTRACT; Emit(CEE_POP, -1, 0); } void ILCodeStream::EmitRET() { WRAPPER_NO_CONTRACT; INT16 iStackDelta = m_pOwner->m_StubHasVoidReturnType ? 0 : -1; Emit(CEE_RET, iStackDelta, 0); } void ILCodeStream::EmitSHR_UN() { WRAPPER_NO_CONTRACT; Emit(CEE_SHR_UN, -1, 0); } void ILCodeStream::EmitSTARG(unsigned uArgIdx) { WRAPPER_NO_CONTRACT; Emit(CEE_STARG, -1, uArgIdx); } void ILCodeStream::EmitSTELEM_REF() { WRAPPER_NO_CONTRACT; Emit(CEE_STELEM_REF, -3, 0); } void ILCodeStream::EmitSTIND_I() { WRAPPER_NO_CONTRACT; Emit(CEE_STIND_I, -2, 0); } void ILCodeStream::EmitSTIND_I1() { WRAPPER_NO_CONTRACT; Emit(CEE_STIND_I1, -2, 0); } void ILCodeStream::EmitSTIND_I2() { WRAPPER_NO_CONTRACT; Emit(CEE_STIND_I2, -2, 0); } void ILCodeStream::EmitSTIND_I4() { WRAPPER_NO_CONTRACT; Emit(CEE_STIND_I4, -2, 0); } void ILCodeStream::EmitSTIND_I8() { WRAPPER_NO_CONTRACT; Emit(CEE_STIND_I8, -2, 0); } void ILCodeStream::EmitSTIND_R4() { WRAPPER_NO_CONTRACT; Emit(CEE_STIND_R4, -2, 0); } void ILCodeStream::EmitSTIND_R8() { WRAPPER_NO_CONTRACT; Emit(CEE_STIND_R8, -2, 0); } void ILCodeStream::EmitSTIND_REF() { WRAPPER_NO_CONTRACT; Emit(CEE_STIND_REF, -2, 0); } void ILCodeStream::EmitSTIND_T(LocalDesc* pType) { CONTRACTL { PRECONDITION(pType->cbType == 1); } CONTRACTL_END; switch (pType->ElementType[0]) { case ELEMENT_TYPE_I1: EmitSTIND_I1(); break; case ELEMENT_TYPE_BOOLEAN: // fall through case ELEMENT_TYPE_U1: EmitSTIND_I1(); break; case ELEMENT_TYPE_I2: EmitSTIND_I2(); break; case ELEMENT_TYPE_CHAR: // fall through case ELEMENT_TYPE_U2: EmitSTIND_I2(); break; case ELEMENT_TYPE_I4: EmitSTIND_I4(); break; case ELEMENT_TYPE_U4: EmitSTIND_I4(); break; case ELEMENT_TYPE_I8: EmitSTIND_I8(); break; case ELEMENT_TYPE_U8: EmitSTIND_I8(); break; case ELEMENT_TYPE_R4: EmitSTIND_R4(); break; case ELEMENT_TYPE_R8: EmitSTIND_R8(); break; case ELEMENT_TYPE_FNPTR: // same as ELEMENT_TYPE_I case ELEMENT_TYPE_I: EmitSTIND_I(); break; case ELEMENT_TYPE_U: EmitSTIND_I(); break; case ELEMENT_TYPE_STRING: // fall through case ELEMENT_TYPE_CLASS: // fall through case ELEMENT_TYPE_ARRAY: case ELEMENT_TYPE_SZARRAY: case ELEMENT_TYPE_OBJECT: EmitSTIND_REF(); break; case ELEMENT_TYPE_INTERNAL: { CONSISTENCY_CHECK_MSG(!(pType->InternalToken.GetMethodTable()->IsValueType()), "don't know how to handle value types here"); EmitSTIND_REF(); break; } default: UNREACHABLE_MSG("unexpected type passed to EmitSTIND_T"); break; } } void ILCodeStream::EmitSTFLD(int token) { WRAPPER_NO_CONTRACT; Emit(CEE_STFLD, -2, token); } void ILCodeStream::EmitSTLOC(DWORD dwLocalNum) { WRAPPER_NO_CONTRACT; Emit(CEE_STLOC, -1, dwLocalNum); } void ILCodeStream::EmitSTOBJ(int token) { WRAPPER_NO_CONTRACT; Emit(CEE_STOBJ, -2, token); } void ILCodeStream::EmitSTSFLD(int token) { WRAPPER_NO_CONTRACT; Emit(CEE_STSFLD, -1, token); } void ILCodeStream::EmitSUB() { WRAPPER_NO_CONTRACT; Emit(CEE_SUB, -1, 0); } void ILCodeStream::EmitTHROW() { WRAPPER_NO_CONTRACT; Emit(CEE_THROW, -1, 0); } void ILCodeStream::EmitNEWOBJ(BinderMethodID id, int numInArgs) { STANDARD_VM_CONTRACT; EmitNEWOBJ(GetToken(MscorlibBinder::GetMethod(id)), numInArgs); } void ILCodeStream::EmitCALL(BinderMethodID id, int numInArgs, int numRetArgs) { STANDARD_VM_CONTRACT; EmitCALL(GetToken(MscorlibBinder::GetMethod(id)), numInArgs, numRetArgs); } void ILStubLinker::SetHasThis (bool fHasThis) { LIMITED_METHOD_CONTRACT; m_fHasThis = fHasThis; } void ILCodeStream::EmitLoadThis () { WRAPPER_NO_CONTRACT; _ASSERTE(m_pOwner->m_fHasThis); // OK, this is ugly, but we add 1 to all LDARGs when // m_fHasThis is true, so we compensate for that here // so that we don't have to have a special method to // load arguments. EmitLDARG((unsigned)-1); } void ILCodeStream::EmitLoadNullPtr() { WRAPPER_NO_CONTRACT; // This is the correct way to load unmanaged zero pointer. EmitLDC(0) alone works // fine in most cases but may lead to wrong code being generated on 64-bit if the // flow graph is complex. EmitLDC(0); EmitCONV_I(); } void ILCodeStream::EmitArgIteratorCreateAndLoad() { STANDARD_VM_CONTRACT; // // we insert the ArgIterator in the same spot that the VASigCookie will go for sanity // LocalDesc aiLoc(MscorlibBinder::GetClass(CLASS__ARG_ITERATOR)); int aiLocNum; aiLocNum = NewLocal(aiLoc); EmitLDLOCA(aiLocNum); EmitDUP(); EmitARGLIST(); EmitLoadNullPtr(); EmitCALL(METHOD__ARG_ITERATOR__CTOR2, 2, 0); aiLoc.ElementType[0] = ELEMENT_TYPE_BYREF; aiLoc.ElementType[1] = ELEMENT_TYPE_INTERNAL; aiLoc.cbType = 2; aiLoc.InternalToken = MscorlibBinder::GetClass(CLASS__ARG_ITERATOR); SetStubTargetArgType(&aiLoc, false); } DWORD ILStubLinker::NewLocal(CorElementType typ) { CONTRACTL { STANDARD_VM_CHECK; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; LocalDesc locDesc(typ); return NewLocal(locDesc); } StubSigBuilder::StubSigBuilder() : m_nItems(0), m_cbSig(0) { STANDARD_VM_CONTRACT; m_pbSigCursor = (BYTE*) m_qbSigBuffer.AllocThrows(INITIAL_BUFFER_SIZE); } void StubSigBuilder::EnsureEnoughQuickBytes(size_t cbToAppend) { STANDARD_VM_CONTRACT; SIZE_T cbBuffer = m_qbSigBuffer.Size(); if ((m_cbSig + cbToAppend) >= cbBuffer) { m_qbSigBuffer.ReSizeThrows(2 * cbBuffer); m_pbSigCursor = ((BYTE*)m_qbSigBuffer.Ptr()) + m_cbSig; } } DWORD StubSigBuilder::Append(LocalDesc* pLoc) { CONTRACTL { STANDARD_VM_CHECK; INJECT_FAULT(COMPlusThrowOM()); PRECONDITION(CheckPointer(pLoc)); } CONTRACTL_END; EnsureEnoughQuickBytes(pLoc->cbType + sizeof(TypeHandle)); memcpyNoGCRefs(m_pbSigCursor, pLoc->ElementType, pLoc->cbType); m_pbSigCursor += pLoc->cbType; m_cbSig += pLoc->cbType; size_t i = 0; while (i < pLoc->cbType) { CONSISTENCY_CHECK( ELEMENT_TYPE_CLASS != pLoc->ElementType[i] && ELEMENT_TYPE_VALUETYPE != pLoc->ElementType[i]); switch (pLoc->ElementType[i]) { case ELEMENT_TYPE_INTERNAL: SET_UNALIGNED_PTR(m_pbSigCursor, (UINT_PTR)pLoc->InternalToken.AsPtr()); m_pbSigCursor += sizeof(TypeHandle); m_cbSig += sizeof(TypeHandle); break; case ELEMENT_TYPE_FNPTR: { SigPointer ptr(pLoc->pSig); SigBuilder sigBuilder; ptr.ConvertToInternalSignature(pLoc->pSigModule, NULL, &sigBuilder); DWORD cbFnPtrSig; PVOID pFnPtrSig = sigBuilder.GetSignature(&cbFnPtrSig); EnsureEnoughQuickBytes(cbFnPtrSig); memcpyNoGCRefs(m_pbSigCursor, pFnPtrSig, cbFnPtrSig); m_pbSigCursor += cbFnPtrSig; m_cbSig += cbFnPtrSig; } break; default: break; } i++; } if (pLoc->ElementType[0] == ELEMENT_TYPE_ARRAY) { EnsureEnoughQuickBytes(pLoc->cbArrayBoundsInfo); memcpyNoGCRefs(m_pbSigCursor, pLoc->pSig, pLoc->cbArrayBoundsInfo); m_pbSigCursor += pLoc->cbArrayBoundsInfo; m_cbSig += pLoc->cbArrayBoundsInfo; } _ASSERTE(m_cbSig <= m_qbSigBuffer.Size()); // we corrupted our buffer resizing if this assert fires return m_nItems++; } //--------------------------------------------------------------------------------------- // DWORD LocalSigBuilder::GetSigSize() { STANDARD_VM_CONTRACT; BYTE temp[4]; UINT32 cbEncoded = CorSigCompressData(m_nItems, temp); S_UINT32 cbSigSize = S_UINT32(1) + // IMAGE_CEE_CS_CALLCONV_LOCAL_SIG S_UINT32(cbEncoded) + // encoded number of locals S_UINT32(m_cbSig) + // types S_UINT32(1); // ELEMENT_TYPE_END if (cbSigSize.IsOverflow()) { IfFailThrow(COR_E_OVERFLOW); } return cbSigSize.Value(); } //--------------------------------------------------------------------------------------- // DWORD LocalSigBuilder::GetSig( BYTE * pbLocalSig, DWORD cbBuffer) { STANDARD_VM_CONTRACT; BYTE temp[4]; size_t cb = CorSigCompressData(m_nItems, temp); _ASSERTE((1 + cb + m_cbSig + 1) == GetSigSize()); if ((1 + cb + m_cbSig + 1) <= cbBuffer) { pbLocalSig[0] = IMAGE_CEE_CS_CALLCONV_LOCAL_SIG; memcpyNoGCRefs(&pbLocalSig[1], temp, cb); memcpyNoGCRefs(&pbLocalSig[1 + cb], m_qbSigBuffer.Ptr(), m_cbSig); pbLocalSig[1 + cb + m_cbSig] = ELEMENT_TYPE_END; return (DWORD)(1 + cb + m_cbSig + 1); } else { return NULL; } } FunctionSigBuilder::FunctionSigBuilder() : m_callingConv(IMAGE_CEE_CS_CALLCONV_DEFAULT) { STANDARD_VM_CONTRACT; m_qbReturnSig.ReSizeThrows(1); *(CorElementType *)m_qbReturnSig.Ptr() = ELEMENT_TYPE_VOID; } void FunctionSigBuilder::SetReturnType(LocalDesc* pLoc) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(pLoc->cbType > 0); } CONTRACTL_END; m_qbReturnSig.ReSizeThrows(pLoc->cbType); memcpyNoGCRefs(m_qbReturnSig.Ptr(), pLoc->ElementType, pLoc->cbType); size_t i = 0; while (i < pLoc->cbType) { CONSISTENCY_CHECK( ELEMENT_TYPE_CLASS != pLoc->ElementType[i] && ELEMENT_TYPE_VALUETYPE != pLoc->ElementType[i]); switch (pLoc->ElementType[i]) { case ELEMENT_TYPE_INTERNAL: m_qbReturnSig.ReSizeThrows(m_qbReturnSig.Size() + sizeof(TypeHandle)); SET_UNALIGNED_PTR((BYTE *)m_qbReturnSig.Ptr() + m_qbReturnSig.Size() - + sizeof(TypeHandle), (UINT_PTR)pLoc->InternalToken.AsPtr()); break; case ELEMENT_TYPE_FNPTR: { SigPointer ptr(pLoc->pSig); SigBuilder sigBuilder; ptr.ConvertToInternalSignature(pLoc->pSigModule, NULL, &sigBuilder); DWORD cbFnPtrSig; PVOID pFnPtrSig = sigBuilder.GetSignature(&cbFnPtrSig); m_qbReturnSig.ReSizeThrows(m_qbReturnSig.Size() + cbFnPtrSig); memcpyNoGCRefs((BYTE *)m_qbReturnSig.Ptr() + m_qbReturnSig.Size() - cbFnPtrSig, pFnPtrSig, cbFnPtrSig); } break; default: break; } i++; } if (pLoc->ElementType[0] == ELEMENT_TYPE_ARRAY) { SIZE_T size = m_qbReturnSig.Size(); m_qbReturnSig.ReSizeThrows(size + pLoc->cbArrayBoundsInfo); memcpyNoGCRefs((BYTE *)m_qbReturnSig.Ptr() + size, pLoc->pSig, pLoc->cbArrayBoundsInfo); } } void FunctionSigBuilder::SetSig(PCCOR_SIGNATURE pSig, DWORD cSig) { STANDARD_VM_CONTRACT; // parse the incoming signature SigPointer sigPtr(pSig, cSig); // 1) calling convention ULONG callConv; IfFailThrow(sigPtr.GetCallingConvInfo(&callConv)); SetCallingConv((CorCallingConvention)callConv); // 2) number of parameters IfFailThrow(sigPtr.GetData(&m_nItems)); // 3) return type PCCOR_SIGNATURE ptr = sigPtr.GetPtr(); IfFailThrow(sigPtr.SkipExactlyOne()); size_t retSigLength = sigPtr.GetPtr() - ptr; m_qbReturnSig.ReSizeThrows(retSigLength); memcpyNoGCRefs(m_qbReturnSig.Ptr(), ptr, retSigLength); // 4) parameters m_cbSig = 0; size_t cbSigLen = (cSig - (sigPtr.GetPtr() - pSig)); m_pbSigCursor = (BYTE *)m_qbSigBuffer.Ptr(); EnsureEnoughQuickBytes(cbSigLen); memcpyNoGCRefs(m_pbSigCursor, sigPtr.GetPtr(), cbSigLen); m_cbSig = cbSigLen; m_pbSigCursor += cbSigLen; } //--------------------------------------------------------------------------------------- // DWORD FunctionSigBuilder::GetSigSize() { STANDARD_VM_CONTRACT; BYTE temp[4]; DWORD cbEncodedLen = CorSigCompressData(m_nItems, temp); SIZE_T cbEncodedRetType = m_qbReturnSig.Size(); CONSISTENCY_CHECK(cbEncodedRetType > 0); S_UINT32 cbSigSize = S_UINT32(1) + // calling convention S_UINT32(cbEncodedLen) + // encoded number of args S_UINT32(cbEncodedRetType) + // encoded return type S_UINT32(m_cbSig) + // types S_UINT32(1); // ELEMENT_TYPE_END if (cbSigSize.IsOverflow()) { IfFailThrow(COR_E_OVERFLOW); } return cbSigSize.Value(); } //--------------------------------------------------------------------------------------- // DWORD FunctionSigBuilder::GetSig( BYTE * pbLocalSig, DWORD cbBuffer) { STANDARD_VM_CONTRACT; BYTE tempLen[4]; size_t cbEncodedLen = CorSigCompressData(m_nItems, tempLen); size_t cbEncodedRetType = m_qbReturnSig.Size(); CONSISTENCY_CHECK(cbEncodedRetType > 0); _ASSERTE((1 + cbEncodedLen + cbEncodedRetType + m_cbSig + 1) == GetSigSize()); if ((1 + cbEncodedLen + cbEncodedRetType + m_cbSig + 1) <= cbBuffer) { BYTE* pbCursor = pbLocalSig; *pbCursor = static_cast<BYTE>(m_callingConv); pbCursor++; memcpyNoGCRefs(pbCursor, tempLen, cbEncodedLen); pbCursor += cbEncodedLen; memcpyNoGCRefs(pbCursor, m_qbReturnSig.Ptr(), m_qbReturnSig.Size()); pbCursor += m_qbReturnSig.Size(); memcpyNoGCRefs(pbCursor, m_qbSigBuffer.Ptr(), m_cbSig); pbCursor += m_cbSig; pbCursor[0] = ELEMENT_TYPE_END; return (DWORD)(1 + cbEncodedLen + cbEncodedRetType + m_cbSig + 1); } else { return NULL; } } DWORD ILStubLinker::NewLocal(LocalDesc loc) { WRAPPER_NO_CONTRACT; return m_localSigBuilder.NewLocal(&loc); } //--------------------------------------------------------------------------------------- // DWORD ILStubLinker::GetLocalSigSize() { LIMITED_METHOD_CONTRACT; return m_localSigBuilder.GetSigSize(); } //--------------------------------------------------------------------------------------- // DWORD ILStubLinker::GetLocalSig( BYTE * pbLocalSig, DWORD cbBuffer) { STANDARD_VM_CONTRACT; DWORD dwRet = m_localSigBuilder.GetSig(pbLocalSig, cbBuffer); return dwRet; } //--------------------------------------------------------------------------------------- // DWORD ILStubLinker::GetStubTargetMethodSigSize() { STANDARD_VM_CONTRACT; return m_nativeFnSigBuilder.GetSigSize(); } //--------------------------------------------------------------------------------------- // DWORD ILStubLinker::GetStubTargetMethodSig( BYTE * pbSig, DWORD cbSig) { LIMITED_METHOD_CONTRACT; DWORD dwRet = m_nativeFnSigBuilder.GetSig(pbSig, cbSig); return dwRet; } void ILStubLinker::SetStubTargetMethodSig(PCCOR_SIGNATURE pSig, DWORD cSig) { STANDARD_VM_CONTRACT; m_nativeFnSigBuilder.SetSig(pSig, cSig); } static BOOL SigHasVoidReturnType(const Signature &signature) { CONTRACTL { THROWS; GC_NOTRIGGER; } CONTRACTL_END SigPointer ptr = signature.CreateSigPointer(); ULONG data; IfFailThrow(ptr.GetCallingConvInfo(&data)); // Skip number of type arguments if (data & IMAGE_CEE_CS_CALLCONV_GENERIC) { IfFailThrow(ptr.GetData(NULL)); } // skip number of args IfFailThrow(ptr.GetData(NULL)); CorElementType retType; IfFailThrow(ptr.PeekElemType(&retType)); return (ELEMENT_TYPE_VOID == retType); } ILStubLinker::ILStubLinker(Module* pStubSigModule, const Signature &signature, SigTypeContext *pTypeContext, MethodDesc *pMD, BOOL fTargetHasThis, BOOL fStubHasThis, BOOL fIsNDirectStub) : m_pCodeStreamList(NULL), m_stubSig(signature), m_pTypeContext(pTypeContext), m_pCode(NULL), m_pStubSigModule(pStubSigModule), m_pLabelList(NULL), m_StubHasVoidReturnType(0), m_iTargetStackDelta(0), m_cbCurrentCompressedSigLen(1), m_nLocals(0), m_fHasThis(false), m_pMD(pMD) { CONTRACTL { THROWS; GC_TRIGGERS; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END m_managedSigPtr = signature.CreateSigPointer(); if (!signature.IsEmpty()) { m_StubHasVoidReturnType = SigHasVoidReturnType(signature); // // Get the stub's calling convention. Set m_fHasThis to match // IMAGE_CEE_CS_CALLCONV_HASTHIS. // ULONG uStubCallingConvInfo; IfFailThrow(m_managedSigPtr.GetCallingConvInfo(&uStubCallingConvInfo)); if (fStubHasThis) { m_fHasThis = true; } // // If target calling convention was specified, use it instead. // Otherwise, derive one based on the stub's signature. // ULONG uCallingConvInfo = uStubCallingConvInfo; ULONG uCallingConv = (uCallingConvInfo & IMAGE_CEE_CS_CALLCONV_MASK); ULONG uNativeCallingConv; if (IMAGE_CEE_CS_CALLCONV_VARARG == uCallingConv) { // // If we have a PInvoke stub that has a VARARG calling convention // we will transition to a NATIVEVARARG calling convention for the // target call. The JIT64 knows about this calling convention, // basically it is the same as the managed vararg calling convention // except without a VASigCookie. // // If our stub is not a PInvoke stub and has a vararg calling convention, // we are most likely going to have to forward those variable arguments // on to our call target. Unfortunately, callsites to varargs methods // in IL always have full signatures (that's where the VASigCookie comes // from). But we don't have that in this case, so we play some tricks and // pass an ArgIterator down to an assembly routine that pulls out the // variable arguments and puts them in the right spot before forwarding // to the stub target. // // The net result is that we don't want to set the native calling // convention to be vararg for non-PInvoke stubs, so we just use // the default callconv. // if (!fIsNDirectStub) uNativeCallingConv = IMAGE_CEE_CS_CALLCONV_DEFAULT; else uNativeCallingConv = IMAGE_CEE_CS_CALLCONV_NATIVEVARARG; } else { uNativeCallingConv = IMAGE_CEE_CS_CALLCONV_DEFAULT; } if (fTargetHasThis && !fIsNDirectStub) { // ndirect native sig never has a 'this' pointer uNativeCallingConv |= IMAGE_CEE_CS_CALLCONV_HASTHIS; } if (fTargetHasThis) { m_iTargetStackDelta--; } m_nativeFnSigBuilder.SetCallingConv((CorCallingConvention)uNativeCallingConv); if (uStubCallingConvInfo & IMAGE_CEE_CS_CALLCONV_GENERIC) IfFailThrow(m_managedSigPtr.GetData(NULL)); // skip number of type parameters IfFailThrow(m_managedSigPtr.GetData(NULL)); // skip number of parameters IfFailThrow(m_managedSigPtr.SkipExactlyOne()); // skip return type } } ILStubLinker::~ILStubLinker() { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; DeleteCodeLabels(); DeleteCodeStreams(); } void ILStubLinker::DeleteCodeLabels() { CONTRACTL { NOTHROW; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; // // walk the list of labels and free each one // ILCodeLabel* pCurrent = m_pLabelList; while (pCurrent) { ILCodeLabel* pDeleteMe = pCurrent; pCurrent = pCurrent->m_pNext; delete pDeleteMe; } m_pLabelList = NULL; } void ILStubLinker::DeleteCodeStreams() { CONTRACTL { NOTHROW; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; ILCodeStream* pCurrent = m_pCodeStreamList; while (pCurrent) { ILCodeStream* pDeleteMe = pCurrent; pCurrent = pCurrent->m_pNextStream; delete pDeleteMe; } m_pCodeStreamList = NULL; } void ILStubLinker::ClearCodeStreams() { CONTRACTL { NOTHROW; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; ILCodeStream* pCurrent = m_pCodeStreamList; while (pCurrent) { pCurrent->ClearCode(); pCurrent = pCurrent->m_pNextStream; } } void ILStubLinker::GetStubReturnType(LocalDesc* pLoc) { WRAPPER_NO_CONTRACT; GetStubReturnType(pLoc, m_pStubSigModule); } void ILStubLinker::GetStubReturnType(LocalDesc* pLoc, Module* pModule) { STANDARD_VM_CONTRACT; SigPointer ptr = m_stubSig.CreateSigPointer(); ULONG uCallingConv; int nTypeArgs = 0; int nArgs; IfFailThrow(ptr.GetCallingConvInfo(&uCallingConv)); if (uCallingConv & IMAGE_CEE_CS_CALLCONV_GENERIC) IfFailThrow(ptr.GetData((ULONG*)&nTypeArgs)); IfFailThrow(ptr.GetData((ULONG*)&nArgs)); GetManagedTypeHelper(pLoc, pModule, ptr.GetPtr(), m_pTypeContext, m_pMD); } CorCallingConvention ILStubLinker::GetStubTargetCallingConv() { LIMITED_METHOD_CONTRACT; return m_nativeFnSigBuilder.GetCallingConv(); } void ILStubLinker::TransformArgForJIT(LocalDesc *pLoc) { STANDARD_VM_CONTRACT; // Turn everything into blittable primitives. The reason this method is needed are // byrefs which are OK only when they ref stack data or are pinned. This condition // cannot be verified by code:NDirect.MarshalingRequired so we explicitly get rid // of them here. switch (pLoc->ElementType[0]) { // primitives case ELEMENT_TYPE_VOID: case ELEMENT_TYPE_BOOLEAN: case ELEMENT_TYPE_CHAR: case ELEMENT_TYPE_I1: case ELEMENT_TYPE_U1: case ELEMENT_TYPE_I2: case ELEMENT_TYPE_U2: case ELEMENT_TYPE_I4: case ELEMENT_TYPE_U4: case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R4: case ELEMENT_TYPE_R8: case ELEMENT_TYPE_I: case ELEMENT_TYPE_U: { // no transformation needed break; } case ELEMENT_TYPE_VALUETYPE: { _ASSERTE(!"Should have been replaced by a native value type!"); break; } case ELEMENT_TYPE_PTR: { #ifdef _TARGET_X86_ if (pLoc->bIsCopyConstructed) { // The only pointers that we don't transform to ELEMENT_TYPE_I are those that are // ET_TYPE_CMOD_REQD<IsCopyConstructed>/ET_TYPE_CMOD_REQD<NeedsCopyConstructorModifier> // in the original signature. This convention is understood by the UM thunk compiler // (code:UMThunkMarshInfo.CompileNExportThunk) which will generate different thunk code. // Such parameters come from unmanaged by value but must enter the IL stub by reference // because we are not supposed to make a copy. } else #endif // _TARGET_X86_ { pLoc->ElementType[0] = ELEMENT_TYPE_I; pLoc->cbType = 1; } break; } case ELEMENT_TYPE_INTERNAL: { // JIT will handle structures if (pLoc->InternalToken.IsValueType()) { _ASSERTE(pLoc->InternalToken.IsBlittable()); break; } // intentional fall-thru } // pointers, byrefs, strings, arrays, other ref types -> ELEMENT_TYPE_I default: { pLoc->ElementType[0] = ELEMENT_TYPE_I; pLoc->cbType = 1; break; } } } Module *ILStubLinker::GetStubSigModule() { LIMITED_METHOD_CONTRACT; return m_pStubSigModule; } SigTypeContext *ILStubLinker::GetStubSigTypeContext() { LIMITED_METHOD_CONTRACT; return m_pTypeContext; } void ILStubLinker::SetStubTargetReturnType(CorElementType typ) { WRAPPER_NO_CONTRACT; LocalDesc locDesc(typ); SetStubTargetReturnType(&locDesc); } void ILStubLinker::SetStubTargetReturnType(LocalDesc* pLoc) { CONTRACTL { WRAPPER(NOTHROW); WRAPPER(GC_NOTRIGGER); WRAPPER(MODE_ANY); PRECONDITION(CheckPointer(pLoc, NULL_NOT_OK)); } CONTRACTL_END; TransformArgForJIT(pLoc); m_nativeFnSigBuilder.SetReturnType(pLoc); if ((1 != pLoc->cbType) || (ELEMENT_TYPE_VOID != pLoc->ElementType[0])) { m_iTargetStackDelta++; } } DWORD ILStubLinker::SetStubTargetArgType(CorElementType typ, bool fConsumeStubArg /*= true*/) { STANDARD_VM_CONTRACT; LocalDesc locDesc(typ); return SetStubTargetArgType(&locDesc, fConsumeStubArg); } void ILStubLinker::SetStubTargetCallingConv(CorCallingConvention uNativeCallingConv) { LIMITED_METHOD_CONTRACT; m_nativeFnSigBuilder.SetCallingConv(uNativeCallingConv); } static size_t GetManagedTypeForMDArray(LocalDesc* pLoc, Module* pModule, PCCOR_SIGNATURE psigManagedArg, SigTypeContext *pTypeContext) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pLoc)); PRECONDITION(CheckPointer(pModule)); PRECONDITION(CheckPointer(psigManagedArg)); PRECONDITION(*psigManagedArg == ELEMENT_TYPE_ARRAY); } CONTRACTL_END; SigPointer ptr; size_t cbDest = 0; // // copy ELEMENT_TYPE_ARRAY // pLoc->ElementType[cbDest] = *psigManagedArg; psigManagedArg++; cbDest++; ptr.SetSig(psigManagedArg); IfFailThrow(ptr.SkipCustomModifiers()); psigManagedArg = ptr.GetPtr(); // // get array type // pLoc->InternalToken = ptr.GetTypeHandleThrowing(pModule, pTypeContext); pLoc->ElementType[cbDest] = ELEMENT_TYPE_INTERNAL; cbDest++; // // get array bounds // size_t cbType; PCCOR_SIGNATURE psigNextManagedArg; // find the start of the next argument ptr.SetSig(psigManagedArg - 1); // -1 to back up to E_T_ARRAY; IfFailThrow(ptr.SkipExactlyOne()); psigNextManagedArg = ptr.GetPtr(); // find the start of the array bounds information ptr.SetSig(psigManagedArg); IfFailThrow(ptr.SkipExactlyOne()); psigManagedArg = ptr.GetPtr(); // point to the array bounds info cbType = psigNextManagedArg - psigManagedArg; pLoc->pSig = psigManagedArg; // point to the array bounds info pLoc->cbArrayBoundsInfo = cbType; // size of array bounds info pLoc->cbType = cbDest; return cbDest; } // static void ILStubLinker::GetManagedTypeHelper(LocalDesc* pLoc, Module* pModule, PCCOR_SIGNATURE psigManagedArg, SigTypeContext *pTypeContext, MethodDesc *pMD) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pLoc)); PRECONDITION(CheckPointer(pModule)); PRECONDITION(CheckPointer(psigManagedArg)); } CONTRACTL_END; SigPointer ptr(psigManagedArg); CorElementType eType; LOG((LF_STUBS, LL_INFO10000, "GetManagedTypeHelper on type at %p\n", psigManagedArg)); IfFailThrow(ptr.PeekElemType(&eType)); size_t cbDest = 0; while (eType == ELEMENT_TYPE_PTR || eType == ELEMENT_TYPE_BYREF || eType == ELEMENT_TYPE_SZARRAY) { pLoc->ElementType[cbDest] = static_cast<BYTE>(eType); cbDest++; if (cbDest >= LocalDesc::MAX_LOCALDESC_ELEMENTS) { COMPlusThrow(kMarshalDirectiveException, IDS_EE_SIGTOOCOMPLEX); } IfFailThrow(ptr.GetElemType(NULL)); IfFailThrow(ptr.PeekElemType(&eType)); } SigPointer ptr2(ptr); IfFailThrow(ptr2.SkipCustomModifiers()); psigManagedArg = ptr2.GetPtr(); switch (eType) { case ELEMENT_TYPE_VAR: case ELEMENT_TYPE_MVAR: { IfFailThrow(ptr.GetElemType(NULL)); // skip ET ULONG varNum; IfFailThrowBF(ptr.GetData(&varNum), BFA_BAD_COMPLUS_SIG, pModule); DWORD varCount = (eType == ELEMENT_TYPE_VAR ? pTypeContext->m_classInst.GetNumArgs() : pTypeContext->m_methodInst.GetNumArgs()); THROW_BAD_FORMAT_MAYBE(varNum < varCount, BFA_BAD_COMPLUS_SIG, pModule); pLoc->InternalToken = (eType == ELEMENT_TYPE_VAR ? pTypeContext->m_classInst[varNum] : pTypeContext->m_methodInst[varNum]); pLoc->ElementType[cbDest] = ELEMENT_TYPE_INTERNAL; cbDest++; break; } case ELEMENT_TYPE_CLASS: case ELEMENT_TYPE_VALUETYPE: case ELEMENT_TYPE_INTERNAL: { pLoc->InternalToken = ptr.GetTypeHandleThrowing(pModule, pTypeContext); pLoc->ElementType[cbDest] = ELEMENT_TYPE_INTERNAL; cbDest++; break; } case ELEMENT_TYPE_GENERICINST: { pLoc->InternalToken = ptr.GetTypeHandleThrowing(pModule, pTypeContext); pLoc->ElementType[cbDest] = ELEMENT_TYPE_INTERNAL; cbDest++; break; } case ELEMENT_TYPE_FNPTR: // save off a pointer to the managed sig // we'll convert it in bulk when we store it // in the generated sig pLoc->pSigModule = pModule; pLoc->pSig = psigManagedArg+1; pLoc->ElementType[cbDest] = ELEMENT_TYPE_FNPTR; cbDest++; break; case ELEMENT_TYPE_ARRAY: cbDest = GetManagedTypeForMDArray(pLoc, pModule, psigManagedArg, pTypeContext); break; default: { size_t cbType; PCCOR_SIGNATURE psigNextManagedArg; IfFailThrow(ptr.SkipExactlyOne()); psigNextManagedArg = ptr.GetPtr(); cbType = psigNextManagedArg - psigManagedArg; size_t cbNewDest; if (!ClrSafeInt<size_t>::addition(cbDest, cbType, cbNewDest) || cbNewDest > LocalDesc::MAX_LOCALDESC_ELEMENTS) { COMPlusThrow(kMarshalDirectiveException, IDS_EE_SIGTOOCOMPLEX); } memcpyNoGCRefs(&pLoc->ElementType[cbDest], psigManagedArg, cbType); cbDest = cbNewDest; break; } } if (cbDest > LocalDesc::MAX_LOCALDESC_ELEMENTS) { COMPlusThrow(kMarshalDirectiveException, IDS_EE_SIGTOOCOMPLEX); } pLoc->cbType = cbDest; } void ILStubLinker::GetStubTargetReturnType(LocalDesc* pLoc) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pLoc)); } CONTRACTL_END; GetStubTargetReturnType(pLoc, m_pStubSigModule); } void ILStubLinker::GetStubTargetReturnType(LocalDesc* pLoc, Module* pModule) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pLoc)); PRECONDITION(CheckPointer(pModule)); } CONTRACTL_END; GetManagedTypeHelper(pLoc, pModule, m_nativeFnSigBuilder.GetReturnSig(), m_pTypeContext, NULL); } void ILStubLinker::GetStubArgType(LocalDesc* pLoc) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pLoc)); } CONTRACTL_END; GetStubArgType(pLoc, m_pStubSigModule); } void ILStubLinker::GetStubArgType(LocalDesc* pLoc, Module* pModule) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pLoc)); PRECONDITION(CheckPointer(pModule)); } CONTRACTL_END; GetManagedTypeHelper(pLoc, pModule, m_managedSigPtr.GetPtr(), m_pTypeContext, m_pMD); } //--------------------------------------------------------------------------------------- // DWORD ILStubLinker::SetStubTargetArgType( LocalDesc * pLoc, // = NULL bool fConsumeStubArg) // = true { STANDARD_VM_CONTRACT; LocalDesc locDesc; if (fConsumeStubArg) { _ASSERTE(m_pStubSigModule); if (pLoc == NULL) { pLoc = &locDesc; GetStubArgType(pLoc, m_pStubSigModule); } IfFailThrow(m_managedSigPtr.SkipExactlyOne()); } TransformArgForJIT(pLoc); DWORD dwArgNum = m_nativeFnSigBuilder.NewArg(pLoc); m_iTargetStackDelta--; return dwArgNum; } // ILStubLinker::SetStubTargetArgType //--------------------------------------------------------------------------------------- // int ILStubLinker::GetToken(MethodDesc* pMD) { STANDARD_VM_CONTRACT; return m_tokenMap.GetToken(pMD); } int ILStubLinker::GetToken(MethodTable* pMT) { STANDARD_VM_CONTRACT; return m_tokenMap.GetToken(TypeHandle(pMT)); } int ILStubLinker::GetToken(TypeHandle th) { STANDARD_VM_CONTRACT; return m_tokenMap.GetToken(th); } int ILStubLinker::GetToken(FieldDesc* pFD) { STANDARD_VM_CONTRACT; return m_tokenMap.GetToken(pFD); } BOOL ILStubLinker::StubHasVoidReturnType() { LIMITED_METHOD_CONTRACT; return m_StubHasVoidReturnType; } void ILStubLinker::ClearCode() { CONTRACTL { NOTHROW; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; DeleteCodeLabels(); ClearCodeStreams(); } // static ILCodeStream* ILStubLinker::FindLastCodeStream(ILCodeStream* pList) { LIMITED_METHOD_CONTRACT; if (NULL == pList) { return NULL; } while (NULL != pList->m_pNextStream) { pList = pList->m_pNextStream; } return pList; } ILCodeStream* ILStubLinker::NewCodeStream(CodeStreamType codeStreamType) { STANDARD_VM_CONTRACT; NewHolder<ILCodeStream> pNewCodeStream = new ILCodeStream(this, codeStreamType); if (NULL == m_pCodeStreamList) { m_pCodeStreamList = pNewCodeStream; } else { ILCodeStream* pTail = FindLastCodeStream(m_pCodeStreamList); CONSISTENCY_CHECK(NULL == pTail->m_pNextStream); pTail->m_pNextStream = pNewCodeStream; } pNewCodeStream.SuppressRelease(); return pNewCodeStream; } int ILCodeStream::GetToken(MethodDesc* pMD) { STANDARD_VM_CONTRACT; return m_pOwner->GetToken(pMD); } int ILCodeStream::GetToken(MethodTable* pMT) { STANDARD_VM_CONTRACT; return m_pOwner->GetToken(pMT); } int ILCodeStream::GetToken(TypeHandle th) { STANDARD_VM_CONTRACT; return m_pOwner->GetToken(th); } int ILCodeStream::GetToken(FieldDesc* pFD) { STANDARD_VM_CONTRACT; return m_pOwner->GetToken(pFD); } DWORD ILCodeStream::NewLocal(CorElementType typ) { STANDARD_VM_CONTRACT; return m_pOwner->NewLocal(typ); } DWORD ILCodeStream::NewLocal(LocalDesc loc) { WRAPPER_NO_CONTRACT; return m_pOwner->NewLocal(loc); } DWORD ILCodeStream::SetStubTargetArgType(CorElementType typ, bool fConsumeStubArg) { STANDARD_VM_CONTRACT; return m_pOwner->SetStubTargetArgType(typ, fConsumeStubArg); } DWORD ILCodeStream::SetStubTargetArgType(LocalDesc* pLoc, bool fConsumeStubArg) { STANDARD_VM_CONTRACT; return m_pOwner->SetStubTargetArgType(pLoc, fConsumeStubArg); } void ILCodeStream::SetStubTargetReturnType(CorElementType typ) { STANDARD_VM_CONTRACT; m_pOwner->SetStubTargetReturnType(typ); } void ILCodeStream::SetStubTargetReturnType(LocalDesc* pLoc) { STANDARD_VM_CONTRACT; m_pOwner->SetStubTargetReturnType(pLoc); } ILCodeLabel* ILCodeStream::NewCodeLabel() { STANDARD_VM_CONTRACT; return m_pOwner->NewCodeLabel(); } void ILCodeStream::ClearCode() { LIMITED_METHOD_CONTRACT; m_uCurInstrIdx = 0; }
; A002446: a(n) = 2^(2*n+1) - 2. ; 0,6,30,126,510,2046,8190,32766,131070,524286,2097150,8388606,33554430,134217726,536870910,2147483646,8589934590,34359738366,137438953470,549755813886,2199023255550,8796093022206,35184372088830,140737488355326,562949953421310,2251799813685246,9007199254740990 mov $1,4 pow $1,$0 div $1,3 mul $1,6
; A021959: Decimal expansion of 1/955. ; 0,0,1,0,4,7,1,2,0,4,1,8,8,4,8,1,6,7,5,3,9,2,6,7,0,1,5,7,0,6,8,0,6,2,8,2,7,2,2,5,1,3,0,8,9,0,0,5,2,3,5,6,0,2,0,9,4,2,4,0,8,3,7,6,9,6,3,3,5,0,7,8,5,3,4,0,3,1,4,1,3,6,1,2,5,6,5,4,4,5,0,2,6,1,7,8,0,1,0 seq $0,199682 ; 2*10^n+1. div $0,191 mod $0,10
<% from pwnlib.shellcraft.aarch64.linux import syscall %> <%page args="addr, length, flags"/> <%docstring> Invokes the syscall msync. See 'man 2 msync' for more information. Arguments: addr(void): addr len(size_t): len flags(int): flags </%docstring> ${syscall('SYS_msync', addr, length, flags)}
/** Copyright 2019 JasmineGraph Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "Logger.h" #include <spdlog/sinks/daily_file_sink.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/spdlog.h> auto logger = spdlog::stdout_color_mt("logger"); auto daily_logger = spdlog::daily_logger_mt("JasmineGraph", "logs/server_logs.log", 00, 01); void Logger::log(std::string message, const std::string log_type) { if (log_type.compare("info") == 0) { daily_logger->info(message); logger->info(message); } else if (log_type.compare("warn") == 0) { daily_logger->warn(message); logger->warn(message); } else if (log_type.compare("trace") == 0) { daily_logger->trace(message); logger->trace(message); } else if (log_type.compare("error") == 0) { daily_logger->error(message); logger->error(message); } else if (log_type.compare("debug") == 0) { daily_logger->debug(message); logger->debug(message); } spdlog::flush_every(std::chrono::seconds(5)); }