text
stringlengths
1
1.05M
#include <string.h> #include <fstream> #include <iostream> #include <stack> #include <cmath> #include <algorithm> #include <iomanip> // output more decimals #include <functional> #include <vector> #include <ctime> #include "string_manipulations.h" #include "node.h" #include "queue.h" #include "probs_calculation.h" #include "ranking_unr_gt.h" #include "write_ranked_tree.h" #include "get_unranked_topology.h" #include "maxlike.h" #include "lbfgsb.h" #define MAX_EXPONENT_VALUE 1024 #define N_rounds 0 using namespace std; double calcNegativeLike(int & N, double* s, vector <Node *> v, int** ar_y, vector<string> gts_vect) { string strGT=""; Node ** arMrca = new Node * [N-1]; int ** ar_rankns = new int * [N-1]; for (int i = 0; i < N-1; i++) ar_rankns[i] = new int [N-1]; for(int i = 0; i < N-1; ++i) { for(int j = 0; j < N - 1; ++j) { ar_rankns[i][j] = 0; } } int ***k; k = new int **[N+1]; for(int i = 0; i < N+1; i++) { k[i] = new int *[N]; for(int j = 0; j < N; ++j) k[i][j] = new int[N+1]; } double * array_invcoal = new double[N-1]; getInvPartialCoal(array_invcoal, N); Node * newnodeGT; double prec_total_prob = 0.; double one_gt_prob = 0.; for(int count = 0; count < gts_vect.size(); ++count) { strGT = gts_vect[count]; std::stack <Node *> stkGT; int lblGT = 0; Node **arGT = new Node * [N]; pushNodes(lblGT, stkGT , strGT); newnodeGT = stkGT.top(); newnodeGT -> distFrRoot = 0.; int tailGT = 0; distFromRoot(newnodeGT); pushToArray(newnodeGT, tailGT, arGT); getRanks(newnodeGT, tailGT, arGT); getDescTaxa(newnodeGT, N); one_gt_prob = getGeneTreeProb(N, s, v, newnodeGT, ar_y, array_invcoal, arMrca, ar_rankns, k); prec_total_prob += log(one_gt_prob); delete [] arGT; deleteTree(newnodeGT); newnodeGT = NULL; deleteStack(stkGT); } delete [] array_invcoal; for(int i = 0; i < N-1; ++i) delete[] ar_rankns[i]; delete [] ar_rankns; delete[] arMrca; for(int i = 0; i < N+1; ++i) { for(int j = 0; j < N; ++j) delete [] k[i][j]; delete [] k[i]; } delete [] k; return -prec_total_prob; } void fisher_shuffle(vector<int> & v) { int N = v.size(); srand(time(NULL)); for(int i = N - 1; i > 0; --i) { int pick = rand() % (i+1); // rand number from 0 to i swap(v[i], v[pick]); } } double newCalcNegativeLike(int & N, double* s, vector <Node *> v, int** ar_y, vector<string> & gts_vect, vector<vector<vector<double>>> & gts_probs_vect) { string strGT=""; Node ** arMrca = new Node * [N-1]; int ** ar_rankns = new int * [N-1]; for (int i = 0; i < N-1; i++) ar_rankns[i] = new int [N-1]; for(int i = 0; i < N-1; ++i) { for(int j = 0; j < N - 1; ++j) { ar_rankns[i][j] = 0; } } int ***k; k = new int **[N+1]; for(int i = 0; i < N+1; i++) { k[i] = new int *[N]; for(int j = 0; j < N; ++j) k[i][j] = new int[N+1]; } double * array_invcoal = new double[N-1]; getInvPartialCoal(array_invcoal, N); Node * newnodeGT; double prec_total_prob = 0.; double total_prob = 0.; double one_gt_prob = 0.; for(int count = 0; count < gts_vect.size(); ++count) { //cout << "---------------------------------------------------countgt = " << count << endl; strGT = gts_vect[count]; std::stack <Node *> stkGT; int lblGT = 0; Node **arGT = new Node * [N]; pushNodes(lblGT, stkGT , strGT); newnodeGT = stkGT.top(); newnodeGT -> distFrRoot = 0.; int tailGT = 0; distFromRoot(newnodeGT); pushToArray(newnodeGT, tailGT, arGT); getRanks(newnodeGT, tailGT, arGT); getDescTaxa(newnodeGT, N); vector<vector<double>> vect; one_gt_prob = getGT(N, s, v, newnodeGT, ar_y, array_invcoal, arMrca, ar_rankns, k, vect); gts_probs_vect.push_back(vect); prec_total_prob += log(one_gt_prob); total_prob += one_gt_prob; delete [] arGT; deleteTree(newnodeGT); deleteStack(stkGT); } delete [] array_invcoal; for(int i = 0; i < N-1; ++i) delete[] ar_rankns[i]; delete [] ar_rankns; delete[] arMrca; for(int i = 0; i < N+1; ++i) { for(int j = 0; j < N; ++j) delete [] k[i][j]; delete [] k[i]; } delete [] k; return -prec_total_prob; } void writeNewickTree(Node * p, int & temp, int N, std::string & str) { if(p -> label.size() != 0) str += p -> label; else { str += '('; writeNewickTree(p -> left, temp, N, str); str += ','; writeNewickTree(p -> right, temp, N, str); str += ')'; } } void swapTwoNodes(Node * a, Node * b, Node * root, int N, vector<string> & str_vect) { Node * tmp; if(a -> parent -> left -> debug_name == a -> debug_name) { a -> parent -> left = b; if(b -> debug_name == b -> parent -> right -> debug_name) { b -> parent -> right = a; } else if(b -> debug_name == b -> parent -> left -> debug_name) { b -> parent -> left = a; } } else if(a -> parent -> right -> debug_name == a -> debug_name) { a -> parent -> right = b; if(b -> debug_name == b -> parent -> right -> debug_name) b -> parent -> right = a; else if(b -> debug_name == b -> parent -> left -> debug_name) b -> parent -> left = a; } tmp = b -> parent; b -> parent = a -> parent; a -> parent = tmp; std::string temp_str = ""; int temp = 0; writeNewickTree(root, temp, N, temp_str); temp_str += ";"; str_vect.push_back(temp_str); if(a -> parent -> left -> debug_name == a -> debug_name) { a -> parent -> left = b; if(b -> debug_name == b -> parent -> right -> debug_name) { b -> parent -> right = a; } else if(b -> debug_name == b -> parent -> left -> debug_name) { b -> parent -> left = a; } } else if(a -> parent -> right -> debug_name == a -> debug_name) { a -> parent -> right = b; if(b -> debug_name == b -> parent -> right -> debug_name) b -> parent -> right = a; else if(b -> debug_name == b -> parent -> left -> debug_name) b -> parent -> left = a; } tmp = b -> parent; b -> parent = a -> parent; a -> parent = tmp; } void swapLabels(Node * a, Node * b, Node * root, int N, vector<string> & str_vect) { std::string temp_str = ""; int temp = 0; std::string tmp = ""; tmp = b -> label; b -> label = a -> label; a -> label = tmp; writeNewickTree(root, temp, N, temp_str); temp_str += ";"; str_vect.push_back(temp_str); tmp = b -> label; b -> label = a -> label; a -> label = tmp; } void insertBetweenNodes(Node * p, Node * root, int N, vector<string> & str_vect) { Node * tmp; std::string temp_str = ""; int temp = 0; if (p -> parent -> left -> debug_name == p -> debug_name) { tmp = p -> parent -> right; p -> left -> parent = p -> parent; p -> parent -> right -> parent = p; p -> parent -> left = p -> left; p -> parent -> right = p; p -> left = tmp; writeNewickTree(root, temp, N, temp_str); temp_str += ";"; str_vect.push_back(temp_str); //to original tree p -> parent -> right = p -> left; p -> left -> parent = p -> parent; p -> left = p -> parent -> left; p -> parent -> left -> parent = p; p -> parent -> left = p; tmp = p -> parent -> right; p -> right -> parent = p -> parent; p -> parent -> right -> parent = p; p -> parent -> left = p -> right; p -> parent -> right = p; p -> right = tmp; temp_str=""; writeNewickTree(root, temp, N, temp_str); temp_str += ";"; str_vect.push_back(temp_str); //to original tree p -> parent -> right = p -> right; p -> right -> parent = p -> parent; p -> right = p -> parent -> left; p -> parent -> left -> parent = p; p -> parent -> left = p; } else { tmp = p -> parent -> left; p -> right -> parent = p -> parent; p -> parent -> left -> parent = p; p -> parent -> right = p -> right; p -> parent -> left = p; p -> right = tmp; writeNewickTree(root, temp, N, temp_str); temp_str += ";"; str_vect.push_back(temp_str); //to original tree p -> parent -> left = p -> right; p -> right -> parent = p -> parent; p -> right = p -> parent -> right; p -> parent -> right -> parent = p; p -> parent -> right = p; tmp = p -> parent -> left; p -> left -> parent = p -> parent; p -> parent -> left -> parent = p; p -> parent -> right = p; p -> parent -> left = p -> left; p -> left = tmp; temp_str=""; writeNewickTree(root, temp, N, temp_str); temp_str += ";"; str_vect.push_back(temp_str); //to original tree tmp = p -> parent -> left; p -> parent -> left = p -> left; p -> left -> parent = p -> parent; p -> left = tmp; tmp -> parent = p; p -> parent -> right = p; } } void cladeTwoNodes(Node * p, Node * ch, Node * root, int N, vector<string> & str_vect) { Node * tmp; int idx = 0; if (p -> left -> label.size() == 0) { tmp = p -> left; tmp -> parent = p -> parent; p -> left = ch; ch -> parent = p; p -> parent -> right = p; p -> parent -> left = tmp; } else { tmp = p -> right; tmp -> parent = p -> parent; p -> right = ch; ch -> parent = p; p -> parent -> right = p; p -> parent -> left = tmp; idx = 1; } std::string temp_str = ""; int temp = 0; writeNewickTree(root, temp, N, temp_str); temp_str += ";"; str_vect.push_back(temp_str); if (idx == 0) { tmp = p -> parent -> left; if(p -> parent -> left -> debug_name == p -> debug_name) { p -> parent -> right = ch; } else { p -> parent -> left = ch; } ch -> parent = p -> parent; p -> left = tmp; tmp -> parent = p; } else { tmp = p -> parent -> left; if(p -> parent -> left -> debug_name == p -> debug_name) { p -> parent -> right = ch; } else { p -> parent -> left = ch; } ch -> parent = p -> parent; p -> right = tmp; tmp -> parent = p; } } void searchInternalNodes(Node * p, Node * root, int N, vector<string> & str_vect) { if (p -> label.size() == 0) { if(p -> rank != 1) { if(p -> parent -> left -> debug_name == p -> debug_name) { if(p -> parent -> right -> label.size() !=0) { if (p -> left -> label.size() != 0 && p -> right -> label.size() != 0) { swapLabels(p -> left, p -> parent -> right, root, N, str_vect); swapLabels(p -> right, p -> parent -> right, root, N, str_vect); } else if (p -> left -> label.size() != 0) { swapLabels(p -> left, p -> parent -> right, root, N, str_vect); cladeTwoNodes(p, p -> parent -> right, root, N, str_vect); } else if (p -> right -> label.size() != 0) { swapLabels(p -> right, p -> parent -> right, root, N, str_vect); cladeTwoNodes(p, p -> parent -> right, root, N, str_vect); } else { insertBetweenNodes(p, root, N, str_vect); } } else { swapTwoNodes(p, p -> parent -> right -> left, root, N, str_vect); swapTwoNodes(p, p -> parent -> right -> right, root, N, str_vect); } } else if(p -> parent -> right -> debug_name == p -> debug_name) { if(p -> parent -> left -> label.size() != 0) { if (p -> left -> label.size() != 0 && p -> right -> label.size() != 0) { swapLabels(p -> left, p -> parent -> left, root, N, str_vect); swapLabels(p -> right, p -> parent -> left, root, N, str_vect); } else if (p -> left -> label.size() != 0) { swapLabels(p -> left, p -> parent -> left, root, N, str_vect); cladeTwoNodes(p, p -> parent -> left, root, N, str_vect); } else if (p -> right -> label.size() != 0) { swapLabels(p -> right, p -> parent -> left, root, N, str_vect); cladeTwoNodes(p, p -> parent -> left, root, N, str_vect); } else { insertBetweenNodes(p, root, N, str_vect); } } else { swapTwoNodes(p, p -> parent -> left -> left, root, N, str_vect); swapTwoNodes(p, p -> parent -> left -> right, root, N, str_vect); } } } searchInternalNodes(p -> right, root, N, str_vect); searchInternalNodes(p -> left, root, N, str_vect); } } void distFrRootBasedOnRanks(Node * p, int N, vector <Node *> & v) { if(p -> label.size() == 0) { p -> distFrRoot = p -> rank - 1; p -> right -> original_parent = p; p -> left -> original_parent = p; distFrRootBasedOnRanks(p -> left, N, v); distFrRootBasedOnRanks(p -> right, N, v); } else { p -> distFrRoot = N - 1; v.push_back(p); } } void rankUnrankedTrees(Node * spnode, int Numtaxa, int rounds, vector<int> index_vector, int ** ar_y, int ***k, double * s, vector <Node *> & vlabels, vector<string> gts_vect, double & threshold, string & candidate_str, double x, double init_a, double init_b, double init_h, int N_subset, int N_maxsubset) { int prod = 1; size_t maxQue = (size_t) Numtaxa*(1+Numtaxa)/2; int tops_count = numberOfRankings(spnode, Numtaxa, prod); vector<vector<int>> seq = permuteRanks(spnode); double s_array[seq.size()][Numtaxa-2]; double res[seq.size()]; if(seq.size() != tops_count) cout << "ERROR: not all ranks!" << endl; // int NR = 2*Numtaxa; // how many rankings to select // cout << "overal ranks: " << seq.size() << endl; int sample_NR; int check_NR; if(N_maxsubset == 0) { sample_NR = 2*Numtaxa; } else { sample_NR = N_maxsubset; // how many rankings to select } if(N_subset == 0) { check_NR = Numtaxa; } else { check_NR = N_subset; } //int check_NR = (int) (Numtaxa/2.); // how many rankings to select // int check_NR = 2*Numtaxa; // how many rankings to select if(check_NR >= sample_NR) { check_NR = Numtaxa; //cout << "Error! Select different number of rankings. Set to default" << endl; sample_NR = 2*Numtaxa; } int diff_NR = sample_NR - check_NR; // how many rankings to select double neg_loglike = 0.; int th_counter = 0; //cout << "threshold: " << threshold << endl; //cout << "N init max " << check_NR << " " << sample_NR << endl; vector<int> shuffle_rankings; for(int i = 0; i < seq.size(); ++i) shuffle_rankings.push_back(i+1); fisher_shuffle(shuffle_rankings); //select subset of ranks int NR; if(seq.size() > sample_NR) { NR = diff_NR; } else { NR = seq.size() - check_NR; if(check_NR >= seq.size()) { check_NR = seq.size(); NR = check_NR; } } // cout << "**************************** NR: " << NR << endl; for(int i = 0; i < check_NR; ++i) { if(vlabels.size() != 0) { while (!vlabels.empty()) { vlabels.pop_back(); } } assignRanks(spnode, seq[shuffle_rankings[i]-1]); distFrRootBasedOnRanks(spnode, Numtaxa, vlabels); makeBeadedTree(spnode, maxQue); makeBeadedArray(spnode, ar_y, maxQue); // vector<vector<vector<double>>> vect; // neg_loglike = newCalcNegativeLike(Numtaxa, s, vlabels, ar_y, gts_vect, vect); double min_temp = 0.; neg_loglike = lbfgs(init_h, s, Numtaxa, vlabels, ar_y, gts_vect, init_a, init_b); // cout << i << " " << neg_loglike << endl; unBeadSpeciesTree(spnode); res[i] = neg_loglike; for(int t = 0; t < Numtaxa-2; ++t) s_array[i][t] = s[t]; if(neg_loglike < threshold) { th_counter++; } } double min_res = res[0]; // cout << "----- min_res = " << min_res << " " << th_counter << " " << check_NR<< endl; if(th_counter != 0) { if(NR == check_NR) { int j = 0; for(int i = 1; i < NR; ++i) { if(res[i] < min_res) { min_res = res[i]; j = i; } } // cout << "+++++best ranking j: " << j << endl; // cout << "+++++min_res = " << min_res << " threshold = " << threshold << endl; if(min_res < threshold) { if(vlabels.size() != 0) { while (!vlabels.empty()) { vlabels.pop_back(); } } threshold = min_res; // cout << "NR fin_res = " << threshold << endl; assignRanks(spnode, seq[shuffle_rankings[j]-1]); distFrRootBasedOnRanks(spnode, Numtaxa, vlabels); int temp = 0; candidate_str = ""; for(int t = 0; t < Numtaxa - 2; ++t) s[t] = s_array[j][t]; writeTreeWithBrLengths(spnode, temp, Numtaxa, candidate_str, s, x); } } else { for(int i = check_NR; i < NR; ++i) { // cout << "ranking ----------------------------- " << i << endl; if(vlabels.size() != 0) { while (!vlabels.empty()) { vlabels.pop_back(); } } assignRanks(spnode, seq[shuffle_rankings[i]-1]); distFrRootBasedOnRanks(spnode, Numtaxa, vlabels); makeBeadedTree(spnode, maxQue); makeBeadedArray(spnode, ar_y, maxQue); // vector<vector<vector<double>>> vect; // neg_loglike = newCalcNegativeLike(Numtaxa, s, vlabels, ar_y, gts_vect, vect); double min_temp = 0.; neg_loglike = lbfgs(init_h, s, Numtaxa, vlabels, ar_y, gts_vect, init_a, init_b); // cout << i << " " << neg_loglike << endl; unBeadSpeciesTree(spnode); res[i] = neg_loglike; for(int t = 0; t < Numtaxa-2; ++t) s_array[i][t] = s[t]; } int j = 0; for(int i = 1; i < NR; ++i) { if(res[i] < min_res) { min_res = res[i]; j = i; } } // cout << "-best ranking j: " << j << endl; // cout << "-min_res = " << min_res << " threshold = " << threshold << endl; if(min_res < threshold) { if(vlabels.size() != 0) { while (!vlabels.empty()) { vlabels.pop_back(); } } threshold = min_res; assignRanks(spnode, seq[shuffle_rankings[j]-1]); distFrRootBasedOnRanks(spnode, Numtaxa, vlabels); int temp = 0; candidate_str = ""; for(int t = 0; t < Numtaxa - 2; ++t) s[t] = s_array[j][t]; writeTreeWithBrLengths(spnode, temp, Numtaxa, candidate_str, s, x); } } } } void calcLikeNoNNI(int & arg_counter, char* argv[]) { // double a = 0.0001; // double b = 6.; // double t = 1e-10; int temp = 0; string candidate_str=""; Node * newnode; int N = getNumberOfTaxa(arg_counter, argv, newnode); double * s_times = new double [N-1]; double * s = new double [N-2]; int ** ar_y = new int * [N]; vector <Node *> v; for (int i = 0; i < N; i++) ar_y[i] = new int [N]; for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) { ar_y[i][j] = 0; } speciesTreeProcessing(newnode, N, s_times, s, v, ar_y); vector<string> gts_vect; if(strcmp(argv[arg_counter],"-ugt") == 0) { ++arg_counter; writeRankedUnrTreesIntoVect(arg_counter, argv, gts_vect); } else if(strcmp(argv[arg_counter],"-rgt") == 0) { ++arg_counter; ifstream finGT(argv[arg_counter]); string strR = ""; while(getline(finGT >> std::ws, strR, ';')) { if(strR.size() < 3) break; removeSpaces(strR); gts_vect.push_back(strR); } finGT.close(); } vector<int> index_vector; for(int i = 0; i < N - 2; ++i) index_vector.push_back(i); double initial_br_length[N]; for(int i = 0; i < N - 2; ++i) initial_br_length[i] = s[i]; double res = 0.; vector<vector<vector<double>>> gts_probs_vect; double neg_loglike = newCalcNegativeLike(N, s, v, ar_y, gts_vect, gts_probs_vect); cout << "Negative log-likelihood = " << neg_loglike << endl; int ***k; k = new int **[N+1]; for(int i = 0; i < N+1; i++) { k[i] = new int *[N]; for(int j = 0; j < N; ++j) k[i][j] = new int[N+1]; } /* for(int index = N-3; index >= 0; --index) { for(int j = 0; j < 1; ++ j) { res = fbrent(a, b, t, s, index, N, newnode, ar_y, k, gts_vect, gts_probs_vect); for(int i = 0; i < N - 2; ++i) cout << s[i] << " "; cout << endl; } cout << "---------- " << index << " res " << res << endl; } */ // for(int i = 0; i < N - 2; ++i) cout << s[i] << " "; // cout << endl; //int rounds = (int) (N/2.); // for(int j = 0; j < rounds; ++j) // { // fisher_shuffle(index_vector); // for(int index = 0; index < N - 2; ++index) // { int rounds = N_rounds; double x = 0.1; double init_a = 0.001; double init_b = 6; double init_h = 1e-10; int i = arg_counter + 1; while(argv[i] != NULL) { if (strcmp(argv[i], "-lb") == 0) { ++i; init_a = atof(argv[i]); } else if (strcmp(argv[i], "-ub") == 0) { ++i; init_b = atof(argv[i]); } else if (strcmp(argv[i], "-tol") == 0) { ++i; init_h = atof(argv[i]); } else if (strcmp(argv[i], "-tiplen") == 0) { ++i; x = atof(argv[i]); } ++i; } cout << "The time of the most recent clade is set to " << x << endl; cout << "Optimize branch lengths using L-BFGS method with tolerance " << init_h << endl; cout << "Allow the branch length to be in the interval [" << init_a << ", " << init_b << "]" << endl; res = lbfgs(init_h, s, N, v, ar_y, gts_vect, init_a, init_b); cout << "Negative log-likelihood = " << res << endl; // cout << j << " " << index_vector[index] << " res " << res << endl; // } // for(int i = 0; i < N - 2; ++i) cout << s[i] << " "; // cout << endl; // } double mse_res = 0.; for(int i = 0; i < N - 2; ++i) mse_res += fabs((s[i] - initial_br_length[i]) * (s[i] - initial_br_length[i])); cout << "mse: " << sqrt(mse_res) << endl; cout << "initial interval lengths" << endl; for(int i = 0; i < N - 2; ++i) cout << initial_br_length[i] << " "; cout << endl; cout << "estimated interval lengths" << endl; for(int i = 0; i < N - 2; ++i) cout << s[i] << " "; cout << endl; cout << "abs difference in interval lengths" << endl; for(int i = 0; i < N - 2; ++i) cout << fabs(s[i] - initial_br_length[i]) << " "; cout << endl; unBeadSpeciesTree(newnode); writeTreeWithBrLengths(newnode, temp, N, candidate_str, s, x); ofstream ftop("outNoNniMLTopo.txt", ios::out | ios::app); ftop << candidate_str << ";" << endl; ftop.close(); ofstream ftopi("outNoNniMse.txt", ios::out | ios::app); ftopi << sqrt(mse_res) << endl; ftopi.close(); ofstream ftopj("outNoNniDiffIntLengths.txt", ios::out | ios::app); for(int i = 0; i < N - 2; ++i) ftopj << fabs(s[i] - initial_br_length[i]) << " "; ftopj << endl; ftopj.close(); for(int i = 0; i < N+1; ++i) { for(int j = 0; j < N; ++j) delete [] k[i][j]; delete [] k[i]; } delete [] k; for(int i = 0; i < N; ++i) { delete[] ar_y[i]; } delete[] ar_y; delete[] s_times; delete[] s; deleteTree(newnode); } void unBeadSpeciesTree(Node * p) { if(p -> label.size() == 0) { if(p -> left != NULL) { unBeadSpeciesTree(p -> left); Node * temp = p -> left; if(p -> left -> left == NULL && p->left->right !=NULL) { p -> left -> right -> parent = p -> left -> parent; p -> left -> parent -> right = p -> left -> right; delete temp; } if(p -> left -> right == NULL && p->left->left !=NULL) { p -> left -> left -> parent = p -> left -> parent; p -> left -> parent -> left = p -> left -> left; delete temp; } } if(p -> right != NULL) { unBeadSpeciesTree(p -> right); Node * temp = p -> right; if(p -> right -> left == NULL && p->right->right !=NULL) { p -> right -> right -> parent = p -> right -> parent; p -> right -> parent -> right = p -> right -> right; delete temp; } if(p -> right -> right == NULL && p->right->left !=NULL) { p -> right -> left -> parent = p -> right -> parent; p -> right -> parent -> left = p -> right -> left; delete temp; } } } } /* void speciesTreeNoBeaded(Node* newnode, int & N, double* s_times, double * s, vector <Node *> v) { Node ** ar = new Node * [N]; int tail = 0; pushToArray(newnode, tail, ar); getRanks(newnode, tail, ar); getS(newnode, s_times, v); for(int j = 2; j < N; ++j) { s[j-2] = s_times[j-2] - s_times[j-1]; } int itemp = 0; double * arDistFrRoot = new double [N]; saveDistFrRoot(newnode, arDistFrRoot, itemp); delete[] ar; delete[] arDistFrRoot; } */ void readUnrankedTrees(string str_ST, int N, int rounds, vector<int> index_vector, int ** ar_y, int ***k, double * s, vector <Node *> v, vector<string> gts_vect, double & threshold, string & candidate_str, double x, double init_a, double init_b, double init_h, int N_subset, int N_maxsubset) { std::stack <Node *> stkGTunr; int lblUnrGT = 0; string ar_strlbl[N-1]; pushNodesUnrankedGT(lblUnrGT, stkGTunr , str_ST, ar_strlbl); Node * pnode = stkGTunr.top(); getDescTaxa(pnode, N); pnode -> rank = 1; rankUnrankedTrees(pnode, N, rounds, index_vector, ar_y, k, s, v, gts_vect, threshold, candidate_str, x, init_a, init_b, init_h, N_subset, N_maxsubset); deleteTree(pnode); } int calcNumberOfTaxaBrL(std::string str) { int i = 0; int lbl = 0; while(i < (int) str.size()) { // last term added to avoid treating e-05 as a label if(((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) && ((i+1) < (int) str.size()) && (str[i+1] != '-' && str[i+1] != '+')) { while(((i+1) < (int) str.size()) && str[i+1] != ':') { ++i; } ++i; while(((i+1) < (int) str.size()) && (str[i+1] != ',' || str[i+1] == ')')) { ++i; } ++lbl; } else if ( str[i] == ')' ) { ++i; } ++i; } return lbl; } string pickInitialCandidate(vector<string> sp_vect, vector<string> gts_vect, Node *& newnode, int & N, vector <Node *> v, double init_h, double init_a, double init_b, int N_subset) { int itemp = 0; int tail = 0; size_t maxQue; string str = ""; double tempdist = 0.; double neg_loglike; vector <string> species_vect; str = sp_vect[0]; //N = calcNumberOfTaxa(str); //N = calcNumberOfTaxaBrL(str); //cout << "N " << N << endl; int indicator = 0; int lbl = countNumberTaxa(indicator, str); // cout << "indicator: " << indicator << endl; N = lbl; if(indicator == 0) //no branch lengths { for(int i = 0; i < sp_vect.size(); ++i) { Node * pt; vector <string> ranked_vect; str = sp_vect[i]; std::stack <Node *> stkGTunr; int lblUnrGT = 0; string * ar_strlbl = new string[N-1]; pushNodesUnrankedGT(lblUnrGT, stkGTunr, str, ar_strlbl); pt = stkGTunr.top(); getDescTaxa(pt, N); pt -> rank = 1; int prod = 1; str = ""; int temp = 0; int tops_count = numberOfRankings(pt, N, prod); vector<vector<int>> seq = permuteRanks(pt); if(seq.size() != tops_count) cout << "ERROR: not all ranks!" << endl; for(int i = 0; i < seq.size(); ++i) { str = ""; assignRanks(pt, seq[i]); writeRankTreeIntoStr(pt, temp, N, str); ranked_vect.push_back(str); } delete [] ar_strlbl; deleteStack(stkGTunr); deleteTree(pt); vector<int> index_vector; vector<int> fin_num_cands; int v_size = ranked_vect.size(); for(int i = 0; i < ranked_vect.size(); ++i) index_vector.push_back(i); //select subset of rankings //int N_subset = 2*N; if(N_subset == 0) { N_subset = index_vector.size(); cout << "The number of rankings considered of the starting tree(s): " << N_subset << endl; } if(index_vector.size() > N_subset) { fisher_shuffle(index_vector); for(int i = 0; i < N_subset; ++i) fin_num_cands.push_back(index_vector[i]); v_size = N_subset; for(int j = 0;j < N_subset; ++j) species_vect.push_back(ranked_vect[fin_num_cands[j]]); } else { species_vect = ranked_vect; } } double tmp_array[species_vect.size()]; for(int i = 0; i < species_vect.size(); ++i) { str = species_vect[i]; stack<Node*> stkST; lbl = 0; pushNodes(lbl, stkST , str); Node * newnode = stkST.top(); newnode -> distFrRoot = 0.; tempdist = 0.; distFromRoot(newnode); isUltrametric(newnode, tempdist); tail = 0; int ** ar_y = new int * [N]; for (int i = 0; i < N; i++) ar_y[i] = new int [N]; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { ar_y[i][j] = 0; } } double * arDistFrRoot = new double [N]; Node ** ar = new Node * [N]; double s_times[N-1]; double s[N-2]; pushToArray(newnode, tail, ar); getRanks(newnode, tail, ar); if(v.size() != 0) { while (!v.empty()) { v.pop_back(); } } getS(newnode, s_times, v); for(int j = 2; j < N; ++j) { s[j-2] = s_times[j-2] - s_times[j-1]; } itemp = 0; saveDistFrRoot(newnode, arDistFrRoot, itemp); maxQue = (size_t) N*(1+N)/2; makeBeadedTree(newnode, maxQue); makeBeadedArray(newnode, ar_y, maxQue); vector<int> index_vector; for(int i = 0; i < N - 2; ++i) index_vector.push_back(i); double initial_br_length[N]; for(int i = 0; i < N - 2; ++i) initial_br_length[i] = s[i]; double res = 0.; //int rounds = (int) (N/2.); // int rounds = N_rounds; // vector<vector<vector<double>>> gts_probs_vect; // neg_loglike = newCalcNegativeLike(N, s, v, ar_y, gts_vect, gts_probs_vect); // cout << "pick init nll: " << neg_loglike << endl; int ***k; k = new int **[N+1]; for(int i = 0; i < N+1; i++) { k[i] = new int *[N]; for(int j = 0; j < N; ++j) k[i][j] = new int[N+1]; } // for(int j = 0; j < rounds; ++j) // { // fisher_shuffle(index_vector); // for(int index = 0; index < N - 2; ++index) // { neg_loglike = lbfgs(init_h, s, N, v, ar_y, gts_vect, init_a, init_b); //cout << "pick init neg_loglike = " << neg_loglike << endl; // } // if(res > neg_loglike) j = rounds; // else neg_loglike = res; // } tmp_array[i] = neg_loglike; for(int i = 0; i < N+1; ++i) { for(int j = 0; j < N; ++j) delete [] k[i][j]; delete [] k[i]; } delete [] k; for(int i = 0; i < N; ++i) { delete[] ar_y[i]; } delete[] ar_y; deleteTree(newnode); delete[] ar; delete[] arDistFrRoot; } double tmp = tmp_array[0]; int min_i = 0; for(int i = 1; i < species_vect.size(); ++i) { if(tmp_array[i] < tmp) { tmp = tmp_array[i]; min_i = i; } } //cout << min_i << endl; return species_vect[min_i]; } else { double tmp_array[sp_vect.size()]; for(int i = 0; i < sp_vect.size(); ++i) { str = sp_vect[i]; stack<Node*> stkST; lbl = 0; pushNodes(lbl, stkST , str); Node * newnode = stkST.top(); newnode -> distFrRoot = 0.; tempdist = 0.; distFromRoot(newnode); isUltrametric(newnode, tempdist); tail = 0; int ** ar_y = new int * [N]; for (int i = 0; i < N; i++) ar_y[i] = new int [N]; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { ar_y[i][j] = 0; } } double * arDistFrRoot = new double [N]; Node ** ar = new Node * [N]; double s_times[N-1]; double s[N-2]; pushToArray(newnode, tail, ar); getRanks(newnode, tail, ar); if(v.size() != 0) { while (!v.empty()) { v.pop_back(); } } getS(newnode, s_times, v); for(int j = 2; j < N; ++j) { s[j-2] = s_times[j-2] - s_times[j-1]; } itemp = 0; saveDistFrRoot(newnode, arDistFrRoot, itemp); maxQue = (size_t) N*(1+N)/2; makeBeadedTree(newnode, maxQue); makeBeadedArray(newnode, ar_y, maxQue); vector<int> index_vector; for(int i = 0; i < N - 2; ++i) index_vector.push_back(i); double initial_br_length[N]; for(int i = 0; i < N - 2; ++i) initial_br_length[i] = s[i]; double res = 0.; //int rounds = (int) (N/2.); // int rounds = N_rounds; // vector<vector<vector<double>>> gts_probs_vect; // neg_loglike = newCalcNegativeLike(N, s, v, ar_y, gts_vect, gts_probs_vect); // cout << "pick init nll: " << neg_loglike << endl; int ***k; k = new int **[N+1]; for(int i = 0; i < N+1; i++) { k[i] = new int *[N]; for(int j = 0; j < N; ++j) k[i][j] = new int[N+1]; } // for(int j = 0; j < rounds; ++j) // { // fisher_shuffle(index_vector); // for(int index = 0; index < N - 2; ++index) // { neg_loglike = lbfgs(init_h, s, N, v, ar_y, gts_vect, init_a, init_b); // cout << "pick init neg_loglike = " << neg_loglike << endl; // } // if(res > neg_loglike) j = rounds; // else neg_loglike = res; // } tmp_array[i] = neg_loglike; for(int i = 0; i < N+1; ++i) { for(int j = 0; j < N; ++j) delete [] k[i][j]; delete [] k[i]; } delete [] k; for(int i = 0; i < N; ++i) { delete[] ar_y[i]; } delete[] ar_y; deleteTree(newnode); delete[] ar; delete[] arDistFrRoot; } double tmp = tmp_array[0]; int min_i = 0; for(int i = 1; i < species_vect.size(); ++i) { if(tmp_array[i] < tmp) { tmp = tmp_array[i]; min_i = i; } } return sp_vect[min_i]; } } void writeTreeWithBrLengths(Node * p, int & temp, int N, std::string & str, double * s, double x) { if(p -> label.size() != 0) str += p -> label; else { str += '('; writeTreeWithBrLengths(p -> left, temp, N, str, s, x); str += ','; writeTreeWithBrLengths(p -> right, temp, N, str, s, x); str += ')'; } if(p -> rank != 1) { if(p -> label.size() == 0) { temp = p -> rank - p -> parent -> rank; double sum = 0.; for(int i = 0; i < temp; ++i) sum += s[p -> rank - 2 - i]; str += ':'; str += to_string(sum); } else { temp = N - p -> parent -> rank - 1; for(int i = 0; i < temp; ++i) x += s[N-3-i]; str += ':'; str += to_string(x); } } } void calcLikeWithNNI(int & arg_counter, char* argv[]) { // clock_t sp_cand_start, sp_cand_stop; double threshold = 0.; Node * newnode; ifstream st_file(argv[arg_counter]); ++arg_counter; vector<string> sp_vect; string strR = ""; while(getline(st_file >> std::ws, strR, ';')) { if(strR.size() < 3) break; removeSpaces(strR); sp_vect.push_back(strR); } st_file.close(); /* ifstream finGT(argv[arg_counter]); ++arg_counter; vector<string> gts_vect; strR = ""; while(getline(finGT >> std::ws, strR, ';')) { if(strR.size() < 3) break; removeSpaces(strR); gts_vect.push_back(strR); } finGT.close(); */ vector<string> gts_vect; if(strcmp(argv[arg_counter],"-ugt") == 0) { ++arg_counter; writeRankedUnrTreesIntoVect(arg_counter, argv, gts_vect); } else if(strcmp(argv[arg_counter],"-rgt") == 0) { ++arg_counter; ifstream finGT(argv[arg_counter]); string strR = ""; while(getline(finGT >> std::ws, strR, ';')) { if(strR.size() < 3) break; removeSpaces(strR); gts_vect.push_back(strR); } finGT.close(); } int N_nni = 5; int N_initsubset = 0; int N_subset = 0; int N_maxsubset = 0; double diff = 0.1; double x = 0.1; double init_a = 0.001; double init_b = 6; double init_h = 1e-10; int i = arg_counter + 1; while(argv[i] != NULL) { if(strcmp(argv[i], "-nni") == 0) { ++i; N_nni = atoi(argv[i]); } else if (strcmp(argv[i], "-diff") == 0) { ++i; diff = atof(argv[i]); } else if (strcmp(argv[i], "-startsubset") == 0) { ++i; N_initsubset = atoi(argv[i]); cout << "The number of maximum rankings considered of the starting tree(s): " << N_initsubset << endl; } else if (strcmp(argv[i], "-initsubset") == 0) { ++i; N_subset = atoi(argv[i]); cout << "The number of initial rankings considered of each unranked species tree candidate: " << N_subset << endl; } else if (strcmp(argv[i], "-maxsubset") == 0) { ++i; N_maxsubset = atoi(argv[i]); cout << "The number of maximum rankings considered of each unranked species tree candidate: " << N_maxsubset << endl; } else if (strcmp(argv[i], "-lb") == 0) { ++i; init_a = atof(argv[i]); } else if (strcmp(argv[i], "-ub") == 0) { ++i; init_b = atof(argv[i]); } else if (strcmp(argv[i], "-tol") == 0) { ++i; init_h = atof(argv[i]); } else if (strcmp(argv[i], "-tiplen") == 0) { ++i; x = atof(argv[i]); } ++i; } cout << "The time of the most recent clade is set to " << x << endl; cout << "Optimize branch lengths using L-BFGS method with tolerance " << init_h << endl; cout << "Allow the branch length to be in the interval [" << init_a << ", " << init_b << "]" << endl; cout << "Maximum number of NNI moves: " << N_nni << endl; cout << "Stop if the difference between log-likelihoods is greater than " << diff << endl; if(N_maxsubset == 0) cout << "The number of maximum rankings considered of each unranked species tree candidate (default): 2*(Number of Taxa)" << endl; if(N_subset == 0) cout << "The number of initial rankings considered of each unranked species tree candidate (default): Number of Taxa" << endl; vector <Node *> v; int N = 0; string initial_tree_string = pickInitialCandidate(sp_vect, gts_vect, newnode, N, v, init_h, init_a, init_b, N_initsubset); ofstream ftopi("outInitialTopo.txt", ios::out | ios::app); ftopi << initial_tree_string << ";" << endl; cout << "Starting ranked species tree: " << initial_tree_string << ";" << endl; ftopi.close(); int ** ar_y = new int * [N]; for (int i = 0; i < N; i++) ar_y[i] = new int [N]; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { ar_y[i][j] = 0; } } double * arDistFrRoot = new double [N]; Node ** ar = new Node * [N]; double s_times[N-1]; double s[N-2]; double tempdist = 0.; int lbl = 0; string str = initial_tree_string; stack<Node*> stkST; pushNodes(lbl, stkST , str); newnode = stkST.top(); newnode -> distFrRoot = 0.; distFromRoot(newnode); isUltrametric(newnode, tempdist); int tail = 0; pushToArray(newnode, tail, ar); getRanks(newnode, tail, ar); if(v.size() != 0) { while (!v.empty()) { v.pop_back(); } } getS(newnode, s_times, v); for(int j = 2; j < N; ++j) { s[j-2] = s_times[j-2] - s_times[j-1]; } int itemp = 0; saveDistFrRoot(newnode, arDistFrRoot, itemp); int tempo = 0; string out_str=""; writeTreeWithBrLengths(newnode, tempo, N, out_str, s, x); size_t maxQue = (size_t) N*(1+N)/2; makeBeadedTree(newnode, maxQue); makeBeadedArray(newnode, ar_y, maxQue); delete[] arDistFrRoot; delete[] ar; vector<int> index_vector; for(int i = 0; i < N - 2; ++i) index_vector.push_back(i); //int rounds = (int) (N/2.); // int rounds = N_rounds; // vector<vector<vector<double>>> gts_probs_vect; // double neg_loglike = newCalcNegativeLike(N, s, v, ar_y, gts_vect, gts_probs_vect); // cout << "init neg_loglike = " << neg_loglike << endl; int ***k; k = new int **[N+1]; for(int i = 0; i < N+1; i++) { k[i] = new int *[N]; for(int j = 0; j < N; ++j) k[i][j] = new int[N+1]; } // for(int j = 0; j < rounds; ++j) // { // fisher_shuffle(index_vector); // cout << "round " << j << endl; // for(int index = 0; index < N - 2; ++index) // { threshold = lbfgs(init_h, s, N, v, ar_y, gts_vect, init_a, init_b); //cout << " " << threshold << endl; // } // if(threshold > neg_loglike) j = rounds; // else neg_loglike = threshold; // } double neg_loglike = threshold; int temp = 0; string candidate_str = ""; unBeadSpeciesTree(newnode); writeTreeWithBrLengths(newnode, temp, N, candidate_str, s, x); //cout << "after br lengths optimization tree: " << candidate_str << endl; double old_threshold = 0.; int nni_counts = 0; while(fabs(old_threshold - threshold) > diff && nni_counts < N_nni) { //cout << "*************************** NNI **************************** " << nni_counts << endl; old_threshold = threshold; vector<string> str_vect; searchInternalNodes(newnode, newnode, N, str_vect); deleteTree(newnode); for(int i = 0; i < str_vect.size(); ++i) { //cout << "*************************** nni **************************** " << i << endl; readUnrankedTrees(str_vect[i], N, rounds, index_vector, ar_y, k, s, v, gts_vect, threshold, candidate_str, x, init_a, init_b, init_h, N_subset, N_maxsubset); } tempdist = 0.; lbl = 0; Node ** ar_c = new Node * [N]; stack<Node*> stkST; pushNodes(lbl, stkST , candidate_str); newnode = stkST.top(); newnode -> distFrRoot = 0.; distFromRoot(newnode); isUltrametric(newnode, tempdist); tail = 0; pushToArray(newnode, tail, ar_c); getRanks(newnode, tail, ar_c); if(v.size() != 0) { while (!v.empty()) { v.pop_back(); } } getS(newnode, s_times, v); nni_counts++; delete[] ar_c; //cout << "LIKE: " << threshold << endl; //cout << "DIFFERENCE: " << fabs(old_threshold-threshold) << endl; } // after the first round of nni, select subset of nni's /* while(fabs(old_threshold - threshold) > 0.1 && nni_counts < 5) { old_threshold = threshold; vector<string> str_vect; searchInternalNodes(newnode, newnode, N, str_vect); deleteTree(newnode); vector<int> shuffle_nni; for(int i = 0; i < 2*N - 4; ++i) shuffle_nni.push_back(i); fisher_shuffle(shuffle_nni); for(int i = 0; i < N - 2; ++i)//keep half nni's { cout << "------------------species tree " << i << endl; readUnrankedTrees(str_vect[shuffle_nni[i]], N, rounds, index_vector, ar_y, k, s, gts_vect, threshold, candidate_str, x); } tempdist = 0.; lbl = 0; Node ** ar_c = new Node * [N]; stack<Node*> stkST; pushNodes(lbl, stkST , candidate_str); newnode = stkST.top(); newnode -> distFrRoot = 0.; distFromRoot(newnode); isUltrametric(newnode, tempdist); tail = 0; pushToArray(newnode, tail, ar_c); getRanks(newnode, tail, ar_c); nni_counts++; delete[] ar_c; cout << "----------NNI_count: " << nni_counts << " diff: " << fabs(old_threshold-threshold) << endl; } */ // cout << "total nni: " << nni_counts << endl; cout << "Negative log-likelihood = " << threshold << endl; ofstream ftop("outWithNniMLTopo.txt", ios::out | ios::app); ftop << candidate_str << ";" << endl; ftop.close(); //cout << "inferred tree: " << candidate_str << ";" << endl; // for(int t = 0; t < N - 2; ++t) // { // cout << "s[" << t << "] = " << s[t] << endl; // } /* ofstream fin("s_i.txt"); for(int i = 0; i < N - 2; ++i) { fin << s[i] << "\t"; } fin << endl; fin.close(); */ for(int i = 0; i < N; ++i) { delete[] ar_y[i]; } delete[] ar_y; for(int i = 0; i < N+1; ++i) { for(int j = 0; j < N; ++j) delete [] k[i][j]; delete [] k[i]; } delete [] k; deleteTree(newnode); } void initProbsVect(int * m, int *** k, double * s, double * coal, int & n, vector<vector<double>> & vect) { vector<double> res; for(int i = 2; i < n; ++i) { res.push_back(conditionalProbability(i, m, k, s)); } res.push_back(coal[m[0] - 1]); vect.push_back(res); } double getGT(int & N, double * s, vector <Node *> v, Node * newnodeGT, int ** ar_y, double * array_invcoal, Node ** arMrca, int ** ar_rankns, int ***k, vector<vector<double>> & vect) { double arhists[MAX_EXPONENT_VALUE]; for(int i = 0; i < MAX_EXPONENT_VALUE; ++i) arhists[i] = 0.; returnMrca(v, newnodeGT, N, arMrca); int * arRankHistory = new int [N-1]; get_hseq(arRankHistory, newnodeGT, v, N); reverseArraySort(arRankHistory, N); /* cout << "Max Ranked History" << endl; for(int i = 0; i < N-1; ++i) cout << arRankHistory[i] << " "; cout << endl; */ int * arRankHistoryCopy = new int[N-1]; for(int i = 0; i < N-1; ++i) { arRankHistoryCopy[i] = arRankHistory[i]; } int * m_i = new int[N-1]; arrayFreq(arRankHistoryCopy, m_i, N-1);//1st arg changes after running this func int max_m_i = *max_element(m_i, m_i+N-1); get_node(arRankHistory, ar_rankns, N, arMrca); for(int i = 0; i < N+1; i++) for(int j = 0; j < N; ++j) for(int z = 0; z < N+1 ; ++z) { k[i][j][z] = 0; } calc_k_ijz(k, N, m_i, ar_y, ar_rankns); int hist_counter = 0; initProbsVect(m_i, k, s, array_invcoal, N, vect); double onehistprob = 1.; for(int i = 0; i < N - 1; ++i) { // cout << hist_counter << " " << i << " " << vect[hist_counter][i] << endl; onehistprob *= vect[hist_counter][i]; } //cout << "99999-*_**_*_*_*_*_*_**_*_" << (int) floor(fabs(log2(fabs(onehistprob)))) << endl; if(onehistprob != 0 && ((int) floor(fabs(log2(fabs(onehistprob))))) < MAX_EXPONENT_VALUE) arhists[ (int) floor(fabs(log2(fabs(onehistprob))))] += fabs(onehistprob); int * arRHcopy = new int[N-1]; for(int i = 0; i < N - 1; ++i) arRHcopy[i] = arRankHistory[i]; int numb = 0; int * next_history; int history_counter = 1; while(*(arRHcopy + N - 2) != 1) { hist_counter++; next_history = getNextHistory (arRHcopy, arRankHistory, N, history_counter, numb); /* cout << "---------- Next Label history ---------- " << endl; for(int i = 0; i < N - 1; ++i) cout << next_history[i] << " "; cout << endl; */ for(int i = 0; i < N-1; ++i) arRankHistoryCopy[i] = next_history[i]; arrayFreq(arRankHistoryCopy, m_i, N-1); max_m_i = *max_element(m_i, m_i+N-1); get_node(next_history, ar_rankns, N, arMrca); for(int i = 0; i < N+1; i++) { for(int j = 0; j <= max_m_i ; ++j) { for(int z = 0; z < N+1 ; ++z) { k[i][j][z] = 0; } } } calc_k_ijz(k, N, m_i, ar_y, ar_rankns); initProbsVect(m_i, k, s, array_invcoal, N, vect); onehistprob = 1.; for(int i = 0; i < N - 1; ++i) { onehistprob *= vect[hist_counter][i]; } if(onehistprob != 0 && ((int) floor(fabs(log2(fabs(onehistprob))))) < MAX_EXPONENT_VALUE) arhists[ (int) floor(fabs(log2(fabs(onehistprob))))] += fabs(onehistprob); history_counter++; } double fin_prob = 0.; for(int i = MAX_EXPONENT_VALUE - 1; i >= 0 ; --i) { if(arhists[i] != 0) { fin_prob += arhists[i]; } } delete[] arRankHistory; delete[] arRHcopy; delete[] arRankHistoryCopy; delete[] m_i; return fin_prob; } double updateNegativeLike(int & N, double* s, vector <Node *> v, int** ar_y, int ***k, vector<string> & gts_vect, vector<vector<vector<double>>> & vect, int & interval) { string strGT=""; Node ** arMrca = new Node * [N-1]; int ** ar_rankns = new int * [N-1]; for (int i = 0; i < N-1; i++) ar_rankns[i] = new int [N-1]; for(int i = 0; i < N-1; ++i) { for(int j = 0; j < N - 1; ++j) { ar_rankns[i][j] = 0; } } Node * newnodeGT; double prec_total_prob = 0.; double one_gt_prob = 0.; //double total = 0.; for(int count = 0; count < gts_vect.size(); ++count) { strGT = gts_vect[count]; std::stack <Node *> stkGT; int lblGT = 0; Node **arGT = new Node * [N]; pushNodes(lblGT, stkGT , strGT); newnodeGT = stkGT.top(); newnodeGT -> distFrRoot = 0.; int tailGT = 0; distFromRoot(newnodeGT); pushToArray(newnodeGT, tailGT, arGT); getRanks(newnodeGT, tailGT, arGT); getDescTaxa(newnodeGT, N); one_gt_prob = updateProbability(N, s, v, newnodeGT, ar_y, arMrca, ar_rankns, k, vect, interval, count); // total += one_gt_prob; prec_total_prob += log(one_gt_prob); delete [] arGT; deleteTree(newnodeGT); newnodeGT = NULL; deleteStack(stkGT); } // cout << "total" << " " << -prec_total_prob << endl; for(int i = 0; i < N-1; ++i) delete[] ar_rankns[i]; delete [] ar_rankns; delete[] arMrca; return -prec_total_prob; } double updateHistoryProbability(vector<vector<vector<double>>> & vect, int & hist_counter, int & n, int & gt_count) { double res = 1.; for(int i = 2; i < n+1; ++i) { res *= vect[gt_count][hist_counter][i-2]; } return res; } double updateProbability(int & N, double * s, vector <Node *> v, Node * newnodeGT, int ** ar_y, Node ** arMrca, int ** ar_rankns, int ***k, vector<vector<vector<double>>> & vect, int & interval, int & gt_count) { double arhists[MAX_EXPONENT_VALUE]; for(int i = 0; i < MAX_EXPONENT_VALUE; ++i) arhists[i] = 0.; returnMrca(v, newnodeGT, N, arMrca); int * arRankHistory = new int [N-1]; get_hseq(arRankHistory, newnodeGT, v, N); reverseArraySort(arRankHistory, N); /* cout << "Max Ranked History" << endl; for(int i = 0; i < N-1; ++i) cout << arRankHistory[i] << " "; cout << endl; */ int * arRankHistoryCopy = new int[N-1]; for(int i = 0; i < N-1; ++i) { arRankHistoryCopy[i] = arRankHistory[i]; } int * m_i = new int[N-1]; arrayFreq(arRankHistoryCopy, m_i, N-1);//1st arg changes after running this func int max_m_i = *max_element(m_i, m_i+N-1); get_node(arRankHistory, ar_rankns, N, arMrca); for(int i = 0; i < N+1; i++) for(int j = 0; j < N; ++j) for(int z = 0; z < N+1 ; ++z) { k[i][j][z] = 0; } calc_k_ijz(k, N, m_i, ar_y, ar_rankns); int hist_counter = 0; vect[gt_count][hist_counter][interval-2] = conditionalProbability(interval, m_i, k, s); double res = 1.; for(int i = 2; i < N+1; ++i) { res *= vect[gt_count][hist_counter][i-2]; } double onehistprob = res; if(onehistprob != 0 && ((int) floor(fabs(log2(fabs(onehistprob))))) < MAX_EXPONENT_VALUE) arhists[ (int) floor(fabs(log2(fabs(onehistprob))))] += fabs(onehistprob); int * arRHcopy = new int[N-1]; for(int i = 0; i < N - 1; ++i) arRHcopy[i] = arRankHistory[i]; int numb = 0; int * next_history; int history_counter = 1; while(*(arRHcopy + N - 2) != 1) { hist_counter++; next_history = getNextHistory (arRHcopy, arRankHistory, N, history_counter, numb); /* cout << "---------- Next Label history ---------- " << endl; for(int i = 0; i < N - 1; ++i) cout << next_history[i] << " "; cout << endl; */ for(int i = 0; i < N-1; ++i) arRankHistoryCopy[i] = next_history[i]; arrayFreq(arRankHistoryCopy, m_i, N-1); max_m_i = *max_element(m_i, m_i+N-1); get_node(next_history, ar_rankns, N, arMrca); for(int i = 0; i < N+1; i++) { for(int j = 0; j <= max_m_i ; ++j) { for(int z = 0; z < N+1 ; ++z) { k[i][j][z] = 0; } } } calc_k_ijz(k, N, m_i, ar_y, ar_rankns); vect[gt_count][hist_counter][interval-2] = conditionalProbability(interval, m_i, k, s); //onehistprob = updateHistoryProbability(vect, hist_counter, N, gt_count); res = 1.; for(int i = 2; i < N+1; ++i) { res *= vect[gt_count][hist_counter][i-2]; } onehistprob = res; if(onehistprob != 0 && ((int) floor(fabs(log2(fabs(onehistprob))))) < MAX_EXPONENT_VALUE) arhists[ (int) floor(fabs(log2(fabs(onehistprob))))] += fabs(onehistprob); history_counter++; } double fin_prob = 0.; for(int i = MAX_EXPONENT_VALUE - 1; i >= 0 ; --i) { if(arhists[i] != 0) { fin_prob += arhists[i]; } } delete[] arRankHistory; delete[] arRHcopy; delete[] arRankHistoryCopy; delete[] m_i; return fin_prob; } //L-BFGS method double lbfgs(double h, double * s, int & N, vector <Node *> vlabels, int ** ar_y, vector<string> gts_vect, double init_a, double init_b) { /* Local variables */ static double f, g[1024]; static integer i__; static double l[1024]; static integer m, n; static double u[1024], x[1024], t1, t2, wa[43251]; static integer nbd[1024], iwa[3072]; static integer taskValue; static integer *task=&taskValue; /* must initialize !! */ static double factr; static integer csaveValue; static integer *csave=&csaveValue; static double dsave[29]; static integer isave[44]; static logical lsave[4]; static double pgtol; static integer iprint; /* We wish to have output at every iteration. */ iprint = -1; /* We specify the tolerances in the stopping criteria. */ factr = 1e7; pgtol = 1e-5; /* m of limited memory corrections stored. (n and m should not */ /* exceed the limits nmax and mmax respectively.) */ n = N-2; m = 5; /* l specifies the lower bounds, */ /* u specifies the upper bounds. */ for (int i = 0; i < n; i++) { x[i] = (init_a + init_b)/2.; // init val, can put any nbd[i] = 2; l[i] = init_a; u[i] = init_b; } *task = (integer)START; L111: setulb(&n, &m, x, l, u, nbd, &f, g, &factr, &pgtol, wa, iwa, task, & iprint, csave, lsave, isave, dsave); if ( IS_FG(*task) ) { //s[index] = x[0]; f = calcNegativeLike(N, x, vlabels, ar_y, gts_vect); // TODO REMOVE int interval = index + 2; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { s[j] = x[j]; } s[i] = x[i] + h; g[i] = calcNegativeLike(N, s, vlabels, ar_y, gts_vect); g[i] = (g[i] - f) / h; } goto L111; } if ( *task==NEW_X ) { goto L111; } return f; }
/******************************************************************************* * * * Copyright (C) 2014-2015 Nick Guletskii * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * * 1. Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * 3. Neither the name of the author(s) nor the names of its contributors may * * be used to endorse or promote products derived from this software * * without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "runner.hpp" #include <cstring> #include <iostream> #include <sstream> #include <sysexits.h> #include <sys/resource.h> #include <algorithm> #include <fstream> #include <map> #include <random> #include <getopt.h> #include <semaphore.h> #include <fcntl.h> namespace openolympus { #define FAIL_CHILD raise(SIGUSR1) static bool signal_handler_started = false; static std::vector<pid_t> pids; bool to_bool(std::string const &s) { return s != "0"; } static int install_syscall_filter(void) { struct sock_filter filter[] = { VALIDATE_ARCHITECTURE, EXAMINE_SYSCALL, ALLOW_SYSCALL(restart_syscall), ALLOW_SYSCALL(read), ALLOW_SYSCALL(write), ALLOW_SYSCALL(lseek), ALLOW_SYSCALL(brk), ALLOW_SYSCALL(ioctl), ALLOW_SYSCALL(munmap), ALLOW_SYSCALL(mprotect), ALLOW_SYSCALL(mremap), ALLOW_SYSCALL(mmap), ALLOW_SYSCALL(gettid), ALLOW_SYSCALL(set_thread_area), ALLOW_SYSCALL(exit_group), ALLOW_SYSCALL(fstat), ALLOW_SYSCALL(uname), ALLOW_SYSCALL(arch_prctl), ALLOW_SYSCALL(access), ALLOW_SYSCALL(open), ALLOW_SYSCALL(close), ALLOW_SYSCALL(stat), ALLOW_SYSCALL(readv), ALLOW_SYSCALL(writev), ALLOW_SYSCALL(dup3), ALLOW_SYSCALL(rt_sigaction), ALLOW_SYSCALL(rt_sigprocmask), ALLOW_SYSCALL(rt_sigreturn), ALLOW_SYSCALL(tgkill), ALLOW_SYSCALL(getrlimit), ALLOW_SYSCALL(readlink), ALLOW_SYSCALL(time), ALLOW_SYSCALL(execve), ALLOW_SYSCALL(nanosleep), KILL_PROCESS, }; struct sock_fprog filter_program = { .len = (unsigned short)(sizeof(filter) / sizeof(filter[0])), .filter = filter, }; if (prctl(PR_SET_PDEATHSIG, SIGKILL)) { goto failed; } if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) { goto failed; } if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &filter_program)) { goto failed; } return 0; failed: ERR_LOG("Seccomp filter not available! Please check that your kernel is correct!" << strerror(errno)); FAIL_CHILD; } pid_t watchdog::getPid() const { return pid; } void watchdog::setup_io() { for (int file_descriptor = 0; file_descriptor < MAX_FILE_DESCRIPTOR; file_descriptor++) { if ((file_descriptor == input_file_descriptor) || (file_descriptor == output_file_descriptor) || (file_descriptor == error_file_descriptor)) { continue; } close(file_descriptor); } if (dup2(error_file_descriptor, STDERR_FILENO) < 0) { ERR_LOG("Couldn't redirect error output."); FAIL_CHILD; } if (dup2(output_file_descriptor, STDOUT_FILENO) < 0) { ERR_LOG("Couldn't redirect output."); FAIL_CHILD; } if (dup2(input_file_descriptor, STDIN_FILENO) < 0) { ERR_LOG("Couldn't redirect input."); FAIL_CHILD; } } void watchdog::setup_rlimit() { rlimit *core_dump_rlimit = new rlimit(); core_dump_rlimit->rlim_cur = 0; core_dump_rlimit->rlim_max = 0; setrlimit(RLIMIT_CORE, core_dump_rlimit); rlimit *disk_rlimit = new rlimit(); disk_rlimit->rlim_cur = disk_limit; disk_rlimit->rlim_max = disk_limit; setrlimit(RLIMIT_CORE, disk_rlimit); } void watchdog::execute_child(std::string program, std::vector<std::string> args) { if ((securitySemaphore = sem_open(semaphoreName.c_str(), O_EXCL)) == SEM_FAILED) { ERR_LOG("Couldn't create security semaphore! " << strerror(errno)); exit(EX_SOFTWARE); } if (setsid() < 0) { ERR_LOG("Couldn't setsid! Error: " << strerror(errno)); FAIL_CHILD; } setup_rlimit(); setup_io(); LOG("Bulding arguments..."); std::array<char *, 256> argv; std::fill(argv.begin(), argv.end(), nullptr); argv[0] = new char[program.size() + 1]; strcpy(argv[0], program.c_str()); argv[0][program.size()] = '\0'; for (size_t i = 0; i < args.size(); i++) { char *writable = new char[args[i].size() + 1]; std::copy(args[i].begin(), args[i].end(), writable); writable[args[i].size()] = '\0'; argv[i + 1] = writable; } std::array<char *, 1> envp; envp[0] = nullptr; if (!chroot_path.empty() && chroot_path != "/") { LOG("Chrooting..."); if (chroot(chroot_path.c_str()) != 0) { ERR_LOG("Couldn't chroot! Error: " << strerror(errno)); FAIL_CHILD; } LOG("Chrooted."); } if (setgid(gid) != 0) { ERR_LOG("Couldn't change gid! Error: " << strerror(errno)); FAIL_CHILD; } if (setuid(uid) != 0) { ERR_LOG("Couldn't change uid! Error: " << strerror(errno)); FAIL_CHILD; } LOG("Waiting for watcher threads to be ready"); if (sem_wait(securitySemaphore) == EINTR) // Wait for the signal polling thread FAIL_CHILD; if (sem_wait(securitySemaphore) == EINTR) // Wait for the timeout thread FAIL_CHILD; if (sem_wait(securitySemaphore) == EINTR) // Wait for the CPU time/memory limiting thread FAIL_CHILD; LOG("Watcher threads are ready. Closing the semaphore."); sem_close(securitySemaphore); sem_unlink(semaphoreName.c_str()); LOG("Closed semaphore."); if (enableSecurity) install_syscall_filter(); LOG("Running execve: " << program); // No cleanup required: we exit here anyway! execve(program.c_str(), argv.data(), envp.data()); ERR_LOG( "Execve failed! Error: " << errno << " " << strerror(errno)); FAIL_CHILD; } void watchdog::enter_watchdog() { start_time = std::chrono::high_resolution_clock::now(); clockid_t clock_id; clock_getcpuclockid(pid, &clock_id); exit_monitor_thread = std::thread([this]() { sem_post(securitySemaphore); int status; do { waitpid(pid, &status, WUNTRACED); if (!running) return; if (WIFEXITED(status)) { int code = WEXITSTATUS(status); if (code != 0) { finish(RUNTIME_ERROR); } else { finish(OK); } } else if (WIFSIGNALED(status)) { int signal = WTERMSIG(status); LOG("Child signaled: " << strsignal(signal)); switch (signal) { case SIGXFSZ: finish(DISK_LIMIT); break; case SIGSEGV: case SIGBUS: case SIGFPE: case SIGABRT: case SIGILL: case SIGQUIT: finish(RUNTIME_ERROR); break; case SIGSYS: finish(SANDBOX_VIOLATION); break; case SIGUSR1: finish(INTERNAL_ERROR); break; default: finish(INTERNAL_ERROR); break; } } } while (!WIFEXITED(status) && !WIFSIGNALED(status) && running); }); exit_monitor_thread.detach(); timeout_thread = std::thread([this]() { sem_post(securitySemaphore); std::unique_lock<std::mutex> lk(running_notifier_mutex); if (!running_notifier.wait_for(lk, std::chrono::milliseconds(time_limit), [this]() { return !running; })) { finish(TIME_LIMIT); } }); timeout_thread.detach(); sem_post(securitySemaphore); LOG("Opening procfs for the first time"); std::ifstream procfs_stream("/proc/" + std::to_string(pid) + "/stat"); while (running) { struct timespec ts; if (clock_getcpuclockid(pid, &clock_id) == 0 && clock_gettime(clock_id, &ts) == 0) { cpu_milliseconds_consumed = ((int64_t) ts.tv_sec) * 1000ll + ((int64_t) ts.tv_nsec / 1000000ll); } procfs_stream.seekg(0); procfs_stream.sync(); if (procfs_stream.fail()) { break; } int64_t user_cpu_time; int64_t kernel_cpu_time; size_t virtual_memory_size; for (int i = 0; i < 40; i++) { switch (i) { case 13: procfs_stream >> user_cpu_time; break; case 14: procfs_stream >> kernel_cpu_time; break; case 23: procfs_stream >> virtual_memory_size; break; default: procfs_stream.ignore(256, ' '); } } if (cpu_milliseconds_consumed > cpu_time_limit) { finish(CPU_TIME_LIMIT); } peak_virtual_memory_size = std::max<size_t>(virtual_memory_size, peak_virtual_memory_size); if (memory_limit != -1 && peak_virtual_memory_size > memory_limit) { finish(MEMORY_LIMIT); } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } LOG("Finishing"); auto end_time = std::chrono::high_resolution_clock::now(); time_consumed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(); running = false; running_notifier.notify_all(); if (exit_monitor_thread.joinable()) exit_monitor_thread.join(); if (timeout_thread.joinable()) timeout_thread.join(); std::map<exit_status, std::string> names { {OK, "OK"}, {CPU_TIME_LIMIT, "TIME_LIMIT"}, {TIME_LIMIT, "TIME_LIMIT"}, {MEMORY_LIMIT, "MEMORY_LIMIT"}, {DISK_LIMIT, "OUTPUT_LIMIT"}, {RUNTIME_ERROR, "RUNTIME_ERROR"}, {SANDBOX_VIOLATION, "SECURITY_VIOLATION"}, {INTERNAL_ERROR, "INTERNAL_ERROR"}, {ABNORMAL_TERMINATION, "ABNORMAL_TERMINATION"} }; LOG("Writing verdict"); std::ofstream verdict; std::ios_base::iostate exceptionMask = verdict.exceptions() | std::ios::failbit; verdict.exceptions(exceptionMask); verdict.open("verdict.txt", std::ios_base::out); verdict << names[status] << "(" << time_consumed << ", " << cpu_milliseconds_consumed << ", " << peak_virtual_memory_size << ")" << std::endl; verdict.flush(); verdict.close(); LOG("Killing"); std::cout.flush(); if (status != OK && pid != 0) killpg(pid, SIGKILL); LOG("Finished"); shutdown(EXIT_SUCCESS); } void watchdog::shutdown(int exit_code) { running_notifier.notify_all(); if (exit_monitor_thread.joinable()) exit_monitor_thread.join(); if (timeout_thread.joinable()) timeout_thread.join(); exit(exit_code); } void watchdog::finish(exit_status status) { running = false; this->status = status; LOG("Destroying semaphore."); sem_close(securitySemaphore); sem_unlink(semaphoreName.c_str()); LOG("Destroyed semaphore."); } std::string watchdog::generate_semaphore_id() { std::vector<char> name(16); std::mt19937_64 mersenneTwister; std::seed_seq sseq { (int)( std::chrono::system_clock::now().time_since_epoch().count() % 1000000007 ), (int)(getpid() % 1000000007) }; mersenneTwister.seed(sseq); std::uniform_int_distribution<> distribution(0, 15); std::generate(name.begin(), name.end(), [&] { return "0123456789ABCDEF"[distribution(mersenneTwister)]; }); return std::string(name.begin(), name.end()); } void watchdog::fork_app(std::string program, std::vector<std::string> args) { running = true; if (!usedOnce) throw std::logic_error("A watchdog can only be used once!"); usedOnce = false; semaphoreName = "/oolw" + generate_semaphore_id(); if ((securitySemaphore = sem_open(semaphoreName.c_str(), O_CREAT, 0664, 0)) == SEM_FAILED) { ERR_LOG("Couldn't create security semaphore! " << strerror(errno)); exit(EX_SOFTWARE); } if (!signal_handler_started) { struct sigaction kill_handler; kill_handler.sa_handler = [](int signal) { for (auto pid : pids) { killpg(pid, signal); } killpg(0, signal); }; sigaction(SIGKILL, &kill_handler, NULL); sigaction(SIGTERM, &kill_handler, NULL); sigaction(SIGHUP, &kill_handler, NULL); struct sigaction interrupt_handler; interrupt_handler.sa_handler = [](int signal) { for (auto pid : pids) { killpg(pid, SIGTERM); } killpg(0, SIGINT); }; sigaction(SIGINT, &interrupt_handler, NULL); } pid = fork(); if (pid == 0) { execute_child(program, args); } else { pids.push_back(pid); enter_watchdog(); } } void run(int argc, char **argv) { int64_t memoryLimit = 64ll * 1024ll * 1024ll; int64_t cpuLimit = 1ll * 1000ll; int64_t timeLimit = 2ll * 1000ll; int64_t diskLimit = 1ll * 1024ll * 1024ll; uid_t uid; gid_t gid; bool enableSecurity = true; std::string jailPath = "/"; { int c; while (true) { static struct option long_options[] = { {"memorylimit", required_argument, 0, 'm'}, {"cpulimit", required_argument, 0, 'c'}, {"timelimit", required_argument, 0, 't'}, {"disklimit", required_argument, 0, 'd'}, {"security", required_argument, 0, 's'}, {"jail", required_argument, 0, 'j'}, {"uid", required_argument, 0, 'u'}, {"gid", required_argument, 0, 'g'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long(argc, argv, "mctd", long_options, &option_index); if (c == -1) break; switch (c) { case 0: break; case 'm': memoryLimit = std::stoll(optarg); break; case 'c': cpuLimit = std::stoll(optarg); break; case 't': timeLimit = std::stoll(optarg); break; case 'd': diskLimit = std::stoll(optarg); break; case 'u': uid = std::stoll(optarg); break; case 'g': gid = std::stoll(optarg); break; case 's': enableSecurity = to_bool(optarg); break; case 'j': jailPath = std::string(optarg); break; case '?': break; default: exit(EX_USAGE); } } } if (argv[optind] == nullptr || argv[optind][0] == '\0') { exit(EX_USAGE); } std::vector<std::string> args; for (size_t index = optind + 1; index < argc; index++) { args.push_back(std::string(argv[index])); } watchdog watcher(enableSecurity, memoryLimit, diskLimit, timeLimit, cpuLimit, gid, uid, jailPath); watcher.fork_app(std::string(argv[optind]), args); } } int main(int argc, char **argv) { openolympus::run(argc, argv); return 0; }
#Confrontare due interi positivi a e b, definiti in memoria, e mettere in $t0 il valore 0 se a e' maggiore di b, 1 altrimenti. #Non è possibile utilizzare l'istruzione di comparazione tra valori: operare sui singoli bit dei valori. .text .globl main main: lw $t1, n1 lw $t2, n2 xor $t3, $t1, $t2 loop: beq $t4, 32, fine andi $t5, $t3, 0x80000000 beq $t5, 0x80000000, confronto sll $t1, $t1, 1 sll $t2, $t2, 1 sll $t3, $t3, 1 add $t4, $t4, 1 j loop confronto: andi $t6, $t1, 0x80000000 beq $t6, 0x80000000, mag_a li $t0, 0 j fine mag_a: li $t0, 1 fine: li $v0, 10 syscall .data n1: .word 5 n2: .word 7
;================================================================================ ; Randomize NPC Items ;-------------------------------------------------------------------------------- ; Old Man - Zora King - Sick Kid - Tree Kid - Sahasrala - Catfish - Rupee NPC ;=SET 1 ;OLD_MAN = "#$01" ;ZORA_KING = "#$02" ;SICK_KID = "#$04" ;TREE_KID = "#$08" ;SAHASRALA = "#$10" ;CATFISH = "#$20" ;UNUSED = "#$40" ;BOOK_MUDORA = "#$80" ;=SET 2 ;ETHER_TABLET = "#$01" ;BOMBOS_TABLET = "#$02" ;SMITH_SWORD = "#$04" ;FAIRY_SWORD = "#$08" ;MUSHROOM = "#$10" ;POWDER = "#$20" ;UNUSED = "#$40" ;MAGIC_BAT = "#$80" ;-------------------------------------------------------------------------------- !NPC_FLAGS = "$7EF410" !NPC_FLAGS_2 = "$7EF411" ItemCheck_FairySword: LDA !NPC_FLAGS_2 : AND.b #$08 RTL ItemCheck_SmithSword: LDA !NPC_FLAGS_2 : AND.b #$04 RTL ItemCheck_MagicBat: LDA !NPC_FLAGS_2 : AND.b #$80 RTL ItemCheck_OldMan: LDA !NPC_FLAGS : AND.b #$01 : CMP #$01 RTL ItemCheck_ZoraKing: LDA !NPC_FLAGS : AND.b #$02 RTL ItemCheck_SickKid: LDA !NPC_FLAGS : AND.b #$04 RTL ItemCheck_TreeKid: LDA !NPC_FLAGS : AND.b #$08 ; FluteBoy_Chillin - 73: LDA $7EF34C RTL ItemCheck_TreeKid2: LDA !NPC_FLAGS : AND.b #$08 : LSR #$02 ; FluteAardvark_InitialStateFromFluteState - 225: LDA $7EF34C : AND.b #$03 RTL ItemCheck_TreeKid3: JSL $0DD030 ; FluteAardvark_Draw - thing we wrote over LDA !NPC_FLAGS : AND.b #$08 BEQ .normal BRA .done LDA.b #$05 .normal LDA $0D80, X .done RTL ItemCheck_Sahasrala: LDA !NPC_FLAGS : AND.b #$10 RTL ItemCheck_Library: LDA !NPC_FLAGS : AND.b #$80 RTL ItemCheck_Mushroom: LDA !NPC_FLAGS_2 : ROL #4 ; does the same thing as below ; LDA !NPC_FLAGS_2 : AND.b #$10 : BEQ .clear ; SEC ;RTL ; .clear ; CLC RTL ItemCheck_Powder: LDA !NPC_FLAGS_2 : AND.b #$20 RTL ItemCheck_Catfish: ;LDA CatfishGoodItem : BEQ .junk ;PHX ; LDA CatfishGoodItem+1 : TAX ; LDA $7EF340-1, X ;PLX ;-- ;CMP CatfishGoodItem : !BLT .oursNewer ;.theirsNewer ;LDA #$20 : RTL ; don't give item ;.oursNewers ;LDA #$00 : RTL ; give item ;.junk LDA !NPC_FLAGS : AND.b #$20 RTL ;-------------------------------------------------------------------------------- ItemSet_FairySword: PHA : LDA !NPC_FLAGS_2 : ORA.b #$08 : STA !NPC_FLAGS_2 : PLA RTL ItemSet_SmithSword: PHA : LDA !NPC_FLAGS_2 : ORA.b #$04 : STA !NPC_FLAGS_2 : PLA RTL ItemSet_MagicBat: PHA : LDA !NPC_FLAGS_2 : ORA.b #$80 : STA !NPC_FLAGS_2 : PLA RTL ItemSet_OldMan: JSL.l Link_ReceiveItem ; thing we wrote over PHA : LDA !NPC_FLAGS : ORA.b #$01 : STA !NPC_FLAGS : PLA RTL ItemSet_ZoraKing: ;JSL $1DE1AA ; Sprite_SpawnFlippersItem ; thing we wrote over PHA : LDA !NPC_FLAGS : ORA.b #$02 : STA !NPC_FLAGS : PLA RTL ItemSet_SickKid: JSL.l Link_ReceiveItem ; thing we wrote over PHA : LDA !NPC_FLAGS : ORA.b #$04 : STA !NPC_FLAGS : PLA RTL ItemSet_TreeKid: JSL.l Link_ReceiveItem ; thing we wrote over PHA : LDA !NPC_FLAGS : ORA.b #$08 : STA !NPC_FLAGS : PLA RTL ItemSet_Sahasrala: JSL.l Link_ReceiveItem ; thing we wrote over PHA : LDA !NPC_FLAGS : ORA.b #$10 : STA !NPC_FLAGS : PLA RTL ItemSet_Catfish: ;JSL $00D52D ; GetAnimatedSpriteTile.variable ; thing we wrote over ;JSL.l LoadCatfishItemGFX PHA : LDA !NPC_FLAGS : ORA.b #$20 : STA !NPC_FLAGS : PLA RTL ItemSet_Library: JSL.l Link_ReceiveItem ; thing we wrote over PHA : LDA !NPC_FLAGS : ORA.b #$80 : STA !NPC_FLAGS : PLA RTL ItemSet_Mushroom: PHA LDA !NPC_FLAGS_2 : ORA.b #$10 : STA !NPC_FLAGS_2 LDY $0DA0, X ; Retrieve stored item type BNE + ; if for any reason the item value is 0 reload it, just in case %GetPossiblyEncryptedItem(MushroomItem, SpriteItemValues) : TAY + PLA ;LDY.b #$29 STZ $02E9 ; thing we wrote over - the mushroom is an npc for item purposes apparently RTL ItemSet_Powder: PHA : LDA !NPC_FLAGS_2 : ORA.b #$20 : STA !NPC_FLAGS_2 : PLA RTL ;================================================================================ ;================================================================================ ; Randomize 300 Rupee NPC ;-------------------------------------------------------------------------------- Set300RupeeNPCItem: INC $0D80, X ; thing we wrote over PHA : PHP REP #$20 ; set 16-bit accumulator LDA $A0 ; these are all decimal because i got them that way CMP.w #291 : BNE + %GetPossiblyEncryptedItem(RupeeNPC_MoldormCave, SpriteItemValues) TAY ; load moldorm cave value into Y BRA .done + CMP.w #286 : BNE + %GetPossiblyEncryptedItem(RupeeNPC_NortheastDarkSwampCave, SpriteItemValues) TAY ; load northeast dark swamp cave value into Y BRA .done + LDY.b #$46 ; default to a normal 300 rupees .done PLP : PLA RTL ;================================================================================
PlayerPC: ld a, ITEM_NAME ld [wNameListType], a call SaveScreenTilesToBuffer1 xor a ld [wBagSavedMenuItem], a ld [wParentMenuItem], a ld a, [wFlags_0xcd60] bit 3, a ; accessing player's PC through another PC? jr nz, PlayerPCMenu ; accessing it directly ld a, SFX_TURN_ON_PC call PlaySound ld hl, TurnedOnPC2Text call PrintText PlayerPCMenu: ld hl, wd730 set 6, [hl] ld a, [wParentMenuItem] ld [wCurrentMenuItem], a ld hl, wFlags_0xcd60 set 5, [hl] call LoadScreenTilesFromBuffer2 coord hl, 0, 0 lb bc, 8, 14 call TextBoxBorder call UpdateSprites coord hl, 2, 2 ld de, PlayersPCMenuEntries call PlaceString ld hl, wTopMenuItemY ld a, 2 ld [hli], a ; wTopMenuItemY dec a ld [hli], a ; wTopMenuItemX inc hl inc hl ld a, 3 ld [hli], a ; wMaxMenuItem ld a, A_BUTTON | B_BUTTON ld [hli], a ; wMenuWatchedKeys xor a ld [hl], a ld hl, wListScrollOffset ld [hli], a ; wListScrollOffset ld [hl], a ; wMenuWatchMovingOutOfBounds ld [wPlayerMonNumber], a ld hl, WhatDoYouWantText call PrintText call HandleMenuInput bit 1, a jp nz, ExitPlayerPC call PlaceUnfilledArrowMenuCursor ld a, [wCurrentMenuItem] ld [wParentMenuItem], a and a jp z, PlayerPCWithdraw dec a jp z, PlayerPCDeposit dec a jp z, PlayerPCToss ExitPlayerPC: ld a, [wFlags_0xcd60] bit 3, a ; accessing player's PC through another PC? jr nz, .next ; accessing it directly ld a, SFX_TURN_OFF_PC call PlaySound call WaitForSoundToFinish .next ld hl, wFlags_0xcd60 res 5, [hl] call LoadScreenTilesFromBuffer2 xor a ld [wListScrollOffset], a ld [wBagSavedMenuItem], a ld hl, wd730 res 6, [hl] xor a ld [wDoNotWaitForButtonPressAfterDisplayingText], a ret PlayerPCDeposit: xor a ld [wCurrentMenuItem], a ld [wListScrollOffset], a ld a, [wNumBagItems] and a jr nz, .loop ld hl, NothingToDepositText call PrintText jp PlayerPCMenu .loop ld hl, WhatToDepositText call PrintText ld hl, wNumBagItems ld a, l ld [wListPointer], a ld a, h ld [wListPointer + 1], a xor a ld [wPrintItemPrices], a ld a, ITEMLISTMENU ld [wListMenuID], a call DisplayListMenuID jp c, PlayerPCMenu call IsKeyItem ld a, 1 ld [wItemQuantity], a ld a, [wIsKeyItem] and a jr nz, .next ; if it's not a key item, there can be more than one of the item ld hl, DepositHowManyText call PrintText call DisplayChooseQuantityMenu cp $ff jp z, .loop .next ld hl, wNumBoxItems call AddItemToInventory jr c, .roomAvailable ld hl, NoRoomToStoreText call PrintText jp .loop .roomAvailable ld hl, wNumBagItems call RemoveItemFromInventory call WaitForSoundToFinish ld a, SFX_WITHDRAW_DEPOSIT call PlaySound call WaitForSoundToFinish ld hl, ItemWasStoredText call PrintText jp .loop PlayerPCWithdraw: xor a ld [wCurrentMenuItem], a ld [wListScrollOffset], a ld a, [wNumBoxItems] and a jr nz, .loop ld hl, NothingStoredText call PrintText jp PlayerPCMenu .loop ld hl, WhatToWithdrawText call PrintText ld hl, wNumBoxItems ld a, l ld [wListPointer], a ld a, h ld [wListPointer + 1], a xor a ld [wPrintItemPrices], a ld a, ITEMLISTMENU ld [wListMenuID], a call DisplayListMenuID jp c, PlayerPCMenu call IsKeyItem ld a, 1 ld [wItemQuantity], a ld a, [wIsKeyItem] and a jr nz, .next ; if it's not a key item, there can be more than one of the item ld hl, WithdrawHowManyText call PrintText call DisplayChooseQuantityMenu cp $ff jp z, .loop .next ld hl, wNumBagItems call AddItemToInventory jr c, .roomAvailable ld hl, CantCarryMoreText call PrintText jp .loop .roomAvailable ld hl, wNumBoxItems call RemoveItemFromInventory call WaitForSoundToFinish ld a, SFX_WITHDRAW_DEPOSIT call PlaySound call WaitForSoundToFinish ld hl, WithdrewItemText call PrintText jp .loop PlayerPCToss: xor a ld [wCurrentMenuItem], a ld [wListScrollOffset], a ld a, [wNumBoxItems] and a jr nz, .loop ld hl, NothingStoredText call PrintText jp PlayerPCMenu .loop ld hl, WhatToTossText call PrintText ld hl, wNumBoxItems ld a, l ld [wListPointer], a ld a, h ld [wListPointer + 1], a xor a ld [wPrintItemPrices], a ld a, ITEMLISTMENU ld [wListMenuID], a push hl call DisplayListMenuID pop hl jp c, PlayerPCMenu push hl call IsKeyItem pop hl ld a, 1 ld [wItemQuantity], a ld a, [wIsKeyItem] and a jr nz, .next ld a, [wcf91] call IsItemHM jr c, .next ; if it's not a key item, there can be more than one of the item push hl ld hl, TossHowManyText call PrintText call DisplayChooseQuantityMenu pop hl cp $ff jp z, .loop .next call TossItem ; disallows tossing key items jp .loop PlayersPCMenuEntries: db "WITHDRAW ITEM" next "DEPOSIT ITEM" next "TOSS ITEM" next "LOG OFF@" TurnedOnPC2Text: TX_FAR _TurnedOnPC2Text db "@" WhatDoYouWantText: TX_FAR _WhatDoYouWantText db "@" WhatToDepositText: TX_FAR _WhatToDepositText db "@" DepositHowManyText: TX_FAR _DepositHowManyText db "@" ItemWasStoredText: TX_FAR _ItemWasStoredText db "@" NothingToDepositText: TX_FAR _NothingToDepositText db "@" NoRoomToStoreText: TX_FAR _NoRoomToStoreText db "@" WhatToWithdrawText: TX_FAR _WhatToWithdrawText db "@" WithdrawHowManyText: TX_FAR _WithdrawHowManyText db "@" WithdrewItemText: TX_FAR _WithdrewItemText db "@" NothingStoredText: TX_FAR _NothingStoredText db "@" CantCarryMoreText: TX_FAR _CantCarryMoreText db "@" WhatToTossText: TX_FAR _WhatToTossText db "@" TossHowManyText: TX_FAR _TossHowManyText db "@"
; DV3 Directory Buffer Handling V3.00  1992 Tony Tebby section dv3 xdef dv3_drnew xdef dv3_drloc xdef dv3_drupd xref dv3_sbloc xref dv3_sbnew xref dv3_a1upd include 'dev8_dv3_keys' include 'dev8_keys_err' include 'dev8_mac_assert' ;+++ ; DV3 allocate a new directory block for extending the directory. ; ; d5 c p directory sector ; d7 c p drive number ; a0 c p channel block ; a2 r pointer to buffer ; a3 c p linkage block ; a4 c p definition block ; a5 c p pointer to map ; ; status return standard ;--- dv3_drnew ddn.reg reg d1/d2/d3/d6/a1 movem.l ddn.reg,-(sp) move.l d3c_sdid(a0),d6 move.l d5,d3 ; sector number divu ddf_asect(a4),d3 ; this can deal with group up to 65535 moveq #0,d2 move.w d3,d2 moveq #0,d0 ; no current group *** we could look at sdsb cmp.l d3,d2 ; first sector of group? bne.s ddn_loc ; ... no, locate group jsr ddf_salloc(a4) ; ... yes, allocate bge.s ddn_new bra.s ddn_exit ddn_loc jsr ddf_slocate(a4) ; locate group blt.s ddn_exit ddn_new move.w d0,d3 ; drive sector / group lea d3c_sdsb(a0),a2 jsr dv3_sbnew ; find new slave block ddn_exit movem.l (sp)+,ddn.reg rts ;+++ ; DV3 locate a directory buffer. ; ; d5 c p directory sector ; d7 c p drive number ; a0 c p channel block ; a2 r pointer to buffer ; a3 c p linkage block ; a4 c p definition block ; a5 c p pointer to map ; ; status return standard ;--- dv3_drloc movem.l ddn.reg,-(sp) move.l d3c_sdid(a0),d6 lea d3c_sdsb(a0),a2 jsr dv3_sbloc ; locate slave block ble.s dlc_exit move.l d5,d3 ; sector number divu ddf_asect(a4),d3 ; this can deal with group up to 65535 moveq #0,d2 move.w d3,d2 moveq #0,d0 ; no current group *** we could look at sb jsr ddf_slocate(a4) ; locate group blt.s dlc_exit move.w d0,d3 ; drive sector / group lea d3c_sdsb(a0),a2 jsr dv3_sbnew ; find new slave block addq.b #sbt.read-sbt.true,sbt_stat(a1) ; read requested jsr ddl_slbfill(a3) ; read sector dlc_exit movem.l (sp)+,ddn.reg rts ;+++ ; DV3 mark a directory buffer updated. ; ; d7 c p drive number ; a0 c p channel block ; a3 c p linkage block ; a4 c p definition block ; a5 c p pointer to map ; ; all registers preserved ; status according to d0 ;--- dv3_drupd move.l a1,-(sp) move.l d3c_sdsb(a0),a1 jsr dv3_a1upd move.l (sp)+,a1 rts end
; A089781: Successive coprime numbers with distinct successive differences: gcd(a(k+1),a(k)) = gcd(a(m+1),a(m)) = 1 and a(k+1)-a(k) = a(m+1)-a(m) <==> m=k. ; 1,2,5,7,11,16,23,29,37,46,57,67,79,92,107,121,137,154,173,191,211,232,255,277,301,326,353,379,407,436,467,497,529,562,597,631,667,704,743,781,821,862,905,947,991,1036,1083,1129,1177,1226,1277,1327,1379,1432,1487,1541,1597,1654,1713,1771,1831,1892,1955,2017,2081,2146,2213,2279,2347,2416,2487,2557,2629,2702,2777,2851,2927,3004,3083,3161,3241,3322,3405,3487,3571,3656,3743,3829,3917,4006,4097,4187,4279,4372,4467,4561,4657,4754,4853,4951,5051,5152,5255,5357,5461,5566,5673,5779,5887,5996,6107,6217,6329,6442,6557,6671,6787,6904,7023,7141,7261,7382,7505,7627,7751,7876,8003,8129,8257,8386,8517,8647,8779,8912,9047,9181,9317,9454,9593,9731,9871,10012,10155,10297,10441,10586,10733,10879,11027,11176,11327,11477,11629,11782,11937,12091,12247,12404,12563,12721,12881,13042,13205,13367,13531,13696,13863,14029,14197,14366,14537,14707,14879,15052,15227,15401,15577,15754,15933,16111,16291,16472,16655,16837,17021,17206,17393,17579,17767,17956,18147,18337,18529,18722,18917,19111,19307,19504,19703,19901,20101,20302,20505,20707,20911,21116,21323,21529,21737,21946,22157,22367,22579,22792,23007,23221,23437,23654,23873,24091,24311,24532,24755,24977,25201,25426,25653,25879,26107,26336,26567,26797,27029,27262,27497,27731,27967,28204,28443,28681,28921,29162,29405,29647,29891,30136,30383,30629,30877,31126 mov $2,$0 add $2,1 mov $6,$0 lpb $2,1 mov $0,$6 sub $2,1 sub $0,$2 mov $8,2 mov $9,$0 lpb $8,1 sub $8,1 add $0,$8 sub $0,1 mov $3,$0 pow $3,2 mod $3,8 trn $3,2 mov $7,$0 pow $7,2 add $3,$7 mul $3,8 mov $4,$3 mov $5,$8 lpb $5,1 sub $5,1 mov $10,$4 lpe lpe lpb $9,1 mov $9,0 sub $10,$4 lpe mov $4,$10 div $4,16 add $4,1 add $1,$4 lpe
<% from pwnlib.shellcraft import common from pwnlib.shellcraft.mips.linux import fork, exit %> <%page args=""/> <%docstring> Attempts to fork. If the fork is successful, the parent exits. </%docstring> <% dont_exit = common.label('forkexit') %> ${fork()} blez $v0, ${dont_exit} ${exit(0)} ${dont_exit}:
.global s_prepare_buffers s_prepare_buffers: push %r14 push %r8 push %rax push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x1840e, %rdx nop nop nop nop dec %rbp movb $0x61, (%rdx) nop nop nop cmp %r14, %r14 lea addresses_UC_ht+0xa64e, %rsi lea addresses_D_ht+0x19f76, %rdi nop nop nop sub %r8, %r8 mov $33, %rcx rep movsl nop and %rcx, %rcx lea addresses_D_ht+0xd00e, %rsi lea addresses_WT_ht+0x268e, %rdi nop nop nop add %rdx, %rdx mov $92, %rcx rep movsq nop nop cmp $34082, %rax lea addresses_A_ht+0x15e0e, %rsi nop nop nop nop nop dec %rcx mov (%rsi), %r8 nop nop nop cmp %rsi, %rsi lea addresses_WT_ht+0x1520e, %rsi lea addresses_D_ht+0x280e, %rdi and $5499, %rbp mov $1, %rcx rep movsl nop xor %rax, %rax lea addresses_D_ht+0x17f0e, %rdi nop nop nop nop cmp $37997, %rcx movb (%rdi), %dl nop nop nop nop xor $33089, %rax lea addresses_WC_ht+0xfa0e, %rax nop nop nop inc %r8 mov (%rax), %ecx nop nop nop nop nop add %rax, %rax pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %rax pop %r8 pop %r14 ret .global s_faulty_load s_faulty_load: push %r12 push %r15 push %r9 push %rbp push %rcx push %rdi push %rdx // Store lea addresses_normal+0x1fe76, %rcx nop nop nop nop nop cmp %rbp, %rbp mov $0x5152535455565758, %r9 movq %r9, (%rcx) nop nop nop nop cmp $63574, %r9 // Store lea addresses_D+0x430e, %r9 nop nop and $14728, %rcx mov $0x5152535455565758, %rdi movq %rdi, (%r9) nop nop nop nop and %r9, %r9 // Store lea addresses_UC+0x2d8e, %r12 nop nop nop inc %rdx mov $0x5152535455565758, %r9 movq %r9, %xmm2 vmovntdq %ymm2, (%r12) nop nop nop inc %r15 // Faulty Load lea addresses_WC+0x1a00e, %r9 nop nop nop nop sub %r15, %r15 movups (%r9), %xmm0 vpextrq $0, %xmm0, %rbp lea oracles, %r12 and $0xff, %rbp shlq $12, %rbp mov (%r12,%rbp,1), %rbp pop %rdx pop %rdi pop %rcx pop %rbp pop %r9 pop %r15 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 2, 'size': 8, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'congruent': 6, 'size': 8, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 5, 'size': 32, 'same': False, 'NT': True}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 10, 'size': 1, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 9, 'size': 8, 'same': True, 'NT': True}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': True}, 'dst': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 7, 'size': 1, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 9, 'size': 4, 'same': False, 'NT': 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 */
; A158129: 100n^2 - 2n. ; 98,396,894,1592,2490,3588,4886,6384,8082,9980,12078,14376,16874,19572,22470,25568,28866,32364,36062,39960,44058,48356,52854,57552,62450,67548,72846,78344,84042,89940,96038,102336,108834,115532,122430,129528,136826,144324,152022,159920,168018,176316,184814,193512,202410,211508,220806,230304,240002,249900,259998,270296,280794,291492,302390,313488,324786,336284,347982,359880,371978,384276,396774,409472,422370,435468,448766,462264,475962,489860,503958,518256,532754,547452,562350,577448,592746,608244,623942,639840,655938,672236,688734,705432,722330,739428,756726,774224,791922,809820,827918,846216,864714,883412,902310,921408,940706,960204,979902,999800 mov $1,5 mov $2,$0 add $2,1 mul $2,2 mul $1,$2 pow $1,2 sub $1,$2 mov $0,$1
;------------------------------------------------------------------------------- ; dabort.asm ; ; Copyright (C) 2009-2016 Texas Instruments Incorporated - www.ti.com ; ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions ; are met: ; ; Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; ; Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in the ; documentation and/or other materials provided with the ; distribution. ; ; Neither the name of Texas Instruments Incorporated nor the names of ; its contributors may be used to endorse or promote products derived ; from this software without specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ; ; ; .text .arm ;------------------------------------------------------------------------------- ; Run Memory Test .ref custom_dabort .def _dabort .asmfunc _dabort stmfd r13!, {r0 - r12, lr}; push registers and link register on to stack ldr r12, esmsr3 ; ESM Group3 status register ldr r0, [r12] tst r0, #0x8 ; check if bit 3 is set, this indicates uncorrectable ECC error on B0TCM bne ramErrorFound tst r0, #0x20 ; check if bit 5 is set, this indicates uncorrectable ECC error on B1TCM bne ramErrorFound2 noRAMerror tst r0, #0x80 ; check if bit 7 is set, this indicates uncorrectable ECC error on ATCM bne flashErrorFound bl custom_dabort ; custom data abort handler required ; If this custom handler is written in assembly, all registers used in the routine ; and the link register must be saved on to the stack upon entry, and restored before ; return from the routine. ldmfd r13!, {r0 - r12, lr}; pop registers and link register from stack subs pc, lr, #8 ; restore state of CPU when abort occurred, and branch back to instruction that was aborted ramErrorFound ldr r1, ramctrl ; RAM control register for B0TCM TCRAMW ldr r2, [r1] tst r2, #0x100 ; check if bit 8 is set in RAMCTRL, this indicates ECC memory write is enabled beq ramErrorReal mov r2, #0x20 str r2, [r1, #0x10] ; clear RAM error status register mov r2, #0x08 str r2, [r12] ; clear ESM group3 channel3 flag for uncorrectable RAM ECC errors mov r2, #5 str r2, [r12, #0x18] ; The nERROR pin will become inactive once the LTC counter expires ldmfd r13!, {r0 - r12, lr} subs pc, lr, #4 ; branch to instruction after the one that caused the abort ; this is the case because the data abort was caused intentionally ; and we do not want to cause the same data abort again. ramErrorFound2 ldr r1, ram2ctrl ; RAM control register for B1TCM TCRAMW ldr r2, [r1] tst r2, #0x100 ; check if bit 8 is set in RAMCTRL, this indicates ECC memory write is enabled beq ramErrorReal mov r2, #0x20 str r2, [r1, #0x10] ; clear RAM error status register mov r2, #0x20 str r2, [r12] ; clear ESM group3 flags channel5 flag for uncorrectable RAM ECC errors mov r2, #5 str r2, [r12, #0x18] ; The nERROR pin will become inactive once the LTC counter expires ldmfd r13!, {r0 - r12, lr} subs pc, lr, #4 ; branch to instruction after the one that caused the abort ; this is the case because the data abort was caused intentionally ; and we do not want to cause the same data abort again. ramErrorReal b ramErrorReal ; branch here forever as continuing operation is not recommended flashErrorFound ldr r1, flashbase ldr r2, [r1, #0x6C] ; read FDIAGCTRL register mov r2, r2, lsr #16 tst r2, #5 ; check if bits 19:16 are 5, this indicates diagnostic mode is enabled beq flashErrorReal mov r2, #1 mov r2, r2, lsl #8 str r2, [r1, #0x1C] ; clear FEDACSTATUS error flag mov r2, #0x80 str r2, [r12] ; clear ESM group3 flag for uncorrectable flash ECC error mov r2, #5 str r2, [r12, #0x18] ; The nERROR pin will become inactive once the LTC counter expires ldmfd r13!, {r0 - r12, lr} subs pc, lr, #4 ; branch to instruction after the one that caused the abort ; this is the case because the data abort was caused intentionally ; and we do not want to cause the same data abort again. flashErrorReal b flashErrorReal ; branch here forever as continuing operation is not recommended esmsr3 .word 0xFFFFF520 ramctrl .word 0xFFFFF800 ram2ctrl .word 0xFFFFF900 ram1errstat .word 0xFFFFF810 ram2errstat .word 0xFFFFF910 flashbase .word 0xFFF87000 .endasmfunc
* Find job information V0.0  1985 Tony Tebby QJUMP * section utils * xdef ut_fjob find a job (given the name) xdef ut_jinf get job information * xref ut_cnmar compare absolute and relative names * include dev8_sbsext_ext_keys * ut_fjob moveq #0,d1 start from job 0 utj_loop move.l a1,-(sp) save name pointer bsr.s ut_jinf get Job information move.l (sp)+,a1 bne.s ut_fjob ... oops, try again cmp.w #$4afb,(a0)+ check flag bne.s utj_cknx bsr.l ut_cnmar compare names beq.s utj_rts ... name found utj_cknx move.l d5,d1 restore next job id bne.s utj_loop ... and check name of next job moveq #err.nj,d0 job not found utj_rts rts * ut_jinf move.l d1,d4 save Job ID moveq #mt.jinf,d0 get Job information moveq #0,d2 scan whole tree trap #1 move.l d1,d5 save next Job ID addq.l #6,a0 move to flag tst.l d0 check errors rts end
; A070707: n^7 mod 26. ; 0,1,24,3,4,21,20,19,18,9,10,15,12,13,14,11,16,17,8,7,6,5,22,23,2,25,0,1,24,3,4,21,20,19,18,9,10,15,12,13,14,11,16,17,8,7,6,5,22,23,2,25,0,1,24,3,4,21,20,19,18,9,10,15,12,13,14,11,16,17,8,7,6,5,22,23,2,25,0,1 pow $0,7 mod $0,26 mov $1,$0
; ; Game device library for the PC6001 ; SECTION code_clib PUBLIC joystick PUBLIC _joystick EXTERN get_psg .joystick ._joystick ;__FASTCALL__ : joystick no. in HL ld a,14 dec l jr z,got_port inc a dec l jr z,got_port ld hl,0 ret got_port: ld l,a call get_psg ;Exits with a = value ld hl,0 cpl rra ;UP rl l rra ;DOWN rl l rra ;LEFT rl l rra ;RIGHT rl l rra jr nc,not_fire1 set 4,l not_fire1: rra ret nc set 5,l ret
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r15 push %r8 push %rbp push %rcx push %rdi push %rsi lea addresses_D_ht+0x473d, %r8 and %r13, %r13 mov $0x6162636465666768, %rbp movq %rbp, %xmm6 vmovups %ymm6, (%r8) nop nop nop nop add $57373, %rsi lea addresses_D_ht+0x1176d, %r11 nop nop nop and %rdi, %rdi mov $0x6162636465666768, %r15 movq %r15, %xmm5 vmovups %ymm5, (%r11) nop nop nop nop nop inc %r15 lea addresses_D_ht+0x59bd, %rdi nop nop mfence mov $0x6162636465666768, %r8 movq %r8, %xmm5 and $0xffffffffffffffc0, %rdi vmovntdq %ymm5, (%rdi) nop nop nop nop nop sub %r11, %r11 lea addresses_WC_ht+0x6aa, %r13 nop nop nop nop nop sub %r8, %r8 mov (%r13), %rsi nop nop nop nop cmp %rsi, %rsi lea addresses_UC_ht+0x1426d, %rbp nop cmp %rsi, %rsi movb $0x61, (%rbp) nop nop nop mfence lea addresses_A_ht+0x16ce2, %rsi nop nop nop nop xor $9265, %r8 mov $0x6162636465666768, %r15 movq %r15, %xmm5 vmovups %ymm5, (%rsi) cmp %rsi, %rsi lea addresses_A_ht+0x883d, %rsi lea addresses_normal_ht+0x403d, %rdi nop nop nop nop nop sub $2632, %r13 mov $86, %rcx rep movsb nop cmp $698, %rsi lea addresses_normal_ht+0x145a, %rsi nop nop xor %r13, %r13 movb (%rsi), %r11b nop nop nop add $40678, %r11 lea addresses_UC_ht+0xd629, %r15 nop inc %rdi mov (%r15), %si nop nop and %r13, %r13 pop %rsi pop %rdi pop %rcx pop %rbp pop %r8 pop %r15 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r13 push %r14 push %r15 push %r9 push %rax push %rbp push %rdi // Store lea addresses_normal+0x18d3d, %rax xor $48757, %r14 mov $0x5152535455565758, %r15 movq %r15, %xmm4 vmovups %ymm4, (%rax) inc %r15 // Store lea addresses_normal+0x263d, %rbp nop nop cmp $25432, %r9 mov $0x5152535455565758, %r14 movq %r14, %xmm0 movups %xmm0, (%rbp) and $25869, %r9 // Faulty Load lea addresses_normal+0x1763d, %r14 nop nop nop nop xor %r15, %r15 mov (%r14), %rdi lea oracles, %r9 and $0xff, %rdi shlq $12, %rdi mov (%r9,%rdi,1), %rdi pop %rdi pop %rbp pop %rax pop %r9 pop %r15 pop %r14 pop %r13 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 8, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 11, 'size': 16, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 8, 'size': 32, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 4, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 6, 'size': 32, 'same': False, 'NT': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 4, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 2, 'size': 2, 'same': False, 'NT': False}} {'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 */
/* * MIT License * * Copyright (c) 2021 KhoaTran Programmer * * 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. */ /****************************************************************************** * PURPOSE * ****************************************************************************** * This file implements for header of History processing * *****************************************************************************/ /****************************************************************************** * VERSION HISTORY * ****************************************************************************** * [1.0.0] * * Dec-01-2021: Initial version * * - Support addWordToHistory/readHistory/deleteHistory * *****************************************************************************/ #include "CWD_HistoryDatabase.h" CWD_HistoryDatabase::CWD_HistoryDatabase() { } void CWD_HistoryDatabase::addWordToHistory(QString simplifyChi, QString traditionalChi, QString definition, QString engdef, QString vietdef) { QFile file("history_data.txt"); if (!file.open(QIODevice::ReadWrite)) { return; } QTextStream out(&file); QString cur_line; // Read all lines out.readAll(); out << traditionalChi << "\t" << simplifyChi << "\t" << definition << "\t" << engdef << "\t" << vietdef << endl; file.close(); } QString CWD_HistoryDatabase::readHistory() { QFile file("history_data.txt"); QString result = ""; if (!file.open(QIODevice::ReadOnly)) { return result; } else { QTextStream in(&file); result = in.readAll(); file.close(); } return result; } void CWD_HistoryDatabase::deleteHistory() { QFile file("history_data.txt"); file.remove(); }
// // Boost.Pointer Container // // Copyright Thorsten Ottosen 2003-2005. Use, modification and // distribution is subject to 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) // // For more information, see http://www.boost.org/libs/ptr_container/ // #ifndef BOOST_ptr_container_PTR_SEQUENCE_ADAPTER_HPP #define BOOST_ptr_container_PTR_SEQUENCE_ADAPTER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif #include <boost/ptr_container/detail/reversible_ptr_container.hpp> #include <boost/ptr_container/indirect_fun.hpp> #include <boost/ptr_container/detail/void_ptr_iterator.hpp> #include <boost/range/reverse_iterator.hpp> #include <boost/range/const_reverse_iterator.hpp> #include <boost/type_traits/remove_pointer.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/type_traits/is_pointer.hpp> #include <boost/type_traits/is_integral.hpp> #include <boost/iterator/iterator_categories.hpp> namespace boost { namespace ptr_container_detail { template < class T, class VoidPtrSeq > struct sequence_config { typedef BOOST_DEDUCED_TYPENAME remove_nullable<T>::type U; typedef VoidPtrSeq void_container_type; typedef BOOST_DEDUCED_TYPENAME VoidPtrSeq::allocator_type allocator_type; typedef U value_type; typedef void_ptr_iterator< BOOST_DEDUCED_TYPENAME VoidPtrSeq::iterator, U > iterator; typedef void_ptr_iterator< BOOST_DEDUCED_TYPENAME VoidPtrSeq::const_iterator, const U > const_iterator; typedef void_ptr_iterator< BOOST_DEDUCED_TYPENAME VoidPtrSeq::reverse_iterator, U > reverse_iterator; typedef void_ptr_iterator< BOOST_DEDUCED_TYPENAME VoidPtrSeq::const_reverse_iterator, const U > const_reverse_iterator; typedef value_type object_type; #ifdef BOOST_NO_SFINAE template< class Iter > static U* get_pointer( Iter i ) { return static_cast<U*>( *i.base() ); } #else template< class Iter > static U* get_pointer( void_ptr_iterator<Iter,U> i ) { return static_cast<U*>( *i.base() ); } template< class Iter > static U* get_pointer( Iter i ) { return &*i; } #endif #if defined(BOOST_NO_SFINAE) && !BOOST_WORKAROUND(__MWERKS__, <= 0x3003) template< class Iter > static const U* get_const_pointer( Iter i ) { return static_cast<const U*>( *i.base() ); } #else // BOOST_NO_SFINAE #if BOOST_WORKAROUND(__MWERKS__, <= 0x3003) template< class Iter > static const U* get_const_pointer( void_ptr_iterator<Iter,U> i ) { return static_cast<const U*>( *i.base() ); } #else // BOOST_WORKAROUND template< class Iter > static const U* get_const_pointer( void_ptr_iterator<Iter,const U> i ) { return static_cast<const U*>( *i.base() ); } #endif // BOOST_WORKAROUND template< class Iter > static const U* get_const_pointer( Iter i ) { return &*i; } #endif // BOOST_NO_SFINAE BOOST_STATIC_CONSTANT(bool, allow_null = boost::is_nullable<T>::value ); }; } // ptr_container_detail template< class Iterator, class T > inline bool is_null( void_ptr_iterator<Iterator,T> i ) { return *i.base() == 0; } template < class T, class VoidPtrSeq, class CloneAllocator = heap_clone_allocator > class ptr_sequence_adapter : public ptr_container_detail::reversible_ptr_container< ptr_container_detail::sequence_config<T,VoidPtrSeq>, CloneAllocator > { typedef ptr_container_detail::reversible_ptr_container< ptr_container_detail::sequence_config<T,VoidPtrSeq>, CloneAllocator > base_type; typedef BOOST_DEDUCED_TYPENAME base_type::scoped_deleter scoped_deleter; typedef ptr_sequence_adapter<T,VoidPtrSeq,CloneAllocator> this_type; public: typedef BOOST_DEDUCED_TYPENAME base_type::value_type value_type; typedef BOOST_DEDUCED_TYPENAME base_type::reference reference; typedef BOOST_DEDUCED_TYPENAME base_type::auto_type auto_type; BOOST_PTR_CONTAINER_DEFINE_CONSTRUCTORS( ptr_sequence_adapter, base_type ) template< class PtrContainer > ptr_sequence_adapter( std::auto_ptr<PtrContainer> clone ) : base_type( clone ) { } template< class PtrContainer > void operator=( std::auto_ptr<PtrContainer> clone ) { base_type::operator=( clone ); } ///////////////////////////////////////////////////////////// // modifiers ///////////////////////////////////////////////////////////// void push_back( value_type x ) // strong { this->enforce_null_policy( x, "Null pointer in 'push_back()'" ); auto_type ptr( x ); // notrow this->c_private().push_back( x ); // strong, commit ptr.release(); // nothrow } void push_front( value_type x ) { this->enforce_null_policy( x, "Null pointer in 'push_front()'" ); auto_type ptr( x ); // nothrow this->c_private().push_front( x ); // strong, commit ptr.release(); // nothrow } auto_type pop_back() { if( this->empty() ) throw bad_ptr_container_operation( "'pop_back()' " " on empty container" ); auto_type ptr( static_cast<value_type>( this->c_private().back() ) ); // nothrow this->c_private().pop_back(); // nothrow return ptr_container_detail::move( ptr ); // nothrow } auto_type pop_front() { if( this->empty() ) throw bad_ptr_container_operation( "'pop_front()' on" " empty container" ); auto_type ptr( static_cast<value_type>( this->c_private().front() ) ); // nothrow this->c_private().pop_front(); // nothrow return ptr_container_detail::move( ptr ); } reference front() { if( this->empty() ) throw bad_ptr_container_operation( "accessing 'front()' on empty container" ); BOOST_ASSERT( !::boost::is_null( this->begin() ) ); return *this->begin(); } const_reference front() const { if( this->empty() ) throw bad_ptr_container_operation( "accessing 'front()' on empty container" ); BOOST_ASSERT( !::boost::is_null( this->begin() ) ); return *this->begin(); } reference back() { if( this->empty() ) throw bad_ptr_container_operation( "accessing 'back()' on empty container" ); BOOST_ASSERT( !::boost::is_null( --this->end() ) ); return *--this->end(); } const_reference back() const { if( this->empty() ) throw bad_ptr_container_operation( "accessing 'back()' on empty container" ); BOOST_ASSERT( !::boost::is_null( --this->end() ) ); return *--this->end(); } public: // deque/vector inerface reference operator[]( size_type n ) // nothrow { BOOST_ASSERT( n < this->size() ); BOOST_ASSERT( !this->is_null( n ) ); return *static_cast<value_type>( this->c_private()[n] ); } const_reference operator[]( size_type n ) const // nothrow { BOOST_ASSERT( n < this->size() ); BOOST_ASSERT( !this->is_null( n ) ); return *static_cast<value_type>( this->c_private()[n] ); } reference at( size_type n ) { if( n >= this->size() ) throw bad_index( "'at()' out of bounds" ); BOOST_ASSERT( !this->is_null( n ) ); return (*this)[n]; } const_reference at( size_type n ) const { if( n >= this->size() ) throw bad_index( "'at()' out of bounds" ); BOOST_ASSERT( !this->is_null( n ) ); return (*this)[n]; } public: // vector interface size_type capacity() const { return this->c_private().capacity(); } void reserve( size_type n ) { this->c_private().reserve( n ); } void reverse() { this->c_private().reverse(); } public: // assign, insert, transfer // overhead: 1 heap allocation (very cheap compared to cloning) template< class InputIterator > void assign( InputIterator first, InputIterator last ) // strong { //#ifdef BOOST_NO_SFINAE //#else // BOOST_STATIC_ASSERT(( boost::is_convertible< typename iterator_reference<InputIterator>::type, // reference_type >::value )); //#endif base_type temp( first, last ); this->swap( temp ); } template< class Range > void assign( const Range& r ) { assign( this->adl_begin(r), this->adl_end(r ) ); } private: template< class I > void insert_impl( iterator before, I first, I last, std::input_iterator_tag ) // strong { ptr_sequence_adapter temp(first,last); // strong transfer( before, temp ); // strong, commit } template< class I > void insert_impl( iterator before, I first, I last, std::forward_iterator_tag ) // strong { if( first == last ) return; scoped_deleter sd( first, last ); // strong this->insert_clones_and_release( sd, before ); // strong, commit } public: using base_type::insert; template< class InputIterator > void insert( iterator before, InputIterator first, InputIterator last ) // strong { insert_impl( before, first, last, BOOST_DEDUCED_TYPENAME iterator_category<InputIterator>::type() ); } #ifdef BOOST_NO_SFINAE #else template< class Range > BOOST_DEDUCED_TYPENAME boost::disable_if< ptr_container_detail::is_pointer_or_integral<Range> >::type insert( iterator before, const Range& r )// ptr_container_detail::is_range_tag ) { insert( before, this->adl_begin(r), this->adl_end(r) ); } #endif void transfer( iterator before, iterator first, iterator last, ptr_sequence_adapter& from ) // strong { BOOST_ASSERT( &from != this ); if( from.empty() ) return; this->c_private(). insert( before.base(), first.base(), last.base() ); // strong from.c_private().erase( first.base(), last.base() ); // nothrow } void transfer( iterator before, iterator object, ptr_sequence_adapter& from ) // strong { BOOST_ASSERT( &from != this ); if( from.empty() ) return; this->c_private(). insert( before.base(), *object.base() ); // strong from.c_private().erase( object.base() ); // nothrow } #ifdef BOOST_NO_SFINAE #else template< class Range > BOOST_DEDUCED_TYPENAME boost::disable_if< boost::is_same< Range, iterator > >::type transfer( iterator before, const Range& r, ptr_sequence_adapter& from ) // strong { transfer( before, this->adl_begin(r), this->adl_end(r), from ); } #endif void transfer( iterator before, ptr_sequence_adapter& from ) // strong { BOOST_ASSERT( &from != this ); if( from.empty() ) return; this->c_private(). insert( before.base(), from.begin().base(), from.end().base() ); // strong from.c_private().clear(); // nothrow } public: // null functions bool is_null( size_type idx ) const { BOOST_ASSERT( idx < this->size() ); return this->c_private()[idx] == 0; } public: // algorithms void sort( iterator first, iterator last ) { sort( first, last, std::less<T>() ); } void sort() { sort( this->begin(), this->end() ); } template< class Compare > void sort( iterator first, iterator last, Compare comp ) { BOOST_ASSERT( first <= last && "out of range sort()" ); BOOST_ASSERT( this->begin() <= first && "out of range sort()" ); BOOST_ASSERT( last <= this->end() && "out of range sort()" ); // some static assert on the arguments of the comparison std::sort( first.base(), last.base(), void_ptr_indirect_fun<Compare,T>(comp) ); } template< class Compare > void sort( Compare comp ) { sort( this->begin(), this->end(), comp ); } void unique( iterator first, iterator last ) { unique( first, last, std::equal_to<T>() ); } void unique() { unique( this->begin(), this->end() ); } private: struct is_not_zero_ptr { template< class U > bool operator()( const U* r ) const { return r != 0; } }; void compact_and_erase_nulls( iterator first, iterator last ) // nothrow { typename base_type::ptr_iterator p = std::stable_partition( first.base(), last.base(), is_not_zero_ptr() ); this->c_private().erase( p, this->end().base() ); } void range_check_impl( iterator first, iterator last, std::bidirectional_iterator_tag ) { /* do nothing */ } void range_check_impl( iterator first, iterator last, std::random_access_iterator_tag ) { BOOST_ASSERT( first <= last && "out of range unique()/erase_if()" ); BOOST_ASSERT( this->begin() <= first && "out of range unique()/erase_if()" ); BOOST_ASSERT( last <= this->end() && "out of range unique()/erase_if)(" ); } void range_check( iterator first, iterator last ) { range_check_impl( first, last, BOOST_DEDUCED_TYPENAME iterator_category<iterator>::type() ); } public: template< class Compare > void unique( iterator first, iterator last, Compare comp ) { range_check(first,last); iterator prev = first; iterator next = first; ++next; for( ; next != last; ++next ) { BOOST_ASSERT( !::boost::is_null(prev) ); BOOST_ASSERT( !::boost::is_null(next) ); if( comp( *prev, *next ) ) { this->remove( next ); // delete object *next.base() = 0; // mark pointer as deleted } else { prev = next; } // ++next } compact_and_erase_nulls( first, last ); } template< class Compare > void unique( Compare comp ) { unique( this->begin(), this->end(), comp ); } template< class Pred > void erase_if( iterator first, iterator last, Pred pred ) { range_check(first,last); iterator next = first; for( ; next != last; ++next ) { BOOST_ASSERT( !::boost::is_null(next) ); if( pred( *next ) ) { this->remove( next ); // delete object *next.base() = 0; // mark pointer as deleted } } compact_and_erase_nulls( first, last ); } template< class Pred > void erase_if( Pred pred ) { erase_if( this->begin(), this->end(), pred ); } void merge( iterator first, iterator last, ptr_sequence_adapter& from ) { merge( first, last, from, std::less<T>() ); } template< class BinPred > void merge( iterator first, iterator last, ptr_sequence_adapter& from, BinPred pred ) { void_ptr_indirect_fun<BinPred,T> bin_pred(pred); size_type current_size = this->size(); this->transfer( this->end(), first, last, from ); typename base_type::ptr_iterator middle = this->begin().base(); std::advance(middle,current_size); std::inplace_merge( this->begin().base(), middle, this->end().base(), bin_pred ); } void merge( ptr_sequence_adapter& r ) { merge( r, std::less<T>() ); BOOST_ASSERT( r.empty() ); } template< class BinPred > void merge( ptr_sequence_adapter& r, BinPred pred ) { merge( r.begin(), r.end(), r, pred ); BOOST_ASSERT( r.empty() ); } }; } // namespace 'boost' #endif
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Berkeley Softworks 1990 -- All Rights Reserved PROJECT: PC GEOS MODULE: GrObj FILE: SplineGuardian.asm AUTHOR: Steve Scholl, Jan 9, 1992 ROUTINES: Name Description ---- ----------- SplineGuardianTransformSplinePoints METHODS: Name ---- SplineGuardianInitialize SplineGuardianActivateCreate SplineGuardianCreateVisWard SplineGuardianAnotherToolActivated SplineGuardianSetSplinePointerActiveStatus SplineGuardianLostEditGrab SplineGuardianGainedEditGrab SplineGuardianInvertEditIndicator SplineGuardianGrObjSpecificInitialize SplineGuardianStartSelect SplineGuardianInitToDefaultAttrs SplineGuardianUpdateEditGrabWithStoredData SplineGuardianCompleteCreate SplineGuardianCompleteTransform SplineGuardianEndCreate SplineGuardianEvaluatePARENTPoint SplineGuardianDrawHandlesRaw SplineGuardianDrawFG SplineGuardianDrawBGArea REVISION HISTORY: Name Date Description ---- ---- ----------- Steve 1/ 9/92 Initial revision DESCRIPTION: $Id: splineGuardian.asm,v 1.1 97/04/04 18:08:54 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrObjClassStructures segment resource SplineGuardianClass ;Define the class record GrObjClassStructures ends GrObjSplineGuardianCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianInitialize %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Initialize the class of the vis ward PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 12/ 7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianInitialize method dynamic SplineGuardianClass, MSG_META_INITIALIZE .enter mov di, offset SplineGuardianClass CallSuper MSG_META_INITIALIZE GrObjDeref di,ds,si mov ds:[di].GOVGI_class.segment, segment GrObjSplineClass mov ds:[di].GOVGI_class.offset, offset GrObjSplineClass BitSet ds:[di].GOI_msgOptFlags, GOMOF_SEND_UI_NOTIFICATION ;This prevents pasted spline objects from going into create ;or edit mode on MSG_GO_NOTIFY_GROBJ_VALID and grabbing ;the mouse as a result. ; mov ds:[di].SGI_splineMode,SM_INACTIVE ; All spline objects have the ward control the create ; andnf ds:[di].GOVGI_flags,not mask GOVGF_CREATE_MODE ornf ds:[di].GOVGI_flags, GOVGCM_VIS_WARD_CREATE \ shl offset GOVGF_CREATE_MODE BitSet ds:[di].GOI_msgOptFlags, \ GOMOF_GET_DWF_SELECTION_HANDLE_BOUNDS_FOR_TRIVIAL_REJECT .leave ret SplineGuardianInitialize endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianCreateVisWard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Do a spline intialize on the ward PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass RETURN: ^lcx:dx - newly created ward DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 5/20/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianCreateVisWard method dynamic SplineGuardianClass, MSG_GOVG_CREATE_VIS_WARD .enter ; Call our superclass so that the we have a ward ; that we can intialize ; mov di,offset SplineGuardianClass call ObjCallSuperNoLock push dx ;save ward chunk mov ax,MSG_SPLINE_INITIALIZE clr dx ;no params mov di,mask MF_FIXUP_DS call GrObjVisGuardianMessageToVisWard pop dx ;^lcx:dx <- ward .leave ret SplineGuardianCreateVisWard endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianInitCreate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Intialize objects instance data to a zero size object, with no rotation and flipping, at the point passed so that it can be interactively dragged open. PASS: *(ds:si) - instance data ds:[bx] - instance data of object ds:[di] - master part of object (if any) ss:bp - PointDWFixed - location to start create from RETURN: nothing DESTROYED: WARNING: May cause block to move and/or chunk to move within block PSEUDO CODE/STRATEGY: nothing KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 11/16/89 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianInitCreate method dynamic SplineGuardianClass, MSG_GO_INIT_CREATE uses ax,cx,dx,bp .enter ; Get default attributes from body. Must do attributes ; before initializing basic data because the visible ; bounds of objects with line attributes are affected ; by the line width ; mov ax,MSG_GO_INIT_TO_DEFAULT_ATTRS call ObjCallInstanceNoLock mov bx,bp ;PointDWFixed stack frame sub sp,size BasicInit mov bp,sp ; Set center to passed PointDWFixed ; mov ax,ss:[bx].PDF_x.DWF_int.high mov ss:[bp].BI_center.PDF_x.DWF_int.high,ax mov ax,ss:[bx].PDF_x.DWF_int.low mov ss:[bp].BI_center.PDF_x.DWF_int.low,ax mov ax,ss:[bx].PDF_x.DWF_frac mov ss:[bp].BI_center.PDF_x.DWF_frac,ax mov ax,ss:[bx].PDF_y.DWF_int.high mov ss:[bp].BI_center.PDF_y.DWF_int.high,ax mov ax,ss:[bx].PDF_y.DWF_int.low mov ss:[bp].BI_center.PDF_y.DWF_int.low,ax mov ax,ss:[bx].PDF_y.DWF_frac mov ss:[bp].BI_center.PDF_y.DWF_frac,ax ; Set GrObj dimensions at 1 by 1 ; mov bx,1 clr ax mov ss:[bp].BI_width.low,ax mov ss:[bp].BI_height.low,ax mov ss:[bp].BI_width.high,bx mov ss:[bp].BI_height.high,bx push ds,si segmov ds,ss,si mov si,bp add si, offset BI_transform call GrObjGlobalInitGrObjTransMatrix pop ds,si ; Send method to initialize basic data ; and then clear stack frame ; mov ax,MSG_GO_INIT_BASIC_DATA call ObjCallInstanceNoLock add sp,size BasicInit .leave ret SplineGuardianInitCreate endm if 0 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianInitToDefaultAttrs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Initialize the spline PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass RETURN: nothing DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 5/ 3/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianInitToDefaultAttrs method dynamic SplineGuardianClass, MSG_GO_INIT_TO_DEFAULT_ATTRS uses dx .enter mov di,offset SplineGuardianClass call ObjCallSuperNoLock mov ax,MSG_SPLINE_INITIALIZE clr dx ;no params mov di,mask MF_FIXUP_DS call GrObjVisGuardianMessageToVisWard .leave ret SplineGuardianInitToDefaultAttrs endm endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianGrObjSpecificInitialize %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set initialization data that is tool specific PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass bp low low nibble - SplineMode for creating new splines high nibble - SplineMode for editing existing splines bp high - GrObjVisGuardianFlags only GOVGF_CAN_EDIT_EXISTING_OBJECTS matters RETURN: nothing DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimzed for SMALL SIZE over SPEED Common cases: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 1/16/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianGrObjSpecificInitialize method dynamic SplineGuardianClass, MSG_GO_GROBJ_SPECIFIC_INITIALIZE uses cx .enter mov ax, bp andnf ah, mask GOVGF_CAN_EDIT_EXISTING_OBJECTS BitClr ds:[di].GOVGI_flags, GOVGF_CAN_EDIT_EXISTING_OBJECTS ornf ds:[di].GOVGI_flags,ah mov ah,al andnf al,0x0f ;just low nibble mov ds:[di].SGI_splineCreateMode, al ; We want existing splines that we edit and splines that finish ; creating to edit the same way. ; mov cl,4 shr ah,cl ;high nibble to low nibble mov ds:[di].SGI_splineAfterCreateMode, ah mov ds:[di].SGI_splineMode, ah .leave ret SplineGuardianGrObjSpecificInitialize endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianAnotherToolActivated %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Notify selected and edited objects that another tool has been activated. If the Spline is not editing it should just call its superclass. If, however, it is editing and the class of the tool being activated is SplineGuardian then it should keep the edit. PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of GrObjClass cx:dx - od of caller bp - AnotherToolActivatedFlags RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: The activating class will be SplineGuardian since that is the class of all Spline editing tools REVISION HISTORY: Name Date Description ---- ---- ----------- srs 3/ 8/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianAnotherToolActivated method dynamic SplineGuardianClass, MSG_GO_ANOTHER_TOOL_ACTIVATED uses ax,cx,dx,bp .enter test ds:[di].GOI_actionModes,mask GOAM_CREATE jnz callSuper test bp,mask ATAF_SHAPE or mask ATAF_STANDARD_POINTER jnz callSuper test ds:[di].GOI_tempState,mask GOTM_EDITED jz callSuper ; Get the class of the tool activating ; push si ;guardian lmem mov bx,cx ;activating handle mov si,dx ;activating lmem mov di,mask MF_FIXUP_DS or mask MF_CALL mov ax,MSG_META_GET_CLASS call ObjMessage ; Check for activating tool being SplineGuardian ; cmp dx,offset SplineGuardianClass jne callSuperPopSI cmp cx,segment SplineGuardianClass jne callSuperPopSI ; Have activating SplineGuardian update us with ; its SplineMode. ; mov ax,MSG_GOVG_UPDATE_EDIT_GRAB_WITH_STORED_DATA mov di,mask MF_FIXUP_DS call ObjMessage pop si ;guardian lmem done: .leave ret callSuperPopSI: mov dx,si ;activating lmem pop si ;guardian lmem mov cx,bx ;activating handle callSuper: mov di,offset SplineGuardianClass mov ax,MSG_GO_ANOTHER_TOOL_ACTIVATED call ObjCallSuperNoLock jmp short done SplineGuardianAnotherToolActivated endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianLostTargetExcl %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Notify Spline that it is losing the edit grab. The Spline needs to mark the Spline pointer as inactive PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass RETURN: nothing DESTROYED: ax,cx,dx,bp PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This message should be optimized for SMALL SIZE over SPEED Common cases: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 1/15/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianLostTargetExcl method dynamic SplineGuardianClass, MSG_META_LOST_TARGET_EXCL .enter mov ax, MSG_SG_SET_SPLINE_MODE mov cl, SM_INACTIVE call ObjCallInstanceNoLock mov ax,MSG_SPLINE_SET_MINIMAL_VIS_BOUNDS mov di,mask MF_FIXUP_DS call GrObjVisGuardianMessageToVisWard mov ax,MSG_META_LOST_TARGET_EXCL mov di,segment SplineGuardianClass mov es, di mov di,offset SplineGuardianClass call ObjCallSuperNoLock Destroy ax,cx,dx,bp .leave ret SplineGuardianLostTargetExcl endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianReplaceGeometryInstanceData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Retransform the spline points for any scale factor between the object dimensions and the vis bounds. PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass ss:bp - BasicInit RETURN: nothing DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 12/15/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianReplaceGeometryInstanceData method dynamic SplineGuardianClass, MSG_GO_REPLACE_GEOMETRY_INSTANCE_DATA .enter mov di,offset SplineGuardianClass call ObjCallSuperNoLock call SplineGuardianTransformSplinePoints mov ax,MSG_VIS_RECREATE_CACHED_GSTATES mov di,mask MF_FIXUP_DS call GrObjVisGuardianMessageToVisWard .leave ret SplineGuardianReplaceGeometryInstanceData endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianTransformSplinePoints %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Transform spline points by the scale factor from the vis bounds to the object dimensions. CALLED BY: INTERNAL SplineGuardianCompleteTransform PASS: *ds:si - SplineGuardianClass RETURN: Spline has been converted DESTROYED: nothing PSEUDO CODE/STRATEGY: WARNING - may cause block to move or object to move within block KNOWN BUGS/SIDE EFFECTS/IDEAS: This routine should be optimized for SMALL SIZE over SPEED Common cases: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 1/16/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianTransformSplinePoints proc far class SplineGuardianClass uses ax,bx,cx,dx,bp,di .enter EC < call ECSplineGuardianCheckLMemObject > ; Bail if no scale factor to transform spline points with ; call GrObjVisGuardianCalcScaleFactorVISToOBJECT jc done clr di ;no window call GrCreateState ; Scale the spline in place so that ; MSG_GOVG_NOTIFY_VIS_WARD_CHANGE_BOUNDS won't try to ; move the object. ; push ax,bx,cx,dx ;scale factor call GrObjVisGuardianGetWardWWFixedCenter call GrApplyTranslation pop ax,bx,cx,dx ;scale factor call GrApplyScale call GrObjVisGuardianGetWardWWFixedCenter negwwf dxcx ;x of center negwwf bxax ;y of center call GrApplyTranslation ; Convert Spline through gstate and have it ; change it vis bounds to match the new size of the Spline ; mov bp,di ;gstate mov ax,MSG_SPLINE_TRANSFORM_POINTS mov di,mask MF_FIXUP_DS call GrObjVisGuardianMessageToVisWard mov di,bp ;gstate call GrDestroyState done: .leave ret SplineGuardianTransformSplinePoints endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianCompleteTransform %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Transform the splines points with the transformation in the normalTransform and then call the super class to complete the transform with the new spline data. PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass bp - GrObjActionNotificationType RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 4/ 9/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianCompleteTransform method dynamic SplineGuardianClass, MSG_GO_COMPLETE_TRANSFORM .enter call SplineGuardianTransformSplinePoints ; ; Call the super class only once all the geometry has been done. ; mov di, offset SplineGuardianClass call ObjCallSuperNoLock .leave ret SplineGuardianCompleteTransform endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianCheckForEditWithFirstStartSelect %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: If the splineAfterCreateMode is one of the beginner modes then we don't want to edit with the first start select because it will add an unwanted anchor point PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass ^lcx:dx - floater RETURN: stc - edit with this start select clc - don't edit with this start select DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 11/11/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianCheckForEditWithFirstStartSelect method dynamic\ SplineGuardianClass, MSG_GOVG_CHECK_FOR_EDIT_WITH_FIRST_START_SELECT .enter cmp ds:[di].SGI_splineAfterCreateMode,SM_BEGINNER_EDIT je dontEdit stc done: .leave ret dontEdit: ; Need to get object out of inactive mode so that its ; anchor points show up ; mov ax,MSG_GOVG_UPDATE_EDIT_GRAB_WITH_STORED_DATA call ObjCallInstanceNoLock clc jmp done SplineGuardianCheckForEditWithFirstStartSelect endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianBeginCreate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: The spline geos from begin to end create immediately so that we can stick it in edit mode. PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass RETURN: nothing DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 9/10/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianBeginCreate method dynamic SplineGuardianClass, MSG_GO_BEGIN_CREATE uses cx .enter ; Make sure we will be in spline create mode ; mov ax,MSG_SG_SWITCH_TO_SPLINE_CREATE_MODE call ObjCallInstanceNoLock mov ax,MSG_GO_BEGIN_CREATE mov di,offset SplineGuardianClass call ObjCallSuperNoLock mov ax,MSG_GO_NOTIFY_GROBJ_VALID call ObjCallInstanceNoLock ; The spline leaves the GrObj's concept of create mode ; right away. Even though we initially add points to the ; spline with a SplineMode with CREATE in it, as far as the ; grobj is concerned it is an object being edited. ; clr cx ;EndCreatePassFlags mov ax,MSG_GO_END_CREATE call ObjCallInstanceNoLock .leave ret SplineGuardianBeginCreate endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianEndCreate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Stop the creation of the object and use the existing data. PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass ss:bp - GrObjMouseData RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 8/26/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianEndCreate method dynamic SplineGuardianClass, MSG_GO_END_CREATE uses ax .enter ; If not in create mode then ignore message ; test ds:[di].GOI_actionModes,mask GOAM_CREATE jz done call ObjMarkDirty andnf ds:[di].GOI_actionModes, not ( mask GOAM_ACTION_PENDING or \ mask GOAM_ACTION_HAPPENING or \ mask GOAM_ACTION_ACTIVATED or \ mask GOAM_CREATE ) mov ax,MSG_GO_SUSPEND_COMPLETE_CREATE call ObjCallInstanceNoLock call GrObjGlobalUndoAcceptActions done: clr cx .leave ret SplineGuardianEndCreate endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianCompleteCreate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Complete the interactive create PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 4/ 6/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianCompleteCreate method dynamic SplineGuardianClass, MSG_GO_COMPLETE_CREATE .enter mov di,offset SplineGuardianClass call ObjCallSuperNoLock mov ax,MSG_GO_BECOME_EDITABLE call ObjCallInstanceNoLock .leave ret SplineGuardianCompleteCreate endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianSwitchToSplineCreateMode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set the splineMode to the mode in splineCreateMode CALLED BY: INTERNAL UTILITY PASS: *ds:si - object RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This routine should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 9/10/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianSwitchToSplineCreateMode method dynamic SplineGuardianClass, MSG_SG_SWITCH_TO_SPLINE_CREATE_MODE uses cx .enter mov cl,ds:[di].SGI_splineCreateMode mov ax,MSG_SG_SET_SPLINE_MODE call ObjCallInstanceNoLock .leave ret SplineGuardianSwitchToSplineCreateMode endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianSwitchToSplineAfterCreateMode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: If the current SplineMode is one of the spline create modes then switch to SGI_afterCreateMode CALLED BY: INTERNAL UTILITY PASS: *ds:si - object RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This routine should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 9/10/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianSwitchToSplineAfterCreateMode method dynamic SplineGuardianClass, MSG_SG_SWITCH_TO_SPLINE_AFTER_CREATE_MODE uses cx .enter ; If the spline is ridiculously small, then nuke it. mov ax, MSG_SPLINE_GET_ENDPOINT_INFO mov cl, GET_FIRST mov di, mask MF_CALL call GrObjVisGuardianMessageToVisWard jc destroy mov di, ds:[si] add di, ds:[di].SplineGuardian_offset cmp ds:[di].SGI_splineMode,SM_ADVANCED_CREATE ja done mov cl, ds:[di].SGI_splineAfterCreateMode mov ax,MSG_SG_SET_SPLINE_MODE call ObjCallInstanceNoLock ; While the spline is being created it doesn't show ; its arrowheads. While it is being edited the arrow heads, ; will update correctly for the most part, so force them ; to draw if they exist. If we didn't do this then the ; arrowheads wouldn't show up until they happened to ; be invalidate by some other operation. ; call GrObjGetLineInfo test al,mask GOLAIR_ARROWHEAD_ON_START or \ mask GOLAIR_ARROWHEAD_ON_END jz done ; It turns out that a spline won't be closed at the time ; we get this message, so we will have to invalidate ; closed splines even though they don't draw arrowheads. ; Big deal. ; mov ax,MSG_GO_INVALIDATE call ObjCallInstanceNoLock done: .leave ret destroy: ; Destroy the object mov ax, MSG_GO_CLEAR_SANS_UNDO call ObjCallInstanceNoLock jmp done SplineGuardianSwitchToSplineAfterCreateMode endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianSetSplineCreateAndAfterCreateModes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set SGI_splineAfterCreateMode and SGI_splineCreateMode PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass cl - splineCreateMode ch - splineAfterCreateMode RETURN: nothing DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 10/14/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianSetSplineCreateAndAfterCreateModes method dynamic \ SplineGuardianClass, MSG_SG_SET_SPLINE_CREATE_AND_AFTER_CREATE_MODES .enter mov ds:[di].SGI_splineCreateMode,cl mov ds:[di].SGI_splineAfterCreateMode,ch .leave ret SplineGuardianSetSplineCreateAndAfterCreateModes endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianSetSplineMode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: SplineGuardian method for MSG_SG_SET_SPLINE_MODE Pass: *ds:si = SplineGuardian object ds:di = SplineGuardian instance cl - SplineMode Return: nothing Destroyed: nothing Comments: Revision History: Name Date Description ---- ------------ ----------- jon Mar 17, 1992 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianSetSplineMode method SplineGuardianClass, MSG_SG_SET_SPLINE_MODE uses ax .enter mov ds:[di].SGI_splineMode, cl mov ax, MSG_GOVG_UPDATE_VIS_WARD_WITH_STORED_DATA call ObjCallInstanceNoLock .leave ret SplineGuardianSetSplineMode endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianUpdateVisWardWithStoredData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: SplineGuardian method for MSG_GOVG_UPDATE_VIS_WARD_WITH_STORED_DATA Called by: Pass: *ds:si = SplineGuardian object ds:di = SplineGuardian instance Return: nothing Destroyed: nothing Comments: Revision History: Name Date Description ---- ------------ ----------- jon Mar 17, 1992 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianUpdateVisWardWithStoredData method SplineGuardianClass, MSG_GOVG_UPDATE_VIS_WARD_WITH_STORED_DATA uses ax,cx .enter mov cl, ds:[di].SGI_splineMode mov ax, MSG_SPLINE_SET_MODE clr di call GrObjVisGuardianMessageToVisWard .leave ret SplineGuardianUpdateVisWardWithStoredData endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianUpdateEditGrabWithStoredData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: Send the spline mode to the edit grab Pass: *ds:si = SplineGuardian object ds:di = SplineGuardian instance Return: nothing Destroyed: ax Comments: Revision History: Name Date Description ---- ------------ ----------- jon Mar 17, 1992 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianUpdateEditGrabWithStoredData method dynamic SplineGuardianClass, MSG_GOVG_UPDATE_EDIT_GRAB_WITH_STORED_DATA uses cx .enter mov ax,MSG_SG_SET_SPLINE_MODE mov cl, ds:[di].SGI_splineMode clr di call GrObjMessageToEdit mov ax,MSG_SG_SET_SPLINE_CREATE_AND_AFTER_CREATE_MODES mov cl, ds:[di].SGI_splineCreateMode mov ch, ds:[di].SGI_splineAfterCreateMode clr di call GrObjMessageToEdit .leave ret SplineGuardianUpdateEditGrabWithStoredData endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianGenerateSplineNotify %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: SplineGuardian method for MSG_TG_GENERATE_SPLINE_NOTIFY Passes the notification to the GrObjBody so that it can coalesce each GrObjSpline's attrs into a single update. Pass: *ds:si = SplineGuardian object ds:di = SplineGuardian instance ss:[bp] - VisSplineGenerateNotifyParams Return: nothing Destroyed: ax Comments: Revision History: Name Date Description ---- ------------ ----------- jon Apr 1, 1992 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianGenerateSplineNotify method dynamic SplineGuardianClass, MSG_SG_GENERATE_SPLINE_NOTIFY .enter ; ; Drop this on the floor if the spline is invalid (this ; happens when a new spline is being created -- in charting, ; for instance). ; test ds:[di].GOI_optFlags, mask GOOF_GROBJ_INVALID jnz done ; ; If the relayed bit is set, we want to send this to the ; ward. Otherwise, to the body ; test ss:[bp].SGNP_sendFlags,mask SNSF_RELAYED_TO_LIKE_OBJECTS jnz sendToWard mov ax, MSG_GB_GENERATE_SPLINE_NOTIFY mov di, mask MF_FIXUP_DS call GrObjMessageToBody EC < ERROR_Z GROBJ_CANT_SEND_MESSAGE_TO_BODY > done: .leave ret sendToWard: mov ax, MSG_SPLINE_GENERATE_NOTIFY mov di, mask MF_FIXUP_DS call GrObjVisGuardianMessageToVisWard jmp done SplineGuardianGenerateSplineNotify endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianSendUINotification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: SplineGuardian method for MSG_GO_SEND_UI_NOTIFICATION Passes the notification to the GrObjBody so that it can coalesce each GrObjSpline's attrs into a single update. Pass: *ds:si = SplineGuardian object ds:di = SplineGuardian instance cx - GrObjUINotificationTypes of notifications that need to be performed. Return: nothing Destroyed: ax Comments: Revision History: Name Date Description ---- ------------ ----------- jon Apr 1, 1992 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianSendUINotification method dynamic SplineGuardianClass, MSG_GO_SEND_UI_NOTIFICATION uses bp .enter mov di, offset SplineGuardianClass call ObjCallSuperNoLock ; ; Bail if grobj invalid. Prevents needless updates in charting ; GrObjDeref di, ds, si test ds:[di].GOI_optFlags, mask GOOF_GROBJ_INVALID jnz done test cx,mask GOUINT_SELECT jz done ; The guardian has been selected so ; tell the ward to update its controllers (except for select state, ; 'cause we want the grobj's select state), so that the controllers ; will reflect the wards attributes,etc. ; sub sp, size SplineGenerateNotifyParams mov bp, sp mov ss:[bp].SGNP_notificationFlags, mask SplineGenerateNotifyFlags mov ss:[bp].SGNP_sendFlags, mask SNSF_UPDATE_APP_TARGET_GCN_LISTS mov ax, MSG_SPLINE_GENERATE_NOTIFY mov di, mask MF_FIXUP_DS call GrObjVisGuardianMessageToVisWard add sp, size SplineGenerateNotifyParams done: .leave ret SplineGuardianSendUINotification endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianLostSelectionList %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: SplineGuardian method for MSG_GO_LOST_SELECTION_LIST Send null notification as we are no longer selected. Overrides superclass's refusal to do this because GOOF_GROBJ_INVALID is set. Pass: *ds:si = SplineGuardian object ds:di = SplineGuardian instance Return: nothing Destroyed: ax Comments: Revision History: Name Date Description ---- ------------ ----------- brianc 9/30/94 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianLostSelectionList method dynamic SplineGuardianClass, MSG_GO_LOST_SELECTION_LIST uses bp .enter push ax sub sp, size SplineGenerateNotifyParams mov bp, sp mov ss:[bp].SGNP_notificationFlags, mask SplineGenerateNotifyFlags mov ss:[bp].SGNP_sendFlags, \ mask SNSF_UPDATE_APP_TARGET_GCN_LISTS or \ mask SNSF_NULL_STATUS or \ mask SNSF_SEND_ONLY or \ mask SNSF_RELAYED_TO_LIKE_OBJECTS mov ax, MSG_SPLINE_GENERATE_NOTIFY mov di, mask MF_FIXUP_DS call GrObjVisGuardianMessageToVisWard add sp, size SplineGenerateNotifyParams pop ax mov di, offset SplineGuardianClass call ObjCallSuperNoLock .leave ret SplineGuardianLostSelectionList endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianCombineSelectionStateNotificationData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: SplineGuardian method for MSG_GO_COMBINE_SELECTION_STATE_NOTIFICATION_DATA Pass: *ds:si = GrObj object ds:di = GrObj instance ^hcx = GrObjNotifySelectionStateChange struct Return: carry set if relevant diff bit(s) are all set Destroyed: nothing Comments: Revision History: Name Date Description ---- ------------ ----------- jon Apr 1, 1992 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianCombineSelectionStateNotificationData method dynamic SplineGuardianClass, MSG_GO_COMBINE_SELECTION_STATE_NOTIFICATION_DATA uses ax .enter mov di, offset SplineGuardianClass call ObjCallSuperNoLock ; ; Indicate that a spline object is selected ; mov bx, cx call MemLock jc done mov es, ax BitSet es:[GONSSC_selectionState].GSS_flags, GSSF_SPLINE_SELECTED call MemUnlock done: .leave ret SplineGuardianCombineSelectionStateNotificationData endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianGetBoundingRectDWFixed %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Calculate the RectDWFixed that bounds the object in the dest gstate coordinate system PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of RectClass ss:bp - BoundingRectData destGState parentGState RETURN: ss:bp - BoundingRectData rect DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 11/12/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianGetBoundingRectDWFixed method dynamic SplineGuardianClass, MSG_GO_GET_BOUNDING_RECTDWFIXED .enter ; If the guardian is grobj invalid then the vis spline isn't ; going to draw anything into a path which will then screw ; up the bounds calc. So If grobj invalid then always use ; optimized recalc. This fixes a bug with converting ; rotated splines from 1.2 documents. ; test ds:[di].GOI_optFlags, mask GOOF_GROBJ_INVALID jnz callSuper call GrObjCheckForOptimizedBoundsCalc jc callSuper CallMod GrObjGetBoundingRectDWFixedFromPath includeLineWidth: CallMod GrObjAdjustRectDWFixedByLineWidth .leave ret callSuper: mov di,offset SplineGuardianClass call ObjCallSuperNoLock jmp includeLineWidth SplineGuardianGetBoundingRectDWFixed endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianGetDWFSelectionHandleBoundsForTrivialReject %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: It is not trivial to calculate the selection handle bounds for rotated or skewed spline PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass ss:bp - RectDWFixed RETURN: ss:bp - RectDWFixed filled DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 11/ 5/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianGetDWFSelectionHandleBoundsForTrivialReject method dynamic SplineGuardianClass, MSG_GO_GET_DWF_SELECTION_HANDLE_BOUNDS_FOR_TRIVIAL_REJECT .enter mov di,offset SplineGuardianClass call GrObjGetDWFSelectionHandleBoundsForTrivialRejectProblems .leave ret SplineGuardianGetDWFSelectionHandleBoundsForTrivialReject endm if 0 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianGetBoundingRectDWFixed %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Use spline specific GenerateNormalFourPointDWFixeds routine which will compenstate for arrowheads if they exist. PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass ss:bp - BoundingRectData destGState parentGState RETURN: ss:bp - BoudingRectData rect DESTROYED: nothing PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 4/10/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianGetBoundingRectDWFixed method dynamic SplineGuardianClass, MSG_GO_GET_BOUNDING_RECTDWFIXED class SplineGuardianClass uses dx,cx .enter mov bx,bp ;BoundingRectData push ds,si sub sp,size FourPointDWFixeds mov bp,sp call SplineGuardianGenerateNormalFourPointDWFixeds mov di,ss:[bx].BRD_parentGState mov dx,ss:[bx].BRD_destGState call GrObjCalcNormalDWFixedMappedCorners mov di,ss mov ds,di ;Rect segment mov es,di ;FourPoints segment mov si,bx ;rect offset mov di,bp ;FourPoints offset call GrObjGlobalSetRectDWFixedFromFourPointDWFixeds add sp, size FourPointDWFixeds pop ds,si mov bp,bx ;BoundingRectData ; This covers arrowheads and problems with the path ; code not including lines ; CallMod GrObjAdjustRectDWFixedByLineWidth .leave ret SplineGuardianGetBoundingRectDWFixed endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianGenerateNormalFourPointDWFixeds %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Fill in FourPointDWFixeds structure from width and height of object -w/2,-h/2,w/2,h/2. Compensate for arrowheads if necessary. CALLED BY: INTERNAL UTILITY PASS: *ds:si - instance data ss:bp - FourPointDWFixeds - empty RETURN: ss:bp - FourDWPoints - filled DESTROYED: nothing PSEUDO CODE/STRATEGY: nothing KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- srs 4/ 2/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianGenerateNormalFourPointDWFixeds proc far class SplineGuardianClass uses si,di,ax,bx,cx,dx .enter EC < call ECSplineGuardianCheckLMemObject > CallMod GrObjGetNormalOBJECTDimensions push ax,bx ;height call GrObjGetArrowheadInfo and al, mask GOLAIR_ARROWHEAD_ON_START or \ mask GOLAIR_ARROWHEAD_ON_END jnz arrowheads pop ax,bx ;height continue: sar dx,1 ;width/2 int rcr cx,1 ;width/2 frac sar bx,1 ;height/2 int rcr ax,1 ;height/2 frac ; Store bottom as height/2 and top as -height/2 ; push dx ;width int xchg bx,ax ;bx <- height frac ;ax <- height int cwd ;sign extend height/2 movdwf ss:[bp].FPDF_BR.PDF_y, dxaxbx movdwf ss:[bp].FPDF_BL.PDF_y, dxaxbx negdwf dxaxbx movdwf ss:[bp].FPDF_TR.PDF_y, dxaxbx movdwf ss:[bp].FPDF_TL.PDF_y, dxaxbx ; Store right as width/2 and left as -width/2 ; pop ax ;width int cwd ;sign extend width/2 movdwf ss:[bp].FPDF_BR.PDF_x, dxaxcx movdwf ss:[bp].FPDF_TR.PDF_x, dxaxcx negdwf dxaxcx movdwf ss:[bp].FPDF_BL.PDF_x, dxaxcx movdwf ss:[bp].FPDF_TL.PDF_x, dxaxcx .leave ret arrowheads: ; When need to expand the bounds to include arrowheads ; which might stick outside of the normal bounds. We ; must be careful to expand the bounds in equal amounts ; in both directions to keep the bounds centered. We ; will expand the bounds by the length of the arrowhead ; branch. This is definitely overkill but it works. ; clr bh mov di,bx ;arrowhead length shl di,1 ;expand in opposite directions pop ax,bx ;height add dx,di ;expand width add bx,di ;expand height jmp continue SplineGuardianGenerateNormalFourPointDWFixeds endp endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianGainedTargetExcl %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Expand the vis bounds of the ward to include the control points. PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardian RETURN: none DESTROYED: ax,cx,dx,bp PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 2/14/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianGainedTargetExcl method dynamic SplineGuardianClass, MSG_META_GAINED_TARGET_EXCL .enter mov cx,mask RSA_CHOOSE_OWN_SIZE mov dx,cx mov di,mask MF_FIXUP_DS mov ax,MSG_VIS_RECALC_SIZE call GrObjVisGuardianMessageToVisWard mov ax, MSG_META_GAINED_TARGET_EXCL mov di, offset SplineGuardianClass call ObjCallSuperNoLock .leave Destroy ax,cx,dx,bp ret SplineGuardianGainedTargetExcl endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianRuleLargeStartSelectForWard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: SplineGuardian method for MSG_GOVG_RULE_LARGE_START_SELECT_FOR_WARD Called by: MSG_GOVG_RULE_LARGE_START_SELECT_FOR_WARD Pass: *ds:si = SplineGuardian object ds:di = SplineGuardian instance Return: nothing Destroyed: ax Comments: Revision History: Name Date Description ---- ------------ ----------- jon Jan 20, 1993 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianRuleLargeStartSelectForWard method dynamic SplineGuardianClass, MSG_GOVG_RULE_LARGE_START_SELECT_FOR_WARD uses cx .enter ; ; If the spline is in create mode, then we want to snap, ; otherwise we just want to set the reference. ; cmp ds:[di].SGI_splineMode,SM_ADVANCED_CREATE ja setReference mov di, offset SplineGuardianClass call ObjCallSuperNoLock done: .leave ret setReference: mov cx, mask VRCS_OVERRIDE or mask VRCS_SET_REFERENCE mov ax, MSG_VIS_RULER_RULE_LARGE_PTR mov di, mask MF_FIXUP_DS call GrObjMessageToRuler jmp done SplineGuardianRuleLargeStartSelectForWard endm GrObjSplineGuardianCode ends GrObjTransferCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianGetTransferBlockFromVisWard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Returns a vm block from the ward with the ward's data in it PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass ss:[bp] - GrObjTransferParams RETURN: cx:dx - 32 bit identifier DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 19 may 92 initial revision %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianGetTransferBlockFromVisWard method dynamic SplineGuardianClass, MSG_GOVG_GET_TRANSFER_BLOCK_FROM_VIS_WARD .enter ; ; Tell the spline object that we want the vm block allocated in ; the transfer file. ; mov bx, ss:[bp].GTP_vmFile mov cx, bx ;cx <- override mov ax, MSG_SPLINE_CREATE_TRANSFER_FORMAT mov di, mask MF_FIXUP_DS or mask MF_CALL call GrObjVisGuardianMessageToVisWard ; ; Return the block in 32 bit id form ; mov_tr cx, ax clr dx .leave ret SplineGuardianGetTransferBlockFromVisWard endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianCreateWardWithTransfer %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Returns a vm block from the ward with the ward's data in it PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass ss:[bp] - GrObjTransferParams cx:dx - 32 bit identifier RETURN: ^lcx:dx <- new ward DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 19 may 92 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianCreateWardWithTransfer method dynamic SplineGuardianClass, MSG_GOVG_CREATE_WARD_WITH_TRANSFER uses bp .enter push cx ;save vm block handle ; ; get the block to store the spline object in ; mov ax,MSG_GB_GET_BLOCK_FOR_ONE_GROBJ mov di,mask MF_FIXUP_DS or mask MF_CALL call GrObjMessageToBody EC < ERROR_Z GROBJ_CANT_SEND_MESSAGE_TO_BODY > ; ; Create our ward in the returned block ; mov ax,MSG_GOVG_CREATE_VIS_WARD call ObjCallInstanceNoLock mov_tr ax, dx ;^lcx:ax <- spline obj pop dx ;dx <- vm block push cx, ax ;save spline object ; ; Have the spline read in its points ; mov bx, ss:[bp].GTP_vmFile mov cx, bx ;bp <- transfer file mov ax, MSG_SPLINE_REPLACE_WITH_TRANSFER_FORMAT mov di, mask MF_FIXUP_DS call GrObjVisGuardianMessageToVisWard pop cx, dx ;return optr .leave ret SplineGuardianCreateWardWithTransfer endm GrObjTransferCode ends GrObjDrawCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianDrawFG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw only the base data of the spline, not the inverted stuff PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass cl - DrawFlags dx - gstate RETURN: nothing DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 12/ 7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianDrawFG method dynamic SplineGuardianClass, MSG_GO_DRAW_FG_AREA, MSG_GO_DRAW_FG_AREA_HI_RES uses dx,bp .enter mov di,dx ;gstate call GrObjVisGuardianOptApplyOBJECTToVISTransform ; Send draw message to vis ward ; mov bp,dx mov di,mask MF_FIXUP_DS mov ax, MSG_SPLINE_DRAW_AREA_ONLY call GrObjVisGuardianMessageToVisWard .leave ret SplineGuardianDrawFG endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianDrawFGLine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw only the base data of the spline, not the inverted stuff. This handler is used for the clip stuff also because the spline fill uses a path which we can't draw to a clip path. PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass cl - DrawFlags dx - gstate RETURN: nothing DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 12/ 7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianDrawFGLine method dynamic SplineGuardianClass, MSG_GO_DRAW_FG_LINE, MSG_GO_DRAW_FG_LINE_HI_RES, MSG_GO_DRAW_CLIP_AREA, MSG_GO_DRAW_CLIP_AREA_HI_RES, MSG_GO_DRAW_QUICK_VIEW uses cx,dx,bp .enter mov di,dx ;gstate call GrObjVisGuardianOptApplyOBJECTToVISTransform mov bp,dx mov di,mask MF_FIXUP_DS mov ax, MSG_SPLINE_DRAW_LINE_ONLY call GrObjVisGuardianMessageToVisWard ; If the spline is closed don't draw the arrowheads. ; mov di,mask MF_FIXUP_DS or mask MF_CALL mov ax,MSG_SPLINE_GET_CLOSED_STATE call GrObjVisGuardianMessageToVisWard tst cl jz arrowheads done: .leave ret arrowheads: mov di,dx ;gstate call GrObjGetLineInfo call SplineGuardianDrawStartArrowhead call SplineGuardianDrawEndArrowhead jmp done SplineGuardianDrawFGLine endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianDrawStartArrowhead %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw arrow head at start of line in needed CALLED BY: INTERNAL SplineGuardianFGLine PASS: *ds:si - object di - gstate with normalTransform applied al - GrObjLineAttrInfoRecord RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This routine should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 9/ 8/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianDrawStartArrowhead proc near uses ax,bx,cx,dx,di,bp .enter EC < call ECSplineGuardianCheckLMemObject > test al, mask GOLAIR_ARROWHEAD_ON_START jz done push dx ;gstate mov cl,GET_FIRST mov di,mask MF_FIXUP_DS or mask MF_CALL mov ax,MSG_SPLINE_GET_ENDPOINT_INFO call GrObjVisGuardianMessageToVisWard pop di ;gstate jc done mov bx,bp call GrObjDrawArrowhead done: .leave ret SplineGuardianDrawStartArrowhead endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianDrawEndArrowhead %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw arrow head at end of line in needed CALLED BY: INTERNAL SplineGuardianFGLine PASS: *ds:si - object di - gstate with normalTransform applied al - GrObjLineAttrInfoRecord RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This routine should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 9/ 8/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianDrawEndArrowhead proc near uses ax,bx,cx,dx,di,bp .enter EC < call ECSplineGuardianCheckLMemObject > test al, mask GOLAIR_ARROWHEAD_ON_END jz done push dx ;gstate mov cl,GET_LAST mov di,mask MF_FIXUP_DS or mask MF_CALL mov ax,MSG_SPLINE_GET_ENDPOINT_INFO call GrObjVisGuardianMessageToVisWard pop di ;gstate jc done mov bx,bp call GrObjDrawArrowhead done: .leave ret SplineGuardianDrawEndArrowhead endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianDrawBGArea %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw only the base data of the spline, not the inverted stuff PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass cl - DrawFlags dx - gstate RETURN: nothing DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 12/ 7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianDrawBGArea method dynamic SplineGuardianClass, MSG_GO_DRAW_BG_AREA, MSG_GO_DRAW_BG_AREA_HI_RES uses dx,bp .enter mov di,dx ;gstate call GrObjVisGuardianOptApplyOBJECTToVISTransform ; Send draw message to vis ward ; mov bp,dx mov di,mask MF_FIXUP_DS mov ax, MSG_SPLINE_DRAW_USING_PASSED_GSTATE_ATTRIBUTES call GrObjVisGuardianMessageToVisWard .leave ret SplineGuardianDrawBGArea endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianDrawSpriteLine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw the spline line for sprite. PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass dx - gstate RETURN: nothing DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 12/ 7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianDrawSpriteLine method dynamic SplineGuardianClass, MSG_GO_DRAW_SPRITE_LINE, MSG_GO_DRAW_SPRITE_LINE_HI_RES uses dx,bp .enter mov di,dx ;gstate mov ax,MSG_GOVG_APPLY_SPRITE_OBJECT_TO_VIS_TRANSFORM call ObjCallInstanceNoLock mov bp,dx mov di,mask MF_FIXUP_DS mov ax, MSG_SPLINE_DRAW_LINE_ONLY call GrObjVisGuardianMessageToVisWard .leave ret SplineGuardianDrawSpriteLine endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianDrawHandlesRaw %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Convenient places as any to get the spline to draw it inverted stuff. PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass dx - gstate RETURN: nothing DESTROYED: ax PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 6/25/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianDrawHandlesRaw method dynamic SplineGuardianClass, MSG_GO_DRAW_HANDLES_RAW uses bp .enter mov di,offset SplineGuardianClass call ObjCallSuperNoLock mov di,dx ;gstate call GrSaveTransform call GrObjApplyNormalTransform call GrObjVisGuardianOptApplyOBJECTToVISTransform mov bp,dx ;gstate mov di,mask MF_FIXUP_DS mov ax,MSG_SPLINE_DRAW_EVERYTHING_ELSE call GrObjVisGuardianMessageToVisWard mov di,dx ;gstate call GrRestoreTransform .leave ret SplineGuardianDrawHandlesRaw endm GrObjDrawCode ends GrObjRequiredInteractiveCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianEvaluatePARENTPointForEdit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Have object evaluate the passed point in terms of editing. (ie could the object edit it self at this point). PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of GrObjClass ss:bp - PointDWFixed in PARENT coordinate system RETURN: al - EvaluatePositionRating dx - EvaluatePositionNotes DESTROYED: ah PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SMALL SIZE over SPEED Common cases: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 4/29/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianEvaluatePARENTPointForEdit method dynamic SplineGuardianClass, MSG_GO_EVALUATE_PARENT_POINT_FOR_EDIT .enter mov ax,MSG_GO_EVALUATE_PARENT_POINT_FOR_SELECTION call ObjCallInstanceNoLock call GrObjCanEdit? jnc cantEdit ; A low evaluation means the point was in the bounds, ; but not on the spline or its control or anchor points. ; For editing purposes this point is used for a drag ; select. We only allow drag selects on editing object. ; Otherwise you would never be able to edit a spline that ; was underneath another spline. ; GrObjDeref di,ds,si test ds:[di].GOI_tempState,mask GOTM_EDITED jnz done cmp al, EVALUATE_LOW jne done mov al,EVALUATE_NONE done: .leave ret cantEdit: ; Object can't be edited, so evaluate as none but leave the ; notes intact. ; mov al,EVALUATE_NONE jmp done SplineGuardianEvaluatePARENTPointForEdit endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SplineGuardianEvaluatePARENTPointForSelection %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: GrObj evaluates point to determine if it should be selected by it. PASS: *(ds:si) - instance data of object ds:[bx] - instance data of object ds:[di] - master part of object (if any) es - segment of SplineGuardianClass ss:bp - PointDWFixed in PARENT coordinates RETURN: al - EvaluatePositionRating dx - EvaluatePositionNotes DESTROYED: ah PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: This method should be optimized for SPEED over SMALL SIZE Common cases: unknown REVISION HISTORY: Name Date Description ---- ---- ----------- srs 6/11/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SplineGuardianEvaluatePARENTPointForSelection method dynamic \ SplineGuardianClass, MSG_GO_EVALUATE_PARENT_POINT_FOR_SELECTION point local PointWWFixed uses cx .enter mov bx,ss:[bp] ;orig bp,PARENT pt frame ; Convert point to OBJECT and store in stack frame. ; If OBJECT coord won't fit in WWF then bail ; push bp ;local frame lea bp, ss:[point] call GrObjConvertNormalPARENTToWWFOBJECT pop bp ;local frame LONG jnc notEvenClose ; Untransform the object coordinate mouse postion into ; the vis coordinates of ward ; clr di call GrCreateState mov dx,di ;gstate call GrObjVisGuardianOptApplyOBJECTToVISTransform movwwf dxcx,point.PF_x movwwf bxax,point.PF_y call GrUntransformWWFixed call GrDestroyState ; Round vis coordinate to integer ; rndwwf dxcx rndwwf bxax mov cx,dx mov dx,bx ; Have spline do its own hit detection ; mov ax,MSG_SPLINE_HIT_DETECT mov di,mask MF_FIXUP_DS or mask MF_CALL call GrObjVisGuardianMessageToVisWard cmp dl, SST_NONE je notEvenClose cmp dl, SST_INSIDE_VIS_BOUNDS je lowEval ; If the hit was on a line segment or anchor or control points ; we want to treat that as a high priority select. So in those ; cases pass clc to complete hit detection routine. This will ; cause the routine to treat the click as if it was a line, which ; is always high priority. ; cmp dl, SST_SEGMENT je complete ;implied clc cmp dl,SST_ANCHOR_POINT je complete cmp dl,SST_CONTROL_POINT je complete stc ;not on line complete: call GrObjGlobalCompleteHitDetectionWithAreaAttrCheck checkSelectionLock: GrObjDeref di,ds,si test ds:[di].GOI_locks, mask GOL_SELECT jnz selectionLock done: .leave ret notEvenClose: movnf al,EVALUATE_NONE clr dx jmp checkSelectionLock lowEval: movnf al, EVALUATE_LOW clr dx jmp checkSelectionLock selectionLock: BitSet dx, EPN_SELECTION_LOCK_SET jmp done SplineGuardianEvaluatePARENTPointForSelection endm GrObjRequiredInteractiveCode ends if ERROR_CHECK GrObjErrorCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ECSplineGuardianCheckLMemObject %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Checks to see if *ds:si* is a pointer to an object stored in an object block and that it is an SplineGuardianClass or one of its subclasses CALLED BY: INTERNAL PASS: *(ds:si) - object chunk to check RETURN: none DESTROYED: nothing - not even flags PSEUDO CODE/STRATEGY: none KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- srs 2/24/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ECSplineGuardianCheckLMemObject proc far ForceRef ECSplineGuardianCheckLMemObject uses es,di .enter pushf call ECCheckLMemObject mov di,segment SplineGuardianClass mov es,di mov di,offset SplineGuardianClass call ObjIsObjectInClass ERROR_NC OBJECT_NOT_A_DRAW_OBJECT popf .leave ret ECSplineGuardianCheckLMemObject endp GrObjErrorCode ends endif
; A098022: Irrational rotation of Log(3)/Log(2) as an implicit sequence with an uneven Cantor cartoon. ; 5,10,17,22,29,34,41,46,51,58,63,70,75,82,87,94,99,104,111,116,123,128,135,140,147,152,157,164,169,176,181,188,193,200,205,210,217,222,229,234,241,246,253,258,263,270,275,282,287,294,299,306,311,316,323,328 mov $3,$0 mul $3,2 mov $4,$0 mov $0,1 add $0,$3 mul $0,2 add $0,2 mov $1,4 lpb $0 sub $0,1 trn $0,8 trn $2,2 add $2,2 add $1,$2 lpe add $1,2 lpb $4 add $1,5 sub $4,1 lpe sub $1,3 mov $0,$1
############################################################################### # File : slti.asm # Project : MIPS32 MUX # Author: : Grant Ayers (ayers@cs.stanford.edu) # # Standards/Formatting: # MIPS gas, soft tab, 80 column # # Description: # Test the functionality of the 'slti' instruction. # ############################################################################### .section .test, "x" .balign 4 .set noreorder .global test .ent test test: lui $s0, 0xbfff # Load the base address 0xbffffff0 ori $s0, 0xfff0 ori $s1, $0, 1 # Prepare the 'done' status #### Test code start #### lui $t0, 0x8000 slti $v0, $t0, 0xffff slti $v1, $t0, 0 and $v0, $v0, $v1 #### Test code end #### sw $v0, 8($s0) # Set the test result sw $s1, 4($s0) # Set 'done' $done: jr $ra nop .end test
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/file_highlighter.h" #include "base/containers/stack.h" #include "base/values.h" namespace extensions { namespace { // Keys for a highlighted dictionary. const char kBeforeHighlightKey[] = "beforeHighlight"; const char kHighlightKey[] = "highlight"; const char kAfterHighlightKey[] = "afterHighlight"; // Increment |index| to the position of the next quote ('"') in |str|, skipping // over any escaped quotes. If no next quote is found, |index| is set to // std::string::npos. Assumes |index| currently points to a quote. void QuoteIncrement(const std::string& str, size_t* index) { size_t i = *index + 1; // Skip over the first quote. bool found = false; while (!found && i < str.size()) { if (str[i] == '\\') i += 2; // if we find an escaped character, skip it. else if (str[i] == '"') found = true; else ++i; } *index = found ? i : std::string::npos; } // Increment |index| by one if the next character is not a comment. Increment // index until the end of the comment if it is a comment. void CommentSafeIncrement(const std::string& str, size_t* index) { size_t i = *index; if (str[i] == '/' && i + 1 < str.size()) { // Eat a single-line comment. if (str[i + 1] == '/') { i += 2; // Eat the '//'. while (i < str.size() && str[i] != '\n' && str[i] != '\r') ++i; } else if (str[i + 1] == '*') { // Eat a multi-line comment. i += 3; // Advance to the first possible comment end. while (i < str.size() && !(str[i - 1] == '*' && str[i] == '/')) ++i; } } *index = i + 1; } // Increment index until the end of the current "chunk"; a "chunk" is a JSON- // style list, object, or string literal, without exceeding |end|. Assumes // |index| currently points to a chunk's starting character ('{', '[', or '"'). void ChunkIncrement(const std::string& str, size_t* index, size_t end) { char c = str[*index]; base::stack<char> stack; do { if (c == '"') QuoteIncrement(str, index); else if (c == '[') stack.push(']'); else if (c == '{') stack.push('}'); else if (!stack.empty() && c == stack.top()) stack.pop(); CommentSafeIncrement(str, index); c = str[*index]; } while (!stack.empty() && *index < end); } } // namespace FileHighlighter::FileHighlighter(const std::string& contents) : contents_(contents), start_(0u), end_(contents_.size()) { } FileHighlighter::~FileHighlighter() { } std::string FileHighlighter::GetBeforeFeature() const { return contents_.substr(0, start_); } std::string FileHighlighter::GetFeature() const { return contents_.substr(start_, end_ - start_); } std::string FileHighlighter::GetAfterFeature() const { return contents_.substr(end_); } void FileHighlighter::SetHighlightedRegions(base::DictionaryValue* dict) const { std::string before_feature = GetBeforeFeature(); if (!before_feature.empty()) dict->SetString(kBeforeHighlightKey, before_feature); std::string feature = GetFeature(); if (!feature.empty()) dict->SetString(kHighlightKey, feature); std::string after_feature = GetAfterFeature(); if (!after_feature.empty()) dict->SetString(kAfterHighlightKey, after_feature); } ManifestHighlighter::ManifestHighlighter(const std::string& manifest, const std::string& key, const std::string& specific) : FileHighlighter(manifest) { start_ = contents_.find('{'); start_ = start_ == std::string::npos ? contents_.size() : start_ + 1; end_ = contents_.rfind('}'); end_ = end_ == std::string::npos ? contents_.size() : end_; Parse(key, specific); } ManifestHighlighter::~ManifestHighlighter() { } void ManifestHighlighter::Parse(const std::string& key, const std::string& specific) { // First, try to find the bounds of the full key. if (FindBounds(key, true) /* enforce at top level */) { // If we succeed, and we have a specific location, find the bounds of the // specific. if (!specific.empty()) FindBounds(specific, false /* don't enforce at top level */); // We may have found trailing whitespace. Don't use base::TrimWhitespace, // because we want to keep any whitespace we find - just not highlight it. size_t trim = contents_.find_last_not_of(" \t\n\r", end_ - 1); if (trim < end_ && trim > start_) end_ = trim + 1; } else { // If we fail, then we set start to end so that the highlighted portion is // empty. start_ = end_; } } bool ManifestHighlighter::FindBounds(const std::string& feature, bool enforce_at_top_level) { char c = '\0'; while (start_ < end_) { c = contents_[start_]; if (c == '"') { // The feature may be quoted. size_t quote_end = start_; QuoteIncrement(contents_, &quote_end); if (contents_.substr(start_ + 1, quote_end - 1 - start_) == feature) { FindBoundsEnd(feature, quote_end + 1); return true; } else { // If it's not the feature, then we can skip the quoted section. start_ = quote_end + 1; } } else if (contents_.substr(start_, feature.size()) == feature) { FindBoundsEnd(feature, start_ + feature.size() + 1); return true; } else if (enforce_at_top_level && (c == '{' || c == '[')) { // If we don't have to be at the top level, then we can skip any chunks // we find. ChunkIncrement(contents_, &start_, end_); } else { CommentSafeIncrement(contents_, &start_); } } return false; } void ManifestHighlighter::FindBoundsEnd(const std::string& feature, size_t local_start) { char c = '\0'; while (local_start < end_) { c = contents_[local_start]; // We're done when we find a terminating character (i.e., either a comma or // an ending bracket. if (c == ',' || c == '}' || c == ']') { end_ = local_start; return; } // We can skip any chunks we find, since we are looking for the end of the // current feature, and don't want to go any deeper. if (c == '"' || c == '{' || c == '[') ChunkIncrement(contents_, &local_start, end_); else CommentSafeIncrement(contents_, &local_start); } } SourceHighlighter::SourceHighlighter(const std::string& contents, size_t line_number) : FileHighlighter(contents) { Parse(line_number); } SourceHighlighter::~SourceHighlighter() { } void SourceHighlighter::Parse(size_t line_number) { // If line 0 is requested, highlight nothing. if (line_number == 0) { start_ = contents_.size(); return; } for (size_t i = 1; i < line_number; ++i) { start_ = contents_.find('\n', start_); if (start_ == std::string::npos) break; start_ += 1; } end_ = contents_.find('\n', start_); // If we went off the end of the string (i.e., the line number was invalid), // then move start and end to the end of the string, so that the highlighted // portion is empty. start_ = start_ == std::string::npos ? contents_.size() : start_; end_ = end_ == std::string::npos ? contents_.size() : end_; } } // namespace extensions
SECTION code_user PUBLIC _extract_get_mmu _extract_get_mmu: ; When loading pages, a particular page must be brought ; into a specific mmu slot. However that mmu slot must ; not be occupied by the stack. This subroutine chooses ; a suitable mmu slot to do this paging. ; exit : hl = mmu slot to use ; ; used : af, hl ld hl,0xa000 xor a sbc hl,sp ld l,7 ld h,a ret nc ld l,3 ret
SECTION code_clib SECTION code_fp_math48 PUBLIC am48_double8u EXTERN am48_double16u am48_double8u: ; 8-bit unsigned integer to double ; ; enter : L = 8-bit unsigned integer n ; ; exit : AC = AC' (exx set saved) ; AC'= (double)(n) ; ; uses : af, bc, de, hl, bc', de', hl' ld h,0 jp am48_double16u
; A022977: 21-n. ; Submitted by Christian Krause ; 21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-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 sub $0,21 mul $0,-1
/* * Driver.hh * * Created on: Jan 23, 2012 * Author: cferenba * * Copyright (c) 2012, Los Alamos National Security, LLC. * All rights reserved. * Use of this source code is governed by a BSD-style open-source * license; see top-level LICENSE file for full license text. */ #ifndef DRIVER_HH_ #define DRIVER_HH_ #include <string> // forward declarations class InputFile; class Mesh; class Hydro; class Driver { public: // children of this object Mesh *mesh; Hydro *hydro; std::string probname; // problem name double time; // simulation time int cycle; // simulation cycle number double tstop; // simulation stop time int cstop; // simulation stop cycle double dtmax; // maximum timestep size double dtinit; // initial timestep size double dtfac; // factor limiting timestep growth int dtreport; // frequency for timestep reports double dt; // current timestep double dtlast; // previous timestep std::string msgdt; // dt limiter message std::string msgdtlast; // previous dt limiter message Driver(const InputFile* inp, const std::string& pname); ~Driver(); void run(); void calcGlobalDt(); }; // class Driver #endif /* DRIVER_HH_ */
db "ALPHA@" ; species name db "It is said to have" next "emerged from an" next "egg in a place" page "where there was" next "nothing, then it" next "shaped the world.@"
include w2.inc include noxport.inc include consts.inc include structs.inc createSeg edit_PCODE,edit2,byte,public,CODE ; DEBUGGING DECLARATIONS ifdef DEBUG midEditn2 equ 22 ; module ID, for native asserts endif ; EXTERNAL FUNCTIONS externFP <N_PdodMother> externFP <IInPlcRef> externFP <CpPlc> externFP <GetPlc> externFP <PutCpPlc> externFP <InvalParaSect> externFP <XDeleteFields> externFP <XDeleteBkmks> externFP <N_FOpenPlc> externFP <N_QcpQfooPlcfoo> externFP <InvalCp1> externFP <InvalText> externFP <IInPlcCheck> externFP <FlushRulerSprms> externFP <FChngSizePhqLcb> externFP <CpMac2Doc> externFP <CpMacDoc> externFP <XDelReferencedText> externFP <XDelInHplcEdit> externFP <XDeleteHdrText> externFP <CpMac1Doc> externFP <XCopyFields> externFP <XCopyBkmks> externFP <XAddHdrText> externFP <FSectLimAtCp> externFP <XAddToHplcEdit> externFP <XAddReferencedText> externFP <CopyMultPlc> externFP <PutPlc> externFP <AdjustHplcCpsToLim> externNP <LN_PxsInit> externNP <LN_PostTn> externNP <LN_FDoTns> externNP <LN_CloseTns> externFP <AdjustHplc> externFP <N_AdjustCp> externFP <IInPlc> externFP <SetErrorMatProc> ifdef DEBUG externFP <AssertProcForNative> externFP <FCkFldForDelete> externFP <S_XReplace> externFP <S_AdjustCp> externFP <S_XRepl1> externFP <AssertSzProc> externFP <LockHeap, UnlockHeap> externFP <S_FOpenPlc> externFP <S_FStretchPlc> externFP <S_XDelFndSedPgdPad> externFP <S_XReplaceCps> endif ;DEBUG sBegin data ; EXTERNALS externW caPage externW caPara externW caSect externW caTable externW caTap externW mpdochdod externW vdocFetch externW vlcb externW vrulss externW vtcc externW vsab externW mpsbps externW caHdt externW vtcxs externW vdocFetchVisi externW vcaCell externW asd externW vfInCommit externW vfNoInval externW vmerr externW docSeqCache externW vcbc externW vdocScratch externW caTapAux ifdef DEBUG externW cHpFreeze externW vdbs externW fDocScratchInUse endif ;DEBUG sEnd data ; CODE SEGMENT _EDIT sBegin edit2 assumes cs,edit2 assumes ds,dgroup assumes ss,dgroup ;------------------------------------------------------------------------- ; FReplace(pca, fn, fc, dfc) ;------------------------------------------------------------------------- ;/* F R E P L A C E */ ;/* Replace cpFirst through (cpLim-1) in doc by fc through (fc+dfc-1) in fn */ ;BOOL FReplace(pca, fn, fc, dfc) ;struct CA *pca; ;int fn; ;FC fc, dfc; ;{ ; struct XBC xbc; ; struct XSR *pxsr; ;#define ixsrReplaceMax 4 ; struct XSR rgxsr[ixsrReplaceMax]; ; %%Function:N_FReplace %%Owner:BRADV cProc N_FReplace,<PUBLIC,FAR>,<si,di> ParmW pca OFFBP_pca = -2 ParmW fn OFFBP_fn = -4 ParmD fc OFFBP_fc = -8 ParmD dfc OFFBP_dfc = -12 LocalV xbc,cbXbcMin LocalV rgxsr,4*cbXsrMin cBegin ; if (vrulss.caRulerSprm.doc != docNil) ; FlushRulerSprms(); ;LN_FlushRulerSprms performs ;if (vrulss.caRulerSprm.doc != docNil) ; FlushRulerSprms(); ;ax, bx, cx, dx are altered. call LN_FlushRulerSprms ; pxsr = PxsInit(rgxsr, ixsrReplaceMax, &xbc); ;LN_PxsInit takes pxs in si, ixsMax in cx, pxbc in bx ;and performs PxsInit(pxs, ixsMax, pxbc). ;ax, bx, cx, dx, di are altered. The result is returned in si. lea si,[rgxsr] mov cx,4 lea bx,[xbc] call LN_PxsInit ; pxsr->pcaDel = pca; ; pxsr->fn = fn; ; pxsr->fc = fc; ; pxsr->dfc = dfc; errnz <OFFBP_fc - OFFBP_dfc - 4> errnz <fcXsr - dfcXsr - 4> errnz <OFFBP_fn - OFFBP_fc - 4> errnz <fnXsr - fcXsr - 4> errnz <OFFBP_pca - OFFBP_fn - 2> errnz <pcaDelXsr - fnXsr - 2> ifdef DEBUG ;Assert es == ds with a call so as not to mess up short jumps. call FR06 endif ;DEBUG push si ;save pxsr mov di,si lea si,[dfc] mov cx,(OFFBP_pca - OFFBP_dfc + 2) SHR 1 rep movsw pop si ;restore pxsr ; XReplace(fTrue, &xbc, pxsr); lea di,[xbc] mov ax,fTrue push ax push di push si ifdef DEBUG cCall S_XReplace,<> else ;!DEBUG push cs call near ptr N_XReplace endif ;!DEBUG ; if (!FDoTns(&xbc)) ; { ;LN_FDoTns takes pxbc in di and performs FDoTns(pxbc). ;fTrue is returned iff carry is true upon return. ;ax, bx, cx, dx are altered. call LN_FDoTns jc FR02 ; SetErrorMat(matReplace); mov ax,matReplace cCall SetErrorMatProc,<ax> ; return fFalse; ; } jmp short FR05 FR02: ; BeginCommit(); ;#define BeginCommit() AssertDo(!vfInCommit++) ifdef DEBUG cmp [vfInCommit],0 je FR03 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1001 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax FR03: endif ;DEBUG inc [vfInCommit] ; XReplace(fFalse, &xbc, pxsr); xor ax,ax push ax push di push si ifdef DEBUG cCall S_XReplace,<> else ;!DEBUG push cs call near ptr N_XReplace endif ;!DEBUG ; EndCommit(); ;#define EndCommit() AssertDo(!--vfInCommit) dec [vfInCommit] ifdef DEBUG je FR04 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1002 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax FR04: endif ;DEBUG ; CloseTns(&xbc); ;LN_CloseTns takes &xbc in di and performs CloseTns. ;ax, bx, cx, dx are altered. call LN_CloseTns ; return fTrue; db 0B8h ;turns next "xor ax,ax" into "mov ax,immediate" FR05: xor ax,ax ;} cEnd ifdef DEBUG FR06: push ax push bx push cx push dx mov ax,ds mov bx,es cmp ax,bx je FR07 mov ax,midEditn2 mov bx,1003 cCall AssertProcForNative,<ax,bx> FR07: pop dx pop cx pop bx pop ax ret endif ;DEBUG ;------------------------------------------------------------------------- ; XReplace(fPlan, pxbc, pxsr) ;------------------------------------------------------------------------- ;/* X R E P L A C E */ ;/* Perform a bifuricated replacement */ ;XReplace(fPlan, pxbc, pxsr) ;BOOL fPlan; ;struct XBC *pxbc; ;struct XSR *pxsr; ;{ ; struct CA *pca = pxsr->pcaDel; ; %%Function:N_XReplace %%Owner:BRADV cProc N_XReplace,<PUBLIC,FAR>,<si,di> ParmW fPlan ParmW pxbc ParmW pxsr ifdef DEBUG LocalV rgchAttempt,42 LocalV rgchEditn,10 endif ;DEBUG cBegin mov di,[pxsr] mov si,[di.pcaDelXsr] ; Assert(pca->cpFirst >= cp0 && pca->cpLim <= CpMac1Doc(pca->doc)); ifdef DEBUG push ax push bx push cx push dx cmp [si.HI_cpFirstCa],0 jge XR01 mov ax,midEditn2 mov bx,1004 cCall AssertProcForNative,<ax,bx> XR01: cCall CpMac1Doc,<[si.docCa]> sub ax,[si.LO_cpLimCa] sbb dx,[si.HI_cpLimCa] jge XR02 mov ax,midEditn2 mov bx,1005 cCall AssertProcForNative,<ax,bx> XR02: pop dx pop cx pop bx pop ax endif ;DEBUG ; /* check that deleted portion may be deleted WRT fields */ ; AssertSz(!vdbs.fCkFldDel || FCkFldForDelete(pca->doc, pca->cpFirst, pca->cpLim), ; "Attempt to delete unmatched field char! " ); ;#define AssertSz(f,sz) ((f) ? 0 : AssertSzProc(SzFrame(sz),(CHAR *)szAssertFile,__LINE__)) ifdef DEBUG push ax push bx push cx push dx cmp [vdbs.fCkFldDelDbs],fFalse je Ltemp005 push [si.docCa] push [si.HI_cpFirstCa] push [si.LO_cpFirstCa] push [si.HI_cpLimCa] push [si.LO_cpLimCa] cCall FCkFldForDelete,<> or ax,ax je Ltemp006 Ltemp005: jmp XR04 Ltemp006: push si push di push ds push es push cs pop ds push ss pop es mov si,offset szAttempt1 lea di,[rgchAttempt] mov cx,cbSzAttempt1 rep movsb jmp short XR03 szAttempt1: db 'Attempt to delete unmatched field char! ',0 cbSzAttempt1 equ $ - szAttempt1 errnz <cbSzAttempt1 - 41> XR03: mov si,offset szEditn1 lea di,[rgchEditn] mov cx,cbSzEditn1 rep movsb jmp short XR035 szEditn1: db 'editn.asm',0 cbSzEditn1 equ $ - szEditn1 errnz <cbSzEditn1 - 10> XR035: pop es pop ds pop di pop si lea ax,[rgchAttempt] lea bx,[rgchEditn] mov cx,1027 cCall AssertSzProc,<ax,bx,cx> XR04: pop dx pop cx pop bx pop ax endif ;DEBUG ; if (DcpCa(pca) != 0) ;/* delete structures for text being deleted */ ; XDeleteStruct(fPlan, pxbc, pxsr); ;Assumes bx = pxbc, cx = fPlan, si = pca, di = pxsr ;ax, bx, cx, dx are altered. mov bx,[pxbc] mov cx,[fPlan] call LN_XDeleteStruct ; if (!fPlan && !vfNoInval) ; /* may call CachePara or FetchCp, must call BEFORE changing piece tbl */ ; InvalText (pca, fTrue /* fEdit */); mov ax,[vfNoInval] or ax,[fPlan] jne XR05 errnz <fTrue - fFalse - 1> inc ax cCall InvalText,<si,ax> XR05: ; XRepl1(fPlan, pxbc, pxsr); push [fPlan] push [pxbc] push di ifdef DEBUG cCall S_XRepl1,<> else ;!DEBUG call LN_XRepl1 endif ;!DEBUG ; if (!fPlan) ; { cmp [fPlan],fFalse jne XR10 ; if (!vfNoInval) ; InvalCp1(pca); ; else ; /* inval the caches even if vfNoInval on */ ; InvalCaFierce(); ;LN_DoInval assumes pca passed in si and performs ;if (!vfNoInval) { InvalCp1(pca); } ;else InvalCaFierce(); ;ax, bx, cx, dx are altered. call LN_DoInval ; AdjustCp(pca, pxsr->dfc); ; } push si push [di.HI_dfcXsr] push [di.LO_dfcXsr] ifdef DEBUG cCall S_AdjustCp,<> else ;!DEBUG push cs call near ptr N_AdjustCp endif ;!DEBUG XR10: ;} cEnd ;------------------------------------------------------------------------- ; IpcdSplit(hplcpcd, cp) ;------------------------------------------------------------------------- ;/* I P C D S P L I T */ ;/* Ensure cp is the beginning of a piece. Return index of that piece. */ ;/* NATIVE (pj 3/9): pcode version takes 4% of detokenize time and 2.4% of RTF time */ ;NATIVE int IpcdSplit(hplcpcd, cp) ;struct PLC **hplcpcd; ;CP cp; ;{ ; int ipcd; ; struct PCD pcd; ; CP dcp; ; %%Function:N_IpcdSplit %%Owner:BRADV cProc N_IpcdSplit,<PUBLIC,FAR>,<di> ParmW hplcpcd ParmD cp cBegin mov di,[hplcpcd] mov ax,[OFF_cp] mov dx,[SEG_cp] call LN_IpcdSplit cEnd ;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs ;IpcdSplit(hplcpcd, cp). The result is returned in ax. ;ax, bx, cx, dx are altered. ; %%Function:LN_IpcdSplit %%Owner:BRADV PUBLIC LN_IpcdSplit LN_IpcdSplit: ; vdocFetch = docNil; /* ensure fetch cache isn't lying */ ; if ((ipcd = IInPlcCheck(hplcpcd, cp)) == -1) ; return(IMacPlc(hplcpcd)); push si ;save caller's si push dx push ax ;save cp push di ;argument for IInPlcCheck push dx ;argument for IInPlcCheck push ax ;argument for IInPlcCheck errnz <docNil> xor ax,ax mov [vdocFetch],ax cCall IInPlcCheck,<> xchg ax,si inc si je IS02 dec si ; if ((dcp = cp - CpPlc(hplcpcd, ipcd)) != cp0) ; {{ /* !NATIVE (at least 50% of calls don't hit this code) */ cCall CpPlc,<di, si> pop bx pop cx ;restore cp sub ax,bx sbb dx,cx push ax or ax,dx pop ax jne IS05 IS005: xchg ax,si IS01: pop si ;restore caller's si ret IS02: mov bx,[di] mov bx,[bx] mov si,[bx.iMacPlcStr] IS03: pop ax pop dx ;restore cp jmp short IS005 IS04: pop di ;restore hplcpcd pop ax pop dx ;restore -dcp mov ax,matReplace cCall SetErrorMatProc,<ax> mov si,iNil jmp short IS03 IS05: ; Assert(!vfInCommit); ifdef DEBUG call IS07 endif ;DEBUG ;/* Insert a new piece flush with the one at ipcd */ ; if (!FOpenPlc(hplcpcd, ++ipcd, 1)) ; { push di ;save hplcpcd push dx push ax ;save -dcp push cx push bx ;save cp inc si mov ax,1 ifdef DEBUG cCall S_FOpenPlc,<di, si, ax> else ;not DEBUG cCall N_FOpenPlc,<di, si, ax> endif ;DEBUG xchg ax,cx jcxz IS04 ; SetErrorMat( matReplace ); ; return iNil; ; } ; QcpQfooPlcfoo takes hplcfoo in bx, ifoo in si, it returns pplcfoo ; in bx, cbfoo in cx, qcp in es:di, qfoo in es:si. ; if DEBUG it returns hpcp in dx:di, hpfoo in dx:si. ; Changes ax, bx, cx, dx, si, di. push si ;save ipcd mov bx,di ifdef DEBUG xor di,di ;Not O.K. to pass ifldMac endif ;DEBUG cCall N_QcpQfooPlcfoo,<> ifdef DEBUG ;Check that es == mpsbps[dx]; call IS09 endif ;DEBUG pop ax ;restore ipcd pop cx pop dx ;restore cp ; PutCpPlc(hplcpcd, ipcd, cp); cmp ax,[bx.icpAdjustPlc] jl IS06 sub cx,[bx.LO_dcpAdjustPlc] sbb dx,[bx.HI_dcpAdjustPlc] IS06: mov es:[di],cx mov es:[di+2],dx ; /* We are doing effectively: ; pcd.fn = pcdPrev.fn; ; pcd.fc = pcdPrev.fc + dcp; ; pcd.prm = pcdPrev.prm; ; pcd.fNoParaLastValid = pcdPrev.fNoParaLast; ; pcd.fNoParaLast = pcdPrev.fNoParaLast; ; */ ; GetPlc(hplcpcd, ipcd - 1, &pcd); ; pcd.fc += dcp; ; PutPlc(hplcpcd, ipcd, &pcd); pop cx pop dx ;restore -dcp push es pop ds mov di,si sub si,cbPcdMin push ax ;save ipcd errnz <cbPcdMin - 8> movsw errnz <(LO_fcPcd) - 2> lodsw sub ax,cx stosw errnz <(HI_fcPcd) - 4> lodsw sbb ax,dx stosw movsw push ss pop ds pop ax ;restore ipcd pop di ;restore hplcpcd ; }} ; return ipcd; ;} jmp short IS01 ifdef DEBUG ;Do this assert with a call so as not to mess up short jumps. IS07: cmp [vfInCommit],fFalse je IS08 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1006 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax IS08: ret endif ;DEBUG ifdef DEBUG IS09: push ax push bx push cx push dx push es ;save es from QcpQfooPlcfoo mov bx,dx shl bx,1 mov ax,mpsbps[bx] mov es,ax shr ax,1 jc IS10 ;Assembler note: There is no way we should have to call ReloadSb here. ; reload sb trashes ax, cx, and dx ; cCall ReloadSb,<> mov ax,midEditn2 mov bx,1007 cCall AssertProcForNative,<ax,bx> IS10: pop ax ;restore es from QcpQfooPlcfoo mov bx,es ;compare with es rederived from the SB of QcpQfooPlcfoo cmp ax,bx je IS11 mov ax,midEditn2 mov bx,1008 cCall AssertProcForNative,<ax,bx> IS11: pop dx pop cx pop bx pop ax ret endif ;/* DEBUG */ ;------------------------------------------------------------------------- ; XRepl1(fPlan, pxbc, pxsr) ;------------------------------------------------------------------------- ;/* X R E P L 1 */ ;/* perform Bifuricated replacement */ ;/* NATIVE (pj 3/9): taking 5.6% of RTF time, 9.9% of detokenize time */ ;NATIVE XRepl1(fPlan, pxbc, pxsr) ;BOOL fPlan; ;struct XBC *pxbc; ;struct XSR *pxsr; ;{ ; struct PLC **hplcpcd; ; int ipcdFirst, ipcdLim; ; int cpcd; ; struct PCD pcd; ; struct PCD pcdPrev; ifdef DEBUG ; %%Function:N_XRepl1 %%Owner:BRADV cProc N_XRepl1,<PUBLIC,FAR>,<si,di> else ;!DEBUG ; %%Function:LN_XRepl1 %%Owner:BRADV cProc LN_XRepl1,<PUBLIC,NEAR>,<si,di> endif ;!DEBUG ParmW fPlan ParmW pxbc ParmW pxsr LocalW OFF_qpcd cBegin ; hplcpcd = PdodDoc(pxsr->pcaDel->doc)->hplcpcd; ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. mov di,[pxsr] mov si,[di.pcaDelXsr] call LN_PdodDocCa mov di,[bx.hplcpcdDod] ; if (fPlan) ; { mov ax,[si.LO_cpFirstCa] mov dx,[si.HI_cpFirstCa] cmp [fPlan],fFalse je XR103 ;Requires dx:ax = pxsr->pcaDel->cpFirst, ;si is pxsr->pcaDel, di is hplcpcd ; pxsr->fNotEmptyPcaDel = (pxsr->pcaDel->cpFirst != pxsr->pcaDel->cpLim); mov bx,[si.LO_cpLimCa] mov cx,[si.HI_cpLimCa] sub bx,ax sbb cx,dx or cx,bx mov bx,[pxsr] mov [bx.fNotEmptyPcaDelXsr],cx ; if ((ipcdFirst = IpcdSplit(hplcpcd, pxsr->pcaDel->cpFirst)) ; == iNil) ; { ;LPostAbort: ; PostTn(pxbc, tntAbort, NULL, 0); ; return; ; } ;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs ;IpcdSplit(hplcpcd, cp). The result is returned in ax. ;ax, bx, cx, dx are altered. call LN_IpcdSplit mov bx,[pxsr] errnz <iNil - (-1)> inc ax je XR102 dec ax ; if (!pxsr->fNotEmptyPcaDel) ; cpcd = 0; mov cx,[bx.fNotEmptyPcaDelXsr] jcxz XR101 ; else ; { ; int ipcdLim; ; if ((ipcdLim = IpcdSplit(hplcpcd, pxsr->pcaDel->cpLim)) ; == iNil) ; goto LPostAbort; push ax ;save ipcdFirst mov ax,[si.LO_cpLimCa] mov dx,[si.HI_cpLimCa] ;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs ;IpcdSplit(hplcpcd, cp). The result is returned in ax. ;ax, bx, cx, dx are altered. call LN_IpcdSplit mov bx,[pxsr] pop cx ;restore ipcdFirst errnz <iNil - (-1)> inc ax je XR102 dec ax ; cpcd = ipcdFirst - ipcdLim; ; } sub cx,ax XR101: ; pxsr->cpcd = cpcd; ; } mov [bx.cpcdXsr],cx ;Assembler note: the following assert is performed below in the ;C source. ; /* number of pieces to be added (negative or zero) */ ; Assert(cpcd <= 0); ifdef DEBUG ;Do this assert with a call so as not to mess up short jumps. call XR110 endif ;DEBUG ;Assembler note: Why check fPlan twice? Do the stuff in the following ;"if (fPlan)" here. ; PostTn(pxbc, tntHplc, hplcpcd, cpcd+1); ;LN_PostTn takes pxbc in bx, tnt in ax, c in cx, h in dx and ;performs PostTn(pxbc, tnt, h, c). ;ax, bx, cx, dx are altered. mov ax,tntHplc mov dx,di inc cx XR1015: mov bx,[pxbc] call LN_PostTn jmp XR109 XR102: ;LN_PostTn takes pxbc in bx, tnt in ax, c in cx, h in dx and ;performs PostTn(pxbc, tnt, h, c). ;ax, bx, cx, dx are altered. mov ax,tntAbort errnz <NULL> xor cx,cx xor dx,dx jmp short XR1015 ; else ; { XR103: ;Assume dx:ax = pxsr->pcaDel->cpFirst, ;si is pxsr->pcaDel, di is hplcpcd ; ipcdFirst = IpcdSplit(hplcpcd, pxsr->pcaDel->cpFirst); ;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs ;IpcdSplit(hplcpcd, cp). The result is returned in ax. ;ax, bx, cx, dx are altered. call LN_IpcdSplit mov bx,[pxsr] ; cpcd = pxsr->cpcd; ; Assert(!pxsr->fNotEmptyPcaDel || ; IInPlc(hplcpcd, pxsr->pcaDel->cpLim) == ipcdFirst - cpcd); ifdef DEBUG ;Do this assert with a call so as not to mess up short jumps. call XR112 endif ;DEBUG ; /* set so vhprc chain is checked when we run out of memory */ ; vmerr.fReclaimHprcs = fTrue; or [vmerr.fReclaimHprcsMerr],maskFReclaimHprcsMerr ; } ; /* number of pieces to be added (negative or zero) */ ; Assert(cpcd <= 0); ifdef DEBUG ;Do this assert with a call so as not to mess up short jumps. call XR110 endif ;DEBUG ; if (fPlan) ; /* simplified, may be one less */ ; PostTn(pxbc, tntHplc, hplcpcd, cpcd+1); ;Assembler note: the "if (fPlan)" case is done above ;in the assembler version. ; else ; { ; if (ipcdFirst > 0) ; GetPlc(hplcpcd, ipcdFirst - 1, &pcdPrev); ; ; if (pxsr->dfc == fc0 || ; (ipcdFirst > 0 && pcdPrev.fn == pxsr->fn && ; pcdPrev.prm == prmNil && pcdPrev.fc + ; (pxsr->pcaDel->cpFirst - CpPlc(hplcpcd,ipcdFirst-1)) ; == pxsr->fc)) ; /* Either pure delete or extension of previous piece */ ; { mov cx,[bx.LO_dfcXsr] or cx,[bx.HI_dfcXsr] je XR106 ;carry clear, pass cpcd to FOpenPlc cmp ax,1 jc XR106 ;carry set, pass cpcd+1 to FOpenPlc ; QcpQfooPlcfoo takes hplcfoo in bx, ifoo in si, it returns pplcfoo ; in bx, cbfoo in cx, qcp in es:di, qfoo in es:si. ; if DEBUG it returns hpcp in dx:di, hpfoo in dx:si. ; Changes ax, bx, cx, dx, si, di. push di ;save hplcpcd push ax ;save ipcdFirst push si ;save pxsr->pcaDel xchg ax,si dec si mov bx,di ifdef DEBUG xor di,di ;Not O.K. to pass ifldMac endif ;DEBUG cCall N_QcpQfooPlcfoo,<> ifdef DEBUG ;Check that es == mpsbps[dx]; call XR114 endif ;DEBUG ; (ipcdFirst > 0 && pcdPrev.fn == pxsr->fn && ; pcdPrev.prm == prmNil && pcdPrev.fc + ; (pxsr->pcaDel->cpFirst - CpPlc(hplcpcd,ipcdFirst-1)) ; == pxsr->fc)) mov [OFF_qpcd],si ;save for later push bx ;save pplcpcd mov bx,[pxsr] mov cx,[bx.fnXsr] mov ax,[bx.LO_fcXsr] mov dx,[bx.HI_fcXsr] pop bx ;restore pplcpcd cmp es:[si.fnPcd],cl jne XR105 cmp es:[si.prmPcd],prmNil jne XR105 sub ax,es:[si.LO_fcPcd] sbb dx,es:[si.HI_fcPcd] pop si ;restore pxsr->pcaDel pop cx ;restore ipcdFirst push cx ;save ipcdFirst push si ;save pxsr->pcaDel sub ax,[si.LO_cpFirstCa] sbb dx,[si.HI_cpFirstCa] ;***Begin in-line CpPlc add ax,es:[di] adc dx,es:[di+2] cmp cx,[bx.icpAdjustPlc] ;Assembler note: use jle instead of jl here because cx is ipcd+1, ;not ipcd. jle XR104 add ax,[bx.LO_dcpAdjustPlc] adc dx,[bx.HI_dcpAdjustPlc] XR104: ;***End in-line CpPlc or ax,dx XR105: pop si ;restore pxsr->pcaDel pop ax ;restore ipcdFirst pop di ;restore hplcpcd ; FOpenPlc(hplcpcd, ipcdFirst, cpcd); ; if (pxsr->dfc != fc0) ; /* If extending, say we might have inserted Eop*/ ; { ; Debug(pcdPrev.fNoParaLastValid = fFalse); ; pcdPrev.fNoParaLast = fFalse; ; PutPlc(hplcpcd, ipcdFirst - 1, &pcdPrev); ; } ; } ; else ; /* Insert one piece */ ; { ; AssertDo(FOpenPlc(hplcpcd, ipcdFirst, cpcd + 1)); stc jne XR106 ;carry set, pass cpcd+1 to FOpenPlc ;Assembler note: set the FNoParaLast flags before the call ;to FOpenPlc rather than after because we have the pointers now. mov bx,[OFF_qpcd] ;restore from above ifdef DEBUG errnz <(fNoParaLastValidPcd) - (fNoParaLastPcd)> and es:[bx.fNoParaLastPcd],NOT (maskFNoParaLastPcd + maskFNoParaLastValidPcd) else ;!DEBUG and es:[bx.fNoParaLastPcd],NOT maskFNoParaLastPcd endif ;!DEBUG ;carry clear, pass cpcd to FOpenPlc ;ax = ipcdFirst, si = pxsr->pcaDel, di = hplcpcd, ;we want to pass cpcd + carry to FOpenPlc XR106: push ax ;save ipcdFirst pushf mov bx,[pxsr] mov cx,[bx.cpcdXsr] adc cx,0 ifdef DEBUG cCall S_FOpenPlc,<di, ax, cx> else ;not DEBUG cCall N_FOpenPlc,<di, ax, cx> endif ;DEBUG ifdef DEBUG ;Perform the AssertDo with a call so as not to mess up short jumps. call XR117 endif ;DEBUG popf pop ax ;restore ipcdFirst jnc XR108 ;if we called FOpenPlc with cpcd we're done ; QcpQfooPlcfoo takes hplcfoo in bx, ifoo in si, it returns pplcfoo ; in bx, cbfoo in cx, qcp in es:di, qfoo in es:si. ; if DEBUG it returns hpcp in dx:di, hpfoo in dx:si. ; Changes ax, bx, cx, dx, si, di. push di ;save hplcpcd push ax ;save ipcdFirst push si ;save pxsr->pcaDel xchg ax,si mov bx,di ifdef DEBUG xor di,di ;Not O.K. to pass ifldMac endif ;DEBUG cCall N_QcpQfooPlcfoo,<> ifdef DEBUG ;Check that es == mpsbps[dx]; call XR114 endif ;DEBUG ; GetPlc(hplcpcd, ipcdFirst, &pcd); ; PutCpPlc(hplcpcd, ipcdFirst, pxsr->pcaDel->cpFirst); ; pcd.fn = pxsr->fn; ; pcd.fc = pxsr->fc; ; pcd.prm = prmNil; ; Debug(pcd.fNoParaLastValid = fFalse); ; pcd.fNoParaLast = fFalse; /* Para state unknown */ ; pcd.fPaphNil = fFalse; ; pcd.fCopied = fTrue; ; PutPlc(hplcpcd, ipcdFirst, &pcd); push bx ;save pplcpcd mov bx,[pxsr] ifdef DEBUG errnz <(fNoParaLastValidPcd) - (fNoParaLastPcd)> endif ;!DEBUG errnz <(fPaphNilPcd) - (fNoParaLastPcd)> errnz <(fCopiedPcd) - (fNoParaLastPcd)> mov cl,maskFCopiedPcd errnz <(fnPcd) - (fNoParaLastPcd) - 1> mov ch,bptr ([bx.fnXsr]) mov wptr (es:[si.fNoParaLastPcd]),cx mov ax,[bx.LO_fcXsr] mov dx,[bx.HI_fcXsr] mov es:[si.LO_fcPcd],ax mov es:[si.HI_fcPcd],dx pop bx ;restore pplcpcd mov es:[si.prmPcd],prmNil pop si ;restore pxsr->pcaDel pop ax ;restore ipcdFirst mov cx,[si.LO_cpFirstCa] mov dx,[si.HI_cpFirstCa] ;***Begin in-line PutCpPlc cmp ax,[bx.icpAdjustPlc] jl XR107 sub cx,[bx.LO_dcpAdjustPlc] sbb dx,[bx.HI_dcpAdjustPlc] XR107: mov es:[di],cx mov es:[di+2],dx ;***End in-line PutCpPlc pop di ;restore hplcpcd ; ipcdFirst++; ; } inc ax XR108: ; AdjustHplc(hplcpcd, pxsr->pcaDel->cpLim, pxsr->dfc - pxsr->pcaDel->cpLim + ; pxsr->pcaDel->cpFirst, ipcdFirst); ;ax = ipcdFirst, si = pxsr->pcaDel, di = hplcpcd mov bx,[pxsr] push di push [si.HI_cpLimCa] push [si.LO_cpLimCa] mov dx,[bx.HI_dfcXsr] mov cx,[bx.LO_dfcXsr] sub cx,[si.LO_cpLimCa] sbb dx,[si.HI_cpLimCa] add cx,[si.LO_cpFirstCa] adc dx,[si.HI_cpFirstCa] push dx push cx push ax push cs call near ptr AdjustHplc ; InvalVisiCache(); ;#define InvalVisiCache() vdocFetchVisi = docNil; vcbc.w = 0 errnz <docNil - 0> xor ax,ax mov [vdocFetchVisi],ax mov [vcbc],ax ; InvalCellCache(); ;#define InvalCellCache() (vcaCell.doc = docNil) mov [vcaCell.docCa],ax ; } XR109: ;} cEnd ; Assert(cpcd <= 0); ifdef DEBUG XR110: push ax push bx push cx push dx mov bx,[pxsr] cmp [bx.cpcdXsr],0 jle XR111 mov ax,midEditn2 mov bx,1009 cCall AssertProcForNative,<ax,bx> XR111: pop dx pop cx pop bx pop ax ret endif ;DEBUG ; Assert(!pxsr->fNotEmptyPcaDel || ; IpcdSplit(hplcpcd, pxsr->pcaDel->cpLim) == ipcdFirst - cpcd); ifdef DEBUG XR112: push ax push bx push cx push dx mov bx,[pxsr] cmp [bx.fNotEmptyPcaDelXsr],0 je XR113 sub ax,[bx.cpcdXsr] push ax ;save ipcdFirst - cpcd mov dx,[si.HI_cpLimCa] mov ax,[si.LO_cpLimCa] ;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs ;IpcdSplit(hplcpcd, cp). The result is returned in ax. ;ax, bx, cx, dx are altered. call LN_IpcdSplit pop cx ;restore ipcdFirst - cpcd cmp ax,cx je XR113 mov ax,midEditn2 mov bx,1010 cCall AssertProcForNative,<ax,bx> XR113: pop dx pop cx pop bx pop ax ret endif ;DEBUG ifdef DEBUG XR114: push ax push bx push cx push dx push es ;save es from QcpQfooPlcfoo mov bx,dx shl bx,1 mov ax,mpsbps[bx] mov es,ax shr ax,1 jc XR115 ;Assembler note: There is no way we should have to call ReloadSb here. ; reload sb trashes ax, cx, and dx ; cCall ReloadSb,<> mov ax,midEditn2 mov bx,1011 cCall AssertProcForNative,<ax,bx> XR115: pop ax ;restore es from QcpQfooPlcfoo mov bx,es ;compare with es rederived from the SB of QcpQfooPlcfoo cmp ax,bx je XR116 mov ax,midEditn2 mov bx,1012 cCall AssertProcForNative,<ax,bx> XR116: pop dx pop cx pop bx pop ax ret endif ;/* DEBUG */ ; AssertDo(FOpenPlc(hplcpcd, ipcdFirst, cpcd + carry)); ifdef DEBUG XR117: or ax,ax jne XR118 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1013 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax XR118: ret endif ;DEBUG ;LN_DoInval assumes pca passed in si and performs ;if (!vfNoInval) { InvalCp1(pca); } ;else InvalCaFierce(); ;ax, bx, cx, dx are altered. LN_DoInval: mov ax,[vfNoInval] or ax,ax jne LN_InvalCaFierce errnz <fTrue - 1> inc ax cCall InvalCp1,<si> ret ;------------------------------------------------------------------------- ; InvalCaFierce() ;------------------------------------------------------------------------- ;/* I n v a l C a F i e r c e */ ;/* NATIVE (pj 3/9) called very frequently for operations with vfNoInval */ ;NATIVE InvalCaFierce() ;{ ;/* unconditionally invalidate CAs and other important docs */ ; InvalLlc(); ;#define InvalLlc() ; %%Function:N_InvalCaFierce %%Owner:BRADV PUBLIC N_InvalCaFierce N_InvalCaFierce: call LN_InvalCaFierce db 0CBh ;far ret LN_InvalCaFierce: errnz <docNil> xor ax,ax ; vdocFetch = docNil; mov [vdocFetch],ax ; caSect.doc = docNil; mov [caSect.docCa],ax ; caPara.doc = docNil; mov [caPara.docCa],ax ; caPage.doc = docNil; mov [caPage.docCa],ax ; caTable.doc = docNil; mov [caTable.docCa],ax ; caTap.doc = docNil; mov [caTap.docCa],ax ; caHdt.doc = docNil; mov [caHdt.docCa],ax ; vtcc.ca.doc = docNil; mov [vtcc.caTcc.docCa],ax ; vtcc.caTap.doc = docNil; mov [vtcc.caTapTcc.docCa],ax ; caTapAux.doc = docNil; mov [caTapAux.docCa],ax ; vtcxs.ca.doc = docNil; mov [vtcxs.caTcxs.docCa],ax ; Win( vlcb.ca.doc = docNil ); mov [vlcb.caLcb.docCa],ax ; Win( InvalVisiCache() ); ;#define InvalVisiCache() (vdocFetchVisi = docNil) mov [vdocFetchVisi],ax ; Win( InvalCellCache() ); ;#define InvalCellCache() (vcaCell.doc = docNil) mov [vcaCell.docCa],ax ; Win( docSeqCache = docNil ); mov [docSeqCache],ax ;} ret ;------------------------------------------------------------------------- ; FRepl1(fPlan, pxbc, pxsr) ;------------------------------------------------------------------------- ;/* F R E P L 1 */ ;/* delete pca and insert the specified piece (does not do checking or ;adjustment) */ ;BOOL FRepl1(pca, fn, fc, dfc) ;struct CA *pca; ;int fn; ;FC fc, dfc; ;{ ; struct XBC xbc; ; struct XSR *pxsr; ;#define ixsrRepl1Max 1 ; struct XSR rgxsr[ixsrRepl1Max]; ; %%Function:N_FRepl1 %%Owner:BRADV cProc N_FRepl1,<PUBLIC,FAR>,<si,di> ParmW pca OFFBP_pca = -2 ParmW fn OFFBP_fn = -4 ParmD fc OFFBP_fc = -8 ParmD dfc OFFBP_dfc = -12 LocalV xbc,cbXbcMin LocalV rgxsr,1*cbXsrMin cBegin ; pxsr = (struct XSR *)PxsInit(rgxsr, ixsrRepl1Max, &xbc); ;LN_PxsInit takes pxs in si, ixsMax in cx, pxbc in bx ;and performs PxsInit(pxs, ixsMax, pxbc). ;ax, bx, cx, dx, di are altered. The result is returned in si. lea si,[rgxsr] mov cx,1 lea bx,[xbc] call LN_PxsInit ; pxsr->pcaDel = pca; ; pxsr->fn = fn; ; pxsr->fc = fc; ; pxsr->dfc = dfc; errnz <OFFBP_fc - OFFBP_dfc - 4> errnz <fcXsr - dfcXsr - 4> errnz <OFFBP_fn - OFFBP_fc - 4> errnz <fnXsr - fcXsr - 4> errnz <OFFBP_pca - OFFBP_fn - 2> errnz <pcaDelXsr - fnXsr - 2> ifdef DEBUG ;Assert es == ds with a call so as not to mess up short jumps. call FR105 endif ;DEBUG push si ;save pxsr mov di,si lea si,[dfc] mov cx,(OFFBP_pca - OFFBP_dfc + 2) SHR 1 rep movsw pop si ;restore pxsr ; XRepl1(fTrue, &xbc, pxsr); mov ax,fTrue lea di,[xbc] push ax push di push si ifdef DEBUG cCall S_XRepl1,<> else ;!DEBUG call LN_XRepl1 endif ;!DEBUG ; if (!FDoTns(&xbc)) ; { ;LN_FDoTns takes pxbc in di and performs FDoTns(pxbc). ;fTrue is returned iff carry is true upon return. ;ax, bx, cx, dx are altered. call LN_FDoTns jc FR101 ; SetErrorMat(matReplace); ; return fFalse; mov ax,matReplace cCall SetErrorMatProc,<ax> jmp short FR104 ; } FR101: ; BeginCommit(); ;#define BeginCommit() AssertDo(!vfInCommit++) ifdef DEBUG cmp [vfInCommit],0 je FR102 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1014 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax FR102: endif ;DEBUG inc [vfInCommit] ; XRepl1(fFalse, &xbc, pxsr); errnz <fFalse> xor ax,ax push ax push di push si ifdef DEBUG cCall S_XRepl1,<> else ;!DEBUG call LN_XRepl1 endif ;!DEBUG ; EndCommit(); ;#define EndCommit() AssertDo(!--vfInCommit) dec [vfInCommit] ifdef DEBUG je FR103 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1015 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax FR103: endif ;DEBUG ; CloseTns(&xbc); ;LN_CloseTns takes &xbc in di and performs CloseTns. ;ax, bx, cx, dx are altered. call LN_CloseTns ; return fTrue; db 0B8h ;turns next "xor ax,ax" into "mov ax,immediate" FR104: xor ax,ax ;} cEnd ifdef DEBUG FR105: push ax push bx push cx push dx mov ax,ds mov bx,es cmp ax,bx je FR106 mov ax,midEditn2 mov bx,1016 cCall AssertProcForNative,<ax,bx> FR106: pop dx pop cx pop bx pop ax ret endif ;DEBUG ;------------------------------------------------------------------------- ; FReplaceCps(pcaDel, pcaIns) ;------------------------------------------------------------------------- ;/* F R E P L A C E C P S */ ;/* General replace routine */ ;/* Replace characters from [pcaDel->cpFirst,pcaDel->cpLim) with characters ; from [pcaIns->cpFirst,pcaIns->cpLim) */ ;BOOL FReplaceCps(pcaDel, pcaIns) ;struct CA *pcaDel, *pcaIns; ;{ ; struct XBC xbc; ; struct XSR *pxsr; ;#define ixsrReplaceCpsMax WinMac(10,8) ; struct XSR rgxsr[ixsrReplaceCpsMax]; ; %%Function:N_FReplaceCps %%Owner:BRADV cProc N_FReplaceCps,<PUBLIC,FAR>,<si,di> ParmW pcaDel ParmW pcaIns LocalV xbc,cbXbcMin LocalV rgxsr,10*cbXsrMin cBegin ; Assert(pcaDel->cpFirst >= cp0 && pcaDel->cpLim <= CpMac1Doc(pcaDel->doc)); ; Assert(DcpCa(pcaDel) >= cp0 && DcpCa(pcaIns) >= cp0); ifdef DEBUG push ax push bx push cx push dx push si mov si,[pcaDel] cmp [si.HI_cpFirstCa],0 jge FRC01 mov ax,midEditn2 mov bx,1017 cCall AssertProcForNative,<ax,bx> FRC01: cCall CpMac1Doc,<[si.docCa]> sub ax,[si.LO_cpLimCa] sbb dx,[si.HI_cpLimCa] jge FRC02 mov ax,midEditn2 mov bx,1018 cCall AssertProcForNative,<ax,bx> FRC02: ;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax. ;Only ax and dx are altered. call LN_DcpCa or dx,dx jge FRC03 mov ax,midEditn2 mov bx,1019 cCall AssertProcForNative,<ax,bx> FRC03: mov si,[pcaIns] ;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax. ;Only ax and dx are altered. call LN_DcpCa or dx,dx jge FRC04 mov ax,midEditn2 mov bx,1020 cCall AssertProcForNative,<ax,bx> FRC04: pop si pop dx pop cx pop bx pop ax endif ;DEBUG ; if (vrulss.caRulerSprm.doc != docNil) ; FlushRulerSprms(); ;LN_FlushRulerSprms performs ;if (vrulss.caRulerSprm.doc != docNil) ; FlushRulerSprms(); ;ax, bx, cx, dx are altered. call LN_FlushRulerSprms ; pxsr = (struct XSR *)PxsInit(rgxsr, ixsrReplaceCpsMax, &xbc); ;LN_PxsInit takes pxs in si, ixsMax in cx, pxbc in bx ;and performs PxsInit(pxs, ixsMax, pxbc). ;ax, bx, cx, dx, di are altered. The result is returned in si. lea si,[rgxsr] mov cx,10 lea bx,[xbc] call LN_PxsInit ; pxsr->pcaDel = pcaDel; ; pxsr->pcaIns = pcaIns; mov ax,[pcaDel] mov [si.pcaDelXsr],ax mov ax,[pcaIns] mov [si.pcaInsXsr],ax ; XReplaceCps(fTrue, &xbc, pxsr); mov ax,fTrue lea di,[xbc] push ax push di push si ifdef DEBUG cCall S_XReplaceCps,<> else ;!DEBUG push cs call near ptr N_XReplaceCps endif ;!DEBUG ; if (!FDoTns(&xbc)) ; { ;LN_FDoTns takes pxbc in di and performs FDoTns(pxbc). ;fTrue is returned iff carry is true upon return. ;ax, bx, cx, dx are altered. call LN_FDoTns jc FRC05 ; SetErrorMat(matReplace); ; return fFalse; mov ax,matReplace cCall SetErrorMatProc,<ax> jmp short FRC08 ; } FRC05: ; BeginCommit(); ;#define BeginCommit() AssertDo(!vfInCommit++) ifdef DEBUG cmp [vfInCommit],0 je FRC06 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1021 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax FRC06: endif ;DEBUG inc [vfInCommit] ; XReplaceCps(fFalse, &xbc, pxsr); errnz <fFalse> xor ax,ax push ax push di push si ifdef DEBUG cCall S_XReplaceCps,<> else ;!DEBUG push cs call near ptr N_XReplaceCps endif ;!DEBUG ; EndCommit(); ;#define EndCommit() AssertDo(!--vfInCommit) dec [vfInCommit] ifdef DEBUG je FRC07 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1022 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax FRC07: endif ;DEBUG ; CloseTns(&xbc); ;LN_CloseTns takes &xbc in di and performs CloseTns. ;ax, bx, cx, dx are altered. call LN_CloseTns ; return fTrue; db 0B8h ;turns next "xor ax,ax" into "mov ax,immediate" FRC08: xor ax,ax ;} cEnd ;------------------------------------------------------------------------- ; XReplaceCps(fPlan, pxbc, pxsr) ;------------------------------------------------------------------------- ;/* X R E P L A C E C P S */ ;XReplaceCps(fPlan, pxbc, pxsr) ;BOOL fPlan; ;struct XBC *pxbc; ;struct XSR *pxsr; ;{ ; struct PLC **hplcpcdDest, **hplcpcdSrc; ; int ipcdFirst, ipcdInsFirst, ipcdLim; ; int cpcd; ; struct CA *pcaDel = pxsr->pcaDel; ; struct CA *pcaIns = pxsr->pcaIns; ; int docDel = pcaDel->doc; ; int docIns = pcaIns->doc; ; CP dcpDel = DcpCa(pcaDel); ; CP dcpIns = DcpCa(pcaIns); ; struct DOD **hdodSrc = mpdochdod[docIns]; ; struct DOD **hdodDest = mpdochdod[docDel]; ; struct PCD pcd; ; %%Function:N_XReplaceCps %%Owner:BRADV cProc N_XReplaceCps,<PUBLIC,FAR>,<si,di> ParmW fPlan ParmW pxbc ParmW pxsr LocalW ipcdFirst LocalW ipcdLim LocalW ipcdInsFirst LocalW hplcpcdSrc LocalW hplcpcdDest LocalD dcpIns LocalD dcpDel LocalV pcd,cbPcdMin LocalV caDel,cbCaMin LocalV caIns,cbCaMin LocalV xbc,cbXbcMin LocalV rgxsr,10*cbXsrMin ifdef DEBUG LocalV rgchAttempt,42 LocalV rgchEditn,10 endif ;DEBUG cBegin ;#ifdef DEBUG ifdef DEBUG ; if (fPlan) ; /* no point doing all this twice! */ ; { cmp [fPlan],fFalse jne Ltemp009 jmp XRC12 Ltemp009: push ax push bx push cx push dx push si ; Assert(pcaDel->cpFirst >= cp0 && pcaDel->cpLim <= CpMac1Doc(docDel)); mov bx,[pxsr] mov si,[bx.pcaDelXsr] cmp [si.HI_cpFirstCa],0 jge XRC01 mov ax,midEditn2 mov bx,1023 cCall AssertProcForNative,<ax,bx> XRC01: cCall CpMac1Doc,<[si.docCa]> sub ax,[si.LO_cpLimCa] sbb dx,[si.HI_cpLimCa] jge XRC02 mov ax,midEditn2 mov bx,1024 cCall AssertProcForNative,<ax,bx> XRC02: ; Assert(dcpDel >= 0 && dcpIns >= cp0); ;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax. ;Only ax and dx are altered. mov bx,[pxsr] mov si,[bx.pcaDelXsr] call LN_DcpCa or dx,dx jge XRC03 mov ax,midEditn2 mov bx,1025 cCall AssertProcForNative,<ax,bx> XRC03: ;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax. ;Only ax and dx are altered. mov bx,[pxsr] mov si,[bx.pcaInsXsr] call LN_DcpCa or dx,dx jge XRC04 mov ax,midEditn2 mov bx,1026 cCall AssertProcForNative,<ax,bx> XRC04: ; Assert(docDel != docIns); mov bx,[pxsr] mov si,[bx.pcaDelXsr] mov ax,[si.docCa] mov si,[bx.pcaInsXsr] cmp ax,[si.docCa] jne XRC05 mov ax,midEditn2 mov bx,1027 cCall AssertProcForNative,<ax,bx> XRC05: ; /* assured by caller */ ; Assert(vrulss.caRulerSprm.doc == docNil); cmp [vrulss.caRulerSprmRulss.docCa],docNil je XRC06 mov ax,midEditn2 mov bx,1028 cCall AssertProcForNative,<ax,bx> XRC06: ; /* assure that if vdocScratch is being used, it has been "Acquired" */ ; Assert ((vdocScratch == docNil || (docDel != vdocScratch && ; docIns != vdocScratch) || fDocScratchInUse)); mov ax,[vdocScratch] cmp ax,docNil je XRC08 cmp [fDocScratchInUse],fFalse jne XRC08 cmp ax,[si.docCa] je XRC07 mov bx,[pxsr] mov bx,[bx.pcaDelXsr] cmp ax,[bx.docCa] jne XRC08 XRC07: mov ax,midEditn2 mov bx,1029 cCall AssertProcForNative,<ax,bx> XRC08: ; /* check that deleted portion is legal WRT fields */ ; AssertSz(!vdbs.fCkFldDel || FCkFldForDelete(docDel, pcaDel->cpFirst, pcaDel->cpLim) ; && FCkFldForDelete(pcaIns->doc, pcaIns->cpFirst, pcaIns->cpLim), ; "Attempt to delete unmatched field char!"); ;#define AssertSz(f,sz) ((f) ? 0 : AssertSzProc(SzFrame(sz),(CHAR *)szAssertFile,__LINE__)) cmp [vdbs.fCkFldDelDbs],fFalse je Ltemp007 mov bx,[pxsr] mov si,[bx.pcaDelXsr] push [si.docCa] push [si.HI_cpFirstCa] push [si.LO_cpFirstCa] push [si.HI_cpLimCa] push [si.LO_cpLimCa] cCall FCkFldForDelete,<> or ax,ax je Ltemp008 mov bx,[pxsr] mov si,[bx.pcaInsXsr] push [si.docCa] push [si.HI_cpFirstCa] push [si.LO_cpFirstCa] push [si.HI_cpLimCa] push [si.LO_cpLimCa] cCall FCkFldForDelete,<> or ax,ax je Ltemp008 Ltemp007: jmp XRC11 Ltemp008: push si push di push ds push es push cs pop ds push ss pop es mov si,offset szAttempt2 lea di,[rgchAttempt] mov cx,cbSzAttempt2 rep movsb jmp short XRC09 szAttempt2: db 'Attempt to delete unmatched field char! ',0 cbSzAttempt2 equ $ - szAttempt2 errnz <cbSzAttempt2 - 41> XRC09: mov si,offset szEditn2 lea di,[rgchEditn] mov cx,cbSzEditn2 rep movsb jmp short XRC10 szEditn2: db 'editn.asm',0 cbSzEditn2 equ $ - szEditn2 errnz <cbSzEditn2 - 10> XRC10: pop es pop ds pop di pop si lea ax,[rgchAttempt] lea bx,[rgchEditn] mov cx,1027 cCall AssertSzProc,<ax,bx,cx> XRC11: ; } ;#endif /* DEBUG */ pop si pop dx pop cx pop bx pop ax XRC12: endif ;DEBUG ; if (dcpIns == 0) ; /* This is just too easy . . . */ ; { mov di,[pxsr] mov si,[di.pcaInsXsr] ;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax. ;Only ax and dx are altered. call LN_DcpCa mov [OFF_dcpIns],ax mov [SEG_dcpIns],dx or ax,dx jne XRC13 ; pxsr->fn = fnNil; ; pxsr->fc = fc0; ; pxsr->dfc = fc0; errnz <fcXsr - dfcXsr - 4> errnz <fnXsr - fcXsr - 4> push ds pop es errnz <fnNil - 0> xor ax,ax push di ;save pxsr errnz <([dfcXsr]) - 0> errnz <(([fnXsr]) - ([dfcXsr])) AND 1> mov cx,(([fnXsr]) - ([dfcXsr]) + 2) SHR 1 rep stosw pop di ;restore pxsr ; XReplace(fPlan, pxbc, pxsr); push [fPlan] push [pxbc] push di ifdef DEBUG cCall S_XReplace,<> else ;!DEBUG push cs call near ptr N_XReplace endif ;!DEBUG ; return; ; } jmp XRC40 XRC13: ; hplcpcdDest = (*hdodDest)->hplcpcd; ;Assembler note: We initialize hplcpcdDest when ;it is most convenient, not here. ; hplcpcdSrc = (*hdodSrc)->hplcpcd; ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa mov cx,[bx.hplcpcdDod] mov [hplcpcdSrc],cx ; if (dcpDel != cp0) ; { ;/* delete structures for text being deleted */ ; XDeleteStruct(fPlan, pxbc, pxsr); ;Assumes bx = pxbc, cx = fPlan, si = pca, di = pxsr ;ax, bx, cx, dx are altered. mov bx,[pxbc] mov cx,[fPlan] call LN_XDeleteStruct ; if (!fPlan && !vfNoInval) ; InvalParaSect(pcaDel, pcaIns, fFalse); mov ax,[vfNoInval] or ax,[fPlan] jne XRC14 cCall InvalParaSect,<si, [di.pcaInsXsr], ax> XRC14: ;/* Get the first and last pieces for insertion */ ; if (fPlan) ; { ; ipcdInsFirst = pxsr->ipcdInsFirst = ; IInPlc(hplcpcdSrc, pcaIns->cpFirst); ; pxsr->ipcdInsLast = IInPlc(hplcpcdSrc, pcaIns->cpLim - 1); ; pxsr->fNotEmptyPcaDel = (dcpDel != 0); ; } ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa mov cx,[bx.hplcpcdDod] mov [hplcpcdDest],cx ;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax. ;Only ax and dx are altered. call LN_DcpCa mov [OFF_dcpDel],ax mov [SEG_dcpDel],dx cmp [fPlan],fFalse je XRC15 or ax,dx mov [di.fNotEmptyPcaDelXsr],ax mov bx,[di.pcaInsXsr] mov cx,[hplcpcdSrc] push cx ;for IInPlc(hplcpcdSrc, pcaIns->cpFirst); push [bx.HI_cpFirstCa] ;for IInPlc(hplcpcdSrc, pcaIns->cpFirst); push [bx.LO_cpFirstCa] ;for IInPlc(hplcpcdSrc, pcaIns->cpFirst); mov ax,-1 cwd add ax,[bx.LO_cpLimCa] adc dx,[bx.HI_cpLimCa] cCall IInPlc,<cx,dx,ax> mov [di.ipcdInsLastXsr],ax cCall IInPlc,<> mov [di.ipcdInsFirstXsr],ax ; else ; ipcdInsFirst = pxsr->ipcdInsFirst; XRC15: mov ax,[di.ipcdInsFirstXsr] mov [ipcdInsFirst],ax ;/* get the limiting pieces for deletion */ ; if (fPlan) ; { ; ipcdFirst = IpcdSplit(hplcpcdDest, pcaDel->cpFirst); ;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs ;IpcdSplit(hplcpcd, cp). The result is returned in ax. ;ax, bx, cx, dx are altered. push [di.fNotEmptyPcaDelXsr] mov di,[hplcpcdDest] mov dx,[si.HI_cpFirstCa] mov ax,[si.LO_cpFirstCa] call LN_IpcdSplit mov [ipcdFirst],ax pop cx ;restore pxsr->fNotEmptyPcaDel ; ipcdLim = (pxsr->fNotEmptyPcaDel) ? ; IpcdSplit(hplcpcdDest, pcaDel->cpLim) : ipcdFirst; ; ;/* check for failure of IpcdSplit */ ; if (ipcdFirst == iNil || ipcdLim == iNil) ; { ; PostTn(pxbc, tntAbort, NULL, 0); ; return; ; } cmp [fPlan],fFalse je XRC19 jcxz XRC16 ;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs ;IpcdSplit(hplcpcd, cp). The result is returned in ax. ;ax, bx, cx, dx are altered. mov dx,[si.HI_cpLimCa] mov ax,[si.LO_cpLimCa] call LN_IpcdSplit XRC16: mov [ipcdLim],ax errnz <iNil - (-1)> inc ax je XRC17 mov ax,[ipcdFirst] errnz <iNil - (-1)> inc ax jne XRC18 XRC17: ;LN_PostTn takes pxbc in bx, tnt in ax, c in cx, h in dx and ;performs PostTn(pxbc, tnt, h, c). ;ax, bx, cx, dx are altered. mov ax,tntAbort mov bx,[pxbc] errnz <NULL> xor cx,cx xor dx,dx call LN_PostTn jmp XRC40 XRC18: ; /* number of pieces to be added */ ; pxsr->cpcd = cpcd = ipcdFirst - ipcdLim + pxsr->ipcdInsLast - ipcdInsFirst +1; ; } mov dx,di ;save hplcpcdDest for call to PostTn mov di,[pxsr] mov ax,[ipcdFirst] sub ax,[ipcdLim] add ax,[di.ipcdInsLastXsr] sub ax,[ipcdInsFirst] inc ax mov [di.cpcdXsr],ax ;Assembler note: This PostTn call has been moved from below ;LN_PostTn takes pxbc in bx, tnt in ax, c in cx, h in dx and ;performs PostTn(pxbc, tnt, h, c). ;ax, bx, cx, dx are altered. ; PostTn(pxbc, tntHplc, hplcpcdDest, cpcd); xchg ax,cx mov ax,tntHplc mov bx,[pxbc] call LN_PostTn jmp XRC27 ; else ; { ; ipcdFirst = IpcdSplit(hplcpcdDest, pcaDel->cpFirst); ; cpcd = pxsr->cpcd; XRC19: ;Assembler note: ipcdFirst has already been computed mov di,[pxsr] ; Assert(cpcd == ipcdFirst + pxsr->ipcdInsLast - ipcdInsFirst + 1 ; - ((pxsr->fNotEmptyPcaDel) ? ; IpcdSplit(hplcpcdDest, pcaDel->cpLim) : ipcdFirst)); ; } ifdef DEBUG push ax push bx push cx push dx mov ax,[ipcdFirst] ;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs ;IpcdSplit(hplcpcd, cp). The result is returned in ax. ;ax, bx, cx, dx are altered. cmp [di.fNotEmptyPcaDelXsr],fFalse je XRC20 push di ;save pxsr mov di,[hplcpcdDest] mov dx,[si.HI_cpLimCa] mov ax,[si.LO_cpLimCa] call LN_IpcdSplit pop di ;restore pxsr XRC20: neg ax add ax,[ipcdFirst] add ax,[di.ipcdInsLastXsr] sub ax,[ipcdInsFirst] inc ax cmp ax,[di.cpcdXsr] je XRC21 mov ax,midEditn2 mov bx,1030 cCall AssertProcForNative,<ax,bx> XRC21: pop dx pop cx pop bx pop ax endif ;DEBUG ; if (fPlan) ; PostTn(pxbc, tntHplc, hplcpcdDest, cpcd); ; ; else ; { ;Assembler note: The fPlan test, and the call to PostTn have been ;done above ; if (!vfNoInval) ; /* may call CachePara or FetchCp, must call BEFORE changing piece tbl */ ; InvalText (pcaDel, fTrue /* fEdit */); mov ax,[vfNoInval] or ax,ax jne XRC215 errnz <fTrue - fFalse - 1> inc ax cCall InvalText,<si,ax> XRC215: ;/* set so vhprc chain is checked when we run out of memory */ ; vmerr.fReclaimHprcs = fTrue; or [vmerr.fReclaimHprcsMerr],maskFReclaimHprcsMerr ;/* adjust pctb size; get pointer to the first new piece, ppcdDest, and to the ;first piece we are inserting. */ ; AssertDo(FOpenPlc(hplcpcdDest, ipcdFirst, cpcd)); push [hplcpcdDest] push [ipcdFirst] push [di.cpcdXsr] ifdef DEBUG cCall S_FOpenPlc,<> else ;not DEBUG cCall N_FOpenPlc,<> endif ;DEBUG ifdef DEBUG ;Perform the AssertDo with a call so as not to mess up short jumps. call XRC41 endif ;DEBUG ; FreezeHp(); ifdef DEBUG call LN_FreezeHpEdit endif ;DEBUG ;/* ensure rgcp in hplcpcdSrc is adjusted before we copy cps. */ ; if (((struct PLC *)*hplcpcdSrc)->icpAdjust < ipcdInsFirst + 1) ; AdjustHplcCpsToLim(hplcpcdSrc, ipcdInsFirst + 1); mov si,[hplcpcdSrc] mov bx,[si] mov ax,[ipcdInsFirst] push ax ;save ipcdInsFirst inc ax cmp [bx.icpAdjustPlc],ax jge XRC22 push si push ax push cs call near ptr AdjustHplcCpsToLim XRC22: pop ax ;restore ipcdInsFirst ;/* fill first new piece and split it appropriately */ ; GetPlc(hplcpcdSrc, ipcdInsFirst, &pcd); push si ;argument for CpPlc push ax ;argument for CpPlc lea bx,[pcd] cCall GetPlc,<si, ax, bx> ; pcd.fc += (pcaIns->cpFirst - CpPlc(hplcpcdSrc, ipcdInsFirst)); cCall CpPlc,<> mov si,[di.pcaInsXsr] sub ax,[si.LO_cpFirstCa] sbb dx,[si.HI_cpFirstCa] sub [pcd.LO_fcPcd],ax sbb [pcd.HI_fcPcd],dx ; pcd.fCopied = fTrue; /* para heights invalid */ or [pcd.fCopiedPcd],maskFCopiedPcd ; PutPlc(hplcpcdDest, ipcdFirst, &pcd); ; PutCpPlc(hplcpcdDest, ipcdFirst, pcaDel->cpFirst); ; ipcdLim = ipcdFirst + 1; mov si,[di.pcaDelXsr] mov cx,[hplcpcdDest] mov ax,[ipcdFirst] push cx ;argument for PutCpPlc push ax ;argument for PutCpPlc push [si.HI_cpFirstCa] ;argument for PutCpPlc push [si.LO_cpFirstCa] ;argument for PutCpPlc lea bx,[pcd] push cx push ax push bx inc ax mov [ipcdLim],ax cCall PutPlc,<> cCall PutCpPlc,<> ; if ((cpcd = pxsr->ipcdInsLast - ipcdInsFirst) != 0) ; { mov cx,[di.ipcdInsLastXsr] sub cx,[ipcdInsFirst] jcxz XRC23 ;/* fill in rest of inserted pieces */ ; ipcdLim += cpcd; add [ipcdLim],cx ; CopyMultPlc(cpcd, hplcpcdSrc, ipcdInsFirst + 1, ; hplcpcdDest, ipcdFirst + 1, ; pcaDel->cpFirst - pcaIns->cpFirst, 0, 0); push cx push [hplcpcdSrc] mov cx,[ipcdInsFirst] inc cx push cx push [hplcpcdDest] mov cx,[ipcdFirst] inc cx push cx mov ax,[si.LO_cpFirstCa] mov dx,[si.HI_cpFirstCa] mov bx,[di.pcaInsXsr] sub ax,[bx.LO_cpFirstCa] sbb dx,[bx.HI_cpFirstCa] push dx push ax xor cx,cx push cx push cx cCall CopyMultPlc,<> ; } XRC23: ;/* adjust rest of pieces in destination doc */ ; AdjustHplc(hplcpcdDest, pcaDel->cpLim, /*dcpAdj*/dcpIns - dcpDel, ; ipcdLim); push [hplcpcdDest] push [si.HI_cpLimCa] push [si.LO_cpLimCa] mov ax,[OFF_dcpIns] mov dx,[SEG_dcpIns] sub ax,[OFF_dcpDel] sbb dx,[SEG_dcpDel] push dx push ax push [ipcdLim] push cs call near ptr AdjustHplc ;/* and inform anyone else who cares */ ; (*hdodDest)->fFormatted |= (pcaIns->doc == docScrap) ? ; vsab.fFormatted : (*hdodSrc)->fFormatted; ; PdodMother(docDel)->fMayHavePic |= (docIns == docScrap) ? ; vsab.fMayHavePic : PdodMother(docIns)->fMayHavePic; mov si,[di.pcaInsXsr] errnz <(fMayHavePicSab) - (fFormattedSab) - 1> mov ax,wptr ([vsab.fFormattedSab]) and ax,maskFFormattedSab + (maskFMayHavePicSab SHL 8) add al,0FFh sbb al,al add ah,0FFh sbb ah,ah cmp [si.docCa],docScrap je XRC24 ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa mov al,[bx.fFormattedDod] push ax ;save flags cCall N_PdodMother,<[si.docCa]> xchg ax,bx pop ax ;restore flags mov ah,[bx.fMayHavePicDod] XRC24: and ax,maskFFormattedDod + (maskFMayHavePicDod SHL 8) mov si,[di.pcaDelXsr] ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa or [bx.fFormattedDod],al push ax ;save flags cCall N_PdodMother,<[si.docCa]> xchg ax,bx pop ax ;restore flags or [bx.fMayHavePicDod],ah ; if (!vfNoInval) ; { ; InvalCp1(pcaDel); ; Win( InvalText (pcaDel, fTrue /* fEdit */) ); ; } ; else ; /* inval the caches even if vfNoInval on */ ; InvalCaFierce(); ;LN_DoInval assumes pca passed in si and performs ;if (!vfNoInval) { InvalCp1(pca); } ;else InvalCaFierce(); ;ax, bx, cx, dx are altered. call LN_DoInval ; /* invalidate FetchCpPccpVisible */ ;#define InvalVisiCache() (vdocFetchVisi = docNil) ;#define InvalCellCache() (vcaCell.doc = docNil) ; InvalVisiCache(); ; InvalCellCache(); ;FUTURE: It seems like we should not have to invalidate ; vdocFetchVisi and vcaCell here because both InvalCaFierce ; and InvalCp1 do it for us, but InvalText calls InvalDde ; which indirectly causes vcaCell to get set up again if ; there is a table. errnz <docNil> xor ax,ax mov [vdocFetchVisi],ax mov [vcaCell.docCa],ax ; MeltHp(); ifdef DEBUG call LN_MeltHpEdit endif ;DEBUG ; AdjustCp(pcaDel, dcpIns); ;/* NOTE after this point pcaDel->cpLim may be untrustworthy because it may ; have been adjusted as a side effect of AdjustCp (eg. selCur.ca) */ push si push [SEG_dcpIns] push [OFF_dcpIns] ifdef DEBUG cCall S_AdjustCp,<> else ;!DEBUG push cs call near ptr N_AdjustCp endif ;!DEBUG ; } XRC27: ;/* copy enclosed structures and subdocs */ ;/* copy any enclosed fields */ ; if (FFieldsInPca(pcaIns)) ; XCopyFields(fPlan, pxbc, pcaIns, pcaDel); ;LN_FFieldsInPca assumes pca passed in si and performs ;FFieldsInPca(pca). ax, bx, cx, dx are altered. ;The sign bit set reflects a true result mov si,[di.pcaInsXsr] call LN_FFieldsInPca jns XRC28 cCall XCopyFields,<[fPlan], [pxbc], si, [di.pcaDelXsr]> XRC28: ;/* page table: if there is a table to be updated, call routine. Even if ;the source table is empty, the destination will have to be invalidated. */ ; if ((*hdodDest)->hplcpgd) ; { ; XAddToHplcEdit(fPlan, pxbc, &pxsr->xsaPgdCopy, pcaIns, pcaDel, ; edcPgd); ; InvalLlc(); ;#define InvalLlc() ; } ;#define edcPgd (offset(DOD, hplcpgd) / sizeof(int)) ;XRC43 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, ; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al); ;ax, bx, cx and dx are altered. mov si,[di.pcaDelXsr] mov dx,([xsaPgdDelXsr]) mov al,([hplcpgdDod]) SHR 1 call XRC43 ; if (!(*hdodSrc)->fShort && !(*hdodDest)->fShort) ; { ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa push wptr ([bx.fShortDod]) mov si,[di.pcaInsXsr] ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa pop ax or al,[bx.fShortDod] je Ltemp011 jmp XRC40 Ltemp011: ;/* copy any bookmarks in the source document which are fully enclosed ; in the insertion range to the destination document */ ; if ((*hdodSrc)->hsttbBkmk != hNil) ; XCopyBkmks(fPlan, pxbc, &pxsr->xsbCopy, pcaIns, pcaDel); cmp [bx.hsttbBkmkDod],hNil je XRC29 lea dx,[di.xsbCopyXsr] cCall XCopyBkmks,<[fPlan], [pxbc], dx, si, [di.pcaDelXsr]> XRC29: ;/* copy any anotations along with their reference marks */ ; if ((*hdodSrc)->docAtn != docNil) ; XAddReferencedText(fPlan, pxbc, &pxsr->xsfAtnCopy, pcaIns, pcaDel, ; edcDrpAtn); ;#define edcDrpAtn (offset(DOD,drpAtn)/sizeof(int)) ;XRC47 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XAddReferencedText(fPlan, pxbc, ((char *)pxsr) + dx, ; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al); ;ax, bx, cx and dx are altered. mov dx,([xsfAtnCopyXsr]) mov al,([drpAtnDod]) SHR 1 call XRC47 ;/* copy any footnotes along with their reference marks */ ; if ((*hdodSrc)->docFtn != docNil) ; XAddReferencedText(fPlan, pxbc, &pxsr->xsfFtnCopy, pcaIns, pcaDel, ; edcDrpFtn); ;#define edcDrpFtn (offset(DOD,drpFtn)/sizeof(int)) ;XRC47 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XAddReferencedText(fPlan, pxbc, ((char *)pxsr) + dx, ; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al); ;ax, bx, cx and dx are altered. mov dx,([xsfFtnCopyXsr]) mov al,([drpFtnDod]) SHR 1 call XRC47 ;/* if there are any sections call AddHplcEdit to copy entries from ;one hplcsed to the other */ ; if ((*hdodSrc)->hplcsed) ; { xor ax,ax ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa errnz <docNil - 0> cmp [bx.hplcSedDod],ax je XRC31 ; caSect.doc = docNil; mov [caSect.docCa],ax ; if ((*hdodSrc)->docHdr != docNil || (*hdodDest)->docHdr != docNil) ; { mov ax,[bx.docHdrDod] push si ;save pcaIns mov si,[di.pcaDelXsr] ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa pop si ;restore pcaIns errnz <docNil - 0> or ax,[bx.docHdrDod] je XRC30 ; XAddHdrText(fPlan, pxbc, pcaIns, pcaDel); cCall XAddHdrText,<[fPlan], [pxbc], si, [di.pcaDelXsr]> ; caSect.doc = docNil; /* XAdd.. called CacheSect */ errnz <docNil - 0> xor ax,ax mov [caSect.docCa],ax ; } XRC30: ; XAddToHplcEdit(fPlan, pxbc, &pxsr->xsaSedCopy, pcaIns, pcaDel, ; edcSed); ; InvalLlc(); ;#define InvalLlc() ;XRC43 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, ; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al); ;ax, bx, cx and dx are altered. mov dx,([xsaSedCopyXsr]) mov al,([hplcsedDod]) SHR 1 call XRC43 ; } XRC31: ; if ((*hdodSrc)->fSea && (*hdodSrc)->hplcsea) ; XAddToHplcEdit(fPlan, pxbc, &pxsr->xsaSeaCopy, pcaIns, pcaDel, ; edcSea); ;#define edcSea (offset(DOD, hplcsea) / sizeof(int)) ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa test [bx.fSeaDod],maskFSeaDod je XRC32 ;XRC43 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, ; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al); ;ax, bx, cx and dx are altered. mov dx,([xsaSeaCopyXsr]) mov al,([hplcseaDod]) SHR 1 call XRC43 XRC32: ;/* outline table: as for page table */ ; if (fPlan) ; pxsr->fNotDelPassCpMac = (pcaDel->cpFirst < (CpMacDoc(docDel)+dcpIns-dcpDel)); mov si,[di.pcaDelXsr] cmp [fPlan],fFalse je XRC34 cCall CpMacDoc,<[si.docCa]> mov bx,[OFF_dcpDel] mov cx,[SEG_dcpDel] sub bx,[OFF_dcpIns] sbb cx,[SEG_dcpIns] sub bx,ax sbb cx,dx errnz <fFalse> xor ax,ax add bx,[si.LO_cpFirstCa] adc cx,[si.HI_cpFirstCa] jge XRC33 errnz <fTrue - fFalse - 1> inc ax XRC33: mov [di.fNotDelPassCpMacXsr],ax XRC34: ; if (((*hdodDest)->hplcpad || (*hdodSrc)->hplcpad) && ; pxsr->fNotDelPassCpMac && (*hdodDest)->dk != dkGlsy) ; { ; XAddToHplcEdit(fPlan, pxbc, &pxsr->xsaPadCopy, pcaIns, pcaDel, ; edcPad); ; } ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa cmp [bx.dkDod],dkGlsy je XRC35 cmp [di.fNotDelPassCpMacXsr],fFalse je XRC35 push si ;save pcaDel mov si,[di.pcaInsXsr] ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa pop si ;restore pcaDel ;XRC44 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if ((cx | hplc) != hNil) ; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, ; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al); ;ax, bx, cx and dx are altered. mov cx,[bx.hplcpadDod] mov dx,([xsaPadCopyXsr]) mov al,([hplcpadDod]) SHR 1 call XRC44 XRC35: ;/* height table */ ; if ((*hdodDest)->hplcphe) ; XAddToHplcEdit(fPlan, pxbc, &pxsr->xsaPheCopy, pcaIns, pcaDel, ; edcPhe); ;XRC43 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, ; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al); ;ax, bx, cx and dx are altered. mov dx,([xsaPheCopyXsr]) mov al,([hplcpheDod]) SHR 1 call XRC43 ;/* we will replace docDest's hidden section character with the hidden section ; mark from docSrc only if we are not already copying the section mark, ; we are copying the tail of docIns to the tail of docDel, the text ; copied from docIns does not end with a section mark, and if docSrc is ; guarded (ie. == docScrap or docUndo) the hidden section character had to ; have been copied from the original document. */ ; if (fPlan) ; { cmp [fPlan],fFalse jne Ltemp010 jmp XRC39 Ltemp010: ; CP cpTailIns = CpTail(docIns); ; struct DOD *pdodIns; ;/* Note that no cps have been adjusted yet */ ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa mov cx,si mov si,[di.pcaInsXsr] mov di,bx ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa ; pxsr->fReplHidnSect = ; pcaDel->cpFirst + dcpDel <= CpMacDoc(docDel) && ;*hdodSrc in bx, pcaDel in cx, pcaIns in si, *hdodDest in di ;***Begin in line CpMacDoc ;return ((*mpdochdod[doc]->cpMac - 2*ccpEop); mov ax,-2*ccpEop cwd add ax,[di.LO_cpMacDod] adc dx,[di.HI_cpMacDod] ;***End in line CpMacDoc xchg cx,si sub ax,[si.LO_cpFirstCa] sbb dx,[si.HI_cpFirstCa] xchg cx,si sub ax,[OFF_dcpDel] sbb dx,[SEG_dcpDel] jl XRC38 ; pcaIns->cpFirst < CpMacDoc(docIns) && ;*hdodSrc in bx, pcaDel in cx, pcaIns in si, *hdodDest in di ;***Begin in line CpMacDoc ;return ((*mpdochdod[doc]->cpMac - 2*ccpEop); mov ax,2*ccpEop cwd sub ax,[bx.LO_cpMacDod] sbb dx,[bx.HI_cpMacDod] ;***End in line CpMacDoc add ax,[si.LO_cpFirstCa] adc dx,[si.HI_cpFirstCa] jge XRC38 ; pcaIns->cpLim >= cpTailIns && ; !FSectLimAtCp(docIns, cpTailIns) && ;Assembler note: do these two lines involving cpTailIns later ;to avoid messing up registers ; pcaDel->cpLim >= CpTail(docDel) - ; ((!PdodDoc(docDel)->fGuarded) ? ccpEop : cp0) && ;*hdodSrc in bx, pcaDel in cx, pcaIns in si, *hdodDest in di ;***Begin in line CpTail ;return (PdodDoc(doc)->fGuarded ? CpMacDocEdit(doc) : CpMacDoc(doc)); ;Assembler note: The following line is CpMacDocEdit. ;return(CpMacDoc(doc) - ccpEop); ;Assembler note: This means that the above expression involving ;CpTail reduces to (CpMacDoc(doc) - ccpEop). mov ax,3*ccpEop cwd sub ax,[di.LO_cpMacDod] sbb dx,[di.HI_cpMacDod] ;***End in line CpTail xchg cx,si add ax,[si.LO_cpLimCa] adc dx,[si.HI_cpLimCa] xchg cx,si jl XRC38 ; (!(pdodIns=PdodDoc(docIns))->fGuarded || test [bx.fGuardedDod],maskFGuardedDod je XRC36 ; (pdodIns->fSedMacEopCopied && (dcpDel > cp0 || dcpIns == CpMacDocEdit(docIns)))); test [bx.fSedMacEopCopiedDod],maskFSedMacEopCopiedDod je XRC38 xor ax,ax cmp ax,[OFF_dcpDel] sbb ax,[SEG_dcpDel] jl XRC36 ;***Begin in line CpMacDocEdit ;return(CpMacDoc(doc) - ccpEop); mov ax,-3*ccpEop cwd add ax,[bx.LO_cpMacDod] adc dx,[bx.HI_cpMacDod] ;***End in line CpMacDocEdit sub ax,[OFF_dcpIns] sbb dx,[SEG_dcpIns] or ax,dx jne XRC38 XRC36: ; CP cpTailIns = CpTail(docIns); ; pcaIns->cpLim >= cpTailIns && ; !FSectLimAtCp(docIns, cpTailIns) && ;Assembler note: These three lines are done above in the C version ;*hdodSrc in bx, pcaDel in cx, pcaIns in si, *hdodDest in di ;***Begin in line CpTail ;return (PdodDoc(doc)->fGuarded ? CpMacDocEdit(doc) : CpMacDoc(doc)); ;Assembler note: The following line is CpMacDocEdit. ;return(CpMacDoc(doc) - ccpEop); mov al,-3*ccpEop test [bx.fGuardedDod],maskFGuardedDod jne XRC37 mov al,-2*ccpEop XRC37: cbw cwd add ax,[bx.LO_cpMacDod] adc dx,[bx.HI_cpMacDod] ;***End in line CpTail cmp [si.LO_cpLimCa],ax mov cx,[si.HI_cpLimCa] sbb cx,dx jl XRC38 cCall FSectLimAtCp,<[si.docCa], dx, ax> or ax,ax jne XRC38 ; } db 0B8h ;turns next "xor ax,ax" into "mov ax,immediate" XRC38: xor ax,ax mov di,[pxsr] mov [di.fReplHidnSectXsr],ax XRC39: ; if (pxsr->fReplHidnSect) ; { cmp [di.fReplHidnSectXsr],fFalse je XRC40 ; struct XSR *pxsrT = PxsAlloc(pxbc); ;***Begin in line PxsAlloc mov bx,[pxbc] ; Assert(pxbc->ixsMac < pxbc->ixsMax); ifdef DEBUG ;Do this assert with a call so as not to mess up short jumps call XRC50 endif ;DEBUG ; return pxbc->rgxs + (cbXSR * pxbc->ixsMac++); mov ax,cbXsrMin mul [bx.ixsMacXbc] inc [bx.ixsMacXbc] mov si,[bx.rgxsXbc] add si,ax ;***End in line PxsAlloc ; struct CA caDel, caIns; ; CheckPxs(fPlan, pxsrT, nxsHidnSect, 0); ;#ifdef DEBUG ;#define CheckPxs(fPlan,pxs,nxsT,wT) (fPlan ? (pxs->nxs=nxsT, pxs->w=wT) : \ ; Assert(pxs->nxs==nxsT && pxs->w==wT)) ;#else ;#define CheckPxs(fPlan,pxs,nxsT,wT) ;#endif /* DEBUG */ ifdef DEBUG ;Do this assert with a call so as not to mess up short jumps call XRC52 endif ;DEBUG ; pxsrT->pcaDel = PcaSetDcp(&caDel, docDel, CpMac1Doc(docDel)-ccpEop, ; ccpEop); mov bx,[di.pcaDelXsr] lea ax,[caDel] mov [si.pcaDelXsr],ax call LN_PcaSetDcp ; pxsrT->pcaIns = PcaSetDcp(&caIns, docIns, CpMac1Doc(docIns)-ccpEop, ; ccpEop); mov bx,[di.pcaInsXsr] lea ax,[caIns] mov [si.pcaInsXsr],ax call LN_PcaSetDcp ; XReplaceCps(fPlan, pxbc, pxsrT); push [fPlan] push [pxbc] push si ifdef DEBUG cCall S_XReplaceCps,<> else ;!DEBUG push cs call near ptr N_XReplaceCps endif ;!DEBUG ; if (!fPlan && PdodDoc(docDel)->fGuarded) ; PdodDoc(docDel)->fSedMacEopCopied = fTrue; cmp [fPlan],fFalse jne XRC40 mov si,[di.pcaDelXsr] ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa test [bx.fGuardedDod],maskFGuardedDod je XRC40 or [bx.fSedMacEopCopiedDod],maskFSedMacEopCopiedDod ; } ; } XRC40: ;} cEnd ; AssertDo(FOpenPlc(hplcpcd, ipcdFirst, cpcd)); ifdef DEBUG XRC41: or ax,ax jne XRC42 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1032 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax XRC42: ret endif ;DEBUG ;XRC43 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, ; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al); ;ax, bx, cx and dx are altered. XRC43: xor cx,cx ;XRC44 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if ((cx | hplc) != hNil) ; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, ; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al); ;ax, bx, cx and dx are altered. XRC44: ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa ifdef DEBUG or al,al jns XRC45 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1033 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax XRC45: endif ;/* DEBUG */ cbw add bx,ax add bx,ax or cx,[bx] jcxz XRC46 push [fPlan] push [pxbc] add dx,di push dx push [di.pcaInsXsr] push [di.pcaDelXsr] push ax cCall XAddToHplcEdit,<> XRC46: ret ;XRC47 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XAddReferencedText(fPlan, pxbc, ((char *)pxsr) + dx, ; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al); ;ax, bx, cx and dx are altered. XRC47: ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa ifdef DEBUG or al,al jns XRC48 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1034 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax XRC48: endif ;/* DEBUG */ ; XAddReferencedText(fPlan, pxbc, ((char *)pxsr) + dx, ; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al); cbw add bx,ax add bx,ax mov cx,[bx] jcxz XRC49 push [fPlan] push [pxbc] add dx,di push dx push [di.pcaInsXsr] push [di.pcaDelXsr] push ax cCall XAddReferencedText,<> XRC49: ret ifdef DEBUG XRC50: push ax push bx push cx push dx mov ax,[bx.ixsMacXbc] cmp ax,[bx.ixsMaxXbc] jl XRC51 mov ax,midEditn2 mov bx,1035 cCall AssertProcForNative,<ax,bx> XRC51: pop dx pop cx pop bx pop ax ret endif ;DEBUG ifdef DEBUG XRC52: push ax push bx push cx push dx cmp [fPlan],fFalse je XRC53 mov [si.nxsXsr],nxsHidnSect mov [si.wXsr],0 jmp short XRC55 XRC53: cmp [si.nxsXsr],nxsHidnSect jne XRC54 cmp [si.wXsr],0 je XRC55 XRC54: mov ax,midEditn2 mov bx,1036 cCall AssertProcForNative,<ax,bx> XRC55: pop dx pop cx pop bx pop ax ret endif ;DEBUG LN_PcaSetDcp: mov cx,[bx.docCa] xchg ax,bx mov [bx.docCa],cx push bx cCall CpMac1Doc,<cx> pop bx mov [bx.LO_cpLimCa],ax mov [bx.HI_cpLimCa],dx sub ax,ccpEop sbb dx,0 mov [bx.LO_cpFirstCa],ax mov [bx.HI_cpFirstCa],dx ret ;------------------------------------------------------------------------- ; XDelFndSedPgdPad(fPlan, pxbc, pxsr) ;------------------------------------------------------------------------- ;/* X D E L F N D S E D P G D P A D */ ;/* Delete all footnote/annotation text corresponding to refs in [cpFirst:cpLim) ;Also delete SED's for section marks and invalidate PGD's in the page table. ;*/ ;EXPORT XDelFndSedPgdPad(fPlan, pxbc, pxsr) ;BOOL fPlan; ;struct XBC *pxbc; ;struct XSR *pxsr; ;{ ; struct PLC **hplc; ; struct DOD **hdod; ; struct CA caT; ifdef DEBUG ; %%Function:N_XDelFndSedPgdPad %%Owner:BRADV cProc N_XDelFndSedPgdPad,<PUBLIC,FAR>,<si,di> else ;!DEBUG ; %%Function:LN_XDelFndSedPgdPad %%Owner:BRADV cProc LN_XDelFndSedPgdPad,<PUBLIC,NEAR>,<si,di> endif ;!DEBUG ParmW fPlan ParmW pxbc ParmW pxsr LocalV caT,cbCaMin cBegin ; caT = *pxsr->pcaDel; push ds pop es mov di,[pxsr] push di ;save pxsr mov si,[di.pcaDelXsr] lea di,[caT] push di errnz <cbCaMin AND 1> mov cx,cbCaMin SHR 1 rep movsw pop si pop di ;restore pxsr ; hdod = mpdochdod[caT.doc]; ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa ;/* FUTURE: why does this have to be done here? Can it be done below with the ;rest of the !fShort processing? */ ; if (!(*hdod)->fShort) cmp [bx.fShortDod],fFalse jne XDFSPP02 ; if ((hplc = (*hdod)->hplcsed) != 0) ; { mov cx,[bx.hplcsedDod] jcxz XDFSPP02 mov dx,[fPlan] push dx ;argument for XDelInHplcEdit push [pxbc] ;argument for XDelInHplcEdit errnz <NULL> xor ax,ax push ax ;argument for XDelInHplcEdit push [di.pcaDelXsr] ;argument for XDelInHplcEdit push cx ;argument for XDelInHplcEdit errnz <edcNone - 0> push ax ;argument for XDelInHplcEdit ; if ((*hdod)->docHdr != docNil) ; XDeleteHdrText(fPlan, pxbc, &pxsr->xsp, pxsr->pcaDel); errnz <docNil - 0> cmp [bx.docHdrDod],ax je XDFSPP01 lea bx,[di.xspXsr] cCall XDeleteHdrText,<dx, [pxbc], bx, [di.pcaDelXsr]> XDFSPP01: ; XDelInHplcEdit(fPlan, pxbc, NULL, pxsr->pcaDel, hplc, ; edcNone); cCall XDelInHplcEdit,<> ; InvalLlc(); ;#define InvalLlc() ; } XDFSPP02: ;/* protect PLCs from lookups with cp > cpMac */ ; Assert(caT.cpLim <= CpMac2Doc(caT.doc)); ifdef DEBUG call XDFSPP12 endif ;/* DEBUG */ ; caT.cpLim = CpMin(caT.cpLim, CpMac2Doc(caT.doc)); cCall CpMac2Doc,<[caT.docCa]> cmp ax,[caT.LO_cpLimCa] mov cx,dx sbb cx,[caT.HI_cpLimCa] jge XDFSPP03 mov [caT.LO_cpLimCa],ax mov [caT.HI_cpLimCa],dx XDFSPP03: ; if (caT.cpLim <= caT.cpFirst) ; return; mov ax,[caT.LO_cpFirstCa] mov dx,[caT.HI_cpFirstCa] sub ax,[caT.LO_cpLimCa] sbb dx,[caT.HI_cpLimCa] jge XDFSPP05 ;/* these PLCs are in short and long docs */ ; if ((hplc = (*hdod)->hplcpgd) != 0) ; { ; XDelInHplcEdit(fPlan, pxbc, &pxsr->xsaPgdDel, &caT, hplc, edcPgd); ; InvalLlc(); ; } ;#define InvalLlc() ;#define edcPgd (offset(DOD, hplcpgd) / sizeof(int)) ;XDFSPP06 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XDelInHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, si, hplc, al); ;ax, bx, cx and dx are altered. mov dx,([xsaPgdDelXsr]) mov al,([hplcpgdDod]) SHR 1 call XDFSPP06 ; if ((hplc = (*hdod)->hplcphe) != 0) ; XDelInHplcEdit(fPlan, pxbc, &pxsr->xsaPheDel, &caT, hplc, edcPhe); ;#define edcPhe (offset(DOD, hplcphe) / sizeof(int)) ;XDFSPP06 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XDelInHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, si, hplc, al); ;ax, bx, cx and dx are altered. mov dx,([xsaPheDelXsr]) mov al,([hplcpheDod]) SHR 1 call XDFSPP06 ; if ((*hdod)->fShort) ; return; ;/* PLCs for long docs only */ ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa cmp [bx.fShortDod],fFalse jne XDFSPP05 ; if ((*hdod)->docFtn != docNil) ; XDelReferencedText(fPlan, pxbc, &pxsr->xsfFtnDel, &caT, edcDrpFtn); ;#define edcDrpFtn (offset(DOD,drpFtn)/sizeof(int)) ;XDFSPP09 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + cx); ;if (hplc != hNil) ; XDelReferencedText(fPlan, pxbc, ((char *)pxsr) + dx, si, al); ;ax, bx, cx and dx are altered. mov dx,([xsfFtnDelXsr]) mov al,([drpFtnDod]) SHR 1 mov cx,([docFtnDod]) call XDFSPP09 ; if ((*hdod)->docAtn != docNil) ; XDelReferencedText(fPlan, pxbc, &pxsr->xsfAtnDel, &caT, edcDrpAtn); ;#define edcDrpAtn (offset(DOD,drpAtn)/sizeof(int)) ;XDFSPP09 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + cx); ;if (hplc != hNil) ; XDelReferencedText(fPlan, pxbc, ((char *)pxsr) + dx, si, al); ;ax, bx, cx and dx are altered. mov dx,([xsfAtnDelXsr]) mov al,([drpAtnDod]) SHR 1 mov cx,([docAtnDod]) call XDFSPP09 ; if ((hplc = (*hdod)->hplcpad) != 0 && caT.cpFirst < CpMacDoc(caT.doc)) ; XDelInHplcEdit(fPlan, pxbc, &pxsr->xsaPadDel, &caT, hplc, edcPad); ;#define edcPad (offset(DOD, hplcpad) / sizeof(int)) cCall CpMacDoc,<[caT.docCa]> cmp [caT.LO_cpFirstCa],ax mov cx,[caT.HI_cpFirstCa] sbb cx,dx jge XDFSPP04 ;XDFSPP06 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XDelInHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, si, hplc, al); ;ax, bx, cx and dx are altered. mov dx,([xsaPadDelXsr]) mov al,([hplcpadDod]) SHR 1 call XDFSPP06 XDFSPP04: ; if ((*hdod)->fSea && (hplc = (*hdod)->hplcsea) != 0) ; XDelInHplcEdit(fPlan, pxbc, &pxsr->xsaSeaDel, &caT, hplc, edcSea); ;#define edcSea (offset(DOD, hplcsea) / sizeof(int)) ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa test [bx.fSeaDod],maskfSeaDod je XDFSPP05 ;XDFSPP06 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XDelInHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, si, hplc, al); ;ax, bx, cx and dx are altered. mov dx,([xsaSeaDelXsr]) mov al,([hplcseaDod]) SHR 1 call XDFSPP06 XDFSPP05: ;} cEnd ;XDFSPP06 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al); ;if (hplc != hNil) ; XDelInHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, si, hplc, al); ;ax, bx, cx and dx are altered. XDFSPP06: ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa ifdef DEBUG or al,al jns XDFSPP07 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1037 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax XDFSPP07: endif ;/* DEBUG */ cbw add bx,ax add bx,ax mov cx,[bx] jcxz XDFSPP08 push [fPlan] push [pxbc] add dx,di push dx push si push cx push ax cCall XDelInHplcEdit,<> XDFSPP08: ret ;XDFSPP09 performs ;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + cx); ;if (hplc != hNil) ; XDelReferencedText(fPlan, pxbc, ((char *)pxsr) + dx, si, al); ;ax, bx, cx and dx are altered. XDFSPP09: ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa ifdef DEBUG or al,al jns XDFSPP10 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1038 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax XDFSPP10: endif ;/* DEBUG */ cbw add bx,cx mov cx,[bx] jcxz XDFSPP11 push [fPlan] push [pxbc] add dx,di push dx push si push ax cCall XDelReferencedText,<> XDFSPP11: ret ; Assert(caT.cpLim <= CpMac2Doc(caT.doc)); ifdef DEBUG XDFSPP12: push ax push bx push cx push dx cCall CpMac2Doc,<[caT.docCa]> sub ax,[caT.LO_cpLimCa] sbb dx,[caT.HI_cpLimCa] jge XDFSPP13 mov ax,midEditn2 mov bx,1040 cCall AssertProcForNative,<ax,bx> XDFSPP13: pop dx pop cx pop bx pop ax ret endif ;/* DEBUG */ ; if (DcpCa(pca) != 0) ;/* delete structures for text being deleted */ ; XDeleteStruct(fPlan, pxbc, pxsr); ;/* X D E L E T E S T R U C T */ ;/* Delete structures from the deletion range */ ;/* %%Function:XDeleteStruct %%owner:peterj %%reviewed: 6/28/89 */ ;XDeleteStruct(fPlan, pxbc, pxsr) ;BOOL fPlan; ;struct XBC *pxbc; ;struct XSR *pxsr; ;{ ; struct CA *pca = pxsr->pcaDel; ; ;/* check for deleting para and sect boundaries; delete entries from parallel ;structures */ ; if (!fPlan && !vfNoInval) ; InvalParaSect(pca, pca, fTrue); ; if (FFieldsInPca(pca)) ; XDeleteFields(fPlan, pxbc, &pxsr->xslDelete, pca); ; ; if (!PdodDoc(pca->doc)->fShort) ; if (PdodDoc(pca->doc)->hsttbBkmk != hNil) ; XDeleteBkmks(fPlan, pxbc, pca, fFalse); ; XDelFndSedPgdPad(fPlan, pxbc, pxsr); ;} PUBLIC LN_XDeleteStruct LN_XDeleteStruct: ;Assumes bx = pxbc, cx = fPlan, si = pca, di = pxsr ;ax, bx, cx, dx are altered. ; if (dcpDel != cp0) ; { ;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax. ;Only ax and dx are altered. mov si,[di.pcaDelXsr] call LN_DcpCa or ax,dx je XDS05 ; if (!fPlan && !vfNoInval) ; /* check for deleting para and sect boundaries; delete entries ; from parallel structures */ ; InvalParaSect(pcaDel, pcaDel, fTrue); push cx ;save fPlan or cx,[vfNoInval] jne XDS01 errnz <fTrue - 1> inc cx push bx ;save pxbc cCall InvalParaSect,<si, si, cx> pop bx ;restore pxbc XDS01: pop cx ;restore fPlan ; if (FFieldsInPca(pcaDel)) ; { ;LN_FFieldsInPca assumes pca passed in si and performs ;FFieldsInPca(pca). ax, bx, cx, dx are altered. ;The sign bit set reflects a true result push bx ;save pxbc push cx ;save fPlan call LN_FFieldsInPca pop cx ;restore fPlan pop bx ;restore pxbc jns XDS03 ; if (!fPlan) ; (*hdodDest)->fFldNestedValid = fFalse; or cx,cx jne XDS02 ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. push bx ;save pxbc call LN_PdodDocCa and [bx.fFldNestedValidDod],NOT maskFFldNestedValidDod pop bx ;restore pxbc XDS02: ; XDeleteFields(fPlan, pxbc, &pxsr->xslDelete, pcaDel); lea ax,[di.xslDeleteXsr] push bx ;save pxbc push cx ;save fPlan cCall XDeleteFields,<cx, bx, ax, si> pop cx ;restore fPlan pop bx ;restore pxbc ; } XDS03: ; if (!(*hdodDest)->fShort) ; if ((*hdodDest)->hsttbBkmk != hNil) ; XDeleteBkmks(fPlan, pxbc, pcaDel, fFalse); ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. push bx ;save pxbc call LN_PdodDocCa xor ax,ax errnz <fFalse> cmp [bx.fShortDod],al jne XDS035 ;do this extra conditional jmp to avoid GP faults mov dx,[bx.hsttbBkmkDod] XDS035: pop bx ;restore pxbc jne XDS04 errnz <hNil> or dx,dx je XDS04 errnz <fFalse> push bx ;save pxbc push cx ;save fPlan cCall XDeleteBkmks,<cx, bx, si, ax> pop cx ;restore fPlan pop bx ;restore pxbc XDS04: ; XDelFndSedPgdPad(fPlan, pxbc, pxsr); push cx push bx push di ifdef DEBUG cCall S_XDelFndSedPgdPad,<> else ;!DEBUG call LN_XDelFndSedPgdPad endif ;!DEBUG ; } XDS05: ret ;LN_FlushRulerSprms performs ;if (vrulss.caRulerSprm.doc != docNil) ; FlushRulerSprms(); ;ax, bx, cx, dx are altered. LN_FlushRulerSprms: cmp [vrulss.caRulerSprmRulss.docCa],docNil je FRS01 cCall FlushRulerSprms,<> FRS01: ret ;/* F F I E L D S I N P C A */ ;/* return fTrue if there are any field characters in pca */ ;BOOL FFieldsInPca(pca) ;struct CA *pca; ;{ ; struct PLC **hplcfld = PdodDoc(pca->doc)->hplcfld; ; ; return (hplcfld != hNil && ; IInPlcRef(hplcfld, pca->cpFirst) <= ; IInPlcCheck(hplcfld, CpMax(0,pca->cpLim-1))); ;} ;LN_FFieldsInPca assumes pca passed in si and performs ;FFieldsInPca(pca). ax, bx, cx, dx are altered. ;The sign bit set reflects a true result ; %%Function:LN_FFieldsInPca %%Owner:BRADV PUBLIC LN_FFieldsInPca LN_FFieldsInPca: ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. call LN_PdodDocCa mov cx,[bx.hplcfldDod] or cx,cx je LN_FFIP02 push di ;save caller's di mov ax,[si.LO_cpLimCa] mov dx,[si.HI_cpLimCa] sub ax,1 sbb dx,0 jge LN_FFIP01 xor ax,ax cwd LN_FFIP01: push cx ;argument for IInPlcCheck push dx ;argument for IInPlcCheck push ax ;argument for IInPlcCheck cCall IInPlcRef,<cx, [si.HI_cpFirstCa], [si.LO_cpFirstCa]> xchg ax,di cCall IInPlcCheck,<> sub di,ax dec di pop di ;restore caller's di LN_FFIP02: ret ;LN_PdodDocCa assumes pca passed in si and performs ;PdodDoc(pca->doc). Only bx is altered. ; %%Function:LN_PdodDocCa %%Owner:BRADV PUBLIC LN_PdodDocCa LN_PdodDocCa: mov bx,[si.docCa] ;LN_PdodDocEdit assumes doc passed in bx and performs ;PdodDoc(doc). Only bx is altered. ; %%Function:LN_PdodDocEdit %%Owner:BRADV PUBLIC LN_PdodDocEdit LN_PdodDocEdit: shl bx,1 mov bx,[bx.mpdochdod] ifdef DEBUG cmp bx,hNil jne LN_PDC01 push ax push bx push cx push dx mov ax,midEditn2 mov bx,1039 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax LN_PDC01: endif ;/* DEBUG */ mov bx,[bx] ret ;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax. ;Only ax and dx are altered. LN_DcpCa: ;***Begin in line DcpCa ;return (pca->cpLim - pca->cpFirst); mov ax,[si.LO_cpLimCa] mov dx,[si.HI_cpLimCa] sub ax,[si.LO_cpFirstCa] sbb dx,[si.HI_cpFirstCa] ;***End in line DcpCa ret ifdef DEBUG PUBLIC LN_FreezeHpEdit LN_FreezeHpEdit: ;#define FreezeHp() (cHpFreeze++?0:LockHeap(sbDds)) cmp [cHpFreeze],0 jne LN_FH01 push ax push bx push cx push dx mov ax,sbDds cCall LockHeap,<ax> pop dx pop cx pop bx pop ax LN_FH01: inc [cHpFreeze] ret endif ;DEBUG ifdef DEBUG ; %%Function:LN_MeltHpEdit %%Owner:BRADV PUBLIC LN_MeltHpEdit LN_MeltHpEdit: ;#define MeltHp() (--cHpFreeze?0:UnlockHeap(sbDds)) dec [cHpFreeze] jne LN_MH01 push ax push bx push cx push dx mov ax,sbDds cCall UnlockHeap,<ax> pop dx pop cx pop bx pop ax LN_MH01: ret endif ;DEBUG sEnd edit2 end
#include "Mcu.inc" #include "PollChain.inc" #include "TestDoubles.inc" radix decimal udata global calledPollAfterSunriseSunset calledPollAfterSunriseSunset res 1 PollAfterSunriseSunsetMock code global initialisePollAfterSunriseSunsetMock global POLL_AFTER_SUNRISESUNSET initialisePollAfterSunriseSunsetMock: banksel calledPollAfterSunriseSunset clrf calledPollAfterSunriseSunset return POLL_AFTER_SUNRISESUNSET: mockCalled calledPollAfterSunriseSunset return end
; A070553: Rectangular array read by rows: n-th row gives the 7 numbers k*10^n mod 7 for 0 <= k < 7. ; 0,1,2,3,4,5,6,0,3,6,2,5,1,4,0,2,4,6,1,3,5,0,6,5,4,3,2,1,0,4,1,5,2,6,3,0,5,3,1,6,4,2,0,1,2,3,4,5,6,0,3,6,2,5,1,4,0,2,4,6,1,3,5,0,6,5,4,3,2,1,0,4,1,5,2,6,3,0,5,3,1,6,4,2 mov $1,$0 lpb $1 mod $0,7 mul $0,24 sub $1,1 trn $1,6 lpe mul $0,2 div $0,48
; A188043: Positions of 1 in A188041; complement of A188042. ; 5,10,15,17,22,27,29,34,39,44,46,51,56,58,63,68,73,75,80,85,87,92,97,99,104,109,114,116,121,126,128,133,138,143,145,150,155,157,162,167,169,174,179,184,186,191,196,198,203,208,213,215,220,225,227,232,237,242,244,249,254,256,261,266,268,273,278,283,285,290,295,297,302,307,312,314,319,324,326,331,336,338,343,348,353,355,360,365,367,372,377,382,384,389,394,396,401,406,411,413,418,423,425,430,435,437,442,447,452,454,459,464,466,471,476,481,483,488,493,495,500,505,507,512,517,522,524,529,534,536,541,546,551,553,558,563,565,570,575,577,582,587,592,594,599,604,606,611,616,621,623,628,633,635,640,645,650,652,657,662,664,669,674,676,681,686,691,693,698,703,705,710,715,720,722,727,732,734,739,744,746,751,756,761,763,768,773,775,780,785,790,792,797,802,804,809,814,819,821,826,831,833,838,843,845,850,855,860,862,867,872,874,879,884,889,891,896,901,903,908,913,915,920,925,930,932,937,942,944,949,954,959,961,966,971,973,978,983,985,990,995,1000,1002,1007,1012,1014,1019,1024,1029,1031 mov $6,$0 add $6,1 mov $8,$0 lpb $6,1 mov $0,$8 sub $6,1 sub $0,$6 mov $13,2 mov $15,$0 lpb $13,1 mov $0,$15 sub $13,1 add $0,$13 sub $0,1 mov $9,$0 mov $12,$0 add $0,1 pow $0,2 mov $2,$0 mov $3,1 lpb $2,1 add $3,1 mov $4,$2 trn $4,2 mov $5,1 lpb $4,1 add $3,4 trn $4,$3 add $5,2 lpe sub $2,$2 lpe mov $7,$5 mov $11,$9 mul $11,2 add $7,$11 div $7,2 add $7,3 add $7,$12 mov $10,$13 lpb $10,1 sub $10,1 mov $14,$7 lpe lpe lpb $15,1 sub $14,$7 mov $15,0 lpe mov $7,$14 sub $7,2 mul $7,3 add $7,2 add $1,$7 lpe
SECTION code_fp_math48 PUBLIC lp_pdoub EXTERN cm48_sccz80p_lp_pdoub defc lp_pdoub = cm48_sccz80p_lp_pdoub
/*========================================================================= * * Copyright RTK Consortium * * 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.txt * * 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 "rtkThreeDCircularProjectionGeometry.h" #include "rtkMacro.h" #include <algorithm> #include <math.h> #include <itkCenteredEuler3DTransform.h> #include <itkEuler3DTransform.h> rtk::ThreeDCircularProjectionGeometry::ThreeDCircularProjectionGeometry(): m_RadiusCylindricalDetector(0.) { } double rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees(const double a) { return a-360*floor(a/360); } double rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And2PIRadians(const double a) { return a-2*vnl_math::pi*floor( a / (2*vnl_math::pi) ); } double rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetweenMinusAndPlusPIRadians(const double a) { double d = ConvertAngleBetween0And2PIRadians(a); if(d>vnl_math::pi) d -= 2*vnl_math::pi; return d; } void rtk::ThreeDCircularProjectionGeometry::AddProjection( const double sid, const double sdd, const double gantryAngle, const double projOffsetX, const double projOffsetY, const double outOfPlaneAngle, const double inPlaneAngle, const double sourceOffsetX, const double sourceOffsetY) { const double degreesToRadians = vcl_atan(1.0) / 45.0; AddProjectionInRadians(sid, sdd, degreesToRadians * gantryAngle, projOffsetX, projOffsetY, degreesToRadians * outOfPlaneAngle, degreesToRadians * inPlaneAngle, sourceOffsetX, sourceOffsetY); } void rtk::ThreeDCircularProjectionGeometry::AddProjectionInRadians( const double sid, const double sdd, const double gantryAngle, const double projOffsetX, const double projOffsetY, const double outOfPlaneAngle, const double inPlaneAngle, const double sourceOffsetX, const double sourceOffsetY) { // Check parallel / divergent projections consistency if( m_GantryAngles.size() ) { if( sdd == 0. && m_SourceToDetectorDistances[0] != 0. ) { itkGenericExceptionMacro(<< "Cannot add a parallel projection in a 3D geometry object containing divergent projections"); } if( sdd != 0. && m_SourceToDetectorDistances[0] == 0. ) { itkGenericExceptionMacro(<< "Cannot add a divergent projection in a 3D geometry object containing parallel projections"); } } // Detector orientation parameters m_GantryAngles.push_back( ConvertAngleBetween0And2PIRadians(gantryAngle) ); m_OutOfPlaneAngles.push_back( ConvertAngleBetween0And2PIRadians(outOfPlaneAngle) ); m_InPlaneAngles.push_back( ConvertAngleBetween0And2PIRadians(inPlaneAngle) ); // Source position parameters m_SourceToIsocenterDistances.push_back( sid ); m_SourceOffsetsX.push_back( sourceOffsetX ); m_SourceOffsetsY.push_back( sourceOffsetY ); // Detector position parameters m_SourceToDetectorDistances.push_back( sdd ); m_ProjectionOffsetsX.push_back( projOffsetX ); m_ProjectionOffsetsY.push_back( projOffsetY ); // Compute sub-matrices AddProjectionTranslationMatrix( ComputeTranslationHomogeneousMatrix(sourceOffsetX-projOffsetX, sourceOffsetY-projOffsetY) ); AddMagnificationMatrix( ComputeProjectionMagnificationMatrix(-sdd, -sid) ); AddRotationMatrix( ComputeRotationHomogeneousMatrix(-outOfPlaneAngle, -gantryAngle, -inPlaneAngle) ); AddSourceTranslationMatrix( ComputeTranslationHomogeneousMatrix(-sourceOffsetX, -sourceOffsetY, 0.) ); Superclass::MatrixType matrix; matrix = this->GetProjectionTranslationMatrices().back().GetVnlMatrix() * this->GetMagnificationMatrices().back().GetVnlMatrix() * this->GetSourceTranslationMatrices().back().GetVnlMatrix()* this->GetRotationMatrices().back().GetVnlMatrix(); this->AddMatrix(matrix); // Calculate source angle VectorType z; z.Fill(0.); z[2] = 1.; HomogeneousVectorType sph = GetSourcePosition( m_GantryAngles.size()-1 ); sph[1] = 0.; // Project position to central plane VectorType sp( &(sph[0]) ); sp.Normalize(); double a = acos(sp*z); if(sp[0] > 0.) a = 2. * vnl_math::pi - a; m_SourceAngles.push_back( ConvertAngleBetween0And2PIRadians(a) ); // Default collimation (uncollimated) m_CollimationUInf.push_back(std::numeric_limits< double >::max()); m_CollimationUSup.push_back(std::numeric_limits< double >::max()); m_CollimationVInf.push_back(std::numeric_limits< double >::max()); m_CollimationVSup.push_back(std::numeric_limits< double >::max()); this->Modified(); } bool rtk::ThreeDCircularProjectionGeometry:: AddProjection(const PointType &sourcePosition, const PointType &detectorPosition, const VectorType &detectorRowVector, const VectorType &detectorColumnVector) { typedef itk::Euler3DTransform<double> EulerType; // these parameters relate absolutely to the WCS (IEC-based): const VectorType &r = detectorRowVector; // row dir const VectorType &c = detectorColumnVector; // column dir VectorType n = itk::CrossProduct(r, c); // normal const PointType &S = sourcePosition; // source pos const PointType &R = detectorPosition; // detector pos if (fabs(r * c) > 1e-6) // non-orthogonal row/column vectors return false; // Euler angles (ZXY convention) from detector orientation in IEC-based WCS: double ga; // gantry angle double oa; // out-of-plane angle double ia; // in-plane angle // extract Euler angles from the orthogonal matrix which is established // by the detector orientation; however, we would like RTK to internally // store the inverse of this rotation matrix, therefore the corresponding // angles are computed here: Matrix3x3Type rm; // reference matrix // NOTE: This transposed matrix should internally // set by rtk::ThreeDProjectionGeometry (inverse) // of external rotation! rm[0][0] = r[0]; rm[0][1] = r[1]; rm[0][2] = r[2]; rm[1][0] = c[0]; rm[1][1] = c[1]; rm[1][2] = c[2]; rm[2][0] = n[0]; rm[2][1] = n[1]; rm[2][2] = n[2]; // extract Euler angles by using the standard ITK implementation: EulerType::Pointer euler = EulerType::New(); euler->SetComputeZYX(false); // ZXY order // workaround: Orthogonality tolerance problem when using // Euler3DTransform->SetMatrix() due to error magnification. // Parent class MatrixOffsetTransformBase does not perform an // orthogonality check on the matrix! euler->itk::MatrixOffsetTransformBase<double>::SetMatrix(rm); oa = euler->GetAngleX(); // delivers radians ga = euler->GetAngleY(); ia = euler->GetAngleZ(); // verify that extracted ZXY angles result in the *desired* matrix: // (at some angle constellations we may run into numerical troubles, therefore, // verify angles and try to fix instabilities) if (!VerifyAngles(oa, ga, ia, rm)) { if (!FixAngles(oa, ga, ia, rm)) { itkWarningMacro(<< "Failed to AddProjection"); return false; } } // since rtk::ThreeDCircularProjectionGeometry::AddProjection() mirrors the // angles (!) internally, let's invert the computed ones in order to // get at the end what we would like (see above); convert rad->deg: ga *= -1.; oa *= -1.; ia *= -1.; // SID: distance from source to isocenter along detector normal double SID = n[0] * S[0] + n[1] * S[1] + n[2] * S[2]; // SDD: distance from source to detector along detector normal double SDD = n[0] * (S[0] - R[0]) + n[1] * (S[1] - R[1]) + n[2] * (S[2] - R[2]); // source offset: compute source's "in-plane" x/y shift off isocenter VectorType Sv; Sv[0] = S[0]; Sv[1] = S[1]; Sv[2] = S[2]; double oSx = Sv * r; double oSy = Sv * c; // detector offset: compute detector's in-plane x/y shift off isocenter VectorType Rv; Rv[0] = R[0]; Rv[1] = R[1]; Rv[2] = R[2]; double oRx = Rv * r; double oRy = Rv * c; // configure native RTK geometry this->AddProjectionInRadians(SID, SDD, ga, oRx, oRy, oa, ia, oSx, oSy); return true; } bool rtk::ThreeDCircularProjectionGeometry:: AddProjection(const HomogeneousProjectionMatrixType &pMat) { Matrix3x3Type A; for (unsigned int i = 0; i < 3; i++) for (unsigned int j = 0; j < 3; j++) { A(i,j) = pMat(i,j); } VectorType p; p[0] = pMat(0,3); p[1] = pMat(1,3); p[2] = pMat(2,3); // Compute determinant of A double d = pMat(0,0)*pMat(1,1)*pMat(2,2) + pMat(0,1)*pMat(1,2)*pMat(2,0) + pMat(0,2)*pMat(1,0)*pMat(2,1) - pMat(0,0)*pMat(1,2)*pMat(2,1) - pMat(0,1)*pMat(1,0)*pMat(2,2) - pMat(0,2)*pMat(1,1)*pMat(2,0); d = -1.*d/std::abs(d); // Extract intrinsic parameters u0, v0 and f (f is chosen to be positive at that point) // The extraction of u0 and v0 is independant of KR-decomp. double u0 = (pMat(0, 0)*pMat(2, 0)) + (pMat(0, 1)*pMat(2, 1)) + (pMat(0, 2)*pMat(2, 2)); double v0 = (pMat(1, 0)*pMat(2, 0)) + (pMat(1, 1)*pMat(2, 1)) + (pMat(1, 2)*pMat(2, 2)); double aU = sqrt(pMat(0, 0)*pMat(0, 0) + pMat(0, 1)*pMat(0, 1) + pMat(0, 2)*pMat(0, 2) - u0*u0); double aV = sqrt(pMat(1, 0)*pMat(1, 0) + pMat(1, 1)*pMat(1, 1) + pMat(1, 2)*pMat(1, 2) - v0*v0); double sdd = 0.5 * (aU + aV); // Def matrix K so that detK = det P[:,:3] Matrix3x3Type K; K.Fill(0.0f); K(0,0) = sdd; K(1,1) = sdd; K(2,2) = -1.0; K(0,2) = -1.*u0; K(1,2) = -1.*v0; K *= d; // Compute R (since det K = det P[:,:3], detR = 1 is enforced) Matrix3x3Type invK(K.GetInverse()); Matrix3x3Type R = invK*A; //Declare a 3D euler transform in order to properly extract angles typedef itk::Euler3DTransform<double> EulerType; EulerType::Pointer euler = EulerType::New(); euler->SetComputeZYX(false); // ZXY order //Extract angle using parent method without orthogonality check euler->itk::MatrixOffsetTransformBase<double>::SetMatrix(R); double oa = euler->GetAngleX(); double ga = euler->GetAngleY(); double ia = euler->GetAngleZ(); // verify that extracted ZXY angles result in the *desired* matrix: // (at some angle constellations we may run into numerical troubles, therefore, // verify angles and try to fix instabilities) if (!VerifyAngles(oa, ga, ia, R)) { if (!FixAngles(oa, ga, ia, R)) { itkWarningMacro(<< "Failed to AddProjection"); return false; } } // Coordinates of source in oriented coord sys : // (sx,sy,sid) = RS = R(-A^{-1}P[:,3]) = -K^{-1}P[:,3] Matrix3x3Type invA(A.GetInverse()); VectorType v = invK*p; v *= -1.; double sx = v[0]; double sy = v[1]; double sid = v[2]; // Add to geometry this->AddProjectionInRadians(sid, sdd, -1.*ga, sx-u0, sy-v0, -1.*oa, -1.*ia, sx, sy); return true; } void rtk::ThreeDCircularProjectionGeometry::Clear() { Superclass::Clear(); m_GantryAngles.clear(); m_OutOfPlaneAngles.clear(); m_InPlaneAngles.clear(); m_SourceAngles.clear(); m_SourceToIsocenterDistances.clear(); m_SourceOffsetsX.clear(); m_SourceOffsetsY.clear(); m_SourceToDetectorDistances.clear(); m_ProjectionOffsetsX.clear(); m_ProjectionOffsetsY.clear(); m_CollimationUInf.clear(); m_CollimationUSup.clear(); m_CollimationVInf.clear(); m_CollimationVSup.clear(); m_ProjectionTranslationMatrices.clear(); m_MagnificationMatrices.clear(); m_RotationMatrices.clear(); m_SourceTranslationMatrices.clear(); this->Modified(); } const std::vector<double> rtk::ThreeDCircularProjectionGeometry::GetTiltAngles() { const std::vector<double> sangles = this->GetSourceAngles(); const std::vector<double> gangles = this->GetGantryAngles(); std::vector<double> tang; for(unsigned int iProj=0; iProj<gangles.size(); iProj++) { double angle = -1. * gangles[iProj] - sangles[iProj]; tang.push_back( ConvertAngleBetween0And2PIRadians(angle) ); } return tang; } const std::multimap<double,unsigned int> rtk::ThreeDCircularProjectionGeometry::GetSortedAngles(const std::vector<double> &angles) const { unsigned int nProj = angles.size(); std::multimap<double,unsigned int> sangles; for(unsigned int iProj=0; iProj<nProj; iProj++) { double angle = angles[iProj]; sangles.insert(std::pair<double, unsigned int>(angle, iProj) ); } return sangles; } const std::map<double,unsigned int> rtk::ThreeDCircularProjectionGeometry::GetUniqueSortedAngles(const std::vector<double> &angles) const { unsigned int nProj = angles.size(); std::map<double,unsigned int> sangles; for(unsigned int iProj=0; iProj<nProj; iProj++) { double angle = angles[iProj]; sangles.insert(std::pair<double, unsigned int>(angle, iProj) ); } return sangles; } const std::vector<double> rtk::ThreeDCircularProjectionGeometry::GetAngularGapsWithNext(const std::vector<double> &angles) const { std::vector<double> angularGaps; unsigned int nProj = angles.size(); angularGaps.resize(nProj); // Special management of single or empty dataset if(nProj==1) angularGaps[0] = 2*vnl_math::pi; if(nProj<2) return angularGaps; // Otherwise we sort the angles in a multimap std::multimap<double,unsigned int> sangles = this->GetSortedAngles( angles ); // We then go over the sorted angles and deduce the angular weight std::multimap<double,unsigned int>::const_iterator curr = sangles.begin(), next = sangles.begin(); next++; // All but the last projection while(next!=sangles.end() ) { angularGaps[curr->second] = ( next->first - curr->first ); curr++; next++; } //Last projection wraps the angle of the first one angularGaps[curr->second] = sangles.begin()->first + 2*vnl_math::pi - curr->first; return angularGaps; } const std::vector<double> rtk::ThreeDCircularProjectionGeometry::GetAngularGaps(const std::vector<double> &angles) { std::vector<double> angularGaps; unsigned int nProj = angles.size(); angularGaps.resize(nProj); // Special management of single or empty dataset if(nProj==1) angularGaps[0] = 2*vnl_math::pi; if(nProj<2) return angularGaps; // Otherwise we sort the angles in a multimap std::multimap<double,unsigned int> sangles = this->GetSortedAngles(angles); // We then go over the sorted angles and deduce the angular weight std::multimap<double,unsigned int>::const_iterator prev = sangles.begin(), curr = sangles.begin(), next = sangles.begin(); next++; //First projection wraps the angle of the last one angularGaps[curr->second] = 0.5 * ( next->first - sangles.rbegin()->first + 2*vnl_math::pi ); curr++; next++; //Rest of the angles while(next!=sangles.end() ) { angularGaps[curr->second] = 0.5 * ( next->first - prev->first ); prev++; curr++; next++; } //Last projection wraps the angle of the first one angularGaps[curr->second] = 0.5 * ( sangles.begin()->first + 2*vnl_math::pi - prev->first ); // FIXME: Trick for the half scan in parallel geometry case if(m_SourceToDetectorDistances[0]==0.) { std::vector<double>::iterator it = std::max_element(angularGaps.begin(), angularGaps.end()); if(*it>itk::Math::pi_over_2) { for(it=angularGaps.begin(); it<angularGaps.end(); it++) { if(*it>itk::Math::pi_over_2) *it -= itk::Math::pi_over_2; *it *= 2.; } } } return angularGaps; } rtk::ThreeDCircularProjectionGeometry::ThreeDHomogeneousMatrixType rtk::ThreeDCircularProjectionGeometry:: ComputeRotationHomogeneousMatrix(double angleX, double angleY, double angleZ) { typedef itk::CenteredEuler3DTransform<double> ThreeDTransformType; ThreeDTransformType::Pointer xfm = ThreeDTransformType::New(); xfm->SetIdentity(); xfm->SetRotation( angleX, angleY, angleZ ); ThreeDHomogeneousMatrixType matrix; matrix.SetIdentity(); for(int i=0; i<3; i++) for(int j=0; j<3; j++) matrix[i][j] = xfm->GetMatrix()[i][j]; return matrix; } rtk::ThreeDCircularProjectionGeometry::TwoDHomogeneousMatrixType rtk::ThreeDCircularProjectionGeometry:: ComputeTranslationHomogeneousMatrix(double transX, double transY) { TwoDHomogeneousMatrixType matrix; matrix.SetIdentity(); matrix[0][2] = transX; matrix[1][2] = transY; return matrix; } rtk::ThreeDCircularProjectionGeometry::ThreeDHomogeneousMatrixType rtk::ThreeDCircularProjectionGeometry:: ComputeTranslationHomogeneousMatrix(double transX, double transY, double transZ) { ThreeDHomogeneousMatrixType matrix; matrix.SetIdentity(); matrix[0][3] = transX; matrix[1][3] = transY; matrix[2][3] = transZ; return matrix; } rtk::ThreeDCircularProjectionGeometry::Superclass::MatrixType rtk::ThreeDCircularProjectionGeometry:: ComputeProjectionMagnificationMatrix(double sdd, const double sid) { Superclass::MatrixType matrix; matrix.Fill(0.0); for(unsigned int i=0; i<2; i++) matrix[i][i] = (sdd==0.)?1.:sdd; matrix[2][2] = (sdd==0.)?0.:1.; matrix[2][3] = (sdd==0.)?1.:sid; return matrix; } void rtk::ThreeDCircularProjectionGeometry:: SetCollimationOfLastProjection(const double uinf, const double usup, const double vinf, const double vsup) { m_CollimationUInf.back() = uinf; m_CollimationUSup.back() = usup; m_CollimationVInf.back() = vinf; m_CollimationVSup.back() = vsup; } const rtk::ThreeDCircularProjectionGeometry::HomogeneousVectorType rtk::ThreeDCircularProjectionGeometry:: GetSourcePosition(const unsigned int i) const { HomogeneousVectorType sourcePosition; sourcePosition[0] = this->GetSourceOffsetsX()[i]; sourcePosition[1] = this->GetSourceOffsetsY()[i]; sourcePosition[2] = this->GetSourceToIsocenterDistances()[i]; sourcePosition[3] = 1.; // Rotate sourcePosition.SetVnlVector(GetRotationMatrices()[i].GetInverse() * sourcePosition.GetVnlVector()); return sourcePosition; } const rtk::ThreeDCircularProjectionGeometry::ThreeDHomogeneousMatrixType rtk::ThreeDCircularProjectionGeometry:: GetProjectionCoordinatesToDetectorSystemMatrix(const unsigned int i) const { // Compute projection inverse and distance to source ThreeDHomogeneousMatrixType matrix; matrix.SetIdentity(); matrix[0][3] = this->GetProjectionOffsetsX()[i]; matrix[1][3] = this->GetProjectionOffsetsY()[i]; if(this->GetSourceToDetectorDistances()[i] == 0.) { matrix[2][3] = -1. * this->GetSourceToIsocenterDistances()[i]; } else { matrix[2][3] = this->GetSourceToIsocenterDistances()[i]-this->GetSourceToDetectorDistances()[i]; } matrix[2][2] = 0.; // Force z to axis to detector distance return matrix; } const rtk::ThreeDCircularProjectionGeometry::ThreeDHomogeneousMatrixType rtk::ThreeDCircularProjectionGeometry:: GetProjectionCoordinatesToFixedSystemMatrix(const unsigned int i) const { ThreeDHomogeneousMatrixType matrix; matrix = this->GetRotationMatrices()[i].GetInverse() * GetProjectionCoordinatesToDetectorSystemMatrix(i).GetVnlMatrix(); return matrix; } double rtk::ThreeDCircularProjectionGeometry:: ToUntiltedCoordinateAtIsocenter(const unsigned int noProj, const double tiltedCoord) const { // Aliases / constant const double sid = this->GetSourceToIsocenterDistances()[noProj]; const double sid2 = sid*sid; const double sdd = this->GetSourceToDetectorDistances()[noProj]; const double sx = this->GetSourceOffsetsX()[noProj]; const double px = this->GetProjectionOffsetsX()[noProj]; // sidu is the distance between the source and the virtual untilted detector const double sidu = sqrt(sid2 + sx*sx); // l is the coordinate on the virtual detector parallel to the real detector // and passing at the isocenter const double l = (tiltedCoord + px - sx) * sid / sdd + sx; // a is the angle between the virtual detector and the real detector const double cosa = sx/sidu; // the following relation refers to a note by R. Clackdoyle, title // "Samping a tilted detector" return l * std::abs(sid) / (sidu - l*cosa); } bool rtk::ThreeDCircularProjectionGeometry:: VerifyAngles(const double outOfPlaneAngleRAD, const double gantryAngleRAD, const double inPlaneAngleRAD, const Matrix3x3Type &referenceMatrix) const { // Check if parameters are Nan. Fails if they are. if(outOfPlaneAngleRAD != outOfPlaneAngleRAD || gantryAngleRAD != gantryAngleRAD || inPlaneAngleRAD != inPlaneAngleRAD) return false; typedef itk::Euler3DTransform<double> EulerType; const Matrix3x3Type &rm = referenceMatrix; // shortcut const double EPSILON = 1e-5; // internal tolerance for comparison EulerType::Pointer euler = EulerType::New(); euler->SetComputeZYX(false); // ZXY order euler->SetRotation(outOfPlaneAngleRAD, gantryAngleRAD, inPlaneAngleRAD); Matrix3x3Type m = euler->GetMatrix(); // resultant matrix for (int i = 0; i < 3; i++) // check whether matrices match for (int j = 0; j < 3; j++) if (fabs(rm[i][j] - m[i][j]) > EPSILON) return false; return true; } bool rtk::ThreeDCircularProjectionGeometry:: FixAngles(double &outOfPlaneAngleRAD, double &gantryAngleRAD, double &inPlaneAngleRAD, const Matrix3x3Type &referenceMatrix) const { const Matrix3x3Type &rm = referenceMatrix; // shortcut const double EPSILON = 1e-6; // internal tolerance for comparison if (fabs(fabs(rm[2][1]) - 1.) > EPSILON) { double oa, ga, ia; // @see Slabaugh, GG, "Computing Euler angles from a rotation matrix" // but their convention is XYZ where we use the YXZ convention // first trial: oa = asin(rm[2][1]); double coa = cos(oa); ga = atan2(-rm[2][0] / coa, rm[2][2] / coa); ia = atan2(-rm[0][1] / coa, rm[1][1] / coa); if (VerifyAngles(oa, ga, ia, rm)) { outOfPlaneAngleRAD = oa; gantryAngleRAD = ga; inPlaneAngleRAD = ia; return true; } // second trial: oa = 3.1415926535897932384626433832795 /*PI*/ - asin(rm[2][1]); coa = cos(oa); ga = atan2(-rm[2][0] / coa, rm[2][2] / coa); ia = atan2(-rm[0][1] / coa, rm[1][1] / coa); if (VerifyAngles(oa, ga, ia, rm)) { outOfPlaneAngleRAD = oa; gantryAngleRAD = ga; inPlaneAngleRAD = ia; return true; } } else { // Gimbal lock, one angle in {ia,oa} has to be set randomly double ia; ia = 0.; if (rm[2][1] < 0.) { double oa = -itk::Math::pi_over_2; double ga = atan2(rm[0][2], rm[0][0]); if (VerifyAngles(oa, ga, ia, rm)) { outOfPlaneAngleRAD = oa; gantryAngleRAD = ga; inPlaneAngleRAD = ia; return true; } } else { double oa = itk::Math::pi_over_2; double ga = atan2(rm[0][2], rm[0][0]); if (VerifyAngles(oa, ga, ia, rm)) { outOfPlaneAngleRAD = oa; gantryAngleRAD = ga; inPlaneAngleRAD = ia; return true; } } } return false; } itk::LightObject::Pointer rtk::ThreeDCircularProjectionGeometry::InternalClone() const { LightObject::Pointer loPtr = Superclass::InternalClone(); Self::Pointer clone = dynamic_cast<Self *>(loPtr.GetPointer()); for(unsigned int iProj=0; iProj<this->GetGantryAngles().size(); iProj++) { clone->AddProjectionInRadians(this->GetSourceToIsocenterDistances()[iProj], this->GetSourceToDetectorDistances()[iProj], this->GetGantryAngles()[iProj], this->GetProjectionOffsetsX()[iProj], this->GetProjectionOffsetsY()[iProj], this->GetOutOfPlaneAngles()[iProj], this->GetInPlaneAngles()[iProj], this->GetSourceOffsetsX()[iProj], this->GetSourceOffsetsY()[iProj]); clone->SetCollimationOfLastProjection( this->GetCollimationUInf()[iProj], this->GetCollimationUSup()[iProj], this->GetCollimationVInf()[iProj], this->GetCollimationVSup()[iProj]); } clone->SetRadiusCylindricalDetector( this->GetRadiusCylindricalDetector() ); return loPtr; }
; A315610: Coordination sequence Gal.5.256.5 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; 1,6,12,14,20,26,32,38,40,46,52,58,64,66,72,78,84,90,92,98,104,110,116,118,124,130,136,142,144,150,156,162,168,170,176,182,188,194,196,202,208,214,220,222,228,234,240,246,248,254 mul $0,2 trn $0,1 mov $1,$0 mul $1,2 lpb $1 add $0,4 sub $1,1 trn $1,4 lpe add $0,1
/* ARPACK++ v1.2 2/18/2000 c++ interface to ARPACK code. MODULE RSymGCay.cc. Example program that illustrates how to solve a real symmetric generalized eigenvalue problem in Cayley mode using the ARrcSymGenEig class. 1) Problem description: In this example we try to solve A*x = B*x*lambda in Cayley mode, where A and B are obtained from the finite element discretrization of the 1-dimensional discrete Laplacian d^2u / dx^2 on the interval [0,1] with zero Dirichlet boundary conditions using piecewise linear elements. 2) Data structure used to represent matrices A and B: ARrcSymGenEig is a class that requires the user to provide a way to perform the matrix-vector products w = OPv = inv(A-sigma*B)*v, w = A*v and w = B*v, where sigma is the adopted shift. In this example a class called SymGenProblemB was created with this purpose. SymGenProblemB contains a member function, MultOPv(v,w), that takes a vector v and returns the product OPv in w. It also contains two objects, A and B, that store matrices A and B, respectively. The product Bv is performed by MultMv, a member function of B, and Av is obtained by calling A.MultMv. 3) The reverse communication interface: This example uses the reverse communication interface, which means that the desired eigenvalues cannot be obtained directly from an ARPACK++ class. Here, the overall process of finding eigenvalues by using the Arnoldi method is splitted into two parts. In the first, a sequence of calls to a function called TakeStep is combined with matrix-vector products in order to find an Arnoldi basis. In the second part, an ARPACK++ function like FindEigenvectors (or EigenValVectors) is used to extract eigenvalues and eigenvectors. 4) Included header files: File Contents ----------- ------------------------------------------- sgenprbb.h The SymGenProblemB class definition. arrgsym.h The ARrcSymGenEig class definition. rsymgsol.h The Solution function. blas1c.h Some blas1 functions. 5) ARPACK Authors: Richard Lehoucq Kristyn Maschhoff Danny Sorensen Chao Yang Dept. of Computational & Applied Mathematics Rice University Houston, Texas */ #include "blas1c.h" #include "sgenprbb.h" #include "rsymgsol.h" #include "arrgsym.h" template<class T> void Test(T type) { // Defining two temporary vectors. T tempA[101], tempB[101]; // Creating a pencil. SymGenProblemB<T> P(100, 150.0); // Creating a symmetric eigenvalue problem. 'S' indicates that // we will use the shift and invert mode. P.A.ncols() furnishes // the dimension of the problem. 4 is the number of eigenvalues // sought and 150.0 is the shift. ARrcSymGenEig<T> prob('C', P.A.ncols(), 4L, 150.0); // Finding an Arnoldi basis. while (!prob.ArnoldiBasisFound()) { // Calling ARPACK FORTRAN code. Almost all work needed to // find an Arnoldi basis is performed by TakeStep. prob.TakeStep(); switch (prob.GetIdo()) { case -1: // Performing w <- OP*(A+sigma*B)*v for the first time. // This product must be performed only if GetIdo is equal to // -1. GetVector supplies a pointer to the input vector, v, // and PutVector a pointer to the output vector, w. P.A.MultMv(prob.GetVector(), tempA); P.B.MultMv(prob.GetVector(), tempB); axpy(P.A.ncols(), prob.GetShift(), tempB, 1, tempA, 1); P.MultOPv(tempA, prob.PutVector()); break; case 1: // Performing w <- OP*(A+sigma*B)*v when Bv is available. // This product must be performed whenever GetIdo is equal to // 1. GetProd supplies a pointer to the previously calculated // product Bv, GetVector a pointer to the input vector, v, // and PutVector a pointer to the output vector, w. P.A.MultMv(prob.GetVector(), tempA); axpy(P.A.ncols(), prob.GetShift(), prob.GetProd(), 1, tempA, 1); P.MultOPv(tempA, prob.PutVector()); break; case 2: // Performing w <- B*v. P.B.MultMv(prob.GetVector(), prob.PutVector()); } } // Finding eigenvalues and eigenvectors. prob.FindEigenvectors(); // Printing solution. Solution(prob); } // Test. int main() { // Solving a double precision problem with n = 100. Test((double)0.0); // Solving a single precision problem with n = 100. Test((float)0.0); } // main
;------------------------------------------------------------------- ; Praktikum SMD 2015 ; M.Wahyudin (140310120031) ; ; Name : LATIH24.ASM (PROG2B) ; Desc : Mencacah 7Seg dengan timer sebagai tunda ; Input : - ; Output: 7Seg(P1) ;------------------------------------------------------------------- scount equ 9Ah mov tmod,#80h ;Pilih timer/counter sebagai timer 0 mode 0 setb TR0 ;nyalakan timer (saat ini timer di TL0.. ;..dan TH0 mencacah dari 0 - 8192) mov b,#0 ;nilai cacahan awal mov r7,#scount ;counter-nya software mov a,b ;isi a dengan b lcall display ;mengambil pola tampilan mov P1,a ;menampilkan digit mov a,b ;mengambil nilai cacahan loop: jnb tf0,loop ;ulang terus hingga timer overflow clr tf0 ;clear overflow flag djnz r7,loop ;kurangi counter software, ulang hingga 0 mov r7,#scount ;reset nilai counter software inc b ;cacah b ketika counter software overflow anl b,#0fh ;modulus 0fh mov a,b ;isi a dengan b lcall display ;mengambil pola tampilan mov P1,a ;menampilkan digit mov a,b ;isi a dengan nilai cacahan sekarang sjmp loop display: inc a movc a,@a+pc ret db 3fh ;0 db 06h ;1 db 5bh ;2 db 4fh ;3 db 66h ;4 db 6dh ;5 db 7dh ;6 db 07h ;7 db 7fh ;8 db 67h ;9 db 77h ;a db 7ch ;b db 39h ;c db 5eh ;d db 79h ;e db 71h ;f end
;***************************************************************************** ;* strfuncs.asm - Because aa_syslib doesn't provide all the string utils. ;***************************************************************************** _DATA segment public dword use32 'data' _DATA ends _CODE segment public dword use32 'code' assume cs:_CODE,ds:_DATA public strchr public stricmp public strstr public stristr ;----------------------------------------------------------------------------- ; static void copylower - copy a string, lowercasing it as it's moved. ; Entry: ; ecx - source ; edx - dest ; Exit: ; eax,ecx,edx - trashed ;----------------------------------------------------------------------------- copylower proc near #loop: mov al,[ecx] cmp al,'A' jb short #have_it cmp al,'Z' ja short #have_it or al,020h #have_it: mov [edx],al inc ecx inc edx test al,al jnz short #loop ret copylower endp ;***************************************************************************** ;* char *strchr(char *str, char chr); ;***************************************************************************** strchr proc near mov eax,[esp+4] mov edx,[esp+8] #loop: mov cl,[eax] cmp cl,dl je short #return inc eax test cl,cl jnz short #loop xor eax,eax #return: ret strchr endp ;***************************************************************************** ;* int stricmp(char *str1, char *str2); ;***************************************************************************** stricmp proc near mov ecx,[esp+4] mov edx,[esp+8] push ebx #loop: mov al,[ecx] cmp al,'A' jb short #have_a cmp al,'Z' ja short #have_a or al,020h #have_a: mov bl,[edx] cmp bl,'A' jb short #have_b cmp bl,'Z' ja short #have_b or bl,020h #have_b: test al,al jz short #atend test bl,bl jz short #atend sub al,bl jnz short #notequal inc ecx inc edx jmp short #loop #atend: sub al,bl #notequal: pop ebx movsx eax,al ret stricmp endp ;***************************************************************************** ;* char *strstr(char *str, char *substr); ;***************************************************************************** strstr proc near mov eax,[esp+4] mov edx,[esp+8] _stristr proc near #mainloop: mov cl,[eax] test cl,cl jz short #notfound cmp cl,[edx] je short #checksubstr inc eax jmp short #mainloop #checksubstr: push eax push edx #subloop: inc eax inc edx mov cl,[edx] test cl,cl jz short #subequal cmp cl,[eax] je short #subloop pop edx pop eax inc eax jmp short #mainloop #subequal: pop edx pop eax jmp short #return #notfound: xor eax,eax #return: ret _stristr endp strstr endp ;***************************************************************************** ;* char *stristr(char *str, char *substr); ;***************************************************************************** stristr proc near #str equ [ebp+8] #substr equ [ebp+12] #lstr equ [ebp-1024] #lsubstr equ [ebp-512] push ebp mov ebp,esp sub esp,1024 mov ecx,#str lea edx,#lstr call copylower mov ecx,#substr lea edx,#lsubstr call copylower lea eax,#lstr lea edx,#lsubstr call _stristr leave ret stristr endp _CODE ends end
frame 1, 08 frame 0, 05 setrepeat 7 frame 2, 03 frame 3, 03 dorepeat 3 frame 2, 20 endanim
; see also MapHeaderPointers MapHeaderBanks: db BANK(PalletTown_h) ;PALLET_TOWN db BANK(ViridianCity_h) ; VIRIDIAN_CITY db BANK(PewterCity_h) ; PEWTER_CITY db BANK(CeruleanCity_h) ; CERULEAN_CITY db BANK(LavenderTown_h) ; LAVENDER_TOWN db BANK(VermilionCity_h) ; VERMILION_CITY db BANK(CeladonCity_h) ; CELADON_CITY db BANK(FuchsiaCity_h) ; FUCHSIA_CITY db BANK(CinnabarIsland_h) ; CINNABAR_ISLAND db BANK(IndigoPlateau_h) ; INDIGO_PLATEAU db BANK(SaffronCity_h) ; SAFFRON_CITY db $1 ; unused db BANK(Route1_h) ; ROUTE_1 db BANK(Route2_h) ; ROUTE_2 db BANK(Route3_h) ; ROUTE_3 db BANK(Route4_h) ; ROUTE_4 db BANK(Route5_h) ; ROUTE_5 db BANK(Route6_h) ; ROUTE_6 db BANK(Route7_h) ; ROUTE_7 db BANK(Route8_h) ; ROUTE_8 db BANK(Route9_h) ; ROUTE_9 db BANK(Route10_h) ; ROUTE_10 db BANK(Route11_h) ; ROUTE_11 db BANK(Route12_h) ; ROUTE_12 db BANK(Route13_h) ; ROUTE_13 db BANK(Route14_h) ; ROUTE_14 db BANK(Route15_h) ; ROUTE_15 db BANK(Route16_h) ; ROUTE_16 db BANK(Route17_h) ; ROUTE_17 db BANK(Route18_h) ; ROUTE_18 db BANK(Route19_h) ; ROUTE_19 db BANK(Route20_h) ; ROUTE_20 db BANK(Route21_h) ; ROUTE_21 db BANK(Route22_h) ; ROUTE_22 db BANK(Route23_h) ; ROUTE_23 db BANK(Route24_h) ; ROUTE_24 db BANK(Route25_h) ; ROUTE_25 db BANK(RedsHouse1F_h) db BANK(RedsHouse2F_h) db BANK(BluesHouse_h) db BANK(OaksLab_h) db BANK(ViridianPokecenter_h) db BANK(ViridianMart_h) db BANK(School_h) db BANK(ViridianHouse_h) db BANK(ViridianGym_h) db BANK(DiglettsCaveRoute2_h) db BANK(ViridianForestExit_h) db BANK(Route2House_h) db BANK(Route2Gate_h) db BANK(ViridianForestEntrance_h) db BANK(ViridianForest_h) db BANK(Museum1F_h) db BANK(Museum2F_h) db BANK(PewterGym_h) db BANK(PewterHouse1_h) db BANK(PewterMart_h) db BANK(PewterHouse2_h) db BANK(PewterPokecenter_h) db BANK(MtMoon1_h) db BANK(MtMoon2_h) db BANK(MtMoon3_h) db BANK(CeruleanHouseTrashed_h) db BANK(CeruleanHouse1_h) db BANK(CeruleanPokecenter_h) db BANK(CeruleanGym_h) db BANK(BikeShop_h) db BANK(CeruleanMart_h) db BANK(MtMoonPokecenter_h) db BANK(CeruleanHouseTrashed_h) db BANK(Route5Gate_h) db BANK(UndergroundPathEntranceRoute5_h) db BANK(DayCareM_h) db BANK(Route6Gate_h) db BANK(UndergroundPathEntranceRoute6_h) db BANK(UndergroundPathEntranceRoute6_h) ;FREEZE db BANK(Route7Gate_h) db BANK(UndergroundPathEntranceRoute7_h) db BANK(UndergroundPathEntranceRoute7Copy_h) ;FREEZE db BANK(Route8Gate_h) db BANK(UndergroundPathEntranceRoute8_h) db BANK(RockTunnelPokecenter_h) db BANK(RockTunnel1_h) db BANK(PowerPlant_h) db BANK(Route11Gate_h) db BANK(DiglettsCaveEntranceRoute11_h) db BANK(Route11GateUpstairs_h) db BANK(Route12Gate_h) db BANK(BillsHouse_h) db BANK(VermilionPokecenter_h) db BANK(FanClub_h) db BANK(VermilionMart_h) db BANK(VermilionGym_h) db BANK(VermilionHouse1_h) db BANK(VermilionDock_h) db BANK(SSAnne1_h) db BANK(SSAnne2_h) db BANK(SSAnne3_h) db BANK(SSAnne4_h) db BANK(SSAnne5_h) db BANK(SSAnne6_h) db BANK(SSAnne7_h) db BANK(SSAnne8_h) db BANK(SSAnne9_h) db BANK(SSAnne10_h) db $1D ;unused db $1D ;unused db $1D ;unused db BANK(VictoryRoad1_h) db $1D ;unused db $1D ;unused db $1D ;unused db $1D ;unused db BANK(Lance_h) db $1D ;unused db $1D ;unused db $1D ;unused db $1D ;unused db BANK(HallofFameRoom_h) db BANK(UndergroundPathNS_h) db BANK(Gary_h) db BANK(UndergroundPathWE_h) db BANK(CeladonMart1_h) db BANK(CeladonMart2_h) db BANK(CeladonMart3_h) db BANK(CeladonMart4_h) db BANK(CeladonMartRoof_h) db BANK(CeladonMartElevator_h) db BANK(CeladonMansion1_h) db BANK(CeladonMansion2_h) db BANK(CeladonMansion3_h) db BANK(CeladonMansion4_h) db BANK(CeladonMansion5_h) db BANK(CeladonPokecenter_h) db BANK(CeladonGym_h) db BANK(CeladonGameCorner_h) db BANK(CeladonMart5_h) db BANK(CeladonPrizeRoom_h) db BANK(CeladonDiner_h) db BANK(CeladonHouse_h) db BANK(CeladonHotel_h) db BANK(LavenderPokecenter_h) db BANK(PokemonTower1_h) db BANK(PokemonTower2_h) db BANK(PokemonTower3_h) db BANK(PokemonTower4_h) db BANK(PokemonTower5_h) db BANK(PokemonTower6_h) db BANK(PokemonTower7_h) db BANK(LavenderHouse1_h) db BANK(LavenderMart_h) db BANK(LavenderHouse2_h) db BANK(FuchsiaMart_h) db BANK(FuchsiaHouse1_h) db BANK(FuchsiaPokecenter_h) db BANK(FuchsiaHouse2_h) db BANK(SafariZoneEntrance_h) db BANK(FuchsiaGym_h) db BANK(FuchsiaMeetingRoom_h) db BANK(SeafoamIslands2_h) db BANK(SeafoamIslands3_h) db BANK(SeafoamIslands4_h) db BANK(SeafoamIslands5_h) db BANK(VermilionHouse2_h) db BANK(FuchsiaHouse3_h) db BANK(Mansion1_h) db BANK(CinnabarGym_h) db BANK(Lab1_h) db BANK(Lab2_h) db BANK(Lab3_h) db BANK(Lab4_h) db BANK(CinnabarPokecenter_h) db BANK(CinnabarMart_h) db BANK(CinnabarMart_h) db BANK(IndigoPlateauLobby_h) db BANK(CopycatsHouse1F_h) db BANK(CopycatsHouse2F_h) db BANK(FightingDojo_h) db BANK(SaffronGym_h) db BANK(SaffronHouse1_h) db BANK(SaffronMart_h) db BANK(SilphCo1_h) db BANK(SaffronPokecenter_h) db BANK(SaffronHouse2_h) db BANK(Route15Gate_h) db BANK(Route15GateUpstairs_h) db BANK(Route16Gate_h) db BANK(Route16GateUpstairs_h) db BANK(Route16House_h) db BANK(Route12House_h) db BANK(Route18Gate_h) db BANK(Route18GateUpstairs_h) db BANK(SeafoamIslands1_h) db BANK(Route22Gate_h) db BANK(VictoryRoad2_h) db BANK(Route12GateUpstairs_h) db BANK(VermilionHouse3_h) db BANK(DiglettsCave_h) db BANK(VictoryRoad3_h) db BANK(RocketHideout1_h) db BANK(RocketHideout2_h) db BANK(RocketHideout3_h) db BANK(RocketHideout4_h) db BANK(RocketHideoutElevator_h) db $01 db $01 db $01 db BANK(SilphCo2_h) db BANK(SilphCo3_h) db BANK(SilphCo4_h) db BANK(SilphCo5_h) db BANK(SilphCo6_h) db BANK(SilphCo7_h) db BANK(SilphCo8_h) db BANK(Mansion2_h) db BANK(Mansion3_h) db BANK(Mansion4_h) db BANK(SafariZoneEast_h) db BANK(SafariZoneNorth_h) db BANK(SafariZoneWest_h) db BANK(SafariZoneCenter_h) db BANK(SafariZoneRestHouse1_h) db BANK(SafariZoneSecretHouse_h) db BANK(SafariZoneRestHouse2_h) db BANK(SafariZoneRestHouse3_h) db BANK(SafariZoneRestHouse4_h) db BANK(UnknownDungeon2_h) db BANK(UnknownDungeon3_h) db BANK(UnknownDungeon1_h) db BANK(NameRater_h) db BANK(CeruleanHouse2_h) db $01 db BANK(RockTunnel2_h) db BANK(SilphCo9_h) db BANK(SilphCo10_h) db BANK(SilphCo11_h) db BANK(SilphCoElevator_h) db $11 db $11 db BANK(TradeCenter_h) db BANK(Colosseum_h) db $11 db $11 db $11 db $11 db BANK(Lorelei_h) db BANK(Bruno_h) db BANK(Agatha_h)
; int b_array_back(b_array_t *a) SECTION code_adt_b_array PUBLIC b_array_back b_array_back: INCLUDE "adt/b_array/z80/asm_b_array_back.asm"
; NMI + few procedures ; this block of code MAY not be longer than $ad60-$adde org nmiHandler .proc NMI bit nmist ; what interruption VBL or DLI ? bpl no DLI jmp dull no sta nmist VBL jmp dull dull rti .endp ; .align $100 ; warning: it MAY NOT cross page boundary (example $31f8 ->$3208) ; it is included at ~$ad60 bufDLIJumps dta a(DLI0) dta a(DLI1) dta a(DLI2) dta a(DLI3) dta a(DLI4) bufDLIJumpsLevelStart dta a(DLI0) dta a(DLI1b) dta a(DLI2) dta a(DLI3b) dta a(DLI4b) bufDLIJumpsGameOver dta a(DLI0) dta a(DLI1c) dta a(DLI2) dta a(DLI3b) dta a(DLI4b) .proc enableNMI lda <NMI sta $fffa lda >NMI sta $fffb lda #$c0 sta nmien rts .endp ; Various waitFrame procedures .proc waitJoyXFrames jsr waitFrameNormal dex beq @+ lda porta eor #$ff and #$f cmp #1 beq @+ cmp #2 beq @+ cmp #4 beq @+ lda trig0 beq @+ bne waitJoyXFrames @ rts .endp .proc waitXFrames ; X = how many frames to wait jsr waitFrameNormal dex bne waitXFrames rts .endp .proc waitFrame l1 lda vcount cmp #engineWaitFrameVcount bcc l1 rts .endp .proc waitFrameNormal l1 lda vcount bne l1 l2 lda vcount beq l2 rts .endp ; this block of code MAY not be longer than $ad60-$adde
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r15 push %r8 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0xf6b7, %rcx dec %r13 movl $0x61626364, (%rcx) nop nop nop nop inc %rdi lea addresses_D_ht+0x190ed, %rbx nop and $21991, %r9 mov $0x6162636465666768, %r8 movq %r8, %xmm6 movups %xmm6, (%rbx) nop nop nop nop xor $43467, %rcx lea addresses_D_ht+0x87cf, %r15 nop nop add %r13, %r13 movb $0x61, (%r15) nop nop cmp $15212, %r8 lea addresses_WT_ht+0x1c71d, %rsi lea addresses_A_ht+0x1d0d, %rdi nop sub %rbx, %rbx mov $68, %rcx rep movsw nop dec %r8 lea addresses_D_ht+0x1af8d, %rsi lea addresses_D_ht+0x19186, %rdi nop xor %r9, %r9 mov $61, %rcx rep movsw cmp $10118, %rsi lea addresses_A_ht+0x9e2d, %rbx nop nop nop inc %r15 mov $0x6162636465666768, %r8 movq %r8, %xmm3 movups %xmm3, (%rbx) nop nop nop nop nop sub %r13, %r13 lea addresses_UC_ht+0xe98d, %rsi lea addresses_normal_ht+0x1960d, %rdi nop nop nop nop and $57608, %rbx mov $118, %rcx rep movsl nop nop nop nop nop add $37857, %rdi lea addresses_WC_ht+0x19cd5, %rsi lea addresses_WT_ht+0x1de8d, %rdi nop nop nop nop nop add $50853, %r9 mov $96, %rcx rep movsb sub $63208, %rcx lea addresses_D_ht+0x1290d, %rsi inc %r15 mov (%rsi), %r8w nop inc %r13 lea addresses_D_ht+0x1c30d, %rdi nop nop nop mfence mov $0x6162636465666768, %rbx movq %rbx, %xmm6 vmovups %ymm6, (%rdi) nop nop nop nop sub $6318, %r13 lea addresses_WC_ht+0xc8bd, %rsi lea addresses_WT_ht+0x19b8d, %rdi clflush (%rdi) nop nop nop nop sub $42074, %r8 mov $101, %rcx rep movsl lfence lea addresses_A_ht+0xc0ef, %rbx nop nop nop cmp $23212, %r15 mov (%rbx), %si nop nop nop nop cmp %rdi, %rdi lea addresses_WC_ht+0x5f0d, %rsi lea addresses_A_ht+0x7b0d, %rdi and %r15, %r15 mov $48, %rcx rep movsl nop nop nop nop sub %rsi, %rsi lea addresses_A_ht+0x770d, %rsi nop nop nop nop nop and $53055, %r15 mov $0x6162636465666768, %rbx movq %rbx, (%rsi) nop nop nop nop nop and %r15, %r15 pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r8 pop %r15 pop %r13 ret .global s_faulty_load s_faulty_load: push %r11 push %r14 push %r15 push %rbp push %rbx push %rcx push %rdx // Store lea addresses_UC+0x1e635, %rbp nop nop nop cmp %rdx, %rdx mov $0x5152535455565758, %r11 movq %r11, %xmm1 movups %xmm1, (%rbp) nop nop nop nop and %r14, %r14 // Store lea addresses_PSE+0x1ed2d, %r15 clflush (%r15) nop nop nop nop nop cmp $42575, %rdx mov $0x5152535455565758, %r11 movq %r11, %xmm4 vmovups %ymm4, (%r15) nop nop nop nop nop sub $28571, %rdx // Faulty Load lea addresses_WC+0x230d, %r11 nop sub $58653, %rcx mov (%r11), %r15w lea oracles, %rbp and $0xff, %r15 shlq $12, %r15 mov (%rbp,%r15,1), %r15 pop %rdx pop %rcx pop %rbx pop %rbp pop %r15 pop %r14 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 2, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 4, 'size': 32, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 1, 'size': 4, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 5, 'size': 16, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 9, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 4, 'size': 16, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': True, 'congruent': 9, 'size': 2, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 10, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 1, 'size': 2, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': True}, 'dst': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 10, 'size': 8, 'same': False, 'NT': True}} {'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 */
; StdScripts indexes (see engine/events/std_scripts.asm) ; also used in TileCollisionStdScripts (see data/events/collision_stdscripts.asm) enum_start enum pokecenternurse enum difficultbookshelf enum picturebookshelf enum magazinebookshelf enum teamrocketoath enum incenseburner enum merchandiseshelf enum townmap enum window enum tv enum homepage enum radio1 enum radio2 enum trashcan enum strengthboulder enum smashrock enum pokecentersign enum martsign enum goldenrodrockets enum radiotowerrockets enum elevatorbutton enum daytotext enum bugcontestresultswarp enum bugcontestresults enum initializeevents enum asknumber1m enum asknumber2m enum registerednumberm enum numberacceptedm enum numberdeclinedm enum phonefullm enum rematchm enum giftm enum packfullm enum rematchgiftm enum asknumber1f enum asknumber2f enum registerednumberf enum numberacceptedf enum numberdeclinedf enum phonefullf enum rematchf enum giftf enum packfullf enum rematchgiftf enum gymstatue1 enum gymstatue2 enum receiveitem enum receivetogepiegg enum pcscript enum gamecornercoinvendor enum happinesschecknpc
; int feof(FILE *stream) INCLUDE "config_private.inc" SECTION code_clib SECTION code_stdio ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $02 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC _feof EXTERN _feof_fastcall _feof: pop af pop hl push hl push af jp _feof_fastcall ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC _feof EXTERN _feof_unlocked defc _feof = _feof_unlocked ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A130270: Triangle read by rows, T(n) followed by 1,2,3,...(n-1). ; Submitted by Jon Maiga ; 1,3,1,6,1,2,10,1,2,3,15,1,2,3,4,21,1,2,3,4,5,28,1,2,3,4,5,6,36,1,2,3,4,5,6,7,45,1,2,3,4,5,6,7,8 mov $2,$0 mov $4,$0 lpb $2 add $2,1 add $3,1 sub $2,$3 sub $2,1 add $4,1 lpe lpb $4 mov $4,$2 sub $4,1 lpe mov $0,$4 add $0,1
;-----------------------------------------------------------------------------; ; Author: Stephen Fewer (stephen_fewer[at]harmonysecurity[dot]com) ; Compatible: Windows 7, 2003 ; Architecture: x64 ; Size: 200 bytes ;-----------------------------------------------------------------------------; [BITS 64] ; Windows x64 calling convention: ; http://msdn.microsoft.com/en-us/library/9b372w95.aspx ; Input: The hash of the API to call in r10d and all its parameters (rcx/rdx/r8/r9/any stack params) ; Output: The return value from the API call will be in RAX. ; Clobbers: RAX, RCX, RDX, R8, R9, R10, R11 ; Un-Clobbered: RBX, RSI, RDI, RBP, R12, R13, R14, R15. ; RSP will be off by -40 hence the 'add rsp, 40' after each call to this function ; Note: This function assumes the direction flag has allready been cleared via a CLD instruction. ; Note: This function is unable to call forwarded exports. api_call: push r9 ; Save the 4th parameter push r8 ; Save the 3rd parameter push rdx ; Save the 2nd parameter push rcx ; Save the 1st parameter push rsi ; Save RSI xor rdx, rdx ; Zero rdx mov rdx, [gs:rdx+96] ; Get a pointer to the PEB mov rdx, [rdx+24] ; Get PEB->Ldr mov rdx, [rdx+32] ; Get the first module from the InMemoryOrder module list next_mod: ; mov rsi, [rdx+80] ; Get pointer to modules name (unicode string) movzx rcx, word [rdx+74] ; Set rcx to the length we want to check xor r9, r9 ; Clear r9 which will store the hash of the module name loop_modname: ; xor rax, rax ; Clear rax lodsb ; Read in the next byte of the name cmp al, 'a' ; Some versions of Windows use lower case module names jl not_lowercase ; sub al, 0x20 ; If so normalise to uppercase not_lowercase: ; ror r9d, 13 ; Rotate right our hash value add r9d, eax ; Add the next byte of the name loop loop_modname ; Loop untill we have read enough ; We now have the module hash computed push rdx ; Save the current position in the module list for later push r9 ; Save the current module hash for later ; Proceed to itterate the export address table, mov rdx, [rdx+32] ; Get this modules base address mov eax, dword [rdx+60] ; Get PE header add rax, rdx ; Add the modules base address cmp word [rax+24], 0x020B ; is this module actually a PE64 executable? ; this test case covers when running on wow64 but in a native x64 context via nativex64.asm and ; their may be a PE32 module present in the PEB's module list, (typicaly the main module). ; as we are using the win64 PEB ([gs:96]) we wont see the wow64 modules present in the win32 PEB ([fs:48]) jne get_next_mod1 ; if not, proceed to the next module mov eax, dword [rax+136] ; Get export tables RVA test rax, rax ; Test if no export address table is present jz get_next_mod1 ; If no EAT present, process the next module add rax, rdx ; Add the modules base address push rax ; Save the current modules EAT mov ecx, dword [rax+24] ; Get the number of function names mov r8d, dword [rax+32] ; Get the rva of the function names add r8, rdx ; Add the modules base address ; Computing the module hash + function hash get_next_func: ; jrcxz get_next_mod ; When we reach the start of the EAT (we search backwards), process the next module dec rcx ; Decrement the function name counter mov esi, dword [r8+rcx*4]; Get rva of next module name add rsi, rdx ; Add the modules base address xor r9, r9 ; Clear r9 which will store the hash of the function name ; And compare it to the one we want loop_funcname: ; xor rax, rax ; Clear rax lodsb ; Read in the next byte of the ASCII function name ror r9d, 13 ; Rotate right our hash value add r9d, eax ; Add the next byte of the name cmp al, ah ; Compare AL (the next byte from the name) to AH (null) jne loop_funcname ; If we have not reached the null terminator, continue add r9, [rsp+8] ; Add the current module hash to the function hash cmp r9d, r10d ; Compare the hash to the one we are searchnig for jnz get_next_func ; Go compute the next function hash if we have not found it ; If found, fix up stack, call the function and then value else compute the next one... pop rax ; Restore the current modules EAT mov r8d, dword [rax+36] ; Get the ordinal table rva add r8, rdx ; Add the modules base address mov cx, [r8+2*rcx] ; Get the desired functions ordinal mov r8d, dword [rax+28] ; Get the function addresses table rva add r8, rdx ; Add the modules base address mov eax, dword [r8+4*rcx]; Get the desired functions RVA add rax, rdx ; Add the modules base address to get the functions actual VA ; We now fix up the stack and perform the call to the drsired function... finish: pop r8 ; Clear off the current modules hash pop r8 ; Clear off the current position in the module list pop rsi ; Restore RSI pop rcx ; Restore the 1st parameter pop rdx ; Restore the 2nd parameter pop r8 ; Restore the 3rd parameter pop r9 ; Restore the 4th parameter pop r10 ; pop off the return address sub rsp, 32 ; reserve space for the four register params (4 * sizeof(QWORD) = 32) ; It is the callers responsibility to restore RSP if need be (or alloc more space or align RSP). push r10 ; push back the return address jmp rax ; Jump into the required function ; We now automagically return to the correct caller... get_next_mod: ; pop rax ; Pop off the current (now the previous) modules EAT get_next_mod1: ; pop r9 ; Pop off the current (now the previous) modules hash pop rdx ; Restore our position in the module list mov rdx, [rdx] ; Get the next module jmp next_mod ; Process this module
; ; Z88dk Generic Floating Point Math Library ; ; ; $Id: div1.asm,v 1.4 2016/06/21 21:16:49 dom Exp $ SECTION code_fp PUBLIC div1 EXTERN fdiv .div1 POP BC POP IX POP DE jp fdiv
; A108793: Semiprimes that can be partitioned into a sum of semiprimes in more than one way. ; Submitted by Christian Krause ; 10,14,15,21,22,25,26,33,34,35,38,39,46,49,51,55,57,58,62,65,69,74,77,82,85,86,87,91,93,94,95,106,111,115,118,119,121,122,123,129,133,134,141,142,143,145,146,155,158,159,161,166,169,177,178,183,185,187,194 add $0,3 seq $0,1358 ; Semiprimes (or biprimes): products of two primes.
; ; Small C z88 File functions ; Written by Dominic Morris <djm@jb.man.ac.uk> ; 22 August 1998 ** UNTESTED ** ; ; *** THIS IS A Z88 SPECIFIC ROUTINE!!! *** ; ; 11/3/99 djm - revised INCLUDE "#fileio.def" INCLUDE "#stdio.def" INCLUDE "libdefs.def" XLIB fdfputc ;*fputc(n,fp) ;int n int fp ;on stack ;return address,fp,n ;n=byte to write, fp=filepointer ; ;fputc - put byte to file, should return written byte/EOF if error ; If we come across a \n for stdout/err we call gn_nln .fdfputc ld hl,2 add hl,sp ld e,(hl) ;filehandle inc hl ld d,(hl) inc hl ld c,(hl) ;byte to put ld a,d or e jr nz,fputc1 .fputc_abort ld hl,EOF ret .fputc1 ld hl,stdout and a sbc hl,de jr z,fdputc_cons ld hl,stdin and a sbc hl,de jr z,fputc_abort ld hl,stderr and a sbc hl,de jr nz,fputc_file ;Output to stdin/out here .fdputc_cons ld a,c cp 13 jr nz,fputc_cons1 call_oz(gn_nln) ld hl,13 ret .fputc_cons1 call_oz(os_out) ld l,c ld h,0 ret .fputc_file push de pop ix ld a,c call_oz(os_pb) jr c,fputc_abort ld l,c ld h,0 ret
__________________________________________________________________________________________________ sample 96 ms submission /* // Definition for a Node. class Node { public: int val; Node* prev; Node* next; Node* child; Node() {} Node(int _val, Node* _prev, Node* _next, Node* _child) { val = _val; prev = _prev; next = _next; child = _child; } }; */ class Solution { public: Node* flatten(Node* head) { stack <Node *> st; Node *cur = head, *prev = nullptr; while (!st.empty() || cur) { if (cur == nullptr) { cur = st.top(); st.pop(); prev->next = cur; prev->next->prev = prev; } if (cur->child != nullptr) { if (cur->next) st.push(cur->next); cur->next = cur->child; cur->next->prev = cur; cur->child = nullptr; } prev = cur; cur = cur->next; } return head; } }; static int fastio = []() { #define endl '\n' std::ios::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(0); return 0; }(); __________________________________________________________________________________________________ sample 29808 kb submission /* // Definition for a Node. class Node { public: int val; Node* prev; Node* next; Node* child; Node() {} Node(int _val, Node* _prev, Node* _next, Node* _child) { val = _val; prev = _prev; next = _next; child = _child; } }; */ class Solution { void dfs(Node* ptr, Node* &pre){ if (!ptr) return; if (pre) pre->next=ptr; ptr->prev=pre; pre=ptr; auto* next=ptr->next; if (ptr->child){ auto* nextLevel=ptr->child; ptr->child=NULL; while (nextLevel->prev) nextLevel=nextLevel->prev; dfs(nextLevel, pre); } dfs(next, pre); } public: Node* flatten(Node* head) { Node* pre=NULL; dfs(head, pre); return head; } }; __________________________________________________________________________________________________
; A016064: Smallest side lengths of almost-equilateral Heronian triangles (sides are consecutive positive integers, area is a nonnegative integer). ; 1,3,13,51,193,723,2701,10083,37633,140451,524173,1956243,7300801,27246963,101687053,379501251,1416317953,5285770563,19726764301,73621286643,274758382273,1025412242451,3826890587533,14282150107683,53301709843201,198924689265123,742397047217293,2770663499604051 mov $1,1 lpb $0 sub $0,1 add $2,$1 add $1,$2 add $1,$2 add $2,1 lpe
;--------------------------------------- ; CLI (Command Line Interface) Plugin ; (C) breeze/fishbone crew 2012 ;--------------------------------------- DEVICE ZXSPECTRUM128 org #be00 edit256 ds 128," " ; 128 bytes ascii ds 128,defaultCol ; 128 bytes colors org #bf00 bufer256 ds 128," " ; 128 bytes ascii ds 128,defaultCol ; 128 bytes colors org #6000 termWidth equ 80 termHeight equ 30 defaultCol equ %01011111 cursorType equ "_" iBufferSize equ 255 historySize equ 10 eBufferSize equ iBufferSize bufferAddr equ #0000 pathStrSize equ 255*4 colorDir equ 15 ; white colorFile equ 8 ; silver colorRO equ 1 ; navy colorHidden equ 13 ; teal colorSystem equ 2 ; amiga pink colorArch equ 3 ; dark violet colorError equ 10 ; red colorWarning equ 14 ; yellow colorOk equ 12 ; lime colorInfo equ 13 ; teal cliTxtPages equ 5 ; size Buffer for cli print (5 pages) cliTxtBegin equ #20 ; start page scopeBinAddr equ #c000 ; /bin list address start scopeBinBank equ #03 ; /bin application list palAddr equ #fc00 ; palette file load address palBank equ #03 ; palette file load memory bank gPalAddr equ #fe00 ; graphics palette file load address gPalBank equ #03 ; graphics palette file load memory bank appAddr equ #c000 ; application load address appBank equ #04 ; application load memory bank tmpAddr equ #c000 ; temp buffer load address tmpBank equ #07 ; temp buffer load bank sprAddr equ #c000 ; sprites load address sprBank equ #08 ; sprites load memory bank include "wcKernel.h.asm" include "tsConf.h.asm" include "pluginHead.asm" include "cli.asm" ;include "zx.pal.asm" ;include "cli.pal.asm" ;include "boing.pal.asm" ;include "test1.asm" ;include "test2.asm" ;include "test3.asm" ;include "test4.asm" ;include "helloworld.asm" ;include "boing.asm" include "type.asm" ;include "loadMod.asm" ;include "miceTest.asm" ;DISPLAY "code size:",/A,endCode-startCode ;DISPLAY "waitResponse addr:",/A,waitResponse ;DISPLAY "ttt addr:",/A,ttt ;DISPLAY "executeApp addr:",/A,executeApp ;DISPLAY "checkIsBin addr:",/A,checkIsBin ;DISPLAY "pathString addr:",/A,pathString ;DISPLAY "checkCallLoop addr:",/A,checkCallLoop SAVEBIN "bin/wc/CLI.WMF", startCode, endCode-startCode ;SAVEBIN "bin/system/pal/zx.pal", zxPalStart, zxPalEnd-zxPalStart ;SAVEBIN "bin/system/pal/cli.pal", cliPalStart, cliPalEnd-cliPalStart ;SAVEBIN "bin/demo/boing/boing.pal", boingPalStart, boingPalEnd-boingPalStart ;SAVEBIN "bin/bin/test1", test1Start, test1End-test1Start ;SAVEBIN "bin/bin/test2", test2Start, test2End-test2Start ;SAVEBIN "bin/bin/test3", t3Start, t3End-t3Start ;SAVEBIN "bin/bin/test4", t4Start, t4End-t4Start ;SAVEBIN "bin/bin/hello", appStart, appEnd-appStart ;SAVEBIN "bin/demo/boing/boing", BoingStart, BoingEnd-BoingStart SAVEBIN "bin/bin/type", typeStart, typeEnd-typeStart ;SAVEBIN "bin/bin/loadMod", loadModStart, loadModEnd-loadModStart ;SAVEBIN "bin/bin/miceTest", miceTestStart, miceTestEnd-miceTestStart
TITLE ../openssl/crypto/bn/asm/x86-mont.asm IF @Version LT 800 ECHO MASM version 8.00 or later is strongly recommended. ENDIF .686 .MODEL FLAT OPTION DOTNAME IF @Version LT 800 .text$ SEGMENT PAGE 'CODE' ELSE .text$ SEGMENT ALIGN(64) 'CODE' ENDIF ALIGN 16 _bn_mul_mont PROC PUBLIC $L_bn_mul_mont_begin:: push ebp push ebx push esi push edi xor eax,eax mov edi,DWORD PTR 40[esp] cmp edi,4 jl $L000just_leave lea esi,DWORD PTR 20[esp] lea edx,DWORD PTR 24[esp] mov ebp,esp add edi,2 neg edi lea esp,DWORD PTR [edi*4+esp-32] neg edi mov eax,esp sub eax,edx and eax,2047 sub esp,eax xor edx,esp and edx,2048 xor edx,2048 sub esp,edx and esp,-64 mov eax,DWORD PTR [esi] mov ebx,DWORD PTR 4[esi] mov ecx,DWORD PTR 8[esi] mov edx,DWORD PTR 12[esi] mov esi,DWORD PTR 16[esi] mov esi,DWORD PTR [esi] mov DWORD PTR 4[esp],eax mov DWORD PTR 8[esp],ebx mov DWORD PTR 12[esp],ecx mov DWORD PTR 16[esp],edx mov DWORD PTR 20[esp],esi lea ebx,DWORD PTR [edi-3] mov DWORD PTR 24[esp],ebp mov esi,DWORD PTR 8[esp] lea ebp,DWORD PTR 1[ebx] mov edi,DWORD PTR 12[esp] xor ecx,ecx mov edx,esi and ebp,1 sub edx,edi lea eax,DWORD PTR 4[ebx*4+edi] or ebp,edx mov edi,DWORD PTR [edi] jz $L001bn_sqr_mont mov DWORD PTR 28[esp],eax mov eax,DWORD PTR [esi] xor edx,edx ALIGN 16 $L002mull: mov ebp,edx mul edi add ebp,eax lea ecx,DWORD PTR 1[ecx] adc edx,0 mov eax,DWORD PTR [ecx*4+esi] cmp ecx,ebx mov DWORD PTR 28[ecx*4+esp],ebp jl $L002mull mov ebp,edx mul edi mov edi,DWORD PTR 20[esp] add eax,ebp mov esi,DWORD PTR 16[esp] adc edx,0 imul edi,DWORD PTR 32[esp] mov DWORD PTR 32[ebx*4+esp],eax xor ecx,ecx mov DWORD PTR 36[ebx*4+esp],edx mov DWORD PTR 40[ebx*4+esp],ecx mov eax,DWORD PTR [esi] mul edi add eax,DWORD PTR 32[esp] mov eax,DWORD PTR 4[esi] adc edx,0 inc ecx jmp $L0032ndmadd ALIGN 16 $L0041stmadd: mov ebp,edx mul edi add ebp,DWORD PTR 32[ecx*4+esp] lea ecx,DWORD PTR 1[ecx] adc edx,0 add ebp,eax mov eax,DWORD PTR [ecx*4+esi] adc edx,0 cmp ecx,ebx mov DWORD PTR 28[ecx*4+esp],ebp jl $L0041stmadd mov ebp,edx mul edi add eax,DWORD PTR 32[ebx*4+esp] mov edi,DWORD PTR 20[esp] adc edx,0 mov esi,DWORD PTR 16[esp] add ebp,eax adc edx,0 imul edi,DWORD PTR 32[esp] xor ecx,ecx add edx,DWORD PTR 36[ebx*4+esp] mov DWORD PTR 32[ebx*4+esp],ebp adc ecx,0 mov eax,DWORD PTR [esi] mov DWORD PTR 36[ebx*4+esp],edx mov DWORD PTR 40[ebx*4+esp],ecx mul edi add eax,DWORD PTR 32[esp] mov eax,DWORD PTR 4[esi] adc edx,0 mov ecx,1 ALIGN 16 $L0032ndmadd: mov ebp,edx mul edi add ebp,DWORD PTR 32[ecx*4+esp] lea ecx,DWORD PTR 1[ecx] adc edx,0 add ebp,eax mov eax,DWORD PTR [ecx*4+esi] adc edx,0 cmp ecx,ebx mov DWORD PTR 24[ecx*4+esp],ebp jl $L0032ndmadd mov ebp,edx mul edi add ebp,DWORD PTR 32[ebx*4+esp] adc edx,0 add ebp,eax adc edx,0 mov DWORD PTR 28[ebx*4+esp],ebp xor eax,eax mov ecx,DWORD PTR 12[esp] add edx,DWORD PTR 36[ebx*4+esp] adc eax,DWORD PTR 40[ebx*4+esp] lea ecx,DWORD PTR 4[ecx] mov DWORD PTR 32[ebx*4+esp],edx cmp ecx,DWORD PTR 28[esp] mov DWORD PTR 36[ebx*4+esp],eax je $L005common_tail mov edi,DWORD PTR [ecx] mov esi,DWORD PTR 8[esp] mov DWORD PTR 12[esp],ecx xor ecx,ecx xor edx,edx mov eax,DWORD PTR [esi] jmp $L0041stmadd ALIGN 16 $L001bn_sqr_mont: mov DWORD PTR [esp],ebx mov DWORD PTR 12[esp],ecx mov eax,edi mul edi mov DWORD PTR 32[esp],eax mov ebx,edx shr edx,1 and ebx,1 inc ecx ALIGN 16 $L006sqr: mov eax,DWORD PTR [ecx*4+esi] mov ebp,edx mul edi add eax,ebp lea ecx,DWORD PTR 1[ecx] adc edx,0 lea ebp,DWORD PTR [eax*2+ebx] shr eax,31 cmp ecx,DWORD PTR [esp] mov ebx,eax mov DWORD PTR 28[ecx*4+esp],ebp jl $L006sqr mov eax,DWORD PTR [ecx*4+esi] mov ebp,edx mul edi add eax,ebp mov edi,DWORD PTR 20[esp] adc edx,0 mov esi,DWORD PTR 16[esp] lea ebp,DWORD PTR [eax*2+ebx] imul edi,DWORD PTR 32[esp] shr eax,31 mov DWORD PTR 32[ecx*4+esp],ebp lea ebp,DWORD PTR [edx*2+eax] mov eax,DWORD PTR [esi] shr edx,31 mov DWORD PTR 36[ecx*4+esp],ebp mov DWORD PTR 40[ecx*4+esp],edx mul edi add eax,DWORD PTR 32[esp] mov ebx,ecx adc edx,0 mov eax,DWORD PTR 4[esi] mov ecx,1 ALIGN 16 $L0073rdmadd: mov ebp,edx mul edi add ebp,DWORD PTR 32[ecx*4+esp] adc edx,0 add ebp,eax mov eax,DWORD PTR 4[ecx*4+esi] adc edx,0 mov DWORD PTR 28[ecx*4+esp],ebp mov ebp,edx mul edi add ebp,DWORD PTR 36[ecx*4+esp] lea ecx,DWORD PTR 2[ecx] adc edx,0 add ebp,eax mov eax,DWORD PTR [ecx*4+esi] adc edx,0 cmp ecx,ebx mov DWORD PTR 24[ecx*4+esp],ebp jl $L0073rdmadd mov ebp,edx mul edi add ebp,DWORD PTR 32[ebx*4+esp] adc edx,0 add ebp,eax adc edx,0 mov DWORD PTR 28[ebx*4+esp],ebp mov ecx,DWORD PTR 12[esp] xor eax,eax mov esi,DWORD PTR 8[esp] add edx,DWORD PTR 36[ebx*4+esp] adc eax,DWORD PTR 40[ebx*4+esp] mov DWORD PTR 32[ebx*4+esp],edx cmp ecx,ebx mov DWORD PTR 36[ebx*4+esp],eax je $L005common_tail mov edi,DWORD PTR 4[ecx*4+esi] lea ecx,DWORD PTR 1[ecx] mov eax,edi mov DWORD PTR 12[esp],ecx mul edi add eax,DWORD PTR 32[ecx*4+esp] adc edx,0 mov DWORD PTR 32[ecx*4+esp],eax xor ebp,ebp cmp ecx,ebx lea ecx,DWORD PTR 1[ecx] je $L008sqrlast mov ebx,edx shr edx,1 and ebx,1 ALIGN 16 $L009sqradd: mov eax,DWORD PTR [ecx*4+esi] mov ebp,edx mul edi add eax,ebp lea ebp,DWORD PTR [eax*1+eax] adc edx,0 shr eax,31 add ebp,DWORD PTR 32[ecx*4+esp] lea ecx,DWORD PTR 1[ecx] adc eax,0 add ebp,ebx adc eax,0 cmp ecx,DWORD PTR [esp] mov DWORD PTR 28[ecx*4+esp],ebp mov ebx,eax jle $L009sqradd mov ebp,edx add edx,edx shr ebp,31 add edx,ebx adc ebp,0 $L008sqrlast: mov edi,DWORD PTR 20[esp] mov esi,DWORD PTR 16[esp] imul edi,DWORD PTR 32[esp] add edx,DWORD PTR 32[ecx*4+esp] mov eax,DWORD PTR [esi] adc ebp,0 mov DWORD PTR 32[ecx*4+esp],edx mov DWORD PTR 36[ecx*4+esp],ebp mul edi add eax,DWORD PTR 32[esp] lea ebx,DWORD PTR [ecx-1] adc edx,0 mov ecx,1 mov eax,DWORD PTR 4[esi] jmp $L0073rdmadd ALIGN 16 $L005common_tail: mov ebp,DWORD PTR 16[esp] mov edi,DWORD PTR 4[esp] lea esi,DWORD PTR 32[esp] mov eax,DWORD PTR [esi] mov ecx,ebx xor edx,edx ALIGN 16 $L010sub: sbb eax,DWORD PTR [edx*4+ebp] mov DWORD PTR [edx*4+edi],eax dec ecx mov eax,DWORD PTR 4[edx*4+esi] lea edx,DWORD PTR 1[edx] jge $L010sub sbb eax,0 and esi,eax not eax mov ebp,edi and ebp,eax or esi,ebp ALIGN 16 $L011copy: mov eax,DWORD PTR [ebx*4+esi] mov DWORD PTR [ebx*4+edi],eax mov DWORD PTR 32[ebx*4+esp],ecx dec ebx jge $L011copy mov esp,DWORD PTR 24[esp] mov eax,1 $L000just_leave: pop edi pop esi pop ebx pop ebp ret _bn_mul_mont ENDP DB 77,111,110,116,103,111,109,101,114,121,32,77,117,108,116,105 DB 112,108,105,99,97,116,105,111,110,32,102,111,114,32,120,56 DB 54,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121 DB 32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46 DB 111,114,103,62,0 .text$ ENDS END
.MODEL SMALL .CODE public int10_override_, setup_int10_ int10_override_ proc far cmp ax, 4f01h je check_mode01 cmp ax, 4f02h jne chain_to_prev cmp bx, 4136h jne chain_to_prev push cx push bx and bx, 4000h or bx, [mode] jmp chain_to_prev_and_restore check_mode01: cmp cx, 136h jne chain_to_prev push cx push bx and cx, 4000h or cx, [mode] chain_to_prev_and_restore: pushf call [cs:chain_int10] pop bx pop cx iret chain_to_prev: jmp [cs:chain_int10] int10_override_ endp setup_int10_ proc near mov [mode], ax mov dx, cs mov ax, offset chain_int10 ret setup_int10_ endp chain_int10 dd -1 mode dw 0 end
main: 0xaf mov $1, $7 add $1, $7, $7 iadd $5 ldd $7, 0x12($6) std $3, 0x12($6) int 15 hlt int1: 0xa7 ; -> m[6]&m[7] mov $1, $7 add $1, $7, $7 rti int2: 0xd ; -> m[8]&m[9] mov $1, $7 add $1, $7, $7 rti exp1: 0x13 ; -> m[2]&m[3] mov $1, $7 add $1, $7, $7 hlt exp2: 0x19 ; -> m[4]&m[5] mov $1, $7 add $1, $7, $7 hlt func1: 0x1f mov $1, $7 add $1, $7, $7 ret func2: 0x2f mov $1, $7 add $1, $7, $7 ret ; this is a commend ;mov ;this is a commend
[BITS 64] section .text extern kernel_entrypoint_main kernel_entrypoint_start: mov ax, 0x0010 mov ds, ax mov es, ax mov fs, ax mov gs, ax mov ss, ax mov rbp, 0x0000000000008000 mov rsp, 0x0000000000008000 call kernel_entrypoint_main
; A256535: The largest number of T-tetrominoes that fit within an n X n square. ; 0,0,1,4,5,8,11,16,19,24,29,36,41,48,55,64,71,80,89,100,109,120,131,144,155,168,181,196,209,224,239,256,271,288,305,324,341,360,379,400,419,440,461,484,505,528,551,576,599,624,649,676,701,728,755,784,811 mov $1,$0 mul $0,2 trn $0,5 add $1,5 trn $1,6 lpb $0,1 trn $0,3 add $0,2 add $1,$0 trn $0,7 lpe
; void exit (int code); ; --------------------- ; This function aborts execution of the program by returning ; the given exit code to the operating system. It never returns. ; Only the 8 lower bits of the exit code are considered, thus ; the exit code should be a number between 0 and 255. section .code global _exit _exit push rbp mov rbp, rsp mov rax, 60 and rdi, 0xffff syscall
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 db 0,0,0,0,0,0,136,136,136,136,136,136,136,136,136,136 db 136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136 db 136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136 db 136,136,136,136,136,136,136,136,136,204,204,204,204,204,204,204 db 204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,204 db 204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,204 db 204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,204 db 204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,204 db 204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,136 db 136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136 db 136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136 db 136,136,136,136,136,136,136,136,136,136,136,136,136,136,136,136 db 136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r14 push %rax push %rbp push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0xfbdc, %rbp nop nop sub $51388, %rbx and $0xffffffffffffffc0, %rbp vmovaps (%rbp), %ymm2 vextracti128 $0, %ymm2, %xmm2 vpextrq $1, %xmm2, %rdi nop nop nop dec %rbx lea addresses_WT_ht+0x5fd4, %r14 nop and $39915, %rdx mov (%r14), %r12w nop nop sub $25007, %rbx lea addresses_normal_ht+0x1badc, %rbx nop sub $21704, %rax mov (%rbx), %rdx nop nop nop nop nop dec %rbx lea addresses_A_ht+0x1a1dc, %rbx nop nop nop nop and %r14, %r14 movb $0x61, (%rbx) nop sub $40366, %r12 lea addresses_WC_ht+0x193dc, %r14 nop nop nop nop nop dec %r12 mov $0x6162636465666768, %rdi movq %rdi, %xmm6 movups %xmm6, (%r14) nop nop nop nop add %rbp, %rbp lea addresses_UC_ht+0x10b5c, %rbx clflush (%rbx) nop nop nop nop add %r12, %r12 mov $0x6162636465666768, %rax movq %rax, %xmm6 and $0xffffffffffffffc0, %rbx vmovaps %ymm6, (%rbx) nop xor %rbx, %rbx lea addresses_WT_ht+0x251c, %rsi lea addresses_WC_ht+0x12fdc, %rdi clflush (%rsi) nop nop dec %r14 mov $72, %rcx rep movsw nop nop nop nop inc %rdi lea addresses_WT_ht+0xdbc5, %rcx nop nop nop xor %rax, %rax movl $0x61626364, (%rcx) nop add $63415, %rcx lea addresses_WC_ht+0x765c, %rax nop xor $35898, %rbx movw $0x6162, (%rax) nop nop nop sub %rbx, %rbx lea addresses_WT_ht+0x11dc, %rsi nop nop nop dec %r14 movups (%rsi), %xmm5 vpextrq $0, %xmm5, %rbp nop inc %rbp lea addresses_normal_ht+0x1c9dc, %rsi lea addresses_UC_ht+0x12ffc, %rdi nop sub %rdx, %rdx mov $89, %rcx rep movsq nop sub $26609, %rsi lea addresses_WT_ht+0x33dc, %rsi lea addresses_normal_ht+0x33dc, %rdi nop nop nop nop nop xor $25511, %rbp mov $57, %rcx rep movsb nop nop nop xor %r12, %r12 lea addresses_A_ht+0x15c36, %rdx clflush (%rdx) nop nop cmp %rcx, %rcx mov (%rdx), %di nop nop nop nop xor %rdi, %rdi pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r14 pop %r12 ret .global s_faulty_load s_faulty_load: push %r12 push %r9 push %rbx push %rcx push %rdi push %rdx // Faulty Load lea addresses_US+0x7dc, %r9 add %rcx, %rcx movb (%r9), %r12b lea oracles, %rbx and $0xff, %r12 shlq $12, %r12 mov (%rbx,%r12,1), %r12 pop %rdx pop %rdi pop %rcx pop %rbx pop %r9 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': True}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': True, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': True, 'congruent': 7, 'size': 32, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 3, 'size': 2, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 8, 'size': 8, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 9, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 9, 'size': 16, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': True, 'congruent': 7, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 6, 'size': 2, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 9, 'size': 16, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 3, 'same': True}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 1, 'size': 2, 'same': False, 'NT': 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 */
section .text org 0x00 mov ax, 9ch mov ss, ax ;set stack segment mov sp, 4096d ;set stack pointer mov ax, 7c0h ;?sets the AL? (AH is rewritten); no mov ah, 0eh mov al, 66h int 10h ;BIOS call to print a character jmp $ section .data times 510-($-$$) db 0 ;$ should be current address, $$ - first address dw 0xAA55 ;mark in the end of the boot sector times 1476500 db 0 ;$fill a floppy size
; scrolls screen in gfx mode org 0x100 section .text start: mov ax,13h int 10h mov ah, 0xc ; draw a pixel mov bh, 0 ; page 0 mov al, 13 ; pixel color mov cx, 50 ; x mov dx, 50 ; y int 0x10 mov ah, 0x06 ; scroll up mov ch, 10 ; upper_y mov cl, 10 ; upper_x mov dh, 100 ; lower_y mov dl, 100 ; lower_x mov al, 5 ; lines mov bh, 1 ; attr int 0x10 ; wait for any key and exit xor ah,ah int 16h ret
#include <algorithm> #include <hpx/hpx_main.hpp> #include <hpx/parallel/algorithms/for_loop.hpp> int main(int argc, char** argv){ int NR = 10; int NZ = 8; double Eps[NR*NZ]; int i = 0; if ((NR >= 1) && (NZ >= 1)){ hpx::parallel::v2::for_loop (hpx::parallel::v1::par, 0,NR-1 + 1,[&](int t1) { hpx::parallel::v2::for_loop (hpx::parallel::v1::par, 0,std::min(NZ-1,t1-NR+2147483647) + 1,[&](int t2) { if ((t1 == NR-1) && (t2 >= 1)){ Eps[(NR-1) * NZ + t2] = -100.; } if (t2 == 0){ Eps[t1 * NZ + 0] = -100.; } } ); } ); } return 0; }
; A014800: Squares of even pentagonal pyramidal numbers. ; 0,36,324,1600,15876,38416,82944,302500,527076,876096,2160900,3240000,4734976,9474084,13032100,17640000,30980356,40297104,51840000,83283876,104162436,129231424,194602500,236421376,285474816,409252900,486202500,574848576,792872964,925376400,1075840000,1438381476,1654699684,1897473600,2472675076,2810696256,3186376704,4064062500,4573275876,5134582336,6430436100,7174090000,7988069376,9848180644,10905624900,12056040000,14661819396,16131032064,17720934400,21294397476,23294695876,25449182784,30258602500,32933538576,35802694656,42168622500,45689062500,49451085376,57752741124,62320129600,67184640000,77866670116,83716478244,89928014400,103507619076,110912977296,118754673664,135829102500,145104617476,154902067776,176156484100,187662240000,199787544576,226003258404,240149002500,255025000000,287088069636,304337582224,322442265600,361352467876,382228116516,404099233344,450979402500,476066880576,502306717696,558412452900,588365702500,619646054976,686375796484,721922115600,758989440000,837894913956,879840248004,923521000000,1016318031876,1065552449536,1116758605824,1225338302500,1282841655876,1342576420416,1469016720900,1535864490000,1605228184576,1751805779364,1829175100900,1909371240000,2078573859076,2167749739584,2260091289600,2454630359076,2557012072356,2662927895104,2885751562500,3002859231376,3123900711936,3378207240100,3511688602500,3649536461376,3938787991044,4090425350400,4246896640000,4574833320996,4746550680964,4923605966400,5294260457476,5488130840976,5687881565184,6105593902500,6323846855076,6548562888256,7017995722500,7263025000000,7515142373376,8041296575524,8315668016100,8597796840000,9186027475716,9492487056144,9807419622400,10463452295076,10804934371396,11155653440064,11885601002500,12265236734976,12654924005376,13465303640100,13886429602500,14318474368576,15216225036804,15682392010000,16160400000000,17152900259236,17667882209124,18195684609600,19290770799876,19858574039616,20440236703744,21646221502500,22271094039076,22910926879296,24236618224900,24923059290000,25625625854976,27080346238884,27833116004100,28603243240000,30196849367556,31020978843904,31863767040000,33606669859876,34507470981636,35428303900224,37331489002500,38314564895376,39319120086016,41394168468900,42465423902500,43559683200576,45818792405764,46984444430400,48174704640000,50630710256676,51897299024484,53190182785600,55856580323076,57230980093456,58633446933504,61524414062500,63013844391876,64533201961536,67663621124100,69275658240000,70919573733376,74305055121444,76047643480900,77824155240000,81481060142596,83362524174864,85280053478400,89225517997476,91254574031076,93321937067584,97573896202500,99759664576576,101986084601856,106563296702500,108915314062500,111310433741376,116232505329924,118760737107600,121334631040000,126622042001316,129336895079044,132100082510400,137774211651076,140686547210496,143650004926464,149733155902500,152854302457476,156029477862976,162544905476100,165886672090000,169285496472576,176257433335204,179832123022500,183467025000000,190920708568836,194741131881024,198625051033600,206586751011876,210666239807716,214812640494144,223309686602500,227662108002576,232084993360896,241145803476900,245785574002500,250499500134976,260153608801284,265095708697600,270115799040000,280393886341156,285653874084804,290995833960000,301929754767876,307523781758736,313203913114624,324826726702500,330771552139876,336806768471616 cal $0,15224 ; Even pentagonal pyramidal numbers. pow $0,2 mov $1,$0
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2013. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -------------------------------------------------------------------------- // $Maintainer: Andreas Bertsch $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/FORMAT/XTandemXMLFile.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <vector> /////////////////////////// START_TEST(XTandemXMLFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; XTandemXMLFile xml_file; XTandemXMLFile* ptr; XTandemXMLFile* nullPointer = 0; ProteinIdentification protein_identification; vector<PeptideIdentification> peptide_identifications; vector<PeptideIdentification> peptide_identifications2; String date_string_1; String date_string_2; PeptideHit peptide_hit; START_SECTION((XTandemXMLFile())) ptr = new XTandemXMLFile(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~XTandemXMLFile()) delete ptr; END_SECTION ptr = new XTandemXMLFile(); START_SECTION(void setModificationDefinitionsSet(const ModificationDefinitionsSet &rhs)) ModificationDefinitionsSet mod_set(ListUtils::create<String>(""), ListUtils::create<String>("Carbamidomethyl (C),Oxidation (M),Carboxymethyl (C)")); ptr->setModificationDefinitionsSet(mod_set); NOT_TESTABLE END_SECTION START_SECTION(void load(const String& filename, ProteinIdentification& protein_identification, std::vector<PeptideIdentification>& id_data)) ptr->load(OPENMS_GET_TEST_DATA_PATH("XTandemXMLFile_test.xml"), protein_identification, peptide_identifications); TEST_EQUAL(peptide_identifications.size(), 303) TEST_EQUAL(protein_identification.getHits().size(), 497) ptr->load(OPENMS_GET_TEST_DATA_PATH("XTandemXMLFile_test_2.xml"), protein_identification, peptide_identifications); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
; A327936: Multiplicative with a(p^e) = p if e >= p, otherwise 1. ; 1,1,1,2,1,1,1,2,1,1,1,2,1,1,1,2,1,1,1,2,1,1,1,2,1,1,3,2,1,1,1,2,1,1,1,2,1,1,1,2,1,1,1,2,1,1,1,2,1,1,1,2,1,3,1,2,1,1,1,2,1,1,1,2,1,1,1,2,1,1,1,2,1,1,1,2,1,1,1,2,3,1,1,2,1,1,1,2,1,1,1,2,1,1,1,2,1,1,1,2 add $0,1 mov $1,1 mov $2,2 mov $3,$0 mov $4,$0 lpb $3 mov $5,$4 mov $6,0 lpb $5 add $6,1 mov $7,$0 div $0,$2 mod $7,$2 cmp $7,0 sub $5,$7 lpe div $6,$2 cmp $6,0 cmp $6,0 mov $7,$2 pow $7,$6 mul $1,$7 add $2,1 div $3,3 lpe mov $0,$1
; A114753: First column of A114751. ; 1,3,3,7,5,11,7,15,9,19,11,23,13,27,15,31,17,35,19,39,21,43,23,47,25,51,27,55,29,59,31,63,33,67,35,71,37,75,39,79,41,83,43,87,45,91,47,95,49,99,51,103,53,107,55,111,57,115,59,119,61,123,63,127,65,131,67,135,69 dif $0,2 mul $0,2 add $0,1
;=============================================================================== ; Copyright 2015-2020 Intel Corporation ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;=============================================================================== ; ; ; Purpose: Cryptography Primitive. ; Big Number Operations ; ; Content: ; mont_mul1024_avx2() ; %include "asmdefs.inc" %include "ia_32e.inc" ;include bn_umulschool.inc ;include variant.inc %if (__ARCH32E >= __ARCH32E_L9) segment .text align=ARCH_ALIGN_FACTOR %assign DIGIT_BITS 27 %assign DIGIT_MASK (1 << DIGIT_BITS) -1 ;************************************************************* ;* void mont_mul1024_avx2(uint64_t* pR, ;* const uint64_t* pA, ;* const uint64_t* pB, ;* const uint64_t* pModulo, int mSize, ;* uint64_t m0) ;************************************************************* align ARCH_ALIGN_FACTOR IPPASM mont_mul1024_avx2,PUBLIC %assign LOCAL_FRAME sizeof(ymmword) USES_GPR rsi,rdi,rbx,rbp,r12,r13,r14 USES_XMM_AVX ymm6,ymm7,ymm8,ymm9,ymm10,ymm11,ymm12,ymm13,ymm14 COMP_ABI 6 mov rbp,rdx ; pointer to B operand movsxd r8, r8d ; redLen value counter ;; clear results and buffers vzeroall ;; expands A and M operands vmovdqu ymmword [rsi+r8*sizeof(qword)], ymm0 vmovdqu ymmword [rcx+r8*sizeof(qword)], ymm0 xor r10, r10 ; ac0 = 0 vmovdqu ymmword [rsp], ymm0 ; {r3:r2:r1;R0} = 0 align ARCH_ALIGN_FACTOR ;; ;; process b[] by quadruples (b[j], b[j+1], b[j+2] and b[j+3]) per pass ;; .loop4_B: mov rbx, qword [rbp] ; rbx = b[j] vpbroadcastq ymm0, qword [rbp] mov r10, rbx ; ac0 = pa[0]*b[j]+pr[0] imul r10, qword [rsi] add r10, qword [rsp] mov rdx, r10 ; y0 = (ac0*m0) & DIGIT_MASK imul edx, r9d and edx, DIGIT_MASK mov r11, rbx ; ac1 = pa[1]*b[j]+pr[1] imul r11, qword [rsi+sizeof(qword)] add r11, qword [rsp+sizeof(qword)] mov r12, rbx ; ac2 = pa[2]*b[j]+pr[2] imul r12, qword [rsi+sizeof(qword)*2] add r12, qword [rsp+sizeof(qword)*2] mov r13, rbx ; ac3 = pa[3]*b[j]+pr[3] imul r13, qword [rsi+sizeof(qword)*3] add r13, qword [rsp+sizeof(qword)*3] vmovd xmm11, edx vpbroadcastq ymm11, xmm11 vpmuludq ymm12, ymm0, ymmword [rsi+sizeof(ymmword)] vpaddq ymm1, ymm1, ymm12 vpmuludq ymm13, ymm0, ymmword [rsi+sizeof(ymmword)*2] vpaddq ymm2, ymm2, ymm13 vpmuludq ymm14, ymm0, ymmword [rsi+sizeof(ymmword)*3] vpaddq ymm3, ymm3, ymm14 vpmuludq ymm12, ymm0, ymmword [rsi+sizeof(ymmword)*4] vpaddq ymm4, ymm4, ymm12 vpmuludq ymm13, ymm0, ymmword [rsi+sizeof(ymmword)*5] vpaddq ymm5, ymm5, ymm13 vpmuludq ymm14, ymm0, ymmword [rsi+sizeof(ymmword)*6] vpaddq ymm6, ymm6, ymm14 vpmuludq ymm12, ymm0, ymmword [rsi+sizeof(ymmword)*7] vpaddq ymm7, ymm7, ymm12 vpmuludq ymm13, ymm0, ymmword [rsi+sizeof(ymmword)*8] vpaddq ymm8, ymm8, ymm13 vpmuludq ymm14, ymm0, ymmword [rsi+sizeof(ymmword)*9] vpaddq ymm9, ymm9, ymm14 mov rax, rdx ; ac0 += pn[0]*y0 imul rax, qword [rcx] add r10, rax shr r10, DIGIT_BITS mov rax, rdx ; ac1 += pn[1]*y0 imul rax, qword [rcx+sizeof(qword)] add r11, rax add r11, r10 mov rax, rdx ; ac2 += pn[2]*y0 imul rax, qword [rcx+sizeof(qword)*2] add r12, rax mov rax, rdx ; ac3 += pn[3]*y0 imul rax, qword [rcx+sizeof(qword)*3] add r13, rax vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)] vpaddq ymm1, ymm1, ymm12 vpmuludq ymm13, ymm11, ymmword [rcx+sizeof(ymmword)*2] vpaddq ymm2, ymm2, ymm13 vpmuludq ymm14, ymm11, ymmword [rcx+sizeof(ymmword)*3] vpaddq ymm3, ymm3, ymm14 vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)*4] vpaddq ymm4, ymm4, ymm12 vpmuludq ymm13, ymm11, ymmword [rcx+sizeof(ymmword)*5] vpaddq ymm5, ymm5, ymm13 vpmuludq ymm14, ymm11, ymmword [rcx+sizeof(ymmword)*6] vpaddq ymm6, ymm6, ymm14 vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)*7] vpaddq ymm7, ymm7, ymm12 vpmuludq ymm13, ymm11, ymmword [rcx+sizeof(ymmword)*8] vpaddq ymm8, ymm8, ymm13 vpmuludq ymm14, ymm11, ymmword [rcx+sizeof(ymmword)*9] vpaddq ymm9, ymm9, ymm14 ;; ------------------------------------------------------------ mov rbx, qword [rbp+sizeof(qword)] ; rbx = b[j+1] vpbroadcastq ymm0, qword [rbp+sizeof(qword)] mov rax, rbx ; ac1 += pa[0]*b[j+1] imul rax, qword [rsi] add r11, rax mov rdx, r11 ; y1 = (ac1*m0) & DIGIT_MASK imul edx, r9d and edx, DIGIT_MASK mov rax, rbx ; ac2 += pa[1]*b[j+1] imul rax, qword [rsi+sizeof(qword)] add r12, rax mov rax, rbx ; ac3 += pa[2]*b[j+1] imul rax, qword [rsi+sizeof(qword)*2] add r13, rax vmovd xmm11, edx vpbroadcastq ymm11, xmm11 vpmuludq ymm12, ymm0, ymmword [rsi+sizeof(ymmword)-sizeof(qword)] vpaddq ymm1, ymm1, ymm12 vpmuludq ymm13, ymm0, ymmword [rsi+sizeof(ymmword)*2-sizeof(qword)] vpaddq ymm2, ymm2, ymm13 vpmuludq ymm14, ymm0, ymmword [rsi+sizeof(ymmword)*3-sizeof(qword)] vpaddq ymm3, ymm3, ymm14 vpmuludq ymm12, ymm0, ymmword [rsi+sizeof(ymmword)*4-sizeof(qword)] vpaddq ymm4, ymm4, ymm12 vpmuludq ymm13, ymm0, ymmword [rsi+sizeof(ymmword)*5-sizeof(qword)] vpaddq ymm5, ymm5, ymm13 vpmuludq ymm14, ymm0, ymmword [rsi+sizeof(ymmword)*6-sizeof(qword)] vpaddq ymm6, ymm6, ymm14 vpmuludq ymm12, ymm0, ymmword [rsi+sizeof(ymmword)*7-sizeof(qword)] vpaddq ymm7, ymm7, ymm12 vpmuludq ymm13, ymm0, ymmword [rsi+sizeof(ymmword)*8-sizeof(qword)] vpaddq ymm8, ymm8, ymm13 vpmuludq ymm14, ymm0, ymmword [rsi+sizeof(ymmword)*9-sizeof(qword)] vpaddq ymm9, ymm9, ymm14 mov rax, rdx ; ac1 += pn[0]*y1 imul rax, qword [rcx] add r11, rax shr r11, DIGIT_BITS mov rax, rdx ; ac2 += pn[1]*y1 imul rax, qword [rcx+sizeof(qword)] add r12, rax add r12, r11 mov rax, rdx ; ac3 += pn[2]*y1 imul rax, qword [rcx+sizeof(qword)*2] add r13, rax vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)-sizeof(qword)] vpaddq ymm1, ymm1, ymm12 vpmuludq ymm13, ymm11, ymmword [rcx+sizeof(ymmword)*2-sizeof(qword)] vpaddq ymm2, ymm2, ymm13 vpmuludq ymm14, ymm11, ymmword [rcx+sizeof(ymmword)*3-sizeof(qword)] vpaddq ymm3, ymm3, ymm14 vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)*4-sizeof(qword)] vpaddq ymm4, ymm4, ymm12 vpmuludq ymm13, ymm11, ymmword [rcx+sizeof(ymmword)*5-sizeof(qword)] vpaddq ymm5, ymm5, ymm13 vpmuludq ymm14, ymm11, ymmword [rcx+sizeof(ymmword)*6-sizeof(qword)] vpaddq ymm6, ymm6, ymm14 vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)*7-sizeof(qword)] vpaddq ymm7, ymm7, ymm12 vpmuludq ymm13, ymm11, ymmword [rcx+sizeof(ymmword)*8-sizeof(qword)] vpaddq ymm8, ymm8, ymm13 vpmuludq ymm14, ymm11, ymmword [rcx+sizeof(ymmword)*9-sizeof(qword)] vpaddq ymm9, ymm9, ymm14 sub r8, 2 jz .exit_loop_B ;; ------------------------------------------------------------ mov rbx, qword [rbp+sizeof(qword)*2] ; rbx = b[j+2] vpbroadcastq ymm0, qword [rbp+sizeof(qword)*2] mov rax, rbx ; ac2 += pa[0]*b[j+2] imul rax, qword [rsi] add r12, rax mov rdx, r12 ; y2 = (ac2*m0) & DIGIT_MASK imul edx, r9d and edx, DIGIT_MASK mov rax, rbx ; ac2 += pa[0]*b[j+2] imul rax, qword [rsi+sizeof(qword)] add r13, rax vmovd xmm11, edx vpbroadcastq ymm11, xmm11 vpmuludq ymm12, ymm0, ymmword [rsi+sizeof(ymmword)-sizeof(qword)*2] vpaddq ymm1, ymm1, ymm12 vpmuludq ymm13, ymm0, ymmword [rsi+sizeof(ymmword)*2-sizeof(qword)*2] vpaddq ymm2, ymm2, ymm13 vpmuludq ymm14, ymm0, ymmword [rsi+sizeof(ymmword)*3-sizeof(qword)*2] vpaddq ymm3, ymm3, ymm14 vpmuludq ymm12, ymm0, ymmword [rsi+sizeof(ymmword)*4-sizeof(qword)*2] vpaddq ymm4, ymm4, ymm12 vpmuludq ymm13, ymm0, ymmword [rsi+sizeof(ymmword)*5-sizeof(qword)*2] vpaddq ymm5, ymm5, ymm13 vpmuludq ymm14, ymm0, ymmword [rsi+sizeof(ymmword)*6-sizeof(qword)*2] vpaddq ymm6, ymm6, ymm14 vpmuludq ymm12, ymm0, ymmword [rsi+sizeof(ymmword)*7-sizeof(qword)*2] vpaddq ymm7, ymm7, ymm12 vpmuludq ymm13, ymm0, ymmword [rsi+sizeof(ymmword)*8-sizeof(qword)*2] vpaddq ymm8, ymm8, ymm13 vpmuludq ymm14, ymm0, ymmword [rsi+sizeof(ymmword)*9-sizeof(qword)*2] vpaddq ymm9, ymm9, ymm14 mov rax, rdx ; ac2 += pn[0]*y2 imul rax, qword [rcx] add r12, rax shr r12, DIGIT_BITS mov rax, rdx ; ac3 += pn[1]*y2 imul rax, qword [rcx+sizeof(qword)] add r13, rax add r13, r12 vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)-sizeof(qword)*2] vpaddq ymm1, ymm1, ymm12 vpmuludq ymm13, ymm11, ymmword [rcx+sizeof(ymmword)*2-sizeof(qword)*2] vpaddq ymm2, ymm2, ymm13 vpmuludq ymm14, ymm11, ymmword [rcx+sizeof(ymmword)*3-sizeof(qword)*2] vpaddq ymm3, ymm3, ymm14 vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)*4-sizeof(qword)*2] vpaddq ymm4, ymm4, ymm12 vpmuludq ymm13, ymm11, ymmword [rcx+sizeof(ymmword)*5-sizeof(qword)*2] vpaddq ymm5, ymm5, ymm13 vpmuludq ymm14, ymm11, ymmword [rcx+sizeof(ymmword)*6-sizeof(qword)*2] vpaddq ymm6, ymm6, ymm14 vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)*7-sizeof(qword)*2] vpaddq ymm7, ymm7, ymm12 vpmuludq ymm13, ymm11, ymmword [rcx+sizeof(ymmword)*8-sizeof(qword)*2] vpaddq ymm8, ymm8, ymm13 vpmuludq ymm14, ymm11, ymmword [rcx+sizeof(ymmword)*9-sizeof(qword)*2] vpaddq ymm9, ymm9, ymm14 ;; ------------------------------------------------------------ mov rbx, qword [rbp+sizeof(qword)*3] ; rbx = b[j+3] vpbroadcastq ymm0, qword [rbp+sizeof(qword)*3] imul rbx, qword [rsi] ; ac3 += pa[0]*b[j+3] add r13, rbx mov rdx, r13 ; y3 = (ac3*m0) & DIGIT_MASK imul edx, r9d and edx, DIGIT_MASK vmovd xmm11, edx vpbroadcastq ymm11, xmm11 vpmuludq ymm12, ymm0, ymmword [rsi+sizeof(ymmword)-sizeof(qword)*3] vpaddq ymm1, ymm1, ymm12 vpmuludq ymm13, ymm0, ymmword [rsi+sizeof(ymmword)*2-sizeof(qword)*3] vpaddq ymm2, ymm2, ymm13 vpmuludq ymm14, ymm0, ymmword [rsi+sizeof(ymmword)*3-sizeof(qword)*3] vpaddq ymm3, ymm3, ymm14 vpmuludq ymm12, ymm0, ymmword [rsi+sizeof(ymmword)*4-sizeof(qword)*3] vpaddq ymm4, ymm4, ymm12 vpmuludq ymm13, ymm0, ymmword [rsi+sizeof(ymmword)*5-sizeof(qword)*3] vpaddq ymm5, ymm5, ymm13 vpmuludq ymm14, ymm0, ymmword [rsi+sizeof(ymmword)*6-sizeof(qword)*3] vpaddq ymm6, ymm6, ymm14 vpmuludq ymm12, ymm0, ymmword [rsi+sizeof(ymmword)*7-sizeof(qword)*3] vpaddq ymm7, ymm7, ymm12 vpmuludq ymm13, ymm0, ymmword [rsi+sizeof(ymmword)*8-sizeof(qword)*3] vpaddq ymm8, ymm8, ymm13 vpmuludq ymm14, ymm0, ymmword [rsi+sizeof(ymmword)*9-sizeof(qword)*3] vpaddq ymm9, ymm9, ymm14 vpmuludq ymm10, ymm0, ymmword [rsi+sizeof(ymmword)*10-sizeof(qword)*3] imul rdx, qword [rcx] ; ac3 += pn[0]*y3 add r13, rdx shr r13, DIGIT_BITS vmovq xmm14, r13 vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)-sizeof(qword)*3] vpaddq ymm1, ymm1, ymm12 vpaddq ymm1, ymm1, ymm14 vmovdqu ymmword [rsp], ymm1 vpmuludq ymm13, ymm11, ymmword [rcx+sizeof(ymmword)*2-sizeof(qword)*3] vpaddq ymm1, ymm2, ymm13 vpmuludq ymm14, ymm11, ymmword [rcx+sizeof(ymmword)*3-sizeof(qword)*3] vpaddq ymm2, ymm3, ymm14 vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)*4-sizeof(qword)*3] vpaddq ymm3, ymm4, ymm12 vpmuludq ymm13, ymm11, ymmword [rcx+sizeof(ymmword)*5-sizeof(qword)*3] vpaddq ymm4, ymm5, ymm13 vpmuludq ymm14, ymm11, ymmword [rcx+sizeof(ymmword)*6-sizeof(qword)*3] vpaddq ymm5, ymm6, ymm14 vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)*7-sizeof(qword)*3] vpaddq ymm6, ymm7, ymm12 vpmuludq ymm13, ymm11, ymmword [rcx+sizeof(ymmword)*8-sizeof(qword)*3] vpaddq ymm7, ymm8, ymm13 vpmuludq ymm14, ymm11, ymmword [rcx+sizeof(ymmword)*9-sizeof(qword)*3] vpaddq ymm8, ymm9, ymm14 vpmuludq ymm12, ymm11, ymmword [rcx+sizeof(ymmword)*10-sizeof(qword)*3] vpaddq ymm9, ymm10, ymm12 ;; ------------------------------------------------------------ add rbp, sizeof(qword)*4 sub r8, 2 jnz .loop4_B .exit_loop_B: mov qword [rdi], r12 mov qword [rdi+sizeof(qword)], r13 vmovdqu ymmword [rdi+sizeof(qword)*2], ymm1 vmovdqu ymmword [rdi+sizeof(qword)*2+sizeof(ymmword)], ymm2 vmovdqu ymmword [rdi+sizeof(qword)*2+sizeof(ymmword)*2], ymm3 vmovdqu ymmword [rdi+sizeof(qword)*2+sizeof(ymmword)*3], ymm4 vmovdqu ymmword [rdi+sizeof(qword)*2+sizeof(ymmword)*4], ymm5 vmovdqu ymmword [rdi+sizeof(qword)*2+sizeof(ymmword)*5], ymm6 vmovdqu ymmword [rdi+sizeof(qword)*2+sizeof(ymmword)*6], ymm7 vmovdqu ymmword [rdi+sizeof(qword)*2+sizeof(ymmword)*7], ymm8 vmovdqu ymmword [rdi+sizeof(qword)*2+sizeof(ymmword)*8], ymm9 ;; ;; normalize ;; mov r8, dword 38 xor rax, rax .norm_loop: add rax, qword [rdi] add rdi, sizeof(qword) mov rdx, dword DIGIT_MASK and rdx, rax shr rax, DIGIT_BITS mov qword [rdi-sizeof(qword)], rdx sub r8, 1 jg .norm_loop mov qword [rdi], rax REST_XMM_AVX REST_GPR ret ENDFUNC mont_mul1024_avx2 %endif ; __ARCH32E_L9
_start: mov ax, 0 mov bx, https://example.com mov cx, SITE syscall mov ax, 1 mov bx, 1 mov cx, [SITE] syscall
//Bai toan cai ba lo 1 // Moi do vat co so luong khong han che // Du lieu cho trong file D://Balo.INP #include <stdio.h> #include <malloc.h> #include <string.h> typedef struct { char TenDV[20]; int TL, GT, PA; } DoVat; typedef int bang[50][100];// Ba lo co trong luong toi da 99 va co toi da 50 do vat DoVat * ReadFromFile(int *W, int *n){ FILE *f; f=fopen("balo1-quyhoachcdong.inp", "r"); fscanf(f, "%d",W); // Xac dinh trong luong Ba lo DoVat *dsdv; dsdv=(DoVat*)malloc(sizeof(DoVat)); int i=0; while (!feof(f)){ fscanf(f, "%d%d",&dsdv[i].TL,&dsdv[i].GT); fgets(dsdv[i].TenDV,20,f); dsdv[i].TenDV[strlen(dsdv[i].TenDV)-1]='\0'; dsdv[i].PA=0; i++; dsdv=(DoVat*)realloc(dsdv, sizeof(DoVat)*(i+1)); } *n=i; fclose(f); return dsdv; } void InDSDV(DoVat *dsdv ,int n, int W){ int i,TongTL=0, TongGT=0; printf("|---|--------------------|---------|---------|---------|\n"); printf("|%-3s|%-20s|%-9s|%-9s|%-9s|\n", "STT", " Ten Do Vat ","T.Luong", "Gia Tri", "P. An"); printf("|---|--------------------|---------|---------|---------|\n"); for(i=0;i<n;i++){ printf("|%-3d",i+1); printf("|%-20s",dsdv[i].TenDV); printf("|%-9d",dsdv[i].TL); printf("|%-9d",dsdv[i].GT); printf("|%-9d|\n",dsdv[i].PA); TongTL=TongTL+dsdv[i].PA * dsdv[i].TL; TongGT=TongGT+dsdv[i].PA * dsdv[i].GT; } printf("|---|--------------------|---------|---------|---------|\n"); printf("Trong luong cua ba lo= %d\n",W); printf("Tong trong luong= %d, Tong gia tri= %d\n", TongTL, TongGT); } void TaoBang(DoVat *dsdv,int n,int W, bang F,bang X){ int xk, yk, k; int FMax, XMax, V; // Dien h?ng dau tien cua hai bang for(V= 0; V<=W; V++) { X[0][V] = V/dsdv[0].TL; F[0][V] = X[0][V] * dsdv[0].GT; } // ?ien c?c d?ng c?n lai for(k= 1; k<n; k++) for(V=0; V<=W; V++) { FMax = F[k-1][V] ; XMax = 0; yk = V/dsdv[k].TL; for(xk = 1; xk<=yk; xk++) if(F[k-1][V-xk*dsdv[k].TL]+xk*dsdv[k].GT>FMax){ FMax=F[k-1][V-xk*dsdv[k].TL]+xk*dsdv[k].GT; XMax= xk; } F[k][V] = FMax; X[k][V] = XMax; } } void InBang(int n, int W, bang F, bang X){ int V, k; for(k=0; k<n; k++){ for(V=0; V<=W; V++) printf("|%4d%2d",F[k][V], X[k][V]); printf("\n"); } } void TraBang(DoVat *dsdv, int n, int W, bang X) { int k, V; V = W; for(k= n-1; k>=0; k--) { dsdv[k].PA = X[k][V]; V = V - X[k][V] * dsdv[k].TL; } } int main(){ int n, W; bang X,F; DoVat *dsdv; dsdv=ReadFromFile(&W, &n); TaoBang(dsdv,n,W,F,X); InBang(n,W,F,X); printf("\n"); TraBang(dsdv,n,W,X); InDSDV(dsdv,n,W); free(dsdv); return 0; }
_zombie: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(void) { 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: 51 push %ecx e: 83 ec 04 sub $0x4,%esp if(fork() > 0) 11: e8 64 02 00 00 call 27a <fork> 16: 85 c0 test %eax,%eax 18: 7e 0d jle 27 <main+0x27> sleep(5); // Let child exit before parent. 1a: 83 ec 0c sub $0xc,%esp 1d: 6a 05 push $0x5 1f: e8 ee 02 00 00 call 312 <sleep> 24: 83 c4 10 add $0x10,%esp exit(); 27: e8 56 02 00 00 call 282 <exit> 2c: 66 90 xchg %ax,%ax 2e: 66 90 xchg %ax,%ax 00000030 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, const char *t) { 30: 55 push %ebp 31: 89 e5 mov %esp,%ebp 33: 53 push %ebx 34: 8b 45 08 mov 0x8(%ebp),%eax 37: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) 3a: 89 c2 mov %eax,%edx 3c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 40: 83 c1 01 add $0x1,%ecx 43: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 47: 83 c2 01 add $0x1,%edx 4a: 84 db test %bl,%bl 4c: 88 5a ff mov %bl,-0x1(%edx) 4f: 75 ef jne 40 <strcpy+0x10> ; return os; } 51: 5b pop %ebx 52: 5d pop %ebp 53: c3 ret 54: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 5a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000060 <strcmp>: int strcmp(const char *p, const char *q) { 60: 55 push %ebp 61: 89 e5 mov %esp,%ebp 63: 53 push %ebx 64: 8b 55 08 mov 0x8(%ebp),%edx 67: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) 6a: 0f b6 02 movzbl (%edx),%eax 6d: 0f b6 19 movzbl (%ecx),%ebx 70: 84 c0 test %al,%al 72: 75 1c jne 90 <strcmp+0x30> 74: eb 2a jmp a0 <strcmp+0x40> 76: 8d 76 00 lea 0x0(%esi),%esi 79: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; 80: 83 c2 01 add $0x1,%edx while(*p && *p == *q) 83: 0f b6 02 movzbl (%edx),%eax p++, q++; 86: 83 c1 01 add $0x1,%ecx 89: 0f b6 19 movzbl (%ecx),%ebx while(*p && *p == *q) 8c: 84 c0 test %al,%al 8e: 74 10 je a0 <strcmp+0x40> 90: 38 d8 cmp %bl,%al 92: 74 ec je 80 <strcmp+0x20> return (uchar)*p - (uchar)*q; 94: 29 d8 sub %ebx,%eax } 96: 5b pop %ebx 97: 5d pop %ebp 98: c3 ret 99: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi a0: 31 c0 xor %eax,%eax return (uchar)*p - (uchar)*q; a2: 29 d8 sub %ebx,%eax } a4: 5b pop %ebx a5: 5d pop %ebp a6: c3 ret a7: 89 f6 mov %esi,%esi a9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000000b0 <strlen>: uint strlen(const char *s) { b0: 55 push %ebp b1: 89 e5 mov %esp,%ebp b3: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) b6: 80 39 00 cmpb $0x0,(%ecx) b9: 74 15 je d0 <strlen+0x20> bb: 31 d2 xor %edx,%edx bd: 8d 76 00 lea 0x0(%esi),%esi c0: 83 c2 01 add $0x1,%edx c3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) c7: 89 d0 mov %edx,%eax c9: 75 f5 jne c0 <strlen+0x10> ; return n; } cb: 5d pop %ebp cc: c3 ret cd: 8d 76 00 lea 0x0(%esi),%esi for(n = 0; s[n]; n++) d0: 31 c0 xor %eax,%eax } d2: 5d pop %ebp d3: c3 ret d4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi da: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000000e0 <memset>: void* memset(void *dst, int c, uint n) { e0: 55 push %ebp e1: 89 e5 mov %esp,%ebp e3: 57 push %edi e4: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : e7: 8b 4d 10 mov 0x10(%ebp),%ecx ea: 8b 45 0c mov 0xc(%ebp),%eax ed: 89 d7 mov %edx,%edi ef: fc cld f0: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } f2: 89 d0 mov %edx,%eax f4: 5f pop %edi f5: 5d pop %ebp f6: c3 ret f7: 89 f6 mov %esi,%esi f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000100 <strchr>: char* strchr(const char *s, char c) { 100: 55 push %ebp 101: 89 e5 mov %esp,%ebp 103: 53 push %ebx 104: 8b 45 08 mov 0x8(%ebp),%eax 107: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 10a: 0f b6 10 movzbl (%eax),%edx 10d: 84 d2 test %dl,%dl 10f: 74 1d je 12e <strchr+0x2e> if(*s == c) 111: 38 d3 cmp %dl,%bl 113: 89 d9 mov %ebx,%ecx 115: 75 0d jne 124 <strchr+0x24> 117: eb 17 jmp 130 <strchr+0x30> 119: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 120: 38 ca cmp %cl,%dl 122: 74 0c je 130 <strchr+0x30> for(; *s; s++) 124: 83 c0 01 add $0x1,%eax 127: 0f b6 10 movzbl (%eax),%edx 12a: 84 d2 test %dl,%dl 12c: 75 f2 jne 120 <strchr+0x20> return (char*)s; return 0; 12e: 31 c0 xor %eax,%eax } 130: 5b pop %ebx 131: 5d pop %ebp 132: c3 ret 133: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 139: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000140 <gets>: char* gets(char *buf, int max) { 140: 55 push %ebp 141: 89 e5 mov %esp,%ebp 143: 57 push %edi 144: 56 push %esi 145: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 146: 31 f6 xor %esi,%esi 148: 89 f3 mov %esi,%ebx { 14a: 83 ec 1c sub $0x1c,%esp 14d: 8b 7d 08 mov 0x8(%ebp),%edi for(i=0; i+1 < max; ){ 150: eb 2f jmp 181 <gets+0x41> 152: 8d b6 00 00 00 00 lea 0x0(%esi),%esi cc = read(0, &c, 1); 158: 8d 45 e7 lea -0x19(%ebp),%eax 15b: 83 ec 04 sub $0x4,%esp 15e: 6a 01 push $0x1 160: 50 push %eax 161: 6a 00 push $0x0 163: e8 32 01 00 00 call 29a <read> if(cc < 1) 168: 83 c4 10 add $0x10,%esp 16b: 85 c0 test %eax,%eax 16d: 7e 1c jle 18b <gets+0x4b> break; buf[i++] = c; 16f: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 173: 83 c7 01 add $0x1,%edi 176: 88 47 ff mov %al,-0x1(%edi) if(c == '\n' || c == '\r') 179: 3c 0a cmp $0xa,%al 17b: 74 23 je 1a0 <gets+0x60> 17d: 3c 0d cmp $0xd,%al 17f: 74 1f je 1a0 <gets+0x60> for(i=0; i+1 < max; ){ 181: 83 c3 01 add $0x1,%ebx 184: 3b 5d 0c cmp 0xc(%ebp),%ebx 187: 89 fe mov %edi,%esi 189: 7c cd jl 158 <gets+0x18> 18b: 89 f3 mov %esi,%ebx break; } buf[i] = '\0'; return buf; } 18d: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 190: c6 03 00 movb $0x0,(%ebx) } 193: 8d 65 f4 lea -0xc(%ebp),%esp 196: 5b pop %ebx 197: 5e pop %esi 198: 5f pop %edi 199: 5d pop %ebp 19a: c3 ret 19b: 90 nop 19c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 1a0: 8b 75 08 mov 0x8(%ebp),%esi 1a3: 8b 45 08 mov 0x8(%ebp),%eax 1a6: 01 de add %ebx,%esi 1a8: 89 f3 mov %esi,%ebx buf[i] = '\0'; 1aa: c6 03 00 movb $0x0,(%ebx) } 1ad: 8d 65 f4 lea -0xc(%ebp),%esp 1b0: 5b pop %ebx 1b1: 5e pop %esi 1b2: 5f pop %edi 1b3: 5d pop %ebp 1b4: c3 ret 1b5: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 1b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000001c0 <stat>: int stat(const char *n, struct stat *st) { 1c0: 55 push %ebp 1c1: 89 e5 mov %esp,%ebp 1c3: 56 push %esi 1c4: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 1c5: 83 ec 08 sub $0x8,%esp 1c8: 6a 00 push $0x0 1ca: ff 75 08 pushl 0x8(%ebp) 1cd: e8 f0 00 00 00 call 2c2 <open> if(fd < 0) 1d2: 83 c4 10 add $0x10,%esp 1d5: 85 c0 test %eax,%eax 1d7: 78 27 js 200 <stat+0x40> return -1; r = fstat(fd, st); 1d9: 83 ec 08 sub $0x8,%esp 1dc: ff 75 0c pushl 0xc(%ebp) 1df: 89 c3 mov %eax,%ebx 1e1: 50 push %eax 1e2: e8 f3 00 00 00 call 2da <fstat> close(fd); 1e7: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 1ea: 89 c6 mov %eax,%esi close(fd); 1ec: e8 b9 00 00 00 call 2aa <close> return r; 1f1: 83 c4 10 add $0x10,%esp } 1f4: 8d 65 f8 lea -0x8(%ebp),%esp 1f7: 89 f0 mov %esi,%eax 1f9: 5b pop %ebx 1fa: 5e pop %esi 1fb: 5d pop %ebp 1fc: c3 ret 1fd: 8d 76 00 lea 0x0(%esi),%esi return -1; 200: be ff ff ff ff mov $0xffffffff,%esi 205: eb ed jmp 1f4 <stat+0x34> 207: 89 f6 mov %esi,%esi 209: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000210 <atoi>: int atoi(const char *s) { 210: 55 push %ebp 211: 89 e5 mov %esp,%ebp 213: 53 push %ebx 214: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 217: 0f be 11 movsbl (%ecx),%edx 21a: 8d 42 d0 lea -0x30(%edx),%eax 21d: 3c 09 cmp $0x9,%al n = 0; 21f: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 224: 77 1f ja 245 <atoi+0x35> 226: 8d 76 00 lea 0x0(%esi),%esi 229: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 230: 8d 04 80 lea (%eax,%eax,4),%eax 233: 83 c1 01 add $0x1,%ecx 236: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax while('0' <= *s && *s <= '9') 23a: 0f be 11 movsbl (%ecx),%edx 23d: 8d 5a d0 lea -0x30(%edx),%ebx 240: 80 fb 09 cmp $0x9,%bl 243: 76 eb jbe 230 <atoi+0x20> return n; } 245: 5b pop %ebx 246: 5d pop %ebp 247: c3 ret 248: 90 nop 249: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000250 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 250: 55 push %ebp 251: 89 e5 mov %esp,%ebp 253: 56 push %esi 254: 53 push %ebx 255: 8b 5d 10 mov 0x10(%ebp),%ebx 258: 8b 45 08 mov 0x8(%ebp),%eax 25b: 8b 75 0c mov 0xc(%ebp),%esi char *dst; const char *src; dst = vdst; src = vsrc; while(n-- > 0) 25e: 85 db test %ebx,%ebx 260: 7e 14 jle 276 <memmove+0x26> 262: 31 d2 xor %edx,%edx 264: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 268: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 26c: 88 0c 10 mov %cl,(%eax,%edx,1) 26f: 83 c2 01 add $0x1,%edx while(n-- > 0) 272: 39 d3 cmp %edx,%ebx 274: 75 f2 jne 268 <memmove+0x18> return vdst; } 276: 5b pop %ebx 277: 5e pop %esi 278: 5d pop %ebp 279: c3 ret 0000027a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 27a: b8 01 00 00 00 mov $0x1,%eax 27f: cd 40 int $0x40 281: c3 ret 00000282 <exit>: SYSCALL(exit) 282: b8 02 00 00 00 mov $0x2,%eax 287: cd 40 int $0x40 289: c3 ret 0000028a <wait>: SYSCALL(wait) 28a: b8 03 00 00 00 mov $0x3,%eax 28f: cd 40 int $0x40 291: c3 ret 00000292 <pipe>: SYSCALL(pipe) 292: b8 04 00 00 00 mov $0x4,%eax 297: cd 40 int $0x40 299: c3 ret 0000029a <read>: SYSCALL(read) 29a: b8 05 00 00 00 mov $0x5,%eax 29f: cd 40 int $0x40 2a1: c3 ret 000002a2 <write>: SYSCALL(write) 2a2: b8 10 00 00 00 mov $0x10,%eax 2a7: cd 40 int $0x40 2a9: c3 ret 000002aa <close>: SYSCALL(close) 2aa: b8 15 00 00 00 mov $0x15,%eax 2af: cd 40 int $0x40 2b1: c3 ret 000002b2 <kill>: SYSCALL(kill) 2b2: b8 06 00 00 00 mov $0x6,%eax 2b7: cd 40 int $0x40 2b9: c3 ret 000002ba <exec>: SYSCALL(exec) 2ba: b8 07 00 00 00 mov $0x7,%eax 2bf: cd 40 int $0x40 2c1: c3 ret 000002c2 <open>: SYSCALL(open) 2c2: b8 0f 00 00 00 mov $0xf,%eax 2c7: cd 40 int $0x40 2c9: c3 ret 000002ca <mknod>: SYSCALL(mknod) 2ca: b8 11 00 00 00 mov $0x11,%eax 2cf: cd 40 int $0x40 2d1: c3 ret 000002d2 <unlink>: SYSCALL(unlink) 2d2: b8 12 00 00 00 mov $0x12,%eax 2d7: cd 40 int $0x40 2d9: c3 ret 000002da <fstat>: SYSCALL(fstat) 2da: b8 08 00 00 00 mov $0x8,%eax 2df: cd 40 int $0x40 2e1: c3 ret 000002e2 <link>: SYSCALL(link) 2e2: b8 13 00 00 00 mov $0x13,%eax 2e7: cd 40 int $0x40 2e9: c3 ret 000002ea <mkdir>: SYSCALL(mkdir) 2ea: b8 14 00 00 00 mov $0x14,%eax 2ef: cd 40 int $0x40 2f1: c3 ret 000002f2 <chdir>: SYSCALL(chdir) 2f2: b8 09 00 00 00 mov $0x9,%eax 2f7: cd 40 int $0x40 2f9: c3 ret 000002fa <dup>: SYSCALL(dup) 2fa: b8 0a 00 00 00 mov $0xa,%eax 2ff: cd 40 int $0x40 301: c3 ret 00000302 <getpid>: SYSCALL(getpid) 302: b8 0b 00 00 00 mov $0xb,%eax 307: cd 40 int $0x40 309: c3 ret 0000030a <sbrk>: SYSCALL(sbrk) 30a: b8 0c 00 00 00 mov $0xc,%eax 30f: cd 40 int $0x40 311: c3 ret 00000312 <sleep>: SYSCALL(sleep) 312: b8 0d 00 00 00 mov $0xd,%eax 317: cd 40 int $0x40 319: c3 ret 0000031a <uptime>: SYSCALL(uptime) 31a: b8 0e 00 00 00 mov $0xe,%eax 31f: cd 40 int $0x40 321: c3 ret 00000322 <sigset>: SYSCALL(sigset) 322: b8 16 00 00 00 mov $0x16,%eax 327: cd 40 int $0x40 329: c3 ret 0000032a <sigsend>: SYSCALL(sigsend) 32a: b8 17 00 00 00 mov $0x17,%eax 32f: cd 40 int $0x40 331: c3 ret 00000332 <sigret>: SYSCALL(sigret) 332: b8 18 00 00 00 mov $0x18,%eax 337: cd 40 int $0x40 339: c3 ret 0000033a <testing>: 33a: b8 19 00 00 00 mov $0x19,%eax 33f: cd 40 int $0x40 341: c3 ret 342: 66 90 xchg %ax,%ax 344: 66 90 xchg %ax,%ax 346: 66 90 xchg %ax,%ax 348: 66 90 xchg %ax,%ax 34a: 66 90 xchg %ax,%ax 34c: 66 90 xchg %ax,%ax 34e: 66 90 xchg %ax,%ax 00000350 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 350: 55 push %ebp 351: 89 e5 mov %esp,%ebp 353: 57 push %edi 354: 56 push %esi 355: 53 push %ebx 356: 83 ec 3c sub $0x3c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 359: 85 d2 test %edx,%edx { 35b: 89 45 c0 mov %eax,-0x40(%ebp) neg = 1; x = -xx; 35e: 89 d0 mov %edx,%eax if(sgn && xx < 0){ 360: 79 76 jns 3d8 <printint+0x88> 362: f6 45 08 01 testb $0x1,0x8(%ebp) 366: 74 70 je 3d8 <printint+0x88> x = -xx; 368: f7 d8 neg %eax neg = 1; 36a: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) } else { x = xx; } i = 0; 371: 31 f6 xor %esi,%esi 373: 8d 5d d7 lea -0x29(%ebp),%ebx 376: eb 0a jmp 382 <printint+0x32> 378: 90 nop 379: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi do{ buf[i++] = digits[x % base]; 380: 89 fe mov %edi,%esi 382: 31 d2 xor %edx,%edx 384: 8d 7e 01 lea 0x1(%esi),%edi 387: f7 f1 div %ecx 389: 0f b6 92 50 07 00 00 movzbl 0x750(%edx),%edx }while((x /= base) != 0); 390: 85 c0 test %eax,%eax buf[i++] = digits[x % base]; 392: 88 14 3b mov %dl,(%ebx,%edi,1) }while((x /= base) != 0); 395: 75 e9 jne 380 <printint+0x30> if(neg) 397: 8b 45 c4 mov -0x3c(%ebp),%eax 39a: 85 c0 test %eax,%eax 39c: 74 08 je 3a6 <printint+0x56> buf[i++] = '-'; 39e: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1) 3a3: 8d 7e 02 lea 0x2(%esi),%edi 3a6: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi 3aa: 8b 7d c0 mov -0x40(%ebp),%edi 3ad: 8d 76 00 lea 0x0(%esi),%esi 3b0: 0f b6 06 movzbl (%esi),%eax write(fd, &c, 1); 3b3: 83 ec 04 sub $0x4,%esp 3b6: 83 ee 01 sub $0x1,%esi 3b9: 6a 01 push $0x1 3bb: 53 push %ebx 3bc: 57 push %edi 3bd: 88 45 d7 mov %al,-0x29(%ebp) 3c0: e8 dd fe ff ff call 2a2 <write> while(--i >= 0) 3c5: 83 c4 10 add $0x10,%esp 3c8: 39 de cmp %ebx,%esi 3ca: 75 e4 jne 3b0 <printint+0x60> putc(fd, buf[i]); } 3cc: 8d 65 f4 lea -0xc(%ebp),%esp 3cf: 5b pop %ebx 3d0: 5e pop %esi 3d1: 5f pop %edi 3d2: 5d pop %ebp 3d3: c3 ret 3d4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; 3d8: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 3df: eb 90 jmp 371 <printint+0x21> 3e1: eb 0d jmp 3f0 <printf> 3e3: 90 nop 3e4: 90 nop 3e5: 90 nop 3e6: 90 nop 3e7: 90 nop 3e8: 90 nop 3e9: 90 nop 3ea: 90 nop 3eb: 90 nop 3ec: 90 nop 3ed: 90 nop 3ee: 90 nop 3ef: 90 nop 000003f0 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 3f0: 55 push %ebp 3f1: 89 e5 mov %esp,%ebp 3f3: 57 push %edi 3f4: 56 push %esi 3f5: 53 push %ebx 3f6: 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++){ 3f9: 8b 75 0c mov 0xc(%ebp),%esi 3fc: 0f b6 1e movzbl (%esi),%ebx 3ff: 84 db test %bl,%bl 401: 0f 84 b3 00 00 00 je 4ba <printf+0xca> ap = (uint*)(void*)&fmt + 1; 407: 8d 45 10 lea 0x10(%ebp),%eax 40a: 83 c6 01 add $0x1,%esi state = 0; 40d: 31 ff xor %edi,%edi ap = (uint*)(void*)&fmt + 1; 40f: 89 45 d4 mov %eax,-0x2c(%ebp) 412: eb 2f jmp 443 <printf+0x53> 414: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 418: 83 f8 25 cmp $0x25,%eax 41b: 0f 84 a7 00 00 00 je 4c8 <printf+0xd8> write(fd, &c, 1); 421: 8d 45 e2 lea -0x1e(%ebp),%eax 424: 83 ec 04 sub $0x4,%esp 427: 88 5d e2 mov %bl,-0x1e(%ebp) 42a: 6a 01 push $0x1 42c: 50 push %eax 42d: ff 75 08 pushl 0x8(%ebp) 430: e8 6d fe ff ff call 2a2 <write> 435: 83 c4 10 add $0x10,%esp 438: 83 c6 01 add $0x1,%esi for(i = 0; fmt[i]; i++){ 43b: 0f b6 5e ff movzbl -0x1(%esi),%ebx 43f: 84 db test %bl,%bl 441: 74 77 je 4ba <printf+0xca> if(state == 0){ 443: 85 ff test %edi,%edi c = fmt[i] & 0xff; 445: 0f be cb movsbl %bl,%ecx 448: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 44b: 74 cb je 418 <printf+0x28> state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 44d: 83 ff 25 cmp $0x25,%edi 450: 75 e6 jne 438 <printf+0x48> if(c == 'd'){ 452: 83 f8 64 cmp $0x64,%eax 455: 0f 84 05 01 00 00 je 560 <printf+0x170> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 45b: 81 e1 f7 00 00 00 and $0xf7,%ecx 461: 83 f9 70 cmp $0x70,%ecx 464: 74 72 je 4d8 <printf+0xe8> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 466: 83 f8 73 cmp $0x73,%eax 469: 0f 84 99 00 00 00 je 508 <printf+0x118> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 46f: 83 f8 63 cmp $0x63,%eax 472: 0f 84 08 01 00 00 je 580 <printf+0x190> putc(fd, *ap); ap++; } else if(c == '%'){ 478: 83 f8 25 cmp $0x25,%eax 47b: 0f 84 ef 00 00 00 je 570 <printf+0x180> write(fd, &c, 1); 481: 8d 45 e7 lea -0x19(%ebp),%eax 484: 83 ec 04 sub $0x4,%esp 487: c6 45 e7 25 movb $0x25,-0x19(%ebp) 48b: 6a 01 push $0x1 48d: 50 push %eax 48e: ff 75 08 pushl 0x8(%ebp) 491: e8 0c fe ff ff call 2a2 <write> 496: 83 c4 0c add $0xc,%esp 499: 8d 45 e6 lea -0x1a(%ebp),%eax 49c: 88 5d e6 mov %bl,-0x1a(%ebp) 49f: 6a 01 push $0x1 4a1: 50 push %eax 4a2: ff 75 08 pushl 0x8(%ebp) 4a5: 83 c6 01 add $0x1,%esi } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 4a8: 31 ff xor %edi,%edi write(fd, &c, 1); 4aa: e8 f3 fd ff ff call 2a2 <write> for(i = 0; fmt[i]; i++){ 4af: 0f b6 5e ff movzbl -0x1(%esi),%ebx write(fd, &c, 1); 4b3: 83 c4 10 add $0x10,%esp for(i = 0; fmt[i]; i++){ 4b6: 84 db test %bl,%bl 4b8: 75 89 jne 443 <printf+0x53> } } } 4ba: 8d 65 f4 lea -0xc(%ebp),%esp 4bd: 5b pop %ebx 4be: 5e pop %esi 4bf: 5f pop %edi 4c0: 5d pop %ebp 4c1: c3 ret 4c2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi state = '%'; 4c8: bf 25 00 00 00 mov $0x25,%edi 4cd: e9 66 ff ff ff jmp 438 <printf+0x48> 4d2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi printint(fd, *ap, 16, 0); 4d8: 83 ec 0c sub $0xc,%esp 4db: b9 10 00 00 00 mov $0x10,%ecx 4e0: 6a 00 push $0x0 4e2: 8b 7d d4 mov -0x2c(%ebp),%edi 4e5: 8b 45 08 mov 0x8(%ebp),%eax 4e8: 8b 17 mov (%edi),%edx 4ea: e8 61 fe ff ff call 350 <printint> ap++; 4ef: 89 f8 mov %edi,%eax 4f1: 83 c4 10 add $0x10,%esp state = 0; 4f4: 31 ff xor %edi,%edi ap++; 4f6: 83 c0 04 add $0x4,%eax 4f9: 89 45 d4 mov %eax,-0x2c(%ebp) 4fc: e9 37 ff ff ff jmp 438 <printf+0x48> 501: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi s = (char*)*ap; 508: 8b 45 d4 mov -0x2c(%ebp),%eax 50b: 8b 08 mov (%eax),%ecx ap++; 50d: 83 c0 04 add $0x4,%eax 510: 89 45 d4 mov %eax,-0x2c(%ebp) if(s == 0) 513: 85 c9 test %ecx,%ecx 515: 0f 84 8e 00 00 00 je 5a9 <printf+0x1b9> while(*s != 0){ 51b: 0f b6 01 movzbl (%ecx),%eax state = 0; 51e: 31 ff xor %edi,%edi s = (char*)*ap; 520: 89 cb mov %ecx,%ebx while(*s != 0){ 522: 84 c0 test %al,%al 524: 0f 84 0e ff ff ff je 438 <printf+0x48> 52a: 89 75 d0 mov %esi,-0x30(%ebp) 52d: 89 de mov %ebx,%esi 52f: 8b 5d 08 mov 0x8(%ebp),%ebx 532: 8d 7d e3 lea -0x1d(%ebp),%edi 535: 8d 76 00 lea 0x0(%esi),%esi write(fd, &c, 1); 538: 83 ec 04 sub $0x4,%esp s++; 53b: 83 c6 01 add $0x1,%esi 53e: 88 45 e3 mov %al,-0x1d(%ebp) write(fd, &c, 1); 541: 6a 01 push $0x1 543: 57 push %edi 544: 53 push %ebx 545: e8 58 fd ff ff call 2a2 <write> while(*s != 0){ 54a: 0f b6 06 movzbl (%esi),%eax 54d: 83 c4 10 add $0x10,%esp 550: 84 c0 test %al,%al 552: 75 e4 jne 538 <printf+0x148> 554: 8b 75 d0 mov -0x30(%ebp),%esi state = 0; 557: 31 ff xor %edi,%edi 559: e9 da fe ff ff jmp 438 <printf+0x48> 55e: 66 90 xchg %ax,%ax printint(fd, *ap, 10, 1); 560: 83 ec 0c sub $0xc,%esp 563: b9 0a 00 00 00 mov $0xa,%ecx 568: 6a 01 push $0x1 56a: e9 73 ff ff ff jmp 4e2 <printf+0xf2> 56f: 90 nop write(fd, &c, 1); 570: 83 ec 04 sub $0x4,%esp 573: 88 5d e5 mov %bl,-0x1b(%ebp) 576: 8d 45 e5 lea -0x1b(%ebp),%eax 579: 6a 01 push $0x1 57b: e9 21 ff ff ff jmp 4a1 <printf+0xb1> putc(fd, *ap); 580: 8b 7d d4 mov -0x2c(%ebp),%edi write(fd, &c, 1); 583: 83 ec 04 sub $0x4,%esp putc(fd, *ap); 586: 8b 07 mov (%edi),%eax write(fd, &c, 1); 588: 6a 01 push $0x1 ap++; 58a: 83 c7 04 add $0x4,%edi putc(fd, *ap); 58d: 88 45 e4 mov %al,-0x1c(%ebp) write(fd, &c, 1); 590: 8d 45 e4 lea -0x1c(%ebp),%eax 593: 50 push %eax 594: ff 75 08 pushl 0x8(%ebp) 597: e8 06 fd ff ff call 2a2 <write> ap++; 59c: 89 7d d4 mov %edi,-0x2c(%ebp) 59f: 83 c4 10 add $0x10,%esp state = 0; 5a2: 31 ff xor %edi,%edi 5a4: e9 8f fe ff ff jmp 438 <printf+0x48> s = "(null)"; 5a9: bb 48 07 00 00 mov $0x748,%ebx while(*s != 0){ 5ae: b8 28 00 00 00 mov $0x28,%eax 5b3: e9 72 ff ff ff jmp 52a <printf+0x13a> 5b8: 66 90 xchg %ax,%ax 5ba: 66 90 xchg %ax,%ax 5bc: 66 90 xchg %ax,%ax 5be: 66 90 xchg %ax,%ax 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 f4 09 00 00 mov 0x9f4,%eax { 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 bp = (Header*)ap - 1; 5ce: 8d 4b f8 lea -0x8(%ebx),%ecx 5d1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5d8: 39 c8 cmp %ecx,%eax 5da: 8b 10 mov (%eax),%edx 5dc: 73 32 jae 610 <free+0x50> 5de: 39 d1 cmp %edx,%ecx 5e0: 72 04 jb 5e6 <free+0x26> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5e2: 39 d0 cmp %edx,%eax 5e4: 72 32 jb 618 <free+0x58> break; if(bp + bp->s.size == p->s.ptr){ 5e6: 8b 73 fc mov -0x4(%ebx),%esi 5e9: 8d 3c f1 lea (%ecx,%esi,8),%edi 5ec: 39 fa cmp %edi,%edx 5ee: 74 30 je 620 <free+0x60> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 5f0: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 5f3: 8b 50 04 mov 0x4(%eax),%edx 5f6: 8d 34 d0 lea (%eax,%edx,8),%esi 5f9: 39 f1 cmp %esi,%ecx 5fb: 74 3a je 637 <free+0x77> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 5fd: 89 08 mov %ecx,(%eax) freep = p; 5ff: a3 f4 09 00 00 mov %eax,0x9f4 } 604: 5b pop %ebx 605: 5e pop %esi 606: 5f pop %edi 607: 5d pop %ebp 608: c3 ret 609: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 610: 39 d0 cmp %edx,%eax 612: 72 04 jb 618 <free+0x58> 614: 39 d1 cmp %edx,%ecx 616: 72 ce jb 5e6 <free+0x26> { 618: 89 d0 mov %edx,%eax 61a: eb bc jmp 5d8 <free+0x18> 61c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi bp->s.size += p->s.ptr->s.size; 620: 03 72 04 add 0x4(%edx),%esi 623: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 626: 8b 10 mov (%eax),%edx 628: 8b 12 mov (%edx),%edx 62a: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 62d: 8b 50 04 mov 0x4(%eax),%edx 630: 8d 34 d0 lea (%eax,%edx,8),%esi 633: 39 f1 cmp %esi,%ecx 635: 75 c6 jne 5fd <free+0x3d> p->s.size += bp->s.size; 637: 03 53 fc add -0x4(%ebx),%edx freep = p; 63a: a3 f4 09 00 00 mov %eax,0x9f4 p->s.size += bp->s.size; 63f: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 642: 8b 53 f8 mov -0x8(%ebx),%edx 645: 89 10 mov %edx,(%eax) } 647: 5b pop %ebx 648: 5e pop %esi 649: 5f pop %edi 64a: 5d pop %ebp 64b: c3 ret 64c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 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 f4 09 00 00 mov 0x9f4,%edx 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 9d 00 00 00 je 710 <malloc+0xc0> 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 6c jbe 6e8 <malloc+0x98> 67c: 81 ff 00 10 00 00 cmp $0x1000,%edi 682: bb 00 10 00 00 mov $0x1000,%ebx 687: 0f 43 df cmovae %edi,%ebx p = sbrk(nu * sizeof(Header)); 68a: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi 691: eb 0e jmp 6a1 <malloc+0x51> 693: 90 nop 694: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 698: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 69a: 8b 48 04 mov 0x4(%eax),%ecx 69d: 39 f9 cmp %edi,%ecx 69f: 73 47 jae 6e8 <malloc+0x98> p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 6a1: 39 05 f4 09 00 00 cmp %eax,0x9f4 6a7: 89 c2 mov %eax,%edx 6a9: 75 ed jne 698 <malloc+0x48> p = sbrk(nu * sizeof(Header)); 6ab: 83 ec 0c sub $0xc,%esp 6ae: 56 push %esi 6af: e8 56 fc ff ff call 30a <sbrk> if(p == (char*)-1) 6b4: 83 c4 10 add $0x10,%esp 6b7: 83 f8 ff cmp $0xffffffff,%eax 6ba: 74 1c je 6d8 <malloc+0x88> hp->s.size = nu; 6bc: 89 58 04 mov %ebx,0x4(%eax) free((void*)(hp + 1)); 6bf: 83 ec 0c sub $0xc,%esp 6c2: 83 c0 08 add $0x8,%eax 6c5: 50 push %eax 6c6: e8 f5 fe ff ff call 5c0 <free> return freep; 6cb: 8b 15 f4 09 00 00 mov 0x9f4,%edx if((p = morecore(nunits)) == 0) 6d1: 83 c4 10 add $0x10,%esp 6d4: 85 d2 test %edx,%edx 6d6: 75 c0 jne 698 <malloc+0x48> return 0; } } 6d8: 8d 65 f4 lea -0xc(%ebp),%esp return 0; 6db: 31 c0 xor %eax,%eax } 6dd: 5b pop %ebx 6de: 5e pop %esi 6df: 5f pop %edi 6e0: 5d pop %ebp 6e1: c3 ret 6e2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi if(p->s.size == nunits) 6e8: 39 cf cmp %ecx,%edi 6ea: 74 54 je 740 <malloc+0xf0> p->s.size -= nunits; 6ec: 29 f9 sub %edi,%ecx 6ee: 89 48 04 mov %ecx,0x4(%eax) p += p->s.size; 6f1: 8d 04 c8 lea (%eax,%ecx,8),%eax p->s.size = nunits; 6f4: 89 78 04 mov %edi,0x4(%eax) freep = prevp; 6f7: 89 15 f4 09 00 00 mov %edx,0x9f4 } 6fd: 8d 65 f4 lea -0xc(%ebp),%esp return (void*)(p + 1); 700: 83 c0 08 add $0x8,%eax } 703: 5b pop %ebx 704: 5e pop %esi 705: 5f pop %edi 706: 5d pop %ebp 707: c3 ret 708: 90 nop 709: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi base.s.ptr = freep = prevp = &base; 710: c7 05 f4 09 00 00 f8 movl $0x9f8,0x9f4 717: 09 00 00 71a: c7 05 f8 09 00 00 f8 movl $0x9f8,0x9f8 721: 09 00 00 base.s.size = 0; 724: b8 f8 09 00 00 mov $0x9f8,%eax 729: c7 05 fc 09 00 00 00 movl $0x0,0x9fc 730: 00 00 00 733: e9 44 ff ff ff jmp 67c <malloc+0x2c> 738: 90 nop 739: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi prevp->s.ptr = p->s.ptr; 740: 8b 08 mov (%eax),%ecx 742: 89 0a mov %ecx,(%edx) 744: eb b1 jmp 6f7 <malloc+0xa7>
; int adt_ListAdd(struct adt_List *list, void *item) ; 02.2003, 06.2005 aralbrec ; CALLER linkage for function pointers XLIB adt_ListAdd LIB adt_ListAdd_callee XREF ASMDISP_ADT_LISTADD_CALLEE .adt_ListAdd pop hl pop bc pop de push de push bc push hl jp adt_ListAdd_callee + ASMDISP_ADT_LISTADD_CALLEE
; A023569: Greatest prime divisor of prime(n) - 3. ; 2,2,2,5,7,2,5,13,7,17,19,5,11,5,7,29,2,17,7,19,5,43,47,7,5,13,53,11,31,2,67,17,73,37,11,5,41,17,11,89,47,19,97,7,13,11,7,113,23,59,17,31,127,13,19,67,137,139,7,29,19,11,31,157,41,167,43,173,7,89,13,37,47,19,193,197,199,29,13,19,107,43,109,11,223,227,229,23,29,17,11,61,31,5,23,37,13,269,17,277 seq $0,215848 ; Primes > 3. sub $0,3 lpb $0 sub $0,1 seq $0,117818 ; a(n) = n if n is 1 or a prime, otherwise a(n) = n divided by the least prime factor of n (A032742(n)). lpe
#pragma once #include "base/Math.hpp" #include "gpu/GLContext.hpp" #include <string> #define COMPUTE_CLOTH_MODULE namespace FW { // Simple helper to manage multiple shaders more easily struct Shader { Shader() {}; Shader(const std::string& name, const bool compute, GLContext *ctx); ~Shader(); GLuint handle; GLContext::Program *program; bool initialized = false; }; } // namespace FW
.model small .data num1 db 0,1,2,3,4,5,6,7,8,9,'$' decimales_1 db 0,1,2,3,4,5,6,7,8,9,'$' num2 db 0,1,2,3,4,5,6,7,8,9,'$' decimales_2 db 0,1,2,3,4,5,6,7,8,9,'$' ;operandos para conjugar la parte decimal de cada operando num_1_mult db 0,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,'$' ;con sus partes decimales num_2_mult db 0,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,'$' over_flow_res db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ;los resultados de las multiplicaciones de 9 digitos por 9 digitos num_res_mult db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,'$' ;pueden tener hasta 39 digitos en el resultado, estos digitos extra ;son guardados en la varibale over_flow_res hay_overFlow db 00h ;bandera para que el en el resultado considere los digitos en over_flow_num_res hay_acarreo db 00h aux db 00h .stack .code begin proc far mov ax,@data mov ds,ax CALL MULTIPLICA ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;IMPRIMIR RESULTADO LEA DX,over_flow_res MOV AH,09 INT 21H XOR AX,AX INT 16H begin endp MULTIPLICA PROC NEAR ;MULTIPLICAR PARTES ENTERAS SIN IMPORTAR ACARREOS MOV SI,12h ;indice del multiplicador MOV DI,12h ;indice del multiplicando MOV BX,00h ;representa las posiciones de la suma dentro de la multiplicacion siguiente_multiplicador_e: siguiente_multiplicando_e: MOV AL,num_1_mult[SI] ;movemos el multiplicador a Al MOV DL,num_2_mult[DI] ;movemos el multiplicando a Dl MUL Dl ; AL*Dl resultado en Ax AAM ;desempacamos el resultado de la multiplicacion previa SUB DI,BX ;decrementamos Di por la posicion de los multiplicandos ADD num_res_mult[DI],Al ;agregamos la parte baja a la posicion de DI en num_res ADD num_res_mult[DI-1],Ah ;agregamos la parte alta a la siguiente posicion de DI en num_res ADD DI,BX ;restauramos Di para obtener la posicion real de el siguiente multiplicando DEC DI ;decrementamos el indice del multiplicando CMP DI,01H JAE siguiente_multiplicando_e ;incrementamos contador de posiciones de multiplicandos INC BX ;incrementamos el desplazamiento de la suma MOV DI,12h ;volvemos al primer indice de los multiplicandos DEC SI ;decrementamos el indice del multiplicador CMP SI,01H JAE siguiente_multiplicador_e MOV hay_overFlow,01h XOR AX,AX INT 16H acarreo_del_Acarreo: MOV hay_acarreo,00h ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;AJUSTAR LOS ACARREOS ENTEROS MOV SI,25h ;los resultados de multiplicaciones 9 enteros*9 enteros pueden llegar a tener hasta 18 digitos JMP siguiente_Acarreo_entero ; AcarreoEntero: MOV hay_acarreo,01h MOV Al,over_flow_res[SI] AAM ADD over_flow_res[SI-1],Ah MOV over_flow_res[SI],Al DEC SI siguiente_Acarreo_entero: CMP over_flow_res[SI],0Ah JAE AcarreoEntero DEC SI JNS siguiente_Acarreo_entero ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; CMP hay_acarreo,01h JNE no_mas_acarreo_mul JMP acarreo_del_Acarreo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; no_mas_acarreo_mul: XOR AX,AX INT 16H ;;AJUSTAR PARA IMPRESION ;;ajustar la parte entera MOV SI,26h JMP inicia_ajuste salta_fin: DEC SI JMP inicia_ajuste inicia_ajuste: MOV AL,over_flow_res[SI] CMP AL,24h JE salta_fin ADD AL,30h MOV over_flow_res[SI],AL DEC SI JNS inicia_ajuste ;;COPIAR A OTRA VARIABLE Y AGREGAR EL PUNTO DECIMAL CONTANDO LA SUMA DE LOS ;; NUMEROS DECIMALES DESPUES DEL PUNTO RET MULTIPLICA ENDP end begin
#ifndef STAN_MATH_REV_FUN_HPP #define STAN_MATH_REV_FUN_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat.hpp> #include <stan/math/rev/fun/LDLT_alloc.hpp> #include <stan/math/rev/fun/LDLT_factor.hpp> #include <stan/math/rev/fun/Phi.hpp> #include <stan/math/rev/fun/Phi_approx.hpp> #include <stan/math/rev/fun/abs.hpp> #include <stan/math/rev/fun/acos.hpp> #include <stan/math/rev/fun/acosh.hpp> #include <stan/math/rev/fun/as_bool.hpp> #include <stan/math/rev/fun/asin.hpp> #include <stan/math/rev/fun/asinh.hpp> #include <stan/math/rev/fun/atan.hpp> #include <stan/math/rev/fun/atan2.hpp> #include <stan/math/rev/fun/atanh.hpp> #include <stan/math/rev/fun/bessel_first_kind.hpp> #include <stan/math/rev/fun/bessel_second_kind.hpp> #include <stan/math/rev/fun/beta.hpp> #include <stan/math/rev/fun/binary_log_loss.hpp> #include <stan/math/rev/fun/calculate_chain.hpp> #include <stan/math/rev/fun/cbrt.hpp> #include <stan/math/rev/fun/ceil.hpp> #include <stan/math/rev/fun/cholesky_decompose.hpp> #include <stan/math/rev/fun/columns_dot_product.hpp> #include <stan/math/rev/fun/columns_dot_self.hpp> #include <stan/math/rev/fun/cos.hpp> #include <stan/math/rev/fun/cosh.hpp> #include <stan/math/rev/fun/cov_exp_quad.hpp> #include <stan/math/rev/fun/crossprod.hpp> #include <stan/math/rev/fun/determinant.hpp> #include <stan/math/rev/fun/digamma.hpp> #include <stan/math/rev/fun/divide.hpp> #include <stan/math/rev/fun/dot_product.hpp> #include <stan/math/rev/fun/dot_self.hpp> #include <stan/math/rev/fun/erf.hpp> #include <stan/math/rev/fun/erfc.hpp> #include <stan/math/rev/fun/exp.hpp> #include <stan/math/rev/fun/exp2.hpp> #include <stan/math/rev/fun/expm1.hpp> #include <stan/math/rev/fun/fabs.hpp> #include <stan/math/rev/fun/falling_factorial.hpp> #include <stan/math/rev/fun/fdim.hpp> #include <stan/math/rev/fun/floor.hpp> #include <stan/math/rev/fun/fma.hpp> #include <stan/math/rev/fun/fmax.hpp> #include <stan/math/rev/fun/fmin.hpp> #include <stan/math/rev/fun/fmod.hpp> #include <stan/math/rev/fun/gamma_p.hpp> #include <stan/math/rev/fun/gamma_q.hpp> #include <stan/math/rev/fun/gp_periodic_cov.hpp> #include <stan/math/rev/fun/grad.hpp> #include <stan/math/rev/fun/grad_inc_beta.hpp> #include <stan/math/rev/fun/hypot.hpp> #include <stan/math/rev/fun/if_else.hpp> #include <stan/math/rev/fun/inc_beta.hpp> #include <stan/math/rev/fun/initialize_variable.hpp> #include <stan/math/rev/fun/inv.hpp> #include <stan/math/rev/fun/inv_Phi.hpp> #include <stan/math/rev/fun/inv_cloglog.hpp> #include <stan/math/rev/fun/inv_logit.hpp> #include <stan/math/rev/fun/inv_sqrt.hpp> #include <stan/math/rev/fun/inv_square.hpp> #include <stan/math/rev/fun/inverse.hpp> #include <stan/math/rev/fun/is_inf.hpp> #include <stan/math/rev/fun/is_nan.hpp> #include <stan/math/rev/fun/is_uninitialized.hpp> #include <stan/math/rev/fun/lbeta.hpp> #include <stan/math/rev/fun/ldexp.hpp> #include <stan/math/rev/fun/lgamma.hpp> #include <stan/math/rev/fun/lmgamma.hpp> #include <stan/math/rev/fun/log.hpp> #include <stan/math/rev/fun/log10.hpp> #include <stan/math/rev/fun/log1m.hpp> #include <stan/math/rev/fun/log1m_exp.hpp> #include <stan/math/rev/fun/log1m_inv_logit.hpp> #include <stan/math/rev/fun/log1p.hpp> #include <stan/math/rev/fun/log1p_exp.hpp> #include <stan/math/rev/fun/log2.hpp> #include <stan/math/rev/fun/log_determinant.hpp> #include <stan/math/rev/fun/log_determinant_ldlt.hpp> #include <stan/math/rev/fun/log_determinant_spd.hpp> #include <stan/math/rev/fun/log_diff_exp.hpp> #include <stan/math/rev/fun/log_falling_factorial.hpp> #include <stan/math/rev/fun/log_inv_logit.hpp> #include <stan/math/rev/fun/log_inv_logit_diff.hpp> #include <stan/math/rev/fun/log_mix.hpp> #include <stan/math/rev/fun/log_rising_factorial.hpp> #include <stan/math/rev/fun/log_softmax.hpp> #include <stan/math/rev/fun/log_sum_exp.hpp> #include <stan/math/rev/fun/logit.hpp> #include <stan/math/rev/fun/matrix_exp_multiply.hpp> #include <stan/math/rev/fun/matrix_power.hpp> #include <stan/math/rev/fun/mdivide_left.hpp> #include <stan/math/rev/fun/mdivide_left_ldlt.hpp> #include <stan/math/rev/fun/mdivide_left_spd.hpp> #include <stan/math/rev/fun/mdivide_left_tri.hpp> #include <stan/math/rev/fun/modified_bessel_first_kind.hpp> #include <stan/math/rev/fun/modified_bessel_second_kind.hpp> #include <stan/math/rev/fun/multiply.hpp> #include <stan/math/rev/fun/multiply_log.hpp> #include <stan/math/rev/fun/multiply_lower_tri_self_transpose.hpp> #include <stan/math/rev/fun/ordered_constrain.hpp> #include <stan/math/rev/fun/owens_t.hpp> #include <stan/math/rev/fun/positive_ordered_constrain.hpp> #include <stan/math/rev/fun/pow.hpp> #include <stan/math/rev/fun/primitive_value.hpp> #include <stan/math/rev/fun/quad_form.hpp> #include <stan/math/rev/fun/quad_form_sym.hpp> #include <stan/math/rev/fun/rising_factorial.hpp> #include <stan/math/rev/fun/round.hpp> #include <stan/math/rev/fun/rows_dot_product.hpp> #include <stan/math/rev/fun/sd.hpp> #include <stan/math/rev/fun/simplex_constrain.hpp> #include <stan/math/rev/fun/sin.hpp> #include <stan/math/rev/fun/sinh.hpp> #include <stan/math/rev/fun/softmax.hpp> #include <stan/math/rev/fun/sqrt.hpp> #include <stan/math/rev/fun/square.hpp> #include <stan/math/rev/fun/squared_distance.hpp> #include <stan/math/rev/fun/stan_print.hpp> #include <stan/math/rev/fun/step.hpp> #include <stan/math/rev/fun/sum.hpp> #include <stan/math/rev/fun/tan.hpp> #include <stan/math/rev/fun/tanh.hpp> #include <stan/math/rev/fun/tcrossprod.hpp> #include <stan/math/rev/fun/tgamma.hpp> #include <stan/math/rev/fun/to_var.hpp> #include <stan/math/rev/fun/trace_gen_inv_quad_form_ldlt.hpp> #include <stan/math/rev/fun/trace_gen_quad_form.hpp> #include <stan/math/rev/fun/trace_inv_quad_form_ldlt.hpp> #include <stan/math/rev/fun/trace_quad_form.hpp> #include <stan/math/rev/fun/trigamma.hpp> #include <stan/math/rev/fun/trunc.hpp> #include <stan/math/rev/fun/typedefs.hpp> #include <stan/math/rev/fun/value_of.hpp> #include <stan/math/rev/fun/value_of_rec.hpp> #include <stan/math/rev/fun/variance.hpp> #endif
#include <PointSpec.h> #include <Asserter.h> #include <Point.h> #include <Util.h> PointSpec::PointSpec() { } void PointSpec::run() { randomizeSpec(); distanceOnXToSpec(); distanceOnYToSpec(); distanceOnZToSpec(); distance2DToSpec(); distance3DSpec(); } void PointSpec::randomizeSpec() { Point p; p.randomize(1); Asserter::assertEqual(true, (p.x == 0), "randomizeSpec: should randomize X dim."); Asserter::assertEqual(true, (p.y == 0), "randomizeSpec: should randomize Y dim."); Asserter::assertEqual(true, (p.z == 0), "randomizeSpec: should randomize Z dim."); } void PointSpec::distanceOnXToSpec() { unsigned char distance; Point p0 = Point(0, 0, 0); Point p1 = Point(10, 20, 30); distance = p0.distanceOnXTo(&p1); Asserter::assertEqual(distance, 10, "distanceOnXToSpec: should get right distance when the second point is ahead."); distance = p1.distanceOnXTo(&p0); Asserter::assertEqual(distance, 10, "distanceOnXToSpec: should get right distance when the second point is behind."); } void PointSpec::distanceOnYToSpec() { unsigned char distance; Point p0 = Point(0, 0, 0); Point p1 = Point(10, 20, 30); distance = p0.distanceOnYTo(&p1); Asserter::assertEqual(distance, 20, "distanceOnYToSpec: should get right distance when the second point is ahead."); distance = p1.distanceOnYTo(&p0); Asserter::assertEqual(distance, 20, "distanceOnYToSpec: should get right distance when the second point is behind."); } void PointSpec::distanceOnZToSpec() { unsigned char distance; Point p0 = Point(0, 0, 0); Point p1 = Point(10, 20, 30); distance = p0.distanceOnZTo(&p1); Asserter::assertEqual(distance, 30, "distanceOnZToSpec: should get right distance when the second point is ahead."); distance = p1.distanceOnZTo(&p0); Asserter::assertEqual(distance, 30, "distanceOnZToSpec: should get right distance when the second point is behind."); } void PointSpec::distance2DToSpec() { float distance; Point p0 = Point(0, 0, 0); Point p1 = Point(3, 4, 0); distance = p0.distance2DTo(&p1); Asserter::assertEqual(distance, 5, "distance2DToSpec: should get right 2D distance when the second point is ahead."); distance = p1.distance2DTo(&p0); Asserter::assertEqual(distance, 5, "distance2DToSpec: should get right 2D distance when the second point is behind."); } void PointSpec::distance3DSpec() { float distance; Point p0 = Point(0, 0, 0); Point p1 = Point(3, 4, 5); distance = p0.distance3DTo(&p1); Asserter::assertEqual(distance, 7, "distance2DToSpec: should get right 3D distance when the second point is ahead."); distance = p1.distance3DTo(&p0); Asserter::assertEqual(distance, 7, "distance2DToSpec: should get right 3D distance when the second point is behind."); }
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1990 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: stringCompare.asm AUTHOR: Gene Anderson, Dec 6, 1990 ROUTINES: Name Description ---- ----------- LocalGetLanguage Get current language for comparisons LocalStringCompare Compare two strings LocalStringCompareNoCase Compare two strings, case-insensitive DoStringCompare Do table-drive string compare LocalStringCompareDosToGeos Compare two strings, converting characters from DOS code page to GEOS character set TranslateSpecialCharacters Translate either string if it has a double-s character in it. TranslateSpecialCharactersESDI If the German double-s character is in the string, copy the whole string to the stack, with the character replaced with two ss's. RemoveStringsFromStack Remove the translated strings from the stack. TranslateAndCopyToStackESDI Copy the string at es:di to the stack REVISION HISTORY: Name Date Description ---- ---- ----------- Gene 12/ 6/90 Initial revision DESCRIPTION: Routines for dealing with string comparison. $Id: stringSort.asm,v 1.1 97/04/05 01:17:11 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ include Internal/prodFeatures.def if DBCS_PCGEOS StringMod segment resource else StringCmpMod segment resource endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LocalGetLanguage %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the current language for comparison CALLED BY: GLOBAL PASS: none RETURN: ax - StandardLanguage DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 9/20/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LOCALGETLANGUAGE proc far .enter mov al, cs:curLanguage clr ah ;ax <- StandardLanguage .leave ret LOCALGETLANGUAGE endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LocalCmpStrings %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Do dictionary order comparison of two strings CALLED BY: DR_LOCAL_COMPARE_STRING PASS: ds:si - ptr to string1 es:di - ptr to string2 cx - maximum # of chars to compare (0 for NULL terminated) RETURN: flags - same as in cmps instruction: if string1 = string2 : if (z) if string1 != string2 : if !(z) if string1 > string2 : if !(c|z) if string1 < string2 : if (c) if string1 >= string2 : if !(c) if string1 <= string2 : if (c|z) DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: This routine should be called when lexigraphical order is required (ie. if one string should come before, at the same point, or after another string). REVISION HISTORY: Name Date Description ---- ---- ----------- eca 10/16/89 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if FULL_EXECUTE_IN_PLACE CopyStackCodeXIP segment resource LocalCmpStrings proc far mov ss:[TPD_callVector].segment, cx DBCS < shl ss:[TPD_callVector].segment, 1 > mov ss:[TPD_dataBX], handle LocalCmpStringsReal mov ss:[TPD_dataAX], offset LocalCmpStringsReal GOTO SysCallMovableXIPWithDSSIAndESDIBlock LocalCmpStrings endp CopyStackCodeXIP ends else LocalCmpStrings proc far FALL_THRU LocalCmpStringsReal LocalCmpStrings endp endif LocalCmpStringsReal proc far SBCS < uses bx > DBCS < uses bp > .enter if SORT_DOUBLE_S_CORRECTLY and not DBCS_PCGEOS push ds, es, si, di, dx call TranslateSpecialCharacters endif ; ; For SBCS and DBCS, we compare for dictionary order by ; comparing first ignoring case and accent. ; ; For Pizza, we compare for SJIS order. ; SBCS < mov bx, offset Lexical1stOrderTable > if DBCS_PCGEOS if SJIS_SORTING mov bp, offset CmpCharsSJISInt else mov bp, offset CmpCharsNoCaseInt endif endif call DoStringCompare if not SJIS_SORTING jne done SBCS < mov bx, offset LexicalOrderTable > DBCS < mov bp, offset CmpCharsInt > call DoStringCompare done: endif if SORT_DOUBLE_S_CORRECTLY and not DBCS_PCGEOS call RemoveStringsFromStack pop ds, es, si, di, dx endif .leave ret LocalCmpStringsReal endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LocalCmpStringsNoCase %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Do dictionary order comparison of two strings CALLED BY: DR_LOCAL_COMPARE_STRING_NO_CASE PASS: -- see LocalCmpStrings -- RETURN: -- see LocalCmpStrings -- DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 12/ 7/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if FULL_EXECUTE_IN_PLACE CopyStackCodeXIP segment resource LocalCmpStringsNoCase proc far mov ss:[TPD_callVector].segment, cx DBCS < shl ss:[TPD_callVector].segment, 1 > mov ss:[TPD_dataBX], handle LocalCmpStringsNoCaseReal mov ss:[TPD_dataAX], offset LocalCmpStringsNoCaseReal GOTO SysCallMovableXIPWithDSSIAndESDIBlock LocalCmpStringsNoCase endp CopyStackCodeXIP ends else LocalCmpStringsNoCase proc far FALL_THRU LocalCmpStringsNoCaseReal LocalCmpStringsNoCase endp endif LocalCmpStringsNoCaseReal proc far SBCS < uses bx > DBCS < uses bp > .enter if SORT_DOUBLE_S_CORRECTLY and not DBCS_PCGEOS push ds, es, si, di, dx call TranslateSpecialCharacters endif ; ; For SBCS and DBCS, we compare ignoring case and accent. ; ; For Pizza, we compare for SJIS order, but ingoring case ; and fullwidth vs. halfwidth. ; SBCS < mov bx, offset Lexical1stOrderTable > if DBCS_PCGEOS if SJIS_SORTING mov bp, offset CmpCharsSJISNoWidthInt else mov bp, offset CmpCharsNoCaseInt endif endif call DoStringCompare if SORT_DOUBLE_S_CORRECTLY and not DBCS_PCGEOS call RemoveStringsFromStack pop ds, es, si, di, dx endif .leave ret LocalCmpStringsNoCaseReal endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LocalCmpChars %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Do dictionary order comparison of two chars PASS: ax - source char cx - dest char RETURN: flags - same as in cmps instruction: if source = dest : if (z) if source != dest : if !(z) if source > dest : if !(c|z) if source < dest : if (c) if source >= dest : if !(c) if source <= dest : if (c|z) DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: DON'T USE THIS unless you are sure you know what you are doing! -- some languages have multi-character sequences that need to be sorted specially (eg. "ch" sorts after "c" in Spanish), so comparing a character at a time will yield incorrect results. REVISION HISTORY: Name Date Description ---- ---- ----------- eca 10/16/89 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LocalCmpChars proc far SBCS < uses bx > DBCS < uses ax, bx, dx > .enter if DBCS_PCGEOS mov dx, cx ;dx <- dest char xchg ax, dx ;ax <- dest char if SJIS_SORTING call CmpCharsSJISInt else call CmpCharsNoCaseInt jne done call CmpCharsInt done: endif else EC < tst ah > EC < ERROR_NZ CANNOT_USE_DOUBLE_BYTE_CHARS_IN_THIS_VERSION > EC < tst ch > EC < ERROR_NZ CANNOT_USE_DOUBLE_BYTE_CHARS_IN_THIS_VERSION > mov bx, offset Lexical1stOrderTable call DoCharCompare jne done mov bx, offset LexicalOrderTable call DoCharCompare done: endif .leave ret LocalCmpChars endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LocalCmpCharsNoCase %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Do dictionary order comparison of two chars CALLED BY: GLOBAL PASS: -- see LocalCmpChars -- RETURN: -- see LocalCmpChars -- DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 12/ 7/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LocalCmpCharsNoCase proc far SBCS < uses bx > DBCS < uses ax, bx, dx > .enter if DBCS_PCGEOS mov dx, cx ;dx <- dest char xchg ax, dx ;ax <- dest char if SJIS_SORTING call CmpCharsSJISNoWidthInt else call CmpCharsNoCaseInt endif else EC < tst ah > EC < ERROR_NZ CANNOT_USE_DOUBLE_BYTE_CHARS_IN_THIS_VERSION > EC < tst ch > EC < ERROR_NZ CANNOT_USE_DOUBLE_BYTE_CHARS_IN_THIS_VERSION > mov bx, offset Lexical1stOrderTable call DoCharCompare endif .leave ret LocalCmpCharsNoCase endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DoCharCompare %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Do table-driven string comparison CALLED BY: LocalCompareChar(), LocalCompareCharNoCase() PASS: cs:bx - ptr to lexical table to use ax - char #1 cx - char #2 RETURN: see LocalCmpChars DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 12/ 7/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if not DBCS_PCGEOS DoCharCompare proc near uses ax .enter cs:xlat ;Map source char mov ah, al ;Save in AH mov al, cl cs:xlat ;Map dest char cmp ah, al ;Compare chars .leave ret DoCharCompare endp endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DoStringCompare %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Do table-driven string comparison CALLED BY: LocalCompareString(), LocalCompareStringNoCase() PASS: SBCS: cs:bx - ptr to lexical table to use DBCS: cs:bp - ptr to character comparison routine ds:si - ptr to string #1 es:di - ptr to string #2 cx - maximum # of chars to compare (0 for NULL-terminated) RETURN: see LocalCompareString DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 12/ 7/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DoStringCompare proc near SBCS < uses ax, cx, si, di > DBCS < uses ax, bx, dx, cx, si, di > .enter mov ax, 0xffff DCS_loop: SBCS < or al, ah ;end of both strings? > DBCS < or ax, dx ;end of both strings? > jz done LocalGetChar ax, dssi ;ax <- source char if not DBCS_PCGEOS cs:xlat ;convert source char endif SBCS < mov ah, al ;dx <- source char > DBCS < mov_tr dx, ax ;dx <- source char > LocalGetChar ax, esdi ;ax <- dest char if not DBCS_PCGEOS cs:xlat ;convert dest char endif SBCS < cmp ah, al ;compare string bytes > DBCS < call bp ;compare characters > loope DCS_loop ;loop while equal done: .leave ret DoStringCompare endp if not DBCS_PCGEOS COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LocalCmpStringsDosToGeos %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Do dictionary order comparison of two strings, converting characters from DOS code page to GEOS character set before comparison CALLED BY: GLOBAL PASS: ds:si - ptr to source string es:di - ptr to dest string cx - maximum # of chars to compare (0 for NULL terminated) ax - LocalCmpStringsDosToGeosFlags LCSDTG_NO_CONVERT_STRING_1 to not convert string 1 (ds:si) LCSDTG_NO_CONVERT_STRING_2 to not convert string 2 (es:di) bx - default character for DOS-to-GEOS conversion RETURN: flags - same as in cmps instruction: if source = dest : if (z) if source != dest : if !(z) if source > dest : if !(c|z) if source < dest : if (c) if source >= dest : if !(c) if source <= dest : if (c|z) DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 10/16/89 Initial version brianc 1/7/91 modified for DOS-to-GEOS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if FULL_EXECUTE_IN_PLACE CopyStackCodeXIP segment resource LocalCmpStringsDosToGeos proc far mov ss:[TPD_callVector].segment, cx DBCS < shl ss:[TPD_callVector].segment, 1 > mov ss:[TPD_dataBX], handle LocalCmpStringsDosToGeosReal mov ss:[TPD_dataAX], offset LocalCmpStringsDosToGeosReal GOTO SysCallMovableXIPWithDSSIAndESDIBlock LocalCmpStringsDosToGeos endp CopyStackCodeXIP ends else LocalCmpStringsDosToGeos proc far FALL_THRU LocalCmpStringsDosToGeosReal LocalCmpStringsDosToGeos endp endif LocalCmpStringsDosToGeosReal proc far uses ax, bx, dx, es, bp .enter if SORT_DOUBLE_S_CORRECTLY and not DBCS_PCGEOS push ds, es, si, di, dx call TranslateSpecialCharacters push dx endif ; for now we only deal with bytes, not words EC < tst bh > EC < ERROR_NZ CANNOT_USE_DOUBLE_BYTE_CHARS_IN_THIS_VERSION > mov bh, bl ;bh <- default char mov bl, al mov bp, bx ;bp <- flags and default char mov dx, es call GetCurrentCodePage ; bx = handle, es = segment push bx ; save handle mov bx, offset Lexical1stOrderTable call DoStringCompareDOSToGEOS jne done mov bx, offset LexicalOrderTable call DoStringCompareDOSToGEOS done: pop bx ; unlock code page call MemUnlock ; (preserves flags) if SORT_DOUBLE_S_CORRECTLY and not DBCS_PCGEOS pop dx call RemoveStringsFromStack pop ds, es, si, di, dx endif .leave ret LocalCmpStringsDosToGeosReal endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DoStringCompareDOSToGEOS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Do table-driven string comparison CALLED BY: LocalCompareStringDOSToGEOS() PASS: cs:bx - ptr to lexical table to use ds:si - ptr to string #1 dx:di - ptr to string #2 es - segment of code page buffer cx - maximum # of chars to compare (0 for NULL-terminated) bp high - default character bp low - LocalCmpStringsDosToGeosFlags LCSDTG_NO_CONVERT_STRING_1 to not convert string 1 (ds:si) LCSDTG_NO_CONVERT_STRING_2 to not convert string 2 (es:di) RETURN: see LocalCompareStringDOSToGEOS DESTROYED: ax PSEUDO CODE/STRATEGY: Either: (1) neither character is a ligature ==> do compare (2) both characters are ligatures ==> do compare (3) source is ligature ==> expand, get matching char from dest (4) dest is ligature ==> expand, get matching char from source KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 12/ 7/90 Initial version brianc 1/7/91 modified for DOS-to-GEOS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DoStringCompareDOSToGEOS proc near uses cx, si, di .enter mov ax, 0xffff DCS_loop: or al, ah ;end of both strings? jz done lodsb ;al <- byte of source test bp, mask LCSDTGF_NO_CONVERT_STRING_1 jnz 10$ call ConvertCharDOSToGEOS ;convert to GEOS char set 10$: cs:xlat ;convert source char mov ah, al push es ;save code page segment mov es, dx ;es:di = string 2 mov al, es:[di] ;al <- byte of dest pop es ;restore code page segment test bp, mask LCSDTG_NO_CONVERT_STRING_2 jnz 20$ call ConvertCharDOSToGEOS ;convert to GEOS char set 20$: inc di cs:xlat ;convert dest char cmp ah, al ;compare string bytes loope DCS_loop ;loop while equal done: .leave ret DoStringCompareDOSToGEOS endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ConvertCharDOSToGEOS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: convert single character from DOS code page to GEOS character set CALLED BY: DoStringCompareDOSToGEOS() PASS: al - character to convert bp high - default character es - segment of code page conversion table RETURN: al - converted character DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- brianc 1/7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ConvertCharDOSToGEOS proc near uses bx, cx .enter mov bx, offset codePageUS ; offset to code page table mov cx, bp ; ch = default char tst al jns done ; low ASCII, no conversion sub al, MIN_MAP_CHAR ; convert to index es:xlat ; al = converted character tst al ; character mappable? jnz done ; yes, return it mov al, ch ; else, return default char done: .leave ret ConvertCharDOSToGEOS endp endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LocalCmpStringsNoSpace %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Compare two strings, ignoring whitespace and punctuation CALLED BY: GLOBAL PASS: -- see LocalCompareString -- RETURN: -- see LocalCompareString -- DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 9/20/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if FULL_EXECUTE_IN_PLACE CopyStackCodeXIP segment resource LocalCmpStringsNoSpace proc far mov ss:[TPD_callVector].segment, cx DBCS < shl ss:[TPD_callVector].segment, 1 > mov ss:[TPD_dataBX], handle LocalCmpStringsNoSpaceReal mov ss:[TPD_dataAX], offset LocalCmpStringsNoSpaceReal GOTO SysCallMovableXIPWithDSSIAndESDIBlock LocalCmpStringsNoSpace endp CopyStackCodeXIP ends else LocalCmpStringsNoSpace proc far FALL_THRU LocalCmpStringsNoSpaceReal LocalCmpStringsNoSpace endp endif LocalCmpStringsNoSpaceReal proc far uses bx .enter if SORT_DOUBLE_S_CORRECTLY and not DBCS_PCGEOS push ds, es, si, di, dx call TranslateSpecialCharacters endif SBCS < mov bx, offset Lexical1stOrderTable > if DBCS_PCGEOS if SJIS_SORTING mov bx, offset CmpCharsSJISInt else mov bx, offset CmpCharsNoCaseInt endif endif call DoStringCompareNoSpace if not SJIS_SORTING jne done SBCS < mov bx, offset LexicalOrderTable > DBCS < mov bx, offset CmpCharsInt > call DoStringCompareNoSpace done: endif if SORT_DOUBLE_S_CORRECTLY and not DBCS_PCGEOS call RemoveStringsFromStack pop ds, es, si, di, dx endif .leave ret LocalCmpStringsNoSpaceReal endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LocalCmpStringsNoSpaceCase %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Compare two strings, ignoring whitespace, punctuation and case CALLED BY: GLOBAL PASS: -- see LocalCompareString -- RETURN: -- see LocalCompareString -- DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 9/20/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if FULL_EXECUTE_IN_PLACE CopyStackCodeXIP segment resource LocalCmpStringsNoSpaceCase proc far mov ss:[TPD_callVector].segment, cx DBCS < shl ss:[TPD_callVector].segment, 1 > mov ss:[TPD_dataBX], handle LocalCmpStringsNoSpaceCaseReal mov ss:[TPD_dataAX], offset LocalCmpStringsNoSpaceCaseReal GOTO SysCallMovableXIPWithDSSIAndESDIBlock LocalCmpStringsNoSpaceCase endp CopyStackCodeXIP ends else LocalCmpStringsNoSpaceCase proc far FALL_THRU LocalCmpStringsNoSpaceCaseReal LocalCmpStringsNoSpaceCase endp endif LocalCmpStringsNoSpaceCaseReal proc far uses bx .enter if SORT_DOUBLE_S_CORRECTLY and not DBCS_PCGEOS push ds, es, si, di, dx call TranslateSpecialCharacters endif SBCS < mov bx, offset Lexical1stOrderTable > if DBCS_PCGEOS if SJIS_SORTING mov bx, offset CmpCharsSJISNoWidthInt else mov bx, offset CmpCharsNoCaseInt endif endif call DoStringCompareNoSpace if SORT_DOUBLE_S_CORRECTLY and not DBCS_PCGEOS call RemoveStringsFromStack pop ds, es, si, di, dx endif .leave ret LocalCmpStringsNoSpaceCaseReal endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DoStringCompareNoSpace %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Do table-driven string comparison ignoring spaces & punctuation CALLED BY: LocalCompareStringNoSpace(), LocalCompareStringNoSpaceCase() PASS: SBCS: cs:bx - ptr to lexical table to use DBCS: cs:bx - ptr to routine to compare chars ds:si - ptr to string #1 es:di - ptr to string #2 cx - maximum # of chars to compare (0 for NULL-terminated) RETURN: see LocalCompareString DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: NOTE: any space or punctuation that is ignored is still included in the character counts. For example, if you pass cx - 2 characters ds:si - "o'leary" es:di - "o'" it will compare the "o" in each string, and ignore the "'" in each string, and return that the strings are equal. REVISION HISTORY: Name Date Description ---- ---- ----------- eca 12/ 7/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DoStringCompareNoSpace proc near uses ax, dx, cx, si, di, bp .enter mov ax, 0xffff DCS_loop: SBCS < or dl, al ;end of both strings? > DBCS < or ax, dx ;end of both strings? > jz done clr bp ;bp <- ignored char count getNextSource: LocalGetChar ax, dssi ;ax <- character of source SBCS < clr ah > call LocalIsSpace jnz nextSourceChar ;branch if a space call LocalIsPunctuation jnz nextSourceChar ;branch if punctuation SBCS < cs:xlat ;convert source char > SBCS < mov dl, al > DBCS < mov dx, ax > getNextDest: LocalGetChar ax, esdi ;ax <- character of dest SBCS < clr ah > call LocalIsSpace jnz nextDestChar ;branch if a space call LocalIsPunctuation jnz nextDestChar ;branch if punctuation SBCS < cs:xlat ;convert dest char > SBCS < cmp dl, al ;compare string bytes > DBCS < push bx > DBCS < call bx ;compare characters > DBCS < pop bx > loope DCS_loop ;loop while equal done: .leave ret ; ; bp is the number of characters we've ignored since the last ; compare -- sort of. ; (1) For each source character ignored, we increment bp and have ; one less character to compare (ie. decrement cx) ; (2) For each destination character ignored, we decrement bp. ; (3) As long as bp is non-negative, it means we've already ; decremented cx when ignoring a character in the source. ; (4) If bp is negative, it means we've ignored more destination ; characters then source characters, and so we need to adjust cx. ; (5) If cx reaches zero while ignoring characters, we're done ; and the strings are equal. ; nextSourceChar: inc bp ;bp <- one more in source dec cx ;cx <- one less to compare clc ;carry <- in case equal jz done ;branch (Z flag set -> equal) jmp getNextSource nextDestChar: dec bp ;bp <- one more in dest jns getNextDest dec cx ;cx <- one less to compare clc ;carry <- in case equal jz done ;branch (Z flag set -> equal) jmp getNextDest DoStringCompareNoSpace endp if SORT_DOUBLE_S_CORRECTLY and not DBCS_PCGEOS COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TranslateSpecialCharacters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Translate either string if it has a double-s character in it. CALLED BY: LocalCmpStringsReal, LocalCmpStringsNoCaseReal, LocalCmpStringsDosToGeosReal, LocalCmpStringsNoSpaceReal, LocalCmpStringsNoSpaceCaseReal PASS: ds:si - ptr to string #1 es:di - ptr to string #2 cx - maximum # of chars to compare (0 for NULL-terminated) RETURN: dx - count of strings copied to stack DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- pjc 5/16/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TranslateSpecialCharacters proc near uses ax .enter clr dx ; Count of strings copied to stack call TranslateSpecialCharactersESDI segxchg es, ds xchg si, di call TranslateSpecialCharactersESDI segxchg es, ds xchg si, di done:: ; Leave in for swat verbose. .leave ret TranslateSpecialCharacters endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TranslateSpecialCharactersESDI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: If the German double-s character is in the string, copy the whole string to the stack, with the character replaced with two ss's. CALLED BY: TranslateSpecialCharacters PASS: es:di = string cx = maximum # of chars to compare (0 for NULL-terminated) dx = current number of strings on stack RETURN: if double-s is in string, es:di = translated string on the stack dx = current number of strings on stack DESTROYED: ax SIDE EFFECTS: if double-s is in string, Allocates space on bottom of stack (below TPD_stackBot) PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- pjc 6/ 6/95 Initial version kho 7/15/96 Preserve cx so that it will work if both strings are to be translated in TranslateSpecialCharacters. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TranslateSpecialCharactersESDI proc near uses cx .enter ; If cx is specified, just check that number of characters. tst cx jnz scanForDoubleS ; Find the null termination. push di mov cx, 0FFFFh clr al repnz scasb pop di neg cx dec cx ; cx = number of characters to compare. scanForDoubleS: ; Look for a German double-s. push di mov al, C_GERMANDBLS repnz scasb pop di je translate done: .leave ret translate: inc dx ; Increment count of strings on stack. call TranslateAndCopyToStackESDI jmp done TranslateSpecialCharactersESDI endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% RemoveStringsFromStack %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Remove the translated strings from the stack. CALLED BY: LocalCmpStringsReal, LocalCmpStringsNoCaseReal, LocalCmpStringsDosToGeosReal, LocalCmpStringsNoSpaceReal, LocalCmpStringsNoSpaceCaseReal PASS: dx - number of strings to remove (0, 1, or 2) RETURN: If strings are on stack, ds:si and/or es:di will be restored to again point to the original strings ** Flags preserved ** DESTROYED: dx SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- pjc 6/ 1/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ RemoveStringsFromStack proc near uses ax,di .enter pushf EC < cmp dx, 2 > EC < ERROR_A STRING_SORT_STACK_CAN_ONLY_HAVE_TWO_STRINGS > ; Streamlined for nothing on the stack. tst dx jnz remove done: popf .leave ret ; <-- EXIT HERE. remove: ; Remove a string from the stack. mov di, ss:[TPD_stackBot] sub di, 2 mov ax, ss:[di] ; Previous stack bottom. mov ss:[TPD_stackBot], ax dec dx jnz remove ; Is another string on stack? jmp done RemoveStringsFromStack endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TranslateAndCopyToStackESDI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Copy the string at ds:si to the stack CALLED BY: TranslateSpecialCharactersESDI PASS: es:di - data to copy RETURN: es:di - now point to copy of data on the stack DESTROYED: nothing SIDE EFFECTS: Allocates space on bottom of stack (below TPD_stackBot) PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- pjc 5/24/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TranslateAndCopyToStackESDI proc near uses ax,cx,ds,si .enter ; Swap ds:si and es:di. xchg si, di segxchg ds, es ; Count the number of double-s's so we know how much space to ; allocate. This is a royal pain in patookis, for one letter, ; albeit a double-letter. clr cx ; Character count. push si ; Start of string. getNextChar: lodsb inc cx ; If we reached the null-termination, we are done. tst al jz copyToStack ; If this is a double-s, we'll need space to translate this to ; two s's. cmp al, C_GERMANDBLS jne getNextChar inc cx ; Count double-s as two chars. jmp getNextChar copyToStack: pop si ; Start of string. ; Allocate space on bottom of the stack, like SysCopyToStackDSSI. mov ax, ss:[TPD_stackBot] mov di, ax add di, cx push di ; Offset to store previous stack bottom. add di, 2 cmp di, sp jae stackOverflow mov ss:[TPD_stackBot], di ; Adjust stack bottom. ; Stuff previous stack bottom. pop di mov ss:[di], ax ; Previous stack bottom. ; Set up destination for translated string. segmov es, ss, di mov di, ax ; Copy string to stack, translating double-s's push di ; Offset of translated string. jcxz setReturnValue nextChar: dec cx lodsb cmp al, C_GERMANDBLS je doubleS stosb tst cx jnz nextChar setReturnValue: segmov es, ss, si ; Segment of translated string. pop di ; Offset of translated string. done: .leave ret ; <---- EXIT HERE doubleS: mov al, C_SMALL_S ; Store two s's in place of stosb ; German double-s. stosb dec cx ; Decrement again for double-s. jmp nextChar stackOverflow: pop di EC < ERROR_AE STACK_OVERFLOW > xchg si, di segxchg ds, es jmp done TranslateAndCopyToStackESDI endp endif ; SORT_DOUBLE_S_CORRECTLY and not DBCS_PCGEOS if DBCS_PCGEOS StringMod ends else StringCmpMod ends endif
; Adding 2 single-digit numbers — ADD_NUM.asm ; Copyright (c) 2021 Janrey Licas ; This code is licensed under MIT license. (see LICENSE for details) .MODEL TINY .CODE ORG 100H ; Set the starting address point. INPUT_ENTRYPOINT: MAIN PROC MOV AH, 01H ; Set mode to get input of a character. INT 21H ; Save the character input stream to AL register. SUB AL, 30H ; Subtract by 30 to represent actual hex single integer. MOV BL, AL ; Move AL to BL Register to accomodate next input. MOV AH, 02H ; Set mode to Display Character mode. MOV DL, 20H ; Display a space for extra feature. INT 21H ; Display the character in DL register. MOV DL, 2BH ; Display a '+' sign. INT 21H ; Same as goes. MOV DL, 20H INT 21H MOV AH, 01H ; Once done, get another character input again. INT 21H SUB AL, 30H ADD BL, AL ; Once we cleaned the 2nd input, add them up. MOV AH, 02H ; The following just display space. MOV DL, 20H INT 21H MOV DL, 3DH ; And also the '=' sign. INT 21H MOV DL, 20H INT 21H MOV DL, BL ; Move the output in DL register because I forgot. ADD DL, 30H ; And also add 30H to display numbers (@ ASCII 30 to 39 for number representation) INT 21H INT 20H ; End the program. MAIN ENDP END INPUT_ENTRYPOINT END
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: MODULE: FILE: swarmpref.asm AUTHOR: Adam de Boor, Dec 3, 1992 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- Adam 12/ 3/92 Initial revision DESCRIPTION: Saver-specific preferences for Swarm app $Id: swarmpref.asm,v 1.1 97/04/04 16:47:24 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ; include the standard suspects include geos.def include heap.def include geode.def include resource.def include ec.def include library.def include object.def include graphics.def include gstring.def UseLib ui.def UseLib config.def ; Most objects we use come from here UseLib saver.def ; ; Include constants from the saver, for use in our objects. ; include ../swarm.def ; ; Now the object tree. ; include swarmpref.rdef idata segment idata ends SwarmPrefCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SwarmPrefGetPrefUITree %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Return the root of the UI tree for "Preferences" CALLED BY: PrefMgr PASS: none RETURN: dx:ax - OD of root of tree DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 8/25/92 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SwarmPrefGetPrefUITree proc far mov dx, handle RootObject mov ax, offset RootObject ret SwarmPrefGetPrefUITree endp global SwarmPrefGetPrefUITree:far COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SwarmPrefGetModuleInfo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Fill in the PrefModuleInfo buffer so that PrefMgr can decide whether to show this button CALLED BY: PrefMgr PASS: ds:si - PrefModuleInfo structure to be filled in RETURN: ds:si - buffer filled in DESTROYED: ax,bx PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECSnd/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- chrisb 10/26/92 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SwarmPrefGetModuleInfo proc far .enter clr ax mov ds:[si].PMI_requiredFeatures, mask PMF_USER mov ds:[si].PMI_prohibitedFeatures, ax mov ds:[si].PMI_minLevel, ax mov ds:[si].PMI_maxLevel, UIInterfaceLevel-1 movdw ds:[si].PMI_monikerList, axax mov {word} ds:[si].PMI_monikerToken, ax mov {word} ds:[si].PMI_monikerToken+2, ax mov {word} ds:[si].PMI_monikerToken+4, ax .leave ret SwarmPrefGetModuleInfo endp global SwarmPrefGetModuleInfo:far SwarmPrefCode ends
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "3rdparty/objTester/obj_parser.h" #include "3rdparty/objTester/list.h" #include "3rdparty/objTester/string_extra.h" #define WHITESPACE " \t\n\r" void obj_free_half_list(objl_list *listo) { list_delete_all(listo); free(listo->names); } int obj_convert_to_list_index(int current_max, int index) { if(index == 0) //no index return -1; if(index < 0) //relative to current list position return current_max + index; return index - 1; //normal counting index } void obj_convert_to_list_index_v(int current_max, int *indices) { for(int i=0; i<MAX_VERTEX_COUNT; i++) indices[i] = obj_convert_to_list_index(current_max, indices[i]); } void obj_set_material_defaults(obj_material *mtl) { mtl->amb[0] = 0.2; mtl->amb[1] = 0.2; mtl->amb[2] = 0.2; mtl->diff[0] = 0.8; mtl->diff[1] = 0.8; mtl->diff[2] = 0.8; mtl->spec[0] = 1.0; mtl->spec[1] = 1.0; mtl->spec[2] = 1.0; mtl->reflect = 0.0; mtl->trans = 1; mtl->glossy = 98; mtl->shiny = 0; mtl->refract_index = 1; mtl->texture_filename[0] = '\0'; } int obj_parse_vertex_index(int *vertex_index, int *texture_index, int *normal_index) { char *temp_str; char *token; int vertex_count = 0; while( (token = strtok(NULL, WHITESPACE)) != NULL) { if(texture_index != NULL) texture_index[vertex_count] = 0; if(normal_index != NULL) normal_index[vertex_count] = 0; vertex_index[vertex_count] = atoi( token ); if(contains(token, "//")) //normal only { temp_str = strchr(token, '/'); temp_str++; normal_index[vertex_count] = atoi( ++temp_str ); } else if(contains(token, "/")) { temp_str = strchr(token, '/'); texture_index[vertex_count] = atoi( ++temp_str ); if(contains(temp_str, "/")) { temp_str = strchr(temp_str, '/'); normal_index[vertex_count] = atoi( ++temp_str ); } } vertex_count++; } return vertex_count; } obj_face* obj_parse_face(obj_growable_scene_data *scene) { int vertex_count; obj_face *face = (obj_face*)malloc(sizeof(obj_face)); memset( face, 0, (unsigned)sizeof(obj_face) ); vertex_count = obj_parse_vertex_index(face->vertex_index, face->texture_index, face->normal_index); obj_convert_to_list_index_v(scene->vertex_list.item_count, face->vertex_index); obj_convert_to_list_index_v(scene->vertex_texture_list.item_count, face->texture_index); obj_convert_to_list_index_v(scene->vertex_normal_list.item_count, face->normal_index); face->vertex_count = vertex_count; return face; } obj_sphere* obj_parse_sphere(obj_growable_scene_data *scene) { int temp_indices[MAX_VERTEX_COUNT]; obj_sphere *obj = (obj_sphere*)malloc(sizeof(obj_sphere)); obj_parse_vertex_index(temp_indices, obj->texture_index, NULL); obj_convert_to_list_index_v(scene->vertex_texture_list.item_count, obj->texture_index); obj->pos_index = obj_convert_to_list_index(scene->vertex_list.item_count, temp_indices[0]); obj->up_normal_index = obj_convert_to_list_index(scene->vertex_normal_list.item_count, temp_indices[1]); obj->equator_normal_index = obj_convert_to_list_index(scene->vertex_normal_list.item_count, temp_indices[2]); return obj; } obj_plane* obj_parse_plane(obj_growable_scene_data *scene) { int temp_indices[MAX_VERTEX_COUNT]; obj_plane *obj = (obj_plane*)malloc(sizeof(obj_plane)); obj_parse_vertex_index(temp_indices, obj->texture_index, NULL); obj_convert_to_list_index_v(scene->vertex_texture_list.item_count, obj->texture_index); obj->pos_index = obj_convert_to_list_index(scene->vertex_list.item_count, temp_indices[0]); obj->normal_index = obj_convert_to_list_index(scene->vertex_normal_list.item_count, temp_indices[1]); obj->rotation_normal_index = obj_convert_to_list_index(scene->vertex_normal_list.item_count, temp_indices[2]); return obj; } obj_light_point* obj_parse_light_point(obj_growable_scene_data *scene) { obj_light_point *o= (obj_light_point*)malloc(sizeof(obj_light_point)); o->pos_index = obj_convert_to_list_index(scene->vertex_list.item_count, atoi( strtok(NULL, WHITESPACE)) ); return o; } obj_light_quad* obj_parse_light_quad(obj_growable_scene_data *scene) { obj_light_quad *o = (obj_light_quad*)malloc(sizeof(obj_light_quad)); obj_parse_vertex_index(o->vertex_index, NULL, NULL); obj_convert_to_list_index_v(scene->vertex_list.item_count, o->vertex_index); return o; } obj_light_disc* obj_parse_light_disc(obj_growable_scene_data *scene) { int temp_indices[MAX_VERTEX_COUNT]; obj_light_disc *obj = (obj_light_disc*)malloc(sizeof(obj_light_disc)); obj_parse_vertex_index(temp_indices, NULL, NULL); obj->pos_index = obj_convert_to_list_index(scene->vertex_list.item_count, temp_indices[0]); obj->normal_index = obj_convert_to_list_index(scene->vertex_normal_list.item_count, temp_indices[1]); return obj; } inline double next_tok( ){ char* t = strtok(NULL, WHITESPACE); return ( t ? atof(t) : 0 ); } obj_vector* obj_parse_vector() { obj_vector *v = (obj_vector*)malloc(sizeof(obj_vector)); v->e[0] = next_tok(); v->e[1] = next_tok(); v->e[2] = next_tok(); return v; } void obj_parse_camera(obj_growable_scene_data *scene, obj_camera *camera) { int indices[3]; obj_parse_vertex_index(indices, NULL, NULL); camera->camera_pos_index = obj_convert_to_list_index(scene->vertex_list.item_count, indices[0]); camera->camera_look_point_index = obj_convert_to_list_index(scene->vertex_list.item_count, indices[1]); camera->camera_up_norm_index = obj_convert_to_list_index(scene->vertex_normal_list.item_count, indices[2]); } int obj_parse_mtl_file(char *filename, objl_list *material_list) { int line_number = 0; char *current_token; char current_line[OBJ_LINE_SIZE]; char material_open = 0; obj_material *current_mtl = NULL; FILE *mtl_file_stream; // open scene mtl_file_stream = fopen( filename, "r"); if(mtl_file_stream == 0) { fprintf(stderr, "Error reading file: %s\n", filename); return 0; } list_make(material_list, 10, 1); while( fgets(current_line, OBJ_LINE_SIZE, mtl_file_stream) ) { current_token = strtok( current_line, " \t\n\r"); line_number++; //skip comments if( current_token == NULL || strequal(current_token, "//") || strequal(current_token, "#")) continue; //start material else if( strequal(current_token, "newmtl")) { material_open = 1; current_mtl = (obj_material*) malloc(sizeof(obj_material)); obj_set_material_defaults(current_mtl); // get the name strncpy(current_mtl->name, strtok(NULL, " \t"), MATERIAL_NAME_SIZE); list_add_item(material_list, current_mtl, current_mtl->name); } //ambient else if( strequal(current_token, "Ka") && material_open) { current_mtl->amb[0] = atof( strtok(NULL, " \t")); current_mtl->amb[1] = atof( strtok(NULL, " \t")); current_mtl->amb[2] = atof( strtok(NULL, " \t")); } //diff else if( strequal(current_token, "Kd") && material_open) { current_mtl->diff[0] = atof( strtok(NULL, " \t")); current_mtl->diff[1] = atof( strtok(NULL, " \t")); current_mtl->diff[2] = atof( strtok(NULL, " \t")); } //specular else if( strequal(current_token, "Ks") && material_open) { current_mtl->spec[0] = atof( strtok(NULL, " \t")); current_mtl->spec[1] = atof( strtok(NULL, " \t")); current_mtl->spec[2] = atof( strtok(NULL, " \t")); } //shiny else if( strequal(current_token, "Ns") && material_open) { current_mtl->shiny = atof( strtok(NULL, " \t")); } //transparent else if( strequal(current_token, "d") && material_open) { current_mtl->trans = atof( strtok(NULL, " \t")); } //reflection else if( strequal(current_token, "r") && material_open) { current_mtl->reflect = atof( strtok(NULL, " \t")); } //glossy else if( strequal(current_token, "sharpness") && material_open) { current_mtl->glossy = atof( strtok(NULL, " \t")); } //refract index else if( strequal(current_token, "Ni") && material_open) { current_mtl->refract_index = atof( strtok(NULL, " \t")); } // illumination type else if( strequal(current_token, "illum") && material_open) { } // texture map else if( strequal(current_token, "map_Ka") && material_open) { strncpy(current_mtl->texture_filename, strtok(NULL, " \t"), OBJ_FILENAME_LENGTH); } else { fprintf(stderr, "Unknown command '%s' in material file %s at line %i:\n\t%s\n", current_token, filename, line_number, current_line); //return 0; } } fclose(mtl_file_stream); return 1; } int obj_parse_obj_file(obj_growable_scene_data *growable_data, const char *filename) { FILE* obj_file_stream; int current_material = -1; char *current_token = NULL; char current_line[OBJ_LINE_SIZE]; int line_number = 0; // open scene obj_file_stream = fopen(filename, "r"); if(obj_file_stream == 0) { fprintf(stderr, "Error reading file: %s\n", filename); return 0; } /* extreme_dimensions[0].x = INFINITY; extreme_dimensions[0].y = INFINITY; extreme_dimensions[0].z = INFINITY; extreme_dimensions[1].x = -INFINITY; extreme_dimensions[1].y = -INFINITY; extreme_dimensions[1].z = -INFINITY; if(v->x < extreme_dimensions[0].x) extreme_dimensions[0].x = v->x; if(v->x > extreme_dimensions[1].x) extreme_dimensions[1].x = v->x; if(v->y < extreme_dimensions[0].y) extreme_dimensions[0].y = v->y; if(v->y > extreme_dimensions[1].y) extreme_dimensions[1].y = v->y; if(v->z < extreme_dimensions[0].z) extreme_dimensions[0].z = v->z; if(v->z > extreme_dimensions[1].z) extreme_dimensions[1].z = v->z;*/ //parser loop while( fgets(current_line, OBJ_LINE_SIZE, obj_file_stream) ) { current_token = strtok( current_line, " \t\n\r"); line_number++; //skip comments if( current_token == NULL || current_token[0] == '#') continue; //parse objects else if( strequal(current_token, "v") ) //process vertex { list_add_item(&growable_data->vertex_list, obj_parse_vector(), NULL); } else if( strequal(current_token, "vn") ) //process vertex normal { list_add_item(&growable_data->vertex_normal_list, obj_parse_vector(), NULL); } else if( strequal(current_token, "vt") ) //process vertex texture { list_add_item(&growable_data->vertex_texture_list, obj_parse_vector(), NULL); } else if( strequal(current_token, "f") ) //process face { obj_face *face = obj_parse_face(growable_data); face->material_index = current_material; list_add_item(&growable_data->face_list, face, NULL); } else if( strequal(current_token, "sp") ) //process sphere { obj_sphere *sphr = obj_parse_sphere(growable_data); sphr->material_index = current_material; list_add_item(&growable_data->sphere_list, sphr, NULL); } else if( strequal(current_token, "pl") ) //process plane { obj_plane *pl = obj_parse_plane(growable_data); pl->material_index = current_material; list_add_item(&growable_data->plane_list, pl, NULL); } else if( strequal(current_token, "p") ) //process point { //make a small sphere to represent the point? } else if( strequal(current_token, "lp") ) //light point source { obj_light_point *o = obj_parse_light_point(growable_data); o->material_index = current_material; list_add_item(&growable_data->light_point_list, o, NULL); } else if( strequal(current_token, "ld") ) //process light disc { obj_light_disc *o = obj_parse_light_disc(growable_data); o->material_index = current_material; list_add_item(&growable_data->light_disc_list, o, NULL); } else if( strequal(current_token, "lq") ) //process light quad { obj_light_quad *o = obj_parse_light_quad(growable_data); o->material_index = current_material; list_add_item(&growable_data->light_quad_list, o, NULL); } else if( strequal(current_token, "c") ) //camera { growable_data->camera = (obj_camera*) malloc(sizeof(obj_camera)); obj_parse_camera(growable_data, growable_data->camera); } else if( strequal(current_token, "usemtl") ) // usemtl { current_material = list_find(&growable_data->material_list, strtok(NULL, WHITESPACE)); } else if( strequal(current_token, "mtllib") ) // mtllib { strncpy(growable_data->material_filename, strtok(NULL, WHITESPACE), OBJ_FILENAME_LENGTH); obj_parse_mtl_file(growable_data->material_filename, &growable_data->material_list); continue; } else if( strequal(current_token, "o") ) //object name { } else if( strequal(current_token, "s") ) //smoothing { } else if( strequal(current_token, "g") ) // group { } else { printf("Unknown command '%s' in scene code at line %i: \"%s\".\n", current_token, line_number, current_line); } } fclose(obj_file_stream); return 1; } void obj_init_temp_storage(obj_growable_scene_data *growable_data) { list_make(&growable_data->vertex_list, 10, 1); list_make(&growable_data->vertex_normal_list, 10, 1); list_make(&growable_data->vertex_texture_list, 10, 1); list_make(&growable_data->face_list, 10, 1); list_make(&growable_data->sphere_list, 10, 1); list_make(&growable_data->plane_list, 10, 1); list_make(&growable_data->light_point_list, 10, 1); list_make(&growable_data->light_quad_list, 10, 1); list_make(&growable_data->light_disc_list, 10, 1); list_make(&growable_data->material_list, 10, 1); growable_data->camera = NULL; } void obj_free_temp_storage(obj_growable_scene_data *growable_data) { obj_free_half_list(&growable_data->vertex_list); obj_free_half_list(&growable_data->vertex_normal_list); obj_free_half_list(&growable_data->vertex_texture_list); obj_free_half_list(&growable_data->face_list); obj_free_half_list(&growable_data->sphere_list); obj_free_half_list(&growable_data->plane_list); obj_free_half_list(&growable_data->light_point_list); obj_free_half_list(&growable_data->light_quad_list); obj_free_half_list(&growable_data->light_disc_list); obj_free_half_list(&growable_data->material_list); } void delete_obj_data(obj_scene_data *data_out) { int i; for(i=0; i<data_out->vertex_count; i++) free(data_out->vertex_list[i]); free(data_out->vertex_list); for(i=0; i<data_out->vertex_normal_count; i++) free(data_out->vertex_normal_list[i]); free(data_out->vertex_normal_list); for(i=0; i<data_out->vertex_texture_count; i++) free(data_out->vertex_texture_list[i]); free(data_out->vertex_texture_list); for(i=0; i<data_out->face_count; i++) free(data_out->face_list[i]); free(data_out->face_list); for(i=0; i<data_out->sphere_count; i++) free(data_out->sphere_list[i]); free(data_out->sphere_list); for(i=0; i<data_out->plane_count; i++) free(data_out->plane_list[i]); free(data_out->plane_list); for(i=0; i<data_out->light_point_count; i++) free(data_out->light_point_list[i]); free(data_out->light_point_list); for(i=0; i<data_out->light_disc_count; i++) free(data_out->light_disc_list[i]); free(data_out->light_disc_list); for(i=0; i<data_out->light_quad_count; i++) free(data_out->light_quad_list[i]); free(data_out->light_quad_list); for(i=0; i<data_out->material_count; i++) free(data_out->material_list[i]); free(data_out->material_list); free(data_out->camera); } void obj_copy_to_out_storage(obj_scene_data *data_out, obj_growable_scene_data *growable_data) { data_out->vertex_count = growable_data->vertex_list.item_count; data_out->vertex_normal_count = growable_data->vertex_normal_list.item_count; data_out->vertex_texture_count = growable_data->vertex_texture_list.item_count; data_out->face_count = growable_data->face_list.item_count; data_out->sphere_count = growable_data->sphere_list.item_count; data_out->plane_count = growable_data->plane_list.item_count; data_out->light_point_count = growable_data->light_point_list.item_count; data_out->light_disc_count = growable_data->light_disc_list.item_count; data_out->light_quad_count = growable_data->light_quad_list.item_count; data_out->material_count = growable_data->material_list.item_count; data_out->vertex_list = (obj_vector**)growable_data->vertex_list.items; data_out->vertex_normal_list = (obj_vector**)growable_data->vertex_normal_list.items; data_out->vertex_texture_list = (obj_vector**)growable_data->vertex_texture_list.items; data_out->face_list = (obj_face**)growable_data->face_list.items; data_out->sphere_list = (obj_sphere**)growable_data->sphere_list.items; data_out->plane_list = (obj_plane**)growable_data->plane_list.items; data_out->light_point_list = (obj_light_point**)growable_data->light_point_list.items; data_out->light_disc_list = (obj_light_disc**)growable_data->light_disc_list.items; data_out->light_quad_list = (obj_light_quad**)growable_data->light_quad_list.items; data_out->material_list = (obj_material**)growable_data->material_list.items; data_out->camera = growable_data->camera; } int parse_obj_scene(obj_scene_data *data_out, const char *filename) { obj_growable_scene_data growable_data; obj_init_temp_storage(&growable_data); if( obj_parse_obj_file(&growable_data, filename) == 0) return 0; //print_vector(NORMAL, "Max bounds are: ", &growable_data->extreme_dimensions[1]); //print_vector(NORMAL, "Min bounds are: ", &growable_data->extreme_dimensions[0]); obj_copy_to_out_storage(data_out, &growable_data); obj_free_temp_storage(&growable_data); return 1; }
############################################################################## # Program : HW#5_1 Programmer: Chaoran Li # Due Date: 11/04/19 Last Modified:11/06/19 # Course: CS3340 Section:501 ############################################################################# # Description: # Write a MIPS assembly language program that # # Joe is running a take-out pizza shop Pizza-R-US that sells 8" round (circle) and 10" square pizzas. # Write a MIPS assembly language program to help him to calculate the total square foot of pizzas he has # sold during a day. # # The program: # # 1. a) prompts Joe for the number of round and square pizzas sold in a day. Obviously, the program # must ask Joe to input two integer numbers: the number of circle piazza and the number of square pizza # sold. # # b) prompts Joe for his estimate of total pizzas sold in that day in square feet (a floating point number). # # 2. calculates the total pizza sold in square feet for each type (circle and square) and for both types. # # 3. a) prints out the calculation results such that Joe would know a) the total number of square feet of # pizza sold, b) the total number of square feet of round pizzas, and c) the total number of square feet # of square piazzas. # # b) prints the message "Yeah!" if the total pizzas sold is greater than Joe's estimate (from 1.b), # otherwise prints "Bummer!". # # Note: single precision floating point arithmetic must be used for round piazzas but integer arithmetic # should be used for square piazzas (except the last step when converting the total square inches to # square feet), and floating point comparison must be used for 3.b). # # Details: # 1. According to my survey about the size of pizza on the Internet, for 8" circle pizza, 8" is its # diameter. For 10" square pizza, 10" is its edge length. # 2. For this case, if the integer for the total square feet for square pizzas is larger than 32-bit, I will use # the formula : total square feet = number * 100 to calculate and print. ############################################################################# # Register: # $s0 area of one square pizza (integer) diagonal length = 10 # $t0 input circle pizza number # $t1 input squre pizza number # $t2 total number of square feet of all square pizzas # $t3 tmp number # Co-processor1: # $f16 Joe's estimate of total area # $f18 area of one circle pizza (single) diameter = 8 # $f20 pi = 3.14159 # $f22 4.0 # $f24 total number of square feet of all circle pizzas # $f26 total number of square feet of all square pizzas # $f28 total number of square feet of all pizzas # $f30 tmp FP # ############################################################################# .data msgIn1: .asciiz "\nHello Joe, how is your day? Tell me how many circle pizzas have you sold today?" msgIn2: .asciiz "\n(Input an integer): " msgIn3: .asciiz "\nHow about square pizzas?" msgIn4: .asciiz "\nOK. Then how many square inches of pizza do you thing you sold today?" msgIn5: .asciiz "\n(Input a single floating point): " msgOut1: .asciiz "\nTotal number of square feet of all circle pizzas:\n" msgOut2: .asciiz "\nTotal number of square feet of all square pizzas:\n" msgOut3: .asciiz "\nTotal number of square feet of all pizzas:\n" msgOut4: .asciiz "\nYeah!" msgOut5: .asciiz "\nBummer!" suffix00: .asciiz "00" pi: .float 3.14159 ############################################################################# .text .globl main main: # init saved register li $s0, 10 # diagonal length = 10 mul $s0, $s0, $s0 # 10 * 10 li $t3, 8 mtc1 $t3, $f18 cvt.s.w $f18, $f18 # diameter = 8 mul.s $f18, $f18, $f18 li $t3, 4 mtc1 $t3, $f22 cvt.s.w $f22, $f22 # 4.0 div.s $f18, $f18, $f22 lwc1 $f20, pi # pi mul.s $f18, $f18, $f20 # 8 * 8 / 4 * pi # prompt for input li $v0, 4 la $a0, msgIn1 syscall li $v0, 4 la $a0, msgIn2 syscall li $v0, 5 # get number of circle pizzas syscall move $t0, $v0 li $v0, 4 la $a0, msgIn3 syscall li $v0, 4 la $a0, msgIn2 syscall li $v0, 5 # get number of square pizzas syscall move $t1, $v0 li $v0, 4 la $a0, msgIn4 syscall li $v0, 4 la $a0, msgIn5 syscall li $v0, 6 # get estimate of total square feet syscall mov.s $f16, $f0 # calculate total square feet of circle pizza and print mtc1 $t0, $f30 cvt.s.w $f30, $f30 # get circle pizza number mul.s $f24, $f18, $f30 # total square feet of circle pizzas li $v0, 4 la $a0, msgOut1 syscall li $v0, 2 # print mov.s $f12, $f24 syscall # calculate total square feet of square pizza and print mult $t1, $s0 # total square feet of square pizzas mfhi $t3 bne $t3, $zero, bigInt # if integer is too big li $v0, 4 la $a0, msgOut2 syscall mflo $a0 # print LO li $v0, 1 syscall # calculate total square feet of all pizza and print mtc1 $a0, $f26 cvt.s.w $f26, $f26 # total square feet of square pizzas (single) j total bigInt: # if integer larger than 32-bit (number * 100) li $v0, 4 la $a0, msgOut2 syscall move $a0, $t1 li $v0, 1 # print number syscall mtc1 $a0, $f26 cvt.s.w $f26, $f26 # total square feet of square pizzas (single) li $v0, 4 la $a0, suffix00 # print 00 syscall li $t3, 100 mtc1 $t3, $f30 cvt.s.w $f30, $f30 # 100 mul.s $f26, $f26, $f30 total: add.s $f28, $f24, $f26 # total square feet of all pizzas li $v0, 4 la $a0, msgOut3 syscall li $v0, 2 # print mov.s $f12, $f28 syscall compare: # compare and print yeah or bummer c.le.s $f16, $f28 # compare with Joe;s estimate bc1t yeah li $v0, 4 # print bummer la $a0, msgOut5 syscall j exit yeah: li $v0, 4 # print yeah la $a0, msgOut4 syscall exit: # exit
#include "tst.h" #include <cassert> int main() { const TST<> tst{ "catamorphism" }; const auto result{ tst + "cat" + "theory" + "function" + "catfish" }; assert(result.value() == 'c'); assert(!result.word()); assert(!result.empty()); assert(result.center().value() == 'a'); assert(!result.center().word()); assert(result.center().center().value() == 't'); assert(result.center().center().word()); assert(result.center().center().center().value() == 'a'); assert(!result.center().center().center().word()); assert(!result.center().center().center().empty()); assert(result.center().center().center().center().value() == 'm'); assert(!result.center().center().center().center().word()); assert(result.center().center().center().center().center().value() == 'o'); assert(!result.center().center().center().center().center().word()); assert(result.center().center().center().center().center().center().value() == 'r'); assert(!result.center().center().center().center().center().center().word()); assert(result.center() .center() .center() .center() .center() .center() .center() .value() == 'p'); assert(!result.center() .center() .center() .center() .center() .center() .center() .word()); assert(result.center() .center() .center() .center() .center() .center() .center() .center() .value() == 'h'); assert(!result.center() .center() .center() .center() .center() .center() .center() .center() .word()); assert(result.center() .center() .center() .center() .center() .center() .center() .center() .center() .value() == 'i'); assert(!result.center() .center() .center() .center() .center() .center() .center() .center() .center() .word()); assert(result.center() .center() .center() .center() .center() .center() .center() .center() .center() .center() .value() == 's'); assert(!result.center() .center() .center() .center() .center() .center() .center() .center() .center() .center() .word()); assert(result.center() .center() .center() .center() .center() .center() .center() .center() .center() .center() .center() .value() == 'm'); assert(result.center() .center() .center() .center() .center() .center() .center() .center() .center() .center() .center() .word()); assert(result.center() .center() .center() .center() .center() .center() .center() .center() .center() .center() .center() .center() .empty()); assert(result.center().center().center().right().value() == 'f'); assert(!result.center().center().center().right().word()); assert(!result.center().center().center().right().empty()); assert(result.center().center().center().right().center().value() == 'i'); assert(!result.center().center().center().right().center().word()); assert(result.center().center().center().right().center().center().value() == 's'); assert(!result.center().center().center().right().center().center().word()); assert(result.center() .center() .center() .right() .center() .center() .center() .value() == 'h'); assert(result.center() .center() .center() .right() .center() .center() .center() .word()); assert(result.center() .center() .center() .right() .center() .center() .center() .center() .empty()); assert(result.right().value() == 't'); assert(!result.right().word()); assert(!result.right().empty()); assert(result.right().center().value() == 'h'); assert(!result.right().center().word()); assert(result.right().center().center().value() == 'e'); assert(!result.right().center().center().word()); assert(result.right().center().center().center().value() == 'o'); assert(!result.right().center().center().center().word()); assert(result.right().center().center().center().center().value() == 'r'); assert(!result.right().center().center().center().center().word()); assert(result.right().center().center().center().center().center().value() == 'y'); assert(result.right().center().center().center().center().center().word()); assert(result.right() .center() .center() .center() .center() .center() .center() .empty()); assert(result.right().left().value() == 'f'); assert(!result.right().left().word()); assert(!result.right().left().empty()); assert(result.right().left().center().value() == 'u'); assert(!result.right().left().center().word()); assert(result.right().left().center().center().value() == 'n'); assert(!result.right().left().center().center().word()); assert(result.right().left().center().center().center().value() == 'c'); assert(!result.right().left().center().center().center().word()); assert(result.right().left().center().center().center().center().value() == 't'); assert(!result.right().left().center().center().center().center().word()); assert(result.right() .left() .center() .center() .center() .center() .center() .value() == 'i'); assert( !result.right().left().center().center().center().center().center().word()); assert(result.right() .left() .center() .center() .center() .center() .center() .center() .value() == 'o'); assert(!result.right() .left() .center() .center() .center() .center() .center() .center() .word()); assert(result.right() .left() .center() .center() .center() .center() .center() .center() .center() .value() == 'n'); assert(result.right() .left() .center() .center() .center() .center() .center() .center() .center() .word()); assert(result.right() .left() .center() .center() .center() .center() .center() .center() .center() .center() .empty()); }
; A282166: a(n) is the minimal sum of a positive integer sequence of length n with no duplicate substrings of length greater than 1, and every number different from its neighbors. ; 1,3,4,7,8,12,13,17,18,22,24,28,30,35,37,42,44,49,51,56,59 add $0,2 lpb $0 mov $2,$0 trn $0,2 seq $2,193832 ; Irregular triangle read by rows in which row n lists 2n-1 copies of 2n-1 and n copies of 2n, for n >= 1. add $1,$2 lpe sub $1,2 mov $0,$1
; A065233: Fill a triangular array by rows by writing numbers 1 up to b(0), 1 up to b(1), etc., where the b(n) are the nonzero 9-gonal (nonagonal) numbers 1, 9, 24, 46, ... (A001106). The initial elements of the rows form a(n). ; 1,1,3,6,1,6,12,19,3,12,22,33,45,12,26,41,57,74,17,36,56,77,99,11,35,60,86,113,141,16,46,77,109,142,176,7,43,80,118,157,197,238,19,62,106,151,197,244,292,16,66,117,169,222,276,331,387,48,106,165,225,286,348 lpb $0 add $2,$0 sub $0,1 lpe mov $1,1 lpb $2 add $3,$1 add $1,7 sub $2,$3 lpe mov $0,$2 add $0,1
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <op_table.hpp> #include <openvino/opsets/opset8.hpp> using namespace std; using namespace ov::opset8; namespace ov { namespace frontend { namespace tf { namespace op { OutputVector TranslateSqrtOp(const NodeContext& node) { auto input = node.get_ng_input(0); auto ng_exponent = ConstructNgNode<Constant>(node.get_name(), input.get_element_type(), Shape{1}, 0.5f); auto power = make_shared<Power>(input, ng_exponent); power->set_friendly_name(node.get_name()); return power->outputs(); } } // namespace op } // namespace tf } // namespace frontend } // namespace ov
; A078832: Smallest prime contained as binary substring in binary representation of n>1, a(1)=1. ; 1,2,3,2,2,2,3,2,2,2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 mov $1,$0 lpb $1 sub $1,2 gcd $0,$1 div $1,2 lpe add $0,1
// Bubble sort implementation using C++ program #include <bits/stdc++.h> using namespace std; void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } // A function to implement bubble sort void bubbleSort(int arr[], int n) { int i, j; for (i = 0; i < n-1; i++) // Last i elements are already in place for (j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) swap(&arr[j], &arr[j+1]); } /* Function to print an array */ void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } // main code int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr)/sizeof(arr[0]); bubbleSort(arr, n); cout<<"Sorted array: \n"; printArray(arr, n); return 0; }
#pragma once #include <buffer.hpp> #include <iostream> namespace libasm { namespace compiled { class function { private: void* memory_address; size_t size; public: template <typename T> T to() { return reinterpret_cast<T>(this->memory_address); } function(byte* binaries, std::size_t); ~function(); }; } }
; double tanh(double x) SECTION code_clib SECTION code_fp_math48 PUBLIC am48_tanh EXTERN am48_dequate, am48_sinh, am48_cosh, am48_ddiv, am48_dpopret am48_tanh: ; hyberbolic tangent ; AC' = tanh(AC') ; ; enter : AC' = double x ; ; exit : AC' = tanh(x) ; carry reset ; ; uses : af, af', bc', de', hl' ; tanh(x) = sinh(x)/cosh(x) push bc ; save AC push de push hl exx call am48_dequate ; AC = AC' = x call am48_cosh exx call am48_sinh call am48_ddiv jp am48_dpopret
/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "rtc_base/physical_socket_server.h" #if defined(_MSC_VER) && _MSC_VER < 1300 #pragma warning(disable : 4786) #endif #ifdef MEMORY_SANITIZER #include <sanitizer/msan_interface.h> #endif #if defined(WEBRTC_POSIX) #include <fcntl.h> #include <string.h> #if defined(WEBRTC_USE_EPOLL) // "poll" will be used to wait for the signal dispatcher. #include <poll.h> #endif #include <signal.h> #include <sys/ioctl.h> #include <sys/select.h> #include <sys/time.h> #include <unistd.h> #endif #if defined(WEBRTC_WIN) #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> #undef SetPort #endif #include <errno.h> #include <algorithm> #include <map> #include "rtc_base/arraysize.h" #include "rtc_base/byte_order.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/network_monitor.h" #include "rtc_base/null_socket_server.h" #include "rtc_base/time_utils.h" #if defined(WEBRTC_LINUX) #include <linux/sockios.h> #endif #if defined(WEBRTC_WIN) #define LAST_SYSTEM_ERROR (::GetLastError()) #elif defined(__native_client__) && __native_client__ #define LAST_SYSTEM_ERROR (0) #elif defined(WEBRTC_POSIX) #define LAST_SYSTEM_ERROR (errno) #endif // WEBRTC_WIN #if defined(WEBRTC_POSIX) #include <netinet/tcp.h> // for TCP_NODELAY #define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h typedef void* SockOptArg; #endif // WEBRTC_POSIX #if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__) int64_t GetSocketRecvTimestamp(int socket) { struct timeval tv_ioctl; int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl); if (ret != 0) return -1; int64_t timestamp = rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) + static_cast<int64_t>(tv_ioctl.tv_usec); return timestamp; } #else int64_t GetSocketRecvTimestamp(int socket) { return -1; } #endif #if defined(WEBRTC_WIN) typedef char* SockOptArg; #endif #if defined(WEBRTC_USE_EPOLL) // POLLRDHUP / EPOLLRDHUP are only defined starting with Linux 2.6.17. #if !defined(POLLRDHUP) #define POLLRDHUP 0x2000 #endif #if !defined(EPOLLRDHUP) #define EPOLLRDHUP 0x2000 #endif #endif namespace rtc { std::unique_ptr<SocketServer> SocketServer::CreateDefault() { #if defined(__native_client__) return std::unique_ptr<SocketServer>(new rtc::NullSocketServer); #else return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer); #endif } PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s) : ss_(ss), s_(s), error_(0), state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED), resolver_(nullptr) { if (s_ != INVALID_SOCKET) { SetEnabledEvents(DE_READ | DE_WRITE); int type = SOCK_STREAM; socklen_t len = sizeof(type); const int res = getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len); RTC_DCHECK_EQ(0, res); udp_ = (SOCK_DGRAM == type); } } PhysicalSocket::~PhysicalSocket() { Close(); } bool PhysicalSocket::Create(int family, int type) { Close(); s_ = ::socket(family, type, 0); udp_ = (SOCK_DGRAM == type); family_ = family; UpdateLastError(); if (udp_) { SetEnabledEvents(DE_READ | DE_WRITE); } return s_ != INVALID_SOCKET; } SocketAddress PhysicalSocket::GetLocalAddress() const { sockaddr_storage addr_storage = {}; socklen_t addrlen = sizeof(addr_storage); sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage); int result = ::getsockname(s_, addr, &addrlen); SocketAddress address; if (result >= 0) { SocketAddressFromSockAddrStorage(addr_storage, &address); } else { RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket=" << s_; } return address; } SocketAddress PhysicalSocket::GetRemoteAddress() const { sockaddr_storage addr_storage = {}; socklen_t addrlen = sizeof(addr_storage); sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage); int result = ::getpeername(s_, addr, &addrlen); SocketAddress address; if (result >= 0) { SocketAddressFromSockAddrStorage(addr_storage, &address); } else { RTC_LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket=" << s_; } return address; } int PhysicalSocket::Bind(const SocketAddress& bind_addr) { SocketAddress copied_bind_addr = bind_addr; // If a network binder is available, use it to bind a socket to an interface // instead of bind(), since this is more reliable on an OS with a weak host // model. if (ss_->network_binder() && !bind_addr.IsAnyIP()) { NetworkBindingResult result = ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr()); if (result == NetworkBindingResult::SUCCESS) { // Since the network binder handled binding the socket to the desired // network interface, we don't need to (and shouldn't) include an IP in // the bind() call; bind() just needs to assign a port. copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family())); } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) { RTC_LOG(LS_INFO) << "Can't bind socket to network because " "network binding is not implemented for this OS."; } else { if (bind_addr.IsLoopbackIP()) { // If we couldn't bind to a loopback IP (which should only happen in // test scenarios), continue on. This may be expected behavior. RTC_LOG(LS_VERBOSE) << "Binding socket to loopback address" << " failed; result: " << static_cast<int>(result); } else { RTC_LOG(LS_WARNING) << "Binding socket to network address" << " failed; result: " << static_cast<int>(result); // If a network binding was attempted and failed, we should stop here // and not try to use the socket. Otherwise, we may end up sending // packets with an invalid source address. // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026 return -1; } } } sockaddr_storage addr_storage; size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage); sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage); int err = ::bind(s_, addr, static_cast<int>(len)); UpdateLastError(); #if !defined(NDEBUG) if (0 == err) { dbg_addr_ = "Bound @ "; dbg_addr_.append(GetLocalAddress().ToString()); } #endif return err; } int PhysicalSocket::Connect(const SocketAddress& addr) { // TODO(pthatcher): Implicit creation is required to reconnect... // ...but should we make it more explicit? if (state_ != CS_CLOSED) { SetError(EALREADY); return SOCKET_ERROR; } if (addr.IsUnresolvedIP()) { RTC_LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect"; resolver_ = new AsyncResolver(); resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult); resolver_->Start(addr); state_ = CS_CONNECTING; return 0; } return DoConnect(addr); } int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) { if ((s_ == INVALID_SOCKET) && !Create(connect_addr.family(), SOCK_STREAM)) { return SOCKET_ERROR; } sockaddr_storage addr_storage; size_t len = connect_addr.ToSockAddrStorage(&addr_storage); sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage); int err = ::connect(s_, addr, static_cast<int>(len)); UpdateLastError(); uint8_t events = DE_READ | DE_WRITE; if (err == 0) { state_ = CS_CONNECTED; } else if (IsBlockingError(GetError())) { state_ = CS_CONNECTING; events |= DE_CONNECT; } else { return SOCKET_ERROR; } EnableEvents(events); return 0; } int PhysicalSocket::GetError() const { CritScope cs(&crit_); return error_; } void PhysicalSocket::SetError(int error) { CritScope cs(&crit_); error_ = error; } AsyncSocket::ConnState PhysicalSocket::GetState() const { return state_; } int PhysicalSocket::GetOption(Option opt, int* value) { int slevel; int sopt; if (TranslateOption(opt, &slevel, &sopt) == -1) return -1; socklen_t optlen = sizeof(*value); int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen); if (ret == -1) { return -1; } if (opt == OPT_DONTFRAGMENT) { #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0; #endif } else if (opt == OPT_DSCP) { #if defined(WEBRTC_POSIX) // unshift DSCP value to get six most significant bits of IP DiffServ field *value >>= 2; #endif } return ret; } int PhysicalSocket::SetOption(Option opt, int value) { int slevel; int sopt; if (TranslateOption(opt, &slevel, &sopt) == -1) return -1; if (opt == OPT_DONTFRAGMENT) { #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT; #endif } else if (opt == OPT_DSCP) { #if defined(WEBRTC_POSIX) // shift DSCP value to fit six most significant bits of IP DiffServ field value <<= 2; #endif } #if defined(WEBRTC_POSIX) if (sopt == IPV6_TCLASS) { // Set the IPv4 option in all cases to support dual-stack sockets. ::setsockopt(s_, IPPROTO_IP, IP_TOS, (SockOptArg)&value, sizeof(value)); } #endif return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value)); } int PhysicalSocket::Send(const void* pv, size_t cb) { int sent = DoSend( s_, reinterpret_cast<const char*>(pv), static_cast<int>(cb), #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) // Suppress SIGPIPE. Without this, attempting to send on a socket whose // other end is closed will result in a SIGPIPE signal being raised to // our process, which by default will terminate the process, which we // don't want. By specifying this flag, we'll just get the error EPIPE // instead and can handle the error gracefully. MSG_NOSIGNAL #else 0 #endif ); UpdateLastError(); MaybeRemapSendError(); // We have seen minidumps where this may be false. RTC_DCHECK(sent <= static_cast<int>(cb)); if ((sent > 0 && sent < static_cast<int>(cb)) || (sent < 0 && IsBlockingError(GetError()))) { EnableEvents(DE_WRITE); } return sent; } int PhysicalSocket::SendTo(const void* buffer, size_t length, const SocketAddress& addr) { sockaddr_storage saddr; size_t len = addr.ToSockAddrStorage(&saddr); int sent = DoSendTo(s_, static_cast<const char*>(buffer), static_cast<int>(length), #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) // Suppress SIGPIPE. See above for explanation. MSG_NOSIGNAL, #else 0, #endif reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len)); UpdateLastError(); MaybeRemapSendError(); // We have seen minidumps where this may be false. RTC_DCHECK(sent <= static_cast<int>(length)); if ((sent > 0 && sent < static_cast<int>(length)) || (sent < 0 && IsBlockingError(GetError()))) { EnableEvents(DE_WRITE); } return sent; } int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) { int received = ::recv(s_, static_cast<char*>(buffer), static_cast<int>(length), 0); if ((received == 0) && (length != 0)) { // Note: on graceful shutdown, recv can return 0. In this case, we // pretend it is blocking, and then signal close, so that simplifying // assumptions can be made about Recv. RTC_LOG(LS_WARNING) << "EOF from socket; deferring close event"; // Must turn this back on so that the select() loop will notice the close // event. EnableEvents(DE_READ); SetError(EWOULDBLOCK); return SOCKET_ERROR; } if (timestamp) { *timestamp = GetSocketRecvTimestamp(s_); } UpdateLastError(); int error = GetError(); bool success = (received >= 0) || IsBlockingError(error); if (udp_ || success) { EnableEvents(DE_READ); } if (!success) { RTC_LOG_F(LS_VERBOSE) << "Error = " << error; } return received; } int PhysicalSocket::RecvFrom(void* buffer, size_t length, SocketAddress* out_addr, int64_t* timestamp) { sockaddr_storage addr_storage; socklen_t addr_len = sizeof(addr_storage); sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage); int received = ::recvfrom(s_, static_cast<char*>(buffer), static_cast<int>(length), 0, addr, &addr_len); if (timestamp) { *timestamp = GetSocketRecvTimestamp(s_); } UpdateLastError(); if ((received >= 0) && (out_addr != nullptr)) SocketAddressFromSockAddrStorage(addr_storage, out_addr); int error = GetError(); bool success = (received >= 0) || IsBlockingError(error); if (udp_ || success) { EnableEvents(DE_READ); } if (!success) { RTC_LOG_F(LS_VERBOSE) << "Error = " << error; } return received; } int PhysicalSocket::Listen(int backlog) { int err = ::listen(s_, backlog); UpdateLastError(); if (err == 0) { state_ = CS_CONNECTING; EnableEvents(DE_ACCEPT); #if !defined(NDEBUG) dbg_addr_ = "Listening @ "; dbg_addr_.append(GetLocalAddress().ToString()); #endif } return err; } AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) { // Always re-subscribe DE_ACCEPT to make sure new incoming connections will // trigger an event even if DoAccept returns an error here. EnableEvents(DE_ACCEPT); sockaddr_storage addr_storage; socklen_t addr_len = sizeof(addr_storage); sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage); SOCKET s = DoAccept(s_, addr, &addr_len); UpdateLastError(); if (s == INVALID_SOCKET) return nullptr; if (out_addr != nullptr) SocketAddressFromSockAddrStorage(addr_storage, out_addr); return ss_->WrapSocket(s); } int PhysicalSocket::Close() { if (s_ == INVALID_SOCKET) return 0; int err = ::closesocket(s_); UpdateLastError(); s_ = INVALID_SOCKET; state_ = CS_CLOSED; SetEnabledEvents(0); if (resolver_) { resolver_->Destroy(false); resolver_ = nullptr; } return err; } SOCKET PhysicalSocket::DoAccept(SOCKET socket, sockaddr* addr, socklen_t* addrlen) { return ::accept(socket, addr, addrlen); } int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) { return ::send(socket, buf, len, flags); } int PhysicalSocket::DoSendTo(SOCKET socket, const char* buf, int len, int flags, const struct sockaddr* dest_addr, socklen_t addrlen) { return ::sendto(socket, buf, len, flags, dest_addr, addrlen); } void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) { if (resolver != resolver_) { return; } int error = resolver_->GetError(); if (error == 0) { error = DoConnect(resolver_->address()); } else { Close(); } if (error) { SetError(error); SignalCloseEvent(this, error); } } void PhysicalSocket::UpdateLastError() { SetError(LAST_SYSTEM_ERROR); } void PhysicalSocket::MaybeRemapSendError() { #if defined(WEBRTC_MAC) // https://developer.apple.com/library/mac/documentation/Darwin/ // Reference/ManPages/man2/sendto.2.html // ENOBUFS - The output queue for a network interface is full. // This generally indicates that the interface has stopped sending, // but may be caused by transient congestion. if (GetError() == ENOBUFS) { SetError(EWOULDBLOCK); } #endif } void PhysicalSocket::SetEnabledEvents(uint8_t events) { enabled_events_ = events; } void PhysicalSocket::EnableEvents(uint8_t events) { enabled_events_ |= events; } void PhysicalSocket::DisableEvents(uint8_t events) { enabled_events_ &= ~events; } int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) { switch (opt) { case OPT_DONTFRAGMENT: #if defined(WEBRTC_WIN) *slevel = IPPROTO_IP; *sopt = IP_DONTFRAGMENT; break; #elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__) RTC_LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported."; return -1; #elif defined(WEBRTC_POSIX) *slevel = IPPROTO_IP; *sopt = IP_MTU_DISCOVER; break; #endif case OPT_RCVBUF: *slevel = SOL_SOCKET; *sopt = SO_RCVBUF; break; case OPT_SNDBUF: *slevel = SOL_SOCKET; *sopt = SO_SNDBUF; break; case OPT_NODELAY: *slevel = IPPROTO_TCP; *sopt = TCP_NODELAY; break; case OPT_DSCP: #if defined(WEBRTC_POSIX) if (family_ == AF_INET6) { *slevel = IPPROTO_IPV6; *sopt = IPV6_TCLASS; } else { *slevel = IPPROTO_IP; *sopt = IP_TOS; } break; #else RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported."; return -1; #endif case OPT_RTP_SENDTIME_EXTN_ID: return -1; // No logging is necessary as this not a OS socket option. default: RTC_NOTREACHED(); return -1; } return 0; } SocketDispatcher::SocketDispatcher(PhysicalSocketServer* ss) #if defined(WEBRTC_WIN) : PhysicalSocket(ss), id_(0), signal_close_(false) #else : PhysicalSocket(ss) #endif { } SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer* ss) #if defined(WEBRTC_WIN) : PhysicalSocket(ss, s), id_(0), signal_close_(false) #else : PhysicalSocket(ss, s) #endif { } SocketDispatcher::~SocketDispatcher() { Close(); } bool SocketDispatcher::Initialize() { RTC_DCHECK(s_ != INVALID_SOCKET); // Must be a non-blocking #if defined(WEBRTC_WIN) u_long argp = 1; ioctlsocket(s_, FIONBIO, &argp); #elif defined(WEBRTC_POSIX) fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK); #endif #if defined(WEBRTC_IOS) // iOS may kill sockets when the app is moved to the background // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When // we attempt to write to such a socket, SIGPIPE will be raised, which by // default will terminate the process, which we don't want. By specifying // this socket option, SIGPIPE will be disabled for the socket. int value = 1; ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value)); #endif ss_->Add(this); return true; } bool SocketDispatcher::Create(int type) { return Create(AF_INET, type); } bool SocketDispatcher::Create(int family, int type) { // Change the socket to be non-blocking. if (!PhysicalSocket::Create(family, type)) return false; if (!Initialize()) return false; #if defined(WEBRTC_WIN) do { id_ = ++next_id_; } while (id_ == 0); #endif return true; } #if defined(WEBRTC_WIN) WSAEVENT SocketDispatcher::GetWSAEvent() { return WSA_INVALID_EVENT; } SOCKET SocketDispatcher::GetSocket() { return s_; } bool SocketDispatcher::CheckSignalClose() { if (!signal_close_) return false; char ch; if (recv(s_, &ch, 1, MSG_PEEK) > 0) return false; state_ = CS_CLOSED; signal_close_ = false; SignalCloseEvent(this, signal_err_); return true; } int SocketDispatcher::next_id_ = 0; #elif defined(WEBRTC_POSIX) int SocketDispatcher::GetDescriptor() { return s_; } bool SocketDispatcher::IsDescriptorClosed() { if (udp_) { // The MSG_PEEK trick doesn't work for UDP, since (at least in some // circumstances) it requires reading an entire UDP packet, which would be // bad for performance here. So, just check whether |s_| has been closed, // which should be sufficient. return s_ == INVALID_SOCKET; } // We don't have a reliable way of distinguishing end-of-stream // from readability. So test on each readable call. Is this // inefficient? Probably. char ch; ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK); if (res > 0) { // Data available, so not closed. return false; } else if (res == 0) { // EOF, so closed. return true; } else { // error switch (errno) { // Returned if we've already closed s_. case EBADF: // Returned during ungraceful peer shutdown. case ECONNRESET: return true; // The normal blocking error; don't log anything. case EWOULDBLOCK: // Interrupted system call. case EINTR: return false; default: // Assume that all other errors are just blocking errors, meaning the // connection is still good but we just can't read from it right now. // This should only happen when connecting (and at most once), because // in all other cases this function is only called if the file // descriptor is already known to be in the readable state. However, // it's not necessary a problem if we spuriously interpret a // "connection lost"-type error as a blocking error, because typically // the next recv() will get EOF, so we'll still eventually notice that // the socket is closed. RTC_LOG_ERR(LS_WARNING) << "Assuming benign blocking error"; return false; } } } #endif // WEBRTC_POSIX uint32_t SocketDispatcher::GetRequestedEvents() { return enabled_events(); } void SocketDispatcher::OnPreEvent(uint32_t ff) { if ((ff & DE_CONNECT) != 0) state_ = CS_CONNECTED; #if defined(WEBRTC_WIN) // We set CS_CLOSED from CheckSignalClose. #elif defined(WEBRTC_POSIX) if ((ff & DE_CLOSE) != 0) state_ = CS_CLOSED; #endif } #if defined(WEBRTC_WIN) void SocketDispatcher::OnEvent(uint32_t ff, int err) { int cache_id = id_; // Make sure we deliver connect/accept first. Otherwise, consumers may see // something like a READ followed by a CONNECT, which would be odd. if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) { if (ff != DE_CONNECT) RTC_LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff; DisableEvents(DE_CONNECT); #if !defined(NDEBUG) dbg_addr_ = "Connected @ "; dbg_addr_.append(GetRemoteAddress().ToString()); #endif SignalConnectEvent(this); } if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) { DisableEvents(DE_ACCEPT); SignalReadEvent(this); } if ((ff & DE_READ) != 0) { DisableEvents(DE_READ); SignalReadEvent(this); } if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) { DisableEvents(DE_WRITE); SignalWriteEvent(this); } if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) { signal_close_ = true; signal_err_ = err; } } #elif defined(WEBRTC_POSIX) void SocketDispatcher::OnEvent(uint32_t ff, int err) { #if defined(WEBRTC_USE_EPOLL) // Remember currently enabled events so we can combine multiple changes // into one update call later. // The signal handlers might re-enable events disabled here, so we can't // keep a list of events to disable at the end of the method. This list // would not be updated with the events enabled by the signal handlers. StartBatchedEventUpdates(); #endif // Make sure we deliver connect/accept first. Otherwise, consumers may see // something like a READ followed by a CONNECT, which would be odd. if ((ff & DE_CONNECT) != 0) { DisableEvents(DE_CONNECT); SignalConnectEvent(this); } if ((ff & DE_ACCEPT) != 0) { DisableEvents(DE_ACCEPT); SignalReadEvent(this); } if ((ff & DE_READ) != 0) { DisableEvents(DE_READ); SignalReadEvent(this); } if ((ff & DE_WRITE) != 0) { DisableEvents(DE_WRITE); SignalWriteEvent(this); } if ((ff & DE_CLOSE) != 0) { // The socket is now dead to us, so stop checking it. SetEnabledEvents(0); SignalCloseEvent(this, err); } #if defined(WEBRTC_USE_EPOLL) FinishBatchedEventUpdates(); #endif } #endif // WEBRTC_POSIX #if defined(WEBRTC_USE_EPOLL) static int GetEpollEvents(uint32_t ff) { int events = 0; if (ff & (DE_READ | DE_ACCEPT)) { events |= EPOLLIN; } if (ff & (DE_WRITE | DE_CONNECT)) { events |= EPOLLOUT; } return events; } void SocketDispatcher::StartBatchedEventUpdates() { RTC_DCHECK_EQ(saved_enabled_events_, -1); saved_enabled_events_ = enabled_events(); } void SocketDispatcher::FinishBatchedEventUpdates() { RTC_DCHECK_NE(saved_enabled_events_, -1); uint8_t old_events = static_cast<uint8_t>(saved_enabled_events_); saved_enabled_events_ = -1; MaybeUpdateDispatcher(old_events); } void SocketDispatcher::MaybeUpdateDispatcher(uint8_t old_events) { if (GetEpollEvents(enabled_events()) != GetEpollEvents(old_events) && saved_enabled_events_ == -1) { ss_->Update(this); } } void SocketDispatcher::SetEnabledEvents(uint8_t events) { uint8_t old_events = enabled_events(); PhysicalSocket::SetEnabledEvents(events); MaybeUpdateDispatcher(old_events); } void SocketDispatcher::EnableEvents(uint8_t events) { uint8_t old_events = enabled_events(); PhysicalSocket::EnableEvents(events); MaybeUpdateDispatcher(old_events); } void SocketDispatcher::DisableEvents(uint8_t events) { uint8_t old_events = enabled_events(); PhysicalSocket::DisableEvents(events); MaybeUpdateDispatcher(old_events); } #endif // WEBRTC_USE_EPOLL int SocketDispatcher::Close() { if (s_ == INVALID_SOCKET) return 0; #if defined(WEBRTC_WIN) id_ = 0; signal_close_ = false; #endif #if defined(WEBRTC_USE_EPOLL) // If we're batching events, the socket can be closed and reopened // during the batch. Set saved_enabled_events_ to 0 here so the new // socket, if any, has the correct old events bitfield if (saved_enabled_events_ != -1) { saved_enabled_events_ = 0; } #endif ss_->Remove(this); return PhysicalSocket::Close(); } #if defined(WEBRTC_POSIX) class EventDispatcher : public Dispatcher { public: EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) { if (pipe(afd_) < 0) RTC_LOG(LERROR) << "pipe failed"; ss_->Add(this); } ~EventDispatcher() override { ss_->Remove(this); close(afd_[0]); close(afd_[1]); } virtual void Signal() { CritScope cs(&crit_); if (!fSignaled_) { const uint8_t b[1] = {0}; const ssize_t res = write(afd_[1], b, sizeof(b)); RTC_DCHECK_EQ(1, res); fSignaled_ = true; } } uint32_t GetRequestedEvents() override { return DE_READ; } void OnPreEvent(uint32_t ff) override { // It is not possible to perfectly emulate an auto-resetting event with // pipes. This simulates it by resetting before the event is handled. CritScope cs(&crit_); if (fSignaled_) { uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1. const ssize_t res = read(afd_[0], b, sizeof(b)); RTC_DCHECK_EQ(1, res); fSignaled_ = false; } } void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); } int GetDescriptor() override { return afd_[0]; } bool IsDescriptorClosed() override { return false; } private: PhysicalSocketServer* ss_; int afd_[2]; bool fSignaled_; CriticalSection crit_; }; // These two classes use the self-pipe trick to deliver POSIX signals to our // select loop. This is the only safe, reliable, cross-platform way to do // non-trivial things with a POSIX signal in an event-driven program (until // proper pselect() implementations become ubiquitous). class PosixSignalHandler { public: // POSIX only specifies 32 signals, but in principle the system might have // more and the programmer might choose to use them, so we size our array // for 128. static constexpr int kNumPosixSignals = 128; // There is just a single global instance. (Signal handlers do not get any // sort of user-defined void * parameter, so they can't access anything that // isn't global.) static PosixSignalHandler* Instance() { static PosixSignalHandler* const instance = new PosixSignalHandler(); return instance; } // Returns true if the given signal number is set. bool IsSignalSet(int signum) const { RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_))); if (signum < static_cast<int>(arraysize(received_signal_))) { return received_signal_[signum]; } else { return false; } } // Clears the given signal number. void ClearSignal(int signum) { RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_))); if (signum < static_cast<int>(arraysize(received_signal_))) { received_signal_[signum] = false; } } // Returns the file descriptor to monitor for signal events. int GetDescriptor() const { return afd_[0]; } // This is called directly from our real signal handler, so it must be // signal-handler-safe. That means it cannot assume anything about the // user-level state of the process, since the handler could be executed at any // time on any thread. void OnPosixSignalReceived(int signum) { if (signum >= static_cast<int>(arraysize(received_signal_))) { // We don't have space in our array for this. return; } // Set a flag saying we've seen this signal. received_signal_[signum] = true; // Notify application code that we got a signal. const uint8_t b[1] = {0}; if (-1 == write(afd_[1], b, sizeof(b))) { // Nothing we can do here. If there's an error somehow then there's // nothing we can safely do from a signal handler. // No, we can't even safely log it. // But, we still have to check the return value here. Otherwise, // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help. return; } } private: PosixSignalHandler() { if (pipe(afd_) < 0) { RTC_LOG_ERR(LS_ERROR) << "pipe failed"; return; } if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) { RTC_LOG_ERR(LS_WARNING) << "fcntl #1 failed"; } if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) { RTC_LOG_ERR(LS_WARNING) << "fcntl #2 failed"; } memset(const_cast<void*>(static_cast<volatile void*>(received_signal_)), 0, sizeof(received_signal_)); } ~PosixSignalHandler() { int fd1 = afd_[0]; int fd2 = afd_[1]; // We clobber the stored file descriptor numbers here or else in principle // a signal that happens to be delivered during application termination // could erroneously write a zero byte to an unrelated file handle in // OnPosixSignalReceived() if some other file happens to be opened later // during shutdown and happens to be given the same file descriptor number // as our pipe had. Unfortunately even with this precaution there is still a // race where that could occur if said signal happens to be handled // concurrently with this code and happens to have already read the value of // afd_[1] from memory before we clobber it, but that's unlikely. afd_[0] = -1; afd_[1] = -1; close(fd1); close(fd2); } int afd_[2]; // These are boolean flags that will be set in our signal handler and read // and cleared from Wait(). There is a race involved in this, but it is // benign. The signal handler sets the flag before signaling the pipe, so // we'll never end up blocking in select() while a flag is still true. // However, if two of the same signal arrive close to each other then it's // possible that the second time the handler may set the flag while it's still // true, meaning that signal will be missed. But the first occurrence of it // will still be handled, so this isn't a problem. // Volatile is not necessary here for correctness, but this data _is_ volatile // so I've marked it as such. volatile uint8_t received_signal_[kNumPosixSignals]; }; class PosixSignalDispatcher : public Dispatcher { public: PosixSignalDispatcher(PhysicalSocketServer* owner) : owner_(owner) { owner_->Add(this); } ~PosixSignalDispatcher() override { owner_->Remove(this); } uint32_t GetRequestedEvents() override { return DE_READ; } void OnPreEvent(uint32_t ff) override { // Events might get grouped if signals come very fast, so we read out up to // 16 bytes to make sure we keep the pipe empty. uint8_t b[16]; ssize_t ret = read(GetDescriptor(), b, sizeof(b)); if (ret < 0) { RTC_LOG_ERR(LS_WARNING) << "Error in read()"; } else if (ret == 0) { RTC_LOG(LS_WARNING) << "Should have read at least one byte"; } } void OnEvent(uint32_t ff, int err) override { for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals; ++signum) { if (PosixSignalHandler::Instance()->IsSignalSet(signum)) { PosixSignalHandler::Instance()->ClearSignal(signum); HandlerMap::iterator i = handlers_.find(signum); if (i == handlers_.end()) { // This can happen if a signal is delivered to our process at around // the same time as we unset our handler for it. It is not an error // condition, but it's unusual enough to be worth logging. RTC_LOG(LS_INFO) << "Received signal with no handler: " << signum; } else { // Otherwise, execute our handler. (*i->second)(signum); } } } } int GetDescriptor() override { return PosixSignalHandler::Instance()->GetDescriptor(); } bool IsDescriptorClosed() override { return false; } void SetHandler(int signum, void (*handler)(int)) { handlers_[signum] = handler; } void ClearHandler(int signum) { handlers_.erase(signum); } bool HasHandlers() { return !handlers_.empty(); } private: typedef std::map<int, void (*)(int)> HandlerMap; HandlerMap handlers_; // Our owner. PhysicalSocketServer* owner_; }; #endif // WEBRTC_POSIX #if defined(WEBRTC_WIN) static uint32_t FlagsToEvents(uint32_t events) { uint32_t ffFD = FD_CLOSE; if (events & DE_READ) ffFD |= FD_READ; if (events & DE_WRITE) ffFD |= FD_WRITE; if (events & DE_CONNECT) ffFD |= FD_CONNECT; if (events & DE_ACCEPT) ffFD |= FD_ACCEPT; return ffFD; } class EventDispatcher : public Dispatcher { public: EventDispatcher(PhysicalSocketServer* ss) : ss_(ss) { hev_ = WSACreateEvent(); if (hev_) { ss_->Add(this); } } ~EventDispatcher() override { if (hev_ != nullptr) { ss_->Remove(this); WSACloseEvent(hev_); hev_ = nullptr; } } virtual void Signal() { if (hev_ != nullptr) WSASetEvent(hev_); } uint32_t GetRequestedEvents() override { return 0; } void OnPreEvent(uint32_t ff) override { WSAResetEvent(hev_); } void OnEvent(uint32_t ff, int err) override {} WSAEVENT GetWSAEvent() override { return hev_; } SOCKET GetSocket() override { return INVALID_SOCKET; } bool CheckSignalClose() override { return false; } private: PhysicalSocketServer* ss_; WSAEVENT hev_; }; #endif // WEBRTC_WIN // Sets the value of a boolean value to false when signaled. class Signaler : public EventDispatcher { public: Signaler(PhysicalSocketServer* ss, bool* pf) : EventDispatcher(ss), pf_(pf) {} ~Signaler() override {} void OnEvent(uint32_t ff, int err) override { if (pf_) *pf_ = false; } private: bool* pf_; }; PhysicalSocketServer::PhysicalSocketServer() : fWait_(false) { #if defined(WEBRTC_USE_EPOLL) // Since Linux 2.6.8, the size argument is ignored, but must be greater than // zero. Before that the size served as hint to the kernel for the amount of // space to initially allocate in internal data structures. epoll_fd_ = epoll_create(FD_SETSIZE); if (epoll_fd_ == -1) { // Not an error, will fall back to "select" below. RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create"; epoll_fd_ = INVALID_SOCKET; } #endif signal_wakeup_ = new Signaler(this, &fWait_); #if defined(WEBRTC_WIN) socket_ev_ = WSACreateEvent(); #endif } PhysicalSocketServer::~PhysicalSocketServer() { #if defined(WEBRTC_WIN) WSACloseEvent(socket_ev_); #endif #if defined(WEBRTC_POSIX) signal_dispatcher_.reset(); #endif delete signal_wakeup_; #if defined(WEBRTC_USE_EPOLL) if (epoll_fd_ != INVALID_SOCKET) { close(epoll_fd_); } #endif RTC_DCHECK(dispatchers_.empty()); } void PhysicalSocketServer::WakeUp() { signal_wakeup_->Signal(); } Socket* PhysicalSocketServer::CreateSocket(int family, int type) { PhysicalSocket* socket = new PhysicalSocket(this); if (socket->Create(family, type)) { return socket; } else { delete socket; return nullptr; } } AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) { SocketDispatcher* dispatcher = new SocketDispatcher(this); if (dispatcher->Create(family, type)) { return dispatcher; } else { delete dispatcher; return nullptr; } } AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) { SocketDispatcher* dispatcher = new SocketDispatcher(s, this); if (dispatcher->Initialize()) { return dispatcher; } else { delete dispatcher; return nullptr; } } void PhysicalSocketServer::Add(Dispatcher* pdispatcher) { CritScope cs(&crit_); if (processing_dispatchers_) { // A dispatcher is being added while a "Wait" call is processing the // list of socket events. // Defer adding to "dispatchers_" set until processing is done to avoid // invalidating the iterator in "Wait". pending_remove_dispatchers_.erase(pdispatcher); pending_add_dispatchers_.insert(pdispatcher); } else { dispatchers_.insert(pdispatcher); } #if defined(WEBRTC_USE_EPOLL) if (epoll_fd_ != INVALID_SOCKET) { AddEpoll(pdispatcher); } #endif // WEBRTC_USE_EPOLL } void PhysicalSocketServer::Remove(Dispatcher* pdispatcher) { CritScope cs(&crit_); if (processing_dispatchers_) { // A dispatcher is being removed while a "Wait" call is processing the // list of socket events. // Defer removal from "dispatchers_" set until processing is done to avoid // invalidating the iterator in "Wait". if (!pending_add_dispatchers_.erase(pdispatcher) && dispatchers_.find(pdispatcher) == dispatchers_.end()) { RTC_LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown " "dispatcher, potentially from a duplicate call to " "Add."; return; } pending_remove_dispatchers_.insert(pdispatcher); } else if (!dispatchers_.erase(pdispatcher)) { RTC_LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown " "dispatcher, potentially from a duplicate call to Add."; return; } #if defined(WEBRTC_USE_EPOLL) if (epoll_fd_ != INVALID_SOCKET) { RemoveEpoll(pdispatcher); } #endif // WEBRTC_USE_EPOLL } void PhysicalSocketServer::Update(Dispatcher* pdispatcher) { #if defined(WEBRTC_USE_EPOLL) if (epoll_fd_ == INVALID_SOCKET) { return; } CritScope cs(&crit_); if (dispatchers_.find(pdispatcher) == dispatchers_.end()) { return; } UpdateEpoll(pdispatcher); #endif } void PhysicalSocketServer::AddRemovePendingDispatchers() { if (!pending_add_dispatchers_.empty()) { for (Dispatcher* pdispatcher : pending_add_dispatchers_) { dispatchers_.insert(pdispatcher); } pending_add_dispatchers_.clear(); } if (!pending_remove_dispatchers_.empty()) { for (Dispatcher* pdispatcher : pending_remove_dispatchers_) { dispatchers_.erase(pdispatcher); } pending_remove_dispatchers_.clear(); } } #if defined(WEBRTC_POSIX) bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) { #if defined(WEBRTC_USE_EPOLL) // We don't keep a dedicated "epoll" descriptor containing only the non-IO // (i.e. signaling) dispatcher, so "poll" will be used instead of the default // "select" to support sockets larger than FD_SETSIZE. if (!process_io) { return WaitPoll(cmsWait, signal_wakeup_); } else if (epoll_fd_ != INVALID_SOCKET) { return WaitEpoll(cmsWait); } #endif return WaitSelect(cmsWait, process_io); } static void ProcessEvents(Dispatcher* dispatcher, bool readable, bool writable, bool check_error) { int errcode = 0; // TODO(pthatcher): Should we set errcode if getsockopt fails? if (check_error) { socklen_t len = sizeof(errcode); ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR, &errcode, &len); } uint32_t ff = 0; // Check readable descriptors. If we're waiting on an accept, signal // that. Otherwise we're waiting for data, check to see if we're // readable or really closed. // TODO(pthatcher): Only peek at TCP descriptors. if (readable) { if (dispatcher->GetRequestedEvents() & DE_ACCEPT) { ff |= DE_ACCEPT; } else if (errcode || dispatcher->IsDescriptorClosed()) { ff |= DE_CLOSE; } else { ff |= DE_READ; } } // Check writable descriptors. If we're waiting on a connect, detect // success versus failure by the reaped error code. if (writable) { if (dispatcher->GetRequestedEvents() & DE_CONNECT) { if (!errcode) { ff |= DE_CONNECT; } else { ff |= DE_CLOSE; } } else { ff |= DE_WRITE; } } // Tell the descriptor about the event. if (ff != 0) { dispatcher->OnPreEvent(ff); dispatcher->OnEvent(ff, errcode); } } bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) { // Calculate timing information struct timeval* ptvWait = nullptr; struct timeval tvWait; int64_t stop_us; if (cmsWait != kForever) { // Calculate wait timeval tvWait.tv_sec = cmsWait / 1000; tvWait.tv_usec = (cmsWait % 1000) * 1000; ptvWait = &tvWait; // Calculate when to return stop_us = rtc::TimeMicros() + cmsWait * 1000; } // Zero all fd_sets. Don't need to do this inside the loop since // select() zeros the descriptors not signaled fd_set fdsRead; FD_ZERO(&fdsRead); fd_set fdsWrite; FD_ZERO(&fdsWrite); // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the // inline assembly in FD_ZERO. // http://crbug.com/344505 #ifdef MEMORY_SANITIZER __msan_unpoison(&fdsRead, sizeof(fdsRead)); __msan_unpoison(&fdsWrite, sizeof(fdsWrite)); #endif fWait_ = true; while (fWait_) { int fdmax = -1; { CritScope cr(&crit_); // TODO(jbauch): Support re-entrant waiting. RTC_DCHECK(!processing_dispatchers_); for (Dispatcher* pdispatcher : dispatchers_) { // Query dispatchers for read and write wait state RTC_DCHECK(pdispatcher); if (!process_io && (pdispatcher != signal_wakeup_)) continue; int fd = pdispatcher->GetDescriptor(); // "select"ing a file descriptor that is equal to or larger than // FD_SETSIZE will result in undefined behavior. RTC_DCHECK_LT(fd, FD_SETSIZE); if (fd > fdmax) fdmax = fd; uint32_t ff = pdispatcher->GetRequestedEvents(); if (ff & (DE_READ | DE_ACCEPT)) FD_SET(fd, &fdsRead); if (ff & (DE_WRITE | DE_CONNECT)) FD_SET(fd, &fdsWrite); } } // Wait then call handlers as appropriate // < 0 means error // 0 means timeout // > 0 means count of descriptors ready int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait); // If error, return error. if (n < 0) { if (errno != EINTR) { RTC_LOG_E(LS_ERROR, EN, errno) << "select"; return false; } // Else ignore the error and keep going. If this EINTR was for one of the // signals managed by this PhysicalSocketServer, the // PosixSignalDeliveryDispatcher will be in the signaled state in the next // iteration. } else if (n == 0) { // If timeout, return success return true; } else { // We have signaled descriptors CritScope cr(&crit_); processing_dispatchers_ = true; for (Dispatcher* pdispatcher : dispatchers_) { int fd = pdispatcher->GetDescriptor(); bool readable = FD_ISSET(fd, &fdsRead); if (readable) { FD_CLR(fd, &fdsRead); } bool writable = FD_ISSET(fd, &fdsWrite); if (writable) { FD_CLR(fd, &fdsWrite); } // The error code can be signaled through reads or writes. ProcessEvents(pdispatcher, readable, writable, readable || writable); } processing_dispatchers_ = false; // Process deferred dispatchers that have been added/removed while the // events were handled above. AddRemovePendingDispatchers(); } // Recalc the time remaining to wait. Doing it here means it doesn't get // calced twice the first time through the loop if (ptvWait) { ptvWait->tv_sec = 0; ptvWait->tv_usec = 0; int64_t time_left_us = stop_us - rtc::TimeMicros(); if (time_left_us > 0) { ptvWait->tv_sec = time_left_us / rtc::kNumMicrosecsPerSec; ptvWait->tv_usec = time_left_us % rtc::kNumMicrosecsPerSec; } } } return true; } #if defined(WEBRTC_USE_EPOLL) // Initial number of events to process with one call to "epoll_wait". static const size_t kInitialEpollEvents = 128; // Maximum number of events to process with one call to "epoll_wait". static const size_t kMaxEpollEvents = 8192; void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher) { RTC_DCHECK(epoll_fd_ != INVALID_SOCKET); int fd = pdispatcher->GetDescriptor(); RTC_DCHECK(fd != INVALID_SOCKET); if (fd == INVALID_SOCKET) { return; } struct epoll_event event = {0}; event.events = GetEpollEvents(pdispatcher->GetRequestedEvents()); event.data.ptr = pdispatcher; int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event); RTC_DCHECK_EQ(err, 0); if (err == -1) { RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD"; } } void PhysicalSocketServer::RemoveEpoll(Dispatcher* pdispatcher) { RTC_DCHECK(epoll_fd_ != INVALID_SOCKET); int fd = pdispatcher->GetDescriptor(); RTC_DCHECK(fd != INVALID_SOCKET); if (fd == INVALID_SOCKET) { return; } struct epoll_event event = {0}; int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event); RTC_DCHECK(err == 0 || errno == ENOENT); if (err == -1) { if (errno == ENOENT) { // Socket has already been closed. RTC_LOG_E(LS_VERBOSE, EN, errno) << "epoll_ctl EPOLL_CTL_DEL"; } else { RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL"; } } } void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher) { RTC_DCHECK(epoll_fd_ != INVALID_SOCKET); int fd = pdispatcher->GetDescriptor(); RTC_DCHECK(fd != INVALID_SOCKET); if (fd == INVALID_SOCKET) { return; } struct epoll_event event = {0}; event.events = GetEpollEvents(pdispatcher->GetRequestedEvents()); event.data.ptr = pdispatcher; int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event); RTC_DCHECK_EQ(err, 0); if (err == -1) { RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD"; } } bool PhysicalSocketServer::WaitEpoll(int cmsWait) { RTC_DCHECK(epoll_fd_ != INVALID_SOCKET); int64_t tvWait = -1; int64_t tvStop = -1; if (cmsWait != kForever) { tvWait = cmsWait; tvStop = TimeAfter(cmsWait); } if (epoll_events_.empty()) { // The initial space to receive events is created only if epoll is used. epoll_events_.resize(kInitialEpollEvents); } fWait_ = true; while (fWait_) { // Wait then call handlers as appropriate // < 0 means error // 0 means timeout // > 0 means count of descriptors ready int n = epoll_wait(epoll_fd_, &epoll_events_[0], static_cast<int>(epoll_events_.size()), static_cast<int>(tvWait)); if (n < 0) { if (errno != EINTR) { RTC_LOG_E(LS_ERROR, EN, errno) << "epoll"; return false; } // Else ignore the error and keep going. If this EINTR was for one of the // signals managed by this PhysicalSocketServer, the // PosixSignalDeliveryDispatcher will be in the signaled state in the next // iteration. } else if (n == 0) { // If timeout, return success return true; } else { // We have signaled descriptors CritScope cr(&crit_); for (int i = 0; i < n; ++i) { const epoll_event& event = epoll_events_[i]; Dispatcher* pdispatcher = static_cast<Dispatcher*>(event.data.ptr); if (dispatchers_.find(pdispatcher) == dispatchers_.end()) { // The dispatcher for this socket no longer exists. continue; } bool readable = (event.events & (EPOLLIN | EPOLLPRI)); bool writable = (event.events & EPOLLOUT); bool check_error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP)); ProcessEvents(pdispatcher, readable, writable, check_error); } } if (static_cast<size_t>(n) == epoll_events_.size() && epoll_events_.size() < kMaxEpollEvents) { // We used the complete space to receive events, increase size for future // iterations. epoll_events_.resize(std::max(epoll_events_.size() * 2, kMaxEpollEvents)); } if (cmsWait != kForever) { tvWait = TimeDiff(tvStop, TimeMillis()); if (tvWait < 0) { // Return success on timeout. return true; } } } return true; } bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) { RTC_DCHECK(dispatcher); int64_t tvWait = -1; int64_t tvStop = -1; if (cmsWait != kForever) { tvWait = cmsWait; tvStop = TimeAfter(cmsWait); } fWait_ = true; struct pollfd fds = {0}; int fd = dispatcher->GetDescriptor(); fds.fd = fd; while (fWait_) { uint32_t ff = dispatcher->GetRequestedEvents(); fds.events = 0; if (ff & (DE_READ | DE_ACCEPT)) { fds.events |= POLLIN; } if (ff & (DE_WRITE | DE_CONNECT)) { fds.events |= POLLOUT; } fds.revents = 0; // Wait then call handlers as appropriate // < 0 means error // 0 means timeout // > 0 means count of descriptors ready int n = poll(&fds, 1, static_cast<int>(tvWait)); if (n < 0) { if (errno != EINTR) { RTC_LOG_E(LS_ERROR, EN, errno) << "poll"; return false; } // Else ignore the error and keep going. If this EINTR was for one of the // signals managed by this PhysicalSocketServer, the // PosixSignalDeliveryDispatcher will be in the signaled state in the next // iteration. } else if (n == 0) { // If timeout, return success return true; } else { // We have signaled descriptors (should only be the passed dispatcher). RTC_DCHECK_EQ(n, 1); RTC_DCHECK_EQ(fds.fd, fd); bool readable = (fds.revents & (POLLIN | POLLPRI)); bool writable = (fds.revents & POLLOUT); bool check_error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP)); ProcessEvents(dispatcher, readable, writable, check_error); } if (cmsWait != kForever) { tvWait = TimeDiff(tvStop, TimeMillis()); if (tvWait < 0) { // Return success on timeout. return true; } } } return true; } #endif // WEBRTC_USE_EPOLL static void GlobalSignalHandler(int signum) { PosixSignalHandler::Instance()->OnPosixSignalReceived(signum); } bool PhysicalSocketServer::SetPosixSignalHandler(int signum, void (*handler)(int)) { // If handler is SIG_IGN or SIG_DFL then clear our user-level handler, // otherwise set one. if (handler == SIG_IGN || handler == SIG_DFL) { if (!InstallSignal(signum, handler)) { return false; } if (signal_dispatcher_) { signal_dispatcher_->ClearHandler(signum); if (!signal_dispatcher_->HasHandlers()) { signal_dispatcher_.reset(); } } } else { if (!signal_dispatcher_) { signal_dispatcher_.reset(new PosixSignalDispatcher(this)); } signal_dispatcher_->SetHandler(signum, handler); if (!InstallSignal(signum, &GlobalSignalHandler)) { return false; } } return true; } Dispatcher* PhysicalSocketServer::signal_dispatcher() { return signal_dispatcher_.get(); } bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) { struct sigaction act; // It doesn't really matter what we set this mask to. if (sigemptyset(&act.sa_mask) != 0) { RTC_LOG_ERR(LS_ERROR) << "Couldn't set mask"; return false; } act.sa_handler = handler; #if !defined(__native_client__) // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it // and it's a nuisance. Though some syscalls still return EINTR and there's no // real standard for which ones. :( act.sa_flags = SA_RESTART; #else act.sa_flags = 0; #endif if (sigaction(signum, &act, nullptr) != 0) { RTC_LOG_ERR(LS_ERROR) << "Couldn't set sigaction"; return false; } return true; } #endif // WEBRTC_POSIX #if defined(WEBRTC_WIN) bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) { int64_t cmsTotal = cmsWait; int64_t cmsElapsed = 0; int64_t msStart = Time(); fWait_ = true; while (fWait_) { std::vector<WSAEVENT> events; std::vector<Dispatcher*> event_owners; events.push_back(socket_ev_); { CritScope cr(&crit_); // TODO(jbauch): Support re-entrant waiting. RTC_DCHECK(!processing_dispatchers_); // Calling "CheckSignalClose" might remove a closed dispatcher from the // set. This must be deferred to prevent invalidating the iterator. processing_dispatchers_ = true; for (Dispatcher* disp : dispatchers_) { if (!process_io && (disp != signal_wakeup_)) continue; SOCKET s = disp->GetSocket(); if (disp->CheckSignalClose()) { // We just signalled close, don't poll this socket } else if (s != INVALID_SOCKET) { WSAEventSelect(s, events[0], FlagsToEvents(disp->GetRequestedEvents())); } else { events.push_back(disp->GetWSAEvent()); event_owners.push_back(disp); } } processing_dispatchers_ = false; // Process deferred dispatchers that have been added/removed while the // events were handled above. AddRemovePendingDispatchers(); } // Which is shorter, the delay wait or the asked wait? int64_t cmsNext; if (cmsWait == kForever) { cmsNext = cmsWait; } else { cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed); } // Wait for one of the events to signal DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()), &events[0], false, static_cast<DWORD>(cmsNext), false); if (dw == WSA_WAIT_FAILED) { // Failed? // TODO(pthatcher): need a better strategy than this! WSAGetLastError(); RTC_NOTREACHED(); return false; } else if (dw == WSA_WAIT_TIMEOUT) { // Timeout? return true; } else { // Figure out which one it is and call it CritScope cr(&crit_); int index = dw - WSA_WAIT_EVENT_0; if (index > 0) { --index; // The first event is the socket event Dispatcher* disp = event_owners[index]; // The dispatcher could have been removed while waiting for events. if (dispatchers_.find(disp) != dispatchers_.end()) { disp->OnPreEvent(0); disp->OnEvent(0, 0); } } else if (process_io) { processing_dispatchers_ = true; for (Dispatcher* disp : dispatchers_) { SOCKET s = disp->GetSocket(); if (s == INVALID_SOCKET) continue; WSANETWORKEVENTS wsaEvents; int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents); if (err == 0) { { if ((wsaEvents.lNetworkEvents & FD_READ) && wsaEvents.iErrorCode[FD_READ_BIT] != 0) { RTC_LOG(WARNING) << "PhysicalSocketServer got FD_READ_BIT error " << wsaEvents.iErrorCode[FD_READ_BIT]; } if ((wsaEvents.lNetworkEvents & FD_WRITE) && wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) { RTC_LOG(WARNING) << "PhysicalSocketServer got FD_WRITE_BIT error " << wsaEvents.iErrorCode[FD_WRITE_BIT]; } if ((wsaEvents.lNetworkEvents & FD_CONNECT) && wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) { RTC_LOG(WARNING) << "PhysicalSocketServer got FD_CONNECT_BIT error " << wsaEvents.iErrorCode[FD_CONNECT_BIT]; } if ((wsaEvents.lNetworkEvents & FD_ACCEPT) && wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) { RTC_LOG(WARNING) << "PhysicalSocketServer got FD_ACCEPT_BIT error " << wsaEvents.iErrorCode[FD_ACCEPT_BIT]; } if ((wsaEvents.lNetworkEvents & FD_CLOSE) && wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) { RTC_LOG(WARNING) << "PhysicalSocketServer got FD_CLOSE_BIT error " << wsaEvents.iErrorCode[FD_CLOSE_BIT]; } } uint32_t ff = 0; int errcode = 0; if (wsaEvents.lNetworkEvents & FD_READ) ff |= DE_READ; if (wsaEvents.lNetworkEvents & FD_WRITE) ff |= DE_WRITE; if (wsaEvents.lNetworkEvents & FD_CONNECT) { if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) { ff |= DE_CONNECT; } else { ff |= DE_CLOSE; errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT]; } } if (wsaEvents.lNetworkEvents & FD_ACCEPT) ff |= DE_ACCEPT; if (wsaEvents.lNetworkEvents & FD_CLOSE) { ff |= DE_CLOSE; errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT]; } if (ff != 0) { disp->OnPreEvent(ff); disp->OnEvent(ff, errcode); } } } processing_dispatchers_ = false; // Process deferred dispatchers that have been added/removed while the // events were handled above. AddRemovePendingDispatchers(); } // Reset the network event until new activity occurs WSAResetEvent(socket_ev_); } // Break? if (!fWait_) break; cmsElapsed = TimeSince(msStart); if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) { break; } } // Done return true; } #endif // WEBRTC_WIN } // namespace rtc
; PEPE gerado por 'lcc' (IST: prs 2005, 2009) ; 'rl' serve como frame-pointer e 'r0' como acumulador ; os registos 'r1' a 'r10' sao preservados nas chamadas ; global main ; TEXT main: ; ncalls=5 PUSH r9 PUSH r10 PUSH rl MOV rl, sp ; P_argc EQU 8 ; P_argv EQU 10 MOV r10,L2 PUSH r10 CALL prints ADD sp,2 MOV r10, 10 ADD r10, rl MOV r10,[r10] MOV r10,[r10] PUSH r10 CALL prints ADD sp,2 CALL printLN JMP L4 L3: MOV r10, 10 ADD r10, rl MOV r10,[r10] MOV r10,[r10] PUSH r10 CALL prints ADD sp,2 CALL printLN L4: MOV r10, 10 ADD r10, rl MOV r10,[r10] ADD r10,2 MOV r9, 10 ADD r9, rl MOV [r9],r10 MOV r10,[r10] MOV r9,0 CMP r10,r9 JNE L3 MOV r0, [rl + 8] L1: MOV sp, rl POP rl POP r10 POP r9 RET ; extern printLN ; extern prints ; RODATA L2: STRING "prog = ", 0
; A056526: First differences of Flavius Josephus's sieve. ; Submitted by Jon Maiga ; 2,4,6,6,8,12,10,14,16,12,18,24,14,34,26,16,30,36,18,42,38,12,60,22,48,38,46,36,60,54,44,36,84,22,60,84,18,78,72,60,38,112,12,96,114,26,88,92,34,90,138,26,82,98,112,54,170,36,60,168,52,128,52,128,94,108,90,188,34,72,170,120,46,158,196,20,160,108,176,96,130,108,146,120,100,204,138,50,228,172,30,210,128,142,150,150,114,258,108,114 mov $2,$0 mov $4,2 lpb $4 mov $0,$2 sub $4,1 add $0,$4 trn $0,1 add $0,1 seq $0,960 ; Flavius Josephus's sieve: Start with the natural numbers; at the k-th sieving step, remove every (k+1)-st term of the sequence remaining after the (k-1)-st sieving step; iterate. div $0,2 mov $5,$4 mul $5,$0 add $3,$5 lpe min $2,1 mul $2,$0 mov $0,$3 sub $0,$2 mul $0,2
; A142410: Primes congruent to 37 mod 48. ; Submitted by Jon Maiga ; 37,181,229,277,373,421,613,661,709,757,853,997,1093,1237,1381,1429,1621,1669,1861,2053,2293,2341,2389,2437,2677,2917,3061,3109,3253,3301,3541,3637,3733,3877,4021,4261,4357,4549,4597,4789,4933,5077,5413,5557,5653,5701,5749,6037,6133,6229,6277,6373,6421,6469,6661,6709,6949,6997,7237,7333,7477,7573,7621,7669,7717,8053,8101,8293,8389,8581,8629,8677,8821,9013,9109,9157,9349,9397,9733,9781,9829,9973,10069,10357,10453,10501,10597,10789,10837,11173,11317,11701,11941,12037,12277,12373,12421,12517,12613 mov $1,8 mov $2,$0 add $2,2 pow $2,2 lpb $2 add $1,28 mov $3,$1 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. sub $0,$3 add $1,20 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 sub $2,1 lpe mov $0,$1 add $0,29
<% from pwnlib.shellcraft.powerpc.linux import syscall %> <%page args="set"/> <%docstring> Invokes the syscall sigsuspend. See 'man 2 sigsuspend' for more information. Arguments: set(sigset_t): set </%docstring> ${syscall('SYS_sigsuspend', set)}
; A059421: A diagonal of A059419. ; 16,136,616,2016,5376,12432,25872,49632,89232,152152,248248,390208,594048,879648,1271328,1798464,2496144,3405864,4576264,6063904,7934080,10261680,13132080,16642080,20900880,26031096,32169816,39469696 mov $1,5 add $1,$0 bin $1,$0 mov $2,2 add $2,$0 mul $2,5 add $2,2 mul $1,$2 sub $1,12 div $1,6 mul $1,8 add $1,16
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r15 push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x8be8, %rsi lea addresses_UC_ht+0x4028, %rdi nop nop nop nop nop xor $5675, %r15 mov $24, %rcx rep movsb nop nop xor %r11, %r11 lea addresses_D_ht+0x2f68, %rsi lea addresses_D_ht+0x10624, %rdi clflush (%rdi) nop nop nop xor %r12, %r12 mov $51, %rcx rep movsb nop nop nop nop nop and %rcx, %rcx lea addresses_A_ht+0x1c168, %r11 nop nop nop nop cmp %rdx, %rdx mov (%r11), %r12w nop dec %r15 pop %rsi pop %rdx pop %rdi pop %rcx pop %r15 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r13 push %r15 push %r8 push %r9 push %rax push %rdi push %rsi // Load mov $0x1d04280000000d68, %r15 nop nop nop nop cmp %rax, %rax mov (%r15), %r13w nop nop nop sub $39114, %rsi // Load mov $0x1d04280000000d68, %r9 nop xor $17382, %rdi vmovups (%r9), %ymm7 vextracti128 $1, %ymm7, %xmm7 vpextrq $1, %xmm7, %r15 nop nop nop add $37800, %r13 // Store mov $0x87c, %rdi nop dec %rax mov $0x5152535455565758, %rsi movq %rsi, %xmm1 vmovups %ymm1, (%rdi) nop nop add %rax, %rax // Faulty Load mov $0x1d04280000000d68, %rsi nop nop add %r13, %r13 vmovups (%rsi), %ymm3 vextracti128 $1, %ymm3, %xmm3 vpextrq $0, %xmm3, %r15 lea oracles, %r13 and $0xff, %r15 shlq $12, %r15 mov (%r13,%r15,1), %r15 pop %rsi pop %rdi pop %rax pop %r9 pop %r8 pop %r15 pop %r13 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'size': 2, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_P', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 5, 'same': True}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 1, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 2, 'AVXalign': True, 'NT': False, 'congruent': 9, 'same': True}} {'00': 19238} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A001826: Number of divisors of n of form 4k+1. ; 1,1,1,1,2,1,1,1,2,2,1,1,2,1,2,1,2,2,1,2,2,1,1,1,3,2,2,1,2,2,1,1,2,2,2,2,2,1,2,2,2,2,1,1,4,1,1,1,2,3,2,2,2,2,2,1,2,2,1,2,2,1,3,1,4,2,1,2,2,2,1,2,2,2,3,1,2,2,1,2,3,2,1,2,4,1,2,1,2,4,2,1,2,1,2,1,2,2,3,3,2,2,1,2,4,2,1,2,2,2,2,1,2,2,2,2,4,1,2,2,2,2,2,1,4,3,1,1,2,4,1,2,2,1,4,2,2,2,1,2,2,1,2,2,4,2,3,2,2,3,1,1,4,2,2,2,2,1,2,2,2,3,1,2,4,1,1,2,3,4,3,1,2,2,3,1,2,2,1,4,2,2,2,1,4,2,2,1,4,2,1,1,2,2,4,2,2,3,1,3,2,2,2,2,4,1,3,2,2,4,1,2,2,1,2,2,2,2,2,2,4,2,1,1,6,2,1,2,2,2,4,2,2,4,2,1,2,2,1,2,2,2,3,2,4,2,2,1,2,4 mov $6,$0 mov $8,2 lpb $8,1 clr $0,6 mov $0,$6 sub $8,1 add $0,$8 sub $0,1 lpb $0,1 mov $1,$0 sub $0,1 add $3,4 div $1,$3 add $5,$1 lpe mov $1,$5 mov $9,$8 lpb $9,1 mov $7,$1 sub $9,1 lpe lpe lpb $6,1 mov $6,0 sub $7,$1 lpe mov $1,$7 add $1,1
// // Created by simon on 12/1/20. // #include "Plugin.hpp" #include "Kommunikationsstelle.hpp" void Plugin::print(const std::string &message) { Kommunikationsstelle::gui_print(message); } void Plugin::draw_rect(TGraphicRect rect) { Kommunikationsstelle::gui_draw_rect(rect); } void Plugin::draw_circle(TGraphicCircle circle) { Kommunikationsstelle::gui_draw_circle(circle); } void Plugin::draw_line(TGraphicLine line) { Kommunikationsstelle::gui_draw_line(line); } void Plugin::draw_text(TGraphicText text) { Kommunikationsstelle::gui_draw_text(text); } void Plugin::draw_pixel(TGraphicPixel pixel) { Kommunikationsstelle::gui_draw_pixel(pixel); } void Plugin::clear() { Kommunikationsstelle::gui_clear(); } void Plugin::on_error(int line, const std::string &message) { Kommunikationsstelle::on_error(line, message); } std::string Plugin::get_input_line(){ return Kommunikationsstelle::get_input_line(); }
tilepal 0, GRAY, RED, BROWN, RED, RED, GREEN, GREEN, BROWN tilepal 0, BROWN, BROWN, BROWN, BROWN, GREEN, GREEN, GREEN, GREEN tilepal 0, BROWN, GRAY, BROWN, RED, RED, GREEN, GREEN, BROWN tilepal 0, BROWN, BROWN, BROWN, BROWN, GREEN, GREEN, GREEN, GREEN tilepal 0, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, GREEN tilepal 0, GREEN, BROWN, BROWN, BROWN, GREEN, GREEN, GREEN, GREEN tilepal 0, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, GREEN tilepal 0, GREEN, GREEN, GREEN, BROWN, GREEN, BROWN, BROWN, GREEN tilepal 0, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN tilepal 0, GRAY, BROWN, GRAY, BROWN, BROWN, BROWN, BROWN, BROWN tilepal 0, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN tilepal 0, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN tilepal 0, GRAY, BROWN, BROWN, RED, YELLOW, GREEN, BROWN, YELLOW tilepal 0, YELLOW, BROWN, BROWN, BROWN, GREEN, GREEN, GREEN, GREEN tilepal 0, BROWN, BROWN, BROWN, RED, WATER, BROWN, BROWN, BROWN tilepal 0, BROWN, BROWN, BROWN, BROWN, GREEN, GREEN, GREEN, GREEN tilepal 1, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, GREEN, GREEN tilepal 1, GREEN, BROWN, BROWN, BROWN, GREEN, GREEN, GREEN, GREEN tilepal 1, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, GREEN, GREEN tilepal 1, GREEN, GREEN, GREEN, BROWN, GREEN, BROWN, BROWN, GREEN tilepal 1, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN tilepal 1, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN tilepal 1, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN tilepal 1, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN, BROWN
; A000241: Crossing number of complete graph with n nodes. ; 0,0,0,0,0,1,3,9,18,36,60,100,150 sub $0,1 lpb $0 sub $0,2 mov $1,$2 add $2,$0 mul $1,$2 lpe div $1,4 mov $0,$1