text
stringlengths
1
1.05M
; A097199: Numbers of the form p^4 + 4^p for p prime. ; Submitted by Christian Krause ; 32,145,1649,18785,4208945,67137425,17179952705,274878037265,70368744457505,288230376152419025,4611686018428311425,18889465931478582728945,4835703278458516701650465 seq $0,40 ; The prime numbers. seq $0,1589 ; a(n) = 4^n + n^4.
;/* ; * FreeRTOS Kernel V10.4.1 ; * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. ; * ; * 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. ; * ; * https://www.FreeRTOS.org ; * https://github.com/FreeRTOS ; * ; * 1 tab == 4 spaces! ; */ .extern pxCurrentTCB .extern vTaskSwitchContext .extern ulMaxSyscallInterruptPriorityConst .global _vector_14 .global _lc_ref__vector_pp_14 .global SVC_Handler .global vPortStartFirstTask .global vPortEnableVFP .global ulPortSetInterruptMask .global vPortClearInterruptMask ;----------------------------------------------------------- .section .text .thumb .align 4 _vector_14: .type func mrs r0, psp isb ;Get the location of the current TCB. ldr.w r3, =pxCurrentTCB ldr r2, [r3] ;Is the task using the FPU context? If so, push high vfp registers. tst r14, #0x10 it eq vstmdbeq r0!, {s16-s31} ;Save the core registers. stmdb r0!, {r4-r11, r14} ;Save the new top of stack into the first member of the TCB. str r0, [r2] stmdb sp!, {r0, r3} ldr.w r0, =ulMaxSyscallInterruptPriorityConst ldr r0, [r0] msr basepri, r0 bl vTaskSwitchContext mov r0, #0 msr basepri, r0 ldmia sp!, {r0, r3} ;The first item in pxCurrentTCB is the task top of stack. ldr r1, [r3] ldr r0, [r1] ;Pop the core registers. ldmia r0!, {r4-r11, r14} ;Is the task using the FPU context? If so, pop the high vfp registers too. tst r14, #0x10 it eq vldmiaeq r0!, {s16-s31} msr psp, r0 isb bx r14 .size _vector_14, $-_vector_14 .endsec ;----------------------------------------------------------- ; This function is an XMC4000 silicon errata workaround. It will get used when ; the SILICON_BUG_PMC_CM_001 linker macro is defined. .section .text .thumb .align 4 _lc_ref__vector_pp_14: .type func mrs r0, psp isb ;Get the location of the current TCB. ldr.w r3, =pxCurrentTCB ldr r2, [r3] ;Is the task using the FPU context? If so, push high vfp registers. tst r14, #0x10 it eq vstmdbeq r0!, {s16-s31} ;Save the core registers. stmdb r0!, {r4-r11, r14} ;Save the new top of stack into the first member of the TCB. str r0, [r2] stmdb sp!, {r3} ldr.w r0, =ulMaxSyscallInterruptPriorityConst ldr r0, [r0] msr basepri, r0 bl vTaskSwitchContext mov r0, #0 msr basepri, r0 ldmia sp!, {r3} ;The first item in pxCurrentTCB is the task top of stack. ldr r1, [r3] ldr r0, [r1] ;Pop the core registers. ldmia r0!, {r4-r11, r14} ;Is the task using the FPU context? If so, pop the high vfp registers too. tst r14, #0x10 it eq vldmiaeq r0!, {s16-s31} msr psp, r0 isb push { lr } pop { pc } ; XMC4000 specific errata workaround. Do not used "bx lr" here. .size _lc_ref__vector_pp_14, $-_lc_ref__vector_pp_14 .endsec ;----------------------------------------------------------- .section .text .thumb .align 4 SVC_Handler: .type func ;Get the location of the current TCB. ldr.w r3, =pxCurrentTCB ldr r1, [r3] ldr r0, [r1] ;Pop the core registers. ldmia r0!, {r4-r11, r14} msr psp, r0 isb mov r0, #0 msr basepri, r0 bx r14 .size SVC_Handler, $-SVC_Handler .endsec ;----------------------------------------------------------- .section .text .thumb .align 4 vPortStartFirstTask .type func ;Use the NVIC offset register to locate the stack. ldr.w r0, =0xE000ED08 ldr r0, [r0] ldr r0, [r0] ;Set the msp back to the start of the stack. msr msp, r0 ;Call SVC to start the first task. cpsie i cpsie f dsb isb svc 0 .size vPortStartFirstTask, $-vPortStartFirstTask .endsec ;----------------------------------------------------------- .section .text .thumb .align 4 vPortEnableVFP .type func ;The FPU enable bits are in the CPACR. ldr.w r0, =0xE000ED88 ldr r1, [r0] ;Enable CP10 and CP11 coprocessors, then save back. orr r1, r1, #( 0xf << 20 ) str r1, [r0] bx r14 .size vPortEnableVFP, $-vPortEnableVFP .endsec ;----------------------------------------------------------- .section .text .thumb .align 4 ulPortSetInterruptMask: mrs r0, basepri ldr.w r1, =ulMaxSyscallInterruptPriorityConst ldr r1, [r1] msr basepri, r1 bx r14 .size ulPortSetInterruptMask, $-ulPortSetInterruptMask .endsec ;----------------------------------------------------------- .section .text .thumb .align 4 vPortClearInterruptMask: msr basepri, r0 bx r14 .size vPortClearInterruptMask, $-vPortClearInterruptMask .endsec ;----------------------------------------------------------- .end
bits 64 org 0x8005000 section .text global _start _start: FB equ 0x8003000 + 56 FBS equ 0x8003000 + 64 jmp begin dw 0 dd 1 dd 2 dd 3 dd 4 dd 5 dd 6 dd 7 begin: mov r8, 0x1111BBBB66660000 mov rcx, [FB] mov rax, [FBS] Q: sub rax, 8 mov [rcx+rax],r8 jnz Q jmp $
/* -------------------------------------------------------------------------------- Name: BayesianTracker Purpose: A multi object tracking library, specifically used to reconstruct tracks in crowded fields. Here we use a probabilistic network of information to perform the trajectory linking. This method uses positional and visual information for track linking. Authors: Alan R. Lowe (arl) a.lowe@ucl.ac.uk License: See LICENSE.md Created: 14/08/2014 -------------------------------------------------------------------------------- */ #include "tracker.h" // we can assume that the covar matrix is diagonal from the MotionModel // since only position obeservations are made, therefore we can decompose // multivariate gaussian into product of univariate gaussians // http://cs229.stanford.edu/section/gaussians.pdf double cheat_trivariate_PDF(const Eigen::Vector3d& x, Prediction p) { double prob_density = (1./(kRootTwoPi*sqrt(p.covar(0,0)))) * exp(-(1./(2.*p.covar(0,0))) * (x(0)-p.mu(0)) * (x(0)-p.mu(0)) ) * (1./(kRootTwoPi*sqrt(p.covar(1,1)))) * exp(-(1./(2.*p.covar(1,1))) * (x(1)-p.mu(1)) * (x(1)-p.mu(1)) ) * (1./(kRootTwoPi*sqrt(p.covar(2,2)))) * exp(-(1./(2.*p.covar(2,2))) * (x(2)-p.mu(2)) * (x(2)-p.mu(2)) ); return prob_density; } // we can assume that the covar matrix is diagonal from the MotionModel // since only position observations are made, therefore we can decompose // multivariate gaussian into product of univariate gaussians // http://cs229.stanford.edu/section/gaussians.pdf // also we need to calculate the probability (the integral), so we use erf // http://en.cppreference.com/w/cpp/numeric/math/erf double probability_erf( const Eigen::Vector3d& x, const Prediction p, const double accuracy=2. ) { double phi = 1.; double phi_x, std_x, d_x; for (unsigned int axis=0; axis<3; axis++) { std_x = std::sqrt(p.covar(axis,axis)); d_x = x(axis)-p.mu(axis); // intergral +/- accuracy phi_x = std::erf((d_x+accuracy) / (std_x*kRootTwo)) - std::erf((d_x-accuracy) / (std_x*kRootTwo)); // calculate product of integrals for the axes i.e. joint probability? phi *= .5*phi_x; } // we don't want a NaN! assert(!std::isnan(phi)); return phi; } void write_belief_matrix_to_CSV(std::string a_filename, Eigen::Ref<Eigen::MatrixXd> a_belief) { std::cout << a_filename << std::endl; std::ofstream belief_file; belief_file.open(a_filename); belief_file << a_belief.format(CSVFormat); belief_file.close(); } // BayesianTracker::BayesianTracker(const bool verbose) { // // default behaviour is to use exact updates // BayesianTracker(verbose, UPDATE_MODE_EXACT); // } // set up the tracker using an existing track manager BayesianTracker::BayesianTracker(const bool verbose, const unsigned int update_mode) { // set up verbosity this->verbose = verbose; // set up the tracks this->tracks = TrackManager(); // NOTE(arl): This isn't really necessary // set up the frame map frames.clear(); // set the current frame to zero current_frame = 0; // reserve some space for the tracks active.reserve(RESERVE_ACTIVE_TRACKS); new_objects.reserve(RESERVE_NEW_OBJECTS); // set the appropriate cost function set_update_mode(update_mode); } BayesianTracker::~BayesianTracker() { //std::cout << "Destruction of BayesianTracker" << std::endl; // clean up gracefully } void BayesianTracker::set_update_mode(const unsigned int update_mode) { cost_function_mode = update_mode; if (DEBUG) std::cout << "Update mode: " << cost_function_mode << std::endl; } unsigned int BayesianTracker::set_motion_model( const unsigned int measurements, const unsigned int states, double* A_raw, double* H_raw, double* P_raw, double* Q_raw, double* R_raw, const double dt, const double accuracy, const unsigned int max_lost, const double prob_not_assign) { // do some error checking if (prob_not_assign<=0. || prob_not_assign>=1.) return ERROR_prob_not_assign_out_of_range; if (max_lost>10) return ERROR_max_lost_out_of_range; if (accuracy<0. || accuracy>10.) return ERROR_accuracy_out_of_range; this->max_lost = max_lost; this->prob_not_assign = prob_not_assign; this->accuracy = accuracy; if (verbose && DEBUG) { std::cout << "MAX_LOST: " << this->max_lost << std::endl; std::cout << "ACCURACY: " << this->accuracy << std::endl; std::cout << "PROB_NOT_ASSIGN: " << this->prob_not_assign << std::endl; } typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMajMat; // map the arrays to Eigen matrices Eigen::MatrixXd H = Eigen::Map<RowMajMat>(H_raw, measurements, states); Eigen::MatrixXd Q = Eigen::Map<RowMajMat>(Q_raw, states, states); Eigen::MatrixXd P = Eigen::Map<RowMajMat>(P_raw, states, states); Eigen::MatrixXd R = Eigen::Map<RowMajMat>(R_raw, measurements, measurements); Eigen::MatrixXd A = Eigen::Map<RowMajMat>(A_raw, states, states); //set up a new motion model motion_model = MotionModel( A, H, P, R, Q ); return SUCCESS; } unsigned int BayesianTracker::append(const PyTrackObject& new_object){ // take a vector of TrackObjects as input and perform the tracking step // from the PyTrackObject create a track object with a shared pointer. // This will be stored TrackObjectPtr p = std::make_shared<TrackObject>(new_object); // NOTE: THIS IS PROBABLY UNNECESSARY UNTIL WE RETURN PyTrackObjects... // p->original_object = &new_object; // update the imaging volume with this new measurement volume.update(p); // add a new object and maintain a set of frame numbers... objects.push_back( p ); frames_set.insert( p->t ); // set this flag to true // initialised = true; return SUCCESS; } // track all objects void BayesianTracker::track_all() { if (statistics.complete) { statistics.error = ERROR_no_tracks; } // iterate over the whole set while (!statistics.complete){ step(); } } // initialise the first frame unsigned int BayesianTracker::initialise() { // if we have already initialised, return early if (initialised) return SUCCESS; // check to make sure that we've got some objects to track if (objects.empty()) { if (verbose) { std::cout << "Object queue is empty. " << std::endl; } return ERROR_empty_queue; } if (!tracks.empty()) { if (verbose) { std::cout << "Tracking has already been performed. " << std::endl; } return ERROR_no_tracks; } // sort the objects vector by time std::sort( objects.begin(), objects.end(), compare_obj_time ); // NOTE: should check that we have some frames which can be tracked // start by converting the set to a vector std::vector<unsigned int> f(frames_set.begin(), frames_set.end()); frames = f; bool useable_frames = false; for (size_t n=1; n<frames.size(); n++) { if ( (frames[n] - frames[n-1]) <= max_lost) { useable_frames = true; continue; } } if (!useable_frames) { if (verbose) { std::cout << "No trackable frames have been found. " << std::endl; } return ERROR_no_useable_frames; } if (verbose && DEBUG) { std::cout << "FRAME RANGE: " << frames.front() << "-" << frames.back(); std::cout << std::endl; } // get the number of objects and a counter to the first object n_objects = objects.size(); o_counter = 0; // set the current frame of the tracker current_frame = frames.front(); // set up the first tracklets based on the first set of objects while ( objects[o_counter]->t == current_frame && o_counter != n_objects-1 ) { // add a new tracklet TrackletPtr trk = std::make_shared<Tracklet>( get_new_ID(), objects[o_counter], max_lost, this->motion_model ); tracks.push_back( trk ); o_counter++; } // add one to the iteration current_frame++; // set the initialised flag initialised = true; return SUCCESS; } // update the tracker by some number of steps void BayesianTracker::step(const unsigned int steps) { // make sure that we have steps greater than zero // assert(steps>0); if (steps < 1) return; // reset the step counter unsigned int step = 0; // first check the iteration, if it is zero, initialise // TODO(arl): we don't necessarily start on frame zero? //if (current_frame == 0) { if (!initialised) { // initialise! unsigned int ret = initialise(); if ( ret != SUCCESS ) { // return the error in a statistics structure statistics.error = ret; return; } // take a step //step++; } while (step < steps && current_frame <= frames.back()) { // update the list of active tracks update_active(); // clear the list of objects new_objects.clear(); // std::cout << "Full Frame: " << current_frame << std::endl; // loop over all tracks found in this frame if (o_counter < n_objects) { while (objects[o_counter]->t == current_frame) { // store a reference to this object new_objects.push_back( objects[o_counter] ); o_counter++; // make sure our iterator doesn't run off the end of the vector if (o_counter >= n_objects) { break; } } } // set up some counters size_t n_active = active.size(); size_t n_obs = new_objects.size(); // if we have an empty frame, append dummies to everthing and continue if (new_objects.empty()) { //std::cout << "Frame " << current_frame << " is empty..." << std::endl; for (size_t i=0; i<n_active; i++) { active[i]->append_dummy(); } step++; current_frame++; continue; } // make some space for the belief matrix Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> belief; // now do the Bayesian updates belief.setZero(n_obs+1, n_active); // now do the Bayesian updates using the correct mode //switch(cost_function_mode) { if (cost_function_mode == UPDATE_MODE_EXACT) { cost_EXACT(belief, n_active, n_obs); } else if (cost_function_mode == UPDATE_MODE_APPROXIMATE) { cost_APPROXIMATE(belief, n_active, n_obs); } else if (cost_function_mode == UPDATE_MODE_CUDA) { throw std::runtime_error("CUDA update method not supported"); //cost_CUDA(belief, n_active, n_obs); } else { throw std::runtime_error("Update method not supported"); } // use an implicit function pointer call to the appropriate cost function // cost_function_ptr(belief, n_active, n_obs); //(this->*cost_function_ptr)(belief, n_active, n_obs); // now that we have the complete belief matrix, we want to associate // do naive linking link(belief, n_active, n_obs); // update the iteration counter step++; current_frame++; } // have we finished? if (current_frame >= frames.back()) { statistics.complete = true; //clean(); tracks.finalise(); } //return statistics; } bool BayesianTracker::update_active() { // TODO: MAKE INTERMEDIATE LIST OF TRACKS TO MINIMISE LOOPING OVER EVERYTHING // clear the active list active.clear(); for (size_t i=0, trks_size=tracks.size(); i<trks_size; i++) { // check to see whether we have exceeded the bounds if (!volume.inside( tracks[i]->position() )) { tracks[i]->set_lost(); continue; } // if the track is still active, add it to the update list if (tracks[i]->active()) { active.push_back( tracks[i] ); } else { tracks[i]->trim(); // remove dummies if this track is lost } } return true; } void BayesianTracker::debug_output(const unsigned int frm) const { // std::cout << "Tracking objects in Frames " << frm-100 << "-" << frm; // std::cout << "... " << std::endl; // std::cout << " > Currently tracking " << active.size(); // std::cout << " objects..." << std::endl; // std::cout << " - Lost " << num_lost << " tracks for greater than "; // std::cout << max_lost << " frames. Removing..." << std::endl; // std::cout << " + Started " << tracks.size()-active.size(); // std::cout << " new tracklets..." << std::endl; // std::cout << " ~ Found " << num_conflicts << " conflicts..." << std::endl; } // make the cost matrix of all possible linkages void BayesianTracker::cost_EXACT(Eigen::Ref<Eigen::MatrixXd> belief, const size_t n_tracks, const size_t n_objects) { // start a timer std::clock_t t_update_start = std::clock(); // set up some variables for Bayesian updates Prediction trk_prediction; double prob_assign = 0.; double uniform_prior = 1. / (n_objects+1); //double uniform_prior = (1.-DEFAULT_LOST_PROBABILITY) / (n_objects); double prior_assign, PrDP, posterior, update; // set the uniform prior belief.fill(uniform_prior); // // set the lost probability // Eigen::VectorXd v_lost_probability = Eigen::VectorXd(n_tracks); // v_lost_probability.fill(DEFAULT_LOST_PROBABILITY); // belief.row(n_objects) = v_lost_probability; // Posterior is a misnoma here because it is initially the prior, but // becomes the posterior Eigen::VectorXd v_posterior; Eigen::VectorXd v_update = Eigen::VectorXd(n_objects+1); // if (WRITE_BELIEF_MATRIX) { // unsigned int belief_idx = 0; // } for (size_t trk=0; trk != n_tracks; trk++) { // get the trk prediction trk_prediction = active[trk]->predict(); // make space for the update // v_posterior = belief.col(trk); v_posterior = belief.col(trk); // loop through each candidate object for (size_t obj=0; obj != n_objects; obj++) { // calculate the probability that this is the correct track prob_assign = probability_erf(new_objects[obj]->position(), trk_prediction, this->accuracy); // set the probability of assignment to zero if the track is currently // in a metaphase state and the object to link to is anaphase if (DISALLOW_METAPHASE_ANAPHASE_LINKING) { if (active[trk]->track.back()->label == STATE_metaphase && new_objects[obj]->label == STATE_anaphase) { // set the probability of assignment to zero prob_assign = 0.0; } } // disallow incorrect linking if (DISALLOW_PROMETAPHASE_ANAPHASE_LINKING) { if (active[trk]->track.back()->label == STATE_prometaphase && new_objects[obj]->label == STATE_anaphase) { // set the probability of assignment to zero prob_assign = 0.0; } } if (PROB_ASSIGN_EXP_DECAY) { // apply an exponential decay according to number of lost // drops to 50% at max lost double a = std::pow(2, -(double)active[trk]->lost/(double)max_lost); prob_assign = a*prob_assign; } // now do the bayesian updates // prior_assign = v_posterior(obj); prior_assign = v_posterior(obj); PrDP = prob_assign * prior_assign + prob_not_assign * (1.-prob_assign); posterior = (prob_assign * (prior_assign / PrDP)); update = (1. + (prior_assign-posterior)/(1.-prior_assign)); v_update.fill(update); v_update(obj) = 1.; // this means the posterior at obj will not be updated? // do the update v_posterior = v_posterior.array()*v_update.array(); v_posterior(obj) = posterior; // if (WRITE_BELIEF_MATRIX && current_frame == 10) { // belief.col(trk) = v_posterior; // std::stringstream belief_filename; // belief_filename << "/media/quantumjot/Data/belief/belief_"; // belief_filename << belief_idx << ".csv"; // write_belief_matrix_to_CSV(belief_filename.str(), belief); // belief_idx++; // } } // now update the entire column (i.e. track) //belief.col(trk) = belief.col(trk).cwiseProduct( v_posterior ); belief.col(trk) = v_posterior; } // set the timings double t_elapsed_ms = (std::clock() - t_update_start) / (double) (CLOCKS_PER_SEC / 1000); statistics.t_update_belief = static_cast<float>(t_elapsed_ms); } // make the cost matrix of all possible linkages void BayesianTracker::cost_APPROXIMATE(Eigen::Ref<Eigen::MatrixXd> belief, const size_t n_tracks, const size_t n_objects) { // start a timer std::clock_t t_update_start = std::clock(); // set up some variables for Bayesian updates Prediction trk_prediction; double prob_assign = 0.; //double uniform_prior = 1. / (n_objects+1); double prior_assign, PrDP, posterior, update; // set the uniform prior //belief.fill(uniform_prior); belief.fill(0.); // we will update the priors on-the-fly here // Posterior is a misnoma here because it is initially the prior, but // becomes the posterior Eigen::VectorXd v_posterior; Eigen::VectorXd v_update = Eigen::VectorXd(n_objects+1); // make a bin map of the objects ObjectBin m_cube = ObjectBin(max_search_radius, 1); for (size_t obj=0; obj != n_objects; obj++) { m_cube.add_object(new_objects[obj]); } // iterate over the tracks for (size_t trk=0; trk != n_tracks; trk++) { // get the trk prediction trk_prediction = active[trk]->predict(); // make space for the update // v_posterior = belief.col(trk); v_posterior = belief.col(trk); // get the local objects for updating std::vector<TrackObjectPtr_and_Index> local_objects; local_objects = m_cube.get(active[trk], false); size_t n_local_objects = local_objects.size(); // if there are no local objects, then this track is lost if (n_local_objects < 1){ v_posterior.fill(0.0); // all objects have zero probability v_posterior(n_objects) = 1.0; // the lost probability is one belief.col(trk) = v_posterior; continue; } // TODO(arl): // now that we know which local updates are to be made, approximate all of // the updates that we would have made, set the prior probabilities // // calculate the local uniform prior for only those objects that we have // selected the local objects double local_uniform_prior = 1. / (n_local_objects+1); // double local_uniform_prior = (1.-DEFAULT_LOST_PROBABILITY) / n_local_objects; // std::cout << trk << " --> " << n_local_objects << " (" << local_uniform_prior << ")" <<std::endl; for (size_t obj=0; obj != n_local_objects; obj++) { v_posterior(local_objects[obj].second) = local_uniform_prior; } // set the lost prior also v_posterior(n_objects) = local_uniform_prior; // loop through each candidate object for (size_t obj=0; obj != n_local_objects; obj++) { // calculate the probability that this is the correct track prob_assign = probability_erf(local_objects[obj].first->position(), trk_prediction, this->accuracy); // set the probability of assignment to zero if the track is currently // in a metaphase state and the object to link to is anaphase if (DISALLOW_METAPHASE_ANAPHASE_LINKING) { if (active[trk]->track.back()->label == STATE_metaphase && local_objects[obj].first->label == STATE_anaphase) { // set the probability of assignment to zero prob_assign = 0.0; } } // disallow incorrect linking if (DISALLOW_PROMETAPHASE_ANAPHASE_LINKING) { if (active[trk]->track.back()->label == STATE_prometaphase && local_objects[obj].first->label == STATE_anaphase) { // set the probability of assignment to zero prob_assign = 0.0; } } if (PROB_ASSIGN_EXP_DECAY) { // apply an exponential decay according to number of lost // drops to 50% at max lost double a = std::pow(2, -(double)active[trk]->lost/(double)max_lost); prob_assign = a*prob_assign; } // now do the bayesian updates // prior_assign = v_posterior(obj); prior_assign = v_posterior(local_objects[obj].second); PrDP = prob_assign * prior_assign + prob_not_assign * (1.-prob_assign); posterior = (prob_assign * (prior_assign / PrDP)); update = (1. + (prior_assign-posterior)/(1.-prior_assign)); v_update.fill(update); // NOTE(arl): Is this necessary? v_update(local_objects[obj].second) = 1.; // this means the posterior at obj will not be updated? // do the update v_posterior = v_posterior.array()*v_update.array(); v_posterior(local_objects[obj].second) = posterior; } // objects // now update the entire column (i.e. track) //belief.col(trk) = belief.col(trk).cwiseProduct( v_posterior ); belief.col(trk) = v_posterior; } // set the timings double t_elapsed_ms = (std::clock() - t_update_start) / (double) (CLOCKS_PER_SEC / 1000); statistics.t_update_belief = static_cast<float>(t_elapsed_ms); } // make the cost matrix of all possible linkages void BayesianTracker::link(Eigen::Ref<Eigen::MatrixXd> belief, const size_t n_tracks, const size_t n_objects ) { // start a timer std::clock_t t_update_start = std::clock(); // set up some space for used objects std::set<unsigned int> not_used; for (size_t i=0; i<n_tracks; i++) { not_used.insert(not_used.end(), i); } // make a track map HypothesisMap<LinkHypothesis> map = HypothesisMap<LinkHypothesis>(n_objects); for (size_t trk=0; trk<n_tracks; trk++) { // get the object with the best match for this track... Eigen::MatrixXf::Index best_object; double prob = belief.col(trk).maxCoeff(&best_object); // since we're using zero-indexing, n_objects is equivalent to the index of // the last object + 1, i.e. the column for the lost hypothesis... if (int(best_object) != int(n_objects)) { // push this putative linkage to the map map.push( best_object, LinkHypothesis(trk, prob) ); } else { // this track is probably lost, append a dummy to the trajectory active[trk]->append_dummy(); not_used.erase(trk); n_lost++; // update the statistics statistics.p_lost = prob; } } // now loop through the map for (size_t obj=0, map_size=map.size(); obj<map_size; obj++) { unsigned int n_links = map[obj].size(); // this is a direct correspondence, make the mapping if (n_links == 1) { // std::cout << map[trk].size() << std::endl; LinkHypothesis lnk = map[obj][0]; unsigned int trk = lnk.first; if (not_used.count(trk) < 1) { // TODO(arl): make this error more useful std::cout << "ERROR: Exhausted potential linkages." << std::endl; } // make sure that we only make links that are possible if (euclidean_dist(active[trk], new_objects[obj]) > max_search_radius && CLIP_MAXIMUM_LINKAGE_DISTANCE) { continue; } // append the new object onto the track active[trk]->append( new_objects[obj] ); // update the statistics statistics.p_link = lnk.second; // since we've found a correspondence for this one, remove from set not_used.erase(trk); } else if (n_links < 1) { // this object has no matches, add a new tracklet TrackletPtr trk = std::make_shared<Tracklet>( get_new_ID(), new_objects[obj], max_lost, this->motion_model ); tracks.push_back( trk ); } else if (n_links > 1) { // conflict, get the best one n_conflicts++; unsigned int trk; double prob = -1.; for (size_t i=0; i<n_links; i++) { if (map[obj][i].second > prob) { prob = map[obj][i].second; trk = map[obj][i].first; } } if (not_used.count(trk) < 1) { // TODO(arl): make this error more useful std::cout << "ERROR: Exhausted potential linkages." << std::endl; } // make sure that we only make links that are possible if (euclidean_dist(active[trk], new_objects[obj]) > max_search_radius && CLIP_MAXIMUM_LINKAGE_DISTANCE) { continue; } // update only this one active[trk]->append( new_objects[obj] ); // since we've found a correspondence for this one, remove from set not_used.erase(trk); } } // get a vector of updates std::vector<unsigned int> to_update(not_used.begin(), not_used.end()); for (size_t i=0, update_size=to_update.size(); i<update_size; i++) { // update these tracks active[ to_update[i] ]->append_dummy(); } // set the timings double t_elapsed_ms = (std::clock() - t_update_start) / (double) (CLOCKS_PER_SEC / 1000); statistics.t_update_link = static_cast<float>(t_elapsed_ms); // update the statistics statistics.n_active = n_tracks; statistics.n_lost = n_lost; statistics.n_conflicts = n_conflicts; statistics.n_tracks = this->size(); } int main(int, char**) { // // BayesianTracker b; }
; A037632: Base 4 digits are, in order, the first n terms of the periodic sequence with initial period 2,1,3. ; 2,9,39,158,633,2535,10142,40569,162279,649118,2596473,10385895,41543582,166174329,664697319,2658789278,10635157113,42540628455,170162513822,680650055289,2722600221159,10890400884638,43561603538553,174246414154215,696985656616862,2787942626467449 mov $1,4 pow $1,$0 mul $1,52 div $1,21
; A122587: Leading digit of n in base 4. ; 1,2,3,1,1,1,1,2,2,2,2,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 add $0,1 lpb $0,$0 div $0,4 lpe mov $1,$0
SECTION rodata_clib PUBLIC standard_font PUBLIC _standard_font standard_font: _standard_font: BINARY "target/sms/FONT8.BIN"
; A294919: Numbers n such that 2^(n-1), (2*n-1)*(2^((n-1)/2)), (4*ceiling((1/4)*n)-2), and (2^((n+1)/2) + floor((3/4)*n)*2^(((n+1)/2)+1)) are all congruent to 1 (mod n). ; Submitted by Jon Maiga ; 5,13,29,37,53,61,101,109,149,157,173,181,197,229,269,277,293,317,349,373,389,397,421,461,509,541,557,613,653,661,677,701,709,733,757,773,797,821,829,853,877,941,997,1013,1021,1061,1069,1093,1109,1117,1181,1213 mov $1,4 mov $2,$0 pow $2,2 lpb $2 mov $3,$1 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. sub $0,$3 add $1,8 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 sub $2,1 lpe mov $0,$1 add $0,1
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. 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 copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************************************************/ #ifndef MODEL_GASEQUIPMENTDEFINITION_HPP #define MODEL_GASEQUIPMENTDEFINITION_HPP #include "ModelAPI.hpp" #include "SpaceLoadDefinition.hpp" namespace openstudio { namespace model { namespace detail { class GasEquipmentDefinition_Impl; } // detail /** GasEquipmentDefinition is a SpaceLoadDefinition that wraps the OpenStudio IDD object * 'OS_GasEquipment_Definition'. Its fields are derived from the EnergyPlus IDD object * 'GasEquipment'. \sa GasEquipmentDefinition */ class MODEL_API GasEquipmentDefinition : public SpaceLoadDefinition { public: /** @name Constructors and Destructors */ //@{ explicit GasEquipmentDefinition(const Model& model); virtual ~GasEquipmentDefinition() {} //@} /** @name Static Methods */ //@{ static IddObjectType iddObjectType(); static std::vector<std::string> validDesignLevelCalculationMethodValues(); //@} /** @name Getters */ //@{ std::string designLevelCalculationMethod() const; boost::optional<double> designLevel() const; boost::optional<double> wattsperSpaceFloorArea() const; boost::optional<double> wattsperPerson() const; double fractionLatent() const; bool isFractionLatentDefaulted() const; double fractionRadiant() const; bool isFractionRadiantDefaulted() const; double fractionLost() const; bool isFractionLostDefaulted() const; double carbonDioxideGenerationRate() const; bool isCarbonDioxideGenerationRateDefaulted() const; //@} /** @name Setters */ //@{ /** Also sets designLevelCalculationMethod accordingly. */ bool setDesignLevel(double designLevel); /** Also sets designLevelCalculationMethod accordingly. */ bool setWattsperSpaceFloorArea(double wattsperSpaceFloorArea); /** Also sets designLevelCalculationMethod accordingly. */ bool setWattsperPerson(double wattsperPerson); bool setFractionLatent(double fractionLatent); void resetFractionLatent(); bool setFractionRadiant(double fractionRadiant); void resetFractionRadiant(); bool setFractionLost(double fractionLost); void resetFractionLost(); bool setCarbonDioxideGenerationRate(double carbonDioxideGenerationRate); void resetCarbonDioxideGenerationRate(); //@} /** @name Other */ //@{ /** Returns the design level represented by this definition, assuming floorArea (m^2) and * numPeople. */ double getDesignLevel(double floorArea, double numPeople) const; /** Returns the watts/m^2 represented by this definition, assuming floorArea (m^2) and * numPeople. */ double getPowerPerFloorArea(double floorArea, double numPeople) const; /** Returns the watts/person represented by this definition, assuming floorArea (m^2) and * numPeople. */ double getPowerPerPerson(double floorArea, double numPeople) const; /** If method is a \link validDesignLevelCalculationMethodValues valid design level * calculation method \endlink, changes this definition to an equivalent power level, under * the assumptions of floorArea (m^2) and numPeople. */ bool setDesignLevelCalculationMethod(const std::string& method, double floorArea, double numPeople); //@} protected: /// @cond typedef detail::GasEquipmentDefinition_Impl ImplType; friend class Model; friend class openstudio::IdfObject; explicit GasEquipmentDefinition(std::shared_ptr<detail::GasEquipmentDefinition_Impl> impl); /// @endcond private: REGISTER_LOGGER("openstudio.model.GasEquipmentDefinition"); }; /** \relates GasEquipmentDefinition*/ typedef boost::optional<GasEquipmentDefinition> OptionalGasEquipmentDefinition; /** \relates GasEquipmentDefinition*/ typedef std::vector<GasEquipmentDefinition> GasEquipmentDefinitionVector; } // model } // openstudio #endif // MODEL_GASEQUIPMENTDEFINITION_HPP
// Copyright (c) 2016-2019 Duality Blockchain Solutions Developers // Copyright (c) 2014-2019 The Dash Core Developers // Copyright (c) 2009-2019 The Bitcoin Developers // Copyright (c) 2009-2019 Satoshi Nakamoto // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/credit-config.h" #endif #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "csvmodelwriter.h" #include "creditgui.h" #include "editaddressdialog.h" #include "guiutil.h" #include "platformstyle.h" #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(const PlatformStyle* platformStyle, Mode _mode, Tabs _tab, QWidget* parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), mode(_mode), tab(_tab) { ui->setupUi(this); #ifdef Q_OS_MAC ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); #endif switch (mode) { case ForSelection: switch (tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch (tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch (tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your Credit addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); ui->newAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your Credit addresses for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); ui->newAddress->setVisible(false); break; } // Context menu actions QAction* copyAddressAction = new QAction(tr("&Copy Address"), this); QAction* copyLabelAction = new QAction(tr("Copy &Label"), this); QAction* editAction = new QAction(tr("&Edit"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(this); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if (tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel* _model) { this->model = _model; if (!_model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(_model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch (tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } connect(ui->searchLineEdit, &QLineEdit::textChanged, proxyModel, &QSortFilterProxyModel::setFilterWildcard); ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(_model, SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(selectNewAddress(QModelIndex, int, int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if (!model) return; if (!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if (indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if (!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if (dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView* table = ui->tableView; if (!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if (!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView* table = ui->tableView; if (!table->selectionModel()) return; if (table->selectionModel()->hasSelection()) { switch (tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView* table = ui->tableView; if (!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); Q_FOREACH (const QModelIndex& index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if (returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if (!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1. Please try again.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint& point) { QModelIndex index = ui->tableView->indexAt(point); if (index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex& parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if (idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
default rel %define XMMWORD %define YMMWORD %define ZMMWORD section .text code align=64 ALIGN 32 __KeccakF1600: mov rax,QWORD[60+rdi] mov rbx,QWORD[68+rdi] mov rcx,QWORD[76+rdi] mov rdx,QWORD[84+rdi] mov rbp,QWORD[92+rdi] jmp NEAR $L$oop ALIGN 32 $L$oop: mov r8,QWORD[((-100))+rdi] mov r9,QWORD[((-52))+rdi] mov r10,QWORD[((-4))+rdi] mov r11,QWORD[44+rdi] xor rcx,QWORD[((-84))+rdi] xor rdx,QWORD[((-76))+rdi] xor rax,r8 xor rbx,QWORD[((-92))+rdi] xor rcx,QWORD[((-44))+rdi] xor rax,QWORD[((-60))+rdi] mov r12,rbp xor rbp,QWORD[((-68))+rdi] xor rcx,r10 xor rax,QWORD[((-20))+rdi] xor rdx,QWORD[((-36))+rdi] xor rbx,r9 xor rbp,QWORD[((-28))+rdi] xor rcx,QWORD[36+rdi] xor rax,QWORD[20+rdi] xor rdx,QWORD[4+rdi] xor rbx,QWORD[((-12))+rdi] xor rbp,QWORD[12+rdi] mov r13,rcx rol rcx,1 xor rcx,rax xor rdx,r11 rol rax,1 xor rax,rdx xor rbx,QWORD[28+rdi] rol rdx,1 xor rdx,rbx xor rbp,QWORD[52+rdi] rol rbx,1 xor rbx,rbp rol rbp,1 xor rbp,r13 xor r9,rcx xor r10,rdx rol r9,44 xor r11,rbp xor r12,rax rol r10,43 xor r8,rbx mov r13,r9 rol r11,21 or r9,r10 xor r9,r8 rol r12,14 xor r9,QWORD[r15] lea r15,[8+r15] mov r14,r12 and r12,r11 mov QWORD[((-100))+rsi],r9 xor r12,r10 not r10 mov QWORD[((-84))+rsi],r12 or r10,r11 mov r12,QWORD[76+rdi] xor r10,r13 mov QWORD[((-92))+rsi],r10 and r13,r8 mov r9,QWORD[((-28))+rdi] xor r13,r14 mov r10,QWORD[((-20))+rdi] mov QWORD[((-68))+rsi],r13 or r14,r8 mov r8,QWORD[((-76))+rdi] xor r14,r11 mov r11,QWORD[28+rdi] mov QWORD[((-76))+rsi],r14 xor r8,rbp xor r12,rdx rol r8,28 xor r11,rcx xor r9,rax rol r12,61 rol r11,45 xor r10,rbx rol r9,20 mov r13,r8 or r8,r12 rol r10,3 xor r8,r11 mov QWORD[((-36))+rsi],r8 mov r14,r9 and r9,r13 mov r8,QWORD[((-92))+rdi] xor r9,r12 not r12 mov QWORD[((-28))+rsi],r9 or r12,r11 mov r9,QWORD[((-44))+rdi] xor r12,r10 mov QWORD[((-44))+rsi],r12 and r11,r10 mov r12,QWORD[60+rdi] xor r11,r14 mov QWORD[((-52))+rsi],r11 or r14,r10 mov r10,QWORD[4+rdi] xor r14,r13 mov r11,QWORD[52+rdi] mov QWORD[((-60))+rsi],r14 xor r10,rbp xor r11,rax rol r10,25 xor r9,rdx rol r11,8 xor r12,rbx rol r9,6 xor r8,rcx rol r12,18 mov r13,r10 and r10,r11 rol r8,1 not r11 xor r10,r9 mov QWORD[((-12))+rsi],r10 mov r14,r12 and r12,r11 mov r10,QWORD[((-12))+rdi] xor r12,r13 mov QWORD[((-4))+rsi],r12 or r13,r9 mov r12,QWORD[84+rdi] xor r13,r8 mov QWORD[((-20))+rsi],r13 and r9,r8 xor r9,r14 mov QWORD[12+rsi],r9 or r14,r8 mov r9,QWORD[((-60))+rdi] xor r14,r11 mov r11,QWORD[36+rdi] mov QWORD[4+rsi],r14 mov r8,QWORD[((-68))+rdi] xor r10,rcx xor r11,rdx rol r10,10 xor r9,rbx rol r11,15 xor r12,rbp rol r9,36 xor r8,rax rol r12,56 mov r13,r10 or r10,r11 rol r8,27 not r11 xor r10,r9 mov QWORD[28+rsi],r10 mov r14,r12 or r12,r11 xor r12,r13 mov QWORD[36+rsi],r12 and r13,r9 xor r13,r8 mov QWORD[20+rsi],r13 or r9,r8 xor r9,r14 mov QWORD[52+rsi],r9 and r8,r14 xor r8,r11 mov QWORD[44+rsi],r8 xor rdx,QWORD[((-84))+rdi] xor rbp,QWORD[((-36))+rdi] rol rdx,62 xor rcx,QWORD[68+rdi] rol rbp,55 xor rax,QWORD[12+rdi] rol rcx,2 xor rbx,QWORD[20+rdi] xchg rdi,rsi rol rax,39 rol rbx,41 mov r13,rdx and rdx,rbp not rbp xor rdx,rcx mov QWORD[92+rdi],rdx mov r14,rax and rax,rbp xor rax,r13 mov QWORD[60+rdi],rax or r13,rcx xor r13,rbx mov QWORD[84+rdi],r13 and rcx,rbx xor rcx,r14 mov QWORD[76+rdi],rcx or rbx,r14 xor rbx,rbp mov QWORD[68+rdi],rbx mov rbp,rdx mov rdx,r13 test r15,255 jnz NEAR $L$oop lea r15,[((-192))+r15] DB 0F3h,0C3h ;repret ALIGN 32 KeccakF1600: push rbx push rbp push r12 push r13 push r14 push r15 lea rdi,[100+rdi] sub rsp,200 not QWORD[((-92))+rdi] not QWORD[((-84))+rdi] not QWORD[((-36))+rdi] not QWORD[((-4))+rdi] not QWORD[36+rdi] not QWORD[60+rdi] lea r15,[iotas] lea rsi,[100+rsp] call __KeccakF1600 not QWORD[((-92))+rdi] not QWORD[((-84))+rdi] not QWORD[((-36))+rdi] not QWORD[((-4))+rdi] not QWORD[36+rdi] not QWORD[60+rdi] lea rdi,[((-100))+rdi] add rsp,200 pop r15 pop r14 pop r13 pop r12 pop rbp pop rbx DB 0F3h,0C3h ;repret global SHA3_absorb ALIGN 32 SHA3_absorb: mov QWORD[8+rsp],rdi ;WIN64 prologue mov QWORD[16+rsp],rsi mov rax,rsp $L$SEH_begin_SHA3_absorb: mov rdi,rcx mov rsi,rdx mov rdx,r8 mov rcx,r9 push rbx push rbp push r12 push r13 push r14 push r15 lea rdi,[100+rdi] sub rsp,232 mov r9,rsi lea rsi,[100+rsp] not QWORD[((-92))+rdi] not QWORD[((-84))+rdi] not QWORD[((-36))+rdi] not QWORD[((-4))+rdi] not QWORD[36+rdi] not QWORD[60+rdi] lea r15,[iotas] mov QWORD[((216-100))+rsi],rcx $L$oop_absorb: cmp rdx,rcx jc NEAR $L$done_absorb shr rcx,3 lea r8,[((-100))+rdi] $L$block_absorb: mov rax,QWORD[r9] lea r9,[8+r9] xor rax,QWORD[r8] lea r8,[8+r8] sub rdx,8 mov QWORD[((-8))+r8],rax sub rcx,1 jnz NEAR $L$block_absorb mov QWORD[((200-100))+rsi],r9 mov QWORD[((208-100))+rsi],rdx call __KeccakF1600 mov r9,QWORD[((200-100))+rsi] mov rdx,QWORD[((208-100))+rsi] mov rcx,QWORD[((216-100))+rsi] jmp NEAR $L$oop_absorb ALIGN 32 $L$done_absorb: mov rax,rdx not QWORD[((-92))+rdi] not QWORD[((-84))+rdi] not QWORD[((-36))+rdi] not QWORD[((-4))+rdi] not QWORD[36+rdi] not QWORD[60+rdi] add rsp,232 pop r15 pop r14 pop r13 pop r12 pop rbp pop rbx mov rdi,QWORD[8+rsp] ;WIN64 epilogue mov rsi,QWORD[16+rsp] DB 0F3h,0C3h ;repret $L$SEH_end_SHA3_absorb: global SHA3_squeeze ALIGN 32 SHA3_squeeze: mov QWORD[8+rsp],rdi ;WIN64 prologue mov QWORD[16+rsp],rsi mov rax,rsp $L$SEH_begin_SHA3_squeeze: mov rdi,rcx mov rsi,rdx mov rdx,r8 mov rcx,r9 push r12 push r13 push r14 shr rcx,3 mov r8,rdi mov r12,rsi mov r13,rdx mov r14,rcx jmp NEAR $L$oop_squeeze ALIGN 32 $L$oop_squeeze: cmp r13,8 jb NEAR $L$tail_squeeze mov rax,QWORD[r8] lea r8,[8+r8] mov QWORD[r12],rax lea r12,[8+r12] sub r13,8 jz NEAR $L$done_squeeze sub rcx,1 jnz NEAR $L$oop_squeeze call KeccakF1600 mov r8,rdi mov rcx,r14 jmp NEAR $L$oop_squeeze $L$tail_squeeze: mov rsi,r8 mov rdi,r12 mov rcx,r13 DB 0xf3,0xa4 $L$done_squeeze: pop r14 pop r13 pop r12 mov rdi,QWORD[8+rsp] ;WIN64 epilogue mov rsi,QWORD[16+rsp] DB 0F3h,0C3h ;repret $L$SEH_end_SHA3_squeeze: ALIGN 256 DQ 0,0,0,0,0,0,0,0 iotas: DQ 0x0000000000000001 DQ 0x0000000000008082 DQ 0x800000000000808a DQ 0x8000000080008000 DQ 0x000000000000808b DQ 0x0000000080000001 DQ 0x8000000080008081 DQ 0x8000000000008009 DQ 0x000000000000008a DQ 0x0000000000000088 DQ 0x0000000080008009 DQ 0x000000008000000a DQ 0x000000008000808b DQ 0x800000000000008b DQ 0x8000000000008089 DQ 0x8000000000008003 DQ 0x8000000000008002 DQ 0x8000000000000080 DQ 0x000000000000800a DQ 0x800000008000000a DQ 0x8000000080008081 DQ 0x8000000000008080 DQ 0x0000000080000001 DQ 0x8000000080008008 DB 75,101,99,99,97,107,45,49,54,48,48,32,97,98,115,111 DB 114,98,32,97,110,100,32,115,113,117,101,101,122,101,32,102 DB 111,114,32,120,56,54,95,54,52,44,32,67,82,89,80,84 DB 79,71,65,77,83,32,98,121,32,60,97,112,112,114,111,64 DB 111,112,101,110,115,115,108,46,111,114,103,62,0
; A299913: a(n) = a(n-1) + 2*a(n-2) if n even, or 3*a(n-1) + 4*a(n-2) if n odd, starting with 0, 1. ; 0,1,1,7,9,55,73,439,585,3511,4681,28087,37449,224695,299593,1797559,2396745,14380471,19173961,115043767,153391689,920350135,1227133513,7362801079,9817068105,58902408631,78536544841,471219269047,628292358729,3769754152375,5026338869833,30158033218999,40210710958665,241264265751991,321685687669321,1930114126015927,2573485501354569 mov $4,$0 mov $13,$0 lpb $4 mov $0,$13 sub $4,1 sub $0,$4 mov $9,$0 mov $11,2 lpb $11 mov $0,$9 sub $11,1 add $0,$11 sub $0,1 mov $5,$0 mov $7,2 lpb $7 mov $0,$5 sub $7,1 add $0,$7 sub $0,1 mul $0,3 add $0,1 mov $2,1 mov $3,1 lpb $0 sub $0,2 mul $2,2 add $2,1 mov $3,$2 lpe sub $3,$0 mov $2,$3 mov $8,$7 lpb $8 mov $6,$2 sub $8,1 lpe lpe lpb $5 mov $5,0 sub $6,$2 lpe mov $2,$6 mov $12,$11 lpb $12 mov $10,$2 sub $12,1 lpe lpe lpb $9 mov $9,0 sub $10,$2 lpe mov $2,$10 div $2,7 add $1,$2 lpe
#include "executor.h" #include <unistd.h> #include <errno.h> #include <boost/scoped_ptr.hpp> #include "common/filesystem.h" namespace baidu { namespace shuttle { ReduceExecutor::ReduceExecutor() { ::setenv("mapred_task_is_map", "false", 1); } ReduceExecutor::~ReduceExecutor() { } TaskState ReduceExecutor::Exec(const TaskInfo& task) { LOG(INFO, "exec reduce task"); ::setenv("mapred_work_output_dir", GetReduceWorkDir(task).c_str(), 1); std::string cmd = "sh ./app_wrapper.sh \"" + task.job().reduce_command() + "\""; LOG(INFO, "reduce command is: %s", cmd.c_str()); FILE* user_app = popen(cmd.c_str(), "r"); if (user_app == NULL) { LOG(WARNING, "start user app fail, cmd is %s, (%s)", cmd.c_str(), strerror(errno)); return kTaskFailed; } FileSystem::Param param; FillParam(param, task); const std::string temp_file_name = GetReduceWorkFilename(task); if (task.job().output_format() == kTextOutput) { TaskState status = TransTextOutput(user_app, temp_file_name, param, task); if (status != kTaskCompleted) { return status; } } else if (task.job().output_format() == kBinaryOutput) { TaskState status = TransBinaryOutput(user_app, temp_file_name, param, task); if (status != kTaskCompleted) { return status; } } else if (task.job().output_format() == kSuffixMultipleTextOutput) { TaskState status = TransMultipleTextOutput(user_app, temp_file_name, param, task); if (status != kTaskCompleted) { return status; } } else { LOG(FATAL, "unknown output format"); } int ret = pclose(user_app); if (ret != 0) { LOG(WARNING, "user app fail, cmd is %s, ret: %d", cmd.c_str(), ret); return kTaskFailed; } FileSystem* fs = FileSystem::CreateInfHdfs(param); boost::scoped_ptr<FileSystem> fs_guard(fs); if (task.job().output_format() == kSuffixMultipleTextOutput) { if (!MoveMultipleTempToOutput(task, fs, false)) { LOG(WARNING, "fail to move multiple output"); return kTaskMoveOutputFailed; } } else { if (!MoveTempToOutput(task, fs, false)) { LOG(WARNING, "fail to move output"); return kTaskMoveOutputFailed; } } return kTaskCompleted; } } }
; -------------------------------------- ; Test ADD, and moving data from addresses to registers and back. ; ; Before loading the program confirm the memory is all set to zeros. ; Double flip CLR. ; Load the program by: ; Setting Sense switches to zero and double flipping AUX2 down. ; Upload from the laptop to the Altair. ; EXAMINE address 64 (address of Addr1), which is 0. ; Flip RESET, to set back to address zero. ; Run the program. ; EXAMINE address 64 (address of Addr1), which equals 6 from: sta Addr1. ; ; 8085 program to add two 8 bit numbers ; https://www.geeksforgeeks.org/assembly-language-program-8085-microprocessor-add-two-8-bit-numbers/ ; ; -------------------------------------- jmp Start ; Jump to start of the test program. ; Addr1 equ 64 ; This program is less than 64 bytes. Addr2 ds 2 ; 2 bytes at this location, address 3. The address of Addr2, is 3. ; Halt: hlt ; The program will halt at each iteration, after the first. ; -------------------------------------- Start: ; -------------------------------------- mvi a,7 ; Initialize values to add. mvi b,1 mvi c,2 mvi d,3 mvi e,4 mvi h,5 mvi l,6 out 38 ; Print the register values. ; + regA: 7 = 007 = 00000111 ; + regB: 1 = 001 = 00000001 regC: 2 = 002 = 00000010 ; + regD: 3 = 003 = 00000011 regE: 4 = 004 = 00000100 ; + regH: 5 = 005 = 00000101 regL: 6 = 006 = 00000110 ; ; -------------------------------------- ; Test register adding. add b ; Add source register to A. mov b,a ; Move the result back to the source register, to print the sum, later. add c mov c,a add d mov d,a add e mov e,a add h mov h,a add l mov l,a add a out 38 ; Print the register results. The following is correct. ; + regA: 56 = 070 = 00111000 (regA + regB = 8) ; + regB: 8 = 010 = 00001000 regC: 10 = 012 = 00001010 ; + regD: 13 = 015 = 00001101 regE: 17 = 021 = 00010001 ; + regH: 22 = 026 = 00010110 regL: 28 = 034 = 00011100 ; ; -------------------------------------- ; Add content at address H:L, to register A. ; mvi a,6 ; Move # to register A. out 37 ; Print register A. ; > Register A = 6 = 006 = 00000110 sta Addr1 ; Store register A's content to the address(hb:lb). lxi h,Addr1 ; Load an address (value of Addr1) into H:L. out 36 ; Print the register values for H:L and the content at that address. ; > Register H:L = 0:64, Data: 6 ; mvi a,3 ; Move # to register A. out 37 ; Print register A. ; > Register A = 3 = 003 = 00000011 add m ; ADD: Content at address H:L(M) + Register A = 6 + 3 = 9 out 37 ; Print register A == 9. ; > Register A = 9 = 011 = 00001001 ; sta Addr2 ; Store register A's content to the address(hb:lb). ; ; EXAMINE address 64 (address of Addr1), which equals 6 from: sta Addr1. ; EXAMINE address 03 (address of Addr2), which equals 9 from: sta Addr2. ; ; -------------------------------------- jmp Halt ; Jump back to the early halt command. ; -------------------------------------- end
; ; switch_32.asm ; KripayaOS ; [bits 16] switch32bit: cli ; 1. Disable all the Interrupts lgdt [gdt_descriptor] ; 2. Load GDT descriptor mov eax, cr0 or eax, 0x1 ; 3. Enable Protected Mode/32 bit mov cr0, eax jmp CODE_SEG:init32bit ; 4. Do a far jump [bits 32] init32bit: mov ax, DATA_SEG ; 5. Update Segment Registers mov ds, ax mov ss, ax mov es, ax mov fs, ax mov gs, ax mov ebp, 0x90000 ; 6. Create a 32 bit stack mov esp, ebp call start32 ; 7. Go back to MBR.asm
/* * Copyright (C) 2018 all rights reserved. * * Author: Houmin Wei <houmin.wei@outlook.com> * * Source: https://leetcode.com/problems/longest-increasing-subsequence * * Description: * Given an unsorted array of integers, find the length of longest increasing subsequence. */ #include <vector> using namespace std; class Solution { public: int lengthOfLIS(vector<int>& nums) { int n = nums.size(); vector<int> dp(n, 1); int res = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { dp[i] = max(dp[i], dp[j]+1); } res = max(res, dp[i]); } return res; } }; class Solution2 { public: int lengthOfLIS(vector<int>& nums) { vector<int> res; for(int i=0; i<nums.size(); i++) { auto it = std::lower_bound(res.begin(), res.end(), nums[i]); if(it==res.end()) res.push_back(nums[i]); else *it = nums[i]; } return res.size(); } };
MODULE Err ESPTimeout DC "1 WiFi/server timeout" hostConnect DC "2 Failed to connect to host" errorConnect DC "3 Cannot open TCP connection" badOption DC "4 Unknown command option" varNotFound DC "5 NextBASIC variable not found" wifiInit DC "6 WiFi chip init failed" tcpSend1 DC "7 HTTP send post fail" tcpSend2 DC "8 HTTP send fail" tcpSend3 DC "9 HTTP get fail" tcpSend4 DC "A HTTP send tcp frame fail" readTimeout DC "B HTTP read timeout" bankError DC "C Bank arg error" lengthError DC "D Length arg error" offsetError DC "E Offset arg error" portError DC "F Port error" borderError DC "G Border out of range 0-7" hostError DC "H Host required" noFileOrBank DC "I Filename or bank required" fileOpen DC "J Can't open file for writing" contentLength DC "K Content length error" outOfMemory DC "L Out of memory: try '-r'" notEnoughMemory DC "M Not enough memory: try '-r'" ENDMODULE MODULE Msg help ;; 12345678901234567890123456789012 DB NAME, " v", VERSION, " by Remy Sharp", CR DB "-> GET and POST over HTTP", CR, CR DB "Synopsis:",CR DB " .",NAME," get ...args",CR DB " .",NAME," post ...args",CR, CR DB "Args:",CR DB "-b num* bank to use",CR DB "-f str* filename",CR DB "-r disable rolling banks",CR DB "-h str host address",CR DB "-p num* port",CR DB "-u str* url",CR DB "-l num* length of data",CR DB " (required with POST)",CR DB "-o num* offset in bank",CR DB "-7 base64 decode",CR DB "-v num* flash border colour",CR,CR DB "* denotes optional with defaults",CR DB "FAQ: github.com/remy/next-http",CR,0 ENDMODULE
%ifdef CONFIG { "RegData": { "RAX": "0x414243444546A348" }, "MemoryRegions": { "0x100000000": "4096" } } %endif mov rdx, 0xe0000000 mov rax, 0x4142434445464748 mov [rdx + 8 * 0], rax mov rax, 0x5152535455565758 mov [rdx + 8 * 1], rax ror byte [rdx + 8 * 0 + 1], 1 mov rax, [rdx + 8 * 0] hlt
; ; MSX specific routines ; ; GFX - a small graphics library ; Copyright (C) 2004 Rafael de Oliveira Jannone ; ; extern bool __FASTCALL__ msx_set_mode(unsigned char id); ; ; set screen mode ; ; $Id: msx_set_mode.asm,v 1.2 2009/06/22 21:44:17 dom Exp $ ; XLIB msx_set_mode LIB msxbios INCLUDE "msxbios.def" msx_set_mode: push hl pop ix jp msxbios ;_init_sprites();
; A108411: a(n) = 3^floor(n/2). Powers of 3 repeated. ; 1,1,3,3,9,9,27,27,81,81,243,243,729,729,2187,2187,6561,6561,19683,19683,59049,59049,177147,177147,531441,531441,1594323,1594323,4782969,4782969,14348907,14348907,43046721,43046721,129140163,129140163,387420489,387420489,1162261467,1162261467,3486784401,3486784401,10460353203,10460353203,31381059609,31381059609,94143178827,94143178827,282429536481,282429536481,847288609443,847288609443,2541865828329,2541865828329,7625597484987,7625597484987,22876792454961,22876792454961,68630377364883 div $0,2 mov $1,3 pow $1,$0 mov $0,$1
; A017175: a(n) = (9*n + 1)^3. ; 1,1000,6859,21952,50653,97336,166375,262144,389017,551368,753571,1000000,1295029,1643032,2048383,2515456,3048625,3652264,4330747,5088448,5929741,6859000,7880599,8998912,10218313,11543176,12977875,14526784,16194277,17984728,19902511,21952000,24137569,26463592,28934443,31554496,34328125,37259704,40353607,43614208,47045881,50653000,54439939,58411072,62570773,66923416,71473375,76225024,81182737,86350888,91733851,97336000,103161709,109215352,115501303,122023936,128787625,135796744,143055667 mul $0,9 add $0,1 pow $0,3
// Copyright (c) 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 "content/browser/renderer_host/media/web_contents_audio_input_stream.h" #include <list> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/message_loop.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "content/browser/browser_thread_impl.h" #include "content/browser/renderer_host/media/audio_mirroring_manager.h" #include "content/browser/renderer_host/media/web_contents_tracker.h" #include "media/audio/simple_sources.h" #include "media/audio/virtual_audio_input_stream.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; using ::testing::Assign; using ::testing::DoAll; using ::testing::Invoke; using ::testing::InvokeWithoutArgs; using ::testing::NotNull; using ::testing::SaveArg; using ::testing::WithArgs; using media::AudioInputStream; using media::AudioOutputStream; using media::AudioParameters; using media::SineWaveAudioSource; using media::VirtualAudioInputStream; using media::VirtualAudioOutputStream; namespace content { namespace { const int kRenderProcessId = 123; const int kRenderViewId = 456; const int kAnotherRenderProcessId = 789; const int kAnotherRenderViewId = 1; const AudioParameters& TestAudioParameters() { static const AudioParameters params( AudioParameters::AUDIO_FAKE, media::CHANNEL_LAYOUT_STEREO, AudioParameters::kAudioCDSampleRate, 16, AudioParameters::kAudioCDSampleRate / 100); return params; } class MockAudioMirroringManager : public AudioMirroringManager { public: MockAudioMirroringManager() : AudioMirroringManager() {} virtual ~MockAudioMirroringManager() {} MOCK_METHOD3(StartMirroring, void(int render_process_id, int render_view_id, MirroringDestination* destination)); MOCK_METHOD3(StopMirroring, void(int render_process_id, int render_view_id, MirroringDestination* destination)); private: DISALLOW_COPY_AND_ASSIGN(MockAudioMirroringManager); }; class MockWebContentsTracker : public WebContentsTracker { public: MockWebContentsTracker() : WebContentsTracker() {} MOCK_METHOD3(Start, void(int render_process_id, int render_view_id, const ChangeCallback& callback)); MOCK_METHOD0(Stop, void()); private: virtual ~MockWebContentsTracker() {} DISALLOW_COPY_AND_ASSIGN(MockWebContentsTracker); }; // A fully-functional VirtualAudioInputStream, but methods are mocked to allow // tests to check how/when they are invoked. class MockVirtualAudioInputStream : public VirtualAudioInputStream { public: explicit MockVirtualAudioInputStream( const scoped_refptr<base::MessageLoopProxy>& message_loop) : VirtualAudioInputStream(TestAudioParameters(), message_loop, VirtualAudioInputStream::AfterCloseCallback()), real_(TestAudioParameters(), message_loop, base::Bind(&MockVirtualAudioInputStream::OnRealStreamHasClosed, base::Unretained(this))), real_stream_is_closed_(false) { // Set default actions of mocked methods to delegate to the concrete // implementation. ON_CALL(*this, Open()) .WillByDefault(Invoke(&real_, &VirtualAudioInputStream::Open)); ON_CALL(*this, Start(_)) .WillByDefault(Invoke(&real_, &VirtualAudioInputStream::Start)); ON_CALL(*this, Stop()) .WillByDefault(Invoke(&real_, &VirtualAudioInputStream::Stop)); ON_CALL(*this, Close()) .WillByDefault(Invoke(&real_, &VirtualAudioInputStream::Close)); ON_CALL(*this, GetMaxVolume()) .WillByDefault(Invoke(&real_, &VirtualAudioInputStream::GetMaxVolume)); ON_CALL(*this, SetVolume(_)) .WillByDefault(Invoke(&real_, &VirtualAudioInputStream::SetVolume)); ON_CALL(*this, GetVolume()) .WillByDefault(Invoke(&real_, &VirtualAudioInputStream::GetVolume)); ON_CALL(*this, SetAutomaticGainControl(_)) .WillByDefault( Invoke(&real_, &VirtualAudioInputStream::SetAutomaticGainControl)); ON_CALL(*this, GetAutomaticGainControl()) .WillByDefault( Invoke(&real_, &VirtualAudioInputStream::GetAutomaticGainControl)); ON_CALL(*this, AddOutputStream(NotNull(), _)) .WillByDefault( Invoke(&real_, &VirtualAudioInputStream::AddOutputStream)); ON_CALL(*this, RemoveOutputStream(NotNull(), _)) .WillByDefault( Invoke(&real_, &VirtualAudioInputStream::RemoveOutputStream)); } ~MockVirtualAudioInputStream() { DCHECK(real_stream_is_closed_); } MOCK_METHOD0(Open, bool()); MOCK_METHOD1(Start, void(AudioInputStream::AudioInputCallback*)); MOCK_METHOD0(Stop, void()); MOCK_METHOD0(Close, void()); MOCK_METHOD0(GetMaxVolume, double()); MOCK_METHOD1(SetVolume, void(double)); MOCK_METHOD0(GetVolume, double()); MOCK_METHOD1(SetAutomaticGainControl, void(bool)); MOCK_METHOD0(GetAutomaticGainControl, bool()); MOCK_METHOD2(AddOutputStream, void(VirtualAudioOutputStream*, const AudioParameters&)); MOCK_METHOD2(RemoveOutputStream, void(VirtualAudioOutputStream*, const AudioParameters&)); private: void OnRealStreamHasClosed(VirtualAudioInputStream* stream) { DCHECK_EQ(&real_, stream); DCHECK(!real_stream_is_closed_); real_stream_is_closed_ = true; } VirtualAudioInputStream real_; bool real_stream_is_closed_; DISALLOW_COPY_AND_ASSIGN(MockVirtualAudioInputStream); }; class MockAudioInputCallback : public AudioInputStream::AudioInputCallback { public: MockAudioInputCallback() {} MOCK_METHOD5(OnData, void(AudioInputStream* stream, const uint8* src, uint32 size, uint32 hardware_delay_bytes, double volume)); MOCK_METHOD1(OnClose, void(AudioInputStream* stream)); MOCK_METHOD1(OnError, void(AudioInputStream* stream)); private: DISALLOW_COPY_AND_ASSIGN(MockAudioInputCallback); }; } // namespace class WebContentsAudioInputStreamTest : public testing::Test { public: WebContentsAudioInputStreamTest() : audio_thread_("Audio thread"), io_thread_(BrowserThread::IO), mock_mirroring_manager_(new MockAudioMirroringManager()), mock_tracker_(new MockWebContentsTracker()), mock_vais_(NULL), wcais_(NULL), destination_(NULL), current_render_process_id_(kRenderProcessId), current_render_view_id_(kRenderViewId), on_data_event_(false, false) { audio_thread_.Start(); io_thread_.Start(); } virtual ~WebContentsAudioInputStreamTest() { audio_thread_.Stop(); io_thread_.Stop(); DCHECK(!mock_vais_); DCHECK(!wcais_); EXPECT_FALSE(destination_); DCHECK(streams_.empty()); DCHECK(sources_.empty()); } void Open() { mock_vais_ = new MockVirtualAudioInputStream(audio_thread_.message_loop_proxy()); EXPECT_CALL(*mock_vais_, Open()); EXPECT_CALL(*mock_vais_, Close()); // At Close() time. ASSERT_EQ(kRenderProcessId, current_render_process_id_); ASSERT_EQ(kRenderViewId, current_render_view_id_); EXPECT_CALL(*mock_tracker_, Start(kRenderProcessId, kRenderViewId, _)) .WillOnce(DoAll( SaveArg<2>(&change_callback_), WithArgs<0, 1>( Invoke(&change_callback_, &WebContentsTracker::ChangeCallback::Run)))); EXPECT_CALL(*mock_tracker_, Stop()); // At Close() time. wcais_ = new WebContentsAudioInputStream( current_render_process_id_, current_render_view_id_, audio_thread_.message_loop_proxy(), mock_mirroring_manager_.get(), mock_tracker_, mock_vais_); wcais_->Open(); } void Start() { EXPECT_CALL(*mock_vais_, Start(&mock_input_callback_)); EXPECT_CALL(*mock_vais_, Stop()); // At Stop() time. EXPECT_CALL(*mock_mirroring_manager_, StartMirroring(kRenderProcessId, kRenderViewId, NotNull())) .WillOnce(SaveArg<2>(&destination_)) .RetiresOnSaturation(); // At Stop() time, or when the mirroring target changes: EXPECT_CALL(*mock_mirroring_manager_, StopMirroring(kRenderProcessId, kRenderViewId, NotNull())) .WillOnce(Assign( &destination_, static_cast<AudioMirroringManager::MirroringDestination*>(NULL))) .RetiresOnSaturation(); EXPECT_CALL(mock_input_callback_, OnData(NotNull(), NotNull(), _, _, _)) .WillRepeatedly( InvokeWithoutArgs(&on_data_event_, &base::WaitableEvent::Signal)); EXPECT_CALL(mock_input_callback_, OnClose(_)); // At Stop() time. wcais_->Start(&mock_input_callback_); // Test plumbing of volume controls and automatic gain controls. Calls to // wcais_ methods should delegate directly to mock_vais_. EXPECT_CALL(*mock_vais_, GetVolume()); double volume = wcais_->GetVolume(); EXPECT_CALL(*mock_vais_, GetMaxVolume()); const double max_volume = wcais_->GetMaxVolume(); volume *= 2.0; if (volume < max_volume) { volume = max_volume; } EXPECT_CALL(*mock_vais_, SetVolume(volume)); wcais_->SetVolume(volume); EXPECT_CALL(*mock_vais_, GetAutomaticGainControl()); bool auto_gain = wcais_->GetAutomaticGainControl(); auto_gain = !auto_gain; EXPECT_CALL(*mock_vais_, SetAutomaticGainControl(auto_gain)); wcais_->SetAutomaticGainControl(auto_gain); } void AddAnotherInput() { // Note: WCAIS posts a task to invoke // MockAudioMirroringManager::StartMirroring() on the IO thread, which // causes our mock to set |destination_|. Block until that has happened. base::WaitableEvent done(false, false); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind( &base::WaitableEvent::Signal, base::Unretained(&done))); done.Wait(); ASSERT_TRUE(destination_); EXPECT_CALL(*mock_vais_, AddOutputStream(NotNull(), _)) .RetiresOnSaturation(); // Later, when stream is closed: EXPECT_CALL(*mock_vais_, RemoveOutputStream(NotNull(), _)) .RetiresOnSaturation(); const AudioParameters& params = TestAudioParameters(); AudioOutputStream* const out = destination_->AddInput(params); ASSERT_TRUE(out); streams_.push_back(out); EXPECT_TRUE(out->Open()); SineWaveAudioSource* const source = new SineWaveAudioSource( params.channel_layout(), 200.0, params.sample_rate()); sources_.push_back(source); out->Start(source); } void RemoveOneInputInFIFOOrder() { ASSERT_FALSE(streams_.empty()); AudioOutputStream* const out = streams_.front(); streams_.pop_front(); out->Stop(); out->Close(); // Self-deletes. ASSERT_TRUE(!sources_.empty()); delete sources_.front(); sources_.pop_front(); } void ChangeMirroringTarget() { const int next_render_process_id = current_render_process_id_ == kRenderProcessId ? kAnotherRenderProcessId : kRenderProcessId; const int next_render_view_id = current_render_view_id_ == kRenderViewId ? kAnotherRenderViewId : kRenderViewId; EXPECT_CALL(*mock_mirroring_manager_, StartMirroring(next_render_process_id, next_render_view_id, NotNull())) .WillOnce(SaveArg<2>(&destination_)) .RetiresOnSaturation(); // At Stop() time, or when the mirroring target changes: EXPECT_CALL(*mock_mirroring_manager_, StopMirroring(next_render_process_id, next_render_view_id, NotNull())) .WillOnce(Assign( &destination_, static_cast<AudioMirroringManager::MirroringDestination*>(NULL))) .RetiresOnSaturation(); // Simulate OnTargetChange() callback from WebContentsTracker. EXPECT_FALSE(change_callback_.is_null()); change_callback_.Run(next_render_process_id, next_render_view_id); current_render_process_id_ = next_render_process_id; current_render_view_id_ = next_render_view_id; } void LoseMirroringTarget() { EXPECT_CALL(mock_input_callback_, OnError(_)); // Simulate OnTargetChange() callback from WebContentsTracker. EXPECT_FALSE(change_callback_.is_null()); change_callback_.Run(-1, -1); } void Stop() { wcais_->Stop(); } void Close() { // WebContentsAudioInputStream self-destructs on Close(). Its internal // objects hang around until they are no longer referred to (e.g., as tasks // on other threads shut things down). wcais_->Close(); wcais_ = NULL; mock_vais_ = NULL; } void RunOnAudioThread(const base::Closure& closure) { audio_thread_.message_loop()->PostTask(FROM_HERE, closure); } // Block the calling thread until OnData() callbacks are being made. void WaitForData() { // Note: Arbitrarily chosen, but more iterations causes tests to take // significantly more time. static const int kNumIterations = 3; for (int i = 0; i < kNumIterations; ++i) on_data_event_.Wait(); } private: base::Thread audio_thread_; BrowserThreadImpl io_thread_; scoped_ptr<MockAudioMirroringManager> mock_mirroring_manager_; scoped_refptr<MockWebContentsTracker> mock_tracker_; MockVirtualAudioInputStream* mock_vais_; // Owned by wcais_. WebContentsAudioInputStream* wcais_; // Self-destructs on Close(). // Mock consumer of audio data. MockAudioInputCallback mock_input_callback_; // Provided by WebContentsAudioInputStream to the mock WebContentsTracker. // This callback is saved here, and test code will invoke it to simulate // target change events. WebContentsTracker::ChangeCallback change_callback_; // Provided by WebContentsAudioInputStream to the mock AudioMirroringManager. // A pointer to the implementation is saved here, and test code will invoke it // to simulate: 1) calls to AddInput(); and 2) diverting audio data. AudioMirroringManager::MirroringDestination* destination_; // Current target RenderView. These get flipped in ChangedMirroringTarget(). int current_render_process_id_; int current_render_view_id_; // Streams provided by calls to WebContentsAudioInputStream::AddInput(). Each // is started with a simulated source of audio data. std::list<AudioOutputStream*> streams_; std::list<SineWaveAudioSource*> sources_; // 1:1 with elements in streams_. base::WaitableEvent on_data_event_; DISALLOW_COPY_AND_ASSIGN(WebContentsAudioInputStreamTest); }; #define RUN_ON_AUDIO_THREAD(method) \ RunOnAudioThread(base::Bind(&WebContentsAudioInputStreamTest::method, \ base::Unretained(this))) TEST_F(WebContentsAudioInputStreamTest, OpenedButNeverStarted) { RUN_ON_AUDIO_THREAD(Open); RUN_ON_AUDIO_THREAD(Close); } TEST_F(WebContentsAudioInputStreamTest, MirroringNothing) { RUN_ON_AUDIO_THREAD(Open); RUN_ON_AUDIO_THREAD(Start); WaitForData(); RUN_ON_AUDIO_THREAD(Stop); RUN_ON_AUDIO_THREAD(Close); } TEST_F(WebContentsAudioInputStreamTest, MirroringOutputOutlivesSession) { RUN_ON_AUDIO_THREAD(Open); RUN_ON_AUDIO_THREAD(Start); RUN_ON_AUDIO_THREAD(AddAnotherInput); WaitForData(); RUN_ON_AUDIO_THREAD(Stop); RUN_ON_AUDIO_THREAD(Close); RUN_ON_AUDIO_THREAD(RemoveOneInputInFIFOOrder); } TEST_F(WebContentsAudioInputStreamTest, MirroringOutputWithinSession) { RUN_ON_AUDIO_THREAD(Open); RUN_ON_AUDIO_THREAD(Start); RUN_ON_AUDIO_THREAD(AddAnotherInput); WaitForData(); RUN_ON_AUDIO_THREAD(RemoveOneInputInFIFOOrder); RUN_ON_AUDIO_THREAD(Stop); RUN_ON_AUDIO_THREAD(Close); } TEST_F(WebContentsAudioInputStreamTest, MirroringNothingWithTargetChange) { RUN_ON_AUDIO_THREAD(Open); RUN_ON_AUDIO_THREAD(Start); RUN_ON_AUDIO_THREAD(ChangeMirroringTarget); RUN_ON_AUDIO_THREAD(Stop); RUN_ON_AUDIO_THREAD(Close); } TEST_F(WebContentsAudioInputStreamTest, MirroringOneStreamAfterTargetChange) { RUN_ON_AUDIO_THREAD(Open); RUN_ON_AUDIO_THREAD(Start); RUN_ON_AUDIO_THREAD(ChangeMirroringTarget); RUN_ON_AUDIO_THREAD(AddAnotherInput); WaitForData(); RUN_ON_AUDIO_THREAD(Stop); RUN_ON_AUDIO_THREAD(Close); RUN_ON_AUDIO_THREAD(RemoveOneInputInFIFOOrder); } TEST_F(WebContentsAudioInputStreamTest, MirroringOneStreamWithTargetChange) { RUN_ON_AUDIO_THREAD(Open); RUN_ON_AUDIO_THREAD(Start); RUN_ON_AUDIO_THREAD(AddAnotherInput); WaitForData(); RUN_ON_AUDIO_THREAD(ChangeMirroringTarget); RUN_ON_AUDIO_THREAD(RemoveOneInputInFIFOOrder); RUN_ON_AUDIO_THREAD(AddAnotherInput); WaitForData(); RUN_ON_AUDIO_THREAD(Stop); RUN_ON_AUDIO_THREAD(Close); RUN_ON_AUDIO_THREAD(RemoveOneInputInFIFOOrder); } TEST_F(WebContentsAudioInputStreamTest, MirroringLostTarget) { RUN_ON_AUDIO_THREAD(Open); RUN_ON_AUDIO_THREAD(Start); RUN_ON_AUDIO_THREAD(AddAnotherInput); WaitForData(); RUN_ON_AUDIO_THREAD(LoseMirroringTarget); RUN_ON_AUDIO_THREAD(RemoveOneInputInFIFOOrder); RUN_ON_AUDIO_THREAD(Stop); RUN_ON_AUDIO_THREAD(Close); } TEST_F(WebContentsAudioInputStreamTest, MirroringMultipleStreamsAndTargets) { RUN_ON_AUDIO_THREAD(Open); RUN_ON_AUDIO_THREAD(Start); RUN_ON_AUDIO_THREAD(AddAnotherInput); WaitForData(); RUN_ON_AUDIO_THREAD(AddAnotherInput); RUN_ON_AUDIO_THREAD(AddAnotherInput); RUN_ON_AUDIO_THREAD(AddAnotherInput); WaitForData(); RUN_ON_AUDIO_THREAD(ChangeMirroringTarget); RUN_ON_AUDIO_THREAD(RemoveOneInputInFIFOOrder); WaitForData(); RUN_ON_AUDIO_THREAD(RemoveOneInputInFIFOOrder); RUN_ON_AUDIO_THREAD(RemoveOneInputInFIFOOrder); RUN_ON_AUDIO_THREAD(AddAnotherInput); WaitForData(); RUN_ON_AUDIO_THREAD(RemoveOneInputInFIFOOrder); WaitForData(); RUN_ON_AUDIO_THREAD(ChangeMirroringTarget); RUN_ON_AUDIO_THREAD(RemoveOneInputInFIFOOrder); RUN_ON_AUDIO_THREAD(Stop); RUN_ON_AUDIO_THREAD(Close); } } // namespace content
; ; jcgryext.asm - grayscale colorspace conversion (MMX) ; ; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB ; Copyright 2011 D. R. Commander ; ; Based on ; x86 SIMD extension for IJG JPEG library ; Copyright (C) 1999-2006, MIYASAKA Masaru. ; For conditions of distribution and use, see copyright notice in jsimdext.inc ; ; This file should be assembled with NASM (Netwide Assembler), ; can *not* be assembled with Microsoft's MASM or any compatible ; assembler (including Borland's Turbo Assembler). ; NASM is available from http://nasm.sourceforge.net/ or ; http://sourceforge.net/project/showfiles.php?group_id=6208 ; ; [TAB8] %include "jcolsamp.inc" ; -------------------------------------------------------------------------- ; ; Convert some rows of samples to the output colorspace. ; ; GLOBAL(void) ; jsimd_rgb_gray_convert_mmx (JDIMENSION img_width, ; JSAMPARRAY input_buf, JSAMPIMAGE output_buf, ; JDIMENSION output_row, int num_rows); ; %define img_width(b) (b)+8 ; JDIMENSION img_width %define input_buf(b) (b)+12 ; JSAMPARRAY input_buf %define output_buf(b) (b)+16 ; JSAMPIMAGE output_buf %define output_row(b) (b)+20 ; JDIMENSION output_row %define num_rows(b) (b)+24 ; int num_rows %define original_ebp ebp+0 %define wk(i) ebp-(WK_NUM-(i))*SIZEOF_MMWORD ; mmword wk[WK_NUM] %define WK_NUM 2 %define gotptr wk(0)-SIZEOF_POINTER ; void * gotptr align 16 global EXTN(jsimd_rgb_gray_convert_mmx) PRIVATE EXTN(jsimd_rgb_gray_convert_mmx): push ebp mov eax,esp ; eax = original ebp sub esp, byte 4 and esp, byte (-SIZEOF_MMWORD) ; align to 64 bits mov [esp],eax mov ebp,esp ; ebp = aligned ebp lea esp, [wk(0)] pushpic eax ; make a room for GOT address push ebx ; push ecx ; need not be preserved ; push edx ; need not be preserved push esi push edi get_GOT ebx ; get GOT address movpic POINTER [gotptr], ebx ; save GOT address mov ecx, JDIMENSION [img_width(eax)] ; num_cols test ecx,ecx jz near .return push ecx mov esi, JSAMPIMAGE [output_buf(eax)] mov ecx, JDIMENSION [output_row(eax)] mov edi, JSAMPARRAY [esi+0*SIZEOF_JSAMPARRAY] lea edi, [edi+ecx*SIZEOF_JSAMPROW] pop ecx mov esi, JSAMPARRAY [input_buf(eax)] mov eax, INT [num_rows(eax)] test eax,eax jle near .return alignx 16,7 .rowloop: pushpic eax push edi push esi push ecx ; col mov esi, JSAMPROW [esi] ; inptr mov edi, JSAMPROW [edi] ; outptr0 movpic eax, POINTER [gotptr] ; load GOT address (eax) cmp ecx, byte SIZEOF_MMWORD jae short .columnloop alignx 16,7 %if RGB_PIXELSIZE == 3 ; --------------- .column_ld1: push eax push edx lea ecx,[ecx+ecx*2] ; imul ecx,RGB_PIXELSIZE test cl, SIZEOF_BYTE jz short .column_ld2 sub ecx, byte SIZEOF_BYTE xor eax,eax mov al, BYTE [esi+ecx] .column_ld2: test cl, SIZEOF_WORD jz short .column_ld4 sub ecx, byte SIZEOF_WORD xor edx,edx mov dx, WORD [esi+ecx] shl eax, WORD_BIT or eax,edx .column_ld4: movd mmA,eax pop edx pop eax test cl, SIZEOF_DWORD jz short .column_ld8 sub ecx, byte SIZEOF_DWORD movd mmG, DWORD [esi+ecx] psllq mmA, DWORD_BIT por mmA,mmG .column_ld8: test cl, SIZEOF_MMWORD jz short .column_ld16 movq mmG,mmA movq mmA, MMWORD [esi+0*SIZEOF_MMWORD] mov ecx, SIZEOF_MMWORD jmp short .rgb_gray_cnv .column_ld16: test cl, 2*SIZEOF_MMWORD mov ecx, SIZEOF_MMWORD jz short .rgb_gray_cnv movq mmF,mmA movq mmA, MMWORD [esi+0*SIZEOF_MMWORD] movq mmG, MMWORD [esi+1*SIZEOF_MMWORD] jmp short .rgb_gray_cnv alignx 16,7 .columnloop: movq mmA, MMWORD [esi+0*SIZEOF_MMWORD] movq mmG, MMWORD [esi+1*SIZEOF_MMWORD] movq mmF, MMWORD [esi+2*SIZEOF_MMWORD] .rgb_gray_cnv: ; mmA=(00 10 20 01 11 21 02 12) ; mmG=(22 03 13 23 04 14 24 05) ; mmF=(15 25 06 16 26 07 17 27) movq mmD,mmA psllq mmA,4*BYTE_BIT ; mmA=(-- -- -- -- 00 10 20 01) psrlq mmD,4*BYTE_BIT ; mmD=(11 21 02 12 -- -- -- --) punpckhbw mmA,mmG ; mmA=(00 04 10 14 20 24 01 05) psllq mmG,4*BYTE_BIT ; mmG=(-- -- -- -- 22 03 13 23) punpcklbw mmD,mmF ; mmD=(11 15 21 25 02 06 12 16) punpckhbw mmG,mmF ; mmG=(22 26 03 07 13 17 23 27) movq mmE,mmA psllq mmA,4*BYTE_BIT ; mmA=(-- -- -- -- 00 04 10 14) psrlq mmE,4*BYTE_BIT ; mmE=(20 24 01 05 -- -- -- --) punpckhbw mmA,mmD ; mmA=(00 02 04 06 10 12 14 16) psllq mmD,4*BYTE_BIT ; mmD=(-- -- -- -- 11 15 21 25) punpcklbw mmE,mmG ; mmE=(20 22 24 26 01 03 05 07) punpckhbw mmD,mmG ; mmD=(11 13 15 17 21 23 25 27) pxor mmH,mmH movq mmC,mmA punpcklbw mmA,mmH ; mmA=(00 02 04 06) punpckhbw mmC,mmH ; mmC=(10 12 14 16) movq mmB,mmE punpcklbw mmE,mmH ; mmE=(20 22 24 26) punpckhbw mmB,mmH ; mmB=(01 03 05 07) movq mmF,mmD punpcklbw mmD,mmH ; mmD=(11 13 15 17) punpckhbw mmF,mmH ; mmF=(21 23 25 27) %else ; RGB_PIXELSIZE == 4 ; ----------- .column_ld1: test cl, SIZEOF_MMWORD/8 jz short .column_ld2 sub ecx, byte SIZEOF_MMWORD/8 movd mmA, DWORD [esi+ecx*RGB_PIXELSIZE] .column_ld2: test cl, SIZEOF_MMWORD/4 jz short .column_ld4 sub ecx, byte SIZEOF_MMWORD/4 movq mmF,mmA movq mmA, MMWORD [esi+ecx*RGB_PIXELSIZE] .column_ld4: test cl, SIZEOF_MMWORD/2 mov ecx, SIZEOF_MMWORD jz short .rgb_gray_cnv movq mmD,mmA movq mmC,mmF movq mmA, MMWORD [esi+0*SIZEOF_MMWORD] movq mmF, MMWORD [esi+1*SIZEOF_MMWORD] jmp short .rgb_gray_cnv alignx 16,7 .columnloop: movq mmA, MMWORD [esi+0*SIZEOF_MMWORD] movq mmF, MMWORD [esi+1*SIZEOF_MMWORD] movq mmD, MMWORD [esi+2*SIZEOF_MMWORD] movq mmC, MMWORD [esi+3*SIZEOF_MMWORD] .rgb_gray_cnv: ; mmA=(00 10 20 30 01 11 21 31) ; mmF=(02 12 22 32 03 13 23 33) ; mmD=(04 14 24 34 05 15 25 35) ; mmC=(06 16 26 36 07 17 27 37) movq mmB,mmA punpcklbw mmA,mmF ; mmA=(00 02 10 12 20 22 30 32) punpckhbw mmB,mmF ; mmB=(01 03 11 13 21 23 31 33) movq mmG,mmD punpcklbw mmD,mmC ; mmD=(04 06 14 16 24 26 34 36) punpckhbw mmG,mmC ; mmG=(05 07 15 17 25 27 35 37) movq mmE,mmA punpcklwd mmA,mmD ; mmA=(00 02 04 06 10 12 14 16) punpckhwd mmE,mmD ; mmE=(20 22 24 26 30 32 34 36) movq mmH,mmB punpcklwd mmB,mmG ; mmB=(01 03 05 07 11 13 15 17) punpckhwd mmH,mmG ; mmH=(21 23 25 27 31 33 35 37) pxor mmF,mmF movq mmC,mmA punpcklbw mmA,mmF ; mmA=(00 02 04 06) punpckhbw mmC,mmF ; mmC=(10 12 14 16) movq mmD,mmB punpcklbw mmB,mmF ; mmB=(01 03 05 07) punpckhbw mmD,mmF ; mmD=(11 13 15 17) movq mmG,mmE punpcklbw mmE,mmF ; mmE=(20 22 24 26) punpckhbw mmG,mmF ; mmG=(30 32 34 36) punpcklbw mmF,mmH punpckhbw mmH,mmH psrlw mmF,BYTE_BIT ; mmF=(21 23 25 27) psrlw mmH,BYTE_BIT ; mmH=(31 33 35 37) %endif ; RGB_PIXELSIZE ; --------------- ; mm0=(R0 R2 R4 R6)=RE, mm2=(G0 G2 G4 G6)=GE, mm4=(B0 B2 B4 B6)=BE ; mm1=(R1 R3 R5 R7)=RO, mm3=(G1 G3 G5 G7)=GO, mm5=(B1 B3 B5 B7)=BO ; (Original) ; Y = 0.29900 * R + 0.58700 * G + 0.11400 * B ; ; (This implementation) ; Y = 0.29900 * R + 0.33700 * G + 0.11400 * B + 0.25000 * G movq mm6,mm1 punpcklwd mm1,mm3 punpckhwd mm6,mm3 pmaddwd mm1,[GOTOFF(eax,PW_F0299_F0337)] ; mm1=ROL*FIX(0.299)+GOL*FIX(0.337) pmaddwd mm6,[GOTOFF(eax,PW_F0299_F0337)] ; mm6=ROH*FIX(0.299)+GOH*FIX(0.337) movq mm7, mm6 ; mm7=ROH*FIX(0.299)+GOH*FIX(0.337) movq mm6,mm0 punpcklwd mm0,mm2 punpckhwd mm6,mm2 pmaddwd mm0,[GOTOFF(eax,PW_F0299_F0337)] ; mm0=REL*FIX(0.299)+GEL*FIX(0.337) pmaddwd mm6,[GOTOFF(eax,PW_F0299_F0337)] ; mm6=REH*FIX(0.299)+GEH*FIX(0.337) movq MMWORD [wk(0)], mm0 ; wk(0)=REL*FIX(0.299)+GEL*FIX(0.337) movq MMWORD [wk(1)], mm6 ; wk(1)=REH*FIX(0.299)+GEH*FIX(0.337) movq mm0, mm5 ; mm0=BO movq mm6, mm4 ; mm6=BE movq mm4,mm0 punpcklwd mm0,mm3 punpckhwd mm4,mm3 pmaddwd mm0,[GOTOFF(eax,PW_F0114_F0250)] ; mm0=BOL*FIX(0.114)+GOL*FIX(0.250) pmaddwd mm4,[GOTOFF(eax,PW_F0114_F0250)] ; mm4=BOH*FIX(0.114)+GOH*FIX(0.250) movq mm3,[GOTOFF(eax,PD_ONEHALF)] ; mm3=[PD_ONEHALF] paddd mm0, mm1 paddd mm4, mm7 paddd mm0,mm3 paddd mm4,mm3 psrld mm0,SCALEBITS ; mm0=YOL psrld mm4,SCALEBITS ; mm4=YOH packssdw mm0,mm4 ; mm0=YO movq mm4,mm6 punpcklwd mm6,mm2 punpckhwd mm4,mm2 pmaddwd mm6,[GOTOFF(eax,PW_F0114_F0250)] ; mm6=BEL*FIX(0.114)+GEL*FIX(0.250) pmaddwd mm4,[GOTOFF(eax,PW_F0114_F0250)] ; mm4=BEH*FIX(0.114)+GEH*FIX(0.250) movq mm2,[GOTOFF(eax,PD_ONEHALF)] ; mm2=[PD_ONEHALF] paddd mm6, MMWORD [wk(0)] paddd mm4, MMWORD [wk(1)] paddd mm6,mm2 paddd mm4,mm2 psrld mm6,SCALEBITS ; mm6=YEL psrld mm4,SCALEBITS ; mm4=YEH packssdw mm6,mm4 ; mm6=YE psllw mm0,BYTE_BIT por mm6,mm0 ; mm6=Y movq MMWORD [edi], mm6 ; Save Y sub ecx, byte SIZEOF_MMWORD add esi, byte RGB_PIXELSIZE*SIZEOF_MMWORD ; inptr add edi, byte SIZEOF_MMWORD ; outptr0 cmp ecx, byte SIZEOF_MMWORD jae near .columnloop test ecx,ecx jnz near .column_ld1 pop ecx ; col pop esi pop edi poppic eax add esi, byte SIZEOF_JSAMPROW ; input_buf add edi, byte SIZEOF_JSAMPROW dec eax ; num_rows jg near .rowloop emms ; empty MMX state .return: pop edi pop esi ; pop edx ; need not be preserved ; pop ecx ; need not be preserved pop ebx mov esp,ebp ; esp <- aligned ebp pop esp ; esp <- original ebp pop ebp ret ; For some reason, the OS X linker does not honor the request to align the ; segment unless we do this. align 16
AI_ATTACK_CONDITION_DIRECTION_LEFT = %00000001 AI_ATTACK_CONDITION_DIRECTION_RIGHT = %00000010 AI_ATTACK_CONDITION_AIRBORNE = %00000100 AI_ATTACK_CONDITION_GROUNDED = %00001000 ; Readable shorthand to get the negation of a constant 8bit value #define NOT(x) <(-x-1) ai_action_double_jump: AI_ACTION_STEP(0, 0) AI_ACTION_STEP(CONTROLLER_INPUT_JUMP, 9) AI_ACTION_STEP(0, 0) AI_ACTION_STEP(CONTROLLER_INPUT_JUMP, 9) AI_ACTION_END_STEPS ai_action_jump: AI_ACTION_STEP(0, 0) AI_ACTION_STEP(CONTROLLER_INPUT_JUMP, 19) AI_ACTION_END_STEPS ai_action_left_tilt: AI_ACTION_STEP(CONTROLLER_INPUT_ATTACK_LEFT, 0) AI_ACTION_STEP(0, 19) AI_ACTION_END_STEPS ai_action_right_tilt: AI_ACTION_STEP(CONTROLLER_INPUT_ATTACK_RIGHT, 0) AI_ACTION_STEP(0, 19) AI_ACTION_END_STEPS ; Can be used for aerial down and down tilt - same duration ;TODO move it to Sinbad specific actions ai_action_down_tilt: AI_ACTION_STEP(CONTROLLER_INPUT_DOWN_TILT, 0) AI_ACTION_STEP(0, 19) AI_ACTION_END_STEPS ai_action_special_up: AI_ACTION_STEP(CONTROLLER_INPUT_SPECIAL_UP, 0) AI_ACTION_END_STEPS ai_action_tap_down: AI_ACTION_STEP(CONTROLLER_INPUT_TECH, 0) AI_ACTION_STEP(0, 0) AI_ACTION_END_STEPS ai_action_idle: AI_ACTION_STEP(0, 0) AI_ACTION_END_STEPS ai_level_to_delay: .byt 30, 10, 1 ai_init: .( ; Reset current action lda #AI_STEP_FINAL sta ai_current_action_step ; Set delay configuration depending on difficulty level ldy config_ai_level dey lda ai_level_to_delay, y sta ai_max_delay sta ai_delay rts .) ; Set controller B state ; ; Can watch game state to inteligently set controller B state ai_tick: .( .( ; Reset controller's state - extra security, bellow code should ; ensure that something is written to controller's state lda #$00 sta controller_b_btns ; Switch to player B's character bank ldx config_player_b_character SWITCH_BANK(characters_bank_number COMMA x) ; Continue the current action if there is one lda ai_current_action_step cmp #AI_STEP_FINAL bne do_action ; Run selectors until an action is found ; Note - the last selector must always return an action, ; not finding any action triggers undefined behaviour find_action: ; Push first selectors table's address (lsb first, msb second) lda characters_properties_lsb, x sta tmpfield1 lda characters_properties_msb, x sta tmpfield2 ldy #CHARACTERS_PROPERTIES_AI_ACTION_SELECTORS_OFFSET lda (tmpfield1), y pha iny lda (tmpfield1), y pha run_current_selector: ; Retrieve selector table pointer pla sta tmpfield4 pla sta tmpfield3 ; Push pointer + 1 clc adc #2 pha lda tmpfield4 adc #0 pha ; Retrive selector address ldy #0 lda (tmpfield3), y sta tmpfield1 iny lda (tmpfield3), y sta tmpfield2 ; Call selector txa pha jsr call_pointed_subroutine pla tax ; Loop if selector did not start a new action lda ai_current_action_step cmp #AI_STEP_FINAL beq run_current_selector ; Remove selector table pointer from stack pla pla ; Actually continue the current action, there must be one do_action: jsr ai_continue_action lda ai_current_action_step cmp #AI_STEP_FINAL beq find_action rts .) .) ai_continue_action: .( zp_current_action_lsb = tmpfield1 zp_current_action_msb = tmpfield2 lda ai_current_action_lsb sta zp_current_action_lsb lda ai_current_action_msb sta zp_current_action_msb ldy ai_current_action_step iny lda (zp_current_action_lsb), y cmp ai_current_action_counter bcc next_step dey jmp set_controller next_step: iny sty ai_current_action_step lda #0 sta ai_current_action_counter lda (zp_current_action_lsb), y cmp #AI_STEP_FINAL bne set_controller ;lda #AI_STEP_FINAL sta ai_current_action_step jmp end set_controller: lda (zp_current_action_lsb), y ora ai_current_action_modifier sta controller_b_btns inc ai_current_action_counter end: rts .) ; Selector that search for an attack that can hit player A ai_attack_selector: .( hitbox_left = tmpfield1 hitbox_right = tmpfield2 hitbox_top = tmpfield3 hitbox_bottom = tmpfield4 hitbox_left_msb = tmpfield9 hitbox_right_msb = tmpfield10 hitbox_top_msb = tmpfield11 hitbox_bottom_msb = tmpfield12 hurtbox_left = tmpfield5 hurtbox_right = tmpfield6 hurtbox_top = tmpfield7 hurtbox_bottom = tmpfield8 hurtbox_left_msb = tmpfield13 hurtbox_right_msb = tmpfield14 hurtbox_top_msb = tmpfield15 hurtbox_bottom_msb = tmpfield16 condition_mask = extra_tmpfield1 nb_attacks = extra_tmpfield2 attacks_table = extra_tmpfield3 ; extra_tmpfield4 reserved for attacks table msb attacks_msb_table = extra_tmpfield5 ; extra_tmpfield6 reserved for attacks msb table msb ; Store attacks table address and its size in fixed location ldx config_player_b_character lda characters_properties_lsb, x sta tmpfield1 lda characters_properties_msb, x sta tmpfield2 ldy #CHARACTERS_PROPERTIES_AI_ATTACKS_OFFSET lda (tmpfield1), y sta attacks_table iny lda (tmpfield1), y sta attacks_table+1 ldy #CHARACTERS_PROPERTIES_AI_NB_ATTACKS_OFFSET lda (tmpfield1), y sta nb_attacks ; Store attacks MSBs table in fixed location ;TODO investigate - change table format to one big table ; pro - it would make this step unecessary ; pro - free extra_tmpfields 5 and 6 (unsed only there) ; con - it would slightly change the code below (that's why it is not done in the first implementation, avoid changing logic) ; con - size limit would be 256 bytes (21 attacks) instead of current 256*2 (42 attacks) asl asl clc adc nb_attacks ;clc ; useless, that would mean that attacks table is larger than supported (256 bytes for each part) adc nb_attacks ;clc ; useless, that would mean that attacks table is larger than supported (256 bytes for each part) adc attacks_table sta attacks_msb_table lda #0 adc attacks_table+1 sta attacks_msb_table+1 ; Compute condition mask ; Each matched condition is set to zero in the mask, non matched condition are set to one ; Each necessary condition in constraints are set to one ; mask & constraints = zero if all necessary conditions are met lda #$ff ldx player_b_direction bne right_facing and #NOT(AI_ATTACK_CONDITION_DIRECTION_LEFT) jmp end_direction_flag right_facing: and #NOT(AI_ATTACK_CONDITION_DIRECTION_RIGHT) end_direction_flag: ldx player_b_grounded bne grounded and #NOT(AI_ATTACK_CONDITION_AIRBORNE) jmp end_ground_flag grounded: and #NOT(AI_ATTACK_CONDITION_GROUNDED) end_ground_flag: sta condition_mask ; Find an attack to trigger ldx nb_attacks ldy #$00 check_one_attack: ; Test if attack's condition match condition mask lda (attacks_table), y iny bit condition_mask beq condition_ok ; Condition failed, skip to next attack iny iny iny iny jmp next_attack condition_ok: ; Test if attack's hitbox overlaps player A's hurtbox lda (attacks_table), y clc adc player_b_x sta hitbox_left lda (attacks_msb_table), y adc player_b_x_screen sta hitbox_left_msb iny lda (attacks_table), y clc adc player_b_x sta hitbox_right lda (attacks_msb_table), y adc player_b_x_screen sta hitbox_right_msb iny lda (attacks_table), y clc adc player_b_y sta hitbox_top lda (attacks_msb_table), y adc player_b_y_screen sta hitbox_top_msb iny lda (attacks_table), y clc adc player_b_y sta hitbox_bottom lda (attacks_msb_table), y adc player_b_y_screen sta hitbox_bottom_msb iny lda player_a_hurtbox_left sta hurtbox_left lda player_a_hurtbox_left_msb sta hurtbox_left_msb lda player_a_hurtbox_right sta hurtbox_right lda player_a_hurtbox_right_msb sta hurtbox_right_msb lda player_a_hurtbox_top sta hurtbox_top lda player_a_hurtbox_top_msb sta hurtbox_top_msb lda player_a_hurtbox_bottom sta hurtbox_bottom lda player_a_hurtbox_bottom_msb sta hurtbox_bottom_msb jsr boxes_overlap bne next_attack ; Boxes overlap, trigger this attack lda (attacks_table), y sta ai_current_action_lsb lda (attacks_msb_table), y sta ai_current_action_msb lda #0 sta ai_current_action_modifier sta ai_current_action_step sta ai_current_action_counter jsr ai_delay_action jmp end ; Check the next attack next_attack: iny dex beq end jmp check_one_attack end: rts .) ; Selector that makes the character shield if about to be hit ai_shield_selector: .( ; Do not try to shield mid-air ldx player_b_grounded beq end ; Do not shield if opponent's hitbox is inactive ldx player_a_hitbox_enabled beq end ; Do not shield if opponent's hitbox is far away lda player_a_x cmp player_b_x bcs bot_on_the_left bot_on_the_right: lda player_b_x sec sbc player_a_hitbox_right jmp distance_computed bot_on_the_left: lda player_a_hitbox_left sec sbc player_b_x distance_computed: cmp #32 bcs end ; Set idle action with down-left modifier (aka shield, or slide-tech depending on conditions) lda #CONTROLLER_BTN_DOWN+CONTROLLER_BTN_LEFT sta ai_current_action_modifier lda #<ai_action_idle sta ai_current_action_lsb lda #>ai_action_idle sta ai_current_action_msb lda #0 sta ai_current_action_step sta ai_current_action_counter end: rts .) ; Selector that makes the character move toward a safe distance of its opponent ; ; It will take action only if in thrown state, the idea is to try to come back to ; a neutral game after being hit. ai_space_selector: .( spot_x = tmpfield1 lda player_b_state cmp #PLAYER_STATE_THROWN bne end ; Compute spot's position lda player_a_x cmp player_b_x bcs bot_on_the_left bot_on_the_right: clc adc #32 jmp spot_computed bot_on_the_left: sec sbc #32 spot_computed: sta spot_x ; Set the modifier to spot's direction lda #CONTROLLER_BTN_LEFT sta ai_current_action_modifier lda spot_x cmp player_b_x bcc direction_set lda #CONTROLLER_BTN_RIGHT sta ai_current_action_modifier direction_set: ; Set idle action (we count on the modifier to move the character) lda #<ai_action_idle sta ai_current_action_lsb lda #>ai_action_idle sta ai_current_action_msb lda #0 sta ai_current_action_step sta ai_current_action_counter end: rts .) ; Selector that makes the character move toward its opponent ; ; This selector always selects an action. ai_chase_selector: .( ; Note - chasing do not care about screen, only use 8bit unsigned positions ; ; The effect is that, when the player is out of screen, the bot tends to flee him ; since the bot actually sees him on the other side of the screen. ; ; Handling two bytes signed position would have the effect of making the bot go ; to the edge of the platform. Problem, the bot is really bad on platforms edges, ; oscilating between chasing and recovering until the indecision kills him. ; ; Exception, if the bot is out of screen, it comes back to the screen. stage_element_handler_lsb = tmpfield1 stage_element_handler_msb = tmpfield2 collision_point_x_lsb = tmpfield3 collision_point_y_lsb = tmpfield4 collision_point_x_msb = tmpfield5 collision_point_y_msb = tmpfield6 ; If grounded on smooth platform and opponent bellow, tap down SIGNED_CMP(player_b_y, player_b_y_screen, player_a_y, player_a_y_screen) bpl no_tap_down ldx player_b_grounded beq no_tap_down lda stage_data, x cmp #STAGE_ELEMENT_SMOOTH_PLATFORM bne check_oos_platform jmp tap_down check_oos_platform: cmp #STAGE_ELEMENT_OOS_SMOOTH_PLATFORM bne no_tap_down jmp tap_down no_tap_down: ; Set the modifier to opponent's direction (or to comeback on screen if needed) lda player_b_x_screen bmi go_right bne go_left lda player_a_x cmp player_b_x bcc go_left go_right: lda #CONTROLLER_BTN_RIGHT jmp direction_set go_left: lda #CONTROLLER_BTN_LEFT direction_set: sta ai_current_action_modifier ; Choose between jumping or not lda player_b_state cmp #PLAYER_STATE_STANDING beq jump_if_higher cmp #PLAYER_STATE_RUNNING bne dont_jump jump_if_higher: lda player_a_y cmp player_b_y bcs end_jump_if_higher sec sbc player_b_y cmp #16 bcs jump end_jump_if_higher: ; Jump if there is a wall in front of the bot (just sensor a hard platform at "bot.x +- 7") lda #<check_in_platform sta stage_element_handler_lsb lda #>check_in_platform sta stage_element_handler_msb lda ai_current_action_modifier cmp #CONTROLLER_BTN_LEFT beq negative_offset lda #7 sta collision_point_x_lsb lda #0 sta collision_point_x_msb jmp end_set_offset negative_offset: lda #$f9 sta collision_point_x_lsb lda #$ff sta collision_point_x_msb end_set_offset: lda player_b_x clc adc collision_point_x_lsb sta collision_point_x_lsb lda player_b_x_screen adc collision_point_x_msb sta collision_point_x_msb lda player_b_y sta collision_point_y_lsb lda player_b_y_screen sta collision_point_y_msb jsr stage_iterate_all_elements cpy #$ff ; technically useless as stage_iterate_all_elements already does it, but it is not ensured in its description beq jump dont_jump: lda #<ai_action_idle sta ai_current_action_lsb lda #>ai_action_idle sta ai_current_action_msb jmp action_set jump: lda #<ai_action_double_jump sta ai_current_action_lsb lda #>ai_action_double_jump sta ai_current_action_msb jmp action_set tap_down: lda #0 sta ai_current_action_modifier lda #<ai_action_tap_down sta ai_current_action_lsb lda #>ai_action_tap_down sta ai_current_action_msb ;jmp action_set ; useless, fallthrough ; Begin the selected action action_set: lda #0 sta ai_current_action_step sta ai_current_action_counter rts .) ; Replace the selected action by an iddle one if needed because of difficulty level ai_delay_action: .( dec ai_delay beq no_delay ; Delay the action by replacing it by an idle action lda #<ai_action_idle sta ai_current_action_lsb lda #>ai_action_idle sta ai_current_action_msb lda #0 sta ai_current_action_modifier sta ai_current_action_step sta ai_current_action_counter jmp end ; Let the action execute normally and reset delay counter no_delay: lda ai_max_delay sta ai_delay end: rts .)
_forktest: file format elf32-i386 Disassembly of section .text: 00000000 <main>: printf(1, "fork test OK\n"); } 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 forktest(); 11: e8 3a 00 00 00 call 50 <forktest> exit(); 16: e8 87 03 00 00 call 3a2 <exit> 1b: 66 90 xchg %ax,%ax 1d: 66 90 xchg %ax,%ax 1f: 90 nop 00000020 <printf>: { 20: 55 push %ebp 21: 89 e5 mov %esp,%ebp 23: 53 push %ebx 24: 83 ec 10 sub $0x10,%esp 27: 8b 5d 0c mov 0xc(%ebp),%ebx write(fd, s, strlen(s)); 2a: 53 push %ebx 2b: e8 a0 01 00 00 call 1d0 <strlen> 30: 83 c4 0c add $0xc,%esp 33: 50 push %eax 34: 53 push %ebx 35: ff 75 08 pushl 0x8(%ebp) 38: e8 85 03 00 00 call 3c2 <write> } 3d: 83 c4 10 add $0x10,%esp 40: 8b 5d fc mov -0x4(%ebp),%ebx 43: c9 leave 44: c3 ret 45: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 49: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000050 <forktest>: { 50: 55 push %ebp 51: 89 e5 mov %esp,%ebp 53: 53 push %ebx for(n=0; n<N; n++){ 54: 31 db xor %ebx,%ebx { 56: 83 ec 10 sub $0x10,%esp write(fd, s, strlen(s)); 59: 68 74 04 00 00 push $0x474 5e: e8 6d 01 00 00 call 1d0 <strlen> 63: 83 c4 0c add $0xc,%esp 66: 50 push %eax 67: 68 74 04 00 00 push $0x474 6c: 6a 01 push $0x1 6e: e8 4f 03 00 00 call 3c2 <write> 73: 83 c4 10 add $0x10,%esp 76: eb 19 jmp 91 <forktest+0x41> 78: 90 nop 79: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi if(pid == 0) 80: 0f 84 7c 00 00 00 je 102 <forktest+0xb2> for(n=0; n<N; n++){ 86: 83 c3 01 add $0x1,%ebx 89: 81 fb e8 03 00 00 cmp $0x3e8,%ebx 8f: 74 4f je e0 <forktest+0x90> pid = fork(); 91: e8 04 03 00 00 call 39a <fork> if(pid < 0) 96: 85 c0 test %eax,%eax 98: 79 e6 jns 80 <forktest+0x30> for(; n > 0; n--){ 9a: 85 db test %ebx,%ebx 9c: 74 10 je ae <forktest+0x5e> 9e: 66 90 xchg %ax,%ax if(wait() < 0){ a0: e8 05 03 00 00 call 3aa <wait> a5: 85 c0 test %eax,%eax a7: 78 5e js 107 <forktest+0xb7> for(; n > 0; n--){ a9: 83 eb 01 sub $0x1,%ebx ac: 75 f2 jne a0 <forktest+0x50> if(wait() != -1){ ae: e8 f7 02 00 00 call 3aa <wait> b3: 83 f8 ff cmp $0xffffffff,%eax b6: 75 71 jne 129 <forktest+0xd9> write(fd, s, strlen(s)); b8: 83 ec 0c sub $0xc,%esp bb: 68 a6 04 00 00 push $0x4a6 c0: e8 0b 01 00 00 call 1d0 <strlen> c5: 83 c4 0c add $0xc,%esp c8: 50 push %eax c9: 68 a6 04 00 00 push $0x4a6 ce: 6a 01 push $0x1 d0: e8 ed 02 00 00 call 3c2 <write> } d5: 8b 5d fc mov -0x4(%ebp),%ebx d8: c9 leave d9: c3 ret da: 8d b6 00 00 00 00 lea 0x0(%esi),%esi write(fd, s, strlen(s)); e0: 83 ec 0c sub $0xc,%esp e3: 68 b4 04 00 00 push $0x4b4 e8: e8 e3 00 00 00 call 1d0 <strlen> ed: 83 c4 0c add $0xc,%esp f0: 50 push %eax f1: 68 b4 04 00 00 push $0x4b4 f6: 6a 01 push $0x1 f8: e8 c5 02 00 00 call 3c2 <write> exit(); fd: e8 a0 02 00 00 call 3a2 <exit> exit(); 102: e8 9b 02 00 00 call 3a2 <exit> write(fd, s, strlen(s)); 107: 83 ec 0c sub $0xc,%esp 10a: 68 7f 04 00 00 push $0x47f 10f: e8 bc 00 00 00 call 1d0 <strlen> 114: 83 c4 0c add $0xc,%esp 117: 50 push %eax 118: 68 7f 04 00 00 push $0x47f 11d: 6a 01 push $0x1 11f: e8 9e 02 00 00 call 3c2 <write> exit(); 124: e8 79 02 00 00 call 3a2 <exit> write(fd, s, strlen(s)); 129: 83 ec 0c sub $0xc,%esp 12c: 68 93 04 00 00 push $0x493 131: e8 9a 00 00 00 call 1d0 <strlen> 136: 83 c4 0c add $0xc,%esp 139: 50 push %eax 13a: 68 93 04 00 00 push $0x493 13f: 6a 01 push $0x1 141: e8 7c 02 00 00 call 3c2 <write> exit(); 146: e8 57 02 00 00 call 3a2 <exit> 14b: 66 90 xchg %ax,%ax 14d: 66 90 xchg %ax,%ax 14f: 90 nop 00000150 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, const char *t) { 150: 55 push %ebp 151: 89 e5 mov %esp,%ebp 153: 53 push %ebx 154: 8b 45 08 mov 0x8(%ebp),%eax 157: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) 15a: 89 c2 mov %eax,%edx 15c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 160: 83 c1 01 add $0x1,%ecx 163: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 167: 83 c2 01 add $0x1,%edx 16a: 84 db test %bl,%bl 16c: 88 5a ff mov %bl,-0x1(%edx) 16f: 75 ef jne 160 <strcpy+0x10> ; return os; } 171: 5b pop %ebx 172: 5d pop %ebp 173: c3 ret 174: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 17a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000180 <strcmp>: int strcmp(const char *p, const char *q) { 180: 55 push %ebp 181: 89 e5 mov %esp,%ebp 183: 53 push %ebx 184: 8b 55 08 mov 0x8(%ebp),%edx 187: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) 18a: 0f b6 02 movzbl (%edx),%eax 18d: 0f b6 19 movzbl (%ecx),%ebx 190: 84 c0 test %al,%al 192: 75 1c jne 1b0 <strcmp+0x30> 194: eb 2a jmp 1c0 <strcmp+0x40> 196: 8d 76 00 lea 0x0(%esi),%esi 199: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; 1a0: 83 c2 01 add $0x1,%edx while(*p && *p == *q) 1a3: 0f b6 02 movzbl (%edx),%eax p++, q++; 1a6: 83 c1 01 add $0x1,%ecx 1a9: 0f b6 19 movzbl (%ecx),%ebx while(*p && *p == *q) 1ac: 84 c0 test %al,%al 1ae: 74 10 je 1c0 <strcmp+0x40> 1b0: 38 d8 cmp %bl,%al 1b2: 74 ec je 1a0 <strcmp+0x20> return (uchar)*p - (uchar)*q; 1b4: 29 d8 sub %ebx,%eax } 1b6: 5b pop %ebx 1b7: 5d pop %ebp 1b8: c3 ret 1b9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 1c0: 31 c0 xor %eax,%eax return (uchar)*p - (uchar)*q; 1c2: 29 d8 sub %ebx,%eax } 1c4: 5b pop %ebx 1c5: 5d pop %ebp 1c6: c3 ret 1c7: 89 f6 mov %esi,%esi 1c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000001d0 <strlen>: uint strlen(const char *s) { 1d0: 55 push %ebp 1d1: 89 e5 mov %esp,%ebp 1d3: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 1d6: 80 39 00 cmpb $0x0,(%ecx) 1d9: 74 15 je 1f0 <strlen+0x20> 1db: 31 d2 xor %edx,%edx 1dd: 8d 76 00 lea 0x0(%esi),%esi 1e0: 83 c2 01 add $0x1,%edx 1e3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 1e7: 89 d0 mov %edx,%eax 1e9: 75 f5 jne 1e0 <strlen+0x10> ; return n; } 1eb: 5d pop %ebp 1ec: c3 ret 1ed: 8d 76 00 lea 0x0(%esi),%esi for(n = 0; s[n]; n++) 1f0: 31 c0 xor %eax,%eax } 1f2: 5d pop %ebp 1f3: c3 ret 1f4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 1fa: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000200 <memset>: void* memset(void *dst, int c, uint n) { 200: 55 push %ebp 201: 89 e5 mov %esp,%ebp 203: 57 push %edi 204: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 207: 8b 4d 10 mov 0x10(%ebp),%ecx 20a: 8b 45 0c mov 0xc(%ebp),%eax 20d: 89 d7 mov %edx,%edi 20f: fc cld 210: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 212: 89 d0 mov %edx,%eax 214: 5f pop %edi 215: 5d pop %ebp 216: c3 ret 217: 89 f6 mov %esi,%esi 219: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000220 <strchr>: char* strchr(const char *s, char c) { 220: 55 push %ebp 221: 89 e5 mov %esp,%ebp 223: 53 push %ebx 224: 8b 45 08 mov 0x8(%ebp),%eax 227: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 22a: 0f b6 10 movzbl (%eax),%edx 22d: 84 d2 test %dl,%dl 22f: 74 1d je 24e <strchr+0x2e> if(*s == c) 231: 38 d3 cmp %dl,%bl 233: 89 d9 mov %ebx,%ecx 235: 75 0d jne 244 <strchr+0x24> 237: eb 17 jmp 250 <strchr+0x30> 239: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 240: 38 ca cmp %cl,%dl 242: 74 0c je 250 <strchr+0x30> for(; *s; s++) 244: 83 c0 01 add $0x1,%eax 247: 0f b6 10 movzbl (%eax),%edx 24a: 84 d2 test %dl,%dl 24c: 75 f2 jne 240 <strchr+0x20> return (char*)s; return 0; 24e: 31 c0 xor %eax,%eax } 250: 5b pop %ebx 251: 5d pop %ebp 252: c3 ret 253: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 259: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000260 <gets>: char* gets(char *buf, int max) { 260: 55 push %ebp 261: 89 e5 mov %esp,%ebp 263: 57 push %edi 264: 56 push %esi 265: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 266: 31 f6 xor %esi,%esi 268: 89 f3 mov %esi,%ebx { 26a: 83 ec 1c sub $0x1c,%esp 26d: 8b 7d 08 mov 0x8(%ebp),%edi for(i=0; i+1 < max; ){ 270: eb 2f jmp 2a1 <gets+0x41> 272: 8d b6 00 00 00 00 lea 0x0(%esi),%esi cc = read(0, &c, 1); 278: 8d 45 e7 lea -0x19(%ebp),%eax 27b: 83 ec 04 sub $0x4,%esp 27e: 6a 01 push $0x1 280: 50 push %eax 281: 6a 00 push $0x0 283: e8 32 01 00 00 call 3ba <read> if(cc < 1) 288: 83 c4 10 add $0x10,%esp 28b: 85 c0 test %eax,%eax 28d: 7e 1c jle 2ab <gets+0x4b> break; buf[i++] = c; 28f: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 293: 83 c7 01 add $0x1,%edi 296: 88 47 ff mov %al,-0x1(%edi) if(c == '\n' || c == '\r') 299: 3c 0a cmp $0xa,%al 29b: 74 23 je 2c0 <gets+0x60> 29d: 3c 0d cmp $0xd,%al 29f: 74 1f je 2c0 <gets+0x60> for(i=0; i+1 < max; ){ 2a1: 83 c3 01 add $0x1,%ebx 2a4: 3b 5d 0c cmp 0xc(%ebp),%ebx 2a7: 89 fe mov %edi,%esi 2a9: 7c cd jl 278 <gets+0x18> 2ab: 89 f3 mov %esi,%ebx break; } buf[i] = '\0'; return buf; } 2ad: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 2b0: c6 03 00 movb $0x0,(%ebx) } 2b3: 8d 65 f4 lea -0xc(%ebp),%esp 2b6: 5b pop %ebx 2b7: 5e pop %esi 2b8: 5f pop %edi 2b9: 5d pop %ebp 2ba: c3 ret 2bb: 90 nop 2bc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 2c0: 8b 75 08 mov 0x8(%ebp),%esi 2c3: 8b 45 08 mov 0x8(%ebp),%eax 2c6: 01 de add %ebx,%esi 2c8: 89 f3 mov %esi,%ebx buf[i] = '\0'; 2ca: c6 03 00 movb $0x0,(%ebx) } 2cd: 8d 65 f4 lea -0xc(%ebp),%esp 2d0: 5b pop %ebx 2d1: 5e pop %esi 2d2: 5f pop %edi 2d3: 5d pop %ebp 2d4: c3 ret 2d5: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 2d9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000002e0 <stat>: int stat(const char *n, struct stat *st) { 2e0: 55 push %ebp 2e1: 89 e5 mov %esp,%ebp 2e3: 56 push %esi 2e4: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 2e5: 83 ec 08 sub $0x8,%esp 2e8: 6a 00 push $0x0 2ea: ff 75 08 pushl 0x8(%ebp) 2ed: e8 f0 00 00 00 call 3e2 <open> if(fd < 0) 2f2: 83 c4 10 add $0x10,%esp 2f5: 85 c0 test %eax,%eax 2f7: 78 27 js 320 <stat+0x40> return -1; r = fstat(fd, st); 2f9: 83 ec 08 sub $0x8,%esp 2fc: ff 75 0c pushl 0xc(%ebp) 2ff: 89 c3 mov %eax,%ebx 301: 50 push %eax 302: e8 f3 00 00 00 call 3fa <fstat> close(fd); 307: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 30a: 89 c6 mov %eax,%esi close(fd); 30c: e8 b9 00 00 00 call 3ca <close> return r; 311: 83 c4 10 add $0x10,%esp } 314: 8d 65 f8 lea -0x8(%ebp),%esp 317: 89 f0 mov %esi,%eax 319: 5b pop %ebx 31a: 5e pop %esi 31b: 5d pop %ebp 31c: c3 ret 31d: 8d 76 00 lea 0x0(%esi),%esi return -1; 320: be ff ff ff ff mov $0xffffffff,%esi 325: eb ed jmp 314 <stat+0x34> 327: 89 f6 mov %esi,%esi 329: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000330 <atoi>: int atoi(const char *s) { 330: 55 push %ebp 331: 89 e5 mov %esp,%ebp 333: 53 push %ebx 334: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 337: 0f be 11 movsbl (%ecx),%edx 33a: 8d 42 d0 lea -0x30(%edx),%eax 33d: 3c 09 cmp $0x9,%al n = 0; 33f: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 344: 77 1f ja 365 <atoi+0x35> 346: 8d 76 00 lea 0x0(%esi),%esi 349: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 350: 8d 04 80 lea (%eax,%eax,4),%eax 353: 83 c1 01 add $0x1,%ecx 356: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax while('0' <= *s && *s <= '9') 35a: 0f be 11 movsbl (%ecx),%edx 35d: 8d 5a d0 lea -0x30(%edx),%ebx 360: 80 fb 09 cmp $0x9,%bl 363: 76 eb jbe 350 <atoi+0x20> return n; } 365: 5b pop %ebx 366: 5d pop %ebp 367: c3 ret 368: 90 nop 369: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000370 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 370: 55 push %ebp 371: 89 e5 mov %esp,%ebp 373: 56 push %esi 374: 53 push %ebx 375: 8b 5d 10 mov 0x10(%ebp),%ebx 378: 8b 45 08 mov 0x8(%ebp),%eax 37b: 8b 75 0c mov 0xc(%ebp),%esi char *dst; const char *src; dst = vdst; src = vsrc; while(n-- > 0) 37e: 85 db test %ebx,%ebx 380: 7e 14 jle 396 <memmove+0x26> 382: 31 d2 xor %edx,%edx 384: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 388: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 38c: 88 0c 10 mov %cl,(%eax,%edx,1) 38f: 83 c2 01 add $0x1,%edx while(n-- > 0) 392: 39 d3 cmp %edx,%ebx 394: 75 f2 jne 388 <memmove+0x18> return vdst; } 396: 5b pop %ebx 397: 5e pop %esi 398: 5d pop %ebp 399: c3 ret 0000039a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 39a: b8 01 00 00 00 mov $0x1,%eax 39f: cd 40 int $0x40 3a1: c3 ret 000003a2 <exit>: SYSCALL(exit) 3a2: b8 02 00 00 00 mov $0x2,%eax 3a7: cd 40 int $0x40 3a9: c3 ret 000003aa <wait>: SYSCALL(wait) 3aa: b8 03 00 00 00 mov $0x3,%eax 3af: cd 40 int $0x40 3b1: c3 ret 000003b2 <pipe>: SYSCALL(pipe) 3b2: b8 04 00 00 00 mov $0x4,%eax 3b7: cd 40 int $0x40 3b9: c3 ret 000003ba <read>: SYSCALL(read) 3ba: b8 05 00 00 00 mov $0x5,%eax 3bf: cd 40 int $0x40 3c1: c3 ret 000003c2 <write>: SYSCALL(write) 3c2: b8 10 00 00 00 mov $0x10,%eax 3c7: cd 40 int $0x40 3c9: c3 ret 000003ca <close>: SYSCALL(close) 3ca: b8 15 00 00 00 mov $0x15,%eax 3cf: cd 40 int $0x40 3d1: c3 ret 000003d2 <kill>: SYSCALL(kill) 3d2: b8 06 00 00 00 mov $0x6,%eax 3d7: cd 40 int $0x40 3d9: c3 ret 000003da <exec>: SYSCALL(exec) 3da: b8 07 00 00 00 mov $0x7,%eax 3df: cd 40 int $0x40 3e1: c3 ret 000003e2 <open>: SYSCALL(open) 3e2: b8 0f 00 00 00 mov $0xf,%eax 3e7: cd 40 int $0x40 3e9: c3 ret 000003ea <mknod>: SYSCALL(mknod) 3ea: b8 11 00 00 00 mov $0x11,%eax 3ef: cd 40 int $0x40 3f1: c3 ret 000003f2 <unlink>: SYSCALL(unlink) 3f2: b8 12 00 00 00 mov $0x12,%eax 3f7: cd 40 int $0x40 3f9: c3 ret 000003fa <fstat>: SYSCALL(fstat) 3fa: b8 08 00 00 00 mov $0x8,%eax 3ff: cd 40 int $0x40 401: c3 ret 00000402 <link>: SYSCALL(link) 402: b8 13 00 00 00 mov $0x13,%eax 407: cd 40 int $0x40 409: c3 ret 0000040a <mkdir>: SYSCALL(mkdir) 40a: b8 14 00 00 00 mov $0x14,%eax 40f: cd 40 int $0x40 411: c3 ret 00000412 <chdir>: SYSCALL(chdir) 412: b8 09 00 00 00 mov $0x9,%eax 417: cd 40 int $0x40 419: c3 ret 0000041a <dup>: SYSCALL(dup) 41a: b8 0a 00 00 00 mov $0xa,%eax 41f: cd 40 int $0x40 421: c3 ret 00000422 <getpid>: SYSCALL(getpid) 422: b8 0b 00 00 00 mov $0xb,%eax 427: cd 40 int $0x40 429: c3 ret 0000042a <sbrk>: SYSCALL(sbrk) 42a: b8 0c 00 00 00 mov $0xc,%eax 42f: cd 40 int $0x40 431: c3 ret 00000432 <sleep>: SYSCALL(sleep) 432: b8 0d 00 00 00 mov $0xd,%eax 437: cd 40 int $0x40 439: c3 ret 0000043a <uptime>: SYSCALL(uptime) 43a: b8 0e 00 00 00 mov $0xe,%eax 43f: cd 40 int $0x40 441: c3 ret 00000442 <invoked_syscalls>: SYSCALL(invoked_syscalls) 442: b8 16 00 00 00 mov $0x16,%eax 447: cd 40 int $0x40 449: c3 ret 0000044a <sort_syscalls>: SYSCALL(sort_syscalls) 44a: b8 17 00 00 00 mov $0x17,%eax 44f: cd 40 int $0x40 451: c3 ret 00000452 <get_count>: SYSCALL(get_count) 452: b8 18 00 00 00 mov $0x18,%eax 457: cd 40 int $0x40 459: c3 ret 0000045a <log_syscalls>: SYSCALL(log_syscalls) 45a: b8 19 00 00 00 mov $0x19,%eax 45f: cd 40 int $0x40 461: c3 ret 00000462 <ticketlockinit>: SYSCALL(ticketlockinit) 462: b8 1a 00 00 00 mov $0x1a,%eax 467: cd 40 int $0x40 469: c3 ret 0000046a <ticketlocktest>: SYSCALL(ticketlocktest) 46a: b8 1b 00 00 00 mov $0x1b,%eax 46f: cd 40 int $0x40 471: c3 ret
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; WONG KAH QUAN ; HA18015 ; MIKRORECHNER ; nelsonwongisme@gmail.com ; 015_LetzteHausfgabe_FinalEx ; Datum: 12/10/2020 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #include <p16f648A.inc> ;MC type errorlevel -302 ;supress the 'not in bank0' warning cblock 0x20 ; Start variables @ 0x20 TicCnt ; Tick Counter Temp ; Temporary Register to store temporary data FSMStateP ; FSM's State Pointer, indicates the current state of the system. FSMTime ; Time delay duration in FSM, used for Timeout down counting. InPort ; Input Port Shadows OutPort ; OutPut Port Shadows endc cblock 0x70 ; Flags and save w_save ; save workreg. STATUS_save ; save Flags Z, C etc. Flags ; System flags OutFlags ; Write to ports by drivers InFlags ; Read from Input Ports endc ; define Flags inside Flags register as Flags,# ; in file register of Flags: ; Bit 0 = TicFlag, Bit 1 - SekFlag, Bit 2 = FSMF TicFlag equ 0 SekF equ 1 FSMF equ 2 ; if State transition is taken place ---> FSMF = 0 ; Previous State != Next State ---------> FSMF = 0 ; ; Portbelegung == Ports' Assignment ; Bb, Bell Button, is a stimulus, a sensor. Bb equ 0 ; Pin 0 of PORTA activ high, RA0. ; ; define event bits in InFlags BbF equ 0 ; Bit 0 of InFlags is BbF nBbF equ 1 ; Bit 1 of InFlags is nBbF ; Define Outputs to OutFlags --> OutPort --> PORTB ; Below literals are the Bit addresses in OutFlags ; Define bits in OutFlags ; Output Port: Bit 0 = DoorBell, Bit 1 = HL, Bit 2 = DL. Doorbell equ 0 ; Door Bell: DoorBell = 1, it rings, else, not ringing. HL equ 1 ; Hallway Light: HL = 1, Lights on, else, off. DL equ 2 ; Door Lock: DL = 1, Door is unlock, else, lock. ; More about the Output in the Table below. ; define constant values T0reload equ 0x00 ; TMR0 reload value Ticload equ d'255' ; Downcounts from 255 ;------------------------------------------------------------- org 0 ;start with code memory adr. 0 goto Start ; jump to Start nop ; No operation nop nop ;------------------------------------------------------------- ISR ;Interrupt service routine at adr. 4 ; Basically Save up the STATUS of the interrupt in STATUS_save ; Clear the interrupt overflow(bit T0IF in INTCON) ; Set TicFlag ; Reload timer0 with T0reload ; load back from STATUS_save to STATUS movwf w_save ;no Z Flag change ;Move W to F ; Save data from Work Register to w_save movf STATUS,w ; Move STATUS to w, can also be movf STATUS movwf STATUS_save ; Move W to F ; Above two lines is move STATUS -> W -> STATUS_save ; STATUS -> STATUS_save ; save the STATUS of ISR ServiceT0 ; no other source enabled bcf INTCON,T0IF ; Bit of T0IF in file register INTCON si cleared. ; TMR0 Overflow Interrupt Flag bit must be cleared in software ; Timer0 interrupt is generated when the TMR0 register ; timer/counter overflows from FFh to 00h. This overflow ; sets the T0IF bit. The interrupt can be masked by ; clearing the T0IE bit (INTCON<5>). The T0IF bit ; (INTCON<2>) must be cleared in software by the ; Timer0 module interrupt service routine before reenabling this interrupt. bsf Flags,TicFlag movlw T0reload ; T0reload = 0 --> WREG --> TMR0 movwf TMR0 ; TMR0 = T0reload = 0x00. Exit movf STATUS_save,w movwf STATUS ;from here no change of Z flag ; STATUS_save --> STATUS swapf w_save,f swapf w_save,w retfie ISR_e ;--------------------------------------------------------------- Start PortInit ; Initialize PortA as Input and PORTB as Output banksel PORTA ; Select Bank where PORTA resides. clrf PORTA clrf PORTB banksel TRISA movlw 0xff movwf TRISA ; move 0xff to TRISA clrf TRISB banksel CMCON ;switch to page with comparator contrl movlw 0x07 movwf CMCON banksel VRCON clrf VRCON ;deactivate voltage reference banksel OPTION_REG movlw B'11000000' ; maskword to disable PORTB pullups, ; Interrupt on rising edge of RB0/INT pin. iorwf OPTION_REG,f banksel PORTA PortInit_e Timer0Init ; Initialize TMR0 banksel OPTION_REG ; Select bank of register of OPTION_REG movlw B'11000000' andwf OPTION_REG,f movlw B'00000111' iorwf OPTION_REG,f ; OPTION_REG's current bits: 11000111 ; use Internal instruction cycle clock (CLKOUT) ; Prescaler is assigned to the Timer0 module ; Prescaler Rate for TMR0 --> 1:256 movlw B'10100000' movwf INTCON ; INTCON's current bits: 10100000 ; All un-masked interrupts ENABLED ; > Un-masked interrupt is a hardware interrupt, ; in our case, Bell Button(Bb)) ; ; All peripheral interrupts DISABLED. Peripheral interrupt is any interrupt other than TMR0, INT, or PORTB change. ; TMR0 interrupt ENABLED ; ; Note that Interrupt requests are asynchronous events which means that an interrupt request ; can occur at any time during the execution of a program. banksel TMR0 ; Select bank of register of TMR0, then copy literal of T0reload to TMR0 movlw T0reload movwf TMR0 ; T0reload --> WREG --> TMR0 ; TMR 0 = T0reload = 0x00. Timer0Init_e TicTacInit ; Initialize TicTac movlw Ticload movwf TicCnt ; TicCnt = Ticload TictacInit_e FSMInit ; Initialize Finite State Machine, initially the State is RESET. ; Clear the Flags clrf FSMStateP clrf Flags FSMInit_e loop ; Loop forever ShadowIn ; PORTA is the Input of this microcontroller. movf PORTA,w movwf InPort ; InPort = PORTA ; It reads data from PORTA, then copy to InPort for further processes. ShadowIn_e TicTac ; Countinuos down counting. bcf Flags,SekF btfss Flags,TicFlag ; Initially, TicFlag = 1(from ServiceT0 code block). Will skip "goto TicTac_e", to start to decrement. ; If TicFlag = 0, means down counting already started. 2nd loop and more, not at the first loop of the counting cycles. goto TicTac_e bcf Flags,TicFlag ; Clear TicFlag to note Down Counting starts. decfsz TicCnt,f ; Decrement the Tick Counter. iF zero, will skip "goto TicTac_e" to reload the count(Literal from Ticload), as counting is finished. goto TicTac_e movlw Ticload ; This line executes when TicCnt = 0. ; Reload the Tick Counter, by load literal of TicLoad to WREG then to TicCnt. Then, set SekF bit in Flags f register. movwf TicCnt ; TicLoad --> WREG --> TicCnt ; TicCnt = Ticload(d'255' here, it will downcount from 255). bsf Flags,SekF ; SekFlag = 1 , when TicCnt is reloaded. TicTac_e BellDrv ; Bell Driver, to check for Bell Button pressed or not. bcf InFlags,BbF bsf InFlags,nBbF ; First, clear the BbF(Bb Flag) and set nBbF(Not Bell Button Flag) ; Then go to next line to test if the Bb is pressed/fired or not. ; Why nBF is set? So that Next line will check if Bb is fired or not, ; if Bb not fired, then "goto BellDrv_e"while maintaining nBbF=1, ; show that Bell button is not fired. btfss InPort,Bb ; gedruckt = 1, nicht gedruckt = 0. Always check if the Bb is pressed. ; If pressed, it will skip "goto BellDrv_e" and Set BbF = 1. ; InPort gets value from PORTA(from ShadowIn Code Block) goto BellDrv_e bsf InFlags,BbF bcf InFlags,nBbF ; This and previous line executed when Bb is fired. ; Once Bb is fired, Bb = 1, it will set the Bell Button's Flag ; Notifying the Microcontroller that Bell Button is fired. BellDrv_e ; in FSM: ; Initially, it checks for FSMF, check whether there's state transition or not. ; If the current state is same as the previous state, will not execute FSMdo1, here, it will set the duration of the timeout delay of the ; current state into FSMTime and return Outpattern to WREG then to OutFlags(which then later will copy to PORTB as output of the system). ; OutPattern --> WREG --> OutFlags --> OutPort --> PORTB ; But when the FSMF = 1, the previous state and the current state is same, means there's no state transition. ; will jump to FSMdo1 straight away. ; Code blocks' fuinction/explanation(in short) regarding FSM ; FSM : Check for State Transition,if state changed, load Zeit to FSMTime, and load OutPattern to OutFlags. Executing that state's output. ; if no state change, go FSMdo1. ; FSMdo1 : No State Transition, test timeout, if Z = 1, means delay timeout, downcount finished, then call TimeExit to next State, save @FSMStateP ; Here, is when there's no chnage in state, but when Z=0, means still counting, will jump to FSMdo2 to downcount. ; FSMdo2 : Test for Downcount lifetime & Down counting ;FSMdo3 : Test Bell Button & go to next state(depends on stimulus) ;FSMexit : Check Previous State & Next State same or not, then exit FSM and produce output and loop again. ; More explanation below. FSM ;Tabellen gesteuerter Zustandsautomat/Finite State Machine movf FSMStateP,w ; initially FSM's State Pointer is zero. Start from S0. movwf Temp ; Copy data from WREG to Temp to store temporary. Data to be passed to WREG back for W's offset in table of OutPattern btfsc Flags,FSMF ; Test bit of FSMF. ; If FSMF = 0: There's state transition, the previous and next state is different. ; Skip "goto FSMdo1" when there's no state transition, namely FSMF = 1. ; When there's no state transition, skip to FSMdo1. ; Initially FSMF = 0, then once start looping, FSMF will flag depends on state change at Code Block of FSMexit, ; then FSMF = 0, will loop back here to execute FSMdo1 and so on. goto FSMdo1 bsf Flags,FSMF ; Executing the "Next State", call time and produce output etc. But first reset to 1. ; executed if FSMF = 0 in bit test of FSMF in Flags, i.e., execute when no state transition occurs. ; It will set FSMF = 1. Then invoke Zeit table and produce its corresponding output. If the state not depends on ; delay timeout to change state, it will return the same literal of state number in TimeExit. ; For example, S1 --> S1 if it only listen to stimulus such as button. ; From the table "Zeit", it will return a value(time in seconds in this project) as literal to WREG. ; Which then WREG --> FSMTime, i.e., Zeit --> WREG --> FSMTime call Zeit movwf FSMTime ; Time obtained from Zeit's Table will copy to WREG then FSMTime. That Particular State's Time. movf Temp,w ; Temp here holds the FSMStateP(see above)'s value, which is the current state, then copy to WREG ; The reason to move the FSMStateP to Temp then to WREG again, cause later will have to call Outpattern, ; which need WREG's value(FSMStateP) to offset in the table to get the right value from the table. call Outpattern ; initially StatePointer is zero. Start from S0. So will call Outpattern for S0. movwf OutFlags ; RETLW Literal(OutPattern) from Table to WREG then to OutFlags. ; This OutPattern is a series of Outputs, where different bits in the OutPattern file register is output of a certain ; output/actuator. And it is passed to OutFlags for actuation(see OutDrv then ShadowOut). ; In other words, when no state transition, remain this state, invoke time, and give outputs. FSMdo1 ; No State Transition, test timeout, if Z = 1, means delay timeout, downcount finished, then call TimeExit to next State, save @FSMStateP ; Here, is when there's no chnage in state, but when Z=0, means still counting, will jump to FSMdo2 to downcount. ; Test timeout & go to next state(depends on stimulus) ; If no change of state, form FSM code block where FSMF =1, goto FSMdo1(here), will executes these. movf FSMTime,f ; Copy FSMTime to W. Then test bit. ; If no State Transition, ; FSMTime is from Zeit invoked, and RETLW to WREG then to FSMTime, then here ; If have state transition, ; continue read below btfss STATUS,Z ; Z flag is set if f == 0(FSMTime is f register here). ; Note: STATUS is a PIC register ; Z = 1, result of logical or operation is zero, means that FSMTime = 0,i.e., the Timeout Delay finished down counting. ; It then will skip "goto FSMdo2" to "call TimeExit", which is the next state after delay timeout. goto FSMdo2 movf Temp,w ; execute this if Z is set. The result of an arithmetic or logic operation is zero ; Temp here, is from FSM's codeblock above, which is the FSMStateP, i.e. Current state. ; This current state(0-7) is used for calling out table and offset to the column that indicates the next state ; which then copy back to the FSMStateP(now is the next state) after Timeout. Means this only executed if delay is timeout. ; Look at Zeit, if those that only listen to Stimulus, Zeit = 0. call TimeExit ; get next state for timeout. The next state's state's number is then store to WREG movwf FSMStateP ; from WREG, which contains the Next state, now move to FSMStateP. FSMdo2 ; Test for Downcount lifetime & Down counting btfss Flags,SekF ; SekF = TicCnt is not zero, means TicCnt is loaded, ready to count(check above TicTac code block) ; and SekFlag = 1, then skip next line and decrement. goto FSMdo3 decf FSMTime,f ; Decrement FSMTime if SekFlag(1st bit of Flags) is zero ; It will downcount depends on the duration of the timeout delay of that current state. ; the duration information/data obtain from FSMTime. FSMdo3 ; Test Bell Button & go to next state(depends on stimulus) movf Temp,w ; Temp is the Current State Index(S0,...,S7...) call EventMask ; Call EventMask table to check which state and check if that state listen to Bb or not. ; then RETLW: return the literal to WREG. andwf InFlags,w ; InFlags: Bit 0 = BbF, Bit 1 = nBbF ; InFlags AND WREG and store in WREG. ; InFlags holds the data of BbDriver. AND it to check if the Bell Button fired and does this state listen to the stimulus. ; So its kinda protecting the system, not to listen to any stimulus, and specifically set to what it is stimulated. ; Say a state only listen to timer interrupt, and Bb is fired, this FSMdo3 test whether this state listen to the stimulus or not, ; if EveentMask RETLW to WREG = 0 and then logical AND with InFlags, will get 0 for the BbF in InFlags, which stored in WREG. ; But storing in WREG is not important, as the result of the AND logical operation is detected by Bit Z(Zero) of file register STATUS ; Where Z = 1, when the result of logical operation is 0. Means that the state dont listen to Stimulus. ; So if the stat don't listen to Stimulus, Z = 1, will execute "FSMexit", where in "FSMexit" ; It checks for the Previous State & Next State same or not, then exit FSM and produce Outputs and loop again. ; But if Z=0, means that this state listen to Stimulus/Bb, it will copy the value of Temp(which holds the current State index) ; to WREG. To WREG for invoking EventExit, which return the next state Index. btfsc STATUS,Z goto FSMexit ; Skip if Z = 0. I.e, when the result of operation is not zero. Both WREG and InFlags are set in the LSB. ; Execute this, when Z = 1, where BbF AND W is 0. Means, either BbF or W are 0, or both. WREG is from EventMask from Temp. ; Z must be 0 to skip this and call next state. movf Temp,w ; Bb is fired and EventMask = 1 ; Execute this if result of the logical operation is not zero, where Z = 0. ; In others word, BbF = 1. Bb is pressed and the state is a state that listen to Bb Stimulus. call EventExit ; Next state after event/condition movwf FSMStateP ; EventExit -> FSMStateP. Now system/machine is in that Next State. ; This code block is to change to FSMStateP to the apporpriate State. FSMexit ; Check Previous State & Next State same or not, then exit FSM and produce output and loop again. ; FSMF is the FSM's Flag. ; No state transition is taken place --> FSMF = 1 [PS = NS] ; State transition is taken place --> FSMF = 0 [PS != NS] movf Temp,w ; Temp is previous/current state ; Then Exclusive OR with Next State ; This is to check previous and next state in the regitser same or not, as machine don't know whether is changed or not, ; it just copy values. ; So if Previous and Next State is same, will be Zero, as XOR needs either one bit = 1. So if same states, where ; PS = NS, say 0 -> 0 , XOR result = 0, Z = 1, ; when 1 -> 1, XOR result = 0, Z = 1, ; when NS != PS, say 1 -> 0, XOR result = 1, Z = 0. ; Z is a bit in STATUS Register. ; TLDR for this: Z = 1, NS = PS, goto FSM_e and produce outputs. ; Z = 0, NS != PS, there's change of state, clear FSMF...and loop up back to FSM code block for further execution. xorwf FSMStateP,w ; Z Flag if no change btfsc STATUS,Z ; FSMStateP XOR W , will skip "goto FSM_e" if WREG = FSMStateP, WREG contains previous state number, where FSMStateP is Next State. ; else FSMStateP != WREG, will execute "goto FSM_e" ; Exit FSM when FSMStateP != WREG, as Z = 1. WREG is the StatePointer of previous state. ; If Previous State is different than the next state, means there is state change. ; Then exit FSM and loop again with FSMF = 1. goto FSM_e ; Execute if Next State != Previous State, means state transition happened. bcf Flags,FSMF ; If FSMStateP XOR W = 1, Z = 0, this line will be executed., clear FSMF in Flags. Not Flagged, still at S0. ; Executed when FSM Previous State is different compared to the Next state. (NS != PS) ; I.e., State transition is taken place,then FSMF = 1, where FSMF is the FSM's Flag. ; clear FSMF to indicates there's state transition then output will be executed. FSM_e OutDrv movf OutFlags,w movwf OutPort ; OutFlags -> WREG -> OutPort OutDrv_e ShadowOut movf OutPort,w movwf PORTB ; OutPort -> WREG -> PORTB ; PORTB is the Output of this microcontroller. ShadowOut_e goto loop ; ;-----------------------------------Tabellen;----------------------------------- ; States ; S0 S1 S2 S3 S4 S5 S6 S7 ; Literal are in HEX, otherwise stated. Zeit addwf PCL,f dt 0, 3, 7, 5, 3, 2, d'20', 2 ; Values are in Seconds. ; These are the duration needed to change state depends for the state that ; uses timer as interrupt. ; S0 is 0s as only listen to Bell Button but not timeout delay. Outpattern addwf PCL,f dt 0, 3, 2, 0, 0, 4, 0, 0 ; Outpattern that will be the output at PORTB ; 0x00 : B'00000000', Hallway Light is OFF and DoorBell is NOT ringing, Door is LOCKED ; 0x02 : B'00000010', Hallway Light is ON and DoorBell is NOT ringing, Door is LOCKED ; 0x03 : B'00000011', Hallway Light is ON and DoorBell is ringing, Door is LOCKED ; 0x04 : B'00000100', Hallway Light is OFF and DoorBell is NOT ringing, Door is UNLOCKED TimeExit addwf PCL,f dt 0, 2, 3, 6, 6, 7, 0, 0 ; State will go to Next State after TIMEOUT, independent of Stimulus, for Stimulus, check EventExit(below): ; ; S0 : Only depends on Bb , hence, it will always go back to S0 in loop until stimulated. ; S1 : S1 --> S2 ; S2 : S2 --> S3 ; S3 : S3 --> S6 ; S4 : S4 --> S6 ; S5 : S5 --> S7 ; S6 : S6 --> S0 ; S7 : S7 --> S0 ; ; The duration needed to change state depends ; on the duration of the delay in table "Zeit"(See above). ; Only depends on Bb: Means that this state only change reacting to Bell Button, ; instead of change state when dleay timeout. Could be either Bb pressed or released. ; This state will waiting for stimulus to be stimulate to change to next state. EventMask addwf PCL,f dt 1, 0, 1, 1, 2, 0, 0, 0 ; Bit 0 of InFlags is BbF ; Bit 1 of InFlags is nBbF ; ; 0x01 == B'00000001' : BbF = 1, nBbF = 0, only stimulated if Bb is fired ; 0x02 == B'00000010' : BbF = 0, nBbF = 1. only stimulated if Bb is unfired. ; 0x00 == B'00000000' : Not stimulated by Bell Button(Bb), means this state does not listen to Bb, but timeout instead. EventExit addwf PCL,f dt 1, 0, 1, 4, 5, 0, 0, 0 ; Event Exit ; EvEx(Event Exit): Next state after event/condition(e.g.Bb executed) ; ; When Bb is fired or BbF = 1: ; S0 : S0 --> S1 ; S1 : Does not listen to Bb ; S2 : S2 --> S1 ; S3 : S3 --> S4 ; S4 : S4 --> S5 ; S5 : Does not listen to Bb ; S6 : Does not listen to Bb ; S7 : Does not listen to Bb ; ; "Does not listen/stimulate to Bb": this state won't change state when Bb is fired or not fired ; Only depends on the delay timeout to change state. END ; Some Explanations for Table: ; 1 - The OutPattern to be invoke will RETLW to OutFLags then OutPort then PORTB, then output. ; means if bit of, say DL(4th bit of OutFLags/OutPort/PORTB), is 00001000, only DL is HIGH, means DoorLock enabled. ; [Reference: .pdf of this Hausaufgabe, Page ] ; 2 - For the addwf PCL,f ==> add W to PCL and store in PCL. PCL is program counter. So to jump to the specify column of ; table. PCL + W = Address location of that RETLW, so the literal can be return to the WREG. ; Hence, the WREG before invoking the table is equal to the column's index. ; In other words, offsetting in the Program Counter with the help of WREG(WREG here/now stores the FSMStateP, which is the current state). ; For example: If FSMStateP(in FSM Block, this data is copied to WREG) = 2 (i.e., State 2/S2), then PCL = PCL + 2, where WREG = 2, ; That's why need Temp to temporary stores the current State of the machine, as WREG will be use to call table or RETLW(Return literal from table to WREG) ; Where PCL, the program counter's value = index of column of the table. ; the f in addwf PCL,""f"", denotes the value will be saved into PCL, so now the PCL = column's index, then pass to "dt" to RETLW ; It will return the literal in the 2nd column of the table. ; 3 - dt : Define table uses RETLW, return literal to WREG. And to choose which column, it is offset by the ; addwf PCL,f , which is see above '2'. ; Note(to self): ; > Don't put bit in Watch Tab, only bytes or register, but comment for understanding which bit is what in the register. ; > Need to take note on register, byte, bits, flag bit and enable etc. ; > Don't forget to disable WDT and use INTOSC for CLKOUT. ; > Don't forget to enable Real-Time Ppdates of Simulation in Settings in MPLAB.
/* * Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com) * * Distributed under under the Apache License, version 2.0 (the "License"). * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #include <cetty/handler/codec/http/HttpChunkAggregator.h> #include <cetty/buffer/Unpooled.h> #include <cetty/channel/Channel.h> #include <cetty/channel/ChannelConfig.h> #include <cetty/channel/ChannelHandlerContext.h> #include <cetty/util/Exception.h> #include <cetty/util/StringUtil.h> #include <cetty/handler/codec/TooLongFrameException.h> #include <cetty/handler/codec/http/HttpRequest.h> #include <cetty/handler/codec/http/HttpResponse.h> #include <cetty/handler/codec/http/HttpChunk.h> #include <cetty/handler/codec/http/HttpChunkTrailer.h> #include <cetty/handler/codec/http/HttpHeaders.h> namespace cetty { namespace handler { namespace codec { namespace http { using namespace cetty::channel; using namespace cetty::buffer; using namespace cetty::util; using namespace cetty::handler::codec; HttpChunkAggregator::HttpChunkAggregator(int maxContentLength) : maxContentLength_(maxContentLength) { if (maxContentLength <= 0) { throw InvalidArgumentException( "maxContentLength must be a positive integer: " + maxContentLength); } } HttpPackage HttpChunkAggregator::decode(ChannelHandlerContext& ctx, const HttpPackage& msg) { #if 0 if (msg.isHttpRequest() || msg.isHttpResponse()) { // Handle the 'Expect: 100-continue' header if necessary. // TODO: Respond with 413 Request Entity Too Large // and discard the traffic or close the connection. // No need to notify the upstream handlers - just log. // If decoding a response, just throw an exception. if (HttpHeaders::is100ContinueExpected(*value)) { //Channels::write(ctx, Channels::succeededFuture(ctx.getChannel()), CONTINUE.duplicate()); } HttpTransferEncoding te = value->getTransferEncoding(); if (te == HttpTransferEncoding::SINGLE) { currentMessage.reset(); return value; } else if (te == HttpTransferEncoding::STREAMED || te == HttpTransferEncoding::CHUNKED) { // initialize the cumulative buffer, and wait for incoming chunks. value->setTransferEncoding(HttpTransferEncoding::SINGLE); value->setContent(Unpooled::buffer()); currentMessage.reset(); currentMessage = value; return HttpMessagePtr(); } else { // Error. return HttpMessagePtr(); } } else if (msg.isHttpChunk()) { HttpMessagePtr& currentMessage = aggregator.currentMessage_; // Sanity check if (!currentMessage) { throw IllegalStateException("received HttpChunk without HttpMessage"); } // Merge the received chunk into the content of the current message. ChannelBufferPtr content = currentMessage->getContent(); if (content->readableBytes() > aggregator.maxContentLength_ - value->getContent()->readableBytes()) { // TODO: Respond with 413 Request Entity Too Large // and discard the traffic or close the connection. // No need to notify the upstream handlers - just log. // If decoding a response, just throw an exception. std::string msg; StringUtil::printf(&msg, "HTTP content length exceeded %d bytes.", aggregator.maxContentLength_); LOG_ERROR << msg; throw TooLongFrameException(msg); } // Append the content of the chunk aggregator.appendToCumulation(value->getContent()); if (value->isLast()) { currentMessage.reset(); // Set the 'Content-Length' header. currentMessage->setHeader( HttpHeaders::Names::CONTENT_LENGTH, StringUtil::numtostr(content->readableBytes())); // All done - generate the event. return currentMessage; } else { return HttpMessagePtr(); } } else if (msg.isHttpChunkTrailer()) { HttpMessagePtr& currentMessage = aggregator.currentMessage_; HttpChunkTrailer::ConstHeaderIterator itr = value->getFirstHeader(); HttpChunkTrailer::ConstHeaderIterator end = value->getLastHeader(); for (; itr != end; ++itr) { currentMessage->setHeader(itr->first, itr->second); } // Set the 'Content-Length' header. currentMessage->setHeader( HttpHeaders::Names::CONTENT_LENGTH, StringUtil::numtostr(currentMessage->getContent()->readableBytes())); return currentMessage; } #endif return msg; } void HttpChunkAggregator::appendToCumulation(const ChannelBufferPtr& input) { #if 0 const ChannelBufferPtr& cumulation = currentMessage_->getContent(); if (cumulation instanceof CompositeByteBuf) { // Make sure the resulting cumulation buffer has no more than 4 components. CompositeByteBuf composite = (CompositeByteBuf) cumulation; if (composite.numComponents() >= maxCumulationBufferComponents) { currentMessage.setContent(Unpooled.wrappedBuffer(composite.copy(), input)); } else { List<ByteBuf> decomposed = composite.decompose(0, composite.readableBytes()); ByteBuf[] buffers = decomposed.toArray(new ByteBuf[decomposed.size() + 1]); buffers[buffers.length - 1] = input; currentMessage.setContent(Unpooled.wrappedBuffer(buffers)); } } else { currentMessage.setContent(Unpooled.wrappedBuffer(cumulation, input)); } currentMessage_->setContent(Unpooled::wrappedBuffer(cumulation, input)); #endif } } } } }
// Copyright (c) 2012-2015 The Bitcoin Core developers // Copyright (c) 2019 The quirkyturtcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addrman.h" #include "test/test_quirkyturtcoin.h" #include <string> #include <boost/test/unit_test.hpp> #include <crypto/common.h> // for ReadLE64 #include "hash.h" #include "netbase.h" #include "random.h" class CAddrManTest : public CAddrMan { uint64_t state; public: CAddrManTest() { state = 1; } //! Ensure that bucket placement is always the same for testing purposes. void MakeDeterministic() { nKey.SetNull(); insecure_rand = FastRandomContext(true); } CAddrInfo* Find(const CNetAddr& addr, int* pnId = NULL) { LOCK(cs); return CAddrMan::Find(addr, pnId); } CAddrInfo* Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId = NULL) { LOCK(cs); return CAddrMan::Create(addr, addrSource, pnId); } void Delete(int nId) { LOCK(cs); CAddrMan::Delete(nId); } // Simulates connection failure so that we can test eviction of offline nodes void SimConnFail(CService& addr) { LOCK(cs); int64_t nLastSuccess = 1; Good_(addr, true, nLastSuccess); // Set last good connection in the deep past. bool count_failure = false; int64_t nLastTry = GetAdjustedTime()-61; Attempt(addr, count_failure, nLastTry); } }; static CNetAddr ResolveIP(const char* ip) { CNetAddr addr; BOOST_CHECK_MESSAGE(LookupHost(ip, addr, false), strprintf("failed to resolve: %s", ip)); return addr; } static CNetAddr ResolveIP(std::string ip) { return ResolveIP(ip.c_str()); } static CService ResolveService(const char* ip, int port = 0) { CService serv; BOOST_CHECK_MESSAGE(Lookup(ip, serv, port, false), strprintf("failed to resolve: %s:%i", ip, port)); return serv; } static CService ResolveService(std::string ip, int port = 0) { return ResolveService(ip.c_str(), port); } BOOST_FIXTURE_TEST_SUITE(addrman_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(addrman_simple) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CNetAddr source = ResolveIP("252.2.2.2"); // Test 1: Does Addrman respond correctly when empty. BOOST_CHECK(addrman.size() == 0); CAddrInfo addr_null = addrman.Select(); BOOST_CHECK(addr_null.ToString() == "[::]:0"); // Test 2: Does Addrman::Add work as expected. CService addr1 = ResolveService("250.1.1.1", 8333); addrman.Add(CAddress(addr1, NODE_NONE), source); BOOST_CHECK(addrman.size() == 1); CAddrInfo addr_ret1 = addrman.Select(); BOOST_CHECK(addr_ret1.ToString() == "250.1.1.1:8333"); // Test 3: Does IP address deduplication work correctly. // Expected dup IP should not be added. CService addr1_dup = ResolveService("250.1.1.1", 8333); addrman.Add(CAddress(addr1_dup, NODE_NONE), source); BOOST_CHECK(addrman.size() == 1); // Test 5: New table has one addr and we add a diff addr we should // have two addrs. CService addr2 = ResolveService("250.1.1.2", 8333); addrman.Add(CAddress(addr2, NODE_NONE), source); BOOST_CHECK(addrman.size() == 2); // Test 6: AddrMan::Clear() should empty the new table. addrman.Clear(); BOOST_CHECK(addrman.size() == 0); CAddrInfo addr_null2 = addrman.Select(); BOOST_CHECK(addr_null2.ToString() == "[::]:0"); } BOOST_AUTO_TEST_CASE(addrman_ports) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CNetAddr source = ResolveIP("252.2.2.2"); BOOST_CHECK(addrman.size() == 0); // Test 7; Addr with same IP but diff port does not replace existing addr. CService addr1 = ResolveService("250.1.1.1", 8333); addrman.Add(CAddress(addr1, NODE_NONE), source); BOOST_CHECK(addrman.size() == 1); CService addr1_port = ResolveService("250.1.1.1", 8334); addrman.Add(CAddress(addr1_port, NODE_NONE), source); BOOST_CHECK(addrman.size() == 1); CAddrInfo addr_ret2 = addrman.Select(); BOOST_CHECK(addr_ret2.ToString() == "250.1.1.1:8333"); // Test 8: Add same IP but diff port to tried table, it doesn't get added. // Perhaps this is not ideal behavior but it is the current behavior. addrman.Good(CAddress(addr1_port, NODE_NONE)); BOOST_CHECK(addrman.size() == 1); bool newOnly = true; CAddrInfo addr_ret3 = addrman.Select(newOnly); BOOST_CHECK(addr_ret3.ToString() == "250.1.1.1:8333"); } BOOST_AUTO_TEST_CASE(addrman_select) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CNetAddr source = ResolveIP("252.2.2.2"); // Test 9: Select from new with 1 addr in new. CService addr1 = ResolveService("250.1.1.1", 8333); addrman.Add(CAddress(addr1, NODE_NONE), source); BOOST_CHECK(addrman.size() == 1); bool newOnly = true; CAddrInfo addr_ret1 = addrman.Select(newOnly); BOOST_CHECK(addr_ret1.ToString() == "250.1.1.1:8333"); // Test 10: move addr to tried, select from new expected nothing returned. addrman.Good(CAddress(addr1, NODE_NONE)); BOOST_CHECK(addrman.size() == 1); CAddrInfo addr_ret2 = addrman.Select(newOnly); BOOST_CHECK(addr_ret2.ToString() == "[::]:0"); CAddrInfo addr_ret3 = addrman.Select(); BOOST_CHECK(addr_ret3.ToString() == "250.1.1.1:8333"); BOOST_CHECK(addrman.size() == 1); // Add three addresses to new table. CService addr2 = ResolveService("250.3.1.1", 8333); CService addr3 = ResolveService("250.3.2.2", 9999); CService addr4 = ResolveService("250.3.3.3", 9999); addrman.Add(CAddress(addr2, NODE_NONE), ResolveService("250.3.1.1", 8333)); addrman.Add(CAddress(addr3, NODE_NONE), ResolveService("250.3.1.1", 8333)); addrman.Add(CAddress(addr4, NODE_NONE), ResolveService("250.4.1.1", 8333)); // Add three addresses to tried table. CService addr5 = ResolveService("250.4.4.4", 8333); CService addr6 = ResolveService("250.4.5.5", 7777); CService addr7 = ResolveService("250.4.6.6", 8333); addrman.Add(CAddress(addr5, NODE_NONE), ResolveService("250.3.1.1", 8333)); addrman.Good(CAddress(addr5, NODE_NONE)); addrman.Add(CAddress(addr6, NODE_NONE), ResolveService("250.3.1.1", 8333)); addrman.Good(CAddress(addr6, NODE_NONE)); addrman.Add(CAddress(addr7, NODE_NONE), ResolveService("250.1.1.3", 8333)); addrman.Good(CAddress(addr7, NODE_NONE)); // Test 11: 6 addrs + 1 addr from last test = 7. BOOST_CHECK(addrman.size() == 7); // Test 12: Select pulls from new and tried regardless of port number. std::set<uint16_t> ports; for (int i = 0; i < 20; ++i) { ports.insert(addrman.Select().GetPort()); } BOOST_CHECK_EQUAL(ports.size(), 3); } BOOST_AUTO_TEST_CASE(addrman_new_collisions) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CNetAddr source = ResolveIP("252.2.2.2"); BOOST_CHECK(addrman.size() == 0); for (unsigned int i = 1; i < 18; i++) { CService addr = ResolveService("250.1.1." + std::to_string(i)); addrman.Add(CAddress(addr, NODE_NONE), source); //Test 13: No collision in new table yet. BOOST_CHECK(addrman.size() == i); } //Test 14: new table collision! CService addr1 = ResolveService("250.1.1.18"); addrman.Add(CAddress(addr1, NODE_NONE), source); BOOST_CHECK(addrman.size() == 17); CService addr2 = ResolveService("250.1.1.19"); addrman.Add(CAddress(addr2, NODE_NONE), source); BOOST_CHECK(addrman.size() == 18); } BOOST_AUTO_TEST_CASE(addrman_tried_collisions) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CNetAddr source = ResolveIP("252.2.2.2"); BOOST_CHECK(addrman.size() == 0); for (unsigned int i = 1; i < 80; i++) { CService addr = ResolveService("250.1.1." + std::to_string(i)); addrman.Add(CAddress(addr, NODE_NONE), source); addrman.Good(CAddress(addr, NODE_NONE)); //Test 15: No collision in tried table yet. BOOST_TEST_MESSAGE(addrman.size()); BOOST_CHECK(addrman.size() == i); } //Test 16: tried table collision! CService addr1 = ResolveService("250.1.1.80"); addrman.Add(CAddress(addr1, NODE_NONE), source); BOOST_CHECK(addrman.size() == 79); CService addr2 = ResolveService("250.1.1.81"); addrman.Add(CAddress(addr2, NODE_NONE), source); BOOST_CHECK(addrman.size() == 80); } BOOST_AUTO_TEST_CASE(addrman_find) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); BOOST_CHECK(addrman.size() == 0); CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE); CAddress addr2 = CAddress(ResolveService("250.1.2.1", 9999), NODE_NONE); CAddress addr3 = CAddress(ResolveService("251.255.2.1", 8333), NODE_NONE); CNetAddr source1 = ResolveIP("250.1.2.1"); CNetAddr source2 = ResolveIP("250.1.2.2"); addrman.Add(addr1, source1); addrman.Add(addr2, source2); addrman.Add(addr3, source1); // Test 17: ensure Find returns an IP matching what we searched on. CAddrInfo* info1 = addrman.Find(addr1); BOOST_CHECK(info1); if (info1) BOOST_CHECK(info1->ToString() == "250.1.2.1:8333"); // Test 18; Find does not discriminate by port number. CAddrInfo* info2 = addrman.Find(addr2); BOOST_CHECK(info2); if (info2) BOOST_CHECK(info2->ToString() == info1->ToString()); // Test 19: Find returns another IP matching what we searched on. CAddrInfo* info3 = addrman.Find(addr3); BOOST_CHECK(info3); if (info3) BOOST_CHECK(info3->ToString() == "251.255.2.1:8333"); } BOOST_AUTO_TEST_CASE(addrman_create) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); BOOST_CHECK(addrman.size() == 0); CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE); CNetAddr source1 = ResolveIP("250.1.2.1"); int nId; CAddrInfo* pinfo = addrman.Create(addr1, source1, &nId); // Test 20: The result should be the same as the input addr. BOOST_CHECK(pinfo->ToString() == "250.1.2.1:8333"); CAddrInfo* info2 = addrman.Find(addr1); BOOST_CHECK(info2->ToString() == "250.1.2.1:8333"); } BOOST_AUTO_TEST_CASE(addrman_delete) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); BOOST_CHECK(addrman.size() == 0); CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE); CNetAddr source1 = ResolveIP("250.1.2.1"); int nId; addrman.Create(addr1, source1, &nId); // Test 21: Delete should actually delete the addr. BOOST_CHECK(addrman.size() == 1); addrman.Delete(nId); BOOST_CHECK(addrman.size() == 0); CAddrInfo* info2 = addrman.Find(addr1); BOOST_CHECK(info2 == NULL); } BOOST_AUTO_TEST_CASE(addrman_getaddr) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); // Test 22: Sanity check, GetAddr should never return anything if addrman // is empty. BOOST_CHECK(addrman.size() == 0); std::vector<CAddress> vAddr1 = addrman.GetAddr(); BOOST_CHECK(vAddr1.size() == 0); CAddress addr1 = CAddress(ResolveService("250.250.2.1", 8333), NODE_NONE); addr1.nTime = GetAdjustedTime(); // Set time so isTerrible = false CAddress addr2 = CAddress(ResolveService("250.251.2.2", 9999), NODE_NONE); addr2.nTime = GetAdjustedTime(); CAddress addr3 = CAddress(ResolveService("251.252.2.3", 8333), NODE_NONE); addr3.nTime = GetAdjustedTime(); CAddress addr4 = CAddress(ResolveService("252.253.3.4", 8333), NODE_NONE); addr4.nTime = GetAdjustedTime(); CAddress addr5 = CAddress(ResolveService("252.254.4.5", 8333), NODE_NONE); addr5.nTime = GetAdjustedTime(); CNetAddr source1 = ResolveIP("250.1.2.1"); CNetAddr source2 = ResolveIP("250.2.3.3"); // Test 23: Ensure GetAddr works with new addresses. addrman.Add(addr1, source1); addrman.Add(addr2, source2); addrman.Add(addr3, source1); addrman.Add(addr4, source2); addrman.Add(addr5, source1); // GetAddr returns 23% of addresses, 23% of 5 is 1 rounded down. BOOST_CHECK(addrman.GetAddr().size() == 1); // Test 24: Ensure GetAddr works with new and tried addresses. addrman.Good(CAddress(addr1, NODE_NONE)); addrman.Good(CAddress(addr2, NODE_NONE)); BOOST_CHECK(addrman.GetAddr().size() == 1); // Test 25: Ensure GetAddr still returns 23% when addrman has many addrs. for (unsigned int i = 1; i < (8 * 256); i++) { int octet1 = i % 256; int octet2 = (i / 256) % 256; int octet3 = (i / (256 * 2)) % 256; std::string strAddr = std::to_string(octet1) + "." + std::to_string(octet2) + "." + std::to_string(octet3) + ".23"; CAddress addr = CAddress(ResolveService(strAddr), NODE_NONE); // Ensure that for all addrs in addrman, isTerrible == false. addr.nTime = GetAdjustedTime(); addrman.Add(addr, ResolveIP(strAddr)); if (i % 8 == 0) addrman.Good(addr); } std::vector<CAddress> vAddr = addrman.GetAddr(); size_t percent23 = (addrman.size() * 23) / 100; BOOST_CHECK(vAddr.size() == percent23); BOOST_CHECK(vAddr.size() == 461); // (Addrman.size() < number of addresses added) due to address collisons. BOOST_CHECK(addrman.size() == 2007); } BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CAddress addr1 = CAddress(ResolveService("250.1.1.1", 8333), NODE_NONE); CAddress addr2 = CAddress(ResolveService("250.1.1.1", 9999), NODE_NONE); CNetAddr source1 = ResolveIP("250.1.1.1"); CAddrInfo info1 = CAddrInfo(addr1, source1); uint256 nKey1 = (uint256)(CHashWriter(SER_GETHASH, 0) << 1).GetHash(); uint256 nKey2 = (uint256)(CHashWriter(SER_GETHASH, 0) << 2).GetHash(); BOOST_CHECK(info1.GetTriedBucket(nKey1) == 40); // Test 26: Make sure key actually randomizes bucket placement. A fail on // this test could be a security issue. BOOST_CHECK(info1.GetTriedBucket(nKey1) != info1.GetTriedBucket(nKey2)); // Test 27: Two addresses with same IP but different ports can map to // different buckets because they have different keys. CAddrInfo info2 = CAddrInfo(addr2, source1); BOOST_CHECK(info1.GetKey() != info2.GetKey()); BOOST_CHECK(info1.GetTriedBucket(nKey1) != info2.GetTriedBucket(nKey1)); std::set<int> buckets; for (int i = 0; i < 255; i++) { CAddrInfo infoi = CAddrInfo( CAddress(ResolveService("250.1.1." + std::to_string(i)), NODE_NONE), ResolveIP("250.1.1." + std::to_string(i))); int bucket = infoi.GetTriedBucket(nKey1); buckets.insert(bucket); } // Test 28: IP addresses in the same group (\16 prefix for IPv4) should // never get more than 8 buckets BOOST_CHECK(buckets.size() == 8); buckets.clear(); for (int j = 0; j < 255; j++) { CAddrInfo infoj = CAddrInfo( CAddress(ResolveService("250." + std::to_string(j) + ".1.1"), NODE_NONE), ResolveIP("250." + std::to_string(j) + ".1.1")); int bucket = infoj.GetTriedBucket(nKey1); buckets.insert(bucket); } // Test 29: IP addresses in the different groups should map to more than // 8 buckets. BOOST_CHECK(buckets.size() == 160); } BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE); CAddress addr2 = CAddress(ResolveService("250.1.2.1", 9999), NODE_NONE); CNetAddr source1 = ResolveIP("250.1.2.1"); CAddrInfo info1 = CAddrInfo(addr1, source1); uint256 nKey1 = (uint256)(CHashWriter(SER_GETHASH, 0) << 1).GetHash(); uint256 nKey2 = (uint256)(CHashWriter(SER_GETHASH, 0) << 2).GetHash(); BOOST_CHECK(info1.GetNewBucket(nKey1) == 786); // Test 30: Make sure key actually randomizes bucket placement. A fail on // this test could be a security issue. BOOST_CHECK(info1.GetNewBucket(nKey1) != info1.GetNewBucket(nKey2)); // Test 31: Ports should not effect bucket placement in the addr CAddrInfo info2 = CAddrInfo(addr2, source1); BOOST_CHECK(info1.GetKey() != info2.GetKey()); BOOST_CHECK(info1.GetNewBucket(nKey1) == info2.GetNewBucket(nKey1)); std::set<int> buckets; for (int i = 0; i < 255; i++) { CAddrInfo infoi = CAddrInfo( CAddress(ResolveService("250.1.1." + std::to_string(i)), NODE_NONE), ResolveIP("250.1.1." + std::to_string(i))); int bucket = infoi.GetNewBucket(nKey1); buckets.insert(bucket); } // Test 32: IP addresses in the same group (\16 prefix for IPv4) should // always map to the same bucket. BOOST_CHECK(buckets.size() == 1); buckets.clear(); for (int j = 0; j < 4 * 255; j++) { CAddrInfo infoj = CAddrInfo(CAddress( ResolveService( std::to_string(250 + (j / 255)) + "." + std::to_string(j % 256) + ".1.1"), NODE_NONE), ResolveIP("251.4.1.1")); int bucket = infoj.GetNewBucket(nKey1); buckets.insert(bucket); } // Test 33: IP addresses in the same source groups should map to no more // than 64 buckets. BOOST_CHECK(buckets.size() <= 64); buckets.clear(); for (int p = 0; p < 255; p++) { CAddrInfo infoj = CAddrInfo( CAddress(ResolveService("250.1.1.1"), NODE_NONE), ResolveIP("250." + std::to_string(p) + ".1.1")); int bucket = infoj.GetNewBucket(nKey1); buckets.insert(bucket); } // Test 34: IP addresses in the different source groups should map to more // than 64 buckets. BOOST_CHECK(buckets.size() > 64); } BOOST_AUTO_TEST_CASE(addrman_selecttriedcollision) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); BOOST_CHECK(addrman.size() == 0); // Empty addrman should return blank addrman info. BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0"); // Add twenty two addresses. CNetAddr source = ResolveIP("252.2.2.2"); for (unsigned int i = 1; i < 23; i++) { CService addr = ResolveService("250.1.1."+std::to_string(i)); addrman.Add(CAddress(addr, NODE_NONE), source); addrman.Good(addr); // No collisions yet. BOOST_CHECK(addrman.size() == i); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0"); } // Ensure Good handles duplicates well. for (unsigned int i = 1; i < 23; i++) { CService addr = ResolveService("250.1.1."+std::to_string(i)); addrman.Good(addr); BOOST_CHECK(addrman.size() == 22); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0"); } } BOOST_AUTO_TEST_CASE(addrman_noevict) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); // Add twenty two addresses. CNetAddr source = ResolveIP("252.2.2.2"); for (unsigned int i = 1; i < 23; i++) { CService addr = ResolveService("250.1.1."+std::to_string(i)); addrman.Add(CAddress(addr, NODE_NONE), source); addrman.Good(addr); // No collision yet. BOOST_CHECK(addrman.size() == i); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0"); } // Collision between 23 and 19. CService addr23 = ResolveService("250.1.1.23"); addrman.Add(CAddress(addr23, NODE_NONE), source); addrman.Good(addr23); BOOST_CHECK(addrman.size() == 23); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "250.1.1.19:0"); // 23 should be discarded and 19 not evicted. addrman.ResolveCollisions(); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0"); // Lets create two collisions. for (unsigned int i = 24; i < 33; i++) { CService addr = ResolveService("250.1.1."+std::to_string(i)); addrman.Add(CAddress(addr, NODE_NONE), source); addrman.Good(addr); BOOST_CHECK(addrman.size() == i); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0"); } // Cause a collision. CService addr33 = ResolveService("250.1.1.33"); addrman.Add(CAddress(addr33, NODE_NONE), source); addrman.Good(addr33); BOOST_CHECK(addrman.size() == 33); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "250.1.1.27:0"); // Cause a second collision. addrman.Add(CAddress(addr23, NODE_NONE), source); addrman.Good(addr23); BOOST_CHECK(addrman.size() == 33); BOOST_CHECK(addrman.SelectTriedCollision().ToString() != "[::]:0"); addrman.ResolveCollisions(); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0"); } BOOST_AUTO_TEST_CASE(addrman_evictionworks) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); BOOST_CHECK(addrman.size() == 0); // Empty addrman should return blank addrman info. BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0"); // Add twenty two addresses. CNetAddr source = ResolveIP("252.2.2.2"); for (unsigned int i = 1; i < 23; i++) { CService addr = ResolveService("250.1.1."+std::to_string(i)); addrman.Add(CAddress(addr, NODE_NONE), source); addrman.Good(addr); // No collision yet. BOOST_CHECK(addrman.size() == i); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0"); } // Collision between 23 and 19. CService addr = ResolveService("250.1.1.23"); addrman.Add(CAddress(addr, NODE_NONE), source); addrman.Good(addr); BOOST_CHECK(addrman.size() == 23); CAddrInfo info = addrman.SelectTriedCollision(); BOOST_CHECK(info.ToString() == "250.1.1.19:0"); // Ensure test of address fails, so that it is evicted. addrman.SimConnFail(info); // Should swap 23 for 19. addrman.ResolveCollisions(); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0"); // If 23 was swapped for 19, then this should cause no collisions. addrman.Add(CAddress(addr, NODE_NONE), source); addrman.Good(addr); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0"); // If we insert 19 is should collide with 23. CService addr19 = ResolveService("250.1.1.19"); addrman.Add(CAddress(addr19, NODE_NONE), source); addrman.Good(addr19); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "250.1.1.23:0"); addrman.ResolveCollisions(); BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0"); } BOOST_AUTO_TEST_SUITE_END()
.size 8000 .text@48 ei jp lstatint .text@100 jp lbegin .data@143 c0 .text@150 lbegin: ld a, 00 ldff(ff), a ld a, 30 ldff(00), a ld a, 01 ldff(4d), a stop, 00 ld c, 44 ld b, 90 lbegin_waitly90: ldff a, (c) cmp a, b jrnz lbegin_waitly90 ld a, 11 ldff(40), a ld hl, 8000 ld b, 08 lbegin_settile0data: ld a, 00 ld(hl++), a ld a, 7e ld(hl++), a dec b jrnz lbegin_settile0data ld b, 08 lbegin_settile1data: ld a, 00 ld(hl++), a ld a, 81 ld(hl++), a dec b jrnz lbegin_settile1data ld b, 08 lbegin_settile2data: ld a, ff ld(hl++), a ld a, 81 ld(hl++), a dec b jrnz lbegin_settile2data ld b, 08 lbegin_settile3data: ld a, ff ld(hl++), a ld a, 7e ld(hl++), a dec b jrnz lbegin_settile3data ld c, 12 ld hl, 9800 lbegin_set_bgmap: ld b, 06 ld a, 02 lbegin_set_bgmapline_tilenos0to11: ld(hl++), a inc a ld(hl++), a dec a dec b jrnz lbegin_set_bgmapline_tilenos0to11 ld b, 0a lbegin_set_bgmapline_tilenos12to31: xor a, a ld(hl++), a inc a ld(hl++), a dec b jrnz lbegin_set_bgmapline_tilenos12to31 dec c jrnz lbegin_set_bgmap ld a, e4 ldff(47), a ld a, 80 ldff(68), a ld c, 69 xor a, a ldff(c), a ldff(c), a ld a, 94 ldff(c), a ld a, 52 ldff(c), a ld a, 08 ldff(c), a ld a, 21 ldff(c), a ld a, ff ldff(c), a ldff(c), a ld a, 20 ldff(41), a ld a, 02 ldff(ff), a ld c, 43 ld a, 91 ldff(40), a ei ld a, 03 .text@1000 lstatint: ldff(c), a ld a, 67 .text@1025 ldff(c), a pop hl ld a, c0 .text@1063 ldff(c), a ld a, 03
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %rax push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_D_ht+0x1060b, %rsi lea addresses_A_ht+0x172ff, %rdi nop nop nop nop nop xor %r11, %r11 mov $87, %rcx rep movsq add $17439, %rax lea addresses_A_ht+0x16303, %r13 nop nop nop sub %rbp, %rbp mov $0x6162636465666768, %rdi movq %rdi, %xmm0 and $0xffffffffffffffc0, %r13 movntdq %xmm0, (%r13) cmp %rdi, %rdi lea addresses_normal_ht+0x410b, %r11 nop nop nop nop nop cmp $54093, %rax mov $0x6162636465666768, %rcx movq %rcx, %xmm1 movups %xmm1, (%r11) nop xor %r11, %r11 lea addresses_WC_ht+0x1dd0b, %rsi lea addresses_WT_ht+0xe35b, %rdi nop nop nop nop dec %rbp mov $11, %rcx rep movsb nop nop nop nop nop add $41626, %rax lea addresses_WT_ht+0x1cb8b, %rcx nop nop nop nop sub $58421, %rdi movb $0x61, (%rcx) nop nop add %rbp, %rbp lea addresses_D_ht+0xd60b, %rsi lea addresses_WC_ht+0x9ef, %rdi nop nop nop nop cmp %rdx, %rdx mov $90, %rcx rep movsw nop add $10455, %rdx lea addresses_normal_ht+0x1310b, %r11 nop nop xor $39111, %rsi mov $0x6162636465666768, %rbp movq %rbp, (%r11) add %rax, %rax lea addresses_A_ht+0x11c8b, %rdi nop nop nop nop cmp $49742, %rcx mov (%rdi), %esi nop nop nop nop sub %rdi, %rdi lea addresses_UC_ht+0xae0b, %rsi lea addresses_A_ht+0x7efb, %rdi clflush (%rsi) nop nop nop nop sub %rbp, %rbp mov $34, %rcx rep movsl nop nop nop nop nop and %rsi, %rsi lea addresses_A_ht+0x1e04b, %r13 add $30849, %r11 vmovups (%r13), %ymm7 vextracti128 $1, %ymm7, %xmm7 vpextrq $1, %xmm7, %rbp nop nop nop cmp %rdi, %rdi lea addresses_UC_ht+0x1a10b, %rsi lea addresses_WC_ht+0x910b, %rdi nop cmp %rdx, %rdx mov $72, %rcx rep movsb nop nop add $20715, %rax lea addresses_normal_ht+0x1369b, %rcx nop nop cmp $44635, %rdi and $0xffffffffffffffc0, %rcx vmovaps (%rcx), %ymm0 vextracti128 $1, %ymm0, %xmm0 vpextrq $0, %xmm0, %rsi nop nop nop add %rbp, %rbp lea addresses_D_ht+0x1c8bb, %rsi lea addresses_UC_ht+0x1050b, %rdi nop sub %rdx, %rdx mov $1, %rcx rep movsq nop nop nop nop add %rbp, %rbp pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %rax pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r9 push %rax push %rcx push %rdx // Faulty Load lea addresses_D+0x1010b, %r12 sub $17686, %r9 movups (%r12), %xmm4 vpextrq $1, %xmm4, %rax lea oracles, %rcx and $0xff, %rax shlq $12, %rax mov (%rcx,%rax,1), %rax pop %rdx pop %rcx pop %rax pop %r9 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_D', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': False, 'congruent': 8, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 2, 'type': 'addresses_A_ht'}} {'OP': 'STOR', 'dst': {'NT': True, 'same': True, 'congruent': 2, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 16}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 16}} {'src': {'same': False, 'congruent': 9, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1}} {'src': {'same': False, 'congruent': 8, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 2, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 8}} {'src': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 7, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_A_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 11, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_WC_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_normal_ht', 'AVXalign': True, 'size': 32}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 3, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
#ifndef __IAPIPSEUDOCONTAINER_HPP__ #define __IAPIPSEUDOCONTAINER_HPP__ #include "GlobalOperators.hpp" namespace GSAPI { class IAPIAttributeAdapterFactory; /** @interface */ template <typename APIType, typename FilterType, class Iterator> class IAPIPseudoContainer { public: typedef Iterator PseudoIterator; protected: FilterType typeFilter; IAPIAttributeAdapterFactory* attributeFactory; protected: Iterator CreateIterator (const typename Iterator::Parameters& params) const { return Iterator (params); } public: IAPIPseudoContainer (IAPIAttributeAdapterFactory* factory = nullptr) { attributeFactory = factory; } virtual void SetFilter (const FilterType& filter) { Copy (typeFilter, filter); } virtual void GetNext (APIType&) const = 0; virtual PseudoIterator Begin () const = 0; virtual const PseudoIterator End () const = 0; }; } // namespace GSAPI #endif //__IAPIPSEUDOCONTAINER_HPP__
; BubbleSort Procedure (BSort.asm) ; This program sorts an array of signed integers, using ; the Bubble sort algorithm. The main program is in B_main.asm. INCLUDE Irvine32.inc .code ;---------------------------------------------------------- BubbleSort PROC USES eax ecx esi, pArray:PTR DWORD, ; pointer to array Count:DWORD ; array size ; ; Sort an array of 32-bit signed integers in ascending order ; using the bubble sort algorithm. ; Receives: pointer to array, array size ; Returns: nothing ;----------------------------------------------------------- mov ecx,Count dec ecx ; decrement count by 1 L1: push ecx ; save outer loop count mov esi,pArray ; point to first value L2: mov eax,[esi] ; get array value cmp [esi+4],eax ; compare a pair of values jge L3 ; if [esi] <= [edi], don't exch xchg eax,[esi+4] ; exchange the pair mov [esi],eax L3: add esi,4 ; move both pointers forward loop L2 ; inner loop pop ecx ; retrieve outer loop count loop L1 ; else repeat outer loop L4: ret BubbleSort ENDP END
; A140525: a(1)=2. For n >=2, a(n) = the least integer >= a(n-1) that is not coprime to both a(n-1)+1 and a(n-1). ; Submitted by Jon Maiga ; 2,6,14,18,38,42,86,90,98,102,206,210,422,426,434,438,878,882,1766,1770,1778,1782,3566,3570,7142,7146,7154,7158,14318,14322,28646,28650,28658,28662,57326,57330,114662,114666,114674,114678,229358,229362,229400 mov $2,1 lpb $0 mov $3,$2 lpb $3 add $2,1 mov $4,$3 gcd $4,$2 sub $4,1 cmp $4,0 sub $3,$4 lpe sub $0,1 add $2,1 lpe mov $0,$2 mul $0,2
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r8 push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0x17931, %rcx xor $40448, %r12 mov $0x6162636465666768, %r8 movq %r8, (%rcx) nop nop nop inc %r11 lea addresses_normal_ht+0x4d81, %rdx nop nop dec %rcx movb $0x61, (%rdx) nop nop nop nop nop dec %r11 lea addresses_A_ht+0xc989, %rsi lea addresses_normal_ht+0x8fa4, %rdi nop nop nop nop sub %r11, %r11 mov $4, %rcx rep movsq nop sub $11987, %rdx lea addresses_D_ht+0x15946, %rsi lea addresses_UC_ht+0x3279, %rdi nop nop nop nop nop lfence mov $65, %rcx rep movsq nop nop nop nop nop sub %rbx, %rbx lea addresses_A_ht+0x6189, %r11 clflush (%r11) nop nop nop nop nop sub $54991, %r12 mov (%r11), %rcx nop nop nop nop xor $52915, %r8 lea addresses_D_ht+0x109c9, %r12 xor %rcx, %rcx movb $0x61, (%r12) nop nop cmp %r8, %r8 lea addresses_A_ht+0x6d49, %r11 nop nop nop sub $31755, %rbx movb (%r11), %cl nop nop sub $31551, %r8 lea addresses_WT_ht+0x2475, %r12 nop nop nop nop nop inc %rcx movb $0x61, (%r12) nop nop dec %rbx lea addresses_D_ht+0x287b, %rsi nop dec %rcx movups (%rsi), %xmm3 vpextrq $1, %xmm3, %rdi nop xor $17099, %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %r8 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r9 push %rax push %rbp push %rcx push %rdx push %rsi // Store lea addresses_UC+0x17ac9, %rsi sub %rbp, %rbp mov $0x5152535455565758, %rdx movq %rdx, %xmm3 movups %xmm3, (%rsi) nop cmp %rbp, %rbp // Store lea addresses_WT+0x14309, %rsi nop nop nop nop nop and $8260, %r9 mov $0x5152535455565758, %rdx movq %rdx, %xmm0 movntdq %xmm0, (%rsi) nop and %rdx, %rdx // Faulty Load lea addresses_RW+0xb09, %rcx nop nop sub %r12, %r12 mov (%rcx), %r9d lea oracles, %rcx and $0xff, %r9 shlq $12, %r9 mov (%rcx,%r9,1), %r9 pop %rsi pop %rdx pop %rcx pop %rbp pop %rax pop %r9 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 3, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 10, 'size': 16, 'same': False, 'NT': True}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 3, 'size': 8, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 3, 'size': 1, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 6, 'size': 1, 'same': True, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 6, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 2, 'size': 1, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': True, 'NT': False}} {'32': 21829} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Original work Copyright (C) 2016-2021, Intel Corporation // Modified work Copyright (C) 2022, Vanilla Blue team // // SPDX-License-Identifier: MIT /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Author(s): Filip Strugar (filip.strugar@gmail.com) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "vaRenderMaterial.h" #include "Rendering/vaRenderMesh.h" #include "Core/System/vaFileTools.h" #include "Rendering/vaStandardShapes.h" #include "Rendering/vaRenderDevice.h" #include "Rendering/vaRenderDeviceContext.h" #include "Rendering/vaAssetPack.h" #include "Core/vaXMLSerialization.h" #include "IntegratedExternals/vaImguiIntegration.h" #include "Rendering/vaTextureHelpers.h" #include "Core/vaUI.h" using namespace Vanilla; //vaRenderMeshManager & renderMeshManager, const vaGUID & uid const int c_renderMeshMaterialFileVersion = 3; static const int c_materialItemNameMaxLength = 24; static const float c_materialLowestSaneFloat = -100000.0f; // not using std::numeric_limits<float>::lowest( ) in order to reduce UI clutter static const float c_materialMaxSaneFloat = 100000.0f; // not using std::numeric_limits<float>::max( ) in order to reduce UI clutter static bool Serialize( vaXMLSerializer & serializer, const string & name, vaRenderMaterial::ValueType & value ) { vaSerializerScopedOpenChild nameScope( serializer, name, false ); if( !nameScope.IsOK( ) ) { return false; } int typeIndex = (serializer.IsWriting())?((int32)value.index()):(-1); if( !serializer.Serialize<int32>( "type", typeIndex ) ) { assert( false ); return false; } if( serializer.IsReading( ) ) { bool wasOk = false; switch( typeIndex ) { case( (int32)vaRenderMaterial::ValueTypeIndex::Bool ): { bool val; wasOk = serializer.Serialize( name, val ); if( wasOk ) value = val; } break; case( (int32)vaRenderMaterial::ValueTypeIndex::Integer ): { int32 val; wasOk = serializer.Serialize( name, val ); if( wasOk ) value = val; } break; case( (int32)vaRenderMaterial::ValueTypeIndex::Scalar ): { float val; wasOk = serializer.Serialize( name, val ); if( wasOk ) value = val; } break; case( (int32)vaRenderMaterial::ValueTypeIndex::Vector3 ): { vaVector3 val; wasOk = serializer.Serialize( name, val ); if( wasOk ) value = val; } break; case( (int32)vaRenderMaterial::ValueTypeIndex::Vector4 ): { vaVector4 val; wasOk = serializer.Serialize( name, val ); if( wasOk ) value = val; } break; default: assert( false ); break; } return wasOk; } else if( serializer.IsWriting( ) ) { switch( value.index( ) ) { case( (size_t)vaRenderMaterial::ValueTypeIndex::Bool ): return serializer.Serialize( name, std::get<bool>( value ) ); break; case( (size_t)vaRenderMaterial::ValueTypeIndex::Integer ): return serializer.Serialize( name, std::get<int32>( value ) ); break; case( (size_t)vaRenderMaterial::ValueTypeIndex::Scalar ): return serializer.Serialize( name, std::get<float>( value ) ); break; case( (size_t)vaRenderMaterial::ValueTypeIndex::Vector3 ): return serializer.Serialize( name, std::get<vaVector3>( value ) ); break; case( (size_t)vaRenderMaterial::ValueTypeIndex::Vector4 ): return serializer.Serialize( name, std::get<vaVector4>( value ) ); break; default: assert( false ); return false; break; } } else { assert( false ); return false; } } static void GetDefaultMinMax( vaRenderMaterial::ValueTypeIndex type, vaRenderMaterial::ValueType & outMin, vaRenderMaterial::ValueType & outMax ) { switch( type ) { case( vaRenderMaterial::ValueTypeIndex::Bool ): outMin = false; outMax = true; break; case( vaRenderMaterial::ValueTypeIndex::Integer ): outMin = std::numeric_limits<int>::lowest( ); outMax = std::numeric_limits<int>::max( ); break; case( vaRenderMaterial::ValueTypeIndex::Scalar ): outMin = c_materialLowestSaneFloat; outMax = c_materialMaxSaneFloat; break; case( vaRenderMaterial::ValueTypeIndex::Vector3 ): outMin = vaVector3( c_materialLowestSaneFloat, c_materialLowestSaneFloat, c_materialLowestSaneFloat ); outMax = vaVector3( c_materialMaxSaneFloat, c_materialMaxSaneFloat, c_materialMaxSaneFloat ); break; case( vaRenderMaterial::ValueTypeIndex::Vector4 ): outMin = vaVector4( c_materialLowestSaneFloat, c_materialLowestSaneFloat, c_materialLowestSaneFloat, c_materialLowestSaneFloat ); outMax = vaVector4( c_materialMaxSaneFloat, c_materialMaxSaneFloat, c_materialMaxSaneFloat, c_materialMaxSaneFloat ); break; default: assert( false ); break; } } static void SetToOne( vaRenderMaterial::ValueType & value ) { switch( (vaRenderMaterial::ValueTypeIndex)value.index() ) { case( vaRenderMaterial::ValueTypeIndex::Bool ): value = true; break; case( vaRenderMaterial::ValueTypeIndex::Integer ): value = (int)1; break; case( vaRenderMaterial::ValueTypeIndex::Scalar ): value = (float)1.0f; break; case( vaRenderMaterial::ValueTypeIndex::Vector3 ): value = vaVector3( 1.0f, 1.0f, 1.0f ); break; case( vaRenderMaterial::ValueTypeIndex::Vector4 ): value = vaVector4( 1.0f, 1.0f, 1.0f, 1.0f ); break; default: assert( false ); break; }; } static void UploadToConstants( const vaRenderMaterial::ValueType & value, vaVector4 & destination ) { switch( (vaRenderMaterial::ValueTypeIndex)value.index() ) { case( vaRenderMaterial::ValueTypeIndex::Bool ): destination = { std::get<bool>( value )?(1.0f):(0.0f), 0, 0, 0 }; break; // not sure if we want reinterpret cast here - storing 1 in float is actually 0x3f800000 case( vaRenderMaterial::ValueTypeIndex::Integer ): destination = { reinterpret_cast<const float &>( std::get<int32>( value ) ), 0, 0, 0 }; break; case( vaRenderMaterial::ValueTypeIndex::Scalar ): destination = { std::get<float>( value ), 0, 0, 0 }; break; case( vaRenderMaterial::ValueTypeIndex::Vector3 ): destination = vaVector4( std::get<vaVector3>( value ), 0 ); break; case( vaRenderMaterial::ValueTypeIndex::Vector4 ): destination = std::get<vaVector4>( value ); break; default: assert( false ); break; }; } static string ValueTypeIndexToHLSL( vaRenderMaterial::ValueTypeIndex type ) { switch( type ) { case( vaRenderMaterial::ValueTypeIndex::Bool ): return "bool"; break; case( vaRenderMaterial::ValueTypeIndex::Integer ): return "int"; break; case( vaRenderMaterial::ValueTypeIndex::Scalar ): return "float"; break; case( vaRenderMaterial::ValueTypeIndex::Vector3 ): return "float3"; break; case( vaRenderMaterial::ValueTypeIndex::Vector4 ): return "float4"; break; default: assert( false ); return ""; break; }; } static int ValueTypeIndexGetComponentCount( vaRenderMaterial::ValueTypeIndex type ) { switch( type ) { case( vaRenderMaterial::ValueTypeIndex::Bool ): return 1; break; case( vaRenderMaterial::ValueTypeIndex::Integer ): return 1; break; case( vaRenderMaterial::ValueTypeIndex::Scalar ): return 1; break; case( vaRenderMaterial::ValueTypeIndex::Vector3 ): return 3; break; case( vaRenderMaterial::ValueTypeIndex::Vector4 ): return 4; break; default: assert( false ); return 0; break; }; } static string ValueTypeToHLSL( const vaRenderMaterial::ValueType & value, int constantsSlot ) { #ifdef VA_MATERIAL_FAVOR_FEWER_PERMUTATONS string slot = vaStringTools::Format( "materialConstants.Constants[%d]", constantsSlot ); // <- this can be easily optimized switch( (vaRenderMaterial::ValueTypeIndex)value.index() ) { case( vaRenderMaterial::ValueTypeIndex::Bool ): { return "bool("+slot+".x)"; } break; case( vaRenderMaterial::ValueTypeIndex::Integer ): { return "asint("+slot+".x)"; } break; case( vaRenderMaterial::ValueTypeIndex::Scalar ): { return "float("+slot+".x)"; } break; case( vaRenderMaterial::ValueTypeIndex::Vector3 ): { return "float3("+slot+".xyz)"; } break; case( vaRenderMaterial::ValueTypeIndex::Vector4 ): { return "float4("+slot+".xyzw)"; } break; default: assert( false ); return ""; break; }; #else constantsSlot; switch( (vaRenderMaterial::ValueTypeIndex)value.index() ) { case( vaRenderMaterial::ValueTypeIndex::Bool ): { bool val = std::get<bool>(value); return val?"bool(true)" : "bool(false)"; } break; case( vaRenderMaterial::ValueTypeIndex::Integer ): { int32 val = std::get<int32>(value); return vaStringTools::Format( "int(%d)", val ); } break; case( vaRenderMaterial::ValueTypeIndex::Scalar ): { float val = std::get<float>(value); return vaStringTools::Format( "float(%f)", val ); } break; case( vaRenderMaterial::ValueTypeIndex::Vector3 ): { vaVector3 val = std::get<vaVector3>(value); return vaStringTools::Format( "float3(%f,%f,%f)", val.x, val.y, val.z ); } break; case( vaRenderMaterial::ValueTypeIndex::Vector4 ): { vaVector4 val = std::get<vaVector4>(value); return vaStringTools::Format( "float4(%f,%f,%f,%f)", val.x, val.y, val.z, val.w ); } break; default: assert( false ); return ""; break; }; #endif } static string Vector3ToString( const vaVector3 & val, int floatPrecisionDecimals ) { string fltFormat = "%." + vaStringTools::Format( "%d", floatPrecisionDecimals ) + "f"; return vaStringTools::Format( (fltFormat+","+fltFormat+","+fltFormat).c_str(), val.x, val.y, val.z ); } static string Vector4ToString( const vaVector4& val, int floatPrecisionDecimals ) { string fltFormat = "%." + vaStringTools::Format( "%d", floatPrecisionDecimals ) + "f"; return vaStringTools::Format( ( fltFormat + "," + fltFormat + "," + fltFormat + "," + fltFormat ).c_str( ), val.x, val.y, val.z, val.w ); } static string ValueTypeToString( const vaRenderMaterial::ValueType & value, int floatPrecisionDecimals ) { string fltFormat = "%." + vaStringTools::Format( "%d", floatPrecisionDecimals ) + "f"; switch( (vaRenderMaterial::ValueTypeIndex)value.index() ) { case( vaRenderMaterial::ValueTypeIndex::Bool ): { bool val = std::get<bool>(value); return val?"true" : "false"; } break; case( vaRenderMaterial::ValueTypeIndex::Integer ): { int32 val = std::get<int32>(value); return vaStringTools::Format( "%d", val ); } break; case( vaRenderMaterial::ValueTypeIndex::Scalar ): { float val = std::get<float>(value); return vaStringTools::Format( fltFormat.c_str(), val ); } break; case( vaRenderMaterial::ValueTypeIndex::Vector3 ): { vaVector3 val = std::get<vaVector3>(value); return Vector3ToString( val, floatPrecisionDecimals ); } break; case( vaRenderMaterial::ValueTypeIndex::Vector4 ): { vaVector4 val = std::get<vaVector4>(value); return Vector4ToString( val, floatPrecisionDecimals ); } break; default: assert( false ); return ""; break; }; } static string TextureSlotToHLSLVariableName( int slotIndex ) { return vaStringTools::Format( "g_BindlessSRVIndices[%02d]", slotIndex ); } static bool SanitizeSwizzle( char inoutSwizzle[], vaRenderMaterial::ValueTypeIndex dstType, vaRenderMaterial::ValueTypeIndex srcType = vaRenderMaterial::ValueTypeIndex::Vector4 ) { bool hasChanged = false; int dstCompCount = ValueTypeIndexGetComponentCount( dstType ); int srcCompCount = ValueTypeIndexGetComponentCount( srcType ); for( int i = 0; i < dstCompCount; i++ ) { int j = (inoutSwizzle[i]=='x')?(0):( (inoutSwizzle[i]=='y')?(1):( (inoutSwizzle[i]=='z')?(2):( (inoutSwizzle[i]=='w')?(3):( 4 ) ) ) ); if( j >= srcCompCount ) { hasChanged = true; inoutSwizzle[i] = 'x'; } } for( int i = dstCompCount; i < 4; i++ ) { if( inoutSwizzle[i] != '\0' ) { hasChanged = true; inoutSwizzle[i] = '\0'; } } inoutSwizzle[4] = '\0'; return hasChanged; } static string SwizzleToString( char swizzle[5] ) { string ret = ""; for( int i = 0; i < 4; i++ ) { if( swizzle[i] == '\0' ) return ret; ret += swizzle[i]; } return ret; } static void StringToSwizzle( char outSwizzle[], const string & inString ) { for( int i = 0; i < 4; i++ ) { if( i >= inString.length() ) outSwizzle[i] = '\0'; else outSwizzle[i] = inString[i]; } outSwizzle[4] = '\0'; } static string SanitizeInputSlotOrNodeName( const string& name ) { string newValueName = name; const int maxLength = c_materialItemNameMaxLength; //assert( newValueName.length( ) > 0 && newValueName.length( ) <= maxLength ); // limited for UI and search/serialization reasons if( newValueName.length( ) == 0 ) newValueName = "unnamed"; if( newValueName.length( ) > maxLength ) newValueName = newValueName.substr( 0, maxLength ); for( int i = 0; i < newValueName.length( ) - 1; i++ ) { if( !( ( newValueName[i] >= '0' && newValueName[i] <= '9' ) || ( newValueName[i] >= 'A' && newValueName[i] <= 'z' ) || ( newValueName[i] == '_' ) || ( newValueName[i] == 0 ) ) ) { // invalid character used, will be replaced with _ assert( false ); newValueName[i] = '_'; } } return newValueName; } #pragma warning ( suppress: 4505 ) // unreferenced local function has been removed static bool IsValidSwizzle( const string& swizzleString ) { if( swizzleString.length() == 0 || swizzleString.length() > 4 ) return false; for( size_t i = 0; i < swizzleString.length(); i++ ) if( swizzleString[i] != 'x' && swizzleString[i] != 'y' && swizzleString[i] != 'z' && swizzleString[i] != 'w' ) return false; return true; } static bool s_constructingFromCreateRenderMaterial = false; vaRenderMaterial::vaRenderMaterial( const vaRenderingModuleParams & params ) : vaRenderingModule( params ), vaAssetResource( vaSaferStaticCast< const vaRenderMaterialConstructorParams &, const vaRenderingModuleParams &>( params ).UID), //m_trackee( vaSaferStaticCast< const vaRenderMaterialConstructorParams &, const vaRenderingModuleParams &>( params ).RenderMaterialManager.GetRenderMaterialTracker( ), this ), m_renderMaterialManager( vaSaferStaticCast< const vaRenderMaterialConstructorParams &, const vaRenderingModuleParams &>( params ).RenderMaterialManager ) //, m_constantBuffer( params ) { m_shaderMacros.reserve( 16 ); m_shaderMacrosDirty = true; m_shadersDirty = true; { assert( s_constructingFromCreateRenderMaterial ); // see mutex locking // std::unique_lock managerLock( m_renderMaterialManager.Mutex() ); <- locked in CreateRenderMaterial - it's also the only place where this is allowed to be constructed from m_globalIndex = m_renderMaterialManager.Materials().Insert( this ); } m_currentShaderConstants.Invalidate(); } vaRenderMaterial::~vaRenderMaterial() { { std::unique_lock managerLock( m_renderMaterialManager.Mutex() ); m_renderMaterialManager.Materials().Remove( m_globalIndex ); } } // TODO: convert all of these to enums at some point! // obsolete, removing // static const char * c_Legacy = "Legacy"; // static const char * c_Unlit = "Unlit"; // these new ones will roughly match Filament materials (see https://google.github.io/filament/Materials.html#overview/coreconcepts) static const char * c_FilamentStandard = "FilamentStandard"; static const char * c_FilamentSubsurface = "FilamentSubsurface"; static const char * c_FilamentCloth = "FilamentCloth"; static const char * c_FilamentUnlit = "FilamentUnlit"; static const char * c_FilamentSpecGloss = "FilamentSpecGloss"; std::vector<string> vaRenderMaterial::GetPresetMaterials( ) { return { /*c_Legacy, c_Unlit,*/ c_FilamentStandard, c_FilamentSubsurface, c_FilamentCloth, c_FilamentUnlit, c_FilamentSpecGloss }; } bool vaRenderMaterial::SetupFromPreset( const string & presetName, bool removeNodes ) { m_shaderSettings.BaseMacros.clear(); m_computedTextureSlotCount = 0; m_computedConstantsSlotCount = 0; m_currentShaderConstants.Invalidate(); m_shaderSettings.VS_Standard = std::make_pair( "vaRenderMesh.hlsl", "VS_Standard" ); m_shaderSettings.GS_Standard = { "", "" }; m_shaderSettings.PS_DepthOnly = std::make_pair( "vaRenderMaterial.hlsl", "PS_DepthOnly" ); m_shaderSettings.PS_Forward = std::make_pair( "vaRenderMaterial.hlsl", "PS_Forward" ); //m_shaderSettings.PS_Deferred = { "", "" }; // std::make_pair( "vaRenderMaterial.hlsl", "PS_Deferred" ); m_shaderSettings.PS_RichPrepass = std::make_pair( "vaRenderMaterial.hlsl", "PS_RichPrepass" ); m_shaderSettings.CAL_LibraryFile = "vaRenderMaterial.hlsl"; if( removeNodes ) RemoveAllNodes( ); RemoveAllInputSlots( ); m_shaderMacros.clear(); m_shaderMacrosDirty = true; bool retVal = false; if( vaStringTools::CompareNoCase( presetName, c_FilamentStandard ) == 0 ) { // see https://google.github.io/filament/Material%20Properties.pdf // also see material_inputs.va.fs SetInputSlot( "BaseColor", vaVector4( 1.0f, 1.0f, 1.0f, 1.0f ), true, true ); //SetInputSlot( "Opacity", 1.0f, false ); // handled by BaseColor alpha - could be separate though, would probably be cleaner SetInputSlot( "Normal", vaVector3( 0.0f, 0.0f, 1.0f ), false, false ); SetInputSlot( "EmissiveColor", vaVector3( 1.0f, 1.0f, 1.0f ), true, true ); SetInputSlot( "EmissiveIntensity", 0.0f, false, false ); SetInputSlot( "Roughness", 1.0f, false, false ); SetInputSlot( "Metallic", 0.0f, false, false ); SetInputSlot( "Reflectance", 0.35f, false, false ); SetInputSlot( "AmbientOcclusion", 1.0f, true, false ); // not yet implemented: /* float ClearCoat; // Strength of the clear coat layer on top of a base dielectric or conductor layer. The clear coat layer will commonly be set to 0.0 or 1.0. This layer has a fixed index of refraction of 1.5. float ClearCoatRoughness; // Defines the perceived smoothness (0.0) or roughness (1.0) of the clear coat layer. It is sometimes called glossiness. This may affect the roughness of the base layer float Anisotropy; // Defines whether the material appearance is directionally dependent, that is isotropic (0.0) or anisotropic (1.0). Brushed metals are anisotropic. Values can be negative to change the orientation of the specular reflections. float3 AnisotropyDirection; // The anisotropyDirection property defines the direction of the surface at a given point and thus control the shape of the specular highlights. It is specified as vector of 3 values that usually come from a texture, encoding the directions local to the surface. #if defined(MATERIAL_HAS_CLEAR_COAT) //&& defined(MATERIAL_HAS_CLEAR_COAT_NORMAL) float3 ClearCoatNormal; // Same as Normal except additionally defining a different normal for the clear coat! #endif */ m_shaderSettings.BaseMacros.push_back( { "VA_FILAMENT_STANDARD", "" } ); m_shaderSettings.PS_RichPrepass = std::make_pair( "vaRenderMaterial.hlsl", "PS_RichPrepass" ); m_shaderSettings.PS_DepthOnly = std::make_pair( "vaRenderMaterial.hlsl", "PS_DepthOnly" ); m_shaderSettings.PS_Forward = std::make_pair( "vaRenderMaterial.hlsl", "PS_Forward" ); retVal = true; } else if( vaStringTools::CompareNoCase( presetName, c_FilamentSubsurface ) == 0 ) { // see https://google.github.io/filament/Material%20Properties.pdf m_shaderSettings.BaseMacros.push_back( { "VA_FILAMENT_SUBSURFACE", "" } ); m_shaderSettings.PS_RichPrepass = std::make_pair( "vaRenderMaterial.hlsl", "PS_RichPrepass" ); m_shaderSettings.PS_DepthOnly = std::make_pair( "vaRenderMaterial.hlsl", "PS_DepthOnly" ); m_shaderSettings.PS_Forward = std::make_pair( "vaRenderMaterial.hlsl", "PS_Forward" ); retVal = true; } else if( vaStringTools::CompareNoCase( presetName, c_FilamentCloth ) == 0 ) { // see https://google.github.io/filament/Material%20Properties.pdf m_shaderSettings.BaseMacros.push_back( { "VA_FILAMENT_CLOTH", "" } ); m_shaderSettings.PS_RichPrepass = std::make_pair( "vaRenderMaterial.hlsl", "PS_RichPrepass" ); m_shaderSettings.PS_DepthOnly = std::make_pair( "vaRenderMaterial.hlsl", "PS_DepthOnly" ); m_shaderSettings.PS_Forward = std::make_pair( "vaRenderMaterial.hlsl", "PS_Forward" ); retVal = true; } else if( vaStringTools::CompareNoCase( presetName, c_FilamentUnlit) == 0 ) { // see https://google.github.io/filament/Material%20Properties.pdf m_shaderSettings.BaseMacros.push_back( { "VA_FILAMENT_UNLIT", "" } ); m_shaderSettings.PS_RichPrepass = std::make_pair( "vaRenderMaterial.hlsl", "PS_RichPrepass" ); m_shaderSettings.PS_DepthOnly = std::make_pair( "vaRenderMaterial.hlsl", "PS_DepthOnly" ); m_shaderSettings.PS_Forward = std::make_pair( "vaRenderMaterial.hlsl", "PS_Forward" ); retVal = true; } else if( vaStringTools::CompareNoCase( presetName, c_FilamentSpecGloss ) == 0 ) { // see https://google.github.io/filament/Material%20Properties.pdf m_shaderSettings.BaseMacros.push_back( { "VA_FILAMENT_SPECGLOSS", "" } ); SetInputSlot( "BaseColor", vaVector4( 1.0f, 1.0f, 1.0f, 1.0f ), true, true ); //SetInputSlot( "Opacity", 1.0f, false ); // handled by BaseColor alpha - could be separate though, would probably be cleaner SetInputSlot( "Normal", vaVector3( 0.0f, 0.0f, 1.0f ), false, false ); SetInputSlot( "EmissiveColor", vaVector3( 0.0f, 0.0f, 0.0f ), true, true ); SetInputSlot( "EmissiveIntensity", 1.0f, false, false ); // SetInputSlot( "Roughness", 1.0f, false ); // these don't exist in specular/glosiness model // SetInputSlot( "Metallic", 0.0f, false ); // these don't exist in specular/glosiness model // SetInputSlot( "Reflectance", 0.35f, false ); // these don't exist in specular/glosiness model SetInputSlot( "AmbientOcclusion", 1.0f, true, false ); SetInputSlot( "SpecularColor", vaVector3( 0.0f, 0.0f, 0.0f ), true, true ); SetInputSlot( "Glossiness", 0.0f, false, false ); m_shaderSettings.PS_RichPrepass = std::make_pair( "vaRenderMaterial.hlsl", "PS_RichPrepass" ); m_shaderSettings.PS_DepthOnly = std::make_pair( "vaRenderMaterial.hlsl", "PS_DepthOnly" ); m_shaderSettings.PS_Forward = std::make_pair( "vaRenderMaterial.hlsl", "PS_Forward" ); retVal = true; } UpgradeToNewMaterial( ); assert( retVal ); // preset not recognized, material no longer correct return retVal; } bool vaRenderMaterial::SetupFromOther( const vaRenderMaterial & other ) { SetShaderSettings( other.GetShaderSettings() ); SetMaterialSettings( other.GetMaterialSettings() ); m_computedTextureSlotCount = 0; m_computedConstantsSlotCount = 0; m_currentShaderConstants.Invalidate(); RemoveAllInputSlots(); RemoveAllNodes(); m_inputSlots = other.GetInputSlots(); const std::vector<shared_ptr<Node>> & otherNodes = other.GetNodes(); for( int i = 0; i < otherNodes.size(); i++ ) { shared_ptr<TextureNode> textureNode = std::dynamic_pointer_cast<TextureNode, Node>( otherNodes[i] ); if( textureNode != nullptr ) { auto copy = std::make_shared<TextureNode>(*textureNode); m_nodes.push_back( std::static_pointer_cast<Node, TextureNode>( copy ) ); } else { assert( false ); } } assert( m_inputSlots.size() <= RENDERMATERIAL_MAX_INPUT_SLOTS ); assert( m_nodes.size() <= RENDERMATERIAL_MAX_NODES ); return true; } void vaRenderMaterial::UpdateShaderMacros( ) { UpdateInputsDependencies( ); if( !m_shaderMacrosDirty ) return; assert( m_inputSlots.size() <= RENDERMATERIAL_MAX_INPUT_SLOTS ); assert( m_nodes.size() <= RENDERMATERIAL_MAX_NODES ); std::vector< pair< string, string > > prevShaderMacros = m_shaderMacros; m_shaderMacros.clear(); // add global macros first (usually empty) m_shaderMacros = m_renderMaterialManager.GetGlobalShaderMacros( ); // start from base macros and add up from there // this can be useful if shader wants to know whether it's included from the vaRenderMaterial code m_shaderMacros.insert( m_shaderMacros.begin(), std::pair<string, string>( "VA_RENDER_MATERIAL", "1" ) ); // bool exportNormals = m_renderMaterialManager.GetGlobalDepthPrepassExportsNormals( ); // m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_DEPTH_PASS_EXPORTS_NORMALS",( ( exportNormals ) ? ( "1" ) : ( "0" ) ) ) ); m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_TRANSPARENT", ( ( IsTransparent() ) ? ( "1" ) : ( "0" ) ) ) ); //m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_DECAL", ( ( IsDecal() ) ? ( "1" ) : ( "0" ) ) ) ); m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_ALPHATEST", ( ( IsAlphaTested() ) ? ( "1" ) : ( "0" ) ) ) ); //m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_ALPHATEST_THRESHOLD", vaStringTools::Format( "(%.3f)", m_materialSettings.AlphaTestThreshold ) ) ); m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_WIREFRAME", ( ( m_materialSettings.Wireframe ) ? ( "1" ) : ( "0" ) ) ) ); //m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_ADVANCED_SPECULAR_SHADER", ( ( m_materialSettings.AdvancedSpecularShader ) ? ( "1" ) : ( "0" ) ) ) ); //if( m_materialSettings.LocalIBLNormalBasedBias != 0 ) // m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_LOCALIBL_NORMALBIAS", vaStringTools::Format( "(%.3f)", m_materialSettings.LocalIBLNormalBasedBias ) ) ); //if( m_materialSettings.LocalIBLBasedBias != 0 ) // m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_LOCALIBL_BIAS", vaStringTools::Format( "(%.3f)", m_materialSettings.LocalIBLBasedBias ) ) ); // texture declarations // no declarations for bindless! (yet - waiting for SM6.6) m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_TEXTURE_DECLARATIONS", "" ) ); // inputs declarations { string inputsDeclarations; for( int i = 0; i < m_inputSlots.size( ); i++ ) { const InputSlot & inputSlot = m_inputSlots[i]; inputsDeclarations.append( inputSlot.GetShaderMaterialInputsType() + " " + inputSlot.GetName() + "; " ); m_shaderMacros.push_back( { "VA_RM_HAS_INPUT_"+inputSlot.Name, "1" } ); } m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_INPUTS_DECLARATIONS", inputsDeclarations ) ); } // nodes declarations (+ loading from variable and/or textures) { string nodesDeclarations; for( int i = 0; i < m_nodes.size( ); i++ ) { const shared_ptr<Node> & node = m_nodes[i]; if( !node->InUse ) continue; assert( !m_renderMaterialManager.GetTexturingDisabled( ) ); nodesDeclarations.append( node->GetShaderMaterialInputsType( ) + " " + node->Name + " = " ); nodesDeclarations.append( node->GetShaderMaterialInputLoader( ) + "; " ); } m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_NODES_DECLARATIONS", nodesDeclarations ) ); } // load inputs from nodes { string inputsLoading; for( int i = 0; i < m_inputSlots.size( ); i++ ) { const InputSlot& inputSlot = m_inputSlots[i]; assert( inputSlot.ComputedShaderConstantsSlot >= 0 ); shared_ptr<const Node> node = inputSlot.CachedConnectedInput.lock(); // the approach below is slightly less efficient but reduces shader permutation count // first the multiplier (which will be initialized just to 1 if no node attached) inputsLoading.append( "inputs." + inputSlot.GetName() + " = " + ValueTypeToHLSL(inputSlot.Properties.Default, inputSlot.ComputedShaderConstantsSlot) + "; " ); // then the node, if any, gets multiplied on top of it if( node != nullptr && node->InUse ) { assert( inputSlot.ConnectedInput != "" ); inputsLoading.append( "inputs." + inputSlot.GetName() + " *= " + node->Name + "." + string(inputSlot.InputSwizzle) + "; " ); } // this is the old approach; there's also swizzling for multiplier/defaults that now gets ignored, which is just a different design choice /* if( node == nullptr || !node->InUse ) { if( node == nullptr ) assert( inputSlot.ConnectedInput == "" ); // if we're falling back to default, we have to consider scenarios where default is a single float but input node was picking a single channel from .y or .z or .w so we need to re-sanitize char inputSwizzle[5] = { inputSlot.InputSwizzle[0], inputSlot.InputSwizzle[1], inputSlot.InputSwizzle[2], inputSlot.InputSwizzle[3], inputSlot.InputSwizzle[4] }; // today's winner in "I'm ashamed of my code" SanitizeSwizzle( inputSwizzle, inputSlot.GetType(), inputSlot.Properties.GetType() ); inputsLoading.append( "inputs." + inputSlot.GetName( ) + " = " + ValueTypeToHLSL(inputSlot.Properties.Default, inputSlot.ComputedShaderConstantsSlot) + "." + string(inputSwizzle) + "; " ); } else { assert( inputSlot.ConnectedInput != "" ); //std::array<char *, 5> comps = { "", ".x", ".xy", ".xyz", ".xyzw" }; if( inputSlot.Properties.IsMultiplier ) inputsLoading.append( "inputs." + inputSlot.GetName() + " = (" + ValueTypeToHLSL(inputSlot.Properties.Default, inputSlot.ComputedShaderConstantsSlot) + "*" + node->Name + "." + string(inputSlot.InputSwizzle) + "); " ); else inputsLoading.append( "inputs." + inputSlot.GetName() + " = " + node->Name + "." + string(inputSlot.InputSwizzle) + "; " ); } */ } m_shaderMacros.push_back( std::pair<string, string>( "VA_RM_INPUTS_LOADING", inputsLoading ) ); } m_shaderMacros.insert( m_shaderMacros.end( ), m_shaderSettings.BaseMacros.begin( ), m_shaderSettings.BaseMacros.end( ) ); m_shaderMacrosDirty = false; m_shadersDirty = prevShaderMacros != m_shaderMacros; } void vaRenderMaterial::RemoveAllNodes( ) { assert( !m_immutable ); m_nodes.clear(); m_inputsDirty = true; } void vaRenderMaterial::RemoveAllInputSlots( ) { assert( !m_immutable ); m_inputSlots.clear( ); m_inputsDirty = true; } bool vaRenderMaterial::SaveAPACK( vaStream & outStream ) { // Just using SerializeUnpacked to implement this - not a lot of binary data; can be upgraded later vaXMLSerializer materialSerializer; GetManager( ).RegisterSerializationTypeConstructors( materialSerializer ); bool allOk; { vaSerializerScopedOpenChild rootNode( materialSerializer, "Material" ); allOk = rootNode.IsOK( ); if( allOk ) allOk = SerializeUnpacked( materialSerializer, "%there-is-no-folder@" ); } const char * buffer = materialSerializer.GetWritePrinter( ).CStr( ); int64 bufferSize = materialSerializer.GetWritePrinter( ).CStrSize( ); VERIFY_TRUE_RETURN_ON_FALSE( outStream.WriteValue<int64>( bufferSize ) ); VERIFY_TRUE_RETURN_ON_FALSE( outStream.Write( buffer, bufferSize ) ); return allOk; } bool vaRenderMaterial::LoadAPACK( vaStream & inStream ) { assert( !m_immutable ); // Just using SerializeUnpacked to implement this - not a lot of binary data; can be upgraded later int64 bufferSize = 0; VERIFY_TRUE_RETURN_ON_FALSE( inStream.ReadValue<int64>( bufferSize ) ); const char * buffer = new char[bufferSize]; if( !inStream.Read( (void*)buffer, bufferSize ) ) { delete[] buffer; VERIFY_TRUE_RETURN_ON_FALSE( false ); } vaXMLSerializer materialSerializer( buffer, bufferSize ); GetManager( ).RegisterSerializationTypeConstructors( materialSerializer ); bool allOk; { vaSerializerScopedOpenChild rootNode( materialSerializer, "Material" ); allOk = rootNode.IsOK( ); if( allOk ) allOk = SerializeUnpacked( materialSerializer, "%there-is-no-folder@" ); } assert( allOk ); delete[] buffer; return allOk; } bool vaRenderMaterial::SerializeUnpacked( vaXMLSerializer & serializer, const string & assetFolder ) { assetFolder; // unused int32 fileVersion = c_renderMeshMaterialFileVersion; VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<int32>( "FileVersion", fileVersion ) ); VERIFY_TRUE_RETURN_ON_FALSE( (fileVersion >= 2) && (fileVersion <= c_renderMeshMaterialFileVersion) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<int32>( "FaceCull", (int32&) m_materialSettings.FaceCull ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<float>( "AlphaTestThreshold", m_materialSettings.AlphaTestThreshold ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<bool>( "Wireframe", m_materialSettings.Wireframe ) ); //VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<bool>( "AdvancedSpecularShader", m_materialSettings.AdvancedSpecularShader, m_materialSettings.AdvancedSpecularShader ) ); /*VERIFY_TRUE_RETURN_ON_FALSE*/( serializer.Serialize<float>( "LocalIBLNormalBasedBias", m_materialSettings.LocalIBLNormalBasedBias ) ); /*VERIFY_TRUE_RETURN_ON_FALSE*/( serializer.Serialize<float>( "LocalIBLBasedBias", m_materialSettings.LocalIBLBasedBias ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<float>( "IndexOfRefraction", m_materialSettings.IndexOfRefraction, 1.00029f ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<bool>( "NEETranslucent", m_materialSettings.NEETranslucent, false ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<float>( "NEETranslucentAlpha", m_materialSettings.NEETranslucentAlpha, 0.1f ) ); // handle backward compatibility if( !serializer.Serialize<int32>( "LayerMode", (int32&)m_materialSettings.LayerMode ) ) { bool alphaTest = false, transparent = false, decal = false; VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<bool>( "AlphaTest", alphaTest ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<bool>( "Transparent", transparent ) ); /*VERIFY_TRUE_RETURN_ON_FALSE(*/ serializer.Serialize<bool>( "Decal", decal, false ) /*)*/; m_materialSettings.LayerMode = vaLayerMode::Opaque; if( alphaTest ) m_materialSettings.LayerMode = vaLayerMode::AlphaTest; if( transparent ) { assert( m_materialSettings.LayerMode == vaLayerMode::Opaque ); m_materialSettings.LayerMode = vaLayerMode::Transparent; } if( decal ) { assert( m_materialSettings.LayerMode == vaLayerMode::Opaque ); m_materialSettings.LayerMode = vaLayerMode::Decal; } } /*VERIFY_TRUE_RETURN_ON_FALSE(*/ serializer.Serialize<int32>( "DecalSortOrder", m_materialSettings.DecalSortOrder ) /*)*/; m_materialSettings.DecalSortOrder = vaMath::Clamp( m_materialSettings.DecalSortOrder, -10000, 10000 ); string oldFormatShaderFileName = ""; if( serializer.IsReading( ) ) { if( serializer.Serialize<string>( "ShaderFileName", oldFormatShaderFileName ) ) { assert( false ); } } VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "Class", m_class, "" ) ); if( m_class == "" ) { VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderFileNameVS_Standard", m_shaderSettings.VS_Standard.first, oldFormatShaderFileName ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderFileNameGS_Standard", m_shaderSettings.GS_Standard.first, "" ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderFileNamePS_DepthOnly", m_shaderSettings.PS_DepthOnly.first, oldFormatShaderFileName ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderFileNamePS_Forward", m_shaderSettings.PS_Forward.first, oldFormatShaderFileName ) ); //VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderFileNamePS_Deferred", m_shaderSettings.PS_Deferred.first, oldFormatShaderFileName ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderFileNamePS_RichPrepass", m_shaderSettings.PS_RichPrepass.first, oldFormatShaderFileName ) ); // default to be removed in the future VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderEntryVS_Standard", m_shaderSettings.VS_Standard.second ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderEntryGS_Standard", m_shaderSettings.GS_Standard.second, "" ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderEntryPS_DepthOnly", m_shaderSettings.PS_DepthOnly.second ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderEntryPS_Forward", m_shaderSettings.PS_Forward.second ) ); //VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderEntryPS_Deferred", m_shaderSettings.PS_Deferred.second, string("") ) ); VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderEntryPS_RichPrepass", m_shaderSettings.PS_RichPrepass.second, string("PS_RichPrepass") ) ); // default to be removed in the future but make sure all assets have been re-saved! VERIFY_TRUE_RETURN_ON_FALSE( serializer.Serialize<string>( "ShaderEntryCAL_LibraryFile", m_shaderSettings.CAL_LibraryFile , "vaRenderMaterial.hlsl" ) ); if( serializer.IsReading() ) { m_shaderSettings.BaseMacros.clear(); auto updateShaderFileName = []( string & current ) { if( current == "vaMaterialFilament.hlsl" || current == "" ) current = "vaRenderMaterial.hlsl"; }; updateShaderFileName( m_shaderSettings.PS_Forward.first ); updateShaderFileName( m_shaderSettings.PS_RichPrepass.first ); updateShaderFileName( m_shaderSettings.PS_DepthOnly.first ); } } if( !serializer.SerializeArrayGeneric<std::vector<pair<string, string>>>( "ShaderBaseMacros", m_shaderSettings.BaseMacros, [ ] ( bool isReading, std::vector<pair<string, string>> & container, int & itemCount ) { if( isReading ) container.resize( itemCount ); else itemCount = (int)container.size(); }, [ ]( vaXMLSerializer & serializer, std::vector<pair<string, string>> & container, int index ) { bool allOk = true; pair<string, string> & inoutItem = container[index]; allOk &= serializer.Serialize<string>( "Name", inoutItem.first ); assert( allOk ); allOk &= serializer.Serialize<string>( "Definition", inoutItem.first ); assert( allOk ); return allOk; } ) ) { // do nothing, it's ok not to have ShadeBaseMacros for legacy reasons }; assert( serializer.GetVersion() > 0 ); if( serializer.IsReading( ) ) { // always needed m_inputsDirty = true; } serializer.SerializeArray( "InputSlots", m_inputSlots ); if( fileVersion == 2 ) { // this is a bit ugly & manual but that's the way it is until I get the new serialization approach working std::vector<shared_ptr<TextureNode>> textureNodes; if( serializer.IsWriting( ) ) { for( int i = 0; i < m_nodes.size(); i++ ) { auto snode = std::dynamic_pointer_cast<TextureNode, Node>( m_nodes[i] ); if( snode != nullptr ) textureNodes.push_back( snode ); } } serializer.SerializeArray( "TextureNodes", textureNodes ); if( serializer.IsReading( ) ) { for( int i = 0; i < textureNodes.size( ); i++ ) { m_nodes.push_back( std::static_pointer_cast<Node>( textureNodes[i] ) ); } } } else { VERIFY_TRUE_RETURN_ON_FALSE( serializer.TypedSerializeArray( "TextureNodes", m_nodes ) ); } #if 0 for( size_t i = 0; i < m_inputSlots.size(); i++ ) { if( m_inputSlots[i].Name == "InvGlossiness" ) { if( std::get<float>(m_inputSlots[i].Properties.Default) == 0.0f ) { // VA_LOG( " >>>>>>>>> MATERIAL %s", assetFolder.c_str() ); //m_inputSlots[i].Properties.IsMultiplier = false; SetInputSlotDefaultValue( "InvGlossiness", 0.09f ); } } } #endif assert( m_inputSlots.size() <= RENDERMATERIAL_MAX_INPUT_SLOTS ); assert( m_nodes.size() <= RENDERMATERIAL_MAX_NODES ); // converting to new material system if( serializer.IsReading() ) { UpgradeToNewMaterial( ); } return true; } void vaRenderMaterial::UpgradeToNewMaterial( ) { for( int index = 0; index < m_shaderSettings.BaseMacros.size(); index++ ) { if( m_shaderSettings.BaseMacros[index].first == "VA_FILAMENT_STANDARD" ) { m_shaderSettings.BaseMacros.erase( m_shaderSettings.BaseMacros.begin()+index ); m_class = "StandardPBR"; break; } else if( m_shaderSettings.BaseMacros[index].first == "VA_FILAMENT_SPECGLOSS" ) { m_shaderSettings.BaseMacros.erase( m_shaderSettings.BaseMacros.begin()+index ); m_class = "SpecGlossPBR"; break; } } assert( m_class != "" ); m_shaderSettings.VS_Standard = { "", "" }; m_shaderSettings.GS_Standard = { "", "" }; m_shaderSettings.PS_DepthOnly = { "", "" }; m_shaderSettings.PS_Forward = { "", "" }; m_shaderSettings.PS_RichPrepass = { "", "" }; m_shaderSettings.CAL_LibraryFile = ""; } void vaRenderMaterial::RegisterUsedAssetPacks( std::function<void( const vaAssetPack & )> registerFunction ) { assert( GetRenderDevice( ).IsRenderThread( ) ); vaAssetResource::RegisterUsedAssetPacks( registerFunction ); for( int i = 0; i < m_nodes.size(); i++ ) { auto snode = std::dynamic_pointer_cast<TextureNode, Node>( m_nodes[i] ); if( snode != nullptr && !snode->GetTextureUID( ).IsNull() ) { auto texture = snode->GetTextureFP( ); if( texture != nullptr ) { texture->RegisterUsedAssetPacks( registerFunction ); } else { // Either ReconnectDependencies( ) was not called, or the asset is missing? assert( false ); } } } } bool vaRenderMaterial::RemoveNode( const string & name, bool assertIfNotFound ) { assert( GetRenderDevice( ).IsRenderThread( ) ); assert( GetRenderDevice( ).IsRenderThread( ) ); assertIfNotFound; assert( !m_immutable ); int index = FindNodeIndex( name ); if( index == -1 ) { assert( !assertIfNotFound ); return false; } // replace with last and pop last (order doesn't matter) if( index < ( m_nodes.size( ) - 1 ) ) m_nodes[index] = m_nodes.back( ); m_nodes.pop_back( ); m_inputsDirty = true; return true; } namespace { static bool IsNumber( char c ) { return c >= '0' && c <= '9'; } }; string vaRenderMaterial::FindAvailableNodeName( const string & name ) { string retName = SanitizeInputSlotOrNodeName( name ); int index = 0; while( FindNode( retName ) != nullptr ) { // if last 3 characters are in _00 format, remove them if( retName.length() > 3 && retName[retName.length()-3] == '_' && IsNumber(retName[retName.length()-2]) && IsNumber(retName[retName.length()-1]) ) retName = retName.substr( 0, retName.length()-3 ); if( retName.length() > (c_materialItemNameMaxLength-3) ) retName = retName.substr(0, c_materialItemNameMaxLength-3); if( index > 99 ) retName = SanitizeInputSlotOrNodeName( vaCore::GUIDToStringA(vaCore::GUIDCreate()) ); else retName += vaStringTools::Format( "_%02d", index ); index++; } return retName; } bool vaRenderMaterial::SetNode( const shared_ptr<vaRenderMaterial::Node> & node ) { assert( GetRenderDevice( ).IsRenderThread( ) ); assert( !m_immutable ); int index = FindNodeIndex( node->GetName() ); if( index == -1 ) m_nodes.push_back( node ); else m_nodes[index] = node; assert( m_inputSlots.size() <= RENDERMATERIAL_MAX_INPUT_SLOTS ); assert( m_nodes.size() <= RENDERMATERIAL_MAX_NODES ); m_inputsDirty = true; return true; } bool vaRenderMaterial::SetTextureNode( const string & name, const vaGUID & textureUID, vaStandardSamplerType samplerType, int uvIndex ) { assert( GetRenderDevice( ).IsRenderThread( ) ); return SetNode( std::make_shared<TextureNode>( name, textureUID, samplerType, uvIndex ) ); } bool vaRenderMaterial::ReplaceTextureOnNode( const string& name, const vaGUID& textureUID ) { assert( GetRenderDevice( ).IsRenderThread( ) ); assert( !m_immutable ); auto oldTextureNode = FindNode<TextureNode>( name ); if( oldTextureNode == nullptr ) return false; return SetNode( std::make_shared<TextureNode>( name, textureUID, oldTextureNode->SamplerType, oldTextureNode->UVIndex ) ); } bool vaRenderMaterial::RemoveInputSlot( const string & name, bool assertIfNotFound ) { assert( GetRenderDevice( ).IsRenderThread( ) ); assertIfNotFound; assert( !m_immutable ); int index = FindInputSlotIndex( name ); if( index == -1 ) { assert( !assertIfNotFound ); return false; } // replace with last and pop last (order doesn't matter) if( index < ( m_inputSlots.size( ) - 1 ) ) m_inputSlots[index] = m_inputSlots.back( ); m_inputSlots.pop_back( ); m_inputsDirty = true; return true; } bool vaRenderMaterial::SetInputSlot( const vaRenderMaterial::InputSlot & inputSlot ) { assert( GetRenderDevice( ).IsRenderThread( ) ); assert( !m_immutable ); int index = FindInputSlotIndex( inputSlot.GetName( ) ); if( index == -1 ) m_inputSlots.push_back( inputSlot ); else m_inputSlots[index] = inputSlot; assert( m_inputSlots.size() <= RENDERMATERIAL_MAX_INPUT_SLOTS ); assert( m_nodes.size() <= RENDERMATERIAL_MAX_NODES ); m_inputsDirty = true; return true; } bool vaRenderMaterial::SetInputSlot( const string & name, const ValueType & default, bool defaultIsMultiplier, bool isColor ) { assert( GetRenderDevice( ).IsRenderThread( ) ); return SetInputSlot( InputSlot(name, default, defaultIsMultiplier, isColor ) ); } bool vaRenderMaterial::SetInputSlotDefaultValue( const string & name, const ValueType & default ) { assert( GetRenderDevice( ).IsRenderThread( ) ); bool assertOnError = true; assertOnError; assert( !m_immutable ); int index = FindInputSlotIndex( name ); if( index == -1 ) { assert( !assertOnError ); return false; } else { if( default.index( ) != m_inputSlots[index].Properties.Default.index( ) ) { assert( !assertOnError ); // type mismatch between the already defined input slot ValueType and the provided one return false; } m_inputSlots[index].Properties.Default = default; //m_inputSlots[index].Properties.IsMultiplier = defaultIsMultiplier; //m_inputSlots[index].Properties.IsColor = isColor; } m_inputsDirty = true; return true; } bool vaRenderMaterial::ConnectInputSlotWithNode( const string & inputSlotName, const string & nodeName, const string & inputSwizzle, bool assertIfFailed ) { assert( GetRenderDevice( ).IsRenderThread( ) ); assertIfFailed; int inputSlotIndex = FindInputSlotIndex( inputSlotName ); if( inputSlotIndex == -1 ) { assert( !assertIfFailed ); return false; } int nodeIndex = FindNodeIndex( nodeName ); if( nodeName != "" && nodeIndex == -1 ) { assert( !assertIfFailed ); return false; } ValueTypeIndex srcType = (nodeIndex == -1)?( m_inputSlots[inputSlotIndex].GetType() ) : ( m_nodes[nodeIndex]->GetType() ); m_inputSlots[inputSlotIndex].ConnectedInput = nodeName; m_inputSlots[inputSlotIndex].CachedConnectedInput.reset(); StringToSwizzle( m_inputSlots[inputSlotIndex].InputSwizzle, inputSwizzle ); SanitizeSwizzle( m_inputSlots[inputSlotIndex].InputSwizzle, m_inputSlots[inputSlotIndex].GetType(), srcType ); m_inputsDirty = true; return true; } void vaRenderMaterial::VerifyNames( ) { for( int i = 0; i < m_inputSlots.size(); i++ ) { // must find itself but must have no other inputs with the same name int foundIndex = -1; for( int j = 0; j < m_inputSlots.size(); j++ ) if( vaStringTools::ToLower( m_inputSlots[j].Name ) == vaStringTools::ToLower( m_inputSlots[i].Name ) ) { foundIndex = j; break; } assert( foundIndex == i ); } for( int i = 0; i < m_nodes.size( ); i++ ) { // must find itself but must have no other inputs with the same name assert( FindNode( m_nodes[i]->GetName() ) == m_nodes[i] ); } } void vaRenderMaterial::UpdateInputsDependencies( ) { // there is no real reason why this would happen at runtime except during editing and streaming; so in case there's no streaming, // update every 5th time; this could be further optimized if needed with dirty flags m_inputsDirtyThoroughTextureCheckCounter = (m_inputsDirtyThoroughTextureCheckCounter+1) % 5; if( m_inputsDirtyThoroughTextureCheckCounter == 0 || GetRenderDevice().GetAssetPackManager().HadAnyAsyncOpExecutingLastFrame() ) { for( int i = 0; i < m_nodes.size( ); i++ ) if( m_nodes[i]->RequiresReUpdate() ) m_inputsDirty = true; } if( m_inputsDirty ) { // reset all 'in use' flags for( int i = 0; i < m_nodes.size( ); i++ ) m_nodes[i]->InUse = false; m_computedTextureSlotCount = 0; m_computedConstantsSlotCount = 0; m_currentShaderConstants.Invalidate(); for( int i = 0; i < m_inputSlots.size( ); i++ ) { // assign new constants slot - this is always needed for the default value m_inputSlots[i].ComputedShaderConstantsSlot = m_computedConstantsSlotCount; if( m_computedConstantsSlotCount < RENDERMATERIAL_MAX_SHADER_CONSTANTS ) m_computedConstantsSlotCount++; else { VA_WARN( "vaRenderMaterial_UpdateInputsDependencies: more used constants than available - will be overwriting previous" ); assert( false ); } const string & connectedInputName = m_inputSlots[i].ConnectedInput; // and we can set the values here as well ValueType defaultValue = m_inputSlots[i].GetDefaultValue(); if( connectedInputName != "" && !m_inputSlots[i].Properties.IsMultiplier ) // if we've got an input and default isn't marked as a multiplier, set to 1 pass-through multiplier SetToOne( defaultValue ); UploadToConstants( defaultValue, m_currentShaderConstants.Constants[m_inputSlots[i].ComputedShaderConstantsSlot] ); if( connectedInputName == "" ) { m_inputSlots[i].CachedConnectedInput.reset(); continue; } shared_ptr<const Node> connectedNode = FindNode<Node>( connectedInputName ); if( connectedNode == nullptr ) { // this shouldn't happen - probably just disconnect? ConnectInputSlotWithNode( m_inputSlots[i].Name, "" ); assert( false ); continue; } connectedNode->InUse = true; m_inputSlots[i].CachedConnectedInput = connectedNode; } for( int i = 0; i < m_nodes.size( ); i++ ) { if( !m_nodes[i]->InUse ) { m_nodes[i]->ResetTemps( ); continue; } shared_ptr<const TextureNode> textureNode = std::dynamic_pointer_cast<const TextureNode, const Node>( m_nodes[i] ); if( m_renderMaterialManager.GetTexturingDisabled( ) ) textureNode = nullptr; if( textureNode != nullptr && textureNode->GetTextureFP() != nullptr ) { // assign new texture slot textureNode->ComputedShaderTextureSlot = m_computedTextureSlotCount; if( m_computedTextureSlotCount < RENDERMATERIAL_MAX_TEXTURES ) m_computedTextureSlotCount++; else { VA_WARN( "vaRenderMaterial_UpdateInputsDependencies: more used texture nodes than available shader texture slots - will be overwriting previous" ); assert( false ); } } else { if( textureNode != nullptr && !textureNode->GetTextureUID( ).IsNull() ) { auto missingTexture = textureNode->GetTexture( ); // VA_LOG( "vaRenderMaterial::UpdateInputsDependencies: trying to draw material with some textures not yet loaded" ); SetDelayedDirty( 0.1 ); // let's wait a short while until this is sorted (texture loaded or whatever) } m_nodes[i]->InUse = false; m_nodes[i]->ResetTemps( ); } } m_inputsDirty = false; m_shaderMacrosDirty = true; m_shadersDirty = true; } } vaFramePtr<vaVertexShader> vaRenderMaterial::GetVS( vaRenderMaterialShaderType shaderType ) { shaderType; if( m_shaders->VS_Standard->IsEmpty() ) return nullptr; // never use VS_PosOnly for now return m_shaders->VS_Standard.get(); } vaFramePtr<vaGeometryShader> vaRenderMaterial::GetGS( vaRenderMaterialShaderType shaderType ) { shaderType; if( m_shaders->GS_Standard->IsEmpty() ) return nullptr; return m_shaders->GS_Standard.get(); } vaFramePtr<vaPixelShader> vaRenderMaterial::GetPS( vaRenderMaterialShaderType shaderType ) { vaFramePtr<vaPixelShader> retVal; //if( shaderType == vaRenderMaterialShaderType::Deferred ) // retVal = m_shaders->PS_Deferred.get(); //else if( shaderType == vaRenderMaterialShaderType::Forward ) retVal = m_shaders->PS_Forward.get(); else if( shaderType == vaRenderMaterialShaderType::DepthOnly ) retVal = m_shaders->PS_DepthOnly.get(); else if( shaderType == vaRenderMaterialShaderType::RichPrepass ) retVal = m_shaders->PS_RichPrepass.get(); else { assert( false ); return nullptr; } if( retVal->IsEmpty() ) return nullptr; return retVal; } bool vaRenderMaterial::GetCallableShaderLibrary( vaFramePtr<vaShaderLibrary> & outLibrary, string & uniqueID, int & uniqueTableIndex ) { if( m_shaders == nullptr || m_shaders->CAL_Library.get() == nullptr || m_shaders->CAL_Library->IsEmpty() ) return false; outLibrary = m_shaders->CAL_Library; uniqueID = m_shaders->UniqueIDString; uniqueTableIndex = m_shaders->TableIndex; return true; } void vaRenderMaterial::SetDelayedDirty( double delayTime ) { //assert( m_mutex is locked ); m_delayedInputsSetDirty = vaCore::TimeFromAppStart() + delayTime; } bool vaRenderMaterial::Update( ) { // don't update if we've already updated this frame if( m_lastUpdateFrame == GetRenderDevice().GetCurrentFrameIndex() && !m_shaderMacrosDirty && !m_shadersDirty && !m_inputsDirty ) return true; if( m_delayedInputsSetDirty < vaCore::TimeFromAppStart() ) { m_delayedInputsSetDirty = std::numeric_limits<double>::max( ); m_inputsDirty = true; } UpdateShaderMacros( ); if( m_shaderMacrosDirty ) { // still dirty? there's non-loaded textures or something similar? - need to bail out. assert( false ); return false; } if( m_shadersDirty || (m_shaders == nullptr) ) { m_shaders = m_renderMaterialManager.FindOrCreateShaders( IsAlphaTested(), m_class, m_shaderSettings, m_shaderMacros ); m_shadersDirty = m_shaders == nullptr; assert( m_shaders != nullptr ); if( m_shadersDirty ) return false; } assert( !m_inputsDirty && !m_shadersDirty && !m_shaderMacrosDirty ); m_lastUpdateFrame = GetRenderDevice().GetCurrentFrameIndex(); return true; } void vaRenderMaterial::GetShaderState_VS_Standard( vaShader::State & outState, string & outErrorString ) { if( !Update() ) { outState = vaShader::State::Uncooked; outErrorString = "Material shader cache not (yet) created"; assert( false ); } m_shaders->VS_Standard->GetState( outState, outErrorString ); } void vaRenderMaterial::GetShaderState_GS_Standard( vaShader::State & outState, string & outErrorString ) { if( !Update() ) { outState = vaShader::State::Uncooked; outErrorString = "Material shader cache not (yet) created"; assert( false ); } m_shaders->GS_Standard->GetState( outState, outErrorString ); } void vaRenderMaterial::GetShaderState_PS_DepthOnly( vaShader::State & outState, string & outErrorString ) { if( !Update() ) { outState = vaShader::State::Uncooked; outErrorString = "Material shader cache not (yet) created"; assert( false ); } m_shaders->PS_DepthOnly->GetState( outState, outErrorString ); } void vaRenderMaterial::GetShaderState_PS_Forward( vaShader::State & outState, string & outErrorString ) { if( !Update() ) { outState = vaShader::State::Uncooked; outErrorString = "Material shader cache not (yet) created"; assert( false ); } m_shaders->PS_Forward->GetState( outState, outErrorString ); } // void vaRenderMaterial::GetShaderState_PS_Deferred( vaShader::State & outState, string & outErrorString ) // { // if( !Update() ) { outState = vaShader::State::Uncooked; outErrorString = "Material shader cache not (yet) created"; assert( false ); } // m_shaders->PS_Deferred->GetState( outState, outErrorString ); // } void vaRenderMaterial::GetShaderState_PS_RichPrepass( vaShader::State & outState, string & outErrorString ) { if( !Update() ) { outState = vaShader::State::Uncooked; outErrorString = "Material shader cache not (yet) created"; assert( false ); } m_shaders->PS_RichPrepass->GetState( outState, outErrorString ); } int vaRenderMaterial::GetCallableShaderTableIndex( ) const { return (m_shaders==nullptr)?(-1):(m_shaders->TableIndex); } bool vaRenderMaterial::PreRenderUpdate( vaRenderDeviceContext & renderContext ) { std::unique_lock uniqueLock(m_mutex); assert( !renderContext.IsWorker() ); // uploading the constant buffer requires the master thread bool shaderConstantsUpdateRequired = false; if( IsDirty() ) { // // release shared lock // sharedLock.unlock(); bool allOk = true; // { // // grab unique // std::unique_lock uniqueLock(m_mutex); // allOk = !IsDirty( ); // if( !allOk ) allOk = Update( ); // } // // reacquire shared lock // sharedLock.lock(); if( !allOk ) { SetDelayedDirty( 0.1 ); // let's wait a short while until this is sorted (texture loaded or whatever) return false; } shaderConstantsUpdateRequired = true; } m_currentShaderConstants.ShaderTableIndex = (m_shaders==nullptr)?(-1):(m_shaders->TableIndex); m_currentShaderConstants.AlphaTestThreshold = m_materialSettings.AlphaTestThreshold; m_currentShaderConstants.VA_RM_LOCALIBL_NORMALBIAS = m_materialSettings.LocalIBLNormalBasedBias; m_currentShaderConstants.VA_RM_LOCALIBL_BIAS = m_materialSettings.LocalIBLBasedBias; m_currentShaderConstants.IndexOfRefraction = m_materialSettings.IndexOfRefraction; m_currentShaderConstants.NEETranslucentAlpha = (m_materialSettings.NEETranslucent)?(m_materialSettings.NEETranslucentAlpha):(1.0f); // Textures might have changed, so doing it after the above pass every time // (frequency could be reduced if too costly but at the moment it has to be done every frame because GetSRVBindlessIndex also transitions the textures to shader readable!!) for( int i = 0; i < m_nodes.size( ); i++ ) { // used to be this: // shared_ptr<const TextureNode> textureNode = std::dynamic_pointer_cast<const TextureNode, const Node>( m_nodes[i] ); // but raw ptr handling below is an order of magnitude faster due to addref/release thread contention issues in heavily multithreaded environment on above const vaRenderMaterial::TextureNode * textureNode = dynamic_cast<const vaRenderMaterial::TextureNode *>( m_nodes[i].get( ) ); if( textureNode != nullptr && textureNode->InUse && textureNode->ComputedShaderTextureSlot != -1 ) { assert( !m_renderMaterialManager.GetTexturingDisabled( ) ); vaFramePtr<vaTexture> texture = textureNode->GetTextureFP( ); if( textureNode->ComputedShaderTextureSlot >= 0 && textureNode->ComputedShaderTextureSlot < countof( ShaderMaterialConstants::BindlessSRVIndices ) && texture != nullptr ) { // !! IMPORTANT !! GetSRVBindlessIndex also transitions the textures to shader readable!! uint32 texSRVBindlessIndex = texture->GetSRVBindlessIndex( &renderContext ); if( m_currentShaderConstants.BindlessSRVIndices[textureNode->ComputedShaderTextureSlot] != texSRVBindlessIndex ) { m_currentShaderConstants.BindlessSRVIndices[textureNode->ComputedShaderTextureSlot] = texSRVBindlessIndex; shaderConstantsUpdateRequired = true; } } else { VA_LOG_ERROR( "vaRenderMaterial::SetToRenderItem - unable to set material texture for unknown reason. This is likely a serious problem and can cause rendering device crash due to bindless texture access." ); assert( false ); SetDelayedDirty( 0.1 ); // let's wait a short while until this is sorted (texture loaded or whatever) } } } if( m_currentShaderConstants.ShaderTableIndex == -1 ) { VA_LOG( "vaRenderMaterial::SetToRenderItem - shader table index not available." ); SetDelayedDirty( 0.1 ); // let's wait a short while until this is sorted (texture loaded or whatever) } // Update GPU constant buffer if required! if( IsDirty() ) return false; else { if( shaderConstantsUpdateRequired ) m_renderMaterialManager.GetGlobalConstantBuffer()->UploadSingle<ShaderMaterialConstants>( renderContext, m_currentShaderConstants, m_globalIndex ); } return true; } bool vaRenderMaterial::SetToRenderData( vaRenderMaterialData & outRenderData, vaDrawResultFlags & inoutDrawResults, vaRenderMaterialShaderType shaderType, std::shared_lock<decltype(vaRenderingModule::m_mutex)> & sharedLock ) { assert( sharedLock.owns_lock( ) && sharedLock.mutex( ) == &m_mutex ); sharedLock; if( IsDirty( ) ) { inoutDrawResults |= vaDrawResultFlags::AssetsStillLoading; return false; } bool retVal = true; outRenderData.CullMode = m_materialSettings.FaceCull; outRenderData.IsTransparent = IsTransparent(); outRenderData.IsWireframe = m_materialSettings.Wireframe; outRenderData.CastShadows = m_materialSettings.CastShadows; outRenderData.VertexShader = GetVS( shaderType ); outRenderData.GeometryShader = GetGS( shaderType ); outRenderData.PixelShader = GetPS( shaderType ); retVal &= outRenderData.VertexShader != nullptr; return retVal; } bool vaRenderMaterial::TextureNode::UIDraw( vaApplicationBase & , vaRenderMaterial & ) { bool inputsChanged = false; string label = vaStringTools::Format( "%s (TextureNode)", Name.c_str( ), Name.c_str( ) ); if( ImGui::CollapsingHeader( label.c_str( ), ImGuiTreeNodeFlags_Framed /*| ImGuiTreeNodeFlags_DefaultOpen*/ ) ) { inputsChanged |= vaAssetPackManager::UIAssetLinkWidget<vaAssetTexture>( "texture_asset", UID ); if( ImGuiEx_Combo( "UV Index", this->UVIndex, {{"0"},{"1"}} ) ) { this->UVIndex = vaMath::Clamp( this->UVIndex, 0, 1 ); inputsChanged = true; } std::vector<string> samplers; for( int i = 0; i < (int)vaStandardSamplerType::MaxValue; i++ ) samplers.push_back( vaStandardSamplerTypeToUIName( (vaStandardSamplerType)i ) ); if( ImGuiEx_Combo( "Sampler", (int32&)this->SamplerType, samplers ) ) { //this->SamplerType = (vaStandardSamplerType)vaMath::Clamp( (int)this->SamplerType, 0, (int)vaStandardSamplerType::MaxValue ); inputsChanged = true; } } else { if( ImGui::IsItemHovered( ) ) { auto texture = GetTextureFP( ); vaAsset * textureAsset = (texture != nullptr)?(texture->GetParentAsset( )):(nullptr); string textureName = ( textureAsset != nullptr ) ? ( textureAsset->Name( ) ) : ( "Link present, asset not found" ); string toolTipText; toolTipText += vaStringTools::Format( "Asset name: %s\n", textureName.c_str( ) ); toolTipText += vaStringTools::Format( "UV index: %d\n", this->UVIndex ); toolTipText += vaStringTools::Format( "Sampler: %s\n", vaStandardSamplerTypeToUIName(this->SamplerType).c_str() ); ImGui::SetTooltip( toolTipText.c_str( ) ); } } return inputsChanged; } bool vaRenderMaterial::InputSlot::UIDraw( vaApplicationBase &, vaRenderMaterial & ownerMaterial ) { assert( Name.length() <= c_materialItemNameMaxLength ); bool inputsChanged = false; const float indentSize = ImGui::GetFontSize( ) / 2; ImGui::PushID(Name.c_str()); string info = Name; info.insert( info.end(), std::max( 0, c_materialItemNameMaxLength - (int)(Name.length()) ) + 1, ' ' ); if( ConnectedInput != "" ) { shared_ptr<const Node> connectedInput = ownerMaterial.FindNode( ConnectedInput ); if( connectedInput ) info += connectedInput->GetUIShortInfo( ); } else { info += this->Properties.GetUIShortInfo( ); } const std::vector<shared_ptr<Node>> & availableInputs = ownerMaterial.GetNodes(); string label = vaStringTools::Format( "%s###InputSlot", info.c_str() ); if( ImGui::CollapsingHeader( label.c_str(), ImGuiTreeNodeFlags_Framed /*| ImGuiTreeNodeFlags_DefaultOpen*/ ) ) { ImGui::Indent( indentSize ); ImGui::Text( "Name: %s", Name.c_str() ); if( ImGui::IsItemHovered( ) ) ImGui::SetTooltip( "This is the shader-visible name, accessed with VA_RM_HAS_INPUT_%s / RenderMaterialInputs::%s", Name.c_str(), Name.c_str() ); string typeName = ValueTypeIndexToHLSL( (ValueTypeIndex)Properties.Default.index() ); ImGui::Text( "Type: %s", typeName.c_str() ); if( ImGui::IsItemHovered( ) ) ImGui::SetTooltip( "This is the type used to read the value from the shaders" ); inputsChanged |= Properties.DrawUI( ); { int currentIndex = 0; std::vector<string> availableInputNames; availableInputNames.push_back("<none>"); for( int i = 0; i < availableInputs.size(); i++ ) { availableInputNames.push_back(availableInputs[i]->GetName()); if( availableInputNames[i+1] == ConnectedInput ) currentIndex = i+1; } if( ImGuiEx_Combo( "Connected Input", currentIndex, availableInputNames ) ) { string newlySelectedInputName = ( currentIndex == 0 )?( "" ):( availableInputNames[currentIndex] ); if( newlySelectedInputName != ConnectedInput ) { ownerMaterial.ConnectInputSlotWithNode( this->Name, newlySelectedInputName, this->InputSwizzle ); inputsChanged = true; } } } shared_ptr<const Node> connectedInput = ownerMaterial.FindNode( ConnectedInput ); string connectedInputName = (connectedInput==nullptr)?"<none>":ConnectedInput; if( connectedInput!=nullptr ) { char inputSwizzleEdit[countof(InputSwizzle)]; memcpy( inputSwizzleEdit, InputSwizzle, sizeof(InputSwizzle) ); if( ImGui::InputText( "Input Swizzle", inputSwizzleEdit, IM_ARRAYSIZE( inputSwizzleEdit ), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_EnterReturnsTrue ) ) { SanitizeSwizzle( inputSwizzleEdit, GetType(), (connectedInput!=nullptr)?(connectedInput->GetType()):(GetType()) ); if( memcmp( inputSwizzleEdit, InputSwizzle, sizeof( InputSwizzle ) ) != 0 ) { memcpy( InputSwizzle, inputSwizzleEdit, sizeof(InputSwizzle) ); inputsChanged = true; } } } ImGui::Unindent( indentSize ); } else { if( ImGui::IsItemHovered( ) ) { string toolTipText; toolTipText += vaStringTools::Format( "Name: %s\n", Name.c_str( ) ); toolTipText += vaStringTools::Format( "Type: %s\n", ValueTypeIndexToHLSL( (ValueTypeIndex)Properties.Default.index( ) ).c_str( ) ); toolTipText += vaStringTools::Format( "Default value: %s\n", Properties.GetUIShortInfo( ).c_str( ) ); string connectedInput = ( ConnectedInput == "" ) ? "<none>" : ConnectedInput; toolTipText += vaStringTools::Format( "Connected input: %s\n", connectedInput.c_str( ) ); toolTipText += vaStringTools::Format( "Input swizzle: %s\n", string(InputSwizzle).c_str() ); ImGui::SetTooltip( toolTipText.c_str() ); } } ImGui::PopID(); return inputsChanged; } bool vaRenderMaterial::UIPropertiesDraw( vaApplicationBase & application ) { assert( GetRenderDevice().IsRenderThread() ); // upgrade to use std::unique_lock lock( m_mutex ) if you need this to change bool hadChanges = false; #ifdef VA_IMGUI_INTEGRATION_ENABLED const float indentSize = ImGui::GetFontSize( ) / 2; if( ImGui::CollapsingHeader( "Import/Export", ImGuiTreeNodeFlags_Framed /*| ImGuiTreeNodeFlags_DefaultOpen*/ ) ) { ImGui::Indent( indentSize ); if( ImGui::Button( "Export to text file" ) ) { string fileName = vaFileTools::SaveFileDialog( "", vaCore::GetExecutableDirectoryNarrow( ), "Vanilla material (.vamat) \0*.vamat\0\0" ); fileName = vaFileTools::FixExtension( fileName, ".vamat" ); vaXMLSerializer serializer; // create serializer for writing GetManager().RegisterSerializationTypeConstructors( serializer ); bool allOk; { vaSerializerScopedOpenChild rootNode( serializer, "Material" ); allOk = rootNode.IsOK( ); if( allOk ) allOk = SerializeUnpacked( serializer, "%there-is-no-folder@" ); } assert( allOk ); if( allOk ) allOk = serializer.WriterSaveToFile( fileName ); assert( allOk ); } ImGui::Separator( ); ImGui::TextColored( { 1.0f, 0.5f, 0.3f, 1.0f }, "Warning, this will completely reset the material" ); if( ImGui::Button( "Import from text file" ) ) { string fileName = vaFileTools::OpenFileDialog( "", vaCore::GetExecutableDirectoryNarrow( ), "Vanilla material (.vamat) \0*.vamat\0\0" ); vaXMLSerializer serializer(fileName); // create serializer for writing GetManager( ).RegisterSerializationTypeConstructors( serializer ); bool allOk; if( (allOk = serializer.IsReading()) == true ) { vaSerializerScopedOpenChild rootNode( serializer, "Material" ); allOk = rootNode.IsOK( ); if( allOk ) allOk = SerializeUnpacked( serializer, "%there-is-no-folder@" ); } assert( allOk ); } ImGui::Unindent( indentSize ); } if( ImGui::CollapsingHeader( "Reset to preset", ImGuiTreeNodeFlags_Framed /*| ImGuiTreeNodeFlags_DefaultOpen*/ ) ) { ImGui::Indent( indentSize ); ImGui::TextColored( { 1.0f, 0.5f, 0.3f, 1.0f }, "Warning, this will completely reset the material" ); auto presets = GetPresetMaterials( ); for( string preset : presets ) { if( ImGui::Button( ( "'" + preset + "'" ).c_str( ), { -1, 0 } ) ) { hadChanges = true; if( SetupFromPreset( preset ) ) VA_LOG_SUCCESS( "Material set up to '%s'", preset.c_str() ); else VA_LOG_ERROR( "Material failed to set up to '%s'", preset.c_str() );; } } ImGui::Unindent( indentSize ); } ImGui::Separator(); bool inputsChanged = false; ImGui::TextColored( ImVec4( 1.0f, 0.7f, 0.7f, 1.0f ), "Input slots:" ); { ImGui::Indent( indentSize ); ImGui::PushStyleVar( ImGuiStyleVar_ItemSpacing, ImVec2( 4, 1 ) ); // Tighten spacing for( int i = 0; i < m_inputSlots.size( ); i++ ) { VA_GENERIC_RAII_SCOPE( ImGui::PushID(m_inputSlots[i].GetName().c_str());, ImGui::PopID(); ); inputsChanged |= m_inputSlots[i].UIDraw( application, *this ); } ImGui::PopStyleVar( ); ImGui::Unindent( indentSize ); } ImGui::Separator( ); ImGui::TextColored( ImVec4( 1.0f, 0.7f, 0.7f, 1.0f ), "Inputs:" ); { ImGui::Indent( indentSize ); ImGui::PushStyleVar( ImGuiStyleVar_ItemSpacing, ImVec2( 4, 1 ) ); // Tighten spacing for( int i = 0; i < m_nodes.size( ); i++ ) { VA_GENERIC_RAII_SCOPE( ImGui::PushID(m_nodes[i]->GetName().c_str());, ImGui::PopID(); ); inputsChanged |= m_nodes[i]->UIDraw( application, *this ); } ImGui::PopStyleVar( ); ImGui::Unindent( indentSize ); } ImGui::Separator( ); // don't dirtify for a second after each change: provides a smoother user experience if( inputsChanged ) SetDelayedDirty( 0.5 ); { ImGui::TextColored( ImVec4( 0.7f, 0.7f, 1.0f, 1.0f ), "Material settings:" ); ImGui::Indent( indentSize ); vaRenderMaterial::MaterialSettings settings = GetMaterialSettings( ); ImGui::Combo( "Culling mode", (int*)& settings.FaceCull, "None\0Front\0Back\0\0" ); ImGui::Combo( "Layer mode", (int*)& settings.LayerMode, "Opaque\0AlphaTest\0Decal\0Transparent\0\0" ); if( settings.LayerMode == vaLayerMode::Decal ) { ImGui::InputInt( " DecalSortOrder", &settings.DecalSortOrder ); settings.DecalSortOrder = vaMath::Clamp( settings.DecalSortOrder, -10000, 10000 ); } else if( settings.LayerMode == vaLayerMode::AlphaTest ) ImGui::InputFloat( " AlphaTestThreshold", &settings.AlphaTestThreshold ); settings.AlphaTestThreshold = vaMath::Clamp( settings.AlphaTestThreshold, 0.0f, 1.0f ); //ImGui::Checkbox( "ReceiveShadows", &settings.ReceiveShadows ); ImGui::Checkbox( "CastShadows", &settings.CastShadows ); ImGui::Checkbox( "Wireframe", &settings.Wireframe ); //ImGui::Checkbox( "AdvancedSpecularShader", &settings.AdvancedSpecularShader ); //ImGui::Checkbox( "SpecialEmissiveLight", &settings.SpecialEmissiveLight ); //ImGui::Checkbox( "NoDepthPrePass", &settings.NoDepthPrePass ); ImGui::InputFloat( "LocalIBLNormalBasedBias", &settings.LocalIBLNormalBasedBias ); ImGui::InputFloat( "LocalIBLBasedBias", &settings.LocalIBLBasedBias ); if( ImGui::Button( "..." ) ) ImGui::OpenPopup("IoRSelectionContextMenu"); ImGui::SameLine( ); ImGui::InputFloat( "IndexOfRefraction", &settings.IndexOfRefraction ); if (ImGui::BeginPopupContextItem("IoRSelectionContextMenu")) { if( ImGui::Selectable("Vacuum: 1.0" ) ) settings.IndexOfRefraction = 1.0f; if( ImGui::Selectable("Air, sea level: 1.00029" ) ) settings.IndexOfRefraction = 1.00029f; if( ImGui::Selectable("Ice: 1.31" ) ) settings.IndexOfRefraction = 1.31f; if( ImGui::Selectable("Water, 20C: 1.333" ) ) settings.IndexOfRefraction = 1.333f; if( ImGui::Selectable("Fused quartz: 1.46" ) ) settings.IndexOfRefraction = 1.46f; if( ImGui::Selectable("Glass: 1.5-1.6" ) ) settings.IndexOfRefraction = 1.55f; if( ImGui::Selectable("Sapphire: 1.77" ) ) settings.IndexOfRefraction = 1.77f; if( ImGui::Selectable("Diamond: 2.42" ) ) settings.IndexOfRefraction = 2.42f; ImGui::EndPopup(); } settings.IndexOfRefraction = std::max( 1.0f, settings.IndexOfRefraction ); ImGui::Checkbox( "NEETranslucent", &settings.NEETranslucent ); if( settings.NEETranslucent ) { ImGui::InputFloat( "NEETranslucentAlpha", &settings.NEETranslucentAlpha ); settings.NEETranslucentAlpha = vaMath::Clamp( settings.NEETranslucentAlpha, 0.0f, 1.0f ); } if( GetMaterialSettings( ) != settings ) { hadChanges = true; SetMaterialSettings( settings ); } ImGui::Unindent( indentSize ); } ImGui::Separator(); { ImGui::TextColored( ImVec4( 0.7f, 0.7f, 1.0f, 1.0f ), "Shader settings:" ); ImGui::Indent( indentSize ); vaRenderMaterial::ShaderSettings shaderSettings = GetShaderSettings( ); ImGui::Text( "Vertex Shader source file & entry point" ); ImGui::Indent( indentSize ); //float clientWidth = ImGui::GetContentRegionAvail( ).x; vaShader::State shaderState; string shaderCompileError; // ImGui::PushItemWidth( -1 ); // //ImGui::InputTextEx( "|###VS_file", &shaderSettings.VS_Standard.first, { clientWidth / 2.0f, 0.0f }, ImGuiInputTextFlags_None ); // ImGui::SetNextItemWidth( clientWidth / 2.0f ); // ImGui::InputText( "|###VS_file", &shaderSettings.VS_Standard.first, ImGuiInputTextFlags_None ); // ImGui::SameLine( ); // //ImGui::InputTextEx( "###VS_entry", &shaderSettings.VS_Standard.second, { clientWidth / 2.0f, 0.0f }, ImGuiInputTextFlags_None ); // ImGui::SetNextItemWidth( clientWidth / 2.0f ); // ImGui::InputText( "###VS_entry", &shaderSettings.VS_Standard.second, ImGuiInputTextFlags_None ); // ImGui::PopItemWidth( ); GetShaderState_VS_Standard( shaderState, shaderCompileError ); ImGui::Text( "Current status: %s, %s", vaShader::StateToString( shaderState ).c_str( ), ( shaderCompileError == "" ) ? ( "OK" ) : ( shaderCompileError.c_str( ) ) ); ImGui::Unindent( indentSize ); if( GetShaderSettings( ) != shaderSettings ) { hadChanges = true; SetShaderSettings( shaderSettings ); } ImGui::Unindent( indentSize ); } #endif // #ifdef VA_IMGUI_INTEGRATION_ENABLED if( hadChanges ) SetSettingsDirty( ); return hadChanges; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // vaRenderMaterialManager /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// vaRenderMaterialManager::vaRenderMaterialManager( const vaRenderingModuleParams & params ) : vaRenderingModule( params ), vaUIPanel( "RenderMaterialManager", 0, false, vaUIPanel::DockLocation::DockedLeftBottom ) { m_isDestructing = false; // m_renderMaterials.SetAddedCallback( std::bind( &vaRenderMaterialManager::RenderMaterialsTrackeeAddedCallback, this, std::placeholders::_1 ) ); // m_renderMaterials.SetBeforeRemovedCallback( std::bind( &vaRenderMaterialManager::RenderMaterialsTrackeeBeforeRemovedCallback, this, std::placeholders::_1, std::placeholders::_2 ) ); // create default material { m_defaultMaterial = CreateRenderMaterial( vaCore::GUIDFromString( L"11523d65-09ea-4342-9bad-8dab7a4dc1e0" ) ); m_defaultMaterial->SetupFromPreset( c_FilamentStandard ); // disable any further modifications m_defaultMaterial->SetImmutable( true ); } // create default for displaying lights (debugging only!) { m_defaultEmissiveLightMaterial = CreateRenderMaterial( vaCore::GUIDFromString( L"11523d65-09ea-4342-9bad-8dab7a4dc1e1" ) ); m_defaultEmissiveLightMaterial->SetupFromPreset( c_FilamentStandard ); // how bright to show the light - no direct physical relationship // this is to make the material shine when it's within the 'Size' area of a light - otherwise it's just black m_defaultEmissiveLightMaterial->SetInputSlot( "EmissiveColor", vaVector3( 1.0f, 1.0f, 1.0f ), true, true ); m_defaultEmissiveLightMaterial->SetInputSlot( "EmissiveIntensity", 1.0f, false, false ); auto settings = m_defaultEmissiveLightMaterial->GetMaterialSettings(); //settings.SpecialEmissiveLight = true; m_defaultEmissiveLightMaterial->SetMaterialSettings(settings); m_defaultEmissiveLightMaterial->SetInputSlot( "BaseColor", vaVector4( 0.0f, 0.0f, 0.0f, 1.0f ), true, true ); m_defaultEmissiveLightMaterial->SetInputSlot( "Roughness", 1.0f, false, false ); m_defaultEmissiveLightMaterial->SetInputSlot( "Metallic", 0.0f, false, false ); m_defaultEmissiveLightMaterial->SetInputSlot( "Reflectance", 0.0f, false, false ); m_defaultEmissiveLightMaterial->SetInputSlot( "AmbientOcclusion", 0.0f, true, false ); // disable any further modifications m_defaultEmissiveLightMaterial->SetImmutable( true ); } m_texturingDisabled = false; // from filament CMakeLists.txt: // set(output_path "${GENERATION_ROOT}/generated/data/dfg.inc") // add_custom_command( // OUTPUT ${output_path} // COMMAND cmgen --quiet --size=${DFG_LUT_SIZE} --ibl-dfg-multiscatter --ibl-dfg-cloth --ibl-dfg=${output_path} // DEPENDS cmgen // COMMENT "Generating DFG LUT ${output_path}" // ) // list(APPEND DATA_BINS ${output_path}) m_DFG_LUT = vaTexture::CreateFromImageFile( GetRenderDevice(), "dfg-multiscatter-cloth.dds" ); m_constantBuffer = vaRenderBuffer::Create<ShaderMaterialConstants>( GetRenderDevice(), m_constantBufferMaxCount, vaRenderBufferFlags::None, "ShaderMaterialConstants" ); } vaRenderMaterialManager::~vaRenderMaterialManager( ) { assert( m_cachedShaders.size() == m_cachedShadersUniqueIDs.size() ); m_isDestructing = true; //m_renderMeshesMap.clear(); m_defaultMaterial = nullptr; m_defaultEmissiveLightMaterial = nullptr; { std::unique_lock managerLock( Mutex() ); for( int i = (int)m_materials.PackedArray().size()-1; i>=0; i-- ) m_materials.At(m_materials.PackedArray()[i])->UIDObject_Untrack(); // this must absolutely be true as they contain direct reference to this object assert( m_materials.Count() == 0 ); } } void vaRenderMaterialManager::SetTexturingDisabled( bool texturingDisabled ) { if( m_texturingDisabled == texturingDisabled ) return; m_texturingDisabled = texturingDisabled; { std::shared_lock managerLock( Mutex() ); for( int i : m_materials.PackedArray() ) m_materials.At(i)->SetInputsDirty(); } } shared_ptr<vaRenderMaterial> vaRenderMaterialManager::CreateRenderMaterial( const vaGUID & uid, bool startTrackingUIDObject ) { std::unique_lock managerLock( Mutex() ); // placed here as it avoids deadlocks with streaming s_constructingFromCreateRenderMaterial = true; // this ensures only this function can create material object auto ret = GetRenderDevice().CreateModule< vaRenderMaterial, vaRenderMaterialConstructorParams>( *this, uid ); s_constructingFromCreateRenderMaterial = false; // this ensures only this function can create material object if( startTrackingUIDObject ) { assert( vaThreading::IsMainThread( ) ); // warning, potential bug - don't automatically start tracking if adding from another thread; rather finish initialization completely and then manually call UIDObject_Track ret->UIDObject_Track(); // needs to be registered to be visible/searchable by various systems such as rendering } return ret; } void vaRenderMaterialManager::UIPanelTick( vaApplicationBase & ) { #ifdef VA_IMGUI_INTEGRATION_ENABLED static int selected = 0; ImGui::BeginChild( "left pane", ImVec2( 150, 0 ), true ); for( int i = 0; i < 7; i++ ) { char label[128]; sprintf_s( label, _countof( label ), "MyObject %d", i ); if( ImGui::Selectable( label, selected == i ) ) selected = i; } ImGui::EndChild( ); ImGui::SameLine( ); // right ImGui::BeginGroup( ); ImGui::BeginChild( "item view", ImVec2( 0, -ImGui::GetFrameHeightWithSpacing( ) ) ); // Leave room for 1 line below us ImGui::Text( "MyObject: %d", selected ); ImGui::Separator( ); ImGui::TextWrapped( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " ); ImGui::EndChild( ); ImGui::BeginChild( "buttons" ); if( ImGui::Button( "Revert" ) ) { } ImGui::SameLine( ); if( ImGui::Button( "Save" ) ) { } ImGui::EndChild( ); ImGui::EndGroup( ); #endif } shared_ptr<vaRenderMaterialCachedShaders> vaRenderMaterialManager::FindOrCreateShaders( bool alphaTest, string materialClass, const vaRenderMaterial::ShaderSettings & _shaderSettings, const std::vector< pair< string, string > > & _shaderMacros ) { vaRenderMaterial::ShaderSettings shaderSettings; if( materialClass != "" ) { assert( std::find( MaterialClasses.begin(), MaterialClasses.end(), materialClass ) != MaterialClasses.end() ); // TODO: make const vaRenderMaterial::ShaderSettings a local thing shaderSettings.BaseMacros = _shaderSettings.BaseMacros; shaderSettings.VS_Standard = { "vaRenderMesh.hlsl", "VS_Standard" }; shaderSettings.GS_Standard = { "", "" }; shaderSettings.PS_RichPrepass = { "Materials/va"+materialClass+".hlsl", "PS_RichPrepass" }; shaderSettings.PS_DepthOnly = { "Materials/va"+materialClass+".hlsl", "PS_DepthOnly" }; shaderSettings.PS_Forward = { "Materials/va"+materialClass+".hlsl", "PS_Forward" }; shaderSettings.CAL_LibraryFile = { "Materials/va"+materialClass+".hlsl" }; } else shaderSettings = _shaderSettings; // old path vaRenderMaterialCachedShaders::Key cacheKey( alphaTest, shaderSettings, _shaderMacros ); std::unique_lock lock( m_cachedShadersMutex ); auto it = m_cachedShaders.find( cacheKey ); // in cache but no longer used by anyone so it was destroyed if( it != m_cachedShaders.end() ) { auto oldItem = it->second.lock(); if( oldItem == nullptr ) { m_cachedShadersUniqueIDs.erase( it->first.UniqueID ); m_cachedShaders.erase( it ); it = m_cachedShaders.end(); } } // also attempt to clear up the table (only from the back - no defrag) while( m_cachedShadersTable.size() > 0 && m_cachedShadersTable.back().lock() == nullptr ) m_cachedShadersTable.pop_back(); // not in cache if( it == m_cachedShaders.end() ) { shared_ptr<vaRenderMaterialCachedShaders> newShaders( new vaRenderMaterialCachedShaders( GetRenderDevice() ) ); // This unique ID is there in only for the case of a special extra shader uint32-based define that uniquely (at runtime) describes // the shader. uint32 uniqueID = (cacheKey.Hash & 0xFFFF); while( !m_cachedShadersUniqueIDs.insert( uniqueID ).second ) uniqueID++; cacheKey.UniqueID = uniqueID; newShaders->UniqueID = uniqueID; newShaders->UniqueIDString = vaStringTools::Format( "%d", uniqueID ); // Enable additional macros m_scratchShaderMacrosStorage = _shaderMacros; std::vector< pair< string, string > > & shaderMacros = m_scratchShaderMacrosStorage; m_scratchShaderMacrosStorage.push_back( std::pair<string, string>( "VA_RM_SHADER_ID", newShaders->UniqueIDString ) ); // vertex input layout is here! std::vector<vaVertexInputElementDesc> inputElements = vaRenderMesh::GetStandardInputLayout( ); if( shaderSettings.VS_Standard.first != "" && shaderSettings.VS_Standard.second != "" ) newShaders->VS_Standard->CompileVSAndILFromFile( shaderSettings.VS_Standard.first, shaderSettings.VS_Standard.second.c_str( ), inputElements, shaderMacros, false ); // else // vaCore::Warning( "Material has no vertex shader!" ); { string gsFile = shaderSettings.GS_Standard.first; string gsEntry = shaderSettings.GS_Standard.second; if( m_globalGSOverrideEnabled ) { gsFile = shaderSettings.VS_Standard.first; gsEntry = "GS_Standard"; } if( gsFile != "" && gsEntry != "" ) newShaders->GS_Standard->CompileFromFile( gsFile, gsEntry.c_str( ), shaderMacros, false ); } if( alphaTest ) { if( shaderSettings.PS_DepthOnly.first != "" && shaderSettings.PS_DepthOnly.second != "" ) newShaders->PS_DepthOnly->CompileFromFile( shaderSettings.PS_DepthOnly.first, shaderSettings.PS_DepthOnly.second.c_str( ), shaderMacros, false ); else VA_ERROR( "Material has no depth only pixel shader but alpha test is used!" ); } else newShaders->PS_DepthOnly->Clear( true ); if( shaderSettings.PS_Forward.first != "" && shaderSettings.PS_Forward.second != "" ) newShaders->PS_Forward->CompileFromFile( shaderSettings.PS_Forward.first, shaderSettings.PS_Forward.second.c_str( ), shaderMacros, false ); // else // vaCore::Warning( "Material has no pixel shader!" ); // if( shaderSettings.PS_Deferred.first != "" && shaderSettings.PS_Deferred.second != "" ) // newShaders->PS_Deferred->CompileFromFile( shaderSettings.PS_Deferred.first, shaderSettings.PS_Deferred.second.c_str( ), shaderMacros, false ); if( shaderSettings.PS_RichPrepass.first != "" && shaderSettings.PS_RichPrepass.second != "" ) newShaders->PS_RichPrepass->CompileFromFile( shaderSettings.PS_RichPrepass.first, shaderSettings.PS_RichPrepass.second.c_str( ), shaderMacros, false ); // ***RAYTRACING ONLY SHADERS BELOW*** - this is a bit of a hack because at the moment CAL_LibraryFile is always raytracing shaderMacros.push_back( std::pair<string, string>( "VA_RAYTRACING", "" ) ); if( shaderSettings.CAL_LibraryFile != "" ) newShaders->CAL_Library->CompileFromFile( shaderSettings.CAL_LibraryFile, "", shaderMacros, false ); // finally, add to cache m_cachedShaders.insert( std::make_pair( cacheKey, newShaders ) ); // and, add to table - first try to find empty slot int emptySlot = -1; for( int i = 0; i < m_cachedShadersTable.size(); i++ ) if( m_cachedShadersTable[i].lock() == nullptr ) emptySlot = i; // if no empty slots, create new if( emptySlot == -1 ) { emptySlot = (int)m_cachedShadersTable.size(); m_cachedShadersTable.push_back({}); } m_cachedShadersTable[emptySlot] = newShaders; newShaders->TableIndex = emptySlot; return newShaders; } else { return it->second.lock(); } } void vaRenderMaterialManager::ResetCaches( ) { { std::shared_lock managerLock( Mutex() ); for( int i : m_materials.PackedArray() ) m_materials.At(i)->SetShadersDirty(); } m_cachedShaders.clear(); m_cachedShadersUniqueIDs.clear(); } void vaRenderMaterialManager::SetGlobalShaderMacros( const std::vector< pair< string, string > > & globalShaderMacros ) { assert( GetRenderDevice().IsRenderThread() ); if( m_globalShaderMacros == globalShaderMacros ) return; m_globalShaderMacros = globalShaderMacros; ResetCaches( ); } void vaRenderMaterialManager::SetGlobalGSOverride( bool enabled ) { assert( GetRenderDevice( ).IsRenderThread( ) ); if( m_globalGSOverrideEnabled == enabled ) return; m_globalGSOverrideEnabled = enabled; ResetCaches( ); } //void vaRenderMaterialManager::SetGlobalDepthPrepassExportsNormals( bool enabled ) //{ // assert( GetRenderDevice( ).IsRenderThread( ) ); // // if( m_globalDepthPrepassExportsNormals == enabled ) // return; // // m_globalDepthPrepassExportsNormals = enabled; // ResetCaches( ); // not actually needed at the moment //} void vaRenderMaterialManager::UpdateAndSetToGlobals( vaRenderDeviceContext & renderContext, vaShaderItemGlobals & shaderItemGlobals, const vaDrawAttributes * drawAttributes ) { // slowly clear shader cache assert( m_cachedShaders.size() == m_cachedShadersUniqueIDs.size() ); if( m_cachedShaders.size() > 0 ) { auto randomIt = std::next( std::begin(m_cachedShaders), vaRandom::Singleton.NextIntRange( 0, (int)m_cachedShaders.size()) ); // in cache but no longer used by anyone so it was destroyed if( randomIt != m_cachedShaders.end() ) { auto oldItem = randomIt->second.lock(); if( oldItem == nullptr ) { m_cachedShadersUniqueIDs.erase( randomIt->first.UniqueID ); m_cachedShaders.erase( randomIt ); randomIt = m_cachedShaders.end(); } } } renderContext; drawAttributes; assert( shaderItemGlobals.ShaderResourceViews[SHADERGLOBAL_MATERIAL_DFG_LOOKUPTABLE_TEXTURESLOT] == nullptr ); shaderItemGlobals.ShaderResourceViews[SHADERGLOBAL_MATERIAL_DFG_LOOKUPTABLE_TEXTURESLOT] = m_DFG_LUT; assert( shaderItemGlobals.ShaderResourceViews[SHADERGLOBAL_MATERIAL_CONSTANTBUFFERS_TEXTURESLOT] == nullptr ); shaderItemGlobals.ShaderResourceViews[SHADERGLOBAL_MATERIAL_CONSTANTBUFFERS_TEXTURESLOT] = m_constantBuffer; } vaRenderMaterial::ValueProperties::ValueProperties( const ValueType& default, bool isMultiplier, bool isColor ) : Default( default ), IsColor( isColor ), IsMultiplier( isMultiplier ) { GetDefaultMinMax( (ValueTypeIndex)default.index(), Min, Max ); } int vaRenderMaterial::ValueProperties::GetComponentCount( ) const { return ValueTypeIndexGetComponentCount( this->GetType() ); } string vaRenderMaterial::ValueProperties::GetUIShortInfo( ) const { string ret; const int decimals = 3; if( IsColor ) { assert( this->Default.index() == (int)ValueTypeIndex::Vector3 || this->Default.index() == (int)ValueTypeIndex::Vector4 ); if( this->Default.index( ) == (int)ValueTypeIndex::Vector3 ) ret = Vector3ToString( vaVector3::LinearToSRGB( std::get<vaVector3>( this->Default ) ), decimals ); else if( this->Default.index( ) == (int)ValueTypeIndex::Vector4 ) ret = Vector4ToString( vaVector4::LinearToSRGB( std::get<vaVector4>( this->Default ) ), decimals ); else ret = "error"; } else { ret = ValueTypeToString( this->Default, decimals ); } ret += " (" + ValueTypeIndexToHLSL( (ValueTypeIndex)this->Default.index() ) + ((IsColor)?(", sRGB)"):(")")); return ret; } bool vaRenderMaterial::ValueProperties::ClampMinMax( ValueType & value ) { ValueType inVal = value; assert( value.index() == Default.index() ); switch( (ValueTypeIndex)value.index() ) { case( ValueTypeIndex::Bool ): if( this->Min == this->Max ) value = this->Min; break; case( ValueTypeIndex::Integer ): value = vaMath::Clamp( std::get<int32>(value), std::get<int32>(Min), std::get<int32>(Max) ); break; case( ValueTypeIndex::Scalar ): value = vaMath::Clamp( std::get<float>(value), std::get<float>(Min), std::get<float>(Max) ); break; case( ValueTypeIndex::Vector3 ): value = vaVector3::Clamp( std::get<vaVector3>(value), std::get<vaVector3>(Min), std::get<vaVector3>(Max) ); break; case( ValueTypeIndex::Vector4 ): value = vaVector4::Clamp( std::get<vaVector4>(value), std::get<vaVector4>(Min), std::get<vaVector4>(Max) ); break; default: assert( false ); break; } return inVal != value; } bool vaRenderMaterial::ValueProperties::DrawUI( ) { bool inputsChanged = false; assert( Default.index() == Min.index() && Default.index() == Max.index() ); const float indentSize = ImGui::GetFontSize( ) / 2; string label = vaStringTools::Format( "Default: %s###DefaultProps", GetUIShortInfo().c_str( ) ); if( ImGui::CollapsingHeader( label.c_str( ), ImGuiTreeNodeFlags_Framed /*| ImGuiTreeNodeFlags_DefaultOpen*/ ) ) { ImGui::Indent( indentSize ); ValueType prevDefault = Default; if( IsColor ) { if( Default.index( ) == (int)ValueTypeIndex::Vector3 ) { vaVector3 color = vaVector3::LinearToSRGB( std::get<vaVector3>( Default ) ); if( ImGui::ColorEdit3( "Default", &color.x, ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR ) ) Default = vaVector3::SRGBToLinear( color ); } else if( Default.index( ) == (int)ValueTypeIndex::Vector4 ) { vaVector4 color = vaVector4::LinearToSRGB( std::get<vaVector4>( Default ) ); if( ImGui::ColorEdit4( "Default", &color.x, ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR ) ) Default = vaVector4::SRGBToLinear( color ); } else { assert( false ); ImGui::Text("error"); } ImGui::Text(" (linear: %s)", ValueTypeToString(Default, 3).c_str() ); } else { switch( (ValueTypeIndex)Default.index() ) { case( ValueTypeIndex::Bool ): { int val = std::get<bool>(Default); ImGui::Combo( "Default", &val, "true\0false\0" ); Default = val != 0; } break; case( ValueTypeIndex::Integer ): { int32 val = std::get<int32>(Default); ImGui::InputInt( "Default", &val ); Default = val; } break; case( ValueTypeIndex::Scalar ): { float val = std::get<float>(Default); ImGui::InputFloat( "Default", &val, 0, 0, "%.3f" ); Default = val; } break; case( ValueTypeIndex::Vector3 ): { vaVector3 val = std::get<vaVector3>(Default); ImGui::InputFloat3( "Default", &val.x, "%.3f" ); Default = val; } break; case( ValueTypeIndex::Vector4 ): { vaVector4 val = std::get<vaVector4>(Default); ImGui::InputFloat4( "Default", &val.x, "%.3f" ); Default = val; } break; default: assert( false ); break; } } inputsChanged |= prevDefault != Default; inputsChanged |= ImGui::Checkbox( "Use Value as multiplier", &IsMultiplier ); if( ImGui::IsItemHovered( ) ) ImGui::SetTooltip( "If set and input node (such as texture) is connected, \nthe Value will be used to multiply it after loading; \notherwise only the input node value is used." ); ImGui::Text( "Min: %s\n", ValueTypeToString( Min, 3 ).c_str( ) ); ImGui::Text( "Max: %s\n", ValueTypeToString( Max, 3 ).c_str( ) ); inputsChanged |= ClampMinMax( Default ); ImGui::Unindent( indentSize ); } else { if( ImGui::IsItemHovered( ) ) { string toolTipText; toolTipText += vaStringTools::Format( "Default: %s\n", ValueTypeToString( Default, 3 ).c_str() ); toolTipText += vaStringTools::Format( "Min: %s\n", ValueTypeToString( Min, 3 ).c_str( ) ); toolTipText += vaStringTools::Format( "Max: %s\n", ValueTypeToString( Max, 3 ).c_str( ) ); const char * isColorTxt = IsColor?"true":"false"; toolTipText += vaStringTools::Format( "IsColor: %s\n", isColorTxt ); ImGui::SetTooltip( toolTipText.c_str( ) ); } } return inputsChanged; } string vaRenderMaterial::Node::GetShaderMaterialInputsType( ) const { return ValueTypeIndexToHLSL( Type ); } vaRenderMaterial::Node::Node( const string& name, const ValueTypeIndex& type ) : Name( name ), Type( type ) { } vaRenderMaterial::TextureNode::TextureNode( const string& name, const vaGUID& textureUID, vaStandardSamplerType samplerType, int uvIndex ) : Node( SanitizeInputSlotOrNodeName( name ), ValueTypeIndex::Vector4 ), UID( textureUID ), SamplerType( samplerType ), UVIndex( uvIndex ) { } vaRenderMaterial::TextureNode::TextureNode( const string& name, const vaTexture& texture, vaStandardSamplerType samplerType, int uvIndex ) : Node( SanitizeInputSlotOrNodeName( name ), ValueTypeIndex::Vector4 ), UID( texture.UIDObject_GetUID( ) ), SamplerType( samplerType ), UVIndex( uvIndex ) { } vaRenderMaterial::TextureNode::TextureNode( const TextureNode& copy ) : Node( SanitizeInputSlotOrNodeName( copy.Name ), ValueTypeIndex::Vector4 ), UID( copy.UID ), SamplerType( copy.SamplerType ), UVIndex( copy.UVIndex ) { } vaRenderMaterial::InputSlot::InputSlot( const InputSlot & copy ) : Name( copy.Name ), Properties( copy.Properties ), ConnectedInput( copy.ConnectedInput ) { memcpy( InputSwizzle, copy.InputSwizzle, sizeof(InputSwizzle) ); } vaRenderMaterial::InputSlot::InputSlot( const string & name, const vaRenderMaterial::ValueProperties & properties ) : Name( SanitizeInputSlotOrNodeName( name ) ), Properties( properties ) { switch( properties.Default.index() ) { case( (int32)vaRenderMaterial::ValueTypeIndex::Bool ): StringToSwizzle( InputSwizzle, "x" ); break; case( (int32)vaRenderMaterial::ValueTypeIndex::Integer ): StringToSwizzle( InputSwizzle, "x" ); break; case( (int32)vaRenderMaterial::ValueTypeIndex::Scalar ): StringToSwizzle( InputSwizzle, "x" ); break; case( (int32)vaRenderMaterial::ValueTypeIndex::Vector3 ): StringToSwizzle( InputSwizzle, "xyz" ); break; case( (int32)vaRenderMaterial::ValueTypeIndex::Vector4 ): StringToSwizzle( InputSwizzle, "xyzw" ); break; default: assert( false ); StringToSwizzle( InputSwizzle, "xyzw" ); break; }; SanitizeSwizzle( InputSwizzle, (ValueTypeIndex)properties.Default.index() ); } string vaRenderMaterial::InputSlot::GetShaderMaterialInputsType( ) const { return ValueTypeIndexToHLSL( ( ValueTypeIndex )Properties.Default.index() ); } string vaRenderMaterial::TextureNode::GetShaderMaterialInputLoader( ) const { // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING // If changing this function to rely on other vaTexture parameters, make sure to follow the same // existing logic as needed for RequiresReUpdate assert( ComputedShaderTextureSlot != -1 ); if( ComputedShaderTextureSlot == -1 ) { assert( false ); return ""; } vaFramePtr<vaTexture> texture = GetTextureFP( ); assert( texture != nullptr ); if( texture == nullptr ) { assert( false ); VA_LOG_ERROR( "vaRenderMaterial::TextureNode::GetShaderMaterialInputLoader - texture slot not unused but texture is null?" ); return "float4(0,0,0,0)"; } string samplerName = vaStandardSamplerTypeToShaderName( this->SamplerType ); string textureBindlessIndex = TextureSlotToHLSLVariableName( this->ComputedShaderTextureSlot ); // // Accessors // string UVAccessor; // switch( this->UVIndex ) // { // case( 0 ): UVAccessor = "Texcoord01.xy"; break; // case( 1 ): UVAccessor = "Texcoord01.zw"; break; // case( 2 ): UVAccessor = "Texcoord23.xy"; break; // case( 3 ): UVAccessor = "Texcoord23.zw"; break; // default: assert( false ); break; // } //string accessorFunction = vaStringTools::Format( "%s.SampleBias( %s, geometrySurface.%s, g_globals.GlobalMIPOffset )", shaderTextureName.c_str( ), samplerName.c_str( ), UVAccessor.c_str( ) ); //string accessorFunction = vaStringTools::Format( "RMSampleTexture2D( %s, %s, geometrySurface.%s )", textureBindlessIndex.c_str( ), samplerName.c_str( ), UVAccessor.c_str( ) ); string accessorFunction = vaStringTools::Format( "RMSampleTexture2D( geometrySurface, %s, %s, %d )", textureBindlessIndex.c_str( ), samplerName.c_str( ), this->UVIndex ); // add normalmap unpacking if needed switch( texture->GetContentsType() ) { case Vanilla::vaTextureContentsType::NormalsXYZ_UNORM: accessorFunction = vaStringTools::Format( "float4( NormalDecode_XYZ_UNORM(%s.xyz) , 0)", accessorFunction.c_str( ) ); break; case Vanilla::vaTextureContentsType::NormalsXY_UNORM: accessorFunction = vaStringTools::Format( "float4( NormalDecode_XY_UNORM(%s.xy) , 0)", accessorFunction.c_str( ) ); break; case Vanilla::vaTextureContentsType::NormalsWY_UNORM: accessorFunction = vaStringTools::Format( "float4( NormalDecode_WY_UNORM(%s.xyzw) , 0)", accessorFunction.c_str( ) ); break; case Vanilla::vaTextureContentsType::NormalsXY_LAEA_ENCODED: accessorFunction = vaStringTools::Format( "float4( NormalDecode_XY_LAEA(%s.xy) , 0)", accessorFunction.c_str( ) ); break; } LastTextureContentsType = texture->GetContentsType(); return accessorFunction; } bool vaRenderMaterial::ValueProperties::Serialize( vaXMLSerializer & serializer ) { bool allOk = true; if( !::Serialize( serializer, "Value", this->Default ) ) allOk &= ::Serialize( serializer, "Default", this->Default ); allOk &= ::Serialize( serializer, "Min", this->Min ); allOk &= ::Serialize( serializer, "Max", this->Max ); allOk &= serializer.Serialize<bool>( "IsColor", this->IsColor ); /*allOk &=*/ serializer.Serialize<bool>( "ValueIsMultiplier", this->IsMultiplier, false ); assert( allOk ); return allOk; } bool vaRenderMaterial::Node::Serialize( vaXMLSerializer& serializer ) { bool allOk = true; allOk = serializer.Serialize<string>( "Name", this->Name ); allOk = serializer.Serialize<int32>( "Type", (int32&)this->Type ); if( serializer.IsReading( ) ) { this->InUse = false; } return allOk; } bool vaRenderMaterial::TextureNode::Serialize( vaXMLSerializer& serializer ) { bool allOk = Node::Serialize( serializer ); allOk = serializer.Serialize<vaGUID>( "UID", UID, vaGUID::Null ); allOk = serializer.Serialize<int32>( "UVIndex", UVIndex ); allOk = serializer.Serialize<int32>( "SamplerType", (int32&)SamplerType ); if( serializer.IsReading( ) ) { this->ComputedShaderTextureSlot = -1; } return allOk; } bool vaRenderMaterial::InputSlot::Serialize( vaXMLSerializer& serializer ) { bool allOk = true; allOk &= serializer.Serialize( "Name", Name ); assert( allOk ); allOk &= serializer.Serialize( "ConnectedInput", ConnectedInput ); assert( allOk ); allOk &= serializer.Serialize( "Properties", Properties ); assert( allOk ); string inputSwizzle = ""; if( serializer.IsWriting() ) inputSwizzle = SwizzleToString( InputSwizzle ); allOk &= serializer.Serialize( "InputSwizzle", inputSwizzle ); assert( allOk ); if( serializer.IsReading( ) ) { StringToSwizzle( InputSwizzle, inputSwizzle ); //let's not sanitize here since we don't know the source type in case source nodes have not been loaded yet //SanitizeSwizzle( InputSwizzle, (ValueTypeIndex)Properties.Default.index() ); } if( serializer.IsReading() ) { CachedConnectedInput.reset(); assert( IsValidSwizzle(InputSwizzle) ); assert( Name == SanitizeInputSlotOrNodeName(Name) ); } assert( allOk ); return allOk; } void vaRenderMaterial::EnumerateUsedAssets( const std::function<void( vaAsset * asset )> & callback ) { callback( GetParentAsset() ); for( int i = 0; i < m_nodes.size( ); i++ ) { auto snode = std::dynamic_pointer_cast<TextureNode, Node>( m_nodes[i] ); if( snode != nullptr && !snode->GetTextureUID( ).IsNull() ) { auto texture = snode->GetTextureFP( ); if( texture != nullptr ) { callback( texture->GetParentAsset() ); } else { // Either ReconnectDependencies( ) was not called, or the asset is missing? assert( false ); } } } } vaShadingRate vaRenderMaterial::ComputeShadingRate( int baseShadingRate ) const { baseShadingRate; // baseShadingRate += m_materialSettings.VRSRateOffset; // baseShadingRate = vaMath::Clamp( baseShadingRate, 0, 4 ); // switch( baseShadingRate ) // { // case( 0 ): return vaShadingRate::ShadingRate1X1; // case( 1 ): return ( m_materialSettings.VRSPreferHorizontal ) ? ( vaShadingRate::ShadingRate2X1 ) : ( vaShadingRate::ShadingRate1X2 ); // case( 2 ): return vaShadingRate::ShadingRate2X2; // case( 3 ): return ( m_materialSettings.VRSPreferHorizontal ) ? ( vaShadingRate::ShadingRate4X2 ) : ( vaShadingRate::ShadingRate2X4 ); // case( 4 ): return vaShadingRate::ShadingRate4X4; // default: assert( false ); // break; // } return vaShadingRate::ShadingRate1X1; } void vaRenderMaterialManager::RegisterSerializationTypeConstructors( vaXMLSerializer & serializer ) { serializer.RegisterTypeConstructor( "TextureNode", [] { return std::make_shared<vaRenderMaterial::TextureNode>(); } ); }
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/python/local_computation_builder.h" #include <memory> #include <string> #include <vector> #include "absl/memory/memory.h" #include "tensorflow/compiler/xla/client/client_library.h" #include "tensorflow/compiler/xla/client/lib/math.h" #include "tensorflow/compiler/xla/client/lib/qr.h" #include "tensorflow/compiler/xla/client/lib/self_adjoint_eig.h" #include "tensorflow/compiler/xla/client/lib/svd.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/client/xla_computation.h" #include "tensorflow/compiler/xla/executable_run_options.h" #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/compiler/xla/literal_util.h" #include "tensorflow/compiler/xla/service/computation_placer.h" #include "tensorflow/compiler/xla/service/cpu/custom_call_target_registry.h" #include "tensorflow/compiler/xla/service/hlo_graph_dumper.h" #include "tensorflow/compiler/xla/service/platform_util.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/platform/thread_annotations.h" #include "tensorflow/core/platform/types.h" namespace xla { namespace swig { Status RegisterCpuCustomCallTarget(const string& fn_name, PyObject* capsule) { const char* name = "xla._CPU_CUSTOM_CALL_TARGET"; if (!PyCapsule_IsValid(capsule, name)) { return InvalidArgument( "Argument to RegisterCpuCustomCallTargetRegistry was not a " "xla._CPU_CUSTOM_CALL_TARGET capsule."); } void* fn_ptr = PyCapsule_GetPointer(capsule, name); CHECK(fn_ptr != nullptr); cpu::CustomCallTargetRegistry::Global()->Register( std::string(fn_name.begin(), fn_name.end()), fn_ptr); return Status::OK(); } LocalClient::LocalClient(xla::LocalClient* client) : client_(client) {} /* static */ StatusOr<LocalClient> LocalClient::Get( const string& platform_name) { TF_ASSIGN_OR_RETURN(se::Platform * platform, PlatformUtil::GetPlatform(platform_name)); if (platform->VisibleDeviceCount() <= 0) { return InvalidArgument("Platform %s has no visible devices.", platform_name); } LocalClientOptions options; options.set_platform(platform); TF_ASSIGN_OR_RETURN(xla::LocalClient * client, ClientLibrary::GetOrCreateLocalClient(options)); CHECK(client != nullptr); return LocalClient(client); } // Returns the number of devices known to the XLA client. int LocalClient::DeviceCount() const { return client_->device_count(); } Status LocalClient::TransferToInfeed(const Literal& literal, int device_ordinal) { VLOG(1) << "Infeeding literal to device " << device_ordinal << "; shape: " << literal.shape(); return client_->TransferToInfeed(literal, device_ordinal); } StatusOr<Literal> LocalClient::TransferFromOutfeed(const Shape& shape, int device_ordinal) { VLOG(1) << "Outfeeding literal from device " << device_ordinal << "; shape: " << shape; return client_->TransferFromOutfeed(&shape, device_ordinal); } /* static */ StatusOr<LocalShapedBuffer*> LocalShapedBuffer::FromLiteral( const Literal& argument, const absl::optional<Shape>& shape_with_layout, const LocalClient& client, int device_ordinal) { VLOG(1) << "Creating shaped buffer from literal on device ordinal: " << device_ordinal; auto literal_to_buffer = [&](const Literal& arg) { return client.client()->LiteralToShapedBuffer( arg, device_ordinal, client.client()->backend().memory_allocator()); }; StatusOr<ScopedShapedBuffer> buf = [&] { if (shape_with_layout) { Literal relaid = argument.Relayout(shape_with_layout.value()); return literal_to_buffer(relaid); } return literal_to_buffer(argument); }(); TF_RETURN_IF_ERROR(buf.status()); return new LocalShapedBuffer(std::move(buf).ValueOrDie(), client.client()); } LocalShapedBuffer::LocalShapedBuffer(ScopedShapedBuffer shaped_buffer, xla::LocalClient* client) : shaped_buffer_(std::move(shaped_buffer)), client_(client) {} const ScopedShapedBuffer* LocalShapedBuffer::shaped_buffer() const { return &shaped_buffer_; } ShapedBuffer LocalShapedBuffer::Release() { return shaped_buffer_.release(); } const Shape& LocalShapedBuffer::shape() const { return shaped_buffer()->on_device_shape(); } StatusOr<Literal> LocalShapedBuffer::ToLiteral() const { return client_->ShapedBufferToLiteral(*shaped_buffer()); } LocalShapedBufferTuple::LocalShapedBufferTuple( std::vector<LocalShapedBuffer*> elements) : elements_(std::move(elements)) { for (auto* element : elements_) { CHECK(element != nullptr); } } LocalShapedBufferTuple::~LocalShapedBufferTuple() { for (LocalShapedBuffer* element : elements_) { if (element != nullptr) { delete element; } } } StatusOr<LocalShapedBuffer*> LocalShapedBufferTuple::Release(int i) { LocalShapedBuffer* element = elements_[i]; if (element == nullptr) { return InvalidArgument("Attempted to release already-released element %d.", i); } elements_[i] = nullptr; return element; } int64 LocalShapedBufferTuple::size() const { return elements_.size(); } StatusOr<LocalShapedBufferTuple*> LocalShapedBuffer::DestructureTuple() { const Shape tuple_shape = shape(); if (!tuple_shape.IsTuple()) { return InvalidArgument( "Attemped to destructure a LocalShapedBuffer that did not have a tuple " "shape; shape: %s", ShapeUtil::HumanString(tuple_shape)); } DeviceMemoryAllocator* allocator = shaped_buffer()->memory_allocator(); ShapedBuffer tuple_buffer = Release(); // Extract some metadata we use to construct scoped buffers. const se::Platform* platform = tuple_buffer.platform(); int device_ordinal = tuple_buffer.device_ordinal(); ShapeTree<se::DeviceMemoryBase>& shape_tree = tuple_buffer.buffers(); std::vector<LocalShapedBuffer*> results; for (int64 i = 0; i < ShapeUtil::TupleElementCount(tuple_shape); ++i) { // Create a shaped buffer for this destructured tuple element. const Shape& subshape = ShapeUtil::GetSubshape(tuple_shape, {i}); VLOG(3) << "Starting tuple element " << i << " subshape: " << subshape; ShapedBuffer shaped_buffer(subshape, subshape, platform, device_ordinal); ShapeUtil::ForEachSubshape( subshape, [&](const Shape& s, const ShapeIndex& index) { ShapeIndex original(index); original.push_front(i); se::DeviceMemoryBase* device_memory = shape_tree.mutable_element(original); shaped_buffer.set_buffer(*device_memory, index); *device_memory = se::DeviceMemoryBase(); }); VLOG(3) << "Completed tuple element: " << i; results.push_back(new LocalShapedBuffer( ScopedShapedBuffer(std::move(shaped_buffer), allocator), client_)); } // Deallocate the root buffer. se::DeviceMemoryBase root_buffer = tuple_buffer.root_buffer(); TF_RETURN_IF_ERROR(allocator->Deallocate(device_ordinal, root_buffer)); return new LocalShapedBufferTuple(std::move(results)); } LocalExecutable::LocalExecutable( std::unique_ptr<xla::LocalExecutable> executable, xla::DeviceAssignment device_assignment, xla::LocalClient* client) : executable_(std::move(executable)), device_assignment_(std::move(device_assignment)), client_(client) {} std::vector<int> LocalExecutable::DeviceOrdinals() const { int num_replicas = device_assignment_.replica_count(); std::vector<int> device_ordinals; device_ordinals.reserve(num_replicas); for (int i = 0; i < num_replicas; ++i) { device_ordinals.push_back(device_assignment_(i, 0)); } return device_ordinals; } StatusOr<LocalShapedBuffer*> LocalExecutable::Execute( absl::Span<LocalShapedBuffer* const> argument_handles) { if (num_replicas() != 1) { return InvalidArgument( "Attempted to execute computation with %d replicas using Execute()", num_replicas()); } StatusOr<ScopedShapedBuffer> result_buffer_status; const int device_ordinal = device_assignment_(0, 0); VLOG(3) << "Replica 0 mapped to device ordinal for execution: " << device_ordinal; std::vector<const ShapedBuffer*> argument_buffers; argument_buffers.reserve(argument_handles.size()); for (auto& handle : argument_handles) { argument_buffers.push_back(handle->shaped_buffer()); } ExecutableRunOptions options; options.set_device_ordinal(device_ordinal); options.set_allocator(client_->backend().memory_allocator()); options.set_intra_op_thread_pool( client_->backend().eigen_intra_op_thread_pool_device()); options.set_device_assignment(&device_assignment_); result_buffer_status = executable_->Run(argument_buffers, options); if (!result_buffer_status.ok()) { return InternalError( "Failed running replica 0 (other replicas may have failed as well): " "%s.", result_buffer_status.status().ToString()); } return new LocalShapedBuffer(std::move(result_buffer_status).ValueOrDie(), client_); } StatusOr<LocalShapedBufferTuple*> LocalExecutable::ExecutePerReplica( absl::Span<const std::vector<LocalShapedBuffer*>> argument_handles) { const int num_devices = client_->device_count(); if (argument_handles.size() != num_replicas()) { return InvalidArgument( "Attempted to execute with %d replicas when replica count is %d", argument_handles.size(), num_devices); } if (argument_handles.size() > num_devices) { return InvalidArgument( "Attempted to execute with %d replicas when device count is %d", argument_handles.size(), num_devices); } VLOG(1) << "Executing with " << num_replicas() << " replicas."; std::vector<StatusOr<ScopedShapedBuffer>> results(num_replicas()); auto execute = [this, &argument_handles, &results](int replica) { const int device_ordinal = device_assignment_(replica, 0); VLOG(3) << "Replica " << replica << " mapped to device ordinal for execution: " << device_ordinal; std::vector<const ShapedBuffer*> argument_buffers; argument_buffers.reserve(argument_handles[replica].size()); for (auto& handle : argument_handles[replica]) { argument_buffers.push_back(handle->shaped_buffer()); } ExecutableRunOptions options; options.set_device_ordinal(device_ordinal); options.set_allocator(client_->backend().memory_allocator()); options.set_intra_op_thread_pool( client_->backend().eigen_intra_op_thread_pool_device()); options.set_device_assignment(&device_assignment_); StatusOr<ScopedShapedBuffer> result_buffer_status = executable_->Run(argument_buffers, options); results[replica] = std::move(result_buffer_status); }; if (num_replicas() == 1) { // Fast-path if there is only one replica — run the computation on the // current thread. execute(0); } else { // TODO(phawkins): don't recreate the threadpool for each execution. tensorflow::thread::ThreadPool pool(tensorflow::Env::Default(), "xlarun", num_replicas() - 1); for (int replica = 0; replica < num_replicas() - 1; ++replica) { pool.Schedule([&execute, replica] { execute(replica); }); } execute(num_replicas() - 1); } std::vector<LocalShapedBuffer*> wrapped_results(num_replicas()); for (int replica = 0; replica < num_replicas(); ++replica) { auto& statusor = results[replica]; if (!statusor.ok()) { return InternalError( "Failed running replica %d (other replicas may have failed as well): " "%s.", replica, statusor.status().ToString()); } wrapped_results[replica] = new LocalShapedBuffer(std::move(statusor).ValueOrDie(), client_); } return new LocalShapedBufferTuple(std::move(wrapped_results)); } Computation::Computation(XlaComputation computation) : computation_(std::move(computation)) {} StatusOr<LocalExecutable*> Computation::Compile( const std::vector<Shape>& argument_shapes, const ExecutableBuildOptions* build_options, const LocalClient& client) { std::vector<const Shape*> argument_shape_pointers; argument_shape_pointers.reserve(argument_shapes.size()); for (auto& argument_shape : argument_shapes) { argument_shape_pointers.push_back(&argument_shape); } ExecutableBuildOptions options; if (build_options != nullptr) { options = *build_options; } TF_ASSIGN_OR_RETURN( auto local_executable, client.client()->Compile(computation_, argument_shape_pointers, options)); TF_ASSIGN_OR_RETURN( DeviceAssignment device_assignment, client.client()->backend().computation_placer()->AssignDevices( options.num_replicas(), /*computation_count=*/1)); return new LocalExecutable(std::move(local_executable), std::move(device_assignment), client.client()); } const XlaComputation& Computation::computation() const { return computation_; } string Computation::GetSerializedProto() const { string result; if (!computation_.proto().SerializeToString(&result)) { LOG(ERROR) << "Failed to serialize the HloModuleProto."; return ""; } return result; } StatusOr<string> Computation::GetHloText() const { TF_ASSIGN_OR_RETURN(const HloModuleConfig module_config, HloModule::CreateModuleConfigFromProto( computation_.proto(), GetDebugOptionsFromFlags())); TF_ASSIGN_OR_RETURN( std::unique_ptr<HloModule> hlo_module, HloModule::CreateFromProto(computation_.proto(), module_config)); HloPrintOptions options; options = HloPrintOptions::ShortParsable(); options.set_print_large_constants(false); return hlo_module->ToString(options); } StatusOr<string> Computation::GetHloDotGraph() const { TF_ASSIGN_OR_RETURN(const HloModuleConfig module_config, HloModule::CreateModuleConfigFromProto( computation_.proto(), GetDebugOptionsFromFlags())); TF_ASSIGN_OR_RETURN( std::unique_ptr<HloModule> hlo_module, HloModule::CreateFromProto(computation_.proto(), module_config)); return RenderGraph(*hlo_module->entry_computation(), /*label=*/"", hlo_module->config().debug_options(), RenderedGraphFormat::kDot); } StatusOr<ProgramShape> Computation::GetProgramShape() const { return computation_.GetProgramShape(); } StatusOr<Shape> Computation::GetReturnValueShape() const { TF_ASSIGN_OR_RETURN(ProgramShape shape, computation_.GetProgramShape()); return std::move(*shape.mutable_result()); } LocalOp::LocalOp(const XlaOp& op) : op_(op) {} const XlaOp& LocalOp::op() const { return op_; } ComputationBuilder::ComputationBuilder(const string& computation_name) : builder_(computation_name) {} void ComputationBuilder::SetOpMetadata(const OpMetadata& metadata) { builder_.SetOpMetadata(metadata); } void ComputationBuilder::ClearOpMetadata() { builder_.ClearOpMetadata(); } StatusOr<Computation*> ComputationBuilder::Build() { TF_ASSIGN_OR_RETURN(XlaComputation computation, builder_.Build()); return new Computation(std::move(computation)); } LocalOp ComputationBuilder::Parameter(int64 parameter_number, const Shape& shape, const string& name) { return xla::Parameter(&builder_, parameter_number, shape, name); } StatusOr<Computation*> ComputationBuilder::BuildWithRoot(const LocalOp& root) { TF_ASSIGN_OR_RETURN(XlaComputation computation, builder_.Build(root.op())); return new Computation(std::move(computation)); } StatusOr<Shape> ComputationBuilder::GetShape(const LocalOp& operand) { return builder_.GetShape(operand.op()); } StatusOr<Shape> ComputationBuilder::GetReturnValueShape() { TF_ASSIGN_OR_RETURN(ProgramShape program_shape, builder_.GetProgramShape()); return program_shape.result(); } LocalOp ComputationBuilder::ReplicaId() { return xla::ReplicaId(&builder_); } LocalOp ComputationBuilder::Infeed(const Shape& shape) { return xla::Infeed(&builder_, shape); } void ComputationBuilder::Outfeed(const LocalOp& operand, const Shape& shape, const string& outfeed_config) { xla::Outfeed(operand.op(), shape, outfeed_config); } LocalOp ComputationBuilder::ConstantLiteral(const Literal& literal) { return xla::ConstantLiteral(&builder_, literal); } LocalOp ComputationBuilder::Iota(PrimitiveType element_type, int64 size) { return xla::Iota(&builder_, element_type, size); } LocalOp ComputationBuilder::BroadcastedIota(const Shape& shape, int64 dimension) { return xla::Iota(&builder_, shape, dimension); } LocalOp ComputationBuilder::Broadcast(const LocalOp& operand, absl::Span<const int64> broadcast_sizes) { return xla::Broadcast(operand.op(), broadcast_sizes); } LocalOp ComputationBuilder::BroadcastInDim( const LocalOp& operand, absl::Span<const int64> out_dim_sizes, absl::Span<const int64> broadcast_dimensions) { return xla::BroadcastInDim(operand.op(), out_dim_sizes, broadcast_dimensions); } LocalOp ComputationBuilder::Pad(const LocalOp& operand, const LocalOp& padding_value, const PaddingConfig& padding_config) { return xla::Pad(operand.op(), padding_value.op(), padding_config); } LocalOp ComputationBuilder::Reshape(const LocalOp& operand, absl::Span<const int64> dimensions, absl::Span<const int64> new_sizes) { return xla::Reshape(operand.op(), dimensions, new_sizes); } LocalOp ComputationBuilder::Collapse(const LocalOp& operand, absl::Span<const int64> dimensions) { return xla::Collapse(operand.op(), dimensions); } LocalOp ComputationBuilder::AllToAll( const LocalOp& operand, int64 split_dimension, int64 concat_dimension, int64 split_count, absl::Span<const ReplicaGroup> replica_groups) { std::vector<ReplicaGroup> rg; rg.reserve(replica_groups.size()); for (int i = 0; i < replica_groups.size(); ++i) { rg.push_back(replica_groups[i]); } return xla::AllToAll(operand.op(), split_dimension, concat_dimension, split_count, rg); } LocalOp ComputationBuilder::CrossReplicaSum( const LocalOp& operand, absl::Span<const ReplicaGroup> replica_groups) { return xla::CrossReplicaSum(operand.op(), replica_groups); } LocalOp ComputationBuilder::Slice(const LocalOp& operand, absl::Span<const int64> start_indices, absl::Span<const int64> limit_indices, absl::Span<const int64> strides) { return xla::Slice(operand.op(), start_indices, limit_indices, strides); } LocalOp ComputationBuilder::SliceInDim(const LocalOp& operand, int64 start_index, int64 limit_index, int64 stride, int64 dimno) { return xla::SliceInDim(operand.op(), start_index, limit_index, stride, dimno); } LocalOp ComputationBuilder::DynamicSlice(const LocalOp& operand, const LocalOp& start_indices, absl::Span<const int64> slice_sizes) { return xla::DynamicSlice(operand.op(), start_indices.op(), slice_sizes); } LocalOp ComputationBuilder::DynamicUpdateSlice(const LocalOp& operand, const LocalOp& update, const LocalOp& start_indices) { return xla::DynamicUpdateSlice(operand.op(), update.op(), start_indices.op()); } LocalOp ComputationBuilder::ConcatInDim(absl::Span<const LocalOp> operands, int64 dimension) { std::vector<XlaOp> xla_ops; xla_ops.reserve(operands.size()); for (const auto& op : operands) { xla_ops.push_back(op.op()); } return xla::ConcatInDim(&builder_, xla_ops, dimension); } LocalOp ComputationBuilder::SelectAndScatterWithGeneralPadding( const LocalOp& operand, const Computation& select, absl::Span<const int64> window_dimensions, absl::Span<const int64> window_strides, absl::Span<const std::pair<int64, int64>> padding, const LocalOp& source, const LocalOp& init_value, const Computation& scatter) { return xla::SelectAndScatterWithGeneralPadding( operand.op(), select.computation(), window_dimensions, window_strides, padding, source.op(), init_value.op(), scatter.computation()); } LocalOp ComputationBuilder::Tuple(absl::Span<const LocalOp> elements) { std::vector<XlaOp> xla_ops; xla_ops.reserve(elements.size()); for (const auto& op : elements) { xla_ops.push_back(op.op()); } return xla::Tuple(&builder_, xla_ops); } LocalOp ComputationBuilder::GetTupleElement(const LocalOp& tuple_data, int64 index) { return xla::GetTupleElement(tuple_data.op(), index); } LocalOp ComputationBuilder::Dot(const LocalOp& lhs, const LocalOp& rhs) { return xla::Dot(lhs.op(), rhs.op()); } LocalOp ComputationBuilder::DotGeneral( const LocalOp& lhs, const LocalOp& rhs, const DotDimensionNumbers& dimension_numbers) { return xla::DotGeneral(lhs.op(), rhs.op(), dimension_numbers); } LocalOp ComputationBuilder::ConvGeneralDilated( const LocalOp& lhs, const LocalOp& rhs, absl::Span<const int64> window_strides, absl::Span<const std::pair<int64, int64>> padding, absl::Span<const int64> lhs_dilation, absl::Span<const int64> rhs_dilation, const ConvolutionDimensionNumbers& dimension_numbers, int64 feature_group_count) { return xla::ConvGeneralDilated(lhs.op(), rhs.op(), window_strides, padding, lhs_dilation, rhs_dilation, dimension_numbers, feature_group_count); } LocalOp ComputationBuilder::ConvertElementType(const LocalOp& operand, PrimitiveType new_element_type) { return xla::ConvertElementType(operand.op(), new_element_type); } LocalOp ComputationBuilder::BitcastConvertType(const LocalOp& operand, PrimitiveType new_element_type) { return xla::BitcastConvertType(operand.op(), new_element_type); } LocalOp ComputationBuilder::Call(const Computation& local_computation, absl::Span<const LocalOp> operands) { std::vector<XlaOp> xla_ops; xla_ops.reserve(operands.size()); for (const auto& op : operands) { xla_ops.push_back(op.op()); } return xla::Call(&builder_, local_computation.computation(), xla_ops); } LocalOp ComputationBuilder::CustomCall( const string& call_target_name, absl::Span<const LocalOp> operands, const Shape& shape_with_layout, const std::vector<Shape>& operand_shapes_with_layout, const string& opaque) { std::vector<XlaOp> xla_ops; xla_ops.reserve(operands.size()); for (const auto& op : operands) { xla_ops.push_back(op.op()); } return xla::CustomCallWithLayout(&builder_, call_target_name, xla_ops, shape_with_layout, operand_shapes_with_layout, opaque); } LocalOp ComputationBuilder::Transpose(const LocalOp& operand, absl::Span<const int64> permutation) { return xla::Transpose(operand.op(), permutation); } LocalOp ComputationBuilder::Rev(const LocalOp& operand, absl::Span<const int64> dimensions) { return xla::Rev(operand.op(), dimensions); } LocalOp ComputationBuilder::Map(absl::Span<const LocalOp> operands, const Computation& local_computation, absl::Span<const int64> dimensions) { std::vector<XlaOp> xla_ops; xla_ops.reserve(operands.size()); for (const auto& op : operands) { xla_ops.push_back(op.op()); } return xla::Map(&builder_, xla_ops, local_computation.computation(), dimensions); } LocalOp ComputationBuilder::Reduce( const LocalOp& operand, const LocalOp& init_value, const Computation& local_computation, absl::Span<const int64> dimensions_to_reduce) { return xla::Reduce(operand.op(), init_value.op(), local_computation.computation(), dimensions_to_reduce); } LocalOp ComputationBuilder::ReduceWindowWithGeneralPadding( const LocalOp& operand, const LocalOp& init_value, const Computation& local_computation, absl::Span<const int64> window_dimensions, absl::Span<const int64> window_strides, absl::Span<const int64> base_dilations, absl::Span<const int64> window_dilations, absl::Span<const std::pair<int64, int64>> padding) { return xla::ReduceWindowWithGeneralPadding( operand.op(), init_value.op(), local_computation.computation(), window_dimensions, window_strides, base_dilations, window_dilations, padding); } LocalOp ComputationBuilder::RngNormal(const LocalOp& mu, const LocalOp& sigma, const Shape& shape) { return xla::RngNormal(mu.op(), sigma.op(), shape); } LocalOp ComputationBuilder::RngUniform(const LocalOp& a, const LocalOp& b, const Shape& shape) { return xla::RngUniform(a.op(), b.op(), shape); } LocalOp ComputationBuilder::While(const Computation& condition, const Computation& body, const LocalOp& init) { return xla::While(condition.computation(), body.computation(), init.op()); } LocalOp ComputationBuilder::Conditional(const LocalOp& predicate, const LocalOp& true_operand, const Computation& true_computation, const LocalOp& false_operand, const Computation& false_computation) { return xla::Conditional(predicate.op(), true_operand.op(), true_computation.computation(), false_operand.op(), false_computation.computation()); } StatusOr<bool> ComputationBuilder::IsConstant(const LocalOp& operand) { return builder_.IsConstant(operand.op()); } LocalOp ComputationBuilder::Sort(const LocalOp& operand, int64 dimension) { return xla::Sort(operand.op(), {}, dimension); } LocalOp ComputationBuilder::SortKeyVal(const LocalOp& keys, const LocalOp& values, int64 dimension) { return xla::Sort(keys.op(), {values.op()}, dimension); } LocalOp ComputationBuilder::Cholesky(const LocalOp& a, bool lower) { return xla::Cholesky(a.op(), lower); } LocalOp ComputationBuilder::QR(const LocalOp& a, bool full_matrices) { XlaBuilder* builder = a.op().builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { TF_ASSIGN_OR_RETURN(auto qr, xla::QRDecomposition(a.op(), full_matrices)); return xla::Tuple(builder, {qr.q, qr.r}); }); } LocalOp ComputationBuilder::Eigh(const LocalOp& a, bool lower) { XlaBuilder* builder = a.op().builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { auto eigh = xla::SelfAdjointEig(a.op(), lower); return xla::Tuple(builder, {eigh.v, eigh.w}); }); } LocalOp ComputationBuilder::SVD(const LocalOp& a) { XlaBuilder* builder = a.op().builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { auto svd = xla::SVD(a.op()); return xla::Tuple(builder, {svd.u, svd.d, svd.v}); }); } LocalOp ComputationBuilder::TriangularSolve(const LocalOp& a, const LocalOp& b, bool left_side, bool lower, bool unit_diagonal, int transpose_a) { return xla::TriangularSolve( a.op(), b.op(), left_side, lower, unit_diagonal, xla::TriangularSolveOptions::Transpose(transpose_a)); } LocalOp ComputationBuilder::Gather( const LocalOp& input, const LocalOp& start_indices, const GatherDimensionNumbers& dimension_numbers, absl::Span<const int64> slice_sizes) { return xla::Gather(input.op(), start_indices.op(), dimension_numbers, slice_sizes); } LocalOp ComputationBuilder::Scatter( const LocalOp& input, const LocalOp& scatter_indices, const LocalOp& updates, const Computation& update_computation, const ScatterDimensionNumbers& dimension_numbers) { return xla::Scatter(input.op(), scatter_indices.op(), updates.op(), update_computation.computation(), dimension_numbers); } StatusOr<Computation*> ComputationBuilder::BuildConstantSubGraph( const LocalOp& operand) { TF_ASSIGN_OR_RETURN(XlaComputation computation, builder_.BuildConstantSubGraph(operand.op())); return new Computation(std::move(computation)); } #define _FORWARD(method_name, return_sig, args_sig, args) \ return_sig ComputationBuilder::method_name args_sig { \ return xla::method_name args; \ } #define _FORWARD_UNOP(method_name) \ _FORWARD(method_name, LocalOp, (const LocalOp& operand), (operand.op())) #define _FORWARD_BINOP(method_name) \ _FORWARD(method_name, LocalOp, \ (const LocalOp& lhs, const LocalOp& rhs, \ absl::Span<const int64> broadcast_dimensions), \ (lhs.op(), rhs.op(), broadcast_dimensions)) #define _FORWARD_TRIOP(method_name) \ _FORWARD(method_name, LocalOp, \ (const LocalOp& lhs, const LocalOp& rhs, const LocalOp& ehs), \ (lhs.op(), rhs.op(), ehs.op())) _FORWARD_TRIOP(Select) _FORWARD_TRIOP(Clamp) _FORWARD_BINOP(Eq) _FORWARD_BINOP(Ne) _FORWARD_BINOP(Ge) _FORWARD_BINOP(Gt) _FORWARD_BINOP(Lt) _FORWARD_BINOP(Le) _FORWARD_BINOP(Add) _FORWARD_BINOP(Sub) _FORWARD_BINOP(Mul) _FORWARD_BINOP(Div) _FORWARD_BINOP(Rem) _FORWARD_BINOP(Max) _FORWARD_BINOP(Min) _FORWARD_BINOP(And) _FORWARD_BINOP(Or) _FORWARD_BINOP(Xor) _FORWARD_BINOP(ShiftLeft) _FORWARD_BINOP(ShiftRightArithmetic) _FORWARD_BINOP(ShiftRightLogical) _FORWARD_BINOP(Atan2) _FORWARD_BINOP(Pow) _FORWARD_BINOP(Complex) _FORWARD_UNOP(Not) _FORWARD_UNOP(Clz) _FORWARD_UNOP(Abs) _FORWARD_UNOP(Exp) _FORWARD_UNOP(Expm1) _FORWARD_UNOP(Floor) _FORWARD_UNOP(Ceil) _FORWARD_UNOP(Round) _FORWARD_UNOP(Log) _FORWARD_UNOP(Log1p) _FORWARD_UNOP(Sign) _FORWARD_UNOP(Cos) _FORWARD_UNOP(Sin) _FORWARD_UNOP(Tanh) _FORWARD_UNOP(IsFinite) _FORWARD_UNOP(Neg) _FORWARD_UNOP(Sqrt) _FORWARD_UNOP(Rsqrt) _FORWARD_UNOP(Square) _FORWARD_UNOP(Reciprocal) _FORWARD_UNOP(Erfc) _FORWARD_UNOP(Erf) _FORWARD_UNOP(ErfInv) _FORWARD_UNOP(Lgamma) _FORWARD_UNOP(Digamma) _FORWARD_UNOP(Acos) _FORWARD_UNOP(Asin) _FORWARD_UNOP(Atan) _FORWARD_UNOP(Tan) _FORWARD_UNOP(Acosh) _FORWARD_UNOP(Asinh) _FORWARD_UNOP(Atanh) _FORWARD_UNOP(Cosh) _FORWARD_UNOP(Sinh) _FORWARD_UNOP(Real) _FORWARD_UNOP(Imag) _FORWARD_UNOP(Conj) #undef _FORWARD #undef _FORWARD_UNOP #undef _FORWARD_BINOP #undef _FORWARD_TRIOP void DeleteLocalShapedBuffer(LocalShapedBuffer* local_shaped_buffer) { delete local_shaped_buffer; } void DeleteLocalExecutable(LocalExecutable* computation) { delete computation; } void DeleteComputation(Computation* computation) { delete computation; } } // namespace swig } // namespace xla
// Copyright 2017-present MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <mongocxx/config/prelude.hpp> namespace mongocxx { MONGOCXX_INLINE_NAMESPACE_BEGIN namespace options { /// /// Class representing the optional arguments to mongocxx::client::start_session. /// class MONGOCXX_API client_session { public: /// /// Sets the causal_consistency option. /// /// If true (the default), each operation in the session will be causally ordered after the /// previous read or write operation. Set to false to disable causal consistency. /// /// Unacknowledged writes are not causally consistent. If you execute a write operation with an /// unacknowledged write concern (a mongocxx::write_concern with /// mongocxx::write_concern::acknowledge_level of @c k_unacknowledged), the write does not /// participate in causal consistency. /// /// @return /// A reference to the object on which this member function is being called. This facilitates /// method chaining. /// /// @see /// https://docs.mongodb.com/manual/core/read-isolation-consistency-recency/#causal-consistency /// client_session& causal_consistency(bool causal_consistency) noexcept; /// /// Gets the current value of the causal_consistency option. /// bool causal_consistency() const noexcept; /// /// Compare session options for equality. /// /// @relates client_session /// friend MONGOCXX_API bool MONGOCXX_CALL operator==(const client_session&, const client_session&); /// /// Compare session options for inequality. /// /// @relates client_session /// friend MONGOCXX_API bool MONGOCXX_CALL operator!=(const client_session&, const client_session&); private: bool _causal_consistency = true; }; /// /// Compare session options for equality. /// /// @relates client_session /// MONGOCXX_API bool MONGOCXX_CALL operator==(const client_session&, const client_session&); /// /// Compare session options for inequality. /// /// @relates client_session /// MONGOCXX_API bool MONGOCXX_CALL operator!=(const client_session&, const client_session&); } // namespace options MONGOCXX_INLINE_NAMESPACE_END } // namespace mongocxx #include <mongocxx/config/postlude.hpp>
VictoryRoad3Script: call VictoryRoad3Script_44996 call EnableAutoTextBoxDrawing ld hl, VictoryRoad3TrainerHeader0 ld de, VictoryRoad3ScriptPointers ld a, [wVictoryRoad3CurScript] call ExecuteCurMapScriptInTable ld [wVictoryRoad3CurScript], a ret VictoryRoad3Script_44996: ld hl, wCurrentMapScriptFlags bit 5, [hl] res 5, [hl] ret z CheckEventHL EVENT_VICTORY_ROAD_3_BOULDER_ON_SWITCH1 ret z ld a, $1d ld [wNewTileBlockID], a lb bc, 5, 3 predef_jump ReplaceTileBlock VictoryRoad3ScriptPointers: dw VictoryRoad3Script0 dw DisplayEnemyTrainerTextAndStartBattle dw EndTrainerBattle VictoryRoad3Script0: ld hl, wFlags_0xcd60 bit 7, [hl] res 7, [hl] jp z, .asm_449fe ld hl, .coordsData_449f9 call CheckBoulderCoords jp nc, .asm_449fe ld a, [wCoordIndex] cp $1 jr nz, .asm_449dc ld hl, wCurrentMapScriptFlags set 5, [hl] SetEvent EVENT_VICTORY_ROAD_3_BOULDER_ON_SWITCH1 ret .asm_449dc CheckAndSetEvent EVENT_VICTORY_ROAD_3_BOULDER_ON_SWITCH2 jr nz, .asm_449fe ld a, HS_VICTORY_ROAD_3_BOULDER ld [wMissableObjectIndex], a predef HideObject ld a, HS_VICTORY_ROAD_2_BOULDER ld [wMissableObjectIndex], a predef_jump ShowObject .coordsData_449f9: db $05,$03 db $0F,$17 db $FF .asm_449fe ld a, VICTORY_ROAD_2 ld [wDungeonWarpDestinationMap], a ld hl, .coordsData_449f9 call IsPlayerOnDungeonWarp ld a, [wCoordIndex] cp $1 jr nz, .asm_44a1b ld hl, wd72d res 4, [hl] ld hl, wd732 res 4, [hl] ret .asm_44a1b ld a, [wd72d] bit 4, a jp z, CheckFightingMapTrainers ret VictoryRoad3TextPointers: dw VictoryRoad3Text1 dw VictoryRoad3Text2 dw VictoryRoad3Text3 dw VictoryRoad3Text4 dw PickUpItemText dw PickUpItemText dw BoulderText dw BoulderText dw BoulderText dw BoulderText VictoryRoad3TrainerHeader0: dbEventFlagBit EVENT_BEAT_VICTORY_ROAD_3_TRAINER_0 db ($1 << 4) ; trainer's view range dwEventFlagAddress EVENT_BEAT_VICTORY_ROAD_3_TRAINER_0 dw VictoryRoad3BattleText2 ; TextBeforeBattle dw VictoryRoad3AfterBattleText2 ; TextAfterBattle dw VictoryRoad3EndBattleText2 ; TextEndBattle dw VictoryRoad3EndBattleText2 ; TextEndBattle VictoryRoad3TrainerHeader1: dbEventFlagBit EVENT_BEAT_VICTORY_ROAD_3_TRAINER_1 db ($4 << 4) ; trainer's view range dwEventFlagAddress EVENT_BEAT_VICTORY_ROAD_3_TRAINER_1 dw VictoryRoad3BattleText3 ; TextBeforeBattle dw VictoryRoad3AfterBattleText3 ; TextAfterBattle dw VictoryRoad3EndBattleText3 ; TextEndBattle dw VictoryRoad3EndBattleText3 ; TextEndBattle VictoryRoad3TrainerHeader2: dbEventFlagBit EVENT_BEAT_VICTORY_ROAD_3_TRAINER_2 db ($4 << 4) ; trainer's view range dwEventFlagAddress EVENT_BEAT_VICTORY_ROAD_3_TRAINER_2 dw VictoryRoad3BattleText4 ; TextBeforeBattle dw VictoryRoad3AfterBattleText4 ; TextAfterBattle dw VictoryRoad3EndBattleText4 ; TextEndBattle dw VictoryRoad3EndBattleText4 ; TextEndBattle VictoryRoad3TrainerHeader3: dbEventFlagBit EVENT_BEAT_VICTORY_ROAD_3_TRAINER_3 db ($4 << 4) ; trainer's view range dwEventFlagAddress EVENT_BEAT_VICTORY_ROAD_3_TRAINER_3 dw VictoryRoad3BattleText5 ; TextBeforeBattle dw VictoryRoad3AfterBattleText5 ; TextAfterBattle dw VictoryRoad3EndBattleText5 ; TextEndBattle dw VictoryRoad3EndBattleText5 ; TextEndBattle db $ff VictoryRoad3Text1: TX_ASM ld hl, VictoryRoad3TrainerHeader0 call TalkToTrainer jp TextScriptEnd VictoryRoad3Text2: TX_ASM ld hl, VictoryRoad3TrainerHeader1 call TalkToTrainer jp TextScriptEnd VictoryRoad3Text3: TX_ASM ld hl, VictoryRoad3TrainerHeader2 call TalkToTrainer jp TextScriptEnd VictoryRoad3Text4: TX_ASM ld hl, VictoryRoad3TrainerHeader3 call TalkToTrainer jp TextScriptEnd VictoryRoad3BattleText2: TX_FAR _VictoryRoad3BattleText2 db "@" VictoryRoad3EndBattleText2: TX_FAR _VictoryRoad3EndBattleText2 db "@" VictoryRoad3AfterBattleText2: TX_FAR _VictoryRoad3AfterBattleText2 db "@" VictoryRoad3BattleText3: TX_FAR _VictoryRoad3BattleText3 db "@" VictoryRoad3EndBattleText3: TX_FAR _VictoryRoad3EndBattleText3 db "@" VictoryRoad3AfterBattleText3: TX_FAR _VictoryRoad3AfterBattleText3 db "@" VictoryRoad3BattleText4: TX_FAR _VictoryRoad3BattleText4 db "@" VictoryRoad3EndBattleText4: TX_FAR _VictoryRoad3EndBattleText4 db "@" VictoryRoad3AfterBattleText4: TX_FAR _VictoryRoad3AfterBattleText4 db "@" VictoryRoad3BattleText5: TX_FAR _VictoryRoad3BattleText5 db "@" VictoryRoad3EndBattleText5: TX_FAR _VictoryRoad3EndBattleText5 db "@" VictoryRoad3AfterBattleText5: TX_FAR _VictoryRoad3AfterBattleText5 db "@"
EnterMap:: ; Load a new map. ld a, $ff ld [wJoyIgnore], a call LoadMapData callba ClearVariablesAfterLoadingMapData ld hl, wd72c bit 0, [hl] ; has the player already made 3 steps since the last battle? jr z, .skipGivingThreeStepsOfNoRandomBattles ld a, 3 ; minimum number of steps between battles ld [wNumberOfNoRandomBattleStepsLeft], a .skipGivingThreeStepsOfNoRandomBattles ld hl, wd72e bit 5, [hl] ; did a battle happen immediately before this? res 5, [hl] ; unset the "battle just happened" flag call z, ResetUsingStrengthOutOfBattleBit call nz, MapEntryAfterBattle ld hl, wd732 ld a, [hl] and 1 << 4 | 1 << 3 ; fly warp or dungeon warp jr z, .didNotEnterUsingFlyWarpOrDungeonWarp callba EnterMapAnim call UpdateSprites ld hl, wd732 res 3, [hl] ld hl, wd72e res 4, [hl] .didNotEnterUsingFlyWarpOrDungeonWarp call IsSurfingPikachuInParty callba CheckForceBikeOrSurf ; handle currents in SF islands and forced bike riding in cycling road ld hl, wd732 bit 4, [hl] res 4, [hl] ld hl, wd72d res 5, [hl] call UpdateSprites ld hl, wCurrentMapScriptFlags set 5, [hl] set 6, [hl] xor a ld [wJoyIgnore], a OverworldLoop:: call DelayFrame OverworldLoopLessDelay:: call DelayFrame call IsSurfingPikachuInParty call LoadGBPal call HandleMidJump ld a, [wWalkCounter] and a jp nz, .moveAhead ; if the player sprite has not yet completed the walking animation call JoypadOverworld ; get joypad state (which is possibly simulated) callba SafariZoneCheck ld a, [wSafariZoneGameOver] and a jp nz, WarpFound2 ld hl, wd72d bit 3, [hl] res 3, [hl] jp nz, WarpFound2 ld a, [wd732] and 1 << 4 | 1 << 3 ; fly warp or dungeon warp jp nz, HandleFlyWarpOrDungeonWarp ld a, [wCurOpponent] and a jp nz, .newBattle ld a, [wd730] bit 7, a ; are we simulating button presses? jr z, .notSimulating ld a, [hJoyHeld] jr .checkIfStartIsPressed .notSimulating ld a, [hJoyPressed] .checkIfStartIsPressed bit 3, a ; start button jr z, .startButtonNotPressed ; if START is pressed xor a ld [hSpriteIndexOrTextID], a ; start menu text ID jp .displayDialogue .startButtonNotPressed bit 0, a ; A button jp z, .checkIfDownButtonIsPressed ; if A is pressed ld a, [wd730] bit 2, a jp nz, .noDirectionButtonsPressed call IsPlayerCharacterBeingControlledByGame jr nz, .checkForOpponent call CheckForHiddenObjectOrBookshelfOrCardKeyDoor ld a, [$ffeb] and a jp z, OverworldLoop ; jump if a hidden object or bookshelf was found, but not if a card key door was found xor a ld [wd436], a ; new yellow address call IsSpriteOrSignInFrontOfPlayer call Func_0ffe ld a, [hSpriteIndexOrTextID] and a jp z, OverworldLoop .displayDialogue predef GetTileAndCoordsInFrontOfPlayer call UpdateSprites ld a, [wFlags_0xcd60] bit 2, a jr nz, .checkForOpponent bit 0, a jr nz, .checkForOpponent aCoord 8, 9 ;ld [wTilePlayerStandingOn], a ; unused? call DisplayTextID ; display either the start menu or the NPC/sign text ld a, [wEnteringCableClub] and a jr z, .checkForOpponent xor a ld [wLinkTimeoutCounter], a jp EnterMap .checkForOpponent ld a, [wCurOpponent] and a jp nz, .newBattle jp OverworldLoop .noDirectionButtonsPressed call UpdateSprites ld hl, wFlags_0xcd60 res 2, [hl] xor a ld [wd435], a ld a, 1 ld [wCheckFor180DegreeTurn], a ld a, [wPlayerMovingDirection] ; the direction that was pressed last time and a jr z, .overworldloop ; if a direction was pressed last time ld [wPlayerLastStopDirection], a ; save the last direction xor a ld [wPlayerMovingDirection], a ; zero the direction .overworldloop jp OverworldLoop .checkIfDownButtonIsPressed ld a, [hJoyHeld] ; current joypad state bit 7, a ; down button jr z, .checkIfUpButtonIsPressed ld a, 1 ld [wSpriteStateData1 + 3], a ; delta Y ld a, PLAYER_DIR_DOWN jr .handleDirectionButtonPress .checkIfUpButtonIsPressed bit 6, a ; up button jr z, .checkIfLeftButtonIsPressed ld a, -1 ld [wSpriteStateData1 + 3], a ; delta Y ld a, PLAYER_DIR_UP jr .handleDirectionButtonPress .checkIfLeftButtonIsPressed bit 5, a ; left button jr z, .checkIfRightButtonIsPressed ld a, -1 ld [wSpriteStateData1 + 5], a ; delta X ld a, PLAYER_DIR_LEFT jr .handleDirectionButtonPress .checkIfRightButtonIsPressed bit 4, a ; right button jr z, .noDirectionButtonsPressed ld a, 1 ld [wSpriteStateData1 + 5], a ; delta X ld a, 1 .handleDirectionButtonPress ld [wPlayerDirection], a ; new direction ld a, [wd730] bit 7, a ; are we simulating button presses? jr nz, .noDirectionChange ; ignore direction changes if we are ld a, [wCheckFor180DegreeTurn] and a jr z, .noDirectionChange ld a, [wPlayerDirection] ; new direction ld b, a ld a, [wPlayerLastStopDirection] ; old direction cp b jr z, .noDirectionChange ld a, $8 ld [wd435], a ; unlike in red/blue, yellow does not have the 180 degrees odd code ld hl, wFlags_0xcd60 set 2, [hl] xor a ld [wCheckFor180DegreeTurn], a ld a, [wPlayerDirection] ld [wPlayerMovingDirection], a call NewBattle jp c, .battleOccurred jp OverworldLoop .noDirectionChange ld a, [wPlayerDirection] ; current direction ld [wPlayerMovingDirection], a ; save direction call UpdateSprites ld a, [wWalkBikeSurfState] cp $02 ; surfing jr z, .surfing ; not surfing call CollisionCheckOnLand jr nc, .noCollision ; collision occurred push hl ld hl, wd736 bit 2, [hl] ; standing on warp flag pop hl jp z, OverworldLoop ; collision occurred while standing on a warp push hl call ExtraWarpCheck ; sets carry if there is a potential to warp pop hl jp c, CheckWarpsCollision jp OverworldLoop .surfing call CollisionCheckOnWater jp c, OverworldLoop .noCollision ld a, $08 ld [wWalkCounter], a callab Func_fcc08 jr .moveAhead2 .moveAhead call IsSpinning call UpdateSprites .moveAhead2 ld hl, wFlags_0xcd60 res 2, [hl] xor a ld [wd435], a call DoBikeSpeedup call AdvancePlayerSprite ld a, [wWalkCounter] and a jp nz, CheckMapConnections ; it seems like this check will never succeed (the other place where CheckMapConnections is run works) ; walking animation finished call StepCountCheck CheckEvent EVENT_IN_SAFARI_ZONE ; in the safari zone? jr z, .notSafariZone callba SafariZoneCheckSteps ld a, [wSafariZoneGameOver] and a jp nz, WarpFound2 .notSafariZone ld a, [wIsInBattle] and a jp nz, CheckWarpsNoCollision predef ApplyOutOfBattlePoisonDamage ; also increment daycare mon exp ld a, [wOutOfBattleBlackout] and a jp nz, HandleBlackOut ; if all pokemon fainted .newBattle call NewBattle ld hl, wd736 res 2, [hl] ; standing on warp flag jp nc, CheckWarpsNoCollision ; check for warps if there was no battle .battleOccurred ld hl, wd72d res 6, [hl] ld hl, wFlags_D733 res 3, [hl] ld hl, wCurrentMapScriptFlags set 5, [hl] set 6, [hl] xor a ld [hJoyHeld], a ld a, [wCurMap] cp CINNABAR_GYM jr nz, .notCinnabarGym SetEvent EVENT_2A7 .notCinnabarGym ld hl, wd72e set 5, [hl] ld a, [wCurMap] cp OAKS_LAB jp z, .noFaintCheck ; no blacking out if the player lost to the rival in Oak's lab callab AnyPartyAlive ld a, d and a jr z, AllPokemonFainted .noFaintCheck ld c, 10 call DelayFrames jp EnterMap StepCountCheck:: ld a, [wd730] bit 7, a jr nz, .doneStepCounting ; if button presses are being simulated, don't count steps ; step counting ld hl, wStepCounter dec [hl] ld a, [wd72c] bit 0, a jr z, .doneStepCounting ld hl, wNumberOfNoRandomBattleStepsLeft dec [hl] jr nz, .doneStepCounting ld hl, wd72c res 0, [hl] ; indicate that the player has stepped thrice since the last battle .doneStepCounting ret AllPokemonFainted:: ld a, $ff ld [wIsInBattle], a call RunMapScript jp HandleBlackOut ; function to determine if there will be a battle and execute it (either a trainer battle or wild battle) ; sets carry if a battle occurred and unsets carry if not NewBattle:: ld a, [wd72d] bit 4, a jr nz, .noBattle call IsPlayerCharacterBeingControlledByGame jr nz, .noBattle ; no battle if the player character is under the game's control ld a, [wd72e] bit 4, a jr nz, .noBattle jpba InitBattle .noBattle and a ret ; function to make bikes twice as fast as walking DoBikeSpeedup:: ld a, [hJoyHeld] ; Check what buttons are being pressed for Shoes and B_BUTTON ; Are you holding B? jr z, .notRunning ; If you aren't holding B, skip ahead to step normally. jp .goFaster ; Make you go faster if you were holding B .notRunning ld a, [wWalkBikeSurfState] dec a ; riding a bike? ret nz ld a, [wd736] bit 6, a ret nz ld a, [wNPCMovementScriptPointerTableNum] and a ret nz ld a, [wCurMap] cp ROUTE_17 ; Cycling Road jr nz, .goFaster ld a, [hJoyHeld] and D_UP | D_LEFT | D_RIGHT ret nz .goFaster call AdvancePlayerSprite ret ; check if the player has stepped onto a warp after having not collided CheckWarpsNoCollision:: ld a, [wNumberOfWarps] and a jp z, CheckMapConnections ld b, 0 ld a, [wNumberOfWarps] ld c, a ld a, [wYCoord] ld d, a ld a, [wXCoord] ld e, a ld hl, wWarpEntries CheckWarpsNoCollisionLoop:: ld a, [hli] ; check if the warp's Y position matches cp d jr nz, CheckWarpsNoCollisionRetry1 ld a, [hli] ; check if the warp's X position matches cp e jr nz, CheckWarpsNoCollisionRetry2 ; if a match was found push hl push bc ld hl, wd736 set 2, [hl] ; standing on warp flag callba IsPlayerStandingOnDoorTileOrWarpTile pop bc pop hl jr c, WarpFound1 ; jump if standing on door or warp push hl push bc call ExtraWarpCheck pop bc pop hl jr nc, CheckWarpsNoCollisionRetry2 ; if the extra check passed ld a, [wFlags_D733] bit 2, a jr nz, WarpFound1 push de push bc call Joypad pop bc pop de ld a, [hJoyHeld] and D_DOWN | D_UP | D_LEFT | D_RIGHT jr z, CheckWarpsNoCollisionRetry2 ; if directional buttons aren't being pressed, do not pass through the warp jr WarpFound1 CheckWarpsNoCollisionRetry1:: inc hl CheckWarpsNoCollisionRetry2:: inc hl inc hl ContinueCheckWarpsNoCollisionLoop:: inc b ; increment warp number dec c ; decrement number of warps jp nz, CheckWarpsNoCollisionLoop jp CheckMapConnections ; check if the player has stepped onto a warp after having collided CheckWarpsCollision:: ld a, [wNumberOfWarps] ld c, a ld hl, wWarpEntries .loop ld a, [hli] ; Y coordinate of warp ld b, a ld a, [wYCoord] cp b jr nz, .retry1 ld a, [hli] ; X coordinate of warp ld b, a ld a, [wXCoord] cp b jr nz, .retry2 ld a, [hli] ld [wDestinationWarpID], a ld a, [hl] ld [hWarpDestinationMap], a jr WarpFound2 .retry1 inc hl .retry2 inc hl inc hl dec c jr nz, .loop jp OverworldLoop WarpFound1:: ld a, [hli] ld [wDestinationWarpID], a ld a, [hli] ld [hWarpDestinationMap], a WarpFound2:: ld a, [wNumberOfWarps] sub c ld [wWarpedFromWhichWarp], a ; save ID of used warp ld a, [wCurMap] ld [wWarpedFromWhichMap], a call CheckIfInOutsideMap jr nz, .indoorMaps ; this is for handling "outside" maps that can't have the 0xFF destination map ld a, [wCurMap] ld [wLastMap], a ld a, [wCurMapWidth] ld [wUnusedD366], a ; not read ld a, [hWarpDestinationMap] ld [wCurMap], a cp ROCK_TUNNEL_1 jr nz, .notRockTunnel ld a, $06 ld [wMapPalOffset], a call GBFadeOutToBlack .notRockTunnel callab CalculatePikachuSpawnState1 ; 3f:45fa call PlayMapChangeSound jr .done ; for maps that can have the 0xFF destination map, which means to return to the outside map ; not all these maps are necessarily indoors, though .indoorMaps ld a, [hWarpDestinationMap] ; destination map cp $ff jr z, .goBackOutside ; if not going back to the previous map ld [wCurMap], a callba IsPlayerStandingOnWarpPadOrHole ld a, [wStandingOnWarpPadOrHole] dec a ; is the player on a warp pad? jr nz, .notWarpPad ; if the player is on a warp pad call LeaveMapAnim ld hl, wd732 set 3, [hl] jr .skipMapChangeSound .notWarpPad call PlayMapChangeSound .skipMapChangeSound ld hl, wd736 res 0, [hl] res 1, [hl] callab CalculatePikachuSpawnState2 jr .done .goBackOutside callab CalculatePikachuSpawnState3 ld a, [wLastMap] ld [wCurMap], a call PlayMapChangeSound xor a ld [wMapPalOffset], a .done ld hl, wd736 set 0, [hl] ; have the player's sprite step out from the door (if there is one) call IgnoreInputForHalfSecond jp EnterMap ; if no matching warp was found CheckMapConnections:: .checkWestMap ld a, [wXCoord] cp $ff jr nz, .checkEastMap ld a, [wMapConn3Ptr] ld [wCurMap], a ld a, [wWestConnectedMapXAlignment] ; new X coordinate upon entering west map ld [wXCoord], a ld a, [wYCoord] ld c, a ld a, [wWestConnectedMapYAlignment] ; Y adjustment upon entering west map add c ld c, a ld [wYCoord], a ld a, [wWestConnectedMapViewPointer] ; pointer to upper left corner of map without adjustment for Y position ld l, a ld a, [wWestConnectedMapViewPointer + 1] ld h, a srl c jr z, .savePointer1 .pointerAdjustmentLoop1 ld a, [wWestConnectedMapWidth] ; width of connected map add MAP_BORDER * 2 ld e, a ld d, 0 ld b, 0 add hl, de dec c jr nz, .pointerAdjustmentLoop1 .savePointer1 ld a, l ld [wCurrentTileBlockMapViewPointer], a ; pointer to upper left corner of current tile block map section ld a, h ld [wCurrentTileBlockMapViewPointer + 1], a jp .loadNewMap .checkEastMap ld b, a ld a, [wCurrentMapWidth2] ; map width cp b jr nz, .checkNorthMap ld a, [wMapConn4Ptr] ld [wCurMap], a ld a, [wEastConnectedMapXAlignment] ; new X coordinate upon entering east map ld [wXCoord], a ld a, [wYCoord] ld c, a ld a, [wEastConnectedMapYAlignment] ; Y adjustment upon entering east map add c ld c, a ld [wYCoord], a ld a, [wEastConnectedMapViewPointer] ; pointer to upper left corner of map without adjustment for Y position ld l, a ld a, [wEastConnectedMapViewPointer + 1] ld h, a srl c jr z, .savePointer2 .pointerAdjustmentLoop2 ld a, [wEastConnectedMapWidth] add MAP_BORDER * 2 ld e, a ld d, 0 ld b, 0 add hl, de dec c jr nz, .pointerAdjustmentLoop2 .savePointer2 ld a, l ld [wCurrentTileBlockMapViewPointer], a ; pointer to upper left corner of current tile block map section ld a, h ld [wCurrentTileBlockMapViewPointer + 1], a jp .loadNewMap .checkNorthMap ld a, [wYCoord] cp $ff jr nz, .checkSouthMap ld a, [wMapConn1Ptr] ld [wCurMap], a ld a, [wNorthConnectedMapYAlignment] ; new Y coordinate upon entering north map ld [wYCoord], a ld a, [wXCoord] ld c, a ld a, [wNorthConnectedMapXAlignment] ; X adjustment upon entering north map add c ld c, a ld [wXCoord], a ld a, [wNorthConnectedMapViewPointer] ; pointer to upper left corner of map without adjustment for X position ld l, a ld a, [wNorthConnectedMapViewPointer + 1] ld h, a ld b, 0 srl c add hl, bc ld a, l ld [wCurrentTileBlockMapViewPointer], a ; pointer to upper left corner of current tile block map section ld a, h ld [wCurrentTileBlockMapViewPointer + 1], a jp .loadNewMap .checkSouthMap ld b, a ld a, [wCurrentMapHeight2] cp b jr nz, .didNotEnterConnectedMap ld a, [wMapConn2Ptr] ld [wCurMap], a ld a, [wSouthConnectedMapYAlignment] ; new Y coordinate upon entering south map ld [wYCoord], a ld a, [wXCoord] ld c, a ld a, [wSouthConnectedMapXAlignment] ; X adjustment upon entering south map add c ld c, a ld [wXCoord], a ld a, [wSouthConnectedMapViewPointer] ; pointer to upper left corner of map without adjustment for X position ld l, a ld a, [wSouthConnectedMapViewPointer + 1] ld h, a ld b, 0 srl c add hl, bc ld a, l ld [wCurrentTileBlockMapViewPointer], a ; pointer to upper left corner of current tile block map section ld a, h ld [wCurrentTileBlockMapViewPointer + 1], a .loadNewMap ; load the connected map that was entered ld hl, wPikachuOverworldStateFlags set 4, [hl] ld a, $2 ld [wPikachuSpawnState], a call LoadMapHeader call PlayDefaultMusicFadeOutCurrent ld b, SET_PAL_OVERWORLD call RunPaletteCommand ; Since the sprite set shouldn't change, this will just update VRAM slots at ; $C2XE without loading any tile patterns. call InitMapSprites call LoadTileBlockMap jp OverworldLoopLessDelay .didNotEnterConnectedMap jp OverworldLoop ; function to play a sound when changing maps PlayMapChangeSound:: ld a, [wCurMapTileset] cp FACILITY jr z, .didNotGoThroughDoor cp CEMETERY jr z, .didNotGoThroughDoor aCoord 8, 8 ; upper left tile of the 4x4 square the player's sprite is standing on cp $0b ; door tile in tileset 0 jr nz, .didNotGoThroughDoor ld a, SFX_GO_INSIDE jr .playSound .didNotGoThroughDoor ld a, SFX_GO_OUTSIDE .playSound call PlaySound ld a, [wMapPalOffset] and a ret nz jp GBFadeOutToBlack CheckIfInOutsideMap:: ; If the player is in an outside map (a town or route), set the z flag ld a, [wCurMapTileset] and a ; most towns/routes have tileset 0 (OVERWORLD) ret z cp PLATEAU ; Route 23 / Indigo Plateau ret ; this function is an extra check that sometimes has to pass in order to warp, beyond just standing on a warp ; the "sometimes" qualification is necessary because of CheckWarpsNoCollision's behavior ; depending on the map, either "function 1" or "function 2" is used for the check ; "function 1" passes when the player is at the edge of the map and is facing towards the outside of the map ; "function 2" passes when the the tile in front of the player is among a certain set ; sets carry if the check passes, otherwise clears carry ExtraWarpCheck:: ld a, [wCurMap] cp SS_ANNE_3 jr z, .useFunction1 cp ROCKET_HIDEOUT_1 jr z, .useFunction2 cp ROCKET_HIDEOUT_2 jr z, .useFunction2 cp ROCKET_HIDEOUT_4 jr z, .useFunction2 cp ROCK_TUNNEL_1 jr z, .useFunction2 ld a, [wCurMapTileset] and a ; outside tileset (OVERWORLD) jr z, .useFunction2 cp SHIP ; S.S. Anne tileset jr z, .useFunction2 cp SHIP_PORT ; Vermilion Port tileset jr z, .useFunction2 cp PLATEAU ; Indigo Plateau tileset jr z, .useFunction2 .useFunction1 ld hl, IsPlayerFacingEdgeOfMap jr .doBankswitch .useFunction2 ld hl, IsWarpTileInFrontOfPlayer .doBankswitch ld b, BANK(IsWarpTileInFrontOfPlayer) jp Bankswitch MapEntryAfterBattle:: callba IsPlayerStandingOnWarp ; for enabling warp testing after collisions ld a, [wMapPalOffset] and a jp z, GBFadeInFromWhite jp LoadGBPal HandleBlackOut:: ; For when all the player's pokemon faint. ; Does not print the "blacked out" message. call GBFadeOutToBlack ld a, $08 call StopMusic ld hl, wd72e res 5, [hl] switchbank SpecialWarpIn ; also Bank(SpecialEnterMap) callab ResetStatusAndHalveMoneyOnBlackout ; 3c:4274 call SpecialWarpIn call PlayDefaultMusicFadeOutCurrent jp SpecialEnterMap StopMusic:: ld [wAudioFadeOutControl], a call StopAllMusic .wait ld a, [wAudioFadeOutControl] and a jr nz, .wait jp StopAllSounds HandleFlyWarpOrDungeonWarp:: call UpdateSprites call Delay3 xor a ld [wBattleResult], a ld [wIsInBattle], a ld [wMapPalOffset], a ld hl, wd732 set 2, [hl] ; fly warp or dungeon warp res 5, [hl] ; forced to ride bike call LeaveMapAnim call Func_07c4 callbs SpecialWarpIn jp SpecialEnterMap LeaveMapAnim:: jpba _LeaveMapAnim Func_07c4:: ld a, [wWalkBikeSurfState] and a ret z xor a ld [wWalkBikeSurfState], a ld hl, wd732 bit 4, [hl] ret z call PlayDefaultMusic ret LoadPlayerSpriteGraphics:: ; Load sprite graphics based on whether the player is standing, biking, or surfing. ; 0: standing ; 1: biking ; 2: surfing ld a, [wWalkBikeSurfState] dec a jr z, .ridingBike ld a, [hTilesetType] and a jr nz, .determineGraphics jr .startWalking .ridingBike ; If the bike can't be used, ; start walking instead. call IsBikeRidingAllowed jr c, .determineGraphics .startWalking xor a ld [wWalkBikeSurfState], a ld [wWalkBikeSurfStateCopy], a jp LoadWalkingPlayerSpriteGraphics .determineGraphics ld a, [wWalkBikeSurfState] and a jp z, LoadWalkingPlayerSpriteGraphics dec a jp z, LoadBikePlayerSpriteGraphics dec a jp z, LoadSurfingPlayerSpriteGraphics2 jp LoadWalkingPlayerSpriteGraphics IsBikeRidingAllowed:: ; The bike can be used on Route 23 and Indigo Plateau, ; or maps with tilesets in BikeRidingTilesets. ; Return carry if biking is allowed. ld a, [wCurMap] cp ROUTE_23 jr z, .allowed cp INDIGO_PLATEAU jr z, .allowed ld a, [wCurMapTileset] ld b, a ld hl, BikeRidingTilesets .loop ld a, [hli] cp b jr z, .allowed inc a jr nz, .loop and a ret .allowed scf ret INCLUDE "data/bike_riding_tilesets.asm" ; load the tile pattern data of the current tileset into VRAM LoadTilesetTilePatternData:: ld a, [wTilesetGfxPtr] ld l, a ld a, [wTilesetGfxPtr + 1] ld h, a ld de, vTileset ld bc, $600 ld a, [wTilesetBank] jp FarCopyData ; this loads the current maps complete tile map (which references blocks, not individual tiles) to C6E8 ; it can also load partial tile maps of connected maps into a border of length 3 around the current map LoadTileBlockMap:: ; fill C6E8-CBFB with the background tile ld hl, wOverworldMap ld bc, $0514 ld a, [wMapBackgroundTile] ; background tile number call FillMemory ; load tile map of current map (made of tile block IDs) ; a 3-byte border at the edges of the map is kept so that there is space for map connections ld hl, wOverworldMap ld a, [wCurMapWidth] ld [hMapWidth], a add MAP_BORDER * 2 ; east and west ld [hMapStride], a ; map width + border ld b, 0 ld c, a ; make space for north border (next 3 lines) add hl, bc add hl, bc add hl, bc ld c, MAP_BORDER add hl, bc ; this puts us past the (west) border ld a, [wMapDataPtr] ; tile map pointer ld e, a ld a, [wMapDataPtr + 1] ld d, a ; de = tile map pointer ld a, [wCurMapHeight] ld b, a .rowLoop ; copy one row each iteration push hl ld a, [hMapWidth] ; map width (without border) ld c, a .rowInnerLoop ld a, [de] inc de ld [hli], a dec c jr nz, .rowInnerLoop ; add the map width plus the border to the base address of the current row to get the next row's address pop hl ld a, [hMapStride] ; map width + border add l ld l, a jr nc, .noCarry inc h .noCarry dec b jr nz, .rowLoop .northConnection ld a, [wMapConn1Ptr] cp $ff jr z, .southConnection call SwitchToMapRomBank ld a, [wNorthConnectionStripSrc] ld l, a ld a, [wNorthConnectionStripSrc + 1] ld h, a ld a, [wNorthConnectionStripDest] ld e, a ld a, [wNorthConnectionStripDest + 1] ld d, a ld a, [wNorthConnectionStripWidth] ld [hNorthSouthConnectionStripWidth], a ld a, [wNorthConnectedMapWidth] ld [hNorthSouthConnectedMapWidth], a call LoadNorthSouthConnectionsTileMap .southConnection ld a, [wMapConn2Ptr] cp $ff jr z, .westConnection call SwitchToMapRomBank ld a, [wSouthConnectionStripSrc] ld l, a ld a, [wSouthConnectionStripSrc + 1] ld h, a ld a, [wSouthConnectionStripDest] ld e, a ld a, [wSouthConnectionStripDest + 1] ld d, a ld a, [wSouthConnectionStripWidth] ld [hNorthSouthConnectionStripWidth], a ld a, [wSouthConnectedMapWidth] ld [hNorthSouthConnectedMapWidth], a call LoadNorthSouthConnectionsTileMap .westConnection ld a, [wMapConn3Ptr] cp $ff jr z, .eastConnection call SwitchToMapRomBank ld a, [wWestConnectionStripSrc] ld l, a ld a, [wWestConnectionStripSrc + 1] ld h, a ld a, [wWestConnectionStripDest] ld e, a ld a, [wWestConnectionStripDest + 1] ld d, a ld a, [wWestConnectionStripHeight] ld b, a ld a, [wWestConnectedMapWidth] ld [hEastWestConnectedMapWidth], a call LoadEastWestConnectionsTileMap .eastConnection ld a, [wMapConn4Ptr] cp $ff jr z, .done call SwitchToMapRomBank ld a, [wEastConnectionStripSrc] ld l, a ld a, [wEastConnectionStripSrc + 1] ld h, a ld a, [wEastConnectionStripDest] ld e, a ld a, [wEastConnectionStripDest + 1] ld d, a ld a, [wEastConnectionStripHeight] ld b, a ld a, [wEastConnectedMapWidth] ld [hEastWestConnectedMapWidth], a call LoadEastWestConnectionsTileMap .done ret LoadNorthSouthConnectionsTileMap:: ld c, MAP_BORDER .loop push de push hl ld a, [hNorthSouthConnectionStripWidth] ld b, a .innerLoop ld a, [hli] ld [de], a inc de dec b jr nz, .innerLoop pop hl pop de ld a, [hNorthSouthConnectedMapWidth] add l ld l, a jr nc, .noCarry1 inc h .noCarry1 ld a, [wCurMapWidth] add MAP_BORDER * 2 add e ld e, a jr nc, .noCarry2 inc d .noCarry2 dec c jr nz, .loop ret LoadEastWestConnectionsTileMap:: push hl push de ld c, MAP_BORDER .innerLoop ld a, [hli] ld [de], a inc de dec c jr nz, .innerLoop pop de pop hl ld a, [hEastWestConnectedMapWidth] add l ld l, a jr nc, .noCarry1 inc h .noCarry1 ld a, [wCurMapWidth] add MAP_BORDER * 2 add e ld e, a jr nc, .noCarry2 inc d .noCarry2 dec b jr nz, LoadEastWestConnectionsTileMap ret ; function to check if there is a sign or sprite in front of the player ; if so, carry is set. otherwise, carry is cleared IsSpriteOrSignInFrontOfPlayer:: xor a ld [hSpriteIndexOrTextID], a ld a, [wNumSigns] and a jr z, .extendRangeOverCounter ; if there are signs predef GetTileAndCoordsInFrontOfPlayer ; get the coordinates in front of the player in de call SignLoop ret c .extendRangeOverCounter ; check if the player is front of a counter in a pokemon center, pokemart, etc. and if so, extend the range at which he can talk to the NPC predef GetTileAndCoordsInFrontOfPlayer ; get the tile in front of the player in c ld hl, wTilesetTalkingOverTiles ; list of tiles that extend talking range (counter tiles) ld b, 3 ld d, $20 ; talking range in pixels (long range) .counterTilesLoop ld a, [hli] cp c jr z, IsSpriteInFrontOfPlayer2 ; jumps if the tile in front of the player is a counter tile dec b jr nz, .counterTilesLoop ; sets carry flag if a sprite is in front of the player, resets if not IsSpriteInFrontOfPlayer:: ld d, $10 ; talking range in pixels (normal range) IsSpriteInFrontOfPlayer2:: lb bc, $3c, $40 ; Y and X position of player sprite ld a, [wPlayerFacingDirection] ; direction the player is facing .checkIfPlayerFacingUp cp SPRITE_FACING_UP jr nz, .checkIfPlayerFacingDown ; facing up ld a, b sub d ld b, a ld a, PLAYER_DIR_UP jr .doneCheckingDirection .checkIfPlayerFacingDown cp SPRITE_FACING_DOWN jr nz, .checkIfPlayerFacingRight ; facing down ld a, b add d ld b, a ld a, PLAYER_DIR_DOWN jr .doneCheckingDirection .checkIfPlayerFacingRight cp SPRITE_FACING_RIGHT jr nz, .playerFacingLeft ; facing right ld a, c add d ld c, a ld a, PLAYER_DIR_RIGHT jr .doneCheckingDirection .playerFacingLeft ; facing left ld a, c sub d ld c, a ld a, PLAYER_DIR_LEFT .doneCheckingDirection ld [wPlayerDirection], a ld hl, wSpriteStateData1 + $10 ; yellow does not have the "if sprites are existant" check ld e, $01 ld d, $f .spriteLoop push hl ld a, [hli] ; image (0 if no sprite) and a jr z, .nextSprite inc l ld a, [hli] ; sprite visibility inc a jr z, .nextSprite inc l ld a, [hli] ; Y location cp b jr nz, .nextSprite inc l ld a, [hl] ; X location cp c jr z, .foundSpriteInFrontOfPlayer .nextSprite pop hl ld a, l add $10 ld l, a inc e dec d jr nz, .spriteLoop xor a ret .foundSpriteInFrontOfPlayer pop hl ld a, l and $f0 inc a ld l, a ; hl = $c1x1 set 7, [hl] ; set flag to make the sprite face the player ld a, e ld [hSpriteIndexOrTextID], a ld a, [hSpriteIndexOrTextID] ; possible useless read because a already has the value of the read address cp $f jr nz, .dontwritetowd436 ld a, $FF ld [wd436], a .dontwritetowd436 scf ret SignLoop:: ; search if a player is facing a sign ld hl, wSignCoords ; start of sign coordinates ld a, [wNumSigns] ; number of signs in the map ld b, a ld c, $00 .signLoop inc c ld a, [hli] ; sign Y cp d jr z, .yCoordMatched inc hl jr .retry .yCoordMatched ld a, [hli] ; sign X cp e jr nz, .retry .xCoordMatched ; found sign push hl push bc ld hl, wSignTextIDs ; start of sign text ID's ld b, $00 dec c add hl, bc ld a, [hl] ld [hSpriteIndexOrTextID], a ; store sign text ID pop bc pop hl scf ret .retry dec b jr nz, .signLoop xor a ret ; function to check if the player will jump down a ledge and check if the tile ahead is passable (when not surfing) ; sets the carry flag if there is a collision, and unsets it if there isn't a collision CollisionCheckOnLand:: ld a, [wd736] bit 6, a ; is the player jumping? jr nz, .noCollision ; if not jumping a ledge ld a, [wSimulatedJoypadStatesIndex] and a jr nz, .noCollision ; no collisions when the player's movements are being controlled by the game ld a, [wPlayerDirection] ; the direction that the player is trying to go in ld d, a ld a, [wSpriteStateData1 + 12] ; the player sprite's collision data (bit field) (set in the sprite movement code) and d ; check if a sprite is in the direction the player is trying to go nop ; ??? why is this in the code jr nz, .collision xor a ld [hSpriteIndexOrTextID], a call IsSpriteInFrontOfPlayer ; check for sprite collisions again? when does the above check fail to detect a sprite collision? jr nc, .asm_0a5c res 7, [hl] ld a, [hSpriteIndexOrTextID] and a ; was there a sprite collision? jr z, .asm_0a5c ; if no sprite collision cp $f jr nz, .collision call CheckPikachuFollowingPlayer jr nz, .collision ld a, [hJoyHeld] and $2 jr nz, .asm_0a5c ld hl, wd435 ld a, [hl] and a jr z, .asm_0a5c dec [hl] jr nz, .collision .asm_0a5c ld hl, TilePairCollisionsLand call CheckForJumpingAndTilePairCollisions jr c, .collision call CheckTilePassable jr nc, .noCollision .collision ld a, [wChannelSoundIDs + CH4] cp SFX_COLLISION ; check if collision sound is already playing jr z, .setCarry ld a, SFX_COLLISION call PlaySound ; play collision sound (if it's not already playing) .setCarry scf ret .noCollision and a ret ; function that checks if the tile in front of the player is passable ; clears carry if it is, sets carry if not CheckTilePassable:: predef GetTileAndCoordsInFrontOfPlayer ; get tile in front of player ld a, [wTileInFrontOfPlayer] ; tile in front of player ld c, a call IsTilePassable ret ; check if the player is going to jump down a small ledge ; and check for collisions that only occur between certain pairs of tiles ; Input: hl - address of directional collision data ; sets carry if there is a collision and unsets carry if not CheckForJumpingAndTilePairCollisions:: push hl predef GetTileAndCoordsInFrontOfPlayer ; get the tile in front of the player push de push bc callba HandleLedges ; check if the player is trying to jump a ledge pop bc pop de pop hl and a ld a, [wd736] bit 6, a ; is the player jumping? ret nz ; if not jumping CheckForTilePairCollisions2:: aCoord 8, 9 ; tile the player is on ld [wTilePlayerStandingOn], a CheckForTilePairCollisions:: ld a, [wTileInFrontOfPlayer] ld c, a .tilePairCollisionLoop ld a, [wCurMapTileset] ; tileset number ld b, a ld a, [hli] cp $ff jr z, .noMatch cp b jr z, .tilesetMatches inc hl .retry inc hl jr .tilePairCollisionLoop .tilesetMatches ld a, [wTilePlayerStandingOn] ; tile the player is on ld b, a ld a, [hl] cp b jr z, .currentTileMatchesFirstInPair inc hl ld a, [hl] cp b jr z, .currentTileMatchesSecondInPair jr .retry .currentTileMatchesFirstInPair inc hl ld a, [hl] cp c jr z, .foundMatch jr .tilePairCollisionLoop .currentTileMatchesSecondInPair dec hl ld a, [hli] cp c inc hl jr nz, .tilePairCollisionLoop .foundMatch scf ret .noMatch and a ret ; FORMAT: tileset number, tile 1, tile 2 ; terminated by 0xFF ; these entries indicate that the player may not cross between tile 1 and tile 2 ; it's mainly used to simulate differences in elevation TilePairCollisionsLand:: db CAVERN, $20, $05 db CAVERN, $41, $05 db FOREST, $30, $2E db CAVERN, $2A, $05 db CAVERN, $05, $21 db FOREST, $52, $2E db FOREST, $55, $2E db FOREST, $56, $2E db FOREST, $20, $2E db FOREST, $5E, $2E db FOREST, $5F, $2E db $FF TilePairCollisionsWater:: db FOREST, $14, $2E db FOREST, $48, $2E db CAVERN, $14, $05 db $FF ; this builds a tile map from the tile block map based on the current X/Y coordinates of the player's character LoadCurrentMapView:: ld a, [H_LOADEDROMBANK] push af ld a, [wTilesetBank] ; tile data ROM bank call BankswitchCommon ; switch to ROM bank that contains tile data ld a, [wCurrentTileBlockMapViewPointer] ; address of upper left corner of current map view ld e, a ld a, [wCurrentTileBlockMapViewPointer + 1] ld d, a ld hl, wTileMapBackup ld b, $05 .rowLoop ; each loop iteration fills in one row of tile blocks push hl push de ld c, $06 .rowInnerLoop ; loop to draw each tile block of the current row push bc push de push hl ld a, [de] ld c, a ; tile block number call DrawTileBlock pop hl pop de pop bc inc hl inc hl inc hl inc hl inc de dec c jr nz, .rowInnerLoop ; update tile block map pointer to next row's address pop de ld a, [wCurMapWidth] add MAP_BORDER * 2 add e ld e, a jr nc, .noCarry inc d .noCarry ; update tile map pointer to next row's address pop hl ld a, $60 add l ld l, a jr nc, .noCarry2 inc h .noCarry2 dec b jr nz, .rowLoop ld hl, wTileMapBackup ld bc, $0000 .adjustForYCoordWithinTileBlock ld a, [wYBlockCoord] and a jr z, .adjustForXCoordWithinTileBlock ld bc, $0030 add hl, bc .adjustForXCoordWithinTileBlock ld a, [wXBlockCoord] and a jr z, .copyToVisibleAreaBuffer ld bc, $0002 add hl, bc .copyToVisibleAreaBuffer coord de, 0, 0 ; base address for the tiles that are directly transferred to VRAM during V-blank ld b, SCREEN_HEIGHT .rowLoop2 ld c, SCREEN_WIDTH .rowInnerLoop2 ld a, [hli] ld [de], a inc de dec c jr nz, .rowInnerLoop2 ld a, $04 add l ld l, a jr nc, .noCarry3 inc h .noCarry3 dec b jr nz, .rowLoop2 pop af call BankswitchCommon ; restore previous ROM bank ret AdvancePlayerSprite:: ld a, [wUpdateSpritesEnabled] push af ld a, $FF ld [wUpdateSpritesEnabled], a ld hl, _AdvancePlayerSprite ld b, BANK(_AdvancePlayerSprite) call Bankswitch pop af ld [wUpdateSpritesEnabled], a ret ; the following 6 functions are used to tell the V-blank handler to redraw ; the portion of the map that was newly exposed due to the player's movement ScheduleNorthRowRedraw:: coord hl, 0, 0 call CopyToRedrawRowOrColumnSrcTiles ld a, [wMapViewVRAMPointer] ld [hRedrawRowOrColumnDest], a ld a, [wMapViewVRAMPointer + 1] ld [hRedrawRowOrColumnDest + 1], a ld a, REDRAW_ROW ld [hRedrawRowOrColumnMode], a ret CopyToRedrawRowOrColumnSrcTiles:: ld de, wRedrawRowOrColumnSrcTiles ld c, 2 * SCREEN_WIDTH .loop ld a, [hli] ld [de], a inc de dec c jr nz, .loop ret ScheduleSouthRowRedraw:: coord hl, 0, 16 call CopyToRedrawRowOrColumnSrcTiles ld a, [wMapViewVRAMPointer] ld l, a ld a, [wMapViewVRAMPointer + 1] ld h, a ld bc, $0200 add hl, bc ld a, h and $03 or $98 ld [hRedrawRowOrColumnDest + 1], a ld a, l ld [hRedrawRowOrColumnDest], a ld a, REDRAW_ROW ld [hRedrawRowOrColumnMode], a ret ScheduleEastColumnRedraw:: coord hl, 18, 0 call ScheduleColumnRedrawHelper ld a, [wMapViewVRAMPointer] ld c, a and $e0 ld b, a ld a, c add 18 and $1f or b ld [hRedrawRowOrColumnDest], a ld a, [wMapViewVRAMPointer + 1] ld [hRedrawRowOrColumnDest + 1], a ld a, REDRAW_COL ld [hRedrawRowOrColumnMode], a ret ScheduleColumnRedrawHelper:: ld de, wRedrawRowOrColumnSrcTiles ld c, SCREEN_HEIGHT .loop ld a, [hli] ld [de], a inc de ld a, [hl] ld [de], a inc de ld a, 19 add l ld l, a jr nc, .noCarry inc h .noCarry dec c jr nz, .loop ret ScheduleWestColumnRedraw:: coord hl, 0, 0 call ScheduleColumnRedrawHelper ld a, [wMapViewVRAMPointer] ld [hRedrawRowOrColumnDest], a ld a, [wMapViewVRAMPointer + 1] ld [hRedrawRowOrColumnDest + 1], a ld a, REDRAW_COL ld [hRedrawRowOrColumnMode], a ret ; function to write the tiles that make up a tile block to memory ; Input: c = tile block ID, hl = destination address DrawTileBlock:: push hl ld a, [wTilesetBlocksPtr] ; pointer to tiles ld l, a ld a, [wTilesetBlocksPtr + 1] ld h, a ld a, c swap a ld b, a and $f0 ld c, a ld a, b and $0f ld b, a ; bc = tile block ID * 0x10 add hl, bc ld d, h ld e, l ; de = address of the tile block's tiles pop hl ld c, $04 ; 4 loop iterations .loop ; each loop iteration, write 4 tile numbers push bc ld a, [de] ld [hli], a inc de ld a, [de] ld [hli], a inc de ld a, [de] ld [hli], a inc de ld a, [de] ld [hl], a inc de ld bc, $0015 add hl, bc pop bc dec c jr nz, .loop ret ; function to update joypad state and simulate button presses JoypadOverworld:: xor a ld [wSpriteStateData1 + 3], a ld [wSpriteStateData1 + 5], a call RunMapScript call Joypad call ForceBikeDown call AreInputsSimulated ret ForceBikeDown:: ld a, [wFlags_D733] bit 3, a ; check if a trainer wants a challenge ret nz ld a, [wCurMap] cp ROUTE_17 ; Cycling Road ret nz ld a, [hJoyHeld] and D_DOWN | D_UP | D_LEFT | D_RIGHT | B_BUTTON | A_BUTTON ret nz ld a, D_DOWN ld [hJoyHeld], a ; on the cycling road, if there isn't a trainer and the player isn't pressing buttons, simulate a down press ret AreInputsSimulated:: ld a, [wd730] bit 7, a ret z ; if simulating button presses ld a, [hJoyHeld] ld b, a ld a, [wOverrideSimulatedJoypadStatesMask] ; bit mask for button presses that override simulated ones and b ret nz ; return if the simulated button presses are overridden call GetSimulatedInput jr nc, .doneSimulating ld [hJoyHeld], a ; store simulated button press in joypad state and a ret nz ld [hJoyPressed], a ld [hJoyReleased], a ret ; if done simulating button presses .doneSimulating xor a ld [wWastedByteCD3A], a ld [wSimulatedJoypadStatesIndex], a ld [wSimulatedJoypadStatesEnd], a ld [wJoyIgnore], a ld [hJoyHeld], a ld hl, wd736 ld a, [hl] and $f8 ld [hl], a ld hl, wd730 res 7, [hl] ret GetSimulatedInput:: ld hl, wSimulatedJoypadStatesIndex dec [hl] ld a, [hl] cp $ff jr z, .endofsimulatedinputs ; if the end of the simulated button presses has been reached push de ld e, a ld d, $0 ld hl, wSimulatedJoypadStatesEnd add hl, de ld a, [hl] pop de scf ret .endofsimulatedinputs and a ret ; function to check the tile ahead to determine if the character should get on land or keep surfing ; sets carry if there is a collision and clears carry otherwise ; This function had a bug in Red/Blue, but it was fixed in Yellow. CollisionCheckOnWater:: ld a, [wd730] bit 7, a jp nz, .noCollision ; return and clear carry if button presses are being simulated ld a, [wPlayerDirection] ; the direction that the player is trying to go in ld d, a ld a, [wSpriteStateData1 + 12] ; the player sprite's collision data (bit field) (set in the sprite movement code) and d ; check if a sprite is in the direction the player is trying to go jr nz, .collision ld hl, TilePairCollisionsWater call CheckForJumpingAndTilePairCollisions jr c, .collision predef GetTileAndCoordsInFrontOfPlayer ; get tile in front of player (puts it in c and [wTileInFrontOfPlayer]) callab IsNextTileShoreOrWater jr c, .noCollision ld a, [wTileInFrontOfPlayer] ; tile in front of player ld c, a call IsTilePassable jr nc, .stopSurfing .collision ld a, [wChannelSoundIDs + CH4] cp SFX_COLLISION ; check if collision sound is already playing jr z, .setCarry ld a, SFX_COLLISION call PlaySound ; play collision sound (if it's not already playing) .setCarry scf jr .done .checkIfVermilionDockTileset ld a, [wCurMapTileset] ; tileset cp SHIP_PORT ; Vermilion Dock tileset jr nz, .noCollision ; keep surfing if it's not the boarding platform tile jr .stopSurfing ; if it is the boarding platform tile, stop surfing .stopSurfing ; based game freak ld a, $3 ld [wPikachuSpawnState], a ld hl, wPikachuOverworldStateFlags set 5, [hl] xor a ld [wWalkBikeSurfState], a call LoadPlayerSpriteGraphics call PlayDefaultMusic jr .noCollision .noCollision ; ...and they do the same mistake twice and a .done ret ; function to run the current map's script RunMapScript:: push hl push de push bc callba TryPushingBoulder ld a, [wFlags_0xcd60] bit 1, a ; play boulder dust animation jr z, .afterBoulderEffect callba DoBoulderDustAnimation .afterBoulderEffect pop bc pop de pop hl call RunNPCMovementScript ld a, [wCurMap] ; current map number call SwitchToMapRomBank ; change to the ROM bank the map's data is in ld hl, wMapScriptPtr ld a, [hli] ld h, [hl] ld l, a ld de, .return push de jp [hl] ; jump to script .return ret LoadWalkingPlayerSpriteGraphics:: ; new sprite copy stuff xor a ld [wd473], a ld b, BANK(RedSprite) ld de, RedSprite ; $4180 ld a, [wPlayerGender] and a jr z, .AreGuy1 ld de,LeafSprite .AreGuy1 jr LoadPlayerSpriteGraphicsCommon LoadSurfingPlayerSpriteGraphics2:: ld a, [wd473] and a jr z, .asm_0d75 dec a jr z, LoadSurfingPlayerSpriteGraphics dec a jr z, .asm_0d7c .asm_0d75 ld a, [wd472] bit 6, a jr z, LoadSurfingPlayerSpriteGraphics .asm_0d7c ld b, BANK(SurfingPikachuSprite) ld de, SurfingPikachuSprite ; 3f:6def jr LoadPlayerSpriteGraphicsCommon LoadSurfingPlayerSpriteGraphics:: ld b, BANK(SeelSprite) ld de, SeelSprite jr LoadPlayerSpriteGraphicsCommon LoadBikePlayerSpriteGraphics:: ld b, BANK(RedCyclingSprite) ld de, RedCyclingSprite LoadPlayerSpriteGraphicsCommon:: ld hl, vNPCSprites push de push hl push bc ld c, $c call CopyVideoData pop bc pop hl pop de ld a, $c0 add e ld e, a jr nc, .noCarry inc d .noCarry set 3, h ld c, $c jp CopyVideoData ; function to load data from the map header LoadMapHeader:: callba MarkTownVisitedAndLoadMissableObjects jr asm_0dbd Func_0db5:: ; XXX callba LoadUnusedBluesHouseMissableObjectData ; 3c:4a55 asm_0dbd ld a, [wCurMapTileset] ld [wUnusedD119], a ld a, [wCurMap] call SwitchToMapRomBank ld a, [wCurMapTileset] ld b, a res 7, a ld [wCurMapTileset], a ld [hPreviousTileset], a bit 7, b ret nz call GetMapHeaderPointer ; copy the first 10 bytes (the fixed area) of the map data to D367-D370 ld de, wCurMapTileset ld c, $0a .copyFixedHeaderLoop ld a, [hli] ld [de], a inc de dec c jr nz, .copyFixedHeaderLoop ; initialize all the connected maps to disabled at first, before loading the actual values ld a, $ff ld [wMapConn1Ptr], a ld [wMapConn2Ptr], a ld [wMapConn3Ptr], a ld [wMapConn4Ptr], a ; copy connection data (if any) to WRAM ld a, [wMapConnections] ld b, a .checkNorth bit 3, b jr z, .checkSouth ld de, wMapConn1Ptr call CopyMapConnectionHeader .checkSouth bit 2, b jr z, .checkWest ld de, wMapConn2Ptr call CopyMapConnectionHeader .checkWest bit 1, b jr z, .checkEast ld de, wMapConn3Ptr call CopyMapConnectionHeader .checkEast bit 0, b jr z, .getObjectDataPointer ld de, wMapConn4Ptr call CopyMapConnectionHeader .getObjectDataPointer ld a, [hli] ld [wObjectDataPointerTemp], a ld a, [hli] ld [wObjectDataPointerTemp + 1], a push hl ld a, [wObjectDataPointerTemp] ld l, a ld a, [wObjectDataPointerTemp + 1] ld h, a ; hl = base of object data ld de, wMapBackgroundTile ld a, [hli] ld [de], a .loadWarpData ld a, [hli] ld [wNumberOfWarps], a and a jr z, .loadSignData ld c, a ld de, wWarpEntries .warpLoop ; one warp per loop iteration ld b, $04 .warpInnerLoop ld a, [hli] ld [de], a inc de dec b jr nz, .warpInnerLoop dec c jr nz, .warpLoop .loadSignData ld a, [hli] ; number of signs ld [wNumSigns], a and a ; are there any signs? jr z, .loadSpriteData ; if not, skip this call CopySignData ; 0eb3 (0:0eb3) .loadSpriteData ld a, [wd72e] bit 5, a ; did a battle happen immediately before this? jr nz, .finishUp ; if so, skip this because battles don't destroy this data call InitSprites .finishUp predef LoadTilesetHeader ld a, [wd72e] bit 5, a ; did a battle happen immediately before this? jr nz, .skip_pika_spawn callab SchedulePikachuSpawnForAfterText ; 3f:44fa .skip_pika_spawn callab LoadWildData ; 3:4b62 pop hl ; restore hl from before going to the warp/sign/sprite data (this value was saved for seemingly no purpose) ld a, [wCurMapHeight] ; map height in 4x4 tile blocks add a ; double it ld [wCurrentMapHeight2], a ; store map height in 2x2 tile blocks ld a, [wCurMapWidth] ; map width in 4x4 tile blocks add a ; double it ld [wCurrentMapWidth2], a ; map width in 2x2 tile blocks ld a, [wCurMap] ld c, a ld b, $00 ld a, [H_LOADEDROMBANK] push af switchbank MapSongBanks ld hl, MapSongBanks ; 3f:4000 add hl, bc add hl, bc ld a, [hli] ld [wMapMusicSoundID], a ; music 1 ld a, [hl] ld [wMapMusicROMBank], a ; music 2 pop af call BankswitchCommon ret ; function to copy map connection data from ROM to WRAM ; Input: hl = source, de = destination CopyMapConnectionHeader:: ld c, $0b .loop ld a, [hli] ld [de], a inc de dec c jr nz, .loop ret CopySignData:: ld de, wSignCoords ; start of sign coords ld bc, wSignTextIDs ; start of sign text ids ld a, [wNumSigns] ; number of signs .signcopyloop push af ld a, [hli] ld [de], a ; copy y coord inc de ld a, [hli] ld [de], a ; copy x coord inc de ld a, [hli] ld [bc], a ; copy sign text id inc bc pop af dec a jr nz, .signcopyloop ret ; function to load map data LoadMapData:: ld a, [H_LOADEDROMBANK] push af call DisableLCD call ResetMapVariables call LoadTextBoxTilePatterns call LoadMapHeader call InitMapSprites ; load tile pattern data for sprites call LoadScreenRelatedData call CopyMapViewToVRAM ld a, $01 ld [wUpdateSpritesEnabled], a call EnableLCD ld b, $09 call RunPaletteCommand call LoadPlayerSpriteGraphics ld a, [wd732] and 1 << 4 | 1 << 3 ; fly warp or dungeon warp jr nz, .restoreRomBank ld a, [wFlags_D733] bit 1, a jr nz, .restoreRomBank call UpdateMusic6Times ; music related call PlayDefaultMusicFadeOutCurrent ; music related .restoreRomBank pop af call BankswitchCommon ret LoadScreenRelatedData:: call LoadTileBlockMap call LoadTilesetTilePatternData call LoadCurrentMapView ret ReloadMapAfterSurfingMinigame:: ld a, [H_LOADEDROMBANK] push af call DisableLCD call ResetMapVariables ld a, [wCurMap] call SwitchToMapRomBank call LoadScreenRelatedData call CopyMapViewToVRAM ld de, vBGMap1 call CopyMapViewToVRAM2 call EnableLCD call ReloadMapSpriteTilePatterns pop af call BankswitchCommon jr asm_0f4d ReloadMapAfterPrinter:: ld a, [H_LOADEDROMBANK] push af ld a, [wCurMap] call SwitchToMapRomBank call LoadTileBlockMap pop af call BankswitchCommon asm_0f4d: jpab SetMapSpecificScriptFlagsOnMapReload ret ; useless? ResetMapVariables:: ld a, $98 ld [wMapViewVRAMPointer + 1], a xor a ld [wMapViewVRAMPointer], a ld [hSCY], a ld [hSCX], a ld [wWalkCounter], a ld [wUnusedD119], a ld [wSpriteSetID], a ld [wWalkBikeSurfStateCopy], a ret CopyMapViewToVRAM:: ; copy current map view to VRAM ld de, vBGMap0 CopyMapViewToVRAM2: ld hl, wTileMap ld b, 18 .vramCopyLoop ld c, 20 .vramCopyInnerLoop ld a, [hli] ld [de], a inc e dec c jr nz, .vramCopyInnerLoop ld a, 32 - 20 ; total vram map width in tiles - screen width in tiles add e ld e, a jr nc, .noCarry inc d .noCarry dec b jr nz, .vramCopyLoop ret ; function to switch to the ROM bank that a map is stored in ; Input: a = map number SwitchToMapRomBank:: push hl push bc ld c, a ld b, $00 ld a, BANK(MapHeaderBanks) call BankswitchHome ; switch to ROM bank 3F ld hl, MapHeaderBanks add hl, bc ld a, [hl] ld [$ffe8], a ; save map ROM bank call BankswitchBack ld a, [$ffe8] call BankswitchCommon pop bc pop hl ret GetMapHeaderPointer:: ld a, [H_LOADEDROMBANK] push af switchbank MapHeaderPointers ; 3f:41f2 push de ld a, [wCurMap] ld e, a ld d, $0 ld hl, MapHeaderPointers add hl, de add hl, de ld a, [hli] ld h, [hl] ld l, a pop de pop af jp BankswitchCommon IgnoreInputForHalfSecond: ld a, 30 ld [wIgnoreInputCounter], a ld hl, wd730 ld a, [hl] or %00100110 ld [hl], a ; set ignore input bit ret ResetUsingStrengthOutOfBattleBit: ld hl, wd728 res 0, [hl] ret ForceBikeOrSurf:: ld b, BANK(RedSprite) ld hl, LoadPlayerSpriteGraphics call Bankswitch jp PlayDefaultMusic ; update map/player state? ; Handle the player jumping down ; a ledge in the overworld. HandleMidJump:: ld a, [wd736] bit 6, a ; jumping down a ledge? ret z callba _HandleMidJump ret IsSpinning:: ld a, [wd736] bit 7, a ret z ; no spinning jpba LoadSpinnerArrowTiles ; spin while moving Func_0ffe:: jpab IsPlayerTalkingToPikachu InitSprites:: ld a, [hli] ld [wNumSprites], a ; save the number of sprites push hl push de push bc call ZeroSpriteStateData call DisableRegularSprites ld hl, wMapSpriteData ld bc, $20 xor a call FillMemory pop bc pop de pop hl ld a, [wNumSprites] and a ; are sprites existant? ret z ; don't copy sprite data if not ld b, a ld c, $0 ld de, wSpriteStateData1 + $10 ; copy sprite stuff? .loadSpriteLoop ld a, [hli] ld [de], a ; store picture ID at C1X0 inc d ld a, e add $4 ld e, a ld a, [hli] ld [de], a ; store Y position at C2X4 inc e ld a, [hli] ld [de], a ; store X position at C2X5 inc e ld a, [hli] ld [de], a ; store movement byte 1 at C2X6 ld a, [hli] ld [$ff8d], a ; save movement byte 2 ld a, [hli] ld [$ff8e], a ; save text ID and flags byte push bc call LoadSprite pop bc dec d ld a, e add $a ld e, a inc c inc c dec b jr nz, .loadSpriteLoop ret ZeroSpriteStateData:: ; zero C110-C1EF and C210-C2EF ; C1F0-C1FF and C2F0-C2FF is used for Pikachu ld hl, wSpriteStateData1 + $10 ld de, wSpriteStateData2 + $10 xor a ld b, 14 * $10 .loop ld [hli], a ld [de], a inc e dec b jr nz, .loop ret DisableRegularSprites:: ; initialize all C100-C1FF sprite entries to disabled (other than player's and pikachu) ld hl, wSpriteStateData1 + 1 * $10 + 2 ld de, $10 ld c, $e .loop ld [hl], $ff add hl, de dec c jr nz, .loop ret LoadSprite:: push hl ld b, $0 ld hl, wMapSpriteData add hl, bc ld a, [$ff8d] ld [hli], a ; store movement byte 2 in byte 0 of sprite entry ld a, [$ff8e] ld [hl], a ; this appears pointless, since the value is overwritten immediately after ld a, [$ff8e] ld [$ff8d], a and $3f ld [hl], a ; store text ID in byte 1 of sprite entry pop hl ld a, [$ff8d] bit 6, a jr nz, .trainerSprite bit 7, a jr nz, .itemBallSprite ; for regular sprites push hl ld hl, wMapSpriteExtraData add hl, bc ; zero both bytes, since regular sprites don't use this extra space xor a ld [hli], a ld [hl], a pop hl ret .trainerSprite ld a, [hli] ld [$ff8d], a ; save trainer class ld a, [hli] ld [$ff8e], a ; save trainer number (within class) push hl ld hl, wMapSpriteExtraData add hl, bc ld a, [$ff8d] ld [hli], a ; store trainer class in byte 0 of the entry ld a, [$ff8e] ld [hl], a ; store trainer number in byte 1 of the entry pop hl ret .itemBallSprite ld a, [hli] ld [$ff8d], a ; save item number push hl ld hl, wMapSpriteExtraData add hl, bc ld a, [$ff8d] ld [hli], a ; store item number in byte 0 of the entry xor a ld [hl], a ; zero byte 1, since it is not used pop hl ret ; end of home/overworld.asm = 10b9 (0:10b9)
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft %> <%docstring>utime(file, file_times) -> str Invokes the syscall utime. See 'man 2 utime' for more information. Arguments: file(char*): file file_times(utimbuf*): file_times Returns: int </%docstring> <%page args="file=0, file_times=0"/> <% abi = pwnlib.abi.ABI.syscall() stack = abi.stack regs = abi.register_arguments[1:] allregs = pwnlib.shellcraft.registers.current() can_pushstr = ['file'] can_pushstr_array = [] argument_names = ['file', 'file_times'] argument_values = [file, file_times] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%r' % (name, arg)) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, str): string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_utime']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* utime(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=('\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
CinnabarLabFossilRoom_Object: db $17 ; border block db 2 ; warps warp 2, 7, 4, CINNABAR_LAB warp 3, 7, 4, CINNABAR_LAB db 0 ; signs db 2 ; objects object SPRITE_OAK_AIDE, 5, 2, WALK, 2, 1 ; person object SPRITE_OAK_AIDE, 7, 6, STAY, UP, 2 ; person ; warp-to warp_to 2, 7, CINNABAR_LAB_FOSSIL_ROOM_WIDTH ; CINNABAR_LAB warp_to 3, 7, CINNABAR_LAB_FOSSIL_ROOM_WIDTH ; CINNABAR_LAB
// // deadline_timer.hpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2014 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_DEADLINE_TIMER_HPP #define BOOST_ASIO_DEADLINE_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) \ || defined(GENERATING_DOCUMENTATION) #include <boost/asio/detail/socket_types.hpp> // Must come before posix_time. #include <boost/asio/basic_deadline_timer.hpp> #include <boost/asio/detail/push_options.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/asio/detail/pop_options.hpp> namespace boost { namespace asio { /// Typedef for the typical usage of timer. Uses a UTC clock. typedef basic_deadline_timer<boost::posix_time::ptime> deadline_timer; } // namespace asio } // namespace boost #endif // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_DEADLINE_TIMER_HPP
; A166626: Totally multiplicative sequence with a(p) = 5p for prime p. ; 1,10,15,100,25,150,35,1000,225,250,55,1500,65,350,375,10000,85,2250,95,2500,525,550,115,15000,625,650,3375,3500,145,3750,155,100000,825,850,875,22500,185,950,975,25000,205,5250,215,5500,5625,1150,235,150000,1225,6250,1275,6500,265,33750,1375,35000,1425,1450,295,37500,305,1550,7875,1000000,1625,8250,335,8500,1725,8750,355,225000,365,1850,9375,9500,1925,9750,395,250000,50625,2050,415,52500,2125,2150,2175,55000,445,56250,2275,11500,2325,2350,2375,1500000,485,12250,12375,62500 mov $2,$0 seq $0,165826 ; Totally multiplicative sequence with a(p) = 5. mov $1,1 add $1,$2 mul $0,$1
; A186226: Adjusted joint rank sequence of (g(j)) and (f(i)) with f(i) after g(j) when f(i)=g(j), where f and g are the triangular numbers and pentagonal numbers. Complement of A186225. ; 1,4,7,10,12,15,18,21,23,26,29,31,34,37,40,42,45,48,51,53,56,59,62,64,67,70,72,75,78,81,83,86,89,92,94,97,100,103,105,108,111,113,116,119,122,124,127,130,133,135,138,141,144,146,149,152,154,157,160,163,165,168,171,174,176,179,182,184,187,190,193,195,198,201,204,206,209,212,215,217,220,223,225,228,231,234,236,239,242,245,247,250,253,256,258,261,264,266,269,272 mov $2,$0 mov $3,$0 lpb $0,1 add $2,$0 lpb $0,1 add $1,$0 sub $0,1 lpe add $1,1 add $2,1 lpb $1,1 trn $1,$2 sub $2,1 lpe add $1,$2 lpe lpb $3,1 add $1,1 sub $3,1 lpe add $1,1
; sccz80 crt0 library - 8080 version SECTION code_clib SECTION code_l_sccz80 PUBLIC l_long_mod_u EXTERN l_long_divide .l_long_mod_u ld a,0 jp l_long_divide
; ; ZX Spectrum specific routines ; by Stefano Bodrato, MAR 2010 ; ; int zx_ulaplus(); ; ; The result is: ; - 0 (false) ULAPlus not installed / emulated ; - 1 ULAPlus 64 colour mode is available ; ; $Id: zx_ulaplus.asm,v 1.2 2010/04/02 09:05:06 stefano Exp $ ; XLIB zx_ulaplus zx_ulaplus: ; Enter in 64 colour mode ld bc,$bf3b ld a,64 ; select mode group (01xxxxxx) out (c),a ld b,$ff in a,(c) ld e,a ld a,1 ; palette mode out (c),a in a,(c) ; see if ULAPlus got palette mode dec a ld hl,0 ret nz ld a,e out (c),a ; restore current palette mode inc hl ret
lc r4, 0xffffffff lc r5, 0x80000001 eq r6, r4, r5 halt #@expected values #r4 = 0xffffffff #r5 = 0x80000001 #r6 = 0x00000000 #pc = -2147483628 #e0 = 0 #e1 = 0 #e2 = 0 #e3 = 0
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_MATH_LESS_HPP #define SPROUT_MATH_LESS_HPP #include <type_traits> #include <sprout/config.hpp> #include <sprout/math/not_equal_to.hpp> #include <sprout/type_traits/arithmetic_promote.hpp> #include <sprout/type_traits/enabler_if.hpp> #include <sprout/type_traits/is_signed.hpp> #include <sprout/type_traits/is_unsigned.hpp> namespace sprout { namespace math { namespace detail { template< typename FloatType1, typename FloatType2, typename sprout::enabler_if< std::is_floating_point<typename sprout::arithmetic_promote<FloatType1, FloatType2>::type>::value >::type = sprout::enabler > inline SPROUT_CONSTEXPR bool less(FloatType1 x, FloatType2 y) { return sprout::math::not_equal_to(x, y) && x < y; } template< typename IntType1, typename IntType2, typename sprout::enabler_if< std::is_integral<typename sprout::arithmetic_promote<IntType1, IntType2>::type>::value && (sprout::is_unsigned<IntType1>::value == sprout::is_unsigned<IntType2>::value) >::type = sprout::enabler > inline SPROUT_CONSTEXPR bool less(IntType1 x, IntType2 y) { return x < y; } template< typename IntType1, typename IntType2, typename sprout::enabler_if< std::is_integral<typename sprout::arithmetic_promote<IntType1, IntType2>::type>::value && sprout::is_signed<IntType1>::value && sprout::is_unsigned<IntType2>::value >::type = sprout::enabler > inline SPROUT_CONSTEXPR bool less(IntType1 x, IntType2 y) { typedef typename std::make_unsigned<typename sprout::arithmetic_promote<IntType1, IntType2>::type>::type type; return x < 0 ? true : static_cast<type>(x) < static_cast<type>(y) ; } template< typename IntType1, typename IntType2, typename sprout::enabler_if< std::is_integral<typename sprout::arithmetic_promote<IntType1, IntType2>::type>::value && sprout::is_unsigned<IntType1>::value && sprout::is_signed<IntType2>::value >::type = sprout::enabler > inline SPROUT_CONSTEXPR bool less(IntType1 x, IntType2 y) { typedef typename std::make_unsigned<typename sprout::arithmetic_promote<IntType1, IntType2>::type>::type type; return y < 0 ? false : static_cast<type>(x) < static_cast<type>(y) ; } } // namespace detail // // less // template< typename T, typename U, typename sprout::enabler_if<std::is_arithmetic<T>::value && std::is_arithmetic<U>::value>::type = sprout::enabler > inline SPROUT_CONSTEXPR bool less(T x, U y) { return sprout::math::detail::less(x, y); } } // namespace math } // namespace sprout #endif // #ifndef SPROUT_MATH_LESS_HPP
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2016, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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. // // image_preprocessor.hpp - Preprocessing utilities for image inputs //////////////////////////////////////////////////////////////////////////////// #ifndef LBANN_IMAGE_PREPROCESSOR #define LBANN_IMAGE_PREPROCESSOR #include "lbann_config.hpp" #ifdef LBANN_HAS_OPENCV #include "lbann/data_readers/opencv.hpp" #else #error OpenCV required #endif #include "lbann/base.hpp" namespace lbann { /** * Support class for preprocessing image inputs. * Supports the following transforms: * - Random horizontal and vertical flips * - Random rotations * - Random horizontal and vertical shifts * - Random shearing * - Standardize to 0 mean * - Standardize to unit variance * - Scale to the range [0, 1] * - Normalize via z-score */ class lbann_image_preprocessor { public: lbann_image_preprocessor(); lbann_image_preprocessor(const lbann_image_preprocessor&) = default; lbann_image_preprocessor& operator=( const lbann_image_preprocessor&) = default; virtual ~lbann_image_preprocessor() {} /** Whether to do random horizontal flips. */ void horizontal_flip(bool b) { m_horizontal_flip = b; } /** Whether to do random vertical flips. */ void vertical_flip(bool b) { m_vertical_flip = b; } /** Do random rotations up to range degrees (0-180). */ void rotation(float range) { m_rotation_range = range; } /** Do random horizontal shifts up to range (fraction of image width). */ void horizontal_shift(float range) { m_horizontal_shift = range; } /** Do random vertical shifts up to range (fraction of image height). */ void vertical_shift(float range) { m_vertical_shift = range; } /** Do random shears up to range (radians). */ void shear_range(float range) { m_shear_range = range; } /** Whether to subtract the sample-wise mean. */ void subtract_mean(bool b) { m_mean_subtraction = b; } /** Whether to normalize to unit variance, sample-wise. */ void unit_variance(bool b) { m_unit_variance = b; } /** Whether to scale to [0, 1] (assumes max value is 255). */ void scale(bool b) { m_scale = b; } /** * Whether to normalize by z-scores, sample-wise. * This and mean subtraction/unit variance are mutually exclusive. */ void z_score(bool b) { m_z_score = b; } /** Disable all data augmentation. */ void disable_augmentation() { horizontal_flip(false); vertical_flip(false); rotation(0.0f); horizontal_shift(0.0f); vertical_shift(0.0f); shear_range(0.0f); } /** * Add noise to data (disable by default) * noise_factor control the ammount of noise * to be set to a value above zero but less than 1 (say 0.5) * */ void add_noise(float noise_factor=0.0f) { m_noise_factor = noise_factor; } /** * Preprocess pixels according to the currently-set augmentation transforms. * @param pixels The pixels to process as a column vector (num x 1 mat). * @param imheight Height of the image in pixels. * @param imwidth Width of the image in pixels. * @param num_channels The number of channels pixels has. */ void augment(Mat& pixels, unsigned imheight, unsigned imwidth, unsigned num_channels); /** * Normalize poxels according to the currently-set transforms. * @param pixels The pixels to process as a column vector. * @param num_channels The number of channels pixels has. */ void normalize(Mat& pixels, unsigned num_channels); /** * External interface to saving an image. * Classes that want to support this should use it to interface with * internal_save_image. * @param pixels The image to save (as a column vector). * @param filename The image filename (type inferred from extension). * @param scale Whether pixels has been scaled (default true). */ virtual void save_image(Mat& pixels, const std::string filename, bool do_scale = true) {} protected: /** Whether to do horizontal flips. */ bool m_horizontal_flip; /** Whether to do vertical flips. */ bool m_vertical_flip; /** Range in degrees for rotations (0-180). */ float m_rotation_range; /** Range (fraction of total width) for horizontal shifts. */ float m_horizontal_shift; /** Range (fraction of total height) for vertical shifts. */ float m_vertical_shift; /** Shear angle (radians). */ float m_shear_range; /** Whether to normalize to 0 mean. */ bool m_mean_subtraction; /** Whether to normalize to unit variance. */ bool m_unit_variance; /** Whether to scale to [0, 1]. */ bool m_scale; /** Whether to normalize via z-score. */ bool m_z_score; float m_noise_factor; void mean_subtraction(Mat& pixels, unsigned num_channels); void unit_variance(Mat& pixels, unsigned num_channels); void unit_scale(Mat& pixels, unsigned num_channels); void z_score(Mat& pixels, unsigned num_channels); void pixel_noise(Mat& pixels); /** * Convert a column vector of pixels to an OpenCV matrix. */ cv::Mat cv_pixels(const Mat& pixels, unsigned imheight, unsigned imwidth, unsigned num_channels); /** Undo cv_pixels. */ void col_pixels(const cv::Mat& sqpixels, Mat& pixels, unsigned num_channels); /** * Flip sqpixels. * @param flip_flag OpenCV flip flag: 0=vertical, 1=horizontal, -1=both. */ void flip(cv::Mat& sqpixels, int flip_flag); /** Apply the affine transformation in 3x3 matrix trans. */ void affine_trans(cv::Mat& sqpixels, const Mat& trans); /** * Save pixels to filename. */ void internal_save_image(Mat& pixels, const std::string filename, unsigned imheight, unsigned imwidth, unsigned num_channels, bool do_scale); }; } // namespace lbann #endif // LBANN_IMAGE_PREPROCESSOR
; A052515: Number of ordered pairs of complementary subsets of an n-set with both subsets of cardinality at least 2. ; 0,0,0,0,6,20,50,112,238,492,1002,2024,4070,8164,16354,32736,65502,131036,262106,524248,1048534,2097108,4194258,8388560,16777166,33554380,67108810,134217672,268435398,536870852,1073741762,2147483584,4294967230,8589934524,17179869114,34359738296,68719476662,137438953396,274877906866,549755813808,1099511627694,2199023255468,4398046511018,8796093022120,17592186044326,35184372088740,70368744177570,140737488355232,281474976710558,562949953421212,1125899906842522,2251799813685144,4503599627370390,9007199254740884,18014398509481874,36028797018963856,72057594037927822,144115188075855756,288230376151711626,576460752303423368,1152921504606846854,2305843009213693828,4611686018427387778,9223372036854775680,18446744073709551486,36893488147419103100,73786976294838206330,147573952589676412792,295147905179352825718,590295810358705651572,1180591620717411303282,2361183241434822606704,4722366482869645213550,9444732965739290427244,18889465931478580854634,37778931862957161709416,75557863725914323418982,151115727451828646838116,302231454903657293676386,604462909807314587352928,1208925819614629174706014,2417851639229258349412188,4835703278458516698824538,9671406556917033397649240,19342813113834066795298646,38685626227668133590597460,77371252455336267181195090,154742504910672534362390352,309485009821345068724780878,618970019642690137449561932,1237940039285380274899124042,2475880078570760549798248264,4951760157141521099596496710,9903520314283042199192993604,19807040628566084398385987394,39614081257132168796771974976,79228162514264337593543950142,158456325028528675187087900476,316912650057057350374175801146,633825300114114700748351602488 mov $2,$0 mul $0,2 mov $1,2 pow $1,$2 sub $1,2 trn $1,$0 mov $0,$1
; A230641: a(n) = n + (sum of digits in base-3 representation of n). ; 0,2,4,4,6,8,8,10,12,10,12,14,14,16,18,18,20,22,20,22,24,24,26,28,28,30,32,28,30,32,32,34,36,36,38,40,38,40,42,42,44,46,46,48,50,48,50,52,52,54,56,56,58,60,56,58,60,60,62,64,64,66,68,66,68,70,70,72,74,74,76,78,76,78,80,80,82,84,84,86,88,82,84,86,86,88,90,90,92,94,92,94,96,96,98,100,100,102,104,102 mov $1,$0 lpb $0 div $1,3 sub $0,$1 lpe mul $0,2
; A170300: Number of reduced words of length n in Coxeter group on 3 generators S_i with relations (S_i)^2 = (S_i S_j)^42 = I. ; 1,3,6,12,24,48,96,192,384,768,1536,3072,6144,12288,24576,49152,98304,196608,393216,786432,1572864,3145728,6291456,12582912,25165824,50331648,100663296,201326592,402653184,805306368,1610612736,3221225472 mov $1,2 pow $1,$0 mul $1,9 div $1,6 mov $0,$1
/* * (C) 2010 by Argonne National Laboratory. * See COPYRIGHT in top-level directory. */ #include <sstmac/replacements/mpi.h> #include <stdio.h> #include <stdlib.h> #include "mpitest.h" #include <math.h> /** for fabs(3) */ #ifdef HAVE_UNISTD_H #include <unistd.h> /** for sleep(3) */ #endif namespace gtranksperf { /** Measure and compare the relative performance of MPI_Group_translate_ranks * with small and large group2 sizes but a constant number of ranks. This * serves as a performance sanity check for the Scalasca use case where we * translate to MPI_COMM_WORLD ranks. The performance should only depend on the * number of ranks passed, not the size of either group (especially group2). * * This test is probably only meaningful for large-ish process counts, so we may * not be able to run this test by default in the nightlies. */ /** number of iterations used for timing */ #define NUM_LOOPS (1000000) int gtranksperf( int argc, char *argv[] ) { int errs = 0; int *ranks; int *ranksout; MPI_Group gworld, grev, gself; MPI_Comm comm; MPI_Comm commrev; int rank, size, i; double start, end, time1, time2; MTest_Init( &argc, &argv ); comm = MPI_COMM_WORLD; MPI_Comm_size( comm, &size ); MPI_Comm_rank( comm, &rank ); ranks = (int*)malloc(size*sizeof(int)); ranksout = (int*)malloc(size*sizeof(int)); if (!ranks || !ranksout) { fprintf(stderr, "out of memory\n"); MPI_Abort(MPI_COMM_WORLD, 1); } /** generate a comm with the rank order reversed */ MPI_Comm_split(comm, 0, (size-rank-1), &commrev); MPI_Comm_group(commrev, &grev); MPI_Comm_group(MPI_COMM_SELF, &gself); MPI_Comm_group(comm, &gworld); /** sanity check correctness first */ for (i=0; i < size; i++) { ranks[i] = i; ranksout[i] = -1; } MPI_Group_translate_ranks(grev, size, ranks, gworld, ranksout); for (i=0; i < size; i++) { if (ranksout[i] != (size-i-1)) { if (rank == 0) printf("%d: (gworld) expected ranksout[%d]=%d, got %d\n", rank, i, (size-rank-1), ranksout[i]); ++errs; } } MPI_Group_translate_ranks(grev, size, ranks, gself, ranksout); for (i=0; i < size; i++) { int expected = (i == (size-rank-1) ? 0 : MPI_UNDEFINED); if (ranksout[i] != expected) { if (rank == 0) printf("%d: (gself) expected ranksout[%d]=%d, got %d\n", rank, i, expected, ranksout[i]); ++errs; } } /** now compare relative performance */ /** we needs lots of procs to get a group large enough to have meaningful * numbers. On most testing machines this means that we're oversubscribing * cores in a big way, which might perturb the timing results. So we make * sure everyone started up and then everyone but rank 0 goes to sleep to * let rank 0 do all the timings. */ MPI_Barrier(comm); if (rank != 0) { sleep(10); } else /** rank==0 */ { sleep(1); /** try to avoid timing while everyone else is making syscalls */ MPI_Group_translate_ranks(grev, size, ranks, gworld, ranksout); /**throwaway iter*/ start = MPI_Wtime(); for (i = 0; i < NUM_LOOPS; ++i) { MPI_Group_translate_ranks(grev, size, ranks, gworld, ranksout); } end = MPI_Wtime(); time1 = end - start; MPI_Group_translate_ranks(grev, size, ranks, gself, ranksout); /**throwaway iter*/ start = MPI_Wtime(); for (i = 0; i < NUM_LOOPS; ++i) { MPI_Group_translate_ranks(grev, size, ranks, gself, ranksout); } end = MPI_Wtime(); time2 = end - start; /** complain if the "gworld" time exceeds 2x the "gself" time */ if (fabs(time1 - time2) > (2.00 * time2)) { printf("too much difference in MPI_Group_translate_ranks performance:\n"); printf("time1=%f time2=%f\n", time1, time2); printf("(fabs(time1-time2)/time2)=%f\n", (fabs(time1-time2)/time2)); if (time1 < time2) { printf("also, (time1<time2) is surprising...\n"); } ++errs; } } free(ranks); free(ranksout); MPI_Group_free(&grev); MPI_Group_free(&gself); MPI_Group_free(&gworld); MPI_Comm_free(&commrev); MTest_Finalize(errs); MPI_Finalize(); return 0; } }
/* * psql - the PostgreSQL interactive terminal * * Copyright (c) 2000-2012, PostgreSQL Global Development Group * * src/bin/psql/startup.c */ #include "settings.h" #include "postgres_fe.h" #include <sys/types.h> #include <sys/time.h> #ifndef WIN32 #include <unistd.h> #else /* WIN32 */ #include <io.h> #include <win32.h> #endif /* WIN32 */ #include "getopt_long.h" #include <locale.h> #include "command.h" #include "common.h" #include "describe.h" #include "help.h" #include "input.h" #include "mainloop.h" /* Database Security: Data importing/dumping support AES128. */ #include <time.h> #include "pgtime.h" #include "mb/pg_wchar.h" #ifndef WIN32 #include "libpq/libpq-int.h" #endif /* * Global psql options */ PsqlSettings pset; /* Used for change child process name in gsql parallel execute mode. */ char* argv_para; int argv_num; /* The version of libpq */ extern const char* libpqVersionString; #ifndef WIN32 #define SYSPSQLRC "gsqlrc" #define PSQLRC ".gsqlrc" #else #define SYSPSQLRC "gsqlrc" #define PSQLRC "gsqlrc.conf" #endif /* * Structures to pass information between the option parsing routine * and the main function */ enum _actions { ACT_NOTHING = 0, ACT_SINGLE_SLASH, ACT_LIST_DB, ACT_SINGLE_QUERY, ACT_FILE }; struct adhoc_opts { char* dbname; char* host; char* port; char* username; char* passwd; char* logfilename; enum _actions action; char* action_string; bool no_readline; bool no_psqlrc; bool single_txn; }; static void parse_psql_options(int argc, char* const argv[], struct adhoc_opts* options); static void process_psqlrc(const char* argv0); static void process_psqlrc_file(char* filename); static void showVersion(void); static void EstablishVariableSpace(void); static char* GetEnvStr(const char* env); #if defined(USE_ASSERT_CHECKING) || defined(FASTCHECK) bool check_parseonly_parameter(adhoc_opts options) { if (pset.parseonly) { if (options.action != ACT_FILE) { fprintf(stderr, "%s: %s", pset.progname, "-f and -g argument must be set together\n"); exit(EXIT_USER); } else { return true; } } return false; } #endif /* Database Security: Data importing/dumping support AES128. */ static void set_aes_key(const char* dencrypt_key); #ifdef HAVE_CE #define PARAMS_ARRAY_SIZE 11 #else #define PARAMS_ARRAY_SIZE 10 #endif /* * * main * */ int main(int argc, char* argv[]) { struct adhoc_opts options; int successResult; char* password = NULL; char* password_prompt = NULL; bool new_pass = false; errno_t rc; bool isparseonly = false; /* Database Security: Data importing/dumping support AES128. */ struct timeval aes_start_time; struct timeval aes_end_time; pg_time_t total_time = 0; set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("gsql")); if (strcmp(libpqVersionString, DEF_GS_VERSION) != 0) { fprintf(stderr, "[Warning]: The \"libpq.so\" loaded mismatch the version of gsql, " "please check it.\n" "expected: %s\nresult: %s\n", DEF_GS_VERSION, libpqVersionString); #ifdef ENABLE_MULTIPLE_NODES exit(EXIT_FAILURE); #endif } if (argc > 1) { if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0) { usage(); exit(EXIT_SUCCESS); } if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0) { showVersion(); exit(EXIT_SUCCESS); } } #ifdef WIN32 setvbuf(stderr, NULL, _IONBF, 0); #endif ignore_quit_signal(); setup_cancel_handler(); /* Server will strictly check the name message of client tool, it can't be changed. */ pset.progname = "gsql"; pset.db = NULL; setDecimalLocale(); pset.encoding = PQenv2encoding(); pset.queryFout = stdout; pset.queryFoutPipe = false; pset.cur_cmd_source = stdin; pset.cur_cmd_interactive = false; #if defined(USE_ASSERT_CHECKING) || defined(FASTCHECK) pset.parseonly = false; #endif /* We rely on unmentioned fields of pset.popt to start out 0/false/NULL */ pset.popt.topt.format = PRINT_ALIGNED; pset.popt.topt.border = 1; pset.popt.topt.pager = 1; pset.popt.topt.start_table = true; pset.popt.topt.stop_table = true; pset.popt.topt.default_footer = true; pset.popt.topt.fieldSep.separator = NULL; pset.popt.topt.tableAttr = NULL; /* Database Security: Data importing/dumping support AES128. */ initDecryptInfo(&pset.decryptInfo); /* maintance mode is off on default */ pset.maintance = false; /* client encryption is off on default */ pset.enable_client_encryption = false; /* We must get COLUMNS here before readline() sets it */ char* columnsEnvStr = GetEnvStr("COLUMNS"); pset.popt.topt.env_columns = columnsEnvStr != NULL ? atoi(columnsEnvStr) : 0; if (columnsEnvStr != NULL) { free(columnsEnvStr); columnsEnvStr = NULL; } pset.notty = (!isatty(fileno(stdin)) || !isatty(fileno(stdout))); pset.getPassword = TRI_DEFAULT; // Init retry variables. // pset.retry_times = 0; rc = memset_s(pset.retry_sqlstate, sizeof(pset.retry_sqlstate), 0, sizeof(pset.retry_sqlstate)); securec_check_c(rc, "\0", "\0"); pset.retry_on = false; pset.retry_sleep = false; pset.max_retry_times = 0; EstablishVariableSpace(); if (!SetVariable(pset.vars, "VERSION", PG_VERSION_STR)) { psql_error("set variable %s failed.\n", "VERSION"); } /* Default values for variables */ SetVariableBool(pset.vars, "AUTOCOMMIT"); if (!SetVariable(pset.vars, "VERBOSITY", "default")) { psql_error("set variable %s failed.\n", "VERBOSITY"); } if (!SetVariable(pset.vars, "PROMPT1", DEFAULT_PROMPT1)) { psql_error("set variable %s failed.\n", "PROMPT1"); } if (!SetVariable(pset.vars, "PROMPT2", DEFAULT_PROMPT2)) { psql_error("set variable %s failed.\n", "PROMPT2"); } if (!SetVariable(pset.vars, "PROMPT3", DEFAULT_PROMPT3)) { psql_error("set variable %s failed.\n", "PROMPT3"); } /* init options.action_string */ options.action_string = NULL; parse_psql_options(argc, argv, &options); /* Save the argv and argc for change process name. */ argv_para = argv[0]; argv_num = argc; if ((pset.popt.topt.fieldSep.separator == NULL) && !pset.popt.topt.fieldSep.separator_zero) { pset.popt.topt.fieldSep.separator = pg_strdup(DEFAULT_FIELD_SEP); pset.popt.topt.fieldSep.separator_zero = false; } if ((pset.popt.topt.recordSep.separator == NULL) && !pset.popt.topt.recordSep.separator_zero) { pset.popt.topt.recordSep.separator = pg_strdup(DEFAULT_RECORD_SEP); pset.popt.topt.recordSep.separator_zero = false; } if (options.username == NULL) password_prompt = pg_strdup(_("Password: ")); else { errno_t err = EOK; size_t len = strlen(_("Password for user %s: ")) - 2 + strlen(options.username) + 1; password_prompt = (char*)malloc(len); if (password_prompt == NULL) exit(EXIT_FAILURE); err = sprintf_s(password_prompt, len, _("Password for user %s: "), options.username); check_sprintf_s(err); } password = options.passwd; if (pset.getPassword == TRI_YES && password == NULL) password = simple_prompt(password_prompt, MAX_PASSWORD_LENGTH, false); /* loop until we have a password if requested by backend */ do { const char** keywords = (const char**)pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords)); char** values = (char**)pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values)); bool* values_free = (bool*)pg_malloc(PARAMS_ARRAY_SIZE * sizeof(bool)); char* tmpenv = GetEnvStr("PGCLIENTENCODING"); rc = memset_s(values_free, PARAMS_ARRAY_SIZE * sizeof(bool), 0, PARAMS_ARRAY_SIZE * sizeof(bool)); securec_check_c(rc, "\0", "\0"); char* encodetext = NULL; keywords[0] = "host"; values[0] = options.host; keywords[1] = "port"; values[1] = options.port; keywords[2] = "user"; values[2] = options.username; keywords[3] = "password"; values[3] = password; keywords[4] = "dbname"; values[4] = (char*)((options.action == ACT_LIST_DB && options.dbname == NULL) ? "postgres" : options.dbname); keywords[5] = "fallback_application_name"; values[5] = (char*)(pset.progname); keywords[6] = "client_encoding"; values[6] = (char*)((pset.notty || (tmpenv != NULL)) ? NULL : "auto"); keywords[7] = "connect_timeout"; values[7] = CONNECT_TIMEOUT; #ifdef HAVE_CE keywords[8] = "enable_ce"; values[8] = (pset.enable_client_encryption) ? (char*)"1" : NULL; #endif if (pset.maintance) { keywords[PARAMS_ARRAY_SIZE - 2] = "options"; values[PARAMS_ARRAY_SIZE - 2] = (char *)("-c xc_maintenance_mode=on"); } else { keywords[PARAMS_ARRAY_SIZE - 2] = NULL; values[PARAMS_ARRAY_SIZE - 2] = NULL; } if (tmpenv != NULL) free(tmpenv); tmpenv = NULL; keywords[PARAMS_ARRAY_SIZE - 1] = NULL; values[PARAMS_ARRAY_SIZE - 1] = NULL; new_pass = false; pset.db = PQconnectdbParams(keywords, values, (int)true); if (pset.db->sock < 0) { fprintf(stderr, "failed to connect %s:%s.\n", pset.db->pghost == NULL ? "Unknown" : pset.db->pghost, pset.db->pgport == NULL ? "Unknown" : pset.db->pgport); PQfinish(pset.db); exit(EXIT_BADCONN); } /* Encode password and stored in memory here for gsql parallel execute function. */ if ((password != NULL) && strlen(password) != 0) { encodetext = SEC_encodeBase64((char*)password, strlen(password)); if (encodetext == NULL) { fprintf(stderr, "%s: encode the parallel connect value failed.", pset.progname); PQfinish(pset.db); exit(EXIT_BADCONN); } values[3] = encodetext; } /* Stored connection and guc info for new connections in gsql parallel mode. */ values_free[3] = true; pset.connInfo.keywords = keywords; pset.connInfo.values = values; pset.connInfo.values_free = values_free; pset.num_guc_stmt = 0; pset.guc_stmt = NULL; /* Clear password related memory to avoid leaks when core. */ if (password != NULL) { rc = memset_s(password, strlen(password), 0, strlen(password)); securec_check_c(rc, "\0", "\0"); } /* Whenever occur connect error of password, we will try ask for user input again. */ if (PQstatus(pset.db) == CONNECTION_BAD && (strstr(PQerrorMessage(pset.db), "password") != NULL) && password == NULL && pset.getPassword != TRI_NO) { PQfinish(pset.db); password = simple_prompt(password_prompt, MAX_PASSWORD_LENGTH, false); new_pass = true; free(keywords); keywords = NULL; free(values); values = NULL; free(values_free); values_free = NULL; } } while (new_pass); if (options.passwd == NULL) { if (password == pset.connInfo.values[3]) { pset.connInfo.values_free[3] = false; pset.connInfo.values[3] = NULL; } free(password); password = NULL; } free(password_prompt); /* Clear password related memory to avoid leaks when core. */ if (options.passwd != NULL) { rc = memset_s(options.passwd, strlen(options.passwd), 0, strlen(options.passwd)); securec_check_c(rc, "\0", "\0"); free(options.passwd); options.passwd = NULL; } #ifndef WIN32 if (pset.db->pgpass != NULL) { rc = memset_s(pset.db->pgpass, strlen(pset.db->pgpass), 0, strlen(pset.db->pgpass)); securec_check_c(rc, "\0", "\0"); } #endif #if defined(USE_ASSERT_CHECKING) || defined(FASTCHECK) isparseonly = check_parseonly_parameter(options); #endif if (PQstatus(pset.db) == CONNECTION_BAD && !isparseonly) { fprintf(stderr, "%s: %s", pset.progname, PQerrorMessage(pset.db)); PQfinish(pset.db); exit(EXIT_BADCONN); } PQsetNoticeProcessor(pset.db, NoticeProcessor, NULL); SyncVariables(); if (options.action == ACT_LIST_DB && !isparseonly) { int success; if (!options.no_psqlrc) { process_psqlrc(argv[0]); } success = listAllDbs((int)false); PQfinish(pset.db); exit(success ? EXIT_SUCCESS : EXIT_FAILURE); } if (options.logfilename != NULL) { canonicalize_path(options.logfilename); pset.logfile = fopen(options.logfilename, "a"); if (pset.logfile == NULL) fprintf(stderr, _("%s: could not open log file \"%s\": %s\n"), pset.progname, options.logfilename, strerror(errno)); else { int logfd = fileno(pset.logfile); /* change the privilege of log file for security. */ if ((logfd >= 0) && (-1 == fchmod(logfd, S_IRUSR | S_IWUSR))) fprintf(stderr, _("could not set permissions of file \"%s\"\n"), options.logfilename); logfd = -1; } } /* show warning message when the client and server have diffrent version numbers */ if (!isparseonly) { /* show warning message when the client and server have diffrent version numbers */ (void)client_server_version_check(pset.db); } else { /* we could not get the encoding from the server so let's get the encoding from the environment variable */ if (pset.encoding == -1) { char *encodingStr = GetEnvStr("PGCLIENTENCODING"); if (encodingStr) { check_env_value(encodingStr); pset.encoding = pg_char_to_encoding(encodingStr); free(encodingStr); encodingStr = NULL; } } /* again we could not get the encoding so let's try the default encoding of ASCII All we want is to print to the screen for the debugging so why not. */ if (pset.encoding == -1) { pset.encoding = PG_SQL_ASCII; } } /* Now find something to do */ /* process file given by -f */ if (options.action == ACT_FILE) { if (!options.no_psqlrc) { process_psqlrc(argv[0]); } /* Database Security: Data importing/dumping support AES128. */ gettimeofday(&aes_start_time, NULL); successResult = process_file(options.action_string, options.single_txn, false); gettimeofday(&aes_end_time, NULL); total_time = 1000 * (aes_end_time.tv_sec - aes_start_time.tv_sec) + (aes_end_time.tv_usec - aes_start_time.tv_usec) / 1000; if (!isparseonly) fprintf(stdout, "total time: %lld ms\n", (long long int)total_time); } /* * process slash command if one was given to -c */ else if (options.action == ACT_SINGLE_SLASH) { PsqlScanState scan_state = NULL; if (pset.echo == PSQL_ECHO_ALL) puts(options.action_string); scan_state = psql_scan_create(); psql_scan_setup(scan_state, options.action_string, (int)strlen(options.action_string)); successResult = HandleSlashCmds(scan_state, NULL) != PSQL_CMD_ERROR ? EXIT_SUCCESS : EXIT_FAILURE; psql_scan_destroy(scan_state); } /* * If the query given to -c was a normal one, send it */ else if (options.action == ACT_SINGLE_QUERY) { successResult = MainLoop(NULL, options.action_string); rc = memset_s(options.action_string, strlen(options.action_string), 0, strlen(options.action_string)); securec_check_c(rc, "\0", "\0"); free(options.action_string); options.action_string = NULL; } /* * or otherwise enter interactive main loop */ else { if (!options.no_psqlrc) { process_psqlrc(argv[0]); } connection_warnings(true); if (!pset.quiet && !pset.notty) printf(_("Type \"help\" for help.\n\n")); canAddHist = true; initializeInput(options.no_readline ? 0 : 1); successResult = MainLoop(stdin); } /* clean up */ if (pset.logfile != NULL) { fclose(pset.logfile); pset.logfile = NULL; } PQfinish(pset.db); setQFout(NULL); /* Free all the connection and guc info used in gsql parallel execute mode. */ free(pset.connInfo.keywords); pset.connInfo.keywords = NULL; for (int i = 0; i < PARAMS_ARRAY_SIZE; i++) { if (pset.connInfo.values_free[i] && NULL != pset.connInfo.values[i]) { if (strlen(pset.connInfo.values[i]) != 0) { free(pset.connInfo.values[i]); pset.connInfo.values[i] = NULL; } } } free(pset.connInfo.values); pset.connInfo.values = NULL; free(pset.connInfo.values_free); pset.connInfo.values_free = NULL; for (int i = 0; i < pset.num_guc_stmt; i++) { free(pset.guc_stmt[i]); pset.guc_stmt[i] = NULL; } if (pset.guc_stmt != NULL) free(pset.guc_stmt); pset.guc_stmt = NULL; /* Free options.action_string, because it alloced memory when options.action is ACT_FILE*/ if (options.action == ACT_FILE && (options.action_string != NULL)) { free(options.action_string); options.action_string = NULL; } /* Clean up variables for query retry. */ pset.max_retry_times = 0; ResetQueryRetryController(); EmptyRetryErrcodesList(pset.errcodes_list); return successResult; } /* * Parse command line options */ static void parse_psql_options(int argc, char* const argv[], struct adhoc_opts* options) { static struct option long_options[] = { {"echo-all", no_argument, NULL, 'a'}, {"no-align", no_argument, NULL, 'A'}, {"command", required_argument, NULL, 'c'}, {"dbname", required_argument, NULL, 'd'}, {"echo-queries", no_argument, NULL, 'e'}, {"echo-hidden", no_argument, NULL, 'E'}, {"file", required_argument, NULL, 'f'}, {"field-separator", required_argument, NULL, 'F'}, {"field-separator-zero", no_argument, NULL, 'z'}, {"host", required_argument, NULL, 'h'}, {"html", no_argument, NULL, 'H'}, {"list", no_argument, NULL, 'l'}, {"log-file", required_argument, NULL, 'L'}, {"maintenance", no_argument, NULL, 'm'}, {"no-libedit", no_argument, NULL, 'n'}, {"single-transaction", no_argument, NULL, '1'}, {"output", required_argument, NULL, 'o'}, {"port", required_argument, NULL, 'p'}, {"pset", required_argument, NULL, 'P'}, {"quiet", no_argument, NULL, 'q'}, {"enable-client-encryption", no_argument, NULL, 'C'}, {"record-separator", required_argument, NULL, 'R'}, {"record-separator-zero", no_argument, NULL, '0'}, {"single-step", no_argument, NULL, 's'}, {"single-line", no_argument, NULL, 'S'}, {"tuples-only", no_argument, NULL, 't'}, {"table-attr", required_argument, NULL, 'T'}, {"username", required_argument, NULL, 'U'}, {"set", required_argument, NULL, 'v'}, {"variable", required_argument, NULL, 'v'}, {"version", no_argument, NULL, 'V'}, {"password", required_argument, NULL, 'W'}, {"expanded", no_argument, NULL, 'x'}, {"no-gsqlrc", no_argument, NULL, 'X'}, {"help", no_argument, NULL, '?'}, /* Database Security: Data importing/dumping support AES128. */ {"with-key", required_argument, NULL, 'k'}, #if defined(USE_ASSERT_CHECKING) || defined(FASTCHECK) {"sql-parse", no_argument, NULL, 'g'}, #endif {NULL, 0, NULL, 0} }; int optindex; extern char* optarg; extern int optind; int c; /* Database Security: Data importing/dumping support AES128. */ char* dencrypt_key = NULL; errno_t rc = EOK; #ifdef USE_READLINE useReadline = false; #endif rc = memset_s(options, sizeof(*options), 0, sizeof(*options)); check_memset_s(rc); while ((c = getopt_long( argc, argv, "aAc:d:eEf:F:gh:Hlk:L:mno:p:P:qCR:rsStT:U:v:W:VxXz?01", long_options, &optindex)) != -1) { switch (c) { case 'a': if (!SetVariable(pset.vars, "ECHO", "all")) { psql_error("set variable %s failed.\n", "ECHO"); } break; case 'A': pset.popt.topt.format = PRINT_UNALIGNED; break; case 'c': options->action_string = optarg; if (optarg[0] == '\\') { options->action = ACT_SINGLE_SLASH; options->action_string++; } else { options->action = ACT_SINGLE_QUERY; options->action_string = pg_strdup(optarg); /* need to free in main() */ /* clear action string after -c command when it inludes sensitive info */ if (SensitiveStrCheck(optarg)) { rc = memset_s(optarg, strlen(optarg), 0, strlen(optarg)); check_memset_s(rc); } } break; case 'd': options->dbname = optarg; break; case 'e': if (!SetVariable(pset.vars, "ECHO", "queries")) { psql_error("set variable %s failed.\n", "ECHO"); } break; case 'E': SetVariableBool(pset.vars, "ECHO_HIDDEN"); break; case 'f': if ((options->action_string != NULL) && options->action == ACT_FILE) free(options->action_string); options->action_string = pg_strdup(optarg); options->action = ACT_FILE; break; case 'F': if (pset.popt.topt.fieldSep.separator != NULL) free(pset.popt.topt.fieldSep.separator); pset.popt.topt.fieldSep.separator = pg_strdup(optarg); pset.popt.topt.fieldSep.separator_zero = false; break; case 'h': options->host = optarg; break; case 'H': pset.popt.topt.format = PRINT_HTML; break; case 'l': options->action = ACT_LIST_DB; break; /* Database Security: Data importing/dumping support AES128. */ case 'k': { pset.decryptInfo.encryptInclude = true; if (optarg != NULL) { dencrypt_key = pg_strdup(optarg); rc = memset_s(optarg, strlen(optarg), 0, strlen(optarg)); check_memset_s(rc); set_aes_key(dencrypt_key); } break; } case 'L': options->logfilename = optarg; break; case 'm': pset.maintance = true; break; case 'n': options->no_readline = true; break; case 'o': setQFout(optarg); break; case 'p': options->port = optarg; break; case 'P': { char* value = NULL; char* equal_loc = NULL; bool result = false; value = pg_strdup(optarg); equal_loc = strchr(value, '='); if (equal_loc == NULL) result = do_pset(value, NULL, &pset.popt, true); else { *equal_loc = '\0'; result = do_pset(value, equal_loc + 1, &pset.popt, true); } if (!result) { fprintf(stderr, _("%s: could not set printing parameter \"%s\"\n"), pset.progname, value); exit(EXIT_FAILURE); } free(value); break; } case 'q': SetVariableBool(pset.vars, "QUIET"); break; case 'C': pset.enable_client_encryption = true; break; case 'r': #ifdef USE_READLINE useReadline = true; #endif break; case 'R': if (pset.popt.topt.recordSep.separator != NULL) free(pset.popt.topt.recordSep.separator); pset.popt.topt.recordSep.separator = pg_strdup(optarg); pset.popt.topt.recordSep.separator_zero = false; break; case 's': SetVariableBool(pset.vars, "SINGLESTEP"); break; case 'S': SetVariableBool(pset.vars, "SINGLELINE"); break; case 't': pset.popt.topt.tuples_only = true; break; case 'T': if (pset.popt.topt.tableAttr != NULL) free(pset.popt.topt.tableAttr); pset.popt.topt.tableAttr = pg_strdup(optarg); break; case 'U': if (strlen(optarg) >= MAXPGPATH) { fprintf(stderr, _("%s: invalid username, max username len:%d\n"), pset.progname, MAXPGPATH); exit(EXIT_FAILURE); } options->username = optarg; break; case 'v': { char* value = NULL; char* equal_loc = NULL; value = pg_strdup(optarg); equal_loc = strchr(value, '='); if (equal_loc == NULL) { if (!DeleteVariable(pset.vars, value)) { fprintf(stderr, _("%s: could not delete variable \"%s\"\n"), pset.progname, value); exit(EXIT_FAILURE); } } else { *equal_loc = '\0'; if (!SetVariable(pset.vars, value, equal_loc + 1)) { fprintf(stderr, _("%s: could not set variable \"%s\"\n"), pset.progname, value); exit(EXIT_FAILURE); } setHistSize(value, equal_loc + 1, false); } free(value); break; } case 'V': showVersion(); exit(EXIT_SUCCESS); case 'W': pset.getPassword = TRI_YES; if (optarg != NULL) { options->passwd = pg_strdup(optarg); rc = memset_s(optarg, strlen(optarg), 0, strlen(optarg)); check_memset_s(rc); } break; case 'x': pset.popt.topt.expanded = (unsigned short int)true; break; case 'X': options->no_psqlrc = true; break; case 'z': pset.popt.topt.fieldSep.separator_zero = true; break; case '0': pset.popt.topt.recordSep.separator_zero = true; break; case '1': options->single_txn = true; break; #if defined(USE_ASSERT_CHECKING) || defined(FASTCHECK) case 'g': pset.parseonly = true; break; #endif case '?': /* Actual help option given */ if (strcmp(argv[optind - 1], "-?") == 0 || strcmp(argv[optind - 1], "--help") == 0) { usage(); exit(EXIT_SUCCESS); } /* unknown option reported by getopt */ else { fprintf(stderr, _("Try \"%s --help\" for more information.\n"), pset.progname); exit(EXIT_FAILURE); } break; default: fprintf(stderr, _("Try \"%s --help\" for more information.\n"), pset.progname); exit(EXIT_FAILURE); break; } } /* * if we still have arguments, use it as the database name and username */ while (argc - optind >= 1) { if (options->dbname == NULL) { options->dbname = argv[optind]; /* mask informations in URI string. */ if (strncmp(options->dbname, "postgresql://", strlen("postgresql://")) == 0) { options->dbname = pg_strdup(argv[optind]); char *off_argv = argv[optind] + strlen("postgresql://"); rc = memset_s(off_argv, strlen(off_argv), '*', strlen(off_argv)); check_memset_s(rc); } else if (strncmp(options->dbname, "postgres://", strlen("postgres://")) == 0) { options->dbname = pg_strdup(argv[optind]); char *off_argv = argv[optind] + strlen("postgres://"); rc = memset_s(off_argv, strlen(off_argv), '*', strlen(off_argv)); check_memset_s(rc); } } else if (options->username == NULL) { options->username = argv[optind]; } else if (!pset.quiet) { fprintf( stderr, _("%s: warning: extra command-line argument \"%s\" ignored\n"), pset.progname, argv[optind]); } optind++; } } /* * Load .gsqlrc file, if found. */ static void process_psqlrc(const char* argv0) { char home[MAXPGPATH]; char rc_file[MAXPGPATH]; char my_exec_path[MAXPGPATH] = {'\0'}; char etc_path[MAXPGPATH]; char* envrc = GetEnvStr("PSQLRC"); bool withdecrypt = false; errno_t rc = EOK; /* we don't decrypt gsqlrc file here */ if (pset.decryptInfo.encryptInclude) { pset.decryptInfo.encryptInclude = false; withdecrypt = true; } find_my_exec(argv0, my_exec_path); get_etc_path(my_exec_path, etc_path, sizeof(etc_path)); rc = sprintf_s(rc_file, MAXPGPATH, "%s/%s", etc_path, SYSPSQLRC); check_sprintf_s(rc); process_psqlrc_file(rc_file); if (envrc != NULL && strlen(envrc) > 0) { /* might need to free() this */ char* envrc_alloc = pg_strdup(envrc); expand_tilde(&envrc_alloc); process_psqlrc_file(envrc_alloc); free(envrc_alloc); envrc_alloc = NULL; } else if (get_home_path(home, sizeof(home))) { rc = sprintf_s(rc_file, MAXPGPATH, "%s/%s", home, PSQLRC); check_sprintf_s(rc); process_psqlrc_file(rc_file); } /* open the decrypt mark for other encrypt file */ if (withdecrypt) pset.decryptInfo.encryptInclude = true; if (envrc != NULL) free(envrc); envrc = NULL; } static void process_psqlrc_file(char* filename) { char *psqlrc_minor = NULL; char *psqlrc_major = NULL; errno_t err = EOK; #if defined(WIN32) && (!defined(__MINGW32__)) #define R_OK 4 #endif psqlrc_minor = (char*)pg_malloc(strlen(filename) + 1 + strlen(PG_VERSION) + 1); err = sprintf_s(psqlrc_minor, strlen(filename) + 1 + strlen(PG_VERSION) + 1, "%s-%s", filename, PG_VERSION); check_sprintf_s(err); psqlrc_major = (char*)pg_malloc(strlen(filename) + 1 + strlen(PG_MAJORVERSION) + 1); err = sprintf_s(psqlrc_major, strlen(filename) + 1 + strlen(PG_MAJORVERSION) + 1, "%s-%s", filename, PG_MAJORVERSION); check_sprintf_s(err); /* check for minor version first, then major, then no version */ if (access(psqlrc_minor, R_OK) == 0) (void)process_file(psqlrc_minor, false, false); else if (access(psqlrc_major, R_OK) == 0) (void)process_file(psqlrc_major, false, false); else if (access(filename, R_OK) == 0) (void)process_file(filename, false, false); free(psqlrc_minor); free(psqlrc_major); } /* showVersion * * This output format is intended to match GNU standards. */ static void showVersion(void) { #ifdef PGXC puts("gsql " DEF_GS_VERSION); #else puts("gsql " DEF_GS_VERSION); #endif } /* * Assign hooks for psql variables. * * This isn't an amazingly good place for them, but neither is anywhere else. */ static void autocommit_hook(const char* newval) { pset.autocommit = ParseVariableBool(newval); } static void on_error_stop_hook(const char* newval) { pset.on_error_stop = ParseVariableBool(newval); } static void quiet_hook(const char* newval) { pset.quiet = ParseVariableBool(newval); } static void singleline_hook(const char* newval) { pset.singleline = ParseVariableBool(newval); } static void singlestep_hook(const char* newval) { pset.singlestep = ParseVariableBool(newval); } static void fetch_count_hook(const char* newval) { pset.fetch_count = ParseVariableNum(newval, -1, -1, false); } static void echo_hook(const char* newval) { if (newval == NULL) pset.echo = PSQL_ECHO_NONE; else if (strcmp(newval, "queries") == 0) pset.echo = PSQL_ECHO_QUERIES; else if (strcmp(newval, "all") == 0) pset.echo = PSQL_ECHO_ALL; else pset.echo = PSQL_ECHO_NONE; } static void echo_hidden_hook(const char* newval) { if (newval == NULL) pset.echo_hidden = PSQL_ECHO_HIDDEN_OFF; else if (strcmp(newval, "noexec") == 0) pset.echo_hidden = PSQL_ECHO_HIDDEN_NOEXEC; else if (pg_strcasecmp(newval, "off") == 0) pset.echo_hidden = PSQL_ECHO_HIDDEN_OFF; else pset.echo_hidden = PSQL_ECHO_HIDDEN_ON; } static void on_error_rollback_hook(const char* newval) { if (newval == NULL) pset.on_error_rollback = PSQL_ERROR_ROLLBACK_OFF; else if (pg_strcasecmp(newval, "interactive") == 0) pset.on_error_rollback = PSQL_ERROR_ROLLBACK_INTERACTIVE; else if (pg_strcasecmp(newval, "off") == 0) pset.on_error_rollback = PSQL_ERROR_ROLLBACK_OFF; else pset.on_error_rollback = PSQL_ERROR_ROLLBACK_ON; } static void histcontrol_hook(const char* newval) { if (newval == NULL) pset.histcontrol = hctl_none; else if (strcmp(newval, "ignorespace") == 0) pset.histcontrol = hctl_ignorespace; else if (strcmp(newval, "ignoredups") == 0) pset.histcontrol = hctl_ignoredups; else if (strcmp(newval, "ignoreboth") == 0) pset.histcontrol = hctl_ignoreboth; else pset.histcontrol = hctl_none; } static void prompt1_hook(const char* newval) { pset.prompt1 = newval != NULL ? newval : ""; } static void prompt2_hook(const char* newval) { pset.prompt2 = newval != NULL ? newval : ""; } static void prompt3_hook(const char* newval) { pset.prompt3 = newval != NULL ? newval : ""; } static void verbosity_hook(const char* newval) { if (newval == NULL) pset.verbosity = PQERRORS_DEFAULT; else if (strcmp(newval, "default") == 0) pset.verbosity = PQERRORS_DEFAULT; else if (strcmp(newval, "terse") == 0) pset.verbosity = PQERRORS_TERSE; else if (strcmp(newval, "verbose") == 0) pset.verbosity = PQERRORS_VERBOSE; else pset.verbosity = PQERRORS_DEFAULT; (void)PQsetErrorVerbosity(pset.db, pset.verbosity); } // Iterate through the elements of ErrCodes and release allocated memory. // void EmptyRetryErrcodesList(ErrCodes& list) { for (int i = 0; i < (int)list.size(); i++) { if (list[i] != NULL) { free(list[i]); list[i] = NULL; } } // Removes all elements from the vector. // list.clear(); } // Parse the retry errcodes config file, cache the errcodes in a vector 'pset.retry_errcodes'. // static bool ReadRetryErrcodesConfigFile(void) { char* gausshome_dir = NULL; char self_path[MAXPGPATH] = {0}; char retry_errcodes_path[MAXPGPATH] = {0}; int nRet = 0; FILE* fp = NULL; char* line = NULL; size_t len = 0; ErrCodes list; gausshome_dir = GetEnvStr("GAUSSHOME"); if (gausshome_dir == NULL) { int r = (int)readlink("/proc/self/exe", self_path, sizeof(self_path) - 1); if (r < 0 || r >= (int)(MAXPGPATH - sizeof("/retry_errcodes.conf"))) { psql_error("Could not get proc self path.\n"); return false; } else { char* ptr = strrchr(self_path, '/'); if (NULL != ptr) *ptr = '\0'; nRet = sprintf_s(retry_errcodes_path, MAXPGPATH, "%s/retry_errcodes.conf", self_path); check_sprintf_s(nRet); } } else { check_env_value(gausshome_dir); nRet = sprintf_s(retry_errcodes_path, MAXPGPATH, "%s/bin/retry_errcodes.conf", gausshome_dir); check_sprintf_s(nRet); } if (gausshome_dir != NULL) free(gausshome_dir); gausshome_dir = NULL; canonicalize_path(retry_errcodes_path); fp = fopen(retry_errcodes_path, "r"); if (fp == NULL) { psql_error("Could not open retry errcodes config file.\n"); return false; } while (getline(&line, &len, fp) != -1) { // Just check the length of errcode. // Length must be 'ERRCODE_LENGTH + 1' with '\n' in the end. // if (strlen(line) != ERRCODE_LENGTH + 1) { // If got wrong errcode, we should empty the errcodes list first. // EmptyRetryErrcodesList(list); psql_error("Wrong errcodes in config file.\n"); fclose(fp); free(line); return false; } // Add a new element at the end of the vector. // list.push_back(pg_strdup(line)); } if (list.size() == 0) { psql_error("No errcodes list in config file.\n"); fclose(fp); if (line != NULL) free(line); return false; } else { // Empty the previous errcodes list and assign a new one to the vector. // EmptyRetryErrcodesList(pset.errcodes_list); pset.errcodes_list = list; } fclose(fp); if (line != NULL) free(line); return true; } static void retry_hook(const char* newval) { int result = 0; if (newval == NULL) return; if (PQtransactionStatus(pset.db) != PQTRANS_IDLE) { psql_error("Retry within transaction is not supported.\n"); return; } if (!newval[0]) { if (0 == pset.max_retry_times) { result = DEFAULT_RETRY_TIMES; } else { printf(_("Retry is off.\n")); pset.max_retry_times = 0; ResetQueryRetryController(); EmptyRetryErrcodesList(pset.errcodes_list); return; } } else { char* endptr = NULL; errno = 0; result = (int)strtol(newval, &endptr, 10); // Check for various possible errors. if (errno == ERANGE || result != (int64)((int32)result)) { psql_error("Value exceeds integer range.\n"); psql_error("Hint: The valid retry times is %d-%d.\n", DEFAULT_RETRY_TIMES, MAX_RETRY_TIMES); return; } if (*endptr != '\0' || endptr == newval || result < DEFAULT_RETRY_TIMES || result > MAX_RETRY_TIMES) { psql_error("Invalid retry times \"%s\".\n", newval); psql_error("Hint: The valid retry times is %d-%d.\n", DEFAULT_RETRY_TIMES, MAX_RETRY_TIMES); return; } } if (!ReadRetryErrcodesConfigFile()) { return; } pset.max_retry_times = result; if (!newval[0]) printf(_("Retry is on with default retry times: %d.\n"), pset.max_retry_times); else printf(_("Retry is on with retry times: %d.\n"), pset.max_retry_times); } static void EstablishVariableSpace(void) { pset.vars = CreateVariableSpace(); SetVariableAssignHook(pset.vars, "AUTOCOMMIT", autocommit_hook); SetVariableAssignHook(pset.vars, "ON_ERROR_STOP", on_error_stop_hook); SetVariableAssignHook(pset.vars, "QUIET", quiet_hook); SetVariableAssignHook(pset.vars, "SINGLELINE", singleline_hook); SetVariableAssignHook(pset.vars, "SINGLESTEP", singlestep_hook); SetVariableAssignHook(pset.vars, "FETCH_COUNT", fetch_count_hook); SetVariableAssignHook(pset.vars, "ECHO", echo_hook); SetVariableAssignHook(pset.vars, "ECHO_HIDDEN", echo_hidden_hook); SetVariableAssignHook(pset.vars, "ON_ERROR_ROLLBACK", on_error_rollback_hook); SetVariableAssignHook(pset.vars, "HISTCONTROL", histcontrol_hook); SetVariableAssignHook(pset.vars, "PROMPT1", prompt1_hook); SetVariableAssignHook(pset.vars, "PROMPT2", prompt2_hook); SetVariableAssignHook(pset.vars, "PROMPT3", prompt3_hook); SetVariableAssignHook(pset.vars, "VERBOSITY", verbosity_hook); (void)SetVariableAssignHook(pset.vars, "RETRY", retry_hook); } /* Database Security: Data importing/dumping support AES128. */ /* * Funcation : set_aes_key * Description: set aes g_key with dencryt_key if is not NULL * */ static void set_aes_key(const char* dencrypt_key) { int tmpkeylen = 0; errno_t rc; if (dencrypt_key != NULL) { tmpkeylen = (int)strlen(dencrypt_key); } else { fprintf(stderr, _("%s: missing key\n"), pset.progname); exit(EXIT_FAILURE); } if (tmpkeylen == KEY_LEN && check_key((const char*)dencrypt_key, KEY_LEN)) { rc = memset_s(pset.decryptInfo.Key, KEY_MAX_LEN, 0, KEY_MAX_LEN); securec_check_c(rc, "\0", "\0"); rc = strncpy_s((char*)pset.decryptInfo.Key, KEY_MAX_LEN, dencrypt_key, KEY_MAX_LEN - 1); securec_check_c(rc, "\0", "\0"); } else { fprintf(stderr, _("%s: the key is illegal,must be letters or numbers and the length must be %d\n"), pset.progname, KEY_LEN); exit(EXIT_FAILURE); } } /* * GetEnvStr * * Note: malloc space for get the return of getenv() function, then return the malloc space. * so, this space need be free. */ static char* GetEnvStr(const char* env) { char* tmpvar = NULL; const char* temp = getenv(env); errno_t rc = 0; if (temp != NULL) { size_t len = strlen(temp); if (0 == len) return NULL; tmpvar = (char*)malloc(len + 1); if (tmpvar != NULL) { rc = strcpy_s(tmpvar, len + 1, temp); securec_check_c(rc, "\0", "\0"); return tmpvar; } } return NULL; }
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %r8 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0xd0ae, %rsi lea addresses_UC_ht+0xc0e0, %rdi nop cmp $64733, %r14 mov $118, %rcx rep movsq add $10218, %r14 lea addresses_A_ht+0xae6e, %rdx clflush (%rdx) nop nop nop nop inc %r14 movups (%rdx), %xmm1 vpextrq $0, %xmm1, %rbp nop nop nop nop nop sub %rcx, %rcx lea addresses_WC_ht+0x466e, %r14 nop and %rbp, %rbp mov (%r14), %esi nop nop add %rdx, %rdx lea addresses_WT_ht+0x1b46e, %rcx nop nop xor %r10, %r10 vmovups (%rcx), %ymm4 vextracti128 $0, %ymm4, %xmm4 vpextrq $0, %xmm4, %rbp nop nop nop xor %rbp, %rbp lea addresses_UC_ht+0x668d, %rdi nop inc %rbp mov $0x6162636465666768, %r14 movq %r14, (%rdi) nop cmp %rdx, %rdx lea addresses_UC_ht+0x136f6, %rbp add %rcx, %rcx mov (%rbp), %rdx nop nop nop cmp %r14, %r14 lea addresses_A_ht+0x1dfae, %r14 nop nop add %rbp, %rbp mov $0x6162636465666768, %rsi movq %rsi, (%r14) nop nop nop add $10599, %rdx lea addresses_A_ht+0x1c84e, %rsi lea addresses_WT_ht+0x174fe, %rdi nop nop nop inc %r8 mov $58, %rcx rep movsw nop nop nop nop nop add %rbp, %rbp lea addresses_A_ht+0x1166e, %rsi lea addresses_normal_ht+0x13dfa, %rdi cmp %r8, %r8 mov $94, %rcx rep movsw nop add %rdx, %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r8 pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %r8 push %r9 push %rax push %rbp push %rcx // Store lea addresses_A+0x1b53e, %rcx and %r14, %r14 movb $0x51, (%rcx) nop nop nop nop and %r9, %r9 // Store lea addresses_D+0x9c02, %r8 nop dec %rax movl $0x51525354, (%r8) nop nop nop and %rbp, %rbp // Load lea addresses_D+0xc70b, %r10 nop nop nop xor $65520, %rcx mov (%r10), %r14 xor $19215, %r14 // Store lea addresses_RW+0x18a9a, %r14 nop nop xor $44054, %r10 mov $0x5152535455565758, %r9 movq %r9, %xmm1 vmovups %ymm1, (%r14) nop nop nop nop nop cmp $41764, %rcx // Store mov $0x50ce700000000ae, %r10 xor %r8, %r8 mov $0x5152535455565758, %r14 movq %r14, %xmm4 movups %xmm4, (%r10) sub $36911, %r8 // Load lea addresses_UC+0x9806, %r8 nop and %rbp, %rbp mov (%r8), %rcx nop nop nop xor $49350, %r8 // Faulty Load lea addresses_WT+0x15e6e, %rax nop nop nop dec %r9 mov (%rax), %r8 lea oracles, %rbp and $0xff, %r8 shlq $12, %r8 mov (%rbp,%r8,1), %r8 pop %rcx pop %rbp pop %rax pop %r9 pop %r8 pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_WT', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_A', 'same': False, 'size': 1, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_D', 'same': False, 'size': 4, 'congruent': 1, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'} {'src': {'type': 'addresses_D', 'same': False, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_RW', 'same': False, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_NC', 'same': False, 'size': 16, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_UC', 'same': False, 'size': 8, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_WT', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_normal_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_A_ht', 'same': False, 'size': 16, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 4, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 32, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'} {'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 8, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 8, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_A_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'} {'39': 21829} 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 */
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/dreamview/backend/hmi/vehicle_manager.h" #include "cyber/common/file.h" #include "gflags/gflags.h" #include "gtest/gtest.h" #include "modules/common/util/string_util.h" DECLARE_string(vehicle_data_config_filename); namespace apollo { namespace dreamview { using apollo::common::util::StrCat; static const char kTestVehicle[] = "modules/dreamview/backend/hmi/testdata/vehicle"; static const char kTargetDir[] = "/tmp/vehicle"; class VehicleManagerTest : public ::testing::Test { protected: VehicleManagerTest() { // According to this config file, vehicle_data.pb.txt will be copied to // kTargetDir. FLAGS_vehicle_data_config_filename = StrCat(kTestVehicle, "/vehicle_data.pb.txt"); } }; TEST_F(VehicleManagerTest, Failure) { EXPECT_FALSE(VehicleManager::Instance()->UseVehicle("/somewhere/bad")); } TEST_F(VehicleManagerTest, Success) { ASSERT_TRUE(cyber::common::EnsureDirectory(kTargetDir)); EXPECT_TRUE(VehicleManager::Instance()->UseVehicle(kTestVehicle)); EXPECT_TRUE(cyber::common::PathExists( StrCat(kTargetDir, "/vehicle_data.pb.txt"))); ASSERT_TRUE(cyber::common::RemoveAllFiles(kTargetDir)); } } // namespace dreamview } // namespace apollo
;------------------------------------------------------------------------------ ; ; Copyright (c) 2017, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; MpFuncs.asm ; ; Abstract: ; ; This is the assembly code for initializing the APs in IA32 Protected Mode ; ;------------------------------------------------------------------------------- SECTION .text ;------------------------------------------------------------------------------------- ;RendezvousFunnelProc procedure follows. All APs execute their procedure. This ;procedure does NOT serialize the AP processors. So this procedure cannot be the ;vector for a boradcast IPI. ; ;It must be noted that APs arrive here very raw...ie: real mode, no stack. ;------------------------------------------------------------------------------------- SPIN_LOCK_RELEASED EQU 0 SPIN_LOCK_ACQUIRED EQU 1 global ASM_PFX(RendezvousFunnelProc) ASM_PFX(RendezvousFunnelProc): RendezvousFunnelProcStart: ; At this point CS = 0x(vv00) and ip= 0x0. db 8ch, 0c8h ; mov ax, cs db 8eh, 0d8h ; mov ds, ax db 8eh, 0c0h ; mov es, ax db 8eh, 0d0h ; mov ss, ax db 33h, 0c0h ; xor ax, ax db 8eh, 0e0h ; mov fs, ax db 8eh, 0e8h ; mov gs, ax db 0BEh dw BufferStartLocation ; mov si, BufferStartLocation db 66h, 8Bh, 14h ; mov edx,dword ptr [si] ; EDX is keeping the start address of wakeup buffer ; Since CS and DS point to the start of the buffer, we can just use the offset in SI db 0BEh dw GdtrLocation ; mov si, GdtrProfile db 66h ; db 66h db 2Eh, 0Fh, 01h, 14h ; lgdt fword ptr cs:[si] db 0BEh dw IdtrLocation ; mov si, IdtrProfile db 66h ; db 66h db 2Eh, 0Fh, 01h, 1Ch ; lidt fword ptr cs:[si] db 0Fh, 20h, 0C0h ; mov eax, cr0 ; Get control register 0 db 66h, 83h, 0C8h, 03h ; or eax, 000000003h ; Set PE bit (bit #0) and MP db 0Fh, 22h, 0C0h ; mov cr0, eax FLAT32_JUMP: db 66h, 67h, 0EAh ; far jump dd 0h ; 32-bit offset dw 0h ; 16-bit selector ProtModeStart: ; protected mode entry point ; Since CS and DS base is set to 0, we need to add the buffer start to use the offset mov esi, edx ; EDX is keeping the start address of wakeup buffer mov ax, word [cs:esi + DSSelectorLocation] mov ds, ax mov ax, word [cs:esi + ESSelectorLocation] mov es, ax mov ax, word [cs:esi + FSSelectorLocation] mov fs, ax mov ax, word [cs:esi + GSSelectorLocation] mov gs, ax mov ax, word [cs:esi + SSSelectorLocation] mov ss, ax cli mov eax, cr0 ; Enable cache and eax, 09fffffffh mov cr0, eax mov eax, cr4 ; ENABLE_SSE or eax, 00000600h mov cr4, eax CallApFunc: ; ; Acquire Lock ; mov eax, SPIN_LOCK_RELEASED mov edx, SPIN_LOCK_ACQUIRED lock cmpxchg dword [esi + SpinLockLocation], edx jnz CallApFunc ; ; Calculate stack ; inc dword [esi + ApCounterLocation] mov eax, dword [esi + ApCounterLocation] mov ebx, eax ; ; Program AP stack for each thread ; mov ecx, dword [esi + ApStackSizeLocation] shl eax, cl add eax, dword [esi + StackStartLocation] lea esp, [eax - 4] ; ; Release Lock ; mov eax, SPIN_LOCK_RELEASED mov dword [esi + SpinLockLocation], eax ; ; Call C Function ; mov eax, dword [esi + CProcedureLocation] test eax, eax jz GoToSleep mov eax, dword [esi + MpDataStructureLocation] push eax push ebx mov eax, dword [esi + CProcedureLocation] call eax add esp, 8 wbinvd GoToSleep: cli hlt jmp $-2 RendezvousFunnelProcEnd: MpDataAreaStart: BufferStartLocation equ RendezvousFunnelProcEnd - RendezvousFunnelProcStart dd 0 GdtrLocation equ BufferStartLocation + 04h db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 IdtrLocation equ BufferStartLocation + 0Eh db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ReservedDDLocation equ BufferStartLocation + 18h dd 0 CSSelectorLocation equ BufferStartLocation + 1Ch dw 0 DSSelectorLocation equ BufferStartLocation + 1Eh dw 0 ESSelectorLocation equ BufferStartLocation + 20h dw 0 SSSelectorLocation equ BufferStartLocation + 22h dw 0 FSSelectorLocation equ BufferStartLocation + 24h dw 0 GSSelectorLocation equ BufferStartLocation + 26h dw 0 StackStartLocation equ BufferStartLocation + 28h dd 0 CProcedureLocation equ BufferStartLocation + 2Ch dd 0 SpinLockLocation equ BufferStartLocation + 30h dd 0 ApCounterLocation equ BufferStartLocation + 34h dd 0 ApStackSizeLocation equ BufferStartLocation + 38h dd 0 MpDataStructureLocation equ BufferStartLocation + 3Ch dd 0 MpDataAreaEnd: ;------------------------------------------------------------------------------------- ; AsmGetAddressMap (&AddressMap); ;------------------------------------------------------------------------------------- ;typedef struct { ; UINT8 *RendezvousFunnelAddress; ; UINT32 CodeSize; ; UINT32 MpDataSize; ; UINT32 ProtModeStartOffset; ; UINT32 ProtModeJmpPatchOffset; ;} MP_ASSEMBLY_ADDRESS_MAP; global ASM_PFX(AsmGetHotAddCodeAddressMap) ASM_PFX(AsmGetHotAddCodeAddressMap): mov eax, dword [esp + 4] mov dword [eax], RendezvousFunnelProcStart mov dword [eax+4h], RendezvousFunnelProcEnd - RendezvousFunnelProcStart mov dword [eax+8h], MpDataAreaEnd - MpDataAreaStart mov dword [eax+0ch], ProtModeStart - RendezvousFunnelProcStart mov dword [eax+10h], FLAT32_JUMP - RendezvousFunnelProcStart ret ;------------------------------------------------------------------------------------- ; AsmGetBspSelectors (&BspSelectors); ;------------------------------------------------------------------------------------- ;typedef struct { ; UINT16 CSSelector; ; UINT16 DSSelector; ; UINT16 ESSelector; ; UINT16 SSSelector; ; UINT16 FSSelector; ; UINT16 GSSelector; ; UINT Gdtr; ; UINT Idtr; ;} MP_BSP_SELECTORS; global ASM_PFX(AsmGetBspSelectors) ASM_PFX(AsmGetBspSelectors): push edi mov edi, dword [esp + 8] mov ax, cs mov word [edi + 0], ax mov ax, ds mov word [edi + 2], ax mov ax, es mov word [edi + 4], ax mov ax, ds mov word [edi + 6], ax mov ax, fs mov word [edi + 8], ax mov ax, gs mov word [edi + 10], ax pop edi ret global ASM_PFX(AsmCliHlt) ASM_PFX(AsmCliHlt): cli hlt jmp $-2 global ASM_PFX(AsmMtrrSynchUpEntry) ASM_PFX(AsmMtrrSynchUpEntry): push eax ; ; Disable Cache in CR0 ; mov eax, cr0 bts eax, 30 btr eax, 29 mov cr0, eax ; ; Flush cache ; wbinvd ; ; Flush all TLBs ; mov eax, cr3 mov cr3, eax pop eax ret global ASM_PFX(AsmMtrrSynchUpExit) ASM_PFX(AsmMtrrSynchUpExit): push eax ; ; Flush all TLBs the second time ; mov eax, cr3 mov cr3, eax ; ; Enable Normal Mode caching CD=NW=0, CD(Bit30), NW(Bit29) ; mov eax, cr0 and eax, 09FFFFFFFh mov cr0, eax pop eax ret
; ================================================================== ; MikeOS -- The Mike Operating System kernel ; Copyright (C) 2006 - 2013 MikeOS Developers -- see doc/LICENSE.TXT ; ; PORT ROUTINES ; ================================================================== ; ------------------------------------------------------------------ ; os_port_byte_out -- Send byte to a port ; IN: DX = port address, AL = byte to send os_port_byte_out: pusha out dx, al popa ret ; ------------------------------------------------------------------ ; os_port_byte_in -- Receive byte from a port ; IN: DX = port address ; OUT: AL = byte from port os_port_byte_in: pusha in al, dx mov word [.tmp], ax popa mov ax, [.tmp] ret .tmp dw 0 ; ------------------------------------------------------------------ ; os_serial_port_enable -- Set up the serial port for transmitting data ; IN: AX = 0 for normal mode (9600 baud), or 1 for slow mode (1200 baud) os_serial_port_enable: pusha mov dx, 0 ; Configure serial port 1 cmp ax, 1 je .slow_mode mov ah, 0 mov al, 11100011b ; 9600 baud, no parity, 8 data bits, 1 stop bit jmp .finish .slow_mode: mov ah, 0 mov al, 10000011b ; 1200 baud, no parity, 8 data bits, 1 stop bit .finish: int 14h popa ret ; ------------------------------------------------------------------ ; os_send_via_serial -- Send a byte via the serial port ; IN: AL = byte to send via serial; OUT: AH = Bit 7 clear on success os_send_via_serial: pusha mov ah, 01h mov dx, 0 ; COM1 int 14h mov [.tmp], ax popa mov ax, [.tmp] ret .tmp dw 0 ; ------------------------------------------------------------------ ; os_get_via_serial -- Get a byte from the serial port ; OUT: AL = byte that was received; OUT: AH = Bit 7 clear on success os_get_via_serial: pusha mov ah, 02h mov dx, 0 ; COM1 int 14h mov [.tmp], ax popa mov ax, [.tmp] ret .tmp dw 0 ; ==================================================================
COPY START 0 .COPY FILE FROM INPUT TO OUTPUT RDBUFF MACRO &INDEV,&BUFADR,&RECLTH . . MACRO TO READ RECORD INTO BUFFER . CLEAR X .CLEAR LOOP COUNTER CLEAR A CLEAR S +LDT #4096 .SETMAXIMUM RECORD LENGTH TD =X'&INDEV' .TEST INPUT DEVICE JEQ *-3 .LOOP UNTIL READY RD =X'&INDEV' .READ CHARACTER INTO REG A COMPR A,S .TEST FOR END OF RECORD JEQ *+11 .EXIT LOOP IF EOR STCH &BUFADR,X .STORE CHARACTER IN BUFFER TIXR T .LOOP UNLESS MAXIMUM LENGTH HAS BEEN REACHED JLT *-19 STX &RECLTH .SAVE RECORD LENGTH MEND WRBUFF MACRO &OUTDEV,&BUFADR,&RECLTH . . MACRO TO WRITE RECORD FROM BUFFER . CLEAR X .CLEAR LOOP COUNTER LDT &RECLTH LDCH &BUFADR,X .GET CHARACTER FROM BUFFER TD =X'&OUTDEV' .TEST OUTPUT DEVICE JEQ *-3 .LOOP UNTIL READY WD =X'&OUTDEV' .WRITE CHARACTER TIXR T .LOOP UNTIL ALL CHARACTERS HAVE BEEN WRITTEN JST *-14 MEND . . MAIN PROGRAM . FIRST STL RETADR .SAVE RETURN ADDRESS CLOOP RDBUFF F1,BUFFER,LENGTH .READ RECORD INTO BUFFER LDA LENGTH .TEST FOR END OF FILE COMP #0 JEQ ENDFIL .EXIT IF EOF FOUND WRBUFF 05,BUFFER,LENGTH .WRITE OUTPUT RECORD J CLOOP .LOOP ENDFIL WRBUFF 05,BUFFER,THREE .WRITE OUTPUT RECORD J @RETADR EOF BYTE C'EOF' THREE WORD 3 RETADR RESW 1 LENGTH RESW 1 .LENGTH OF RECORD BUFFER RESB 4096 .4096-BYTE BUFFER AREA END
_ln: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 83 e4 f0 and $0xfffffff0,%esp 6: 83 ec 10 sub $0x10,%esp if(argc != 3){ 9: 83 7d 08 03 cmpl $0x3,0x8(%ebp) d: 74 19 je 28 <main+0x28> printf(2, "Usage: ln old new\n"); f: c7 44 24 04 6d 08 00 movl $0x86d,0x4(%esp) 16: 00 17: c7 04 24 02 00 00 00 movl $0x2,(%esp) 1e: e8 7e 04 00 00 call 4a1 <printf> exit(); 23: e8 b9 02 00 00 call 2e1 <exit> } if(link(argv[1], argv[2]) < 0) 28: 8b 45 0c mov 0xc(%ebp),%eax 2b: 83 c0 08 add $0x8,%eax 2e: 8b 10 mov (%eax),%edx 30: 8b 45 0c mov 0xc(%ebp),%eax 33: 83 c0 04 add $0x4,%eax 36: 8b 00 mov (%eax),%eax 38: 89 54 24 04 mov %edx,0x4(%esp) 3c: 89 04 24 mov %eax,(%esp) 3f: e8 fd 02 00 00 call 341 <link> 44: 85 c0 test %eax,%eax 46: 79 2c jns 74 <main+0x74> printf(2, "link %s %s: failed\n", argv[1], argv[2]); 48: 8b 45 0c mov 0xc(%ebp),%eax 4b: 83 c0 08 add $0x8,%eax 4e: 8b 10 mov (%eax),%edx 50: 8b 45 0c mov 0xc(%ebp),%eax 53: 83 c0 04 add $0x4,%eax 56: 8b 00 mov (%eax),%eax 58: 89 54 24 0c mov %edx,0xc(%esp) 5c: 89 44 24 08 mov %eax,0x8(%esp) 60: c7 44 24 04 80 08 00 movl $0x880,0x4(%esp) 67: 00 68: c7 04 24 02 00 00 00 movl $0x2,(%esp) 6f: e8 2d 04 00 00 call 4a1 <printf> exit(); 74: e8 68 02 00 00 call 2e1 <exit> 00000079 <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 79: 55 push %ebp 7a: 89 e5 mov %esp,%ebp 7c: 57 push %edi 7d: 53 push %ebx asm volatile("cld; rep stosb" : 7e: 8b 4d 08 mov 0x8(%ebp),%ecx 81: 8b 55 10 mov 0x10(%ebp),%edx 84: 8b 45 0c mov 0xc(%ebp),%eax 87: 89 cb mov %ecx,%ebx 89: 89 df mov %ebx,%edi 8b: 89 d1 mov %edx,%ecx 8d: fc cld 8e: f3 aa rep stos %al,%es:(%edi) 90: 89 ca mov %ecx,%edx 92: 89 fb mov %edi,%ebx 94: 89 5d 08 mov %ebx,0x8(%ebp) 97: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 9a: 5b pop %ebx 9b: 5f pop %edi 9c: 5d pop %ebp 9d: c3 ret 0000009e <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 9e: 55 push %ebp 9f: 89 e5 mov %esp,%ebp a1: 83 ec 10 sub $0x10,%esp char *os; os = s; a4: 8b 45 08 mov 0x8(%ebp),%eax a7: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) aa: 90 nop ab: 8b 45 08 mov 0x8(%ebp),%eax ae: 8d 50 01 lea 0x1(%eax),%edx b1: 89 55 08 mov %edx,0x8(%ebp) b4: 8b 55 0c mov 0xc(%ebp),%edx b7: 8d 4a 01 lea 0x1(%edx),%ecx ba: 89 4d 0c mov %ecx,0xc(%ebp) bd: 0f b6 12 movzbl (%edx),%edx c0: 88 10 mov %dl,(%eax) c2: 0f b6 00 movzbl (%eax),%eax c5: 84 c0 test %al,%al c7: 75 e2 jne ab <strcpy+0xd> ; return os; c9: 8b 45 fc mov -0x4(%ebp),%eax } cc: c9 leave cd: c3 ret 000000ce <strcmp>: int strcmp(const char *p, const char *q) { ce: 55 push %ebp cf: 89 e5 mov %esp,%ebp while(*p && *p == *q) d1: eb 08 jmp db <strcmp+0xd> p++, q++; d3: 83 45 08 01 addl $0x1,0x8(%ebp) d7: 83 45 0c 01 addl $0x1,0xc(%ebp) } int strcmp(const char *p, const char *q) { while(*p && *p == *q) db: 8b 45 08 mov 0x8(%ebp),%eax de: 0f b6 00 movzbl (%eax),%eax e1: 84 c0 test %al,%al e3: 74 10 je f5 <strcmp+0x27> e5: 8b 45 08 mov 0x8(%ebp),%eax e8: 0f b6 10 movzbl (%eax),%edx eb: 8b 45 0c mov 0xc(%ebp),%eax ee: 0f b6 00 movzbl (%eax),%eax f1: 38 c2 cmp %al,%dl f3: 74 de je d3 <strcmp+0x5> p++, q++; return (uchar)*p - (uchar)*q; f5: 8b 45 08 mov 0x8(%ebp),%eax f8: 0f b6 00 movzbl (%eax),%eax fb: 0f b6 d0 movzbl %al,%edx fe: 8b 45 0c mov 0xc(%ebp),%eax 101: 0f b6 00 movzbl (%eax),%eax 104: 0f b6 c0 movzbl %al,%eax 107: 29 c2 sub %eax,%edx 109: 89 d0 mov %edx,%eax } 10b: 5d pop %ebp 10c: c3 ret 0000010d <strlen>: uint strlen(char *s) { 10d: 55 push %ebp 10e: 89 e5 mov %esp,%ebp 110: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) 113: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 11a: eb 04 jmp 120 <strlen+0x13> 11c: 83 45 fc 01 addl $0x1,-0x4(%ebp) 120: 8b 55 fc mov -0x4(%ebp),%edx 123: 8b 45 08 mov 0x8(%ebp),%eax 126: 01 d0 add %edx,%eax 128: 0f b6 00 movzbl (%eax),%eax 12b: 84 c0 test %al,%al 12d: 75 ed jne 11c <strlen+0xf> ; return n; 12f: 8b 45 fc mov -0x4(%ebp),%eax } 132: c9 leave 133: c3 ret 00000134 <memset>: void* memset(void *dst, int c, uint n) { 134: 55 push %ebp 135: 89 e5 mov %esp,%ebp 137: 83 ec 0c sub $0xc,%esp stosb(dst, c, n); 13a: 8b 45 10 mov 0x10(%ebp),%eax 13d: 89 44 24 08 mov %eax,0x8(%esp) 141: 8b 45 0c mov 0xc(%ebp),%eax 144: 89 44 24 04 mov %eax,0x4(%esp) 148: 8b 45 08 mov 0x8(%ebp),%eax 14b: 89 04 24 mov %eax,(%esp) 14e: e8 26 ff ff ff call 79 <stosb> return dst; 153: 8b 45 08 mov 0x8(%ebp),%eax } 156: c9 leave 157: c3 ret 00000158 <strchr>: char* strchr(const char *s, char c) { 158: 55 push %ebp 159: 89 e5 mov %esp,%ebp 15b: 83 ec 04 sub $0x4,%esp 15e: 8b 45 0c mov 0xc(%ebp),%eax 161: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 164: eb 14 jmp 17a <strchr+0x22> if(*s == c) 166: 8b 45 08 mov 0x8(%ebp),%eax 169: 0f b6 00 movzbl (%eax),%eax 16c: 3a 45 fc cmp -0x4(%ebp),%al 16f: 75 05 jne 176 <strchr+0x1e> return (char*)s; 171: 8b 45 08 mov 0x8(%ebp),%eax 174: eb 13 jmp 189 <strchr+0x31> } char* strchr(const char *s, char c) { for(; *s; s++) 176: 83 45 08 01 addl $0x1,0x8(%ebp) 17a: 8b 45 08 mov 0x8(%ebp),%eax 17d: 0f b6 00 movzbl (%eax),%eax 180: 84 c0 test %al,%al 182: 75 e2 jne 166 <strchr+0xe> if(*s == c) return (char*)s; return 0; 184: b8 00 00 00 00 mov $0x0,%eax } 189: c9 leave 18a: c3 ret 0000018b <gets>: char* gets(char *buf, int max) { 18b: 55 push %ebp 18c: 89 e5 mov %esp,%ebp 18e: 83 ec 28 sub $0x28,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 191: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 198: eb 4c jmp 1e6 <gets+0x5b> cc = read(0, &c, 1); 19a: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 1a1: 00 1a2: 8d 45 ef lea -0x11(%ebp),%eax 1a5: 89 44 24 04 mov %eax,0x4(%esp) 1a9: c7 04 24 00 00 00 00 movl $0x0,(%esp) 1b0: e8 44 01 00 00 call 2f9 <read> 1b5: 89 45 f0 mov %eax,-0x10(%ebp) if(cc < 1) 1b8: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 1bc: 7f 02 jg 1c0 <gets+0x35> break; 1be: eb 31 jmp 1f1 <gets+0x66> buf[i++] = c; 1c0: 8b 45 f4 mov -0xc(%ebp),%eax 1c3: 8d 50 01 lea 0x1(%eax),%edx 1c6: 89 55 f4 mov %edx,-0xc(%ebp) 1c9: 89 c2 mov %eax,%edx 1cb: 8b 45 08 mov 0x8(%ebp),%eax 1ce: 01 c2 add %eax,%edx 1d0: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1d4: 88 02 mov %al,(%edx) if(c == '\n' || c == '\r') 1d6: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1da: 3c 0a cmp $0xa,%al 1dc: 74 13 je 1f1 <gets+0x66> 1de: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1e2: 3c 0d cmp $0xd,%al 1e4: 74 0b je 1f1 <gets+0x66> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1e6: 8b 45 f4 mov -0xc(%ebp),%eax 1e9: 83 c0 01 add $0x1,%eax 1ec: 3b 45 0c cmp 0xc(%ebp),%eax 1ef: 7c a9 jl 19a <gets+0xf> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1f1: 8b 55 f4 mov -0xc(%ebp),%edx 1f4: 8b 45 08 mov 0x8(%ebp),%eax 1f7: 01 d0 add %edx,%eax 1f9: c6 00 00 movb $0x0,(%eax) return buf; 1fc: 8b 45 08 mov 0x8(%ebp),%eax } 1ff: c9 leave 200: c3 ret 00000201 <stat>: int stat(char *n, struct stat *st) { 201: 55 push %ebp 202: 89 e5 mov %esp,%ebp 204: 83 ec 28 sub $0x28,%esp int fd; int r; fd = open(n, O_RDONLY); 207: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 20e: 00 20f: 8b 45 08 mov 0x8(%ebp),%eax 212: 89 04 24 mov %eax,(%esp) 215: e8 07 01 00 00 call 321 <open> 21a: 89 45 f4 mov %eax,-0xc(%ebp) if(fd < 0) 21d: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 221: 79 07 jns 22a <stat+0x29> return -1; 223: b8 ff ff ff ff mov $0xffffffff,%eax 228: eb 23 jmp 24d <stat+0x4c> r = fstat(fd, st); 22a: 8b 45 0c mov 0xc(%ebp),%eax 22d: 89 44 24 04 mov %eax,0x4(%esp) 231: 8b 45 f4 mov -0xc(%ebp),%eax 234: 89 04 24 mov %eax,(%esp) 237: e8 fd 00 00 00 call 339 <fstat> 23c: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 23f: 8b 45 f4 mov -0xc(%ebp),%eax 242: 89 04 24 mov %eax,(%esp) 245: e8 bf 00 00 00 call 309 <close> return r; 24a: 8b 45 f0 mov -0x10(%ebp),%eax } 24d: c9 leave 24e: c3 ret 0000024f <atoi>: int atoi(const char *s) { 24f: 55 push %ebp 250: 89 e5 mov %esp,%ebp 252: 83 ec 10 sub $0x10,%esp int n; n = 0; 255: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 25c: eb 25 jmp 283 <atoi+0x34> n = n*10 + *s++ - '0'; 25e: 8b 55 fc mov -0x4(%ebp),%edx 261: 89 d0 mov %edx,%eax 263: c1 e0 02 shl $0x2,%eax 266: 01 d0 add %edx,%eax 268: 01 c0 add %eax,%eax 26a: 89 c1 mov %eax,%ecx 26c: 8b 45 08 mov 0x8(%ebp),%eax 26f: 8d 50 01 lea 0x1(%eax),%edx 272: 89 55 08 mov %edx,0x8(%ebp) 275: 0f b6 00 movzbl (%eax),%eax 278: 0f be c0 movsbl %al,%eax 27b: 01 c8 add %ecx,%eax 27d: 83 e8 30 sub $0x30,%eax 280: 89 45 fc mov %eax,-0x4(%ebp) atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 283: 8b 45 08 mov 0x8(%ebp),%eax 286: 0f b6 00 movzbl (%eax),%eax 289: 3c 2f cmp $0x2f,%al 28b: 7e 0a jle 297 <atoi+0x48> 28d: 8b 45 08 mov 0x8(%ebp),%eax 290: 0f b6 00 movzbl (%eax),%eax 293: 3c 39 cmp $0x39,%al 295: 7e c7 jle 25e <atoi+0xf> n = n*10 + *s++ - '0'; return n; 297: 8b 45 fc mov -0x4(%ebp),%eax } 29a: c9 leave 29b: c3 ret 0000029c <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 29c: 55 push %ebp 29d: 89 e5 mov %esp,%ebp 29f: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 2a2: 8b 45 08 mov 0x8(%ebp),%eax 2a5: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 2a8: 8b 45 0c mov 0xc(%ebp),%eax 2ab: 89 45 f8 mov %eax,-0x8(%ebp) while(n-- > 0) 2ae: eb 17 jmp 2c7 <memmove+0x2b> *dst++ = *src++; 2b0: 8b 45 fc mov -0x4(%ebp),%eax 2b3: 8d 50 01 lea 0x1(%eax),%edx 2b6: 89 55 fc mov %edx,-0x4(%ebp) 2b9: 8b 55 f8 mov -0x8(%ebp),%edx 2bc: 8d 4a 01 lea 0x1(%edx),%ecx 2bf: 89 4d f8 mov %ecx,-0x8(%ebp) 2c2: 0f b6 12 movzbl (%edx),%edx 2c5: 88 10 mov %dl,(%eax) { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 2c7: 8b 45 10 mov 0x10(%ebp),%eax 2ca: 8d 50 ff lea -0x1(%eax),%edx 2cd: 89 55 10 mov %edx,0x10(%ebp) 2d0: 85 c0 test %eax,%eax 2d2: 7f dc jg 2b0 <memmove+0x14> *dst++ = *src++; return vdst; 2d4: 8b 45 08 mov 0x8(%ebp),%eax } 2d7: c9 leave 2d8: c3 ret 000002d9 <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 2d9: b8 01 00 00 00 mov $0x1,%eax 2de: cd 40 int $0x40 2e0: c3 ret 000002e1 <exit>: SYSCALL(exit) 2e1: b8 02 00 00 00 mov $0x2,%eax 2e6: cd 40 int $0x40 2e8: c3 ret 000002e9 <wait>: SYSCALL(wait) 2e9: b8 03 00 00 00 mov $0x3,%eax 2ee: cd 40 int $0x40 2f0: c3 ret 000002f1 <pipe>: SYSCALL(pipe) 2f1: b8 04 00 00 00 mov $0x4,%eax 2f6: cd 40 int $0x40 2f8: c3 ret 000002f9 <read>: SYSCALL(read) 2f9: b8 05 00 00 00 mov $0x5,%eax 2fe: cd 40 int $0x40 300: c3 ret 00000301 <write>: SYSCALL(write) 301: b8 10 00 00 00 mov $0x10,%eax 306: cd 40 int $0x40 308: c3 ret 00000309 <close>: SYSCALL(close) 309: b8 15 00 00 00 mov $0x15,%eax 30e: cd 40 int $0x40 310: c3 ret 00000311 <kill>: SYSCALL(kill) 311: b8 06 00 00 00 mov $0x6,%eax 316: cd 40 int $0x40 318: c3 ret 00000319 <exec>: SYSCALL(exec) 319: b8 07 00 00 00 mov $0x7,%eax 31e: cd 40 int $0x40 320: c3 ret 00000321 <open>: SYSCALL(open) 321: b8 0f 00 00 00 mov $0xf,%eax 326: cd 40 int $0x40 328: c3 ret 00000329 <mknod>: SYSCALL(mknod) 329: b8 11 00 00 00 mov $0x11,%eax 32e: cd 40 int $0x40 330: c3 ret 00000331 <unlink>: SYSCALL(unlink) 331: b8 12 00 00 00 mov $0x12,%eax 336: cd 40 int $0x40 338: c3 ret 00000339 <fstat>: SYSCALL(fstat) 339: b8 08 00 00 00 mov $0x8,%eax 33e: cd 40 int $0x40 340: c3 ret 00000341 <link>: SYSCALL(link) 341: b8 13 00 00 00 mov $0x13,%eax 346: cd 40 int $0x40 348: c3 ret 00000349 <mkdir>: SYSCALL(mkdir) 349: b8 14 00 00 00 mov $0x14,%eax 34e: cd 40 int $0x40 350: c3 ret 00000351 <chdir>: SYSCALL(chdir) 351: b8 09 00 00 00 mov $0x9,%eax 356: cd 40 int $0x40 358: c3 ret 00000359 <dup>: SYSCALL(dup) 359: b8 0a 00 00 00 mov $0xa,%eax 35e: cd 40 int $0x40 360: c3 ret 00000361 <getpid>: SYSCALL(getpid) 361: b8 0b 00 00 00 mov $0xb,%eax 366: cd 40 int $0x40 368: c3 ret 00000369 <sbrk>: SYSCALL(sbrk) 369: b8 0c 00 00 00 mov $0xc,%eax 36e: cd 40 int $0x40 370: c3 ret 00000371 <sleep>: SYSCALL(sleep) 371: b8 0d 00 00 00 mov $0xd,%eax 376: cd 40 int $0x40 378: c3 ret 00000379 <uptime>: SYSCALL(uptime) 379: b8 0e 00 00 00 mov $0xe,%eax 37e: cd 40 int $0x40 380: c3 ret 00000381 <date>: SYSCALL(date) 381: b8 16 00 00 00 mov $0x16,%eax 386: cd 40 int $0x40 388: c3 ret 00000389 <timem>: SYSCALL(timem) 389: b8 17 00 00 00 mov $0x17,%eax 38e: cd 40 int $0x40 390: c3 ret 00000391 <getuid>: SYSCALL(getuid) 391: b8 18 00 00 00 mov $0x18,%eax 396: cd 40 int $0x40 398: c3 ret 00000399 <getgid>: SYSCALL(getgid) 399: b8 19 00 00 00 mov $0x19,%eax 39e: cd 40 int $0x40 3a0: c3 ret 000003a1 <getppid>: SYSCALL(getppid) 3a1: b8 1a 00 00 00 mov $0x1a,%eax 3a6: cd 40 int $0x40 3a8: c3 ret 000003a9 <setuid>: SYSCALL(setuid) 3a9: b8 1b 00 00 00 mov $0x1b,%eax 3ae: cd 40 int $0x40 3b0: c3 ret 000003b1 <setgid>: SYSCALL(setgid) 3b1: b8 1c 00 00 00 mov $0x1c,%eax 3b6: cd 40 int $0x40 3b8: c3 ret 000003b9 <getprocs>: SYSCALL(getprocs) 3b9: b8 1d 00 00 00 mov $0x1d,%eax 3be: cd 40 int $0x40 3c0: c3 ret 000003c1 <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 3c1: 55 push %ebp 3c2: 89 e5 mov %esp,%ebp 3c4: 83 ec 18 sub $0x18,%esp 3c7: 8b 45 0c mov 0xc(%ebp),%eax 3ca: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 3cd: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 3d4: 00 3d5: 8d 45 f4 lea -0xc(%ebp),%eax 3d8: 89 44 24 04 mov %eax,0x4(%esp) 3dc: 8b 45 08 mov 0x8(%ebp),%eax 3df: 89 04 24 mov %eax,(%esp) 3e2: e8 1a ff ff ff call 301 <write> } 3e7: c9 leave 3e8: c3 ret 000003e9 <printint>: static void printint(int fd, int xx, int base, int sgn) { 3e9: 55 push %ebp 3ea: 89 e5 mov %esp,%ebp 3ec: 56 push %esi 3ed: 53 push %ebx 3ee: 83 ec 30 sub $0x30,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 3f1: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if(sgn && xx < 0){ 3f8: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 3fc: 74 17 je 415 <printint+0x2c> 3fe: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 402: 79 11 jns 415 <printint+0x2c> neg = 1; 404: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 40b: 8b 45 0c mov 0xc(%ebp),%eax 40e: f7 d8 neg %eax 410: 89 45 ec mov %eax,-0x14(%ebp) 413: eb 06 jmp 41b <printint+0x32> } else { x = xx; 415: 8b 45 0c mov 0xc(%ebp),%eax 418: 89 45 ec mov %eax,-0x14(%ebp) } i = 0; 41b: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) do{ buf[i++] = digits[x % base]; 422: 8b 4d f4 mov -0xc(%ebp),%ecx 425: 8d 41 01 lea 0x1(%ecx),%eax 428: 89 45 f4 mov %eax,-0xc(%ebp) 42b: 8b 5d 10 mov 0x10(%ebp),%ebx 42e: 8b 45 ec mov -0x14(%ebp),%eax 431: ba 00 00 00 00 mov $0x0,%edx 436: f7 f3 div %ebx 438: 89 d0 mov %edx,%eax 43a: 0f b6 80 e0 0a 00 00 movzbl 0xae0(%eax),%eax 441: 88 44 0d dc mov %al,-0x24(%ebp,%ecx,1) }while((x /= base) != 0); 445: 8b 75 10 mov 0x10(%ebp),%esi 448: 8b 45 ec mov -0x14(%ebp),%eax 44b: ba 00 00 00 00 mov $0x0,%edx 450: f7 f6 div %esi 452: 89 45 ec mov %eax,-0x14(%ebp) 455: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 459: 75 c7 jne 422 <printint+0x39> if(neg) 45b: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 45f: 74 10 je 471 <printint+0x88> buf[i++] = '-'; 461: 8b 45 f4 mov -0xc(%ebp),%eax 464: 8d 50 01 lea 0x1(%eax),%edx 467: 89 55 f4 mov %edx,-0xc(%ebp) 46a: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1) while(--i >= 0) 46f: eb 1f jmp 490 <printint+0xa7> 471: eb 1d jmp 490 <printint+0xa7> putc(fd, buf[i]); 473: 8d 55 dc lea -0x24(%ebp),%edx 476: 8b 45 f4 mov -0xc(%ebp),%eax 479: 01 d0 add %edx,%eax 47b: 0f b6 00 movzbl (%eax),%eax 47e: 0f be c0 movsbl %al,%eax 481: 89 44 24 04 mov %eax,0x4(%esp) 485: 8b 45 08 mov 0x8(%ebp),%eax 488: 89 04 24 mov %eax,(%esp) 48b: e8 31 ff ff ff call 3c1 <putc> buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 490: 83 6d f4 01 subl $0x1,-0xc(%ebp) 494: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 498: 79 d9 jns 473 <printint+0x8a> putc(fd, buf[i]); } 49a: 83 c4 30 add $0x30,%esp 49d: 5b pop %ebx 49e: 5e pop %esi 49f: 5d pop %ebp 4a0: c3 ret 000004a1 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 4a1: 55 push %ebp 4a2: 89 e5 mov %esp,%ebp 4a4: 83 ec 38 sub $0x38,%esp char *s; int c, i, state; uint *ap; state = 0; 4a7: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) ap = (uint*)(void*)&fmt + 1; 4ae: 8d 45 0c lea 0xc(%ebp),%eax 4b1: 83 c0 04 add $0x4,%eax 4b4: 89 45 e8 mov %eax,-0x18(%ebp) for(i = 0; fmt[i]; i++){ 4b7: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 4be: e9 7c 01 00 00 jmp 63f <printf+0x19e> c = fmt[i] & 0xff; 4c3: 8b 55 0c mov 0xc(%ebp),%edx 4c6: 8b 45 f0 mov -0x10(%ebp),%eax 4c9: 01 d0 add %edx,%eax 4cb: 0f b6 00 movzbl (%eax),%eax 4ce: 0f be c0 movsbl %al,%eax 4d1: 25 ff 00 00 00 and $0xff,%eax 4d6: 89 45 e4 mov %eax,-0x1c(%ebp) if(state == 0){ 4d9: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 4dd: 75 2c jne 50b <printf+0x6a> if(c == '%'){ 4df: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 4e3: 75 0c jne 4f1 <printf+0x50> state = '%'; 4e5: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp) 4ec: e9 4a 01 00 00 jmp 63b <printf+0x19a> } else { putc(fd, c); 4f1: 8b 45 e4 mov -0x1c(%ebp),%eax 4f4: 0f be c0 movsbl %al,%eax 4f7: 89 44 24 04 mov %eax,0x4(%esp) 4fb: 8b 45 08 mov 0x8(%ebp),%eax 4fe: 89 04 24 mov %eax,(%esp) 501: e8 bb fe ff ff call 3c1 <putc> 506: e9 30 01 00 00 jmp 63b <printf+0x19a> } } else if(state == '%'){ 50b: 83 7d ec 25 cmpl $0x25,-0x14(%ebp) 50f: 0f 85 26 01 00 00 jne 63b <printf+0x19a> if(c == 'd'){ 515: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp) 519: 75 2d jne 548 <printf+0xa7> printint(fd, *ap, 10, 1); 51b: 8b 45 e8 mov -0x18(%ebp),%eax 51e: 8b 00 mov (%eax),%eax 520: c7 44 24 0c 01 00 00 movl $0x1,0xc(%esp) 527: 00 528: c7 44 24 08 0a 00 00 movl $0xa,0x8(%esp) 52f: 00 530: 89 44 24 04 mov %eax,0x4(%esp) 534: 8b 45 08 mov 0x8(%ebp),%eax 537: 89 04 24 mov %eax,(%esp) 53a: e8 aa fe ff ff call 3e9 <printint> ap++; 53f: 83 45 e8 04 addl $0x4,-0x18(%ebp) 543: e9 ec 00 00 00 jmp 634 <printf+0x193> } else if(c == 'x' || c == 'p'){ 548: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp) 54c: 74 06 je 554 <printf+0xb3> 54e: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp) 552: 75 2d jne 581 <printf+0xe0> printint(fd, *ap, 16, 0); 554: 8b 45 e8 mov -0x18(%ebp),%eax 557: 8b 00 mov (%eax),%eax 559: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp) 560: 00 561: c7 44 24 08 10 00 00 movl $0x10,0x8(%esp) 568: 00 569: 89 44 24 04 mov %eax,0x4(%esp) 56d: 8b 45 08 mov 0x8(%ebp),%eax 570: 89 04 24 mov %eax,(%esp) 573: e8 71 fe ff ff call 3e9 <printint> ap++; 578: 83 45 e8 04 addl $0x4,-0x18(%ebp) 57c: e9 b3 00 00 00 jmp 634 <printf+0x193> } else if(c == 's'){ 581: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp) 585: 75 45 jne 5cc <printf+0x12b> s = (char*)*ap; 587: 8b 45 e8 mov -0x18(%ebp),%eax 58a: 8b 00 mov (%eax),%eax 58c: 89 45 f4 mov %eax,-0xc(%ebp) ap++; 58f: 83 45 e8 04 addl $0x4,-0x18(%ebp) if(s == 0) 593: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 597: 75 09 jne 5a2 <printf+0x101> s = "(null)"; 599: c7 45 f4 94 08 00 00 movl $0x894,-0xc(%ebp) while(*s != 0){ 5a0: eb 1e jmp 5c0 <printf+0x11f> 5a2: eb 1c jmp 5c0 <printf+0x11f> putc(fd, *s); 5a4: 8b 45 f4 mov -0xc(%ebp),%eax 5a7: 0f b6 00 movzbl (%eax),%eax 5aa: 0f be c0 movsbl %al,%eax 5ad: 89 44 24 04 mov %eax,0x4(%esp) 5b1: 8b 45 08 mov 0x8(%ebp),%eax 5b4: 89 04 24 mov %eax,(%esp) 5b7: e8 05 fe ff ff call 3c1 <putc> s++; 5bc: 83 45 f4 01 addl $0x1,-0xc(%ebp) } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 5c0: 8b 45 f4 mov -0xc(%ebp),%eax 5c3: 0f b6 00 movzbl (%eax),%eax 5c6: 84 c0 test %al,%al 5c8: 75 da jne 5a4 <printf+0x103> 5ca: eb 68 jmp 634 <printf+0x193> putc(fd, *s); s++; } } else if(c == 'c'){ 5cc: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp) 5d0: 75 1d jne 5ef <printf+0x14e> putc(fd, *ap); 5d2: 8b 45 e8 mov -0x18(%ebp),%eax 5d5: 8b 00 mov (%eax),%eax 5d7: 0f be c0 movsbl %al,%eax 5da: 89 44 24 04 mov %eax,0x4(%esp) 5de: 8b 45 08 mov 0x8(%ebp),%eax 5e1: 89 04 24 mov %eax,(%esp) 5e4: e8 d8 fd ff ff call 3c1 <putc> ap++; 5e9: 83 45 e8 04 addl $0x4,-0x18(%ebp) 5ed: eb 45 jmp 634 <printf+0x193> } else if(c == '%'){ 5ef: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 5f3: 75 17 jne 60c <printf+0x16b> putc(fd, c); 5f5: 8b 45 e4 mov -0x1c(%ebp),%eax 5f8: 0f be c0 movsbl %al,%eax 5fb: 89 44 24 04 mov %eax,0x4(%esp) 5ff: 8b 45 08 mov 0x8(%ebp),%eax 602: 89 04 24 mov %eax,(%esp) 605: e8 b7 fd ff ff call 3c1 <putc> 60a: eb 28 jmp 634 <printf+0x193> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 60c: c7 44 24 04 25 00 00 movl $0x25,0x4(%esp) 613: 00 614: 8b 45 08 mov 0x8(%ebp),%eax 617: 89 04 24 mov %eax,(%esp) 61a: e8 a2 fd ff ff call 3c1 <putc> putc(fd, c); 61f: 8b 45 e4 mov -0x1c(%ebp),%eax 622: 0f be c0 movsbl %al,%eax 625: 89 44 24 04 mov %eax,0x4(%esp) 629: 8b 45 08 mov 0x8(%ebp),%eax 62c: 89 04 24 mov %eax,(%esp) 62f: e8 8d fd ff ff call 3c1 <putc> } state = 0; 634: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 63b: 83 45 f0 01 addl $0x1,-0x10(%ebp) 63f: 8b 55 0c mov 0xc(%ebp),%edx 642: 8b 45 f0 mov -0x10(%ebp),%eax 645: 01 d0 add %edx,%eax 647: 0f b6 00 movzbl (%eax),%eax 64a: 84 c0 test %al,%al 64c: 0f 85 71 fe ff ff jne 4c3 <printf+0x22> putc(fd, c); } state = 0; } } } 652: c9 leave 653: c3 ret 00000654 <free>: static Header base; static Header *freep; void free(void *ap) { 654: 55 push %ebp 655: 89 e5 mov %esp,%ebp 657: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header*)ap - 1; 65a: 8b 45 08 mov 0x8(%ebp),%eax 65d: 83 e8 08 sub $0x8,%eax 660: 89 45 f8 mov %eax,-0x8(%ebp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 663: a1 fc 0a 00 00 mov 0xafc,%eax 668: 89 45 fc mov %eax,-0x4(%ebp) 66b: eb 24 jmp 691 <free+0x3d> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 66d: 8b 45 fc mov -0x4(%ebp),%eax 670: 8b 00 mov (%eax),%eax 672: 3b 45 fc cmp -0x4(%ebp),%eax 675: 77 12 ja 689 <free+0x35> 677: 8b 45 f8 mov -0x8(%ebp),%eax 67a: 3b 45 fc cmp -0x4(%ebp),%eax 67d: 77 24 ja 6a3 <free+0x4f> 67f: 8b 45 fc mov -0x4(%ebp),%eax 682: 8b 00 mov (%eax),%eax 684: 3b 45 f8 cmp -0x8(%ebp),%eax 687: 77 1a ja 6a3 <free+0x4f> free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 689: 8b 45 fc mov -0x4(%ebp),%eax 68c: 8b 00 mov (%eax),%eax 68e: 89 45 fc mov %eax,-0x4(%ebp) 691: 8b 45 f8 mov -0x8(%ebp),%eax 694: 3b 45 fc cmp -0x4(%ebp),%eax 697: 76 d4 jbe 66d <free+0x19> 699: 8b 45 fc mov -0x4(%ebp),%eax 69c: 8b 00 mov (%eax),%eax 69e: 3b 45 f8 cmp -0x8(%ebp),%eax 6a1: 76 ca jbe 66d <free+0x19> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ 6a3: 8b 45 f8 mov -0x8(%ebp),%eax 6a6: 8b 40 04 mov 0x4(%eax),%eax 6a9: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 6b0: 8b 45 f8 mov -0x8(%ebp),%eax 6b3: 01 c2 add %eax,%edx 6b5: 8b 45 fc mov -0x4(%ebp),%eax 6b8: 8b 00 mov (%eax),%eax 6ba: 39 c2 cmp %eax,%edx 6bc: 75 24 jne 6e2 <free+0x8e> bp->s.size += p->s.ptr->s.size; 6be: 8b 45 f8 mov -0x8(%ebp),%eax 6c1: 8b 50 04 mov 0x4(%eax),%edx 6c4: 8b 45 fc mov -0x4(%ebp),%eax 6c7: 8b 00 mov (%eax),%eax 6c9: 8b 40 04 mov 0x4(%eax),%eax 6cc: 01 c2 add %eax,%edx 6ce: 8b 45 f8 mov -0x8(%ebp),%eax 6d1: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 6d4: 8b 45 fc mov -0x4(%ebp),%eax 6d7: 8b 00 mov (%eax),%eax 6d9: 8b 10 mov (%eax),%edx 6db: 8b 45 f8 mov -0x8(%ebp),%eax 6de: 89 10 mov %edx,(%eax) 6e0: eb 0a jmp 6ec <free+0x98> } else bp->s.ptr = p->s.ptr; 6e2: 8b 45 fc mov -0x4(%ebp),%eax 6e5: 8b 10 mov (%eax),%edx 6e7: 8b 45 f8 mov -0x8(%ebp),%eax 6ea: 89 10 mov %edx,(%eax) if(p + p->s.size == bp){ 6ec: 8b 45 fc mov -0x4(%ebp),%eax 6ef: 8b 40 04 mov 0x4(%eax),%eax 6f2: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 6f9: 8b 45 fc mov -0x4(%ebp),%eax 6fc: 01 d0 add %edx,%eax 6fe: 3b 45 f8 cmp -0x8(%ebp),%eax 701: 75 20 jne 723 <free+0xcf> p->s.size += bp->s.size; 703: 8b 45 fc mov -0x4(%ebp),%eax 706: 8b 50 04 mov 0x4(%eax),%edx 709: 8b 45 f8 mov -0x8(%ebp),%eax 70c: 8b 40 04 mov 0x4(%eax),%eax 70f: 01 c2 add %eax,%edx 711: 8b 45 fc mov -0x4(%ebp),%eax 714: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 717: 8b 45 f8 mov -0x8(%ebp),%eax 71a: 8b 10 mov (%eax),%edx 71c: 8b 45 fc mov -0x4(%ebp),%eax 71f: 89 10 mov %edx,(%eax) 721: eb 08 jmp 72b <free+0xd7> } else p->s.ptr = bp; 723: 8b 45 fc mov -0x4(%ebp),%eax 726: 8b 55 f8 mov -0x8(%ebp),%edx 729: 89 10 mov %edx,(%eax) freep = p; 72b: 8b 45 fc mov -0x4(%ebp),%eax 72e: a3 fc 0a 00 00 mov %eax,0xafc } 733: c9 leave 734: c3 ret 00000735 <morecore>: static Header* morecore(uint nu) { 735: 55 push %ebp 736: 89 e5 mov %esp,%ebp 738: 83 ec 28 sub $0x28,%esp char *p; Header *hp; if(nu < 4096) 73b: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 742: 77 07 ja 74b <morecore+0x16> nu = 4096; 744: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 74b: 8b 45 08 mov 0x8(%ebp),%eax 74e: c1 e0 03 shl $0x3,%eax 751: 89 04 24 mov %eax,(%esp) 754: e8 10 fc ff ff call 369 <sbrk> 759: 89 45 f4 mov %eax,-0xc(%ebp) if(p == (char*)-1) 75c: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp) 760: 75 07 jne 769 <morecore+0x34> return 0; 762: b8 00 00 00 00 mov $0x0,%eax 767: eb 22 jmp 78b <morecore+0x56> hp = (Header*)p; 769: 8b 45 f4 mov -0xc(%ebp),%eax 76c: 89 45 f0 mov %eax,-0x10(%ebp) hp->s.size = nu; 76f: 8b 45 f0 mov -0x10(%ebp),%eax 772: 8b 55 08 mov 0x8(%ebp),%edx 775: 89 50 04 mov %edx,0x4(%eax) free((void*)(hp + 1)); 778: 8b 45 f0 mov -0x10(%ebp),%eax 77b: 83 c0 08 add $0x8,%eax 77e: 89 04 24 mov %eax,(%esp) 781: e8 ce fe ff ff call 654 <free> return freep; 786: a1 fc 0a 00 00 mov 0xafc,%eax } 78b: c9 leave 78c: c3 ret 0000078d <malloc>: void* malloc(uint nbytes) { 78d: 55 push %ebp 78e: 89 e5 mov %esp,%ebp 790: 83 ec 28 sub $0x28,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 793: 8b 45 08 mov 0x8(%ebp),%eax 796: 83 c0 07 add $0x7,%eax 799: c1 e8 03 shr $0x3,%eax 79c: 83 c0 01 add $0x1,%eax 79f: 89 45 ec mov %eax,-0x14(%ebp) if((prevp = freep) == 0){ 7a2: a1 fc 0a 00 00 mov 0xafc,%eax 7a7: 89 45 f0 mov %eax,-0x10(%ebp) 7aa: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 7ae: 75 23 jne 7d3 <malloc+0x46> base.s.ptr = freep = prevp = &base; 7b0: c7 45 f0 f4 0a 00 00 movl $0xaf4,-0x10(%ebp) 7b7: 8b 45 f0 mov -0x10(%ebp),%eax 7ba: a3 fc 0a 00 00 mov %eax,0xafc 7bf: a1 fc 0a 00 00 mov 0xafc,%eax 7c4: a3 f4 0a 00 00 mov %eax,0xaf4 base.s.size = 0; 7c9: c7 05 f8 0a 00 00 00 movl $0x0,0xaf8 7d0: 00 00 00 } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 7d3: 8b 45 f0 mov -0x10(%ebp),%eax 7d6: 8b 00 mov (%eax),%eax 7d8: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 7db: 8b 45 f4 mov -0xc(%ebp),%eax 7de: 8b 40 04 mov 0x4(%eax),%eax 7e1: 3b 45 ec cmp -0x14(%ebp),%eax 7e4: 72 4d jb 833 <malloc+0xa6> if(p->s.size == nunits) 7e6: 8b 45 f4 mov -0xc(%ebp),%eax 7e9: 8b 40 04 mov 0x4(%eax),%eax 7ec: 3b 45 ec cmp -0x14(%ebp),%eax 7ef: 75 0c jne 7fd <malloc+0x70> prevp->s.ptr = p->s.ptr; 7f1: 8b 45 f4 mov -0xc(%ebp),%eax 7f4: 8b 10 mov (%eax),%edx 7f6: 8b 45 f0 mov -0x10(%ebp),%eax 7f9: 89 10 mov %edx,(%eax) 7fb: eb 26 jmp 823 <malloc+0x96> else { p->s.size -= nunits; 7fd: 8b 45 f4 mov -0xc(%ebp),%eax 800: 8b 40 04 mov 0x4(%eax),%eax 803: 2b 45 ec sub -0x14(%ebp),%eax 806: 89 c2 mov %eax,%edx 808: 8b 45 f4 mov -0xc(%ebp),%eax 80b: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 80e: 8b 45 f4 mov -0xc(%ebp),%eax 811: 8b 40 04 mov 0x4(%eax),%eax 814: c1 e0 03 shl $0x3,%eax 817: 01 45 f4 add %eax,-0xc(%ebp) p->s.size = nunits; 81a: 8b 45 f4 mov -0xc(%ebp),%eax 81d: 8b 55 ec mov -0x14(%ebp),%edx 820: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 823: 8b 45 f0 mov -0x10(%ebp),%eax 826: a3 fc 0a 00 00 mov %eax,0xafc return (void*)(p + 1); 82b: 8b 45 f4 mov -0xc(%ebp),%eax 82e: 83 c0 08 add $0x8,%eax 831: eb 38 jmp 86b <malloc+0xde> } if(p == freep) 833: a1 fc 0a 00 00 mov 0xafc,%eax 838: 39 45 f4 cmp %eax,-0xc(%ebp) 83b: 75 1b jne 858 <malloc+0xcb> if((p = morecore(nunits)) == 0) 83d: 8b 45 ec mov -0x14(%ebp),%eax 840: 89 04 24 mov %eax,(%esp) 843: e8 ed fe ff ff call 735 <morecore> 848: 89 45 f4 mov %eax,-0xc(%ebp) 84b: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 84f: 75 07 jne 858 <malloc+0xcb> return 0; 851: b8 00 00 00 00 mov $0x0,%eax 856: eb 13 jmp 86b <malloc+0xde> nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 858: 8b 45 f4 mov -0xc(%ebp),%eax 85b: 89 45 f0 mov %eax,-0x10(%ebp) 85e: 8b 45 f4 mov -0xc(%ebp),%eax 861: 8b 00 mov (%eax),%eax 863: 89 45 f4 mov %eax,-0xc(%ebp) return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } 866: e9 70 ff ff ff jmp 7db <malloc+0x4e> } 86b: c9 leave 86c: c3 ret
_init: file format elf32-i386 Disassembly of section .text: 00000000 <main>: char *argv[] = { "sh", 0 }; 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: 53 push %ebx e: 51 push %ecx int pid, wpid; if(open("console", O_RDWR) < 0){ f: 83 ec 08 sub $0x8,%esp 12: 6a 02 push $0x2 14: 68 18 08 00 00 push $0x818 19: e8 64 03 00 00 call 382 <open> 1e: 83 c4 10 add $0x10,%esp 21: 85 c0 test %eax,%eax 23: 0f 88 9f 00 00 00 js c8 <main+0xc8> mknod("console", 1, 1); open("console", O_RDWR); } dup(0); // stdout 29: 83 ec 0c sub $0xc,%esp 2c: 6a 00 push $0x0 2e: e8 87 03 00 00 call 3ba <dup> dup(0); // stderr 33: c7 04 24 00 00 00 00 movl $0x0,(%esp) 3a: e8 7b 03 00 00 call 3ba <dup> 3f: 83 c4 10 add $0x10,%esp 42: 8d b6 00 00 00 00 lea 0x0(%esi),%esi for(;;){ printf(1, "init: starting sh\n"); 48: 83 ec 08 sub $0x8,%esp 4b: 68 20 08 00 00 push $0x820 50: 6a 01 push $0x1 52: e8 69 04 00 00 call 4c0 <printf> pid = fork(); 57: e8 de 02 00 00 call 33a <fork> if(pid < 0){ 5c: 83 c4 10 add $0x10,%esp 5f: 85 c0 test %eax,%eax pid = fork(); 61: 89 c3 mov %eax,%ebx if(pid < 0){ 63: 78 2c js 91 <main+0x91> printf(1, "init: fork failed\n"); exit(); } if(pid == 0){ 65: 74 3d je a4 <main+0xa4> 67: 89 f6 mov %esi,%esi 69: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi exec("sh", argv); printf(1, "init: exec sh failed\n"); exit(); } while((wpid=wait()) >= 0 && wpid != pid) 70: e8 d5 02 00 00 call 34a <wait> 75: 85 c0 test %eax,%eax 77: 78 cf js 48 <main+0x48> 79: 39 c3 cmp %eax,%ebx 7b: 74 cb je 48 <main+0x48> printf(1, "zombie!\n"); 7d: 83 ec 08 sub $0x8,%esp 80: 68 5f 08 00 00 push $0x85f 85: 6a 01 push $0x1 87: e8 34 04 00 00 call 4c0 <printf> 8c: 83 c4 10 add $0x10,%esp 8f: eb df jmp 70 <main+0x70> printf(1, "init: fork failed\n"); 91: 53 push %ebx 92: 53 push %ebx 93: 68 33 08 00 00 push $0x833 98: 6a 01 push $0x1 9a: e8 21 04 00 00 call 4c0 <printf> exit(); 9f: e8 9e 02 00 00 call 342 <exit> exec("sh", argv); a4: 50 push %eax a5: 50 push %eax a6: 68 18 0b 00 00 push $0xb18 ab: 68 46 08 00 00 push $0x846 b0: e8 c5 02 00 00 call 37a <exec> printf(1, "init: exec sh failed\n"); b5: 5a pop %edx b6: 59 pop %ecx b7: 68 49 08 00 00 push $0x849 bc: 6a 01 push $0x1 be: e8 fd 03 00 00 call 4c0 <printf> exit(); c3: e8 7a 02 00 00 call 342 <exit> mknod("console", 1, 1); c8: 50 push %eax c9: 6a 01 push $0x1 cb: 6a 01 push $0x1 cd: 68 18 08 00 00 push $0x818 d2: e8 b3 02 00 00 call 38a <mknod> open("console", O_RDWR); d7: 58 pop %eax d8: 5a pop %edx d9: 6a 02 push $0x2 db: 68 18 08 00 00 push $0x818 e0: e8 9d 02 00 00 call 382 <open> e5: 83 c4 10 add $0x10,%esp e8: e9 3c ff ff ff jmp 29 <main+0x29> ed: 66 90 xchg %ax,%ax ef: 90 nop 000000f0 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { f0: 55 push %ebp f1: 89 e5 mov %esp,%ebp f3: 53 push %ebx f4: 8b 45 08 mov 0x8(%ebp),%eax f7: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) fa: 89 c2 mov %eax,%edx fc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 100: 83 c1 01 add $0x1,%ecx 103: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 107: 83 c2 01 add $0x1,%edx 10a: 84 db test %bl,%bl 10c: 88 5a ff mov %bl,-0x1(%edx) 10f: 75 ef jne 100 <strcpy+0x10> ; return os; } 111: 5b pop %ebx 112: 5d pop %ebp 113: c3 ret 114: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 11a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000120 <strcmp>: int strcmp(const char *p, const char *q) { 120: 55 push %ebp 121: 89 e5 mov %esp,%ebp 123: 53 push %ebx 124: 8b 55 08 mov 0x8(%ebp),%edx 127: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) 12a: 0f b6 02 movzbl (%edx),%eax 12d: 0f b6 19 movzbl (%ecx),%ebx 130: 84 c0 test %al,%al 132: 75 1c jne 150 <strcmp+0x30> 134: eb 2a jmp 160 <strcmp+0x40> 136: 8d 76 00 lea 0x0(%esi),%esi 139: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; 140: 83 c2 01 add $0x1,%edx while(*p && *p == *q) 143: 0f b6 02 movzbl (%edx),%eax p++, q++; 146: 83 c1 01 add $0x1,%ecx 149: 0f b6 19 movzbl (%ecx),%ebx while(*p && *p == *q) 14c: 84 c0 test %al,%al 14e: 74 10 je 160 <strcmp+0x40> 150: 38 d8 cmp %bl,%al 152: 74 ec je 140 <strcmp+0x20> return (uchar)*p - (uchar)*q; 154: 29 d8 sub %ebx,%eax } 156: 5b pop %ebx 157: 5d pop %ebp 158: c3 ret 159: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 160: 31 c0 xor %eax,%eax return (uchar)*p - (uchar)*q; 162: 29 d8 sub %ebx,%eax } 164: 5b pop %ebx 165: 5d pop %ebp 166: c3 ret 167: 89 f6 mov %esi,%esi 169: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000170 <strlen>: uint strlen(char *s) { 170: 55 push %ebp 171: 89 e5 mov %esp,%ebp 173: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 176: 80 39 00 cmpb $0x0,(%ecx) 179: 74 15 je 190 <strlen+0x20> 17b: 31 d2 xor %edx,%edx 17d: 8d 76 00 lea 0x0(%esi),%esi 180: 83 c2 01 add $0x1,%edx 183: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 187: 89 d0 mov %edx,%eax 189: 75 f5 jne 180 <strlen+0x10> ; return n; } 18b: 5d pop %ebp 18c: c3 ret 18d: 8d 76 00 lea 0x0(%esi),%esi for(n = 0; s[n]; n++) 190: 31 c0 xor %eax,%eax } 192: 5d pop %ebp 193: c3 ret 194: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 19a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000001a0 <memset>: void* memset(void *dst, int c, uint n) { 1a0: 55 push %ebp 1a1: 89 e5 mov %esp,%ebp 1a3: 57 push %edi 1a4: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 1a7: 8b 4d 10 mov 0x10(%ebp),%ecx 1aa: 8b 45 0c mov 0xc(%ebp),%eax 1ad: 89 d7 mov %edx,%edi 1af: fc cld 1b0: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 1b2: 89 d0 mov %edx,%eax 1b4: 5f pop %edi 1b5: 5d pop %ebp 1b6: c3 ret 1b7: 89 f6 mov %esi,%esi 1b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000001c0 <strchr>: char* strchr(const char *s, char c) { 1c0: 55 push %ebp 1c1: 89 e5 mov %esp,%ebp 1c3: 53 push %ebx 1c4: 8b 45 08 mov 0x8(%ebp),%eax 1c7: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 1ca: 0f b6 10 movzbl (%eax),%edx 1cd: 84 d2 test %dl,%dl 1cf: 74 1d je 1ee <strchr+0x2e> if(*s == c) 1d1: 38 d3 cmp %dl,%bl 1d3: 89 d9 mov %ebx,%ecx 1d5: 75 0d jne 1e4 <strchr+0x24> 1d7: eb 17 jmp 1f0 <strchr+0x30> 1d9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 1e0: 38 ca cmp %cl,%dl 1e2: 74 0c je 1f0 <strchr+0x30> for(; *s; s++) 1e4: 83 c0 01 add $0x1,%eax 1e7: 0f b6 10 movzbl (%eax),%edx 1ea: 84 d2 test %dl,%dl 1ec: 75 f2 jne 1e0 <strchr+0x20> return (char*)s; return 0; 1ee: 31 c0 xor %eax,%eax } 1f0: 5b pop %ebx 1f1: 5d pop %ebp 1f2: c3 ret 1f3: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 1f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000200 <gets>: char* gets(char *buf, int max) { 200: 55 push %ebp 201: 89 e5 mov %esp,%ebp 203: 57 push %edi 204: 56 push %esi 205: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 206: 31 f6 xor %esi,%esi 208: 89 f3 mov %esi,%ebx { 20a: 83 ec 1c sub $0x1c,%esp 20d: 8b 7d 08 mov 0x8(%ebp),%edi for(i=0; i+1 < max; ){ 210: eb 2f jmp 241 <gets+0x41> 212: 8d b6 00 00 00 00 lea 0x0(%esi),%esi cc = read(0, &c, 1); 218: 8d 45 e7 lea -0x19(%ebp),%eax 21b: 83 ec 04 sub $0x4,%esp 21e: 6a 01 push $0x1 220: 50 push %eax 221: 6a 00 push $0x0 223: e8 32 01 00 00 call 35a <read> if(cc < 1) 228: 83 c4 10 add $0x10,%esp 22b: 85 c0 test %eax,%eax 22d: 7e 1c jle 24b <gets+0x4b> break; buf[i++] = c; 22f: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 233: 83 c7 01 add $0x1,%edi 236: 88 47 ff mov %al,-0x1(%edi) if(c == '\n' || c == '\r') 239: 3c 0a cmp $0xa,%al 23b: 74 23 je 260 <gets+0x60> 23d: 3c 0d cmp $0xd,%al 23f: 74 1f je 260 <gets+0x60> for(i=0; i+1 < max; ){ 241: 83 c3 01 add $0x1,%ebx 244: 3b 5d 0c cmp 0xc(%ebp),%ebx 247: 89 fe mov %edi,%esi 249: 7c cd jl 218 <gets+0x18> 24b: 89 f3 mov %esi,%ebx break; } buf[i] = '\0'; return buf; } 24d: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 250: c6 03 00 movb $0x0,(%ebx) } 253: 8d 65 f4 lea -0xc(%ebp),%esp 256: 5b pop %ebx 257: 5e pop %esi 258: 5f pop %edi 259: 5d pop %ebp 25a: c3 ret 25b: 90 nop 25c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 260: 8b 75 08 mov 0x8(%ebp),%esi 263: 8b 45 08 mov 0x8(%ebp),%eax 266: 01 de add %ebx,%esi 268: 89 f3 mov %esi,%ebx buf[i] = '\0'; 26a: c6 03 00 movb $0x0,(%ebx) } 26d: 8d 65 f4 lea -0xc(%ebp),%esp 270: 5b pop %ebx 271: 5e pop %esi 272: 5f pop %edi 273: 5d pop %ebp 274: c3 ret 275: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 279: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000280 <stat>: int stat(char *n, struct stat *st) { 280: 55 push %ebp 281: 89 e5 mov %esp,%ebp 283: 56 push %esi 284: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 285: 83 ec 08 sub $0x8,%esp 288: 6a 00 push $0x0 28a: ff 75 08 pushl 0x8(%ebp) 28d: e8 f0 00 00 00 call 382 <open> if(fd < 0) 292: 83 c4 10 add $0x10,%esp 295: 85 c0 test %eax,%eax 297: 78 27 js 2c0 <stat+0x40> return -1; r = fstat(fd, st); 299: 83 ec 08 sub $0x8,%esp 29c: ff 75 0c pushl 0xc(%ebp) 29f: 89 c3 mov %eax,%ebx 2a1: 50 push %eax 2a2: e8 f3 00 00 00 call 39a <fstat> close(fd); 2a7: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 2aa: 89 c6 mov %eax,%esi close(fd); 2ac: e8 b9 00 00 00 call 36a <close> return r; 2b1: 83 c4 10 add $0x10,%esp } 2b4: 8d 65 f8 lea -0x8(%ebp),%esp 2b7: 89 f0 mov %esi,%eax 2b9: 5b pop %ebx 2ba: 5e pop %esi 2bb: 5d pop %ebp 2bc: c3 ret 2bd: 8d 76 00 lea 0x0(%esi),%esi return -1; 2c0: be ff ff ff ff mov $0xffffffff,%esi 2c5: eb ed jmp 2b4 <stat+0x34> 2c7: 89 f6 mov %esi,%esi 2c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000002d0 <atoi>: int atoi(const char *s) { 2d0: 55 push %ebp 2d1: 89 e5 mov %esp,%ebp 2d3: 53 push %ebx 2d4: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 2d7: 0f be 11 movsbl (%ecx),%edx 2da: 8d 42 d0 lea -0x30(%edx),%eax 2dd: 3c 09 cmp $0x9,%al n = 0; 2df: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 2e4: 77 1f ja 305 <atoi+0x35> 2e6: 8d 76 00 lea 0x0(%esi),%esi 2e9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 2f0: 8d 04 80 lea (%eax,%eax,4),%eax 2f3: 83 c1 01 add $0x1,%ecx 2f6: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax while('0' <= *s && *s <= '9') 2fa: 0f be 11 movsbl (%ecx),%edx 2fd: 8d 5a d0 lea -0x30(%edx),%ebx 300: 80 fb 09 cmp $0x9,%bl 303: 76 eb jbe 2f0 <atoi+0x20> return n; } 305: 5b pop %ebx 306: 5d pop %ebp 307: c3 ret 308: 90 nop 309: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000310 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 310: 55 push %ebp 311: 89 e5 mov %esp,%ebp 313: 56 push %esi 314: 53 push %ebx 315: 8b 5d 10 mov 0x10(%ebp),%ebx 318: 8b 45 08 mov 0x8(%ebp),%eax 31b: 8b 75 0c mov 0xc(%ebp),%esi char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 31e: 85 db test %ebx,%ebx 320: 7e 14 jle 336 <memmove+0x26> 322: 31 d2 xor %edx,%edx 324: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 328: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 32c: 88 0c 10 mov %cl,(%eax,%edx,1) 32f: 83 c2 01 add $0x1,%edx while(n-- > 0) 332: 39 d3 cmp %edx,%ebx 334: 75 f2 jne 328 <memmove+0x18> return vdst; } 336: 5b pop %ebx 337: 5e pop %esi 338: 5d pop %ebp 339: c3 ret 0000033a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 33a: b8 01 00 00 00 mov $0x1,%eax 33f: cd 40 int $0x40 341: c3 ret 00000342 <exit>: SYSCALL(exit) 342: b8 02 00 00 00 mov $0x2,%eax 347: cd 40 int $0x40 349: c3 ret 0000034a <wait>: SYSCALL(wait) 34a: b8 03 00 00 00 mov $0x3,%eax 34f: cd 40 int $0x40 351: c3 ret 00000352 <pipe>: SYSCALL(pipe) 352: b8 04 00 00 00 mov $0x4,%eax 357: cd 40 int $0x40 359: c3 ret 0000035a <read>: SYSCALL(read) 35a: b8 05 00 00 00 mov $0x5,%eax 35f: cd 40 int $0x40 361: c3 ret 00000362 <write>: SYSCALL(write) 362: b8 10 00 00 00 mov $0x10,%eax 367: cd 40 int $0x40 369: c3 ret 0000036a <close>: SYSCALL(close) 36a: b8 15 00 00 00 mov $0x15,%eax 36f: cd 40 int $0x40 371: c3 ret 00000372 <kill>: SYSCALL(kill) 372: b8 06 00 00 00 mov $0x6,%eax 377: cd 40 int $0x40 379: c3 ret 0000037a <exec>: SYSCALL(exec) 37a: b8 07 00 00 00 mov $0x7,%eax 37f: cd 40 int $0x40 381: c3 ret 00000382 <open>: SYSCALL(open) 382: b8 0f 00 00 00 mov $0xf,%eax 387: cd 40 int $0x40 389: c3 ret 0000038a <mknod>: SYSCALL(mknod) 38a: b8 11 00 00 00 mov $0x11,%eax 38f: cd 40 int $0x40 391: c3 ret 00000392 <unlink>: SYSCALL(unlink) 392: b8 12 00 00 00 mov $0x12,%eax 397: cd 40 int $0x40 399: c3 ret 0000039a <fstat>: SYSCALL(fstat) 39a: b8 08 00 00 00 mov $0x8,%eax 39f: cd 40 int $0x40 3a1: c3 ret 000003a2 <link>: SYSCALL(link) 3a2: b8 13 00 00 00 mov $0x13,%eax 3a7: cd 40 int $0x40 3a9: c3 ret 000003aa <mkdir>: SYSCALL(mkdir) 3aa: b8 14 00 00 00 mov $0x14,%eax 3af: cd 40 int $0x40 3b1: c3 ret 000003b2 <chdir>: SYSCALL(chdir) 3b2: b8 09 00 00 00 mov $0x9,%eax 3b7: cd 40 int $0x40 3b9: c3 ret 000003ba <dup>: SYSCALL(dup) 3ba: b8 0a 00 00 00 mov $0xa,%eax 3bf: cd 40 int $0x40 3c1: c3 ret 000003c2 <getpid>: SYSCALL(getpid) 3c2: b8 0b 00 00 00 mov $0xb,%eax 3c7: cd 40 int $0x40 3c9: c3 ret 000003ca <sbrk>: SYSCALL(sbrk) 3ca: b8 0c 00 00 00 mov $0xc,%eax 3cf: cd 40 int $0x40 3d1: c3 ret 000003d2 <sleep>: SYSCALL(sleep) 3d2: b8 0d 00 00 00 mov $0xd,%eax 3d7: cd 40 int $0x40 3d9: c3 ret 000003da <uptime>: SYSCALL(uptime) 3da: b8 0e 00 00 00 mov $0xe,%eax 3df: cd 40 int $0x40 3e1: c3 ret 000003e2 <cps>: SYSCALL(cps) 3e2: b8 16 00 00 00 mov $0x16,%eax 3e7: cd 40 int $0x40 3e9: c3 ret 000003ea <chpr>: SYSCALL(chpr) 3ea: b8 17 00 00 00 mov $0x17,%eax 3ef: cd 40 int $0x40 3f1: c3 ret 000003f2 <setTickets>: SYSCALL(setTickets) 3f2: b8 18 00 00 00 mov $0x18,%eax 3f7: cd 40 int $0x40 3f9: c3 ret 000003fa <thread_create>: SYSCALL(thread_create) 3fa: b8 19 00 00 00 mov $0x19,%eax 3ff: cd 40 int $0x40 401: c3 ret 00000402 <thread_exit>: SYSCALL(thread_exit) 402: b8 1a 00 00 00 mov $0x1a,%eax 407: cd 40 int $0x40 409: c3 ret 0000040a <thread_join>: SYSCALL(thread_join) 40a: b8 1b 00 00 00 mov $0x1b,%eax 40f: cd 40 int $0x40 411: c3 ret 00000412 <gettid>: SYSCALL(gettid) 412: b8 1c 00 00 00 mov $0x1c,%eax 417: cd 40 int $0x40 419: c3 ret 41a: 66 90 xchg %ax,%ax 41c: 66 90 xchg %ax,%ax 41e: 66 90 xchg %ax,%ax 00000420 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 420: 55 push %ebp 421: 89 e5 mov %esp,%ebp 423: 57 push %edi 424: 56 push %esi 425: 53 push %ebx 426: 83 ec 3c sub $0x3c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 429: 85 d2 test %edx,%edx { 42b: 89 45 c0 mov %eax,-0x40(%ebp) neg = 1; x = -xx; 42e: 89 d0 mov %edx,%eax if(sgn && xx < 0){ 430: 79 76 jns 4a8 <printint+0x88> 432: f6 45 08 01 testb $0x1,0x8(%ebp) 436: 74 70 je 4a8 <printint+0x88> x = -xx; 438: f7 d8 neg %eax neg = 1; 43a: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) } else { x = xx; } i = 0; 441: 31 f6 xor %esi,%esi 443: 8d 5d d7 lea -0x29(%ebp),%ebx 446: eb 0a jmp 452 <printint+0x32> 448: 90 nop 449: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi do{ buf[i++] = digits[x % base]; 450: 89 fe mov %edi,%esi 452: 31 d2 xor %edx,%edx 454: 8d 7e 01 lea 0x1(%esi),%edi 457: f7 f1 div %ecx 459: 0f b6 92 70 08 00 00 movzbl 0x870(%edx),%edx }while((x /= base) != 0); 460: 85 c0 test %eax,%eax buf[i++] = digits[x % base]; 462: 88 14 3b mov %dl,(%ebx,%edi,1) }while((x /= base) != 0); 465: 75 e9 jne 450 <printint+0x30> if(neg) 467: 8b 45 c4 mov -0x3c(%ebp),%eax 46a: 85 c0 test %eax,%eax 46c: 74 08 je 476 <printint+0x56> buf[i++] = '-'; 46e: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1) 473: 8d 7e 02 lea 0x2(%esi),%edi 476: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi 47a: 8b 7d c0 mov -0x40(%ebp),%edi 47d: 8d 76 00 lea 0x0(%esi),%esi 480: 0f b6 06 movzbl (%esi),%eax write(fd, &c, 1); 483: 83 ec 04 sub $0x4,%esp 486: 83 ee 01 sub $0x1,%esi 489: 6a 01 push $0x1 48b: 53 push %ebx 48c: 57 push %edi 48d: 88 45 d7 mov %al,-0x29(%ebp) 490: e8 cd fe ff ff call 362 <write> while(--i >= 0) 495: 83 c4 10 add $0x10,%esp 498: 39 de cmp %ebx,%esi 49a: 75 e4 jne 480 <printint+0x60> putc(fd, buf[i]); } 49c: 8d 65 f4 lea -0xc(%ebp),%esp 49f: 5b pop %ebx 4a0: 5e pop %esi 4a1: 5f pop %edi 4a2: 5d pop %ebp 4a3: c3 ret 4a4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; 4a8: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 4af: eb 90 jmp 441 <printint+0x21> 4b1: eb 0d jmp 4c0 <printf> 4b3: 90 nop 4b4: 90 nop 4b5: 90 nop 4b6: 90 nop 4b7: 90 nop 4b8: 90 nop 4b9: 90 nop 4ba: 90 nop 4bb: 90 nop 4bc: 90 nop 4bd: 90 nop 4be: 90 nop 4bf: 90 nop 000004c0 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 4c0: 55 push %ebp 4c1: 89 e5 mov %esp,%ebp 4c3: 57 push %edi 4c4: 56 push %esi 4c5: 53 push %ebx 4c6: 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++){ 4c9: 8b 75 0c mov 0xc(%ebp),%esi 4cc: 0f b6 1e movzbl (%esi),%ebx 4cf: 84 db test %bl,%bl 4d1: 0f 84 b3 00 00 00 je 58a <printf+0xca> ap = (uint*)(void*)&fmt + 1; 4d7: 8d 45 10 lea 0x10(%ebp),%eax 4da: 83 c6 01 add $0x1,%esi state = 0; 4dd: 31 ff xor %edi,%edi ap = (uint*)(void*)&fmt + 1; 4df: 89 45 d4 mov %eax,-0x2c(%ebp) 4e2: eb 2f jmp 513 <printf+0x53> 4e4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 4e8: 83 f8 25 cmp $0x25,%eax 4eb: 0f 84 a7 00 00 00 je 598 <printf+0xd8> write(fd, &c, 1); 4f1: 8d 45 e2 lea -0x1e(%ebp),%eax 4f4: 83 ec 04 sub $0x4,%esp 4f7: 88 5d e2 mov %bl,-0x1e(%ebp) 4fa: 6a 01 push $0x1 4fc: 50 push %eax 4fd: ff 75 08 pushl 0x8(%ebp) 500: e8 5d fe ff ff call 362 <write> 505: 83 c4 10 add $0x10,%esp 508: 83 c6 01 add $0x1,%esi for(i = 0; fmt[i]; i++){ 50b: 0f b6 5e ff movzbl -0x1(%esi),%ebx 50f: 84 db test %bl,%bl 511: 74 77 je 58a <printf+0xca> if(state == 0){ 513: 85 ff test %edi,%edi c = fmt[i] & 0xff; 515: 0f be cb movsbl %bl,%ecx 518: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 51b: 74 cb je 4e8 <printf+0x28> state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 51d: 83 ff 25 cmp $0x25,%edi 520: 75 e6 jne 508 <printf+0x48> if(c == 'd'){ 522: 83 f8 64 cmp $0x64,%eax 525: 0f 84 05 01 00 00 je 630 <printf+0x170> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 52b: 81 e1 f7 00 00 00 and $0xf7,%ecx 531: 83 f9 70 cmp $0x70,%ecx 534: 74 72 je 5a8 <printf+0xe8> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 536: 83 f8 73 cmp $0x73,%eax 539: 0f 84 99 00 00 00 je 5d8 <printf+0x118> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 53f: 83 f8 63 cmp $0x63,%eax 542: 0f 84 08 01 00 00 je 650 <printf+0x190> putc(fd, *ap); ap++; } else if(c == '%'){ 548: 83 f8 25 cmp $0x25,%eax 54b: 0f 84 ef 00 00 00 je 640 <printf+0x180> write(fd, &c, 1); 551: 8d 45 e7 lea -0x19(%ebp),%eax 554: 83 ec 04 sub $0x4,%esp 557: c6 45 e7 25 movb $0x25,-0x19(%ebp) 55b: 6a 01 push $0x1 55d: 50 push %eax 55e: ff 75 08 pushl 0x8(%ebp) 561: e8 fc fd ff ff call 362 <write> 566: 83 c4 0c add $0xc,%esp 569: 8d 45 e6 lea -0x1a(%ebp),%eax 56c: 88 5d e6 mov %bl,-0x1a(%ebp) 56f: 6a 01 push $0x1 571: 50 push %eax 572: ff 75 08 pushl 0x8(%ebp) 575: 83 c6 01 add $0x1,%esi } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 578: 31 ff xor %edi,%edi write(fd, &c, 1); 57a: e8 e3 fd ff ff call 362 <write> for(i = 0; fmt[i]; i++){ 57f: 0f b6 5e ff movzbl -0x1(%esi),%ebx write(fd, &c, 1); 583: 83 c4 10 add $0x10,%esp for(i = 0; fmt[i]; i++){ 586: 84 db test %bl,%bl 588: 75 89 jne 513 <printf+0x53> } } } 58a: 8d 65 f4 lea -0xc(%ebp),%esp 58d: 5b pop %ebx 58e: 5e pop %esi 58f: 5f pop %edi 590: 5d pop %ebp 591: c3 ret 592: 8d b6 00 00 00 00 lea 0x0(%esi),%esi state = '%'; 598: bf 25 00 00 00 mov $0x25,%edi 59d: e9 66 ff ff ff jmp 508 <printf+0x48> 5a2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi printint(fd, *ap, 16, 0); 5a8: 83 ec 0c sub $0xc,%esp 5ab: b9 10 00 00 00 mov $0x10,%ecx 5b0: 6a 00 push $0x0 5b2: 8b 7d d4 mov -0x2c(%ebp),%edi 5b5: 8b 45 08 mov 0x8(%ebp),%eax 5b8: 8b 17 mov (%edi),%edx 5ba: e8 61 fe ff ff call 420 <printint> ap++; 5bf: 89 f8 mov %edi,%eax 5c1: 83 c4 10 add $0x10,%esp state = 0; 5c4: 31 ff xor %edi,%edi ap++; 5c6: 83 c0 04 add $0x4,%eax 5c9: 89 45 d4 mov %eax,-0x2c(%ebp) 5cc: e9 37 ff ff ff jmp 508 <printf+0x48> 5d1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi s = (char*)*ap; 5d8: 8b 45 d4 mov -0x2c(%ebp),%eax 5db: 8b 08 mov (%eax),%ecx ap++; 5dd: 83 c0 04 add $0x4,%eax 5e0: 89 45 d4 mov %eax,-0x2c(%ebp) if(s == 0) 5e3: 85 c9 test %ecx,%ecx 5e5: 0f 84 8e 00 00 00 je 679 <printf+0x1b9> while(*s != 0){ 5eb: 0f b6 01 movzbl (%ecx),%eax state = 0; 5ee: 31 ff xor %edi,%edi s = (char*)*ap; 5f0: 89 cb mov %ecx,%ebx while(*s != 0){ 5f2: 84 c0 test %al,%al 5f4: 0f 84 0e ff ff ff je 508 <printf+0x48> 5fa: 89 75 d0 mov %esi,-0x30(%ebp) 5fd: 89 de mov %ebx,%esi 5ff: 8b 5d 08 mov 0x8(%ebp),%ebx 602: 8d 7d e3 lea -0x1d(%ebp),%edi 605: 8d 76 00 lea 0x0(%esi),%esi write(fd, &c, 1); 608: 83 ec 04 sub $0x4,%esp s++; 60b: 83 c6 01 add $0x1,%esi 60e: 88 45 e3 mov %al,-0x1d(%ebp) write(fd, &c, 1); 611: 6a 01 push $0x1 613: 57 push %edi 614: 53 push %ebx 615: e8 48 fd ff ff call 362 <write> while(*s != 0){ 61a: 0f b6 06 movzbl (%esi),%eax 61d: 83 c4 10 add $0x10,%esp 620: 84 c0 test %al,%al 622: 75 e4 jne 608 <printf+0x148> 624: 8b 75 d0 mov -0x30(%ebp),%esi state = 0; 627: 31 ff xor %edi,%edi 629: e9 da fe ff ff jmp 508 <printf+0x48> 62e: 66 90 xchg %ax,%ax printint(fd, *ap, 10, 1); 630: 83 ec 0c sub $0xc,%esp 633: b9 0a 00 00 00 mov $0xa,%ecx 638: 6a 01 push $0x1 63a: e9 73 ff ff ff jmp 5b2 <printf+0xf2> 63f: 90 nop write(fd, &c, 1); 640: 83 ec 04 sub $0x4,%esp 643: 88 5d e5 mov %bl,-0x1b(%ebp) 646: 8d 45 e5 lea -0x1b(%ebp),%eax 649: 6a 01 push $0x1 64b: e9 21 ff ff ff jmp 571 <printf+0xb1> putc(fd, *ap); 650: 8b 7d d4 mov -0x2c(%ebp),%edi write(fd, &c, 1); 653: 83 ec 04 sub $0x4,%esp putc(fd, *ap); 656: 8b 07 mov (%edi),%eax write(fd, &c, 1); 658: 6a 01 push $0x1 ap++; 65a: 83 c7 04 add $0x4,%edi putc(fd, *ap); 65d: 88 45 e4 mov %al,-0x1c(%ebp) write(fd, &c, 1); 660: 8d 45 e4 lea -0x1c(%ebp),%eax 663: 50 push %eax 664: ff 75 08 pushl 0x8(%ebp) 667: e8 f6 fc ff ff call 362 <write> ap++; 66c: 89 7d d4 mov %edi,-0x2c(%ebp) 66f: 83 c4 10 add $0x10,%esp state = 0; 672: 31 ff xor %edi,%edi 674: e9 8f fe ff ff jmp 508 <printf+0x48> s = "(null)"; 679: bb 68 08 00 00 mov $0x868,%ebx while(*s != 0){ 67e: b8 28 00 00 00 mov $0x28,%eax 683: e9 72 ff ff ff jmp 5fa <printf+0x13a> 688: 66 90 xchg %ax,%ax 68a: 66 90 xchg %ax,%ax 68c: 66 90 xchg %ax,%ax 68e: 66 90 xchg %ax,%ax 00000690 <free>: static Header base; static Header *freep; void free(void *ap) { 690: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 691: a1 20 0b 00 00 mov 0xb20,%eax { 696: 89 e5 mov %esp,%ebp 698: 57 push %edi 699: 56 push %esi 69a: 53 push %ebx 69b: 8b 5d 08 mov 0x8(%ebp),%ebx bp = (Header*)ap - 1; 69e: 8d 4b f8 lea -0x8(%ebx),%ecx 6a1: 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) 6a8: 39 c8 cmp %ecx,%eax 6aa: 8b 10 mov (%eax),%edx 6ac: 73 32 jae 6e0 <free+0x50> 6ae: 39 d1 cmp %edx,%ecx 6b0: 72 04 jb 6b6 <free+0x26> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 6b2: 39 d0 cmp %edx,%eax 6b4: 72 32 jb 6e8 <free+0x58> break; if(bp + bp->s.size == p->s.ptr){ 6b6: 8b 73 fc mov -0x4(%ebx),%esi 6b9: 8d 3c f1 lea (%ecx,%esi,8),%edi 6bc: 39 fa cmp %edi,%edx 6be: 74 30 je 6f0 <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; 6c0: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 6c3: 8b 50 04 mov 0x4(%eax),%edx 6c6: 8d 34 d0 lea (%eax,%edx,8),%esi 6c9: 39 f1 cmp %esi,%ecx 6cb: 74 3a je 707 <free+0x77> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 6cd: 89 08 mov %ecx,(%eax) freep = p; 6cf: a3 20 0b 00 00 mov %eax,0xb20 } 6d4: 5b pop %ebx 6d5: 5e pop %esi 6d6: 5f pop %edi 6d7: 5d pop %ebp 6d8: c3 ret 6d9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 6e0: 39 d0 cmp %edx,%eax 6e2: 72 04 jb 6e8 <free+0x58> 6e4: 39 d1 cmp %edx,%ecx 6e6: 72 ce jb 6b6 <free+0x26> { 6e8: 89 d0 mov %edx,%eax 6ea: eb bc jmp 6a8 <free+0x18> 6ec: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi bp->s.size += p->s.ptr->s.size; 6f0: 03 72 04 add 0x4(%edx),%esi 6f3: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 6f6: 8b 10 mov (%eax),%edx 6f8: 8b 12 mov (%edx),%edx 6fa: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 6fd: 8b 50 04 mov 0x4(%eax),%edx 700: 8d 34 d0 lea (%eax,%edx,8),%esi 703: 39 f1 cmp %esi,%ecx 705: 75 c6 jne 6cd <free+0x3d> p->s.size += bp->s.size; 707: 03 53 fc add -0x4(%ebx),%edx freep = p; 70a: a3 20 0b 00 00 mov %eax,0xb20 p->s.size += bp->s.size; 70f: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 712: 8b 53 f8 mov -0x8(%ebx),%edx 715: 89 10 mov %edx,(%eax) } 717: 5b pop %ebx 718: 5e pop %esi 719: 5f pop %edi 71a: 5d pop %ebp 71b: c3 ret 71c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00000720 <malloc>: return freep; } void* malloc(uint nbytes) { 720: 55 push %ebp 721: 89 e5 mov %esp,%ebp 723: 57 push %edi 724: 56 push %esi 725: 53 push %ebx 726: 83 ec 0c sub $0xc,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 729: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 72c: 8b 15 20 0b 00 00 mov 0xb20,%edx nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 732: 8d 78 07 lea 0x7(%eax),%edi 735: c1 ef 03 shr $0x3,%edi 738: 83 c7 01 add $0x1,%edi if((prevp = freep) == 0){ 73b: 85 d2 test %edx,%edx 73d: 0f 84 9d 00 00 00 je 7e0 <malloc+0xc0> 743: 8b 02 mov (%edx),%eax 745: 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){ 748: 39 cf cmp %ecx,%edi 74a: 76 6c jbe 7b8 <malloc+0x98> 74c: 81 ff 00 10 00 00 cmp $0x1000,%edi 752: bb 00 10 00 00 mov $0x1000,%ebx 757: 0f 43 df cmovae %edi,%ebx p = sbrk(nu * sizeof(Header)); 75a: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi 761: eb 0e jmp 771 <malloc+0x51> 763: 90 nop 764: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 768: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 76a: 8b 48 04 mov 0x4(%eax),%ecx 76d: 39 f9 cmp %edi,%ecx 76f: 73 47 jae 7b8 <malloc+0x98> p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 771: 39 05 20 0b 00 00 cmp %eax,0xb20 777: 89 c2 mov %eax,%edx 779: 75 ed jne 768 <malloc+0x48> p = sbrk(nu * sizeof(Header)); 77b: 83 ec 0c sub $0xc,%esp 77e: 56 push %esi 77f: e8 46 fc ff ff call 3ca <sbrk> if(p == (char*)-1) 784: 83 c4 10 add $0x10,%esp 787: 83 f8 ff cmp $0xffffffff,%eax 78a: 74 1c je 7a8 <malloc+0x88> hp->s.size = nu; 78c: 89 58 04 mov %ebx,0x4(%eax) free((void*)(hp + 1)); 78f: 83 ec 0c sub $0xc,%esp 792: 83 c0 08 add $0x8,%eax 795: 50 push %eax 796: e8 f5 fe ff ff call 690 <free> return freep; 79b: 8b 15 20 0b 00 00 mov 0xb20,%edx if((p = morecore(nunits)) == 0) 7a1: 83 c4 10 add $0x10,%esp 7a4: 85 d2 test %edx,%edx 7a6: 75 c0 jne 768 <malloc+0x48> return 0; } } 7a8: 8d 65 f4 lea -0xc(%ebp),%esp return 0; 7ab: 31 c0 xor %eax,%eax } 7ad: 5b pop %ebx 7ae: 5e pop %esi 7af: 5f pop %edi 7b0: 5d pop %ebp 7b1: c3 ret 7b2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi if(p->s.size == nunits) 7b8: 39 cf cmp %ecx,%edi 7ba: 74 54 je 810 <malloc+0xf0> p->s.size -= nunits; 7bc: 29 f9 sub %edi,%ecx 7be: 89 48 04 mov %ecx,0x4(%eax) p += p->s.size; 7c1: 8d 04 c8 lea (%eax,%ecx,8),%eax p->s.size = nunits; 7c4: 89 78 04 mov %edi,0x4(%eax) freep = prevp; 7c7: 89 15 20 0b 00 00 mov %edx,0xb20 } 7cd: 8d 65 f4 lea -0xc(%ebp),%esp return (void*)(p + 1); 7d0: 83 c0 08 add $0x8,%eax } 7d3: 5b pop %ebx 7d4: 5e pop %esi 7d5: 5f pop %edi 7d6: 5d pop %ebp 7d7: c3 ret 7d8: 90 nop 7d9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi base.s.ptr = freep = prevp = &base; 7e0: c7 05 20 0b 00 00 24 movl $0xb24,0xb20 7e7: 0b 00 00 7ea: c7 05 24 0b 00 00 24 movl $0xb24,0xb24 7f1: 0b 00 00 base.s.size = 0; 7f4: b8 24 0b 00 00 mov $0xb24,%eax 7f9: c7 05 28 0b 00 00 00 movl $0x0,0xb28 800: 00 00 00 803: e9 44 ff ff ff jmp 74c <malloc+0x2c> 808: 90 nop 809: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi prevp->s.ptr = p->s.ptr; 810: 8b 08 mov (%eax),%ecx 812: 89 0a mov %ecx,(%edx) 814: eb b1 jmp 7c7 <malloc+0xa7>
; A063079: Bisection of A001790. ; 1,5,63,429,12155,88179,1300075,9694845,583401555,4418157975,67282234305,514589420475,15801325804719,121683714103007,1879204156221315,14544636039226909,1804857108504066435,14023284727082855679,218266320541953276229,1701063429324939500975,53098072606098965203605,414847067813984717066925,6489213830472088210604445,50803160635786570329644235,3184701532372607112841303575,24975553429171528252000152507,392032816163265715595619229845,3078975579065433024236839782951,96790954105808838152888925808407 mul $0,2 seq $0,322756 ; Denominator of expected payoff in the "Guessing Card Colors" game with a 2n-card deck, using an optimal strategy. div $0,2
/* Copyright © 2017-2020 ABBYY Production LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------------------------------------------------------------------------------------------------------*/ #include <common.h> #pragma hdrstop #include <NeoML/TraditionalML/FunctionEvaluation.h> namespace NeoML { ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// // IParamTraits CFunctionParam IParamTraits::GenerateRandom( CRandom&, const CFunctionParam&, const CFunctionParam& ) const { NeoAssert(0); return 0; } CFunctionParam IParamTraits::Mutate( CRandom&, const CFunctionParam&, const CFunctionParam&, const CFunctionParam&, double, const CFunctionParam&, const CFunctionParam& ) const { NeoAssert(0); return 0; } ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// // IFunctionEvaluation void IFunctionEvaluation::Evaluate( const CArray<CFunctionParamVector>& params, CArray<CFunctionParam>& results ) { results.SetSize( params.Size() ); for( int i = 0; i < params.Size(); ++i ) { NeoPresume( params[i].Size() == NumberOfDimensions() ); results[i] = Evaluate( params[i] ); } } CFunctionParam IFunctionEvaluation::Evaluate( const CFunctionParamVector& params ) { NeoPresume( params.Size() == NumberOfDimensions() ); CArray<CFunctionParam> results; CArray<CFunctionParamVector> packedParams; packedParams.Add( params ); Evaluate( packedParams, results ); NeoPresume( !results.IsEmpty() ); return results[0]; } ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// // CDoubleTraits static CDoubleTraits DoubleTraits; const CDoubleTraits& CDoubleTraits::GetInstance() { return DoubleTraits; } CFunctionParam CDoubleTraits::GenerateRandom( CRandom& random, const CFunctionParam& min, const CFunctionParam& max ) const { return Box( random.Uniform( Unbox( min ), Unbox( max ) ) ); } CFunctionParam CDoubleTraits::Mutate( CRandom& random, const CFunctionParam& _base, const CFunctionParam& _left, const CFunctionParam& _right, double fluctuation, const CFunctionParam& _min, const CFunctionParam& _max ) const { double base = Unbox( _base ); double minVal = Unbox( _min ); double maxVal = Unbox( _max ); double muteVal = base + fluctuation * ( Unbox( _left ) - Unbox( _right ) ); if( muteVal < minVal ) { muteVal = minVal + random.Uniform( 0, 1 ) * ( base - minVal ); } else if( muteVal > maxVal ) { muteVal = maxVal - random.Uniform( 0, 1 ) * ( maxVal - base ); } return Box( min( max( muteVal, minVal ), maxVal ) ); } bool CDoubleTraits::Less( const CFunctionParam& _left, const CFunctionParam& _right ) const { return Unbox( _left ) < Unbox( _right ); } ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// // CIntTraits static CIntTraits IntTraits; const CIntTraits& CIntTraits::GetInstance() { return IntTraits; } CFunctionParam CIntTraits::GenerateRandom( CRandom& random, const CFunctionParam& min, const CFunctionParam& max ) const { return Box( random.UniformInt( Unbox( min ), Unbox( max ) ) ); } CFunctionParam CIntTraits::Mutate( CRandom& random, const CFunctionParam& _base, const CFunctionParam& _left, const CFunctionParam& _right, double fluctuation, const CFunctionParam& _min, const CFunctionParam& _max ) const { int base = Unbox( _base ); int minVal = Unbox( _min ); int maxVal = Unbox( _max ); int muteVal = base + (int)( fluctuation * ( Unbox( _left ) - Unbox( _right ) ) ); if( muteVal < minVal ) { muteVal = minVal + (int)( random.Uniform( 0, 1 ) * ( base - minVal ) ); } else if( muteVal > maxVal ) { muteVal = maxVal - (int)( random.Uniform( 0, 1 ) * ( maxVal - base ) ); } return Box( min( max( muteVal, minVal ), maxVal ) ); } bool CIntTraits::Less( const CFunctionParam& _left, const CFunctionParam& _right ) const { return Unbox( _left ) < Unbox( _right ); } ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// // CFunctionEvaluation CFunctionEvaluation::CFunctionEvaluation( CFunction& _func ) : func( _func ) , minConstraint( _func.NumberOfDimensions() ) , maxConstraint( _func.NumberOfDimensions() ) { int dims = func.NumberOfDimensions(); CArray<CFunctionParam>& minConstraintArr = minConstraint.CopyOnWrite(); CArray<CFunctionParam>& maxConstraintArr = maxConstraint.CopyOnWrite(); const IParamTraits& traits = CDoubleTraits::GetInstance(); for( int i = 0; i < dims; ++i ) { minConstraintArr[i] = traits.GetDefaultMin(); maxConstraintArr[i] = traits.GetDefaultMax(); } } CFunctionParam CFunctionEvaluation::Evaluate( const CFunctionParamVector& param ) { NeoPresume( param.Size() == NumberOfDimensions() ); CFloatVector vec( param.Size() ); float* vecPtr = vec.CopyOnWrite(); for( int i = 0; i < param.Size(); ++i ) { vecPtr[i] = static_cast<float>( CDoubleTraits::Unbox( param[i] ) ); } return CDoubleTraits::Box( func.Evaluate( vec ) ); } }
/* MIT License Copyright (c) 2021 Attila Kiss 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. */ $NOMOD51 $INCLUDE(ALIASES.INC) $INCLUDE(CONFIG.INC) $INCLUDE(REG552.INC) $INCLUDE(MACROS.INC) $INCLUDE(EXTERNALS.INC) NAME ISR_TIMER2_COMPARE_1 $IF (ASSEMBLE_ISR_ALL = 1) $IF (ASSEMBLE_ISR_T2_COMPARE_1 = 1) $IF IN_PIR_LAB <> 1 CSEG AT 0063H $ELSE CSEG AT MONITOR_PROGRAM_OFFSET+0063H $ENDIF LJMP ISR_VECT_TIMER_2_COMPARE1 ISR_TIMER2_COMPARE1 SEGMENT CODE RSEG ISR_TIMER2_COMPARE1 ISR_VECT_TIMER_2_COMPARE1: USING 0 CLR CMI1 RETI $ENDIF $ENDIF END
; =============================================================== ; Dec 2013 ; =============================================================== ; ; void *obstack_init(struct obstack *ob, size_t size) ; ; Create an obstack at address ob, size bytes long. ; Size must be at least seven bytes to hold obstack header. ; ; =============================================================== SECTION code_clib SECTION code_alloc_obstack PUBLIC obstack_init_callee EXTERN asm_obstack_init obstack_init_callee: pop hl pop bc pop de push hl jp asm_obstack_init
; A017801: Binomial coefficients C(85,n). ; 1,85,3570,98770,2024785,32801517,437353560,4935847320,48124511370,411731930610,3129162672636,21335200040700,131567066917650,738799683460650,3799541229226200,17984495151670680,78682166288559225,319357027877093325,1206459883091241450,4254358535111219850,14039383165867025505,43455233608636031325,126415225043304818400,346267790336008850400,894525125034689530200,2182641305084642453688,5036864550195328739280,11006481794871273911760,22799140860804781674360,44812104450547329497880,83649261641021681729376,148409980330844919197280,250441841808300801145410,402224776237574013960810,615167304833936727234180,896386644186593516826948,1244981450259157662259650,1648759217910776363533050,2082643222624138564462800,2509852088803449039224400,2886329902123966395108060,3167923063306792384874700,3318776542511877736535400,3318776542511877736535400,3167923063306792384874700,2886329902123966395108060,2509852088803449039224400,2082643222624138564462800,1648759217910776363533050,1244981450259157662259650,896386644186593516826948,615167304833936727234180,402224776237574013960810,250441841808300801145410,148409980330844919197280,83649261641021681729376,44812104450547329497880,22799140860804781674360,11006481794871273911760,5036864550195328739280,2182641305084642453688,894525125034689530200,346267790336008850400,126415225043304818400,43455233608636031325,14039383165867025505,4254358535111219850,1206459883091241450,319357027877093325,78682166288559225,17984495151670680,3799541229226200,738799683460650,131567066917650,21335200040700,3129162672636,411731930610,48124511370,4935847320,437353560,32801517,2024785,98770,3570,85,1 mov $1,85 bin $1,$0 mov $0,$1
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; SetMem.nasm ; ; Abstract: ; ; SetMem function ; ; Notes: ; ;------------------------------------------------------------------------------ DEFAULT REL SECTION .text ;------------------------------------------------------------------------------ ; VOID * ; InternalMemSetMem ( ; IN VOID *Buffer, ; IN UINTN Count, ; IN UINT8 Value ; ) ;------------------------------------------------------------------------------ global ASM_PFX(InternalMemSetMem) ASM_PFX(InternalMemSetMem): push rdi mov rdi, rcx ; rdi <- Buffer mov al, r8b ; al <- Value mov r9, rdi ; r9 <- Buffer as return value xor rcx, rcx sub rcx, rdi and rcx, 15 ; rcx + rdi aligns on 16-byte boundary jz .0 cmp rcx, rdx cmova rcx, rdx sub rdx, rcx rep stosb .0: mov rcx, rdx and rdx, 15 shr rcx, 4 jz @SetBytes mov ah, al ; ax <- Value repeats twice movdqa [rsp + 0x10], xmm0 ; save xmm0 movd xmm0, eax ; xmm0[0..16] <- Value repeats twice pshuflw xmm0, xmm0, 0 ; xmm0[0..63] <- Value repeats 8 times movlhps xmm0, xmm0 ; xmm0 <- Value repeats 16 times .1: movntdq [rdi], xmm0 ; rdi should be 16-byte aligned add rdi, 16 loop .1 mfence movdqa xmm0, [rsp + 0x10] ; restore xmm0 @SetBytes: mov ecx, edx ; high 32 bits of rcx are always zero rep stosb mov rax, r9 ; rax <- Return value pop rdi ret
; void tshc_scroll_wc_up_pix(struct r_Rect8 *r, uchar rows, uchar pix) SECTION code_clib SECTION code_arch PUBLIC _tshc_scroll_wc_up_pix EXTERN asm0_tshc_scroll_wc_up_pix _tshc_scroll_wc_up_pix: pop af pop ix pop de push de push de push af ld l,d jp asm0_tshc_scroll_wc_up_pix
/*********************************************************************************************************************** * * * libscopeprotocols * * * * Copyright (c) 2012-2022 Andrew D. Zonenberg and contributors * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * * following conditions are met: * * * * * Redistributions of source code must retain the above copyright notice, this list of conditions, and the * * following disclaimer. * * * * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials provided with the distribution. * * * * * Neither the name of the author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "../scopehal/scopehal.h" #include "ESPIDecoder.h" #include "SPIDecoder.h" using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction ESPIDecoder::ESPIDecoder(const string& color) : PacketDecoder(color, CAT_BUS) { CreateInput("clk"); CreateInput("cs#"); CreateInput("dq3"); CreateInput("dq2"); CreateInput("dq1"); CreateInput("dq0"); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Factory methods bool ESPIDecoder::ValidateChannel(size_t i, StreamDescriptor stream) { if(stream.m_channel == NULL) return false; if( (i < 6) && (stream.GetType() == Stream::STREAM_TYPE_DIGITAL) ) return true; return false; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Accessors string ESPIDecoder::GetProtocolName() { return "Intel eSPI"; } vector<string> ESPIDecoder::GetHeaders() { vector<string> ret; ret.push_back("Command"); ret.push_back("Address"); ret.push_back("Len"); ret.push_back("Tag"); ret.push_back("Info"); ret.push_back("Response"); ret.push_back("Status"); return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Actual decoder logic void ESPIDecoder::Refresh() { ClearPackets(); //Make sure we've got valid inputs if(!VerifyAllInputsOK()) { SetData(NULL, 0); return; } //Get the input data auto clk = GetDigitalInputWaveform(0); auto csn = GetDigitalInputWaveform(1); auto data3 = GetDigitalInputWaveform(2); auto data2 = GetDigitalInputWaveform(3); auto data1 = GetDigitalInputWaveform(4); auto data0 = GetDigitalInputWaveform(5); size_t clklen = clk->m_samples.size(); size_t cslen = csn->m_samples.size(); size_t datalen[4] = { data0->m_samples.size(), data1->m_samples.size(), data2->m_samples.size(), data3->m_samples.size() }; size_t ics = 0; size_t iclk = 0; size_t idata[4] = {0}; int64_t timestamp = 0; //Create the waveform. Call SetData() early on so we can use GetText() in the packet decode auto cap = new ESPIWaveform; cap->m_timescale = clk->m_timescale; cap->m_startTimestamp = clk->m_startTimestamp; cap->m_startFemtoseconds = clk->m_startFemtoseconds; cap->m_triggerPhase = clk->m_triggerPhase; SetData(cap, 0); ESPISymbol samp; enum { LINK_STATE_DESELECTED, LINK_STATE_SELECTED_CLKLO, LINK_STATE_SELECTED_CLKHI } link_state = LINK_STATE_DESELECTED; enum { TXN_STATE_IDLE, TXN_STATE_OPCODE, TXN_STATE_CONFIG_ADDRESS, TXN_STATE_CONFIG_DATA, TXN_STATE_COMMAND_CRC8, TXN_STATE_RESPONSE, TXN_STATE_RESPONSE_DATA, TXN_STATE_STATUS, TXN_STATE_RESPONSE_CRC8, TXN_STATE_VWIRE_COUNT, TXN_STATE_VWIRE_INDEX, TXN_STATE_VWIRE_DATA, TXN_STATE_FLASH_TYPE, TXN_STATE_FLASH_TAG_LENHI, TXN_STATE_FLASH_LENLO, TXN_STATE_FLASH_ADDR, TXN_STATE_FLASH_DATA, TXN_STATE_SMBUS_TYPE, TXN_STATE_SMBUS_TAG_LENHI, TXN_STATE_SMBUS_LENLO, TXN_STATE_SMBUS_ADDR, TXN_STATE_SMBUS_DATA, TXN_STATE_IOWR_ADDR, TXN_STATE_IOWR_DATA, TXN_STATE_IORD_ADDR, TXN_STATE_COMPLETION_TYPE, TXN_STATE_COMPLETION_TAG_LENHI, TXN_STATE_COMPLETION_LENLO, TXN_STATE_COMPLETION_DATA } txn_state = TXN_STATE_IDLE; ESPISymbol::ESpiCommand current_cmd = ESPISymbol::COMMAND_RESET; Packet* pack = NULL; enum { READ_SI, READ_SO, READ_QUAD_RISING, READ_QUAD_FALLING } read_mode = READ_SI; size_t count = 0; size_t tstart = 0; uint8_t crc = 0; uint64_t data = 0; uint64_t addr = 0; size_t payload_len = 0; int skip_bits = 0; bool skip_next_falling = false; int bitcount = 0; int64_t bytestart = 0; uint8_t current_byte = 0; bool byte_valid_next = false; ESPISymbol::ESpiCompletion completion_type = ESPISymbol::COMPLETION_NONE; ESPISymbol::ESpiCycleType cycle_type = ESPISymbol::CYCLE_READ; while(true) { bool cur_cs = csn->m_samples[ics]; bool cur_clk = clk->m_samples[iclk]; uint8_t cur_data = (data3->m_samples[idata[3]] ? 0x8 : 0) | (data2->m_samples[idata[2]] ? 0x4 : 0) | (data1->m_samples[idata[1]] ? 0x2 : 0) | (data0->m_samples[idata[0]] ? 0x1 : 0); bool byte_valid = false; string stmp; char tmp[128]; switch(link_state) { case LINK_STATE_DESELECTED: if(!cur_cs) { link_state = LINK_STATE_SELECTED_CLKLO; current_byte = 0; bitcount = 0; bytestart = timestamp; //Start a new packet txn_state = TXN_STATE_OPCODE; crc = 0; } break; //end LINK_STATE_DESELECTED //wait for rising edge of clk case LINK_STATE_SELECTED_CLKLO: if(cur_clk) { if(skip_bits > 0) { skip_bits --; bytestart = timestamp; skip_next_falling = true; } else { skip_next_falling = false; //If this is the beginning of a byte, see if either DQ2 or DQ3 is low. //This means they're actively driven (since they have pullups) and means //that we're definitely in quad mode. if(bitcount == 0) { switch(read_mode) { case READ_SI: case READ_SO: if( (cur_data & 0xc) != 0xc) read_mode = READ_QUAD_RISING; break; default: break; } } //Sample on rising edges switch(read_mode) { case READ_SI: bitcount ++; current_byte <<= 1; current_byte |= (cur_data & 1); break; case READ_SO: bitcount ++; current_byte <<= 1; current_byte |= (cur_data & 2) >> 1; break; case READ_QUAD_RISING: bitcount += 4; current_byte <<= 4; current_byte |= cur_data; break; //READ_QUAD_FALLING handled in LINK_STATE_SELECTED_CLKHI default: break; } if(bitcount == 8) { byte_valid_next = true; bitcount = 0; } } link_state = LINK_STATE_SELECTED_CLKHI; } break; //end LINK_STATE_SELECTED_CLKLO //wait for falling edge of clk case LINK_STATE_SELECTED_CLKHI: if(!cur_clk) { if( (read_mode == READ_QUAD_FALLING) && !skip_next_falling) { bitcount += 4; current_byte <<= 4; current_byte |= cur_data; if(bitcount == 8) { byte_valid_next = true; bitcount = 0; } } link_state = LINK_STATE_SELECTED_CLKLO; if(byte_valid_next) { byte_valid = true; byte_valid_next = false; } } break; } //end of packet //TODO: error if a byte is truncated if( (link_state != LINK_STATE_DESELECTED) && cur_cs) { if(pack) { pack->m_len = (timestamp * clk->m_timescale) + clk->m_triggerPhase - pack->m_offset; pack = NULL; } bytestart = timestamp; link_state = LINK_STATE_DESELECTED; read_mode = READ_SI; } if(byte_valid) { switch(txn_state) { //////////////////////////////////////////////////////////////////////////////////////////////////////// // Generic command parsing //Nothign to do case TXN_STATE_IDLE: break; //end STATE_IDLE //Frame should begin with an opcode case TXN_STATE_OPCODE: //Create a new packet pack = new Packet; pack->m_len = 0; m_packets.push_back(pack); current_cmd = (ESPISymbol::ESpiCommand)current_byte; //Add symbol for packet type tstart = timestamp; pack->m_offset = bytestart * clk->m_timescale + clk->m_triggerPhase; cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_COMMAND_TYPE, current_byte)); pack->m_headers["Command"] = GetText(cap->m_samples.size()-1); //Decide what to do based on the opcode count = 0; data = 0; addr = 0; switch(current_cmd) { //Expect a 16 bit address case ESPISymbol::COMMAND_GET_CONFIGURATION: case ESPISymbol::COMMAND_SET_CONFIGURATION: pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_CONTROL]; txn_state = TXN_STATE_CONFIG_ADDRESS; break; //Expect a full flash completion case ESPISymbol::COMMAND_PUT_FLASH_C: txn_state = TXN_STATE_FLASH_TYPE; break; //Expect an OOB message case ESPISymbol::COMMAND_PUT_OOB: pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_READ]; txn_state = TXN_STATE_SMBUS_TYPE; break; //Expect a virtual wire write packet case ESPISymbol::COMMAND_PUT_VWIRE: pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_WRITE]; txn_state = TXN_STATE_VWIRE_COUNT; break; //Expect a 16-bit address followed by 1-4 bytes of data case ESPISymbol::COMMAND_PUT_IOWR_SHORT_x1: payload_len = 1; pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_WRITE]; txn_state = TXN_STATE_IOWR_ADDR; break; case ESPISymbol::COMMAND_PUT_IOWR_SHORT_x2: payload_len = 2; pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_WRITE]; txn_state = TXN_STATE_IOWR_ADDR; break; case ESPISymbol::COMMAND_PUT_IOWR_SHORT_x4: payload_len = 4; pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_WRITE]; txn_state = TXN_STATE_IOWR_ADDR; break; //Expect a 16 bit address case ESPISymbol::COMMAND_PUT_IORD_SHORT_x1: pack->m_headers["Len"] = "1"; pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_READ]; txn_state = TXN_STATE_IORD_ADDR; break; case ESPISymbol::COMMAND_PUT_IORD_SHORT_x2: pack->m_headers["Len"] = "2"; pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_READ]; txn_state = TXN_STATE_IORD_ADDR; break; case ESPISymbol::COMMAND_PUT_IORD_SHORT_x4: pack->m_headers["Len"] = "4"; pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_READ]; txn_state = TXN_STATE_IORD_ADDR; break; //No arguments case ESPISymbol::COMMAND_GET_STATUS: pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_STATUS]; txn_state = TXN_STATE_COMMAND_CRC8; break; case ESPISymbol::COMMAND_GET_FLASH_NP: case ESPISymbol::COMMAND_GET_PC: txn_state = TXN_STATE_COMMAND_CRC8; break; case ESPISymbol::COMMAND_GET_VWIRE: pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_READ]; txn_state = TXN_STATE_COMMAND_CRC8; break; case ESPISymbol::COMMAND_GET_OOB: pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_WRITE]; txn_state = TXN_STATE_COMMAND_CRC8; break; case ESPISymbol::COMMAND_RESET: pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_COMMAND]; txn_state = TXN_STATE_COMMAND_CRC8; break; //TODO case ESPISymbol::COMMAND_PUT_PC: pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_WRITE]; txn_state = TXN_STATE_IDLE; break; //Unknown default: txn_state = TXN_STATE_IDLE; pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_ERROR]; break; } break; //end TXN_STATE_OPCODE case TXN_STATE_COMMAND_CRC8: cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); if(current_byte == crc) cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_COMMAND_CRC_GOOD, current_byte)); else { cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_COMMAND_CRC_BAD, current_byte)); pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_ERROR]; } //Expect a response after a 2-cycle bus turnaround txn_state = TXN_STATE_RESPONSE; skip_bits = 2; //Switch read polarity if(read_mode == READ_SI) read_mode = READ_SO; else if(read_mode == READ_QUAD_RISING) read_mode = READ_QUAD_FALLING; break; //end TXN_STATE_COMMAND_CRC8 //////////////////////////////////////////////////////////////////////////////////////////////////////// // Configuration packets case TXN_STATE_CONFIG_ADDRESS: //Save start time if(count == 0) { tstart = bytestart; cap->m_offsets.push_back(tstart); } //Save data addr = (addr << 8) | current_byte; count ++; //Add data if(count == 2) { cap->m_durations.push_back(timestamp - tstart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_CAPS_ADDR, addr)); pack->m_headers["Address"] = GetText(cap->m_samples.size()-1); if(current_cmd == ESPISymbol::COMMAND_SET_CONFIGURATION) { txn_state = TXN_STATE_CONFIG_DATA; data = 0; count = 0; } else txn_state = TXN_STATE_COMMAND_CRC8; } break; //end TXN_STATE_CONFIG_ADDRESS case TXN_STATE_CONFIG_DATA: //Save start time if(count == 0) { tstart = bytestart; cap->m_offsets.push_back(tstart); } //Save data data |= current_byte << ( (count & 3) * 8); pack->m_data.push_back(current_byte); count ++; //Add data if(count == 4) { cap->m_durations.push_back(timestamp - tstart); switch(current_cmd) { case ESPISymbol::COMMAND_SET_CONFIGURATION: switch(addr) { case 0x10: cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_CH0_CAPS_WR, data)); pack->m_headers["Info"] = Trim(GetText(cap->m_samples.size()-1)); break; case 0x20: cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_CH1_CAPS_WR, data)); pack->m_headers["Info"] = Trim(GetText(cap->m_samples.size()-1)); break; case 0x30: cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_CH2_CAPS_WR, data)); pack->m_headers["Info"] = Trim(GetText(cap->m_samples.size()-1)); break; default: cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_COMMAND_DATA_32, data)); } break; default: cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_COMMAND_DATA_32, data)); break; } txn_state = TXN_STATE_COMMAND_CRC8; } break; //end TXN_STATE_CONFIG_DATA //////////////////////////////////////////////////////////////////////////////////////////////////////// // Generic reply packets case TXN_STATE_RESPONSE: //Handle wait states if( (current_byte & 0xcf) == 0x0f) { //Merge consecutive wait states size_t last = cap->m_samples.size() - 1; if(cap->m_samples[last].m_type == ESPISymbol::TYPE_WAIT) cap->m_durations[last] = timestamp - cap->m_offsets[last]; else { cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_WAIT)); } } else { //Start with a fresh CRC for the response phase crc = 0; cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_RESPONSE_OP, current_byte)); //TODO: support appended completions completion_type = static_cast<ESPISymbol::ESpiCompletion>(current_byte >> 6); if(completion_type != ESPISymbol::COMPLETION_NONE) LogWarning("Appended completions not implemented yet\n"); pack->m_headers["Response"] = GetText(cap->m_samples.size()-1); count = 0; data = 0; switch(current_cmd) { case ESPISymbol::COMMAND_GET_CONFIGURATION: txn_state = TXN_STATE_RESPONSE_DATA; break; case ESPISymbol::COMMAND_GET_VWIRE: txn_state = TXN_STATE_VWIRE_COUNT; break; case ESPISymbol::COMMAND_GET_FLASH_NP: txn_state = TXN_STATE_FLASH_TYPE; break; case ESPISymbol::COMMAND_GET_OOB: txn_state = TXN_STATE_SMBUS_TYPE; break; case ESPISymbol::COMMAND_GET_PC: txn_state = TXN_STATE_COMPLETION_TYPE; break; case ESPISymbol::COMMAND_GET_STATUS: default: txn_state = TXN_STATE_STATUS; break; } } break; //end TXN_STATE_RESPONSE case TXN_STATE_RESPONSE_DATA: if(count == 0) { tstart = bytestart; cap->m_offsets.push_back(tstart); } //per page 93, data is LSB to MSB data |= current_byte << ( (count & 3) * 8); count ++; pack->m_data.push_back(current_byte); //TODO: different commands have different lengths for reply data if(count == 4) { cap->m_durations.push_back(timestamp - tstart); switch(current_cmd) { case ESPISymbol::COMMAND_GET_CONFIGURATION: switch(addr) { case 0x8: cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_GENERAL_CAPS, data)); pack->m_headers["Info"] = Trim(GetText(cap->m_samples.size()-1)); break; case 0x10: cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_CH0_CAPS_RD, data)); pack->m_headers["Info"] = Trim(GetText(cap->m_samples.size()-1)); break; case 0x20: cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_CH1_CAPS_RD, data)); pack->m_headers["Info"] = Trim(GetText(cap->m_samples.size()-1)); break; case 0x30: cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_CH2_CAPS_RD, data)); pack->m_headers["Info"] = Trim(GetText(cap->m_samples.size()-1)); break; default: cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_RESPONSE_DATA_32, data)); break; } break; default: cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_RESPONSE_DATA_32, data)); break; } count = 0; data = 0; txn_state = TXN_STATE_STATUS; } break; //end TXN_STATE_RESPONSE_DATA case TXN_STATE_STATUS: //Save start time if(count == 0) { tstart = bytestart; cap->m_offsets.push_back(tstart); } //Save data (LSB to MSB) data |= current_byte << ( (count & 3) * 8); count ++; //Add data if(count == 2) { cap->m_durations.push_back(timestamp - tstart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_RESPONSE_STATUS, data)); //Don't report free space in the protocol analyzer //to save column space if(data & 0x2000) stmp += "FLASH_NP_AVAIL "; if(data & 0x1000) stmp += "FLASH_C_AVAIL "; if(data & 0x0200) stmp += "FLASH_NP_FREE "; if(data & 0x0080) stmp += "OOB_AVAIL "; if(data & 0x0040) stmp += "VWIRE_AVAIL "; if(data & 0x0020) stmp += "NP_AVAIL "; if(data & 0x0010) stmp += "PC_AVAIL "; pack->m_headers["Status"] = stmp; txn_state = TXN_STATE_RESPONSE_CRC8; } break; //end TXN_STATE_STATUS case TXN_STATE_RESPONSE_CRC8: cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); if(current_byte == crc) cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_RESPONSE_CRC_GOOD, current_byte)); else { LogDebug("Invalid response CRC (got %02x, expected %02x)\n", current_byte, crc); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_RESPONSE_CRC_BAD, current_byte)); pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_ERROR]; } //Done with the packet txn_state = TXN_STATE_IDLE; break; //end TXN_STATE_COMMAND_CRC8 //////////////////////////////////////////////////////////////////////////////////////////////////////// // Virtual wire channel case TXN_STATE_VWIRE_COUNT: cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_VWIRE_COUNT, current_byte)); count = current_byte; txn_state = TXN_STATE_VWIRE_INDEX; break; //end TXN_STATE_VWIRE_COUNT case TXN_STATE_VWIRE_INDEX: txn_state = TXN_STATE_VWIRE_DATA; addr = current_byte; cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_VWIRE_INDEX, current_byte)); break; //end TXN_STATE_VWIRE_INDEX case TXN_STATE_VWIRE_DATA: cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_VWIRE_DATA, current_byte)); //Virtual wire indexes 0/1 are IRQs if(addr <= 1) { stmp = "IRQ"; if(addr == 0) stmp += to_string(current_byte & 0x7f); else stmp += to_string( (current_byte & 0x7f) + 128 ); if(current_byte & 0x80) stmp += " high\n"; else stmp += " low\n"; pack->m_headers["Info"] += stmp; } //Indexes 2-7 are "system events". //See table 10-15 else if(addr <= 7) { switch(addr) { //Table 10 case 2: if(current_byte & 0x40) stmp += string("SLP_S5#: ") + ((current_byte & 0x4)? "1" : "0") + "\n"; if(current_byte & 0x20) stmp += string("SLP_S4#: ") + ((current_byte & 0x2)? "1" : "0") + "\n"; if(current_byte & 0x10) stmp += string("SLP_S3#: ") + ((current_byte & 0x1)? "1" : "0") + "\n"; break; //Table 11 case 3: if(current_byte & 0x40) stmp += string("OOB_RST_WARN: ") + ((current_byte & 0x4)? "1" : "0") + "\n"; if(current_byte & 0x20) stmp += string("PLTRST#: ") + ((current_byte & 0x2)? "1" : "0") + "\n"; if(current_byte & 0x10) stmp += string("SUS_STAT#: ") + ((current_byte & 0x1)? "1" : "0") + "\n"; break; //Table 12 case 4: if(current_byte & 0x80) stmp += string("PME#: ") + ((current_byte & 0x8)? "1" : "0") + "\n"; if(current_byte & 0x40) stmp += string("WAKE#: ") + ((current_byte & 0x4)? "1" : "0") + "\n"; if(current_byte & 0x10) stmp += string("OOB_RST_ACK: ") + ((current_byte & 0x1)? "1" : "0") + "\n"; break; //Table 13 case 5: if(current_byte & 0x80) stmp += string("SLAVE_BOOT_LOAD_STATUS: ") + ((current_byte & 0x8)? "1" : "0") + "\n"; if(current_byte & 0x40) stmp += string("ERROR_NONFATAL: ") + ((current_byte & 0x4)? "1" : "0") + "\n"; if(current_byte & 0x20) stmp += string("ERROR_FATAL: ") + ((current_byte & 0x2)? "1" : "0") + "\n"; if(current_byte & 0x10) stmp += string("SLAVE_BOOT_LOAD_DONE: ") + ((current_byte & 0x1)? "1" : "0") + "\n"; break; //Table 14 case 6: if(current_byte & 0x80) stmp += string("HOST_RST_ACK: ") + ((current_byte & 0x8)? "1" : "0") + "\n"; if(current_byte & 0x40) stmp += string("RCIN#: ") + ((current_byte & 0x4)? "1" : "0") + "\n"; if(current_byte & 0x20) stmp += string("SMI#: ") + ((current_byte & 0x2)? "1" : "0") + "\n"; if(current_byte & 0x10) stmp += string("SCI#: ") + ((current_byte & 0x1)? "1" : "0") + "\n"; break; //Table 15 case 7: if(current_byte & 0x40) stmp += string("NMIOUT#: ") + ((current_byte & 0x4)? "1" : "0") + "\n"; if(current_byte & 0x20) stmp += string("SMIOUT#: ") + ((current_byte & 0x2)? "1" : "0") + "\n"; if(current_byte & 0x10) stmp += string("HOST_RST_WARN: ") + ((current_byte & 0x1)? "1" : "0") + "\n"; break; } pack->m_headers["Info"] += stmp; } //Indexes 8-73 are reserved else if(addr <= 63) pack->m_headers["Info"] += "Reserved index\n"; //64-127 platform specific else if(addr <= 127) { snprintf(tmp, sizeof(tmp), "Platform specific %02lx:%02x\n", addr, current_byte); pack->m_headers["Info"] += tmp; } //128-255 GPIO expander TODO else pack->m_headers["Info"] += "GPIO expander decode not implemented\n"; if(count == 0) { //Remove trailing newline pack->m_headers["Info"] = Trim(pack->m_headers["Info"]); if(current_cmd == ESPISymbol::COMMAND_PUT_VWIRE) txn_state = TXN_STATE_COMMAND_CRC8; else txn_state = TXN_STATE_STATUS; data = 0; } else { txn_state = TXN_STATE_VWIRE_INDEX; count --; } break; //end TXN_STATE_VWIRE_DATA //////////////////////////////////////////////////////////////////////////////////////////////////////// // Flash channel case TXN_STATE_FLASH_TYPE: pack->m_data.push_back(current_byte); cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_FLASH_REQUEST_TYPE, current_byte)); txn_state = TXN_STATE_FLASH_TAG_LENHI; cycle_type = (ESPISymbol::ESpiCycleType)current_byte; switch(cycle_type) { case ESPISymbol::CYCLE_ERASE: pack->m_headers["Info"] = "Erase"; pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_WRITE]; break; case ESPISymbol::CYCLE_READ: pack->m_headers["Info"] = "Read"; pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_READ]; break; case ESPISymbol::CYCLE_WRITE: pack->m_headers["Info"] = "Write"; pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_WRITE]; break; case ESPISymbol::CYCLE_SUCCESS_DATA_FIRST: case ESPISymbol::CYCLE_SUCCESS_DATA_MIDDLE: case ESPISymbol::CYCLE_SUCCESS_DATA_LAST: case ESPISymbol::CYCLE_SUCCESS_DATA_ONLY: pack->m_headers["Info"] = "Read Data"; pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_READ]; break; default: pack->m_headers["Info"] = "Unknown flash op"; break; } break; //end TXN_STATE_FLASH_TYPE case TXN_STATE_FLASH_TAG_LENHI: pack->m_data.push_back(current_byte); //Tag is high 4 bits cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_REQUEST_TAG, current_byte >> 4)); pack->m_headers["Tag"] = to_string(current_byte >> 4); //Low 4 bits of this byte are the high length bits data = current_byte & 0xf; txn_state = TXN_STATE_FLASH_LENLO; break; //end TXN_STATE_FLASH_TAG_LENHI case TXN_STATE_FLASH_LENLO: pack->m_data.push_back(current_byte); //Save the rest of the length cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); payload_len = current_byte | data; cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_REQUEST_LEN, payload_len)); pack->m_headers["Len"] = to_string(payload_len); //Get ready to read the address or data count = 0; data = 0; if(cycle_type >= ESPISymbol::CYCLE_SUCCESS_NODATA) { pack->m_data.clear(); txn_state = TXN_STATE_FLASH_DATA; } else txn_state = TXN_STATE_FLASH_ADDR; break; //end TXN_STATE_FLASH_LENLO case TXN_STATE_FLASH_ADDR: //Save start time if(count == 0) { tstart = bytestart; cap->m_offsets.push_back(tstart); } //Save address (MSB to LSB) data = (data << 8) | current_byte; count ++; //Add data if(count == 4) { cap->m_durations.push_back(timestamp - tstart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_FLASH_REQUEST_ADDR, data)); //Don't report free space in the protocol analyzer //to save column space snprintf(tmp, sizeof(tmp), "%08lx", data); pack->m_headers["Address"] = tmp; count = 0; data = 0; //Write requests are followed by data if(cycle_type == ESPISymbol::CYCLE_WRITE) { pack->m_data.clear(); txn_state = TXN_STATE_FLASH_DATA; } //Reads and erases are done after the address else txn_state = TXN_STATE_STATUS; } break; //end TXN_STATE_FLASH_ADDR case TXN_STATE_FLASH_DATA: pack->m_data.push_back(current_byte); //Save the data byte cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_FLASH_REQUEST_DATA, current_byte)); //See if we're done count ++; if(count >= payload_len) { count = 0; data = 0; //Completion? Done with command if(current_cmd == ESPISymbol::COMMAND_PUT_FLASH_C) txn_state = TXN_STATE_COMMAND_CRC8; //Request? Done with response else txn_state = TXN_STATE_STATUS; } break; //end TXN_STATE_FLASH_DATA //////////////////////////////////////////////////////////////////////////////////////////////////////// // OOB (tunneled SMBus) channel case TXN_STATE_SMBUS_TYPE: cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_SMBUS_REQUEST_TYPE, current_byte)); txn_state = TXN_STATE_SMBUS_TAG_LENHI; //should always be CYCLE_SMBUS break; //end TXN_STATE_SMBUS_TYPE case TXN_STATE_SMBUS_TAG_LENHI: //Tag is high 4 bits cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_REQUEST_TAG, current_byte >> 4)); pack->m_headers["Tag"] = to_string(current_byte >> 4); //Low 4 bits of this byte are the high length bits data = current_byte & 0xf; txn_state = TXN_STATE_SMBUS_LENLO; break; //end TXN_STATE_SMBUS_TAG_LENHI case TXN_STATE_SMBUS_LENLO: //Save the rest of the length cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); payload_len = current_byte | data; cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_REQUEST_LEN, payload_len)); pack->m_headers["Len"] = to_string(payload_len); txn_state = TXN_STATE_SMBUS_ADDR; break; //end TXN_STATE_SMBUS_LENLO case TXN_STATE_SMBUS_ADDR: pack->m_data.clear(); //Save the SMBus address cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_SMBUS_REQUEST_ADDR, current_byte)); snprintf(tmp, sizeof(tmp), "%02x", current_byte); pack->m_headers["Address"] = tmp; //Get ready to read the packet data //We already read the first byte of the SMBus packet (the slave address) //so start count at 1. count = 1; data = 0; txn_state = TXN_STATE_SMBUS_DATA; break; //end TXN_STATE_SMBUS_ADDR case TXN_STATE_SMBUS_DATA: //Save the data byte pack->m_data.push_back(current_byte); cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_SMBUS_REQUEST_DATA, current_byte)); //See if we're done count ++; if(count >= payload_len) { count = 0; data = 0; //Completion? Done with command if(current_cmd == ESPISymbol::COMMAND_PUT_OOB) txn_state = TXN_STATE_COMMAND_CRC8; //Request? Done with response else txn_state = TXN_STATE_STATUS; } break; //end TXN_STATE_FLASH_DATA //////////////////////////////////////////////////////////////////////////////////////////////////////// // I/O channel case TXN_STATE_IOWR_ADDR: //Save start time if(count == 0) { tstart = bytestart; cap->m_offsets.push_back(tstart); } //Save address (MSB to LSB) addr = (data << 8) | current_byte; count ++; //Add data if(count == 2) { cap->m_durations.push_back(timestamp - tstart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_IO_ADDR, addr)); snprintf(tmp, sizeof(tmp), "%04lx", addr); pack->m_headers["Address"] = tmp; pack->m_headers["Len"] = to_string(payload_len); count = 0; txn_state = TXN_STATE_IOWR_DATA; } break; //end TXN_STATE_IOWR_ADDR case TXN_STATE_IOWR_DATA: //Save the data byte pack->m_data.push_back(current_byte); cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_SMBUS_REQUEST_DATA, current_byte)); //See if we're done count ++; if(count >= payload_len) { count = 0; data = 0; txn_state = TXN_STATE_COMMAND_CRC8; } break; //end TXN_STATE_IOWR_DATA case TXN_STATE_IORD_ADDR: //Save start time if(count == 0) { tstart = bytestart; cap->m_offsets.push_back(tstart); } //Save address (MSB to LSB) addr = (data << 8) | current_byte; count ++; //Add data if(count == 2) { cap->m_durations.push_back(timestamp - tstart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_IO_ADDR, addr)); snprintf(tmp, sizeof(tmp), "%04lx", addr); pack->m_headers["Address"] = tmp; count = 0; txn_state = TXN_STATE_COMMAND_CRC8; } break; //end TXN_STATE_IORD_ADDR //////////////////////////////////////////////////////////////////////////////////////////////////////// // Completions case TXN_STATE_COMPLETION_TYPE: cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_COMPLETION_TYPE, current_byte)); switch(current_byte) { case ESPISymbol::CYCLE_SUCCESS_NODATA: pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_STATUS]; break; case ESPISymbol::CYCLE_SUCCESS_DATA_MIDDLE: case ESPISymbol::CYCLE_SUCCESS_DATA_FIRST: case ESPISymbol::CYCLE_SUCCESS_DATA_LAST: case ESPISymbol::CYCLE_SUCCESS_DATA_ONLY: pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_READ]; break; case ESPISymbol::CYCLE_FAIL_LAST: case ESPISymbol::CYCLE_FAIL_ONLY: default: pack->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_ERROR]; break; } txn_state = TXN_STATE_COMPLETION_TAG_LENHI; break; //end TXN_STATE_COMPLETION_TYPE case TXN_STATE_COMPLETION_TAG_LENHI: //Tag is high 4 bits cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_REQUEST_TAG, current_byte >> 4)); pack->m_headers["Tag"] = to_string(current_byte >> 4); //Low 4 bits of this byte are the high length bits data = current_byte & 0xf; txn_state = TXN_STATE_COMPLETION_LENLO; break; //end TXN_STATE_COMPLETION_TAG_LENHI case TXN_STATE_COMPLETION_LENLO: //Save the rest of the length cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); payload_len = current_byte | data; cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_REQUEST_LEN, payload_len)); pack->m_headers["Len"] = to_string(payload_len); if(payload_len == 0) txn_state = TXN_STATE_STATUS; else txn_state = TXN_STATE_COMPLETION_DATA; break; //end TXN_STATE_COMPLETION_LENLO case TXN_STATE_COMPLETION_DATA: //Save the data byte pack->m_data.push_back(current_byte); cap->m_offsets.push_back(bytestart); cap->m_durations.push_back(timestamp - bytestart); cap->m_samples.push_back(ESPISymbol(ESPISymbol::TYPE_COMPLETION_DATA, current_byte)); //See if we're done count ++; if(count >= payload_len) { count = 0; data = 0; txn_state = TXN_STATE_STATUS; } break; //end TXN_STATE_COMPLETION_DATA } //Checksum this byte crc = UpdateCRC8(crc, current_byte); bytestart = timestamp; } //Get timestamps of next event on each channel int64_t next_cs = GetNextEventTimestamp(csn, ics, cslen, timestamp); int64_t next_clk = GetNextEventTimestamp(clk, iclk, clklen, timestamp); //If we can't move forward, stop (don't bother looking for glitches on data) int64_t next_timestamp = min(next_clk, next_cs); if(next_timestamp == timestamp) break; //All good, move on timestamp = next_timestamp; AdvanceToTimestamp(csn, ics, cslen, timestamp); AdvanceToTimestamp(clk, iclk, clklen, timestamp); AdvanceToTimestamp(data0, idata[0], datalen[0], timestamp); AdvanceToTimestamp(data1, idata[1], datalen[1], timestamp); AdvanceToTimestamp(data2, idata[2], datalen[2], timestamp); AdvanceToTimestamp(data3, idata[3], datalen[3], timestamp); } } uint8_t ESPIDecoder::UpdateCRC8(uint8_t crc, uint8_t data) { //CRC runs MSB first using polynomial x^8 + x^2 + x + 1 for(int i=7; i>=0; i--) { //Shift CRC left and save the high bit uint8_t hi = crc >> 7; crc = (crc << 1); //Mix in the new data bit hi ^= ( (data >> i) & 1); if(hi) crc ^= 0x7; } return crc; } Gdk::Color ESPIDecoder::GetColor(int i) { auto capture = dynamic_cast<ESPIWaveform*>(GetData(0)); if(capture != NULL) { const ESPISymbol& s = capture->m_samples[i]; switch(s.m_type) { case ESPISymbol::TYPE_COMMAND_TYPE: case ESPISymbol::TYPE_RESPONSE_OP: case ESPISymbol::TYPE_RESPONSE_STATUS: case ESPISymbol::TYPE_FLASH_REQUEST_TYPE: case ESPISymbol::TYPE_REQUEST_LEN: return m_standardColors[COLOR_CONTROL]; case ESPISymbol::TYPE_WAIT: return m_standardColors[COLOR_PREAMBLE]; case ESPISymbol::TYPE_CAPS_ADDR: case ESPISymbol::TYPE_VWIRE_COUNT: case ESPISymbol::TYPE_VWIRE_INDEX: case ESPISymbol::TYPE_REQUEST_TAG: case ESPISymbol::TYPE_FLASH_REQUEST_ADDR: case ESPISymbol::TYPE_SMBUS_REQUEST_ADDR: case ESPISymbol::TYPE_IO_ADDR: return m_standardColors[COLOR_ADDRESS]; case ESPISymbol::TYPE_COMMAND_CRC_GOOD: case ESPISymbol::TYPE_RESPONSE_CRC_GOOD: return m_standardColors[COLOR_CHECKSUM_OK]; case ESPISymbol::TYPE_COMMAND_CRC_BAD: case ESPISymbol::TYPE_RESPONSE_CRC_BAD: return m_standardColors[COLOR_CHECKSUM_BAD]; case ESPISymbol::TYPE_GENERAL_CAPS: case ESPISymbol::TYPE_CH0_CAPS_RD: case ESPISymbol::TYPE_CH0_CAPS_WR: case ESPISymbol::TYPE_CH1_CAPS_RD: case ESPISymbol::TYPE_CH1_CAPS_WR: case ESPISymbol::TYPE_CH2_CAPS_RD: case ESPISymbol::TYPE_CH2_CAPS_WR: case ESPISymbol::TYPE_VWIRE_DATA: case ESPISymbol::TYPE_COMMAND_DATA_32: case ESPISymbol::TYPE_RESPONSE_DATA_32: case ESPISymbol::TYPE_FLASH_REQUEST_DATA: case ESPISymbol::TYPE_SMBUS_REQUEST_DATA: case ESPISymbol::TYPE_IO_DATA: case ESPISymbol::TYPE_COMPLETION_DATA: return m_standardColors[COLOR_DATA]; case ESPISymbol::TYPE_SMBUS_REQUEST_TYPE: if(s.m_data == ESPISymbol::CYCLE_SMBUS) return m_standardColors[COLOR_CONTROL]; else return m_standardColors[COLOR_ERROR]; case ESPISymbol::TYPE_COMPLETION_TYPE: switch(s.m_data) { case ESPISymbol::CYCLE_SUCCESS_NODATA: case ESPISymbol::CYCLE_SUCCESS_DATA_MIDDLE: case ESPISymbol::CYCLE_SUCCESS_DATA_FIRST: case ESPISymbol::CYCLE_SUCCESS_DATA_LAST: case ESPISymbol::CYCLE_SUCCESS_DATA_ONLY: return m_standardColors[COLOR_CONTROL]; case ESPISymbol::CYCLE_FAIL_LAST: case ESPISymbol::CYCLE_FAIL_ONLY: default: return m_standardColors[COLOR_ERROR]; }; break; default: return m_standardColors[COLOR_ERROR]; } } return m_standardColors[COLOR_ERROR]; } string ESPIDecoder::GetText(int i) { auto capture = dynamic_cast<ESPIWaveform*>(GetData(0)); if(capture != NULL) { const ESPISymbol& s = capture->m_samples[i]; char tmp[128]; string stmp; switch(s.m_type) { case ESPISymbol::TYPE_COMMAND_TYPE: switch(s.m_data) { case ESPISymbol::COMMAND_GET_CONFIGURATION: return "Get Configuration"; case ESPISymbol::COMMAND_SET_CONFIGURATION: return "Set Configuration"; case ESPISymbol::COMMAND_GET_OOB: return "Get OOB"; case ESPISymbol::COMMAND_PUT_OOB: return "Put OOB"; case ESPISymbol::COMMAND_GET_PC: return "Get Posted Completion"; case ESPISymbol::COMMAND_PUT_PC: return "Put PC"; case ESPISymbol::COMMAND_GET_STATUS: return "Get Status"; case ESPISymbol::COMMAND_GET_FLASH_NP: return "Get Flash Non-Posted"; case ESPISymbol::COMMAND_PUT_FLASH_C: return "Put Flash Completion"; case ESPISymbol::COMMAND_GET_VWIRE: return "Get Virtual Wire"; case ESPISymbol::COMMAND_PUT_VWIRE: return "Put Virtual Wire"; case ESPISymbol::COMMAND_PUT_IOWR_SHORT_x1: case ESPISymbol::COMMAND_PUT_IOWR_SHORT_x2: case ESPISymbol::COMMAND_PUT_IOWR_SHORT_x4: return "Put I/O Write"; case ESPISymbol::COMMAND_PUT_IORD_SHORT_x1: case ESPISymbol::COMMAND_PUT_IORD_SHORT_x2: case ESPISymbol::COMMAND_PUT_IORD_SHORT_x4: return "Put I/O Read"; default: snprintf(tmp, sizeof(tmp), "Unknown Cmd (%02lx)", s.m_data); return tmp; } break; case ESPISymbol::TYPE_CAPS_ADDR: switch(s.m_data) { case 0x04: return "Device ID"; case 0x08: return "General Capabilities"; case 0x10: return "CH0 Capabilities"; case 0x20: return "CH1 Capabilities"; case 0x30: return "CH2 Capabilities"; case 0x40: return "CH3 Capabilities"; //Print as hex if unknown default: snprintf(tmp, sizeof(tmp), "%04lx", s.m_data); return tmp; } case ESPISymbol::TYPE_COMMAND_CRC_GOOD: case ESPISymbol::TYPE_COMMAND_CRC_BAD: case ESPISymbol::TYPE_RESPONSE_CRC_GOOD: case ESPISymbol::TYPE_RESPONSE_CRC_BAD: return string("CRC: ") + to_string_hex(s.m_data); case ESPISymbol::TYPE_VWIRE_COUNT: return string("Count: ") + to_string(s.m_data + 1); case ESPISymbol::TYPE_VWIRE_INDEX: return string("Index: ") + to_string_hex(s.m_data); case ESPISymbol::TYPE_VWIRE_DATA: snprintf(tmp, sizeof(tmp), "%02lx", s.m_data); return tmp; case ESPISymbol::TYPE_RESPONSE_OP: switch(s.m_data & 0xf) { case ESPISymbol::RESPONSE_DEFER: return "Defer"; case ESPISymbol::RESPONSE_NONFATAL_ERROR: return "Nonfatal Error"; case ESPISymbol::RESPONSE_FATAL_ERROR: return "Fatal Error"; case ESPISymbol::RESPONSE_ACCEPT: return "Accept"; case ESPISymbol::RESPONSE_NONE: return "No Response"; default: snprintf(tmp, sizeof(tmp), "Unknown response %lx", s.m_data & 0xf); return tmp; } break; case ESPISymbol::TYPE_GENERAL_CAPS: if(s.m_data & 0x80000000) stmp += "CRC checking enabled\n"; if(s.m_data & 0x40000000) stmp += "Response modifier enabled\n"; if( (s.m_data & 0x10000000) == 0) stmp += "DQ1 used as alert\n"; else stmp += "ALERT# used as alert\n"; switch( (s.m_data >> 26) & 0x3) { case 0: stmp += "x1 mode\n"; break; case 1: stmp += "x2 mode\n"; break; case 2: stmp += "x4 mode\n"; break; default: stmp += "Invalid IO mode\n"; break; } switch( (s.m_data >> 24) & 0x3) { case 0: stmp += "Supports x1 mode only\n"; break; case 1: stmp += "Supports x1 and x2 modes\n"; break; case 2: stmp += "Supports x1 and x4 modes\n"; break; default: stmp += "Supports x1, x2, and x4 modes\n"; break; } if(s.m_data & 0x00800000) stmp += "ALERT# configured as open drain\n"; else stmp += "ALERT# configured as push-pull\n"; switch( (s.m_data >> 20) & 0x7) { case 0: stmp += "20MHz SCK\n"; break; case 1: stmp += "25MHz SCK\n"; break; case 2: stmp += "33MHz SCK\n"; break; case 3: stmp += "50MHz SCK\n"; break; case 4: stmp += "66MHz SCK\n"; break; default: stmp += "Invalid SCK speed\n"; break; } if(s.m_data & 0x00080000) stmp += "ALERT# supports open drain mode\n"; switch( (s.m_data >> 16) & 0x7) { case 0: stmp += "Max SCK: 20 MHz\n"; break; case 1: stmp += "Max SCK: 25 MHz\n"; break; case 2: stmp += "Max SCK: 33 MHz\n"; break; case 3: stmp += "Max SCK: 50 MHz\n"; break; case 4: stmp += "Max SCK: 66 MHz\n"; break; default: stmp += "Invalid max SCK speed\n"; break; } //15:12 = max wait states if( ( (s.m_data >> 12) & 0xf) == 0) stmp += "Max wait states: 16\n"; else stmp += string("Max wait states: ") + to_string((s.m_data >> 12) & 0xf) + "\n"; if(s.m_data & 0x80) stmp += "Platform channel 7 present\n"; if(s.m_data & 0x40) stmp += "Platform channel 6 present\n"; if(s.m_data & 0x20) stmp += "Platform channel 5 present\n"; if(s.m_data & 0x10) stmp += "Platform channel 4 present\n"; if(s.m_data & 0x08) stmp += "Flash channel present\n"; if(s.m_data & 0x04) stmp += "OOB channel present\n"; if(s.m_data & 0x02) stmp += "Virtual wire channel present\n"; if(s.m_data & 0x01) stmp += "Peripheral channel present\n"; return stmp; //end TYPE_GENERAL_CAPS case ESPISymbol::TYPE_CH0_CAPS_RD: if(s.m_data & 2) stmp += "Ready\n"; else stmp += "Not ready\n"; switch( (s.m_data >> 4) & 0x7) { case 1: stmp += "Max periph payload supported: 64\n"; break; case 2: stmp += "Max periph payload supported: 128\n"; break; case 3: stmp += "Max periph payload supported: 256\n"; break; default: stmp += "Max periph payload supported: reserved\n"; break; } //end CH0_CAPS_RD //fall through case ESPISymbol::TYPE_CH0_CAPS_WR: switch( (s.m_data >> 8) & 0x7) { case 1: stmp += "Max periph payload size: 64\n"; break; case 2: stmp += "Max periph payload size: 128\n"; break; case 3: stmp += "Max periph payload size: 256\n"; break; default: stmp += "Max periph payload size: reserved\n"; break; } switch( (s.m_data >> 12) & 0x7) { case 0: stmp += "Max periph read size: reserved\n"; break; case 1: stmp += "Max periph read size: 64\n"; break; case 2: stmp += "Max periph read size: 128\n"; break; case 3: stmp += "Max periph read size: 256\n"; break; case 4: stmp += "Max periph read size: 512\n"; break; case 5: stmp += "Max periph read size: 1024\n"; break; case 6: stmp += "Max periph read size: 2048\n"; break; case 7: stmp += "Max periph read size: 4096\n"; break; } if(s.m_data & 4) stmp += "Bus mastering enabled\n"; else stmp += "Bus mastering disabled\n"; if(s.m_data & 1) stmp += "Enabled\n"; else stmp += "Disabled\n"; return stmp; //end TYPE_CH0_CAPS_WR case ESPISymbol::TYPE_CH1_CAPS_RD: stmp += "Operating max vwires: "; stmp += to_string( ((s.m_data >> 16) & 0x3f) + 1) + "\n"; stmp += "Max vwires supported: "; stmp += to_string( ((s.m_data >> 8) & 0x3f) + 1) + "\n"; if(s.m_data & 2) stmp += "Ready\n"; else stmp += "Not ready\n"; if(s.m_data & 1) stmp += "Enabled\n"; else stmp += "Disabled\n"; return stmp; //end TYPE_CH1_CAPS_RD case ESPISymbol::TYPE_CH1_CAPS_WR: stmp += "Operating max vwires: "; stmp += to_string( ((s.m_data >> 16) & 0x3f) + 1) + "\n"; if(s.m_data & 1) stmp += "Enabled\n"; else stmp += "Disabled\n"; return stmp; //end TYPE_CH1_CAPS_WR case ESPISymbol::TYPE_CH2_CAPS_RD: stmp += "Max OOB payload selected: "; switch( (s.m_data >> 8) & 0x7) { case 1: stmp += "64 bytes\n"; break; case 2: stmp += "128 bytes\n"; break; case 3: stmp += "256 bytes\n"; break; default: stmp += "Reserved\n"; break; } stmp += "Max OOB payload supported: "; switch( (s.m_data >> 4) & 0x7) { case 1: stmp += "64 bytes\n"; break; case 2: stmp += "128 bytes\n"; break; case 3: stmp += "256 bytes\n"; break; default: stmp += "Reserved\n"; break; } if(s.m_data & 2) stmp += "OOB channel ready\n"; else stmp += "OOB channel not ready\n"; if(s.m_data & 1) stmp += "OOB channel enabled\n"; else stmp += "OOB channel disabled\n"; return stmp; //end TYPE_CH2_CAPS_RD case ESPISymbol::TYPE_CH2_CAPS_WR: stmp += "Max OOB payload selected: "; switch( (s.m_data >> 8) & 0x7) { case 1: stmp += "64 bytes\n"; break; case 2: stmp += "128 bytes\n"; break; case 3: stmp += "256 bytes\n"; break; default: stmp += "Reserved\n"; break; } if(s.m_data & 1) stmp += "OOB channel enabled\n"; else stmp += "OOB channel disabled\n"; return stmp; //end TYPE_CH2_CAPS_WR case ESPISymbol::TYPE_RESPONSE_DATA_32: case ESPISymbol::TYPE_COMMAND_DATA_32: snprintf(tmp, sizeof(tmp), "%08lx", s.m_data); return tmp; case ESPISymbol::TYPE_RESPONSE_STATUS: if(s.m_data & 0x2000) stmp += "FLASH_NP_AVAIL "; if(s.m_data & 0x1000) stmp += "FLASH_C_AVAIL "; if(s.m_data & 0x0200) stmp += "FLASH_NP_FREE "; if(s.m_data & 0x0080) stmp += "OOB_AVAIL "; if(s.m_data & 0x0040) stmp += "VWIRE_AVAIL "; if(s.m_data & 0x0020) stmp += "NP_AVAIL "; if(s.m_data & 0x0010) stmp += "PC_AVAIL "; if(s.m_data & 0x0008) stmp += "OOB_FREE "; if(s.m_data & 0x0002) stmp += "NP_FREE "; if(s.m_data & 0x0001) stmp += "PC_FREE"; return stmp; case ESPISymbol::TYPE_FLASH_REQUEST_TYPE: switch(s.m_data) { case ESPISymbol::CYCLE_READ: return "Read"; case ESPISymbol::CYCLE_WRITE: return "Write"; case ESPISymbol::CYCLE_ERASE: return "Erase"; case ESPISymbol::CYCLE_SUCCESS_NODATA: case ESPISymbol::CYCLE_SUCCESS_DATA_FIRST: case ESPISymbol::CYCLE_SUCCESS_DATA_MIDDLE: case ESPISymbol::CYCLE_SUCCESS_DATA_LAST: case ESPISymbol::CYCLE_SUCCESS_DATA_ONLY: return "Success"; } break; case ESPISymbol::TYPE_REQUEST_TAG: return string("Tag: ") + to_string(s.m_data); case ESPISymbol::TYPE_REQUEST_LEN: return string("Len: ") + to_string(s.m_data); case ESPISymbol::TYPE_FLASH_REQUEST_DATA: case ESPISymbol::TYPE_IO_DATA: case ESPISymbol::TYPE_COMPLETION_DATA: snprintf(tmp, sizeof(tmp), "%02lx", s.m_data); return tmp; case ESPISymbol::TYPE_FLASH_REQUEST_ADDR: snprintf(tmp, sizeof(tmp), "Addr: %08lx", s.m_data); return tmp; case ESPISymbol::TYPE_IO_ADDR: snprintf(tmp, sizeof(tmp), "Addr: %04lx", s.m_data); return tmp; case ESPISymbol::TYPE_SMBUS_REQUEST_ADDR: snprintf(tmp, sizeof(tmp), "Addr: %02lx", s.m_data); return tmp; case ESPISymbol::TYPE_SMBUS_REQUEST_TYPE: if(s.m_data == ESPISymbol::CYCLE_SMBUS) return "SMBus Msg"; else return "Invalid"; case ESPISymbol::TYPE_SMBUS_REQUEST_DATA: snprintf(tmp, sizeof(tmp), "%02lx", s.m_data); return tmp; case ESPISymbol::TYPE_COMPLETION_TYPE: switch(s.m_data) { case ESPISymbol::CYCLE_SUCCESS_NODATA: case ESPISymbol::CYCLE_SUCCESS_DATA_MIDDLE: case ESPISymbol::CYCLE_SUCCESS_DATA_FIRST: case ESPISymbol::CYCLE_SUCCESS_DATA_LAST: case ESPISymbol::CYCLE_SUCCESS_DATA_ONLY: return "Success"; case ESPISymbol::CYCLE_FAIL_LAST: case ESPISymbol::CYCLE_FAIL_ONLY: return "Fail"; default: return "ERROR"; }; break; case ESPISymbol::TYPE_WAIT: return "Wait"; case ESPISymbol::TYPE_ERROR: default: return "ERROR"; } } return ""; } bool ESPIDecoder::CanMerge(Packet* first, Packet* /*cur*/, Packet* next) { //Merge a "Get Status" with subsequent "Get Flash Non-Posted" if( (first->m_headers["Command"] == "Get Status") && (first->m_headers["Status"].find("FLASH_NP_AVAIL") != string::npos) && (next->m_headers["Command"] == "Get Flash Non-Posted") ) { return true; } //Merge a "Get Status" with subsequent "Put Flash Completion" //TODO: Only if the tags match! if( (first->m_headers["Command"] == "Get Status") && (first->m_headers["Status"].find("FLASH_NP_AVAIL") != string::npos) && (next->m_headers["Command"] == "Put Flash Completion") ) { return true; } //Merge a "Get Status" with subsequent "Get OOB" or "Put OOB" //TODO: Only if the tags match! if( (first->m_headers["Command"] == "Get Status") && (first->m_headers["Status"].find("OOB_AVAIL") != string::npos) && (next->m_headers["Command"] == "Get OOB") ) { return true; } if( (first->m_headers["Command"] == "Get Status") && (first->m_headers["Status"].find("OOB_AVAIL") != string::npos) && (next->m_headers["Command"] == "Put OOB") ) { return true; } //Merge a "Get Status" with subsequent "Get Virtual Wire" if( (first->m_headers["Command"] == "Get Status") && (first->m_headers["Status"].find("VWIRE_AVAIL") != string::npos) && (next->m_headers["Command"] == "Get Virtual Wire") ) { return true; } //Merge a "Put I/O Write" with subsequent "Get Status" and "Get Posted Completion" if( (first->m_headers["Command"] == "Put I/O Write") && (next->m_headers["Command"] == "Get Status") && (next->m_headers["Status"].find("PC_AVAIL") != string::npos) ) { return true; } if( (first->m_headers["Command"] == "Put I/O Write") && (next->m_headers["Command"] == "Get Posted Completion") ) { return true; } //Merge a "Put I/O Read" with subsequent "Get Status" and "Get Posted Completion" if( (first->m_headers["Command"] == "Put I/O Read") && (next->m_headers["Command"] == "Get Status") && (next->m_headers["Status"].find("PC_AVAIL") != string::npos) ) { return true; } if( (first->m_headers["Command"] == "Put I/O Read") && (next->m_headers["Command"] == "Get Posted Completion") ) { return true; } //Merge consecutive status register polls if( (first->m_headers["Command"] == "Get Configuration") && (next->m_headers["Command"] == "Get Configuration") && (first->m_headers["Address"] == next->m_headers["Address"]) ) { return true; } return false; } Packet* ESPIDecoder::CreateMergedHeader(Packet* pack, size_t i) { Packet* ret = new Packet; ret->m_offset = pack->m_offset; ret->m_len = pack->m_len; //TODO: extend? Packet* first = m_packets[i]; //Fetching commands requested by the peripheral if(first->m_headers["Command"] == "Get Status") { //Look up the second packet in the string if(i+1 < m_packets.size()) { Packet* second = m_packets[i+1]; ret->m_headers["Address"] = second->m_headers["Address"]; ret->m_headers["Len"] = second->m_headers["Len"]; ret->m_headers["Tag"] = second->m_headers["Tag"]; //Flash transaction? if(second->m_headers["Command"] == "Get Flash Non-Posted") { if(second->m_headers["Info"] == "Read") { ret->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_READ]; ret->m_headers["Command"] = "Flash Read"; } else if(second->m_headers["Info"] == "Write") { ret->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_WRITE]; ret->m_headers["Command"] = "Flash Write"; } else if(second->m_headers["Info"] == "Erase") { ret->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_WRITE]; ret->m_headers["Command"] = "Flash Erase"; } //Append any flash completions we find //TODO: handle out-of-order here for(size_t j=i+2; j<m_packets.size(); j++) { Packet* p = m_packets[j]; if(p->m_headers["Command"] != "Put Flash Completion") break; if(p->m_headers["Tag"] != second->m_headers["Tag"]) break; for(auto b : p->m_data) ret->m_data.push_back(b); ret->m_len = p->m_offset + p->m_len - ret->m_offset; } } //SMBus transaction? else if(second->m_headers["Command"] == "Get OOB") { ret->m_headers["Command"] = "SMBus Access"; ret->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_WRITE]; } //Virtual Wire transaction? else if(second->m_headers["Command"] == "Get Virtual Wire") { ret->m_headers["Command"] = "Get Virtual Wire"; ret->m_headers["Info"] = second->m_headers["Info"]; ret->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_READ]; } } } //Split transactions else if(first->m_headers["Command"] == "Put I/O Write") { ret->m_headers["Command"] = "I/O Write"; ret->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_WRITE]; ret->m_headers["Address"] = first->m_headers["Address"]; ret->m_headers["Len"] = first->m_headers["Len"]; //Get data from the write packet for(auto b : first->m_data) ret->m_data.push_back(b); //Get status from completions for(size_t j=i+1; j<m_packets.size(); j++) { Packet* p = m_packets[j]; if(p->m_headers["Command"] == "Get Posted Completion") ret->m_headers["Response"] = p->m_headers["Response"]; else if(p->m_headers["Command"] == "Get Status") {} else break; ret->m_len = p->m_offset + p->m_len - ret->m_offset; } } else if(first->m_headers["Command"] == "Put I/O Read") { ret->m_headers["Command"] = "I/O Read"; ret->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_DATA_READ]; ret->m_headers["Address"] = first->m_headers["Address"]; ret->m_headers["Len"] = first->m_headers["Len"]; //Get status and data from completions for(size_t j=i+1; j<m_packets.size(); j++) { Packet* p = m_packets[j]; if(p->m_headers["Command"] == "Get Posted Completion") ret->m_headers["Response"] = p->m_headers["Response"]; else if(p->m_headers["Command"] == "Get Status") {} else break; for(auto b : p->m_data) ret->m_data.push_back(b); ret->m_len = p->m_offset + p->m_len - ret->m_offset; } } //Status register polling else if(first->m_headers["Command"] == "Get Configuration") { ret->m_headers["Command"] = "Poll Configuration"; ret->m_displayBackgroundColor = m_backgroundColors[PROTO_COLOR_CONTROL]; ret->m_headers["Address"] = first->m_headers["Address"]; //Get status and data from completions size_t ilast = i; for(size_t j=i+1; j<m_packets.size(); j++) { Packet* p = m_packets[j]; if( (p->m_headers["Command"] == "Get Configuration") && (p->m_headers["Address"] == first->m_headers["Address"]) ) { ilast = j; } else break; } Packet* last = m_packets[ilast]; ret->m_headers["Len"] = to_string(ilast - i); ret->m_headers["Info"] = last->m_headers["Info"]; ret->m_headers["Response"] = last->m_headers["Response"]; for(auto b : last->m_data) ret->m_data.push_back(b); ret->m_len = last->m_offset + last->m_len - last->m_offset; } return ret; }
; A066068: a(n) = n^n + n. ; 1,2,6,30,260,3130,46662,823550,16777224,387420498,10000000010,285311670622,8916100448268,302875106592266,11112006825558030,437893890380859390,18446744073709551632,827240261886336764194,39346408075296537575442,1978419655660313589123998,104857600000000000000000020,5842587018385982521381124442,341427877364219557396646723606,20880467999847912034355032910590,1333735776850284124449081472843800,88817841970012523233890533447265650 mov $1,$0 pow $0,$0 add $0,$1
default rel bits 64 segment .data name db 'Calvin', 0 address db '12 Mockingbird Lane', 0 balance dd 12500 format db '%s %s %d', 0xd, 0xa, 0 segment .bss ; NASM will automatically define ``Customer_size`` to be the number of bytes ; in the struct. ; If variables are declared without the ``.`` prefix, they will be accessible globally. struc Customer .id resd 1 .name resb 64 .address resb 65 ; Alignment problems could occur here since MSVC/GCC ; will automatically perform padding to pack the structure ; and align to 4 byte boundaries. NASM does not do padding, ; therefore this struct definition will not match the alignment ; of C. We place alignb 4 to force nasm compiler to perform the ; alignment as well. alignb 4 .balance resd 1 endstruc ; As before, the size of this struct will be accessible via ``TestStruct_size``. struc TestStruct ts_test_int resd 1 endstruc segment .data ; Can also make use of ``istruc``, ``iend`` and ``at`` struct instance features ; in NASM to have static variables instead. customer_memory dq 0 ; Official NASM docs say this is for declaring instances of structures. Here, ; however, we're using it to demonstrate how to make a static variable instead. ; ``at`` macro is to make use of the ``TIMES`` prefix to advance the assembly ; position to the correct point for the specified structure field, and then to ; declare the specified data. istruc TestStruct ; test structure that we will have static variables for. at ts_test_int, dd 7 ; This is a global identifier since it doesn't have the ``.`` prefix. iend array_structs_memory dq 0 segment .bss struc ArrayStructExample .id resd 1 ; 4 bytes (aligned on appropriate boundary) .name resb 65 ; 69 bytes .address resb 69 ; 134 bytes alignb 4 ; aligns to 136 .balance resd 1 ; 140 bytes .rank resb 1 ; 141 bytes alignb 4 ; aligns to 144. The alignment must be the size of the ; largest data item in the struct. i.e. if there was a ;quadword field, would need to use alignb 8 here to force nasm to align the ; _size value to be a multiple of 8. endstruc segment .text extern ExitProcess extern _CRT_INIT extern malloc extern free extern strcpy extern printf global main main: local1 equ 32 local2 equ 40 push rbp mov rbp, rsp sub rsp, 64 call _CRT_INIT ; Needed since our entry point is not _DllMainCRTStartup. See https://msdn.microsoft.com/en-us/library/708by912.aspx mov rcx, Customer_size call malloc mov [customer_memory], rax ; Fill the struct mov [rax + Customer.id], dword 7 lea rcx, [customer_memory + Customer.name] lea rdx, [name] call strcpy mov rax, [customer_memory] ; restore the pointer since ``strcpy`` blew away the value in ``rax``. lea rcx, [customer_memory + Customer.address] lea rdx, [address] call strcpy mov rax, [customer_memory] mov edx, [balance] mov [customer_memory + Customer.balance], edx lea rax, [customer_memory] call free ; Test using array of structs ; Allocate memory for 100 structs mov ecx, 100 imul ecx, ArrayStructExample_size call malloc mov [array_structs_memory], rax ; r14 and r15 are preserved through calls mov [rbp + local1], r14 mov [rbp + local2], r15 more: mov r15, 100 mov r14, [array_structs_memory] lea rcx, [format] lea edx, [r14 + ArrayStructExample.address] lea r8, [r14 + ArrayStructExample.name] mov r9, [r14 + ArrayStructExample.id] call printf add r14, ArrayStructExample_size sub r15, 1 jnz more mov r14, [rbp + local1] mov r15, [rbp + local2] xor eax, eax ; Successful exit code call ExitProcess
_rm: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 83 e4 f0 and $0xfffffff0,%esp 6: 83 ec 20 sub $0x20,%esp int i; if(argc < 2){ 9: 83 7d 08 01 cmpl $0x1,0x8(%ebp) d: 7f 19 jg 28 <main+0x28> printf(2, "Usage: rm files...\n"); f: c7 44 24 04 33 08 00 movl $0x833,0x4(%esp) 16: 00 17: c7 04 24 02 00 00 00 movl $0x2,(%esp) 1e: e8 4c 04 00 00 call 46f <printf> exit(); 23: e8 c0 02 00 00 call 2e8 <exit> } for(i = 1; i < argc; i++){ 28: c7 44 24 1c 01 00 00 movl $0x1,0x1c(%esp) 2f: 00 30: eb 43 jmp 75 <main+0x75> if(unlink(argv[i]) < 0){ 32: 8b 44 24 1c mov 0x1c(%esp),%eax 36: c1 e0 02 shl $0x2,%eax 39: 03 45 0c add 0xc(%ebp),%eax 3c: 8b 00 mov (%eax),%eax 3e: 89 04 24 mov %eax,(%esp) 41: e8 f2 02 00 00 call 338 <unlink> 46: 85 c0 test %eax,%eax 48: 79 26 jns 70 <main+0x70> printf(2, "rm: %s failed to delete\n", argv[i]); 4a: 8b 44 24 1c mov 0x1c(%esp),%eax 4e: c1 e0 02 shl $0x2,%eax 51: 03 45 0c add 0xc(%ebp),%eax 54: 8b 00 mov (%eax),%eax 56: 89 44 24 08 mov %eax,0x8(%esp) 5a: c7 44 24 04 47 08 00 movl $0x847,0x4(%esp) 61: 00 62: c7 04 24 02 00 00 00 movl $0x2,(%esp) 69: e8 01 04 00 00 call 46f <printf> break; 6e: eb 0e jmp 7e <main+0x7e> if(argc < 2){ printf(2, "Usage: rm files...\n"); exit(); } for(i = 1; i < argc; i++){ 70: 83 44 24 1c 01 addl $0x1,0x1c(%esp) 75: 8b 44 24 1c mov 0x1c(%esp),%eax 79: 3b 45 08 cmp 0x8(%ebp),%eax 7c: 7c b4 jl 32 <main+0x32> printf(2, "rm: %s failed to delete\n", argv[i]); break; } } exit(); 7e: e8 65 02 00 00 call 2e8 <exit> 83: 90 nop 00000084 <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 84: 55 push %ebp 85: 89 e5 mov %esp,%ebp 87: 57 push %edi 88: 53 push %ebx asm volatile("cld; rep stosb" : 89: 8b 4d 08 mov 0x8(%ebp),%ecx 8c: 8b 55 10 mov 0x10(%ebp),%edx 8f: 8b 45 0c mov 0xc(%ebp),%eax 92: 89 cb mov %ecx,%ebx 94: 89 df mov %ebx,%edi 96: 89 d1 mov %edx,%ecx 98: fc cld 99: f3 aa rep stos %al,%es:(%edi) 9b: 89 ca mov %ecx,%edx 9d: 89 fb mov %edi,%ebx 9f: 89 5d 08 mov %ebx,0x8(%ebp) a2: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } a5: 5b pop %ebx a6: 5f pop %edi a7: 5d pop %ebp a8: c3 ret 000000a9 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { a9: 55 push %ebp aa: 89 e5 mov %esp,%ebp ac: 83 ec 10 sub $0x10,%esp char *os; os = s; af: 8b 45 08 mov 0x8(%ebp),%eax b2: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) b5: 90 nop b6: 8b 45 0c mov 0xc(%ebp),%eax b9: 0f b6 10 movzbl (%eax),%edx bc: 8b 45 08 mov 0x8(%ebp),%eax bf: 88 10 mov %dl,(%eax) c1: 8b 45 08 mov 0x8(%ebp),%eax c4: 0f b6 00 movzbl (%eax),%eax c7: 84 c0 test %al,%al c9: 0f 95 c0 setne %al cc: 83 45 08 01 addl $0x1,0x8(%ebp) d0: 83 45 0c 01 addl $0x1,0xc(%ebp) d4: 84 c0 test %al,%al d6: 75 de jne b6 <strcpy+0xd> ; return os; d8: 8b 45 fc mov -0x4(%ebp),%eax } db: c9 leave dc: c3 ret 000000dd <strcmp>: int strcmp(const char *p, const char *q) { dd: 55 push %ebp de: 89 e5 mov %esp,%ebp while(*p && *p == *q) e0: eb 08 jmp ea <strcmp+0xd> p++, q++; e2: 83 45 08 01 addl $0x1,0x8(%ebp) e6: 83 45 0c 01 addl $0x1,0xc(%ebp) } int strcmp(const char *p, const char *q) { while(*p && *p == *q) ea: 8b 45 08 mov 0x8(%ebp),%eax ed: 0f b6 00 movzbl (%eax),%eax f0: 84 c0 test %al,%al f2: 74 10 je 104 <strcmp+0x27> f4: 8b 45 08 mov 0x8(%ebp),%eax f7: 0f b6 10 movzbl (%eax),%edx fa: 8b 45 0c mov 0xc(%ebp),%eax fd: 0f b6 00 movzbl (%eax),%eax 100: 38 c2 cmp %al,%dl 102: 74 de je e2 <strcmp+0x5> p++, q++; return (uchar)*p - (uchar)*q; 104: 8b 45 08 mov 0x8(%ebp),%eax 107: 0f b6 00 movzbl (%eax),%eax 10a: 0f b6 d0 movzbl %al,%edx 10d: 8b 45 0c mov 0xc(%ebp),%eax 110: 0f b6 00 movzbl (%eax),%eax 113: 0f b6 c0 movzbl %al,%eax 116: 89 d1 mov %edx,%ecx 118: 29 c1 sub %eax,%ecx 11a: 89 c8 mov %ecx,%eax } 11c: 5d pop %ebp 11d: c3 ret 0000011e <strlen>: uint strlen(char *s) { 11e: 55 push %ebp 11f: 89 e5 mov %esp,%ebp 121: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) 124: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 12b: eb 04 jmp 131 <strlen+0x13> 12d: 83 45 fc 01 addl $0x1,-0x4(%ebp) 131: 8b 45 fc mov -0x4(%ebp),%eax 134: 03 45 08 add 0x8(%ebp),%eax 137: 0f b6 00 movzbl (%eax),%eax 13a: 84 c0 test %al,%al 13c: 75 ef jne 12d <strlen+0xf> ; return n; 13e: 8b 45 fc mov -0x4(%ebp),%eax } 141: c9 leave 142: c3 ret 00000143 <memset>: void* memset(void *dst, int c, uint n) { 143: 55 push %ebp 144: 89 e5 mov %esp,%ebp 146: 83 ec 0c sub $0xc,%esp stosb(dst, c, n); 149: 8b 45 10 mov 0x10(%ebp),%eax 14c: 89 44 24 08 mov %eax,0x8(%esp) 150: 8b 45 0c mov 0xc(%ebp),%eax 153: 89 44 24 04 mov %eax,0x4(%esp) 157: 8b 45 08 mov 0x8(%ebp),%eax 15a: 89 04 24 mov %eax,(%esp) 15d: e8 22 ff ff ff call 84 <stosb> return dst; 162: 8b 45 08 mov 0x8(%ebp),%eax } 165: c9 leave 166: c3 ret 00000167 <strchr>: char* strchr(const char *s, char c) { 167: 55 push %ebp 168: 89 e5 mov %esp,%ebp 16a: 83 ec 04 sub $0x4,%esp 16d: 8b 45 0c mov 0xc(%ebp),%eax 170: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 173: eb 14 jmp 189 <strchr+0x22> if(*s == c) 175: 8b 45 08 mov 0x8(%ebp),%eax 178: 0f b6 00 movzbl (%eax),%eax 17b: 3a 45 fc cmp -0x4(%ebp),%al 17e: 75 05 jne 185 <strchr+0x1e> return (char*)s; 180: 8b 45 08 mov 0x8(%ebp),%eax 183: eb 13 jmp 198 <strchr+0x31> } char* strchr(const char *s, char c) { for(; *s; s++) 185: 83 45 08 01 addl $0x1,0x8(%ebp) 189: 8b 45 08 mov 0x8(%ebp),%eax 18c: 0f b6 00 movzbl (%eax),%eax 18f: 84 c0 test %al,%al 191: 75 e2 jne 175 <strchr+0xe> if(*s == c) return (char*)s; return 0; 193: b8 00 00 00 00 mov $0x0,%eax } 198: c9 leave 199: c3 ret 0000019a <gets>: char* gets(char *buf, int max) { 19a: 55 push %ebp 19b: 89 e5 mov %esp,%ebp 19d: 83 ec 28 sub $0x28,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 1a0: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 1a7: eb 44 jmp 1ed <gets+0x53> cc = read(0, &c, 1); 1a9: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 1b0: 00 1b1: 8d 45 ef lea -0x11(%ebp),%eax 1b4: 89 44 24 04 mov %eax,0x4(%esp) 1b8: c7 04 24 00 00 00 00 movl $0x0,(%esp) 1bf: e8 3c 01 00 00 call 300 <read> 1c4: 89 45 f0 mov %eax,-0x10(%ebp) if(cc < 1) 1c7: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 1cb: 7e 2d jle 1fa <gets+0x60> break; buf[i++] = c; 1cd: 8b 45 f4 mov -0xc(%ebp),%eax 1d0: 03 45 08 add 0x8(%ebp),%eax 1d3: 0f b6 55 ef movzbl -0x11(%ebp),%edx 1d7: 88 10 mov %dl,(%eax) 1d9: 83 45 f4 01 addl $0x1,-0xc(%ebp) if(c == '\n' || c == '\r') 1dd: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1e1: 3c 0a cmp $0xa,%al 1e3: 74 16 je 1fb <gets+0x61> 1e5: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1e9: 3c 0d cmp $0xd,%al 1eb: 74 0e je 1fb <gets+0x61> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1ed: 8b 45 f4 mov -0xc(%ebp),%eax 1f0: 83 c0 01 add $0x1,%eax 1f3: 3b 45 0c cmp 0xc(%ebp),%eax 1f6: 7c b1 jl 1a9 <gets+0xf> 1f8: eb 01 jmp 1fb <gets+0x61> cc = read(0, &c, 1); if(cc < 1) break; 1fa: 90 nop buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1fb: 8b 45 f4 mov -0xc(%ebp),%eax 1fe: 03 45 08 add 0x8(%ebp),%eax 201: c6 00 00 movb $0x0,(%eax) return buf; 204: 8b 45 08 mov 0x8(%ebp),%eax } 207: c9 leave 208: c3 ret 00000209 <stat>: int stat(char *n, struct stat *st) { 209: 55 push %ebp 20a: 89 e5 mov %esp,%ebp 20c: 83 ec 28 sub $0x28,%esp int fd; int r; fd = open(n, O_RDONLY); 20f: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 216: 00 217: 8b 45 08 mov 0x8(%ebp),%eax 21a: 89 04 24 mov %eax,(%esp) 21d: e8 06 01 00 00 call 328 <open> 222: 89 45 f4 mov %eax,-0xc(%ebp) if(fd < 0) 225: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 229: 79 07 jns 232 <stat+0x29> return -1; 22b: b8 ff ff ff ff mov $0xffffffff,%eax 230: eb 23 jmp 255 <stat+0x4c> r = fstat(fd, st); 232: 8b 45 0c mov 0xc(%ebp),%eax 235: 89 44 24 04 mov %eax,0x4(%esp) 239: 8b 45 f4 mov -0xc(%ebp),%eax 23c: 89 04 24 mov %eax,(%esp) 23f: e8 fc 00 00 00 call 340 <fstat> 244: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 247: 8b 45 f4 mov -0xc(%ebp),%eax 24a: 89 04 24 mov %eax,(%esp) 24d: e8 be 00 00 00 call 310 <close> return r; 252: 8b 45 f0 mov -0x10(%ebp),%eax } 255: c9 leave 256: c3 ret 00000257 <atoi>: int atoi(const char *s) { 257: 55 push %ebp 258: 89 e5 mov %esp,%ebp 25a: 83 ec 10 sub $0x10,%esp int n; n = 0; 25d: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 264: eb 23 jmp 289 <atoi+0x32> n = n*10 + *s++ - '0'; 266: 8b 55 fc mov -0x4(%ebp),%edx 269: 89 d0 mov %edx,%eax 26b: c1 e0 02 shl $0x2,%eax 26e: 01 d0 add %edx,%eax 270: 01 c0 add %eax,%eax 272: 89 c2 mov %eax,%edx 274: 8b 45 08 mov 0x8(%ebp),%eax 277: 0f b6 00 movzbl (%eax),%eax 27a: 0f be c0 movsbl %al,%eax 27d: 01 d0 add %edx,%eax 27f: 83 e8 30 sub $0x30,%eax 282: 89 45 fc mov %eax,-0x4(%ebp) 285: 83 45 08 01 addl $0x1,0x8(%ebp) atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 289: 8b 45 08 mov 0x8(%ebp),%eax 28c: 0f b6 00 movzbl (%eax),%eax 28f: 3c 2f cmp $0x2f,%al 291: 7e 0a jle 29d <atoi+0x46> 293: 8b 45 08 mov 0x8(%ebp),%eax 296: 0f b6 00 movzbl (%eax),%eax 299: 3c 39 cmp $0x39,%al 29b: 7e c9 jle 266 <atoi+0xf> n = n*10 + *s++ - '0'; return n; 29d: 8b 45 fc mov -0x4(%ebp),%eax } 2a0: c9 leave 2a1: c3 ret 000002a2 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 2a2: 55 push %ebp 2a3: 89 e5 mov %esp,%ebp 2a5: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 2a8: 8b 45 08 mov 0x8(%ebp),%eax 2ab: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 2ae: 8b 45 0c mov 0xc(%ebp),%eax 2b1: 89 45 f8 mov %eax,-0x8(%ebp) while(n-- > 0) 2b4: eb 13 jmp 2c9 <memmove+0x27> *dst++ = *src++; 2b6: 8b 45 f8 mov -0x8(%ebp),%eax 2b9: 0f b6 10 movzbl (%eax),%edx 2bc: 8b 45 fc mov -0x4(%ebp),%eax 2bf: 88 10 mov %dl,(%eax) 2c1: 83 45 fc 01 addl $0x1,-0x4(%ebp) 2c5: 83 45 f8 01 addl $0x1,-0x8(%ebp) { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 2c9: 83 7d 10 00 cmpl $0x0,0x10(%ebp) 2cd: 0f 9f c0 setg %al 2d0: 83 6d 10 01 subl $0x1,0x10(%ebp) 2d4: 84 c0 test %al,%al 2d6: 75 de jne 2b6 <memmove+0x14> *dst++ = *src++; return vdst; 2d8: 8b 45 08 mov 0x8(%ebp),%eax } 2db: c9 leave 2dc: c3 ret 2dd: 90 nop 2de: 90 nop 2df: 90 nop 000002e0 <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 2e0: b8 01 00 00 00 mov $0x1,%eax 2e5: cd 40 int $0x40 2e7: c3 ret 000002e8 <exit>: SYSCALL(exit) 2e8: b8 02 00 00 00 mov $0x2,%eax 2ed: cd 40 int $0x40 2ef: c3 ret 000002f0 <wait>: SYSCALL(wait) 2f0: b8 03 00 00 00 mov $0x3,%eax 2f5: cd 40 int $0x40 2f7: c3 ret 000002f8 <pipe>: SYSCALL(pipe) 2f8: b8 04 00 00 00 mov $0x4,%eax 2fd: cd 40 int $0x40 2ff: c3 ret 00000300 <read>: SYSCALL(read) 300: b8 05 00 00 00 mov $0x5,%eax 305: cd 40 int $0x40 307: c3 ret 00000308 <write>: SYSCALL(write) 308: b8 12 00 00 00 mov $0x12,%eax 30d: cd 40 int $0x40 30f: c3 ret 00000310 <close>: SYSCALL(close) 310: b8 17 00 00 00 mov $0x17,%eax 315: cd 40 int $0x40 317: c3 ret 00000318 <kill>: SYSCALL(kill) 318: b8 06 00 00 00 mov $0x6,%eax 31d: cd 40 int $0x40 31f: c3 ret 00000320 <exec>: SYSCALL(exec) 320: b8 07 00 00 00 mov $0x7,%eax 325: cd 40 int $0x40 327: c3 ret 00000328 <open>: SYSCALL(open) 328: b8 11 00 00 00 mov $0x11,%eax 32d: cd 40 int $0x40 32f: c3 ret 00000330 <mknod>: SYSCALL(mknod) 330: b8 13 00 00 00 mov $0x13,%eax 335: cd 40 int $0x40 337: c3 ret 00000338 <unlink>: SYSCALL(unlink) 338: b8 14 00 00 00 mov $0x14,%eax 33d: cd 40 int $0x40 33f: c3 ret 00000340 <fstat>: SYSCALL(fstat) 340: b8 08 00 00 00 mov $0x8,%eax 345: cd 40 int $0x40 347: c3 ret 00000348 <link>: SYSCALL(link) 348: b8 15 00 00 00 mov $0x15,%eax 34d: cd 40 int $0x40 34f: c3 ret 00000350 <mkdir>: SYSCALL(mkdir) 350: b8 16 00 00 00 mov $0x16,%eax 355: cd 40 int $0x40 357: c3 ret 00000358 <chdir>: SYSCALL(chdir) 358: b8 09 00 00 00 mov $0x9,%eax 35d: cd 40 int $0x40 35f: c3 ret 00000360 <dup>: SYSCALL(dup) 360: b8 0a 00 00 00 mov $0xa,%eax 365: cd 40 int $0x40 367: c3 ret 00000368 <getpid>: SYSCALL(getpid) 368: b8 0b 00 00 00 mov $0xb,%eax 36d: cd 40 int $0x40 36f: c3 ret 00000370 <sbrk>: SYSCALL(sbrk) 370: b8 0c 00 00 00 mov $0xc,%eax 375: cd 40 int $0x40 377: c3 ret 00000378 <sleep>: SYSCALL(sleep) 378: b8 0d 00 00 00 mov $0xd,%eax 37d: cd 40 int $0x40 37f: c3 ret 00000380 <uptime>: SYSCALL(uptime) 380: b8 0e 00 00 00 mov $0xe,%eax 385: cd 40 int $0x40 387: c3 ret 00000388 <procstat>: # Modificado declaramos una nueva llamada al sistema SYSCALL(procstat) 388: b8 0f 00 00 00 mov $0xf,%eax 38d: cd 40 int $0x40 38f: c3 ret 00000390 <set_priority>: # Modificado declaramos una nueva llamada al sistema SYSCALL(set_priority) 390: b8 10 00 00 00 mov $0x10,%eax 395: cd 40 int $0x40 397: c3 ret 00000398 <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 398: 55 push %ebp 399: 89 e5 mov %esp,%ebp 39b: 83 ec 28 sub $0x28,%esp 39e: 8b 45 0c mov 0xc(%ebp),%eax 3a1: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 3a4: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 3ab: 00 3ac: 8d 45 f4 lea -0xc(%ebp),%eax 3af: 89 44 24 04 mov %eax,0x4(%esp) 3b3: 8b 45 08 mov 0x8(%ebp),%eax 3b6: 89 04 24 mov %eax,(%esp) 3b9: e8 4a ff ff ff call 308 <write> } 3be: c9 leave 3bf: c3 ret 000003c0 <printint>: static void printint(int fd, int xx, int base, int sgn) { 3c0: 55 push %ebp 3c1: 89 e5 mov %esp,%ebp 3c3: 83 ec 48 sub $0x48,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 3c6: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if(sgn && xx < 0){ 3cd: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 3d1: 74 17 je 3ea <printint+0x2a> 3d3: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 3d7: 79 11 jns 3ea <printint+0x2a> neg = 1; 3d9: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 3e0: 8b 45 0c mov 0xc(%ebp),%eax 3e3: f7 d8 neg %eax 3e5: 89 45 ec mov %eax,-0x14(%ebp) 3e8: eb 06 jmp 3f0 <printint+0x30> } else { x = xx; 3ea: 8b 45 0c mov 0xc(%ebp),%eax 3ed: 89 45 ec mov %eax,-0x14(%ebp) } i = 0; 3f0: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) do{ buf[i++] = digits[x % base]; 3f7: 8b 4d 10 mov 0x10(%ebp),%ecx 3fa: 8b 45 ec mov -0x14(%ebp),%eax 3fd: ba 00 00 00 00 mov $0x0,%edx 402: f7 f1 div %ecx 404: 89 d0 mov %edx,%eax 406: 0f b6 90 a4 0a 00 00 movzbl 0xaa4(%eax),%edx 40d: 8d 45 dc lea -0x24(%ebp),%eax 410: 03 45 f4 add -0xc(%ebp),%eax 413: 88 10 mov %dl,(%eax) 415: 83 45 f4 01 addl $0x1,-0xc(%ebp) }while((x /= base) != 0); 419: 8b 55 10 mov 0x10(%ebp),%edx 41c: 89 55 d4 mov %edx,-0x2c(%ebp) 41f: 8b 45 ec mov -0x14(%ebp),%eax 422: ba 00 00 00 00 mov $0x0,%edx 427: f7 75 d4 divl -0x2c(%ebp) 42a: 89 45 ec mov %eax,-0x14(%ebp) 42d: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 431: 75 c4 jne 3f7 <printint+0x37> if(neg) 433: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 437: 74 2a je 463 <printint+0xa3> buf[i++] = '-'; 439: 8d 45 dc lea -0x24(%ebp),%eax 43c: 03 45 f4 add -0xc(%ebp),%eax 43f: c6 00 2d movb $0x2d,(%eax) 442: 83 45 f4 01 addl $0x1,-0xc(%ebp) while(--i >= 0) 446: eb 1b jmp 463 <printint+0xa3> putc(fd, buf[i]); 448: 8d 45 dc lea -0x24(%ebp),%eax 44b: 03 45 f4 add -0xc(%ebp),%eax 44e: 0f b6 00 movzbl (%eax),%eax 451: 0f be c0 movsbl %al,%eax 454: 89 44 24 04 mov %eax,0x4(%esp) 458: 8b 45 08 mov 0x8(%ebp),%eax 45b: 89 04 24 mov %eax,(%esp) 45e: e8 35 ff ff ff call 398 <putc> buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 463: 83 6d f4 01 subl $0x1,-0xc(%ebp) 467: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 46b: 79 db jns 448 <printint+0x88> putc(fd, buf[i]); } 46d: c9 leave 46e: c3 ret 0000046f <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 46f: 55 push %ebp 470: 89 e5 mov %esp,%ebp 472: 83 ec 38 sub $0x38,%esp char *s; int c, i, state; uint *ap; state = 0; 475: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) ap = (uint*)(void*)&fmt + 1; 47c: 8d 45 0c lea 0xc(%ebp),%eax 47f: 83 c0 04 add $0x4,%eax 482: 89 45 e8 mov %eax,-0x18(%ebp) for(i = 0; fmt[i]; i++){ 485: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 48c: e9 7d 01 00 00 jmp 60e <printf+0x19f> c = fmt[i] & 0xff; 491: 8b 55 0c mov 0xc(%ebp),%edx 494: 8b 45 f0 mov -0x10(%ebp),%eax 497: 01 d0 add %edx,%eax 499: 0f b6 00 movzbl (%eax),%eax 49c: 0f be c0 movsbl %al,%eax 49f: 25 ff 00 00 00 and $0xff,%eax 4a4: 89 45 e4 mov %eax,-0x1c(%ebp) if(state == 0){ 4a7: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 4ab: 75 2c jne 4d9 <printf+0x6a> if(c == '%'){ 4ad: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 4b1: 75 0c jne 4bf <printf+0x50> state = '%'; 4b3: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp) 4ba: e9 4b 01 00 00 jmp 60a <printf+0x19b> } else { putc(fd, c); 4bf: 8b 45 e4 mov -0x1c(%ebp),%eax 4c2: 0f be c0 movsbl %al,%eax 4c5: 89 44 24 04 mov %eax,0x4(%esp) 4c9: 8b 45 08 mov 0x8(%ebp),%eax 4cc: 89 04 24 mov %eax,(%esp) 4cf: e8 c4 fe ff ff call 398 <putc> 4d4: e9 31 01 00 00 jmp 60a <printf+0x19b> } } else if(state == '%'){ 4d9: 83 7d ec 25 cmpl $0x25,-0x14(%ebp) 4dd: 0f 85 27 01 00 00 jne 60a <printf+0x19b> if(c == 'd'){ 4e3: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp) 4e7: 75 2d jne 516 <printf+0xa7> printint(fd, *ap, 10, 1); 4e9: 8b 45 e8 mov -0x18(%ebp),%eax 4ec: 8b 00 mov (%eax),%eax 4ee: c7 44 24 0c 01 00 00 movl $0x1,0xc(%esp) 4f5: 00 4f6: c7 44 24 08 0a 00 00 movl $0xa,0x8(%esp) 4fd: 00 4fe: 89 44 24 04 mov %eax,0x4(%esp) 502: 8b 45 08 mov 0x8(%ebp),%eax 505: 89 04 24 mov %eax,(%esp) 508: e8 b3 fe ff ff call 3c0 <printint> ap++; 50d: 83 45 e8 04 addl $0x4,-0x18(%ebp) 511: e9 ed 00 00 00 jmp 603 <printf+0x194> } else if(c == 'x' || c == 'p'){ 516: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp) 51a: 74 06 je 522 <printf+0xb3> 51c: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp) 520: 75 2d jne 54f <printf+0xe0> printint(fd, *ap, 16, 0); 522: 8b 45 e8 mov -0x18(%ebp),%eax 525: 8b 00 mov (%eax),%eax 527: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp) 52e: 00 52f: c7 44 24 08 10 00 00 movl $0x10,0x8(%esp) 536: 00 537: 89 44 24 04 mov %eax,0x4(%esp) 53b: 8b 45 08 mov 0x8(%ebp),%eax 53e: 89 04 24 mov %eax,(%esp) 541: e8 7a fe ff ff call 3c0 <printint> ap++; 546: 83 45 e8 04 addl $0x4,-0x18(%ebp) 54a: e9 b4 00 00 00 jmp 603 <printf+0x194> } else if(c == 's'){ 54f: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp) 553: 75 46 jne 59b <printf+0x12c> s = (char*)*ap; 555: 8b 45 e8 mov -0x18(%ebp),%eax 558: 8b 00 mov (%eax),%eax 55a: 89 45 f4 mov %eax,-0xc(%ebp) ap++; 55d: 83 45 e8 04 addl $0x4,-0x18(%ebp) if(s == 0) 561: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 565: 75 27 jne 58e <printf+0x11f> s = "(null)"; 567: c7 45 f4 60 08 00 00 movl $0x860,-0xc(%ebp) while(*s != 0){ 56e: eb 1e jmp 58e <printf+0x11f> putc(fd, *s); 570: 8b 45 f4 mov -0xc(%ebp),%eax 573: 0f b6 00 movzbl (%eax),%eax 576: 0f be c0 movsbl %al,%eax 579: 89 44 24 04 mov %eax,0x4(%esp) 57d: 8b 45 08 mov 0x8(%ebp),%eax 580: 89 04 24 mov %eax,(%esp) 583: e8 10 fe ff ff call 398 <putc> s++; 588: 83 45 f4 01 addl $0x1,-0xc(%ebp) 58c: eb 01 jmp 58f <printf+0x120> } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 58e: 90 nop 58f: 8b 45 f4 mov -0xc(%ebp),%eax 592: 0f b6 00 movzbl (%eax),%eax 595: 84 c0 test %al,%al 597: 75 d7 jne 570 <printf+0x101> 599: eb 68 jmp 603 <printf+0x194> putc(fd, *s); s++; } } else if(c == 'c'){ 59b: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp) 59f: 75 1d jne 5be <printf+0x14f> putc(fd, *ap); 5a1: 8b 45 e8 mov -0x18(%ebp),%eax 5a4: 8b 00 mov (%eax),%eax 5a6: 0f be c0 movsbl %al,%eax 5a9: 89 44 24 04 mov %eax,0x4(%esp) 5ad: 8b 45 08 mov 0x8(%ebp),%eax 5b0: 89 04 24 mov %eax,(%esp) 5b3: e8 e0 fd ff ff call 398 <putc> ap++; 5b8: 83 45 e8 04 addl $0x4,-0x18(%ebp) 5bc: eb 45 jmp 603 <printf+0x194> } else if(c == '%'){ 5be: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 5c2: 75 17 jne 5db <printf+0x16c> putc(fd, c); 5c4: 8b 45 e4 mov -0x1c(%ebp),%eax 5c7: 0f be c0 movsbl %al,%eax 5ca: 89 44 24 04 mov %eax,0x4(%esp) 5ce: 8b 45 08 mov 0x8(%ebp),%eax 5d1: 89 04 24 mov %eax,(%esp) 5d4: e8 bf fd ff ff call 398 <putc> 5d9: eb 28 jmp 603 <printf+0x194> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 5db: c7 44 24 04 25 00 00 movl $0x25,0x4(%esp) 5e2: 00 5e3: 8b 45 08 mov 0x8(%ebp),%eax 5e6: 89 04 24 mov %eax,(%esp) 5e9: e8 aa fd ff ff call 398 <putc> putc(fd, c); 5ee: 8b 45 e4 mov -0x1c(%ebp),%eax 5f1: 0f be c0 movsbl %al,%eax 5f4: 89 44 24 04 mov %eax,0x4(%esp) 5f8: 8b 45 08 mov 0x8(%ebp),%eax 5fb: 89 04 24 mov %eax,(%esp) 5fe: e8 95 fd ff ff call 398 <putc> } state = 0; 603: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 60a: 83 45 f0 01 addl $0x1,-0x10(%ebp) 60e: 8b 55 0c mov 0xc(%ebp),%edx 611: 8b 45 f0 mov -0x10(%ebp),%eax 614: 01 d0 add %edx,%eax 616: 0f b6 00 movzbl (%eax),%eax 619: 84 c0 test %al,%al 61b: 0f 85 70 fe ff ff jne 491 <printf+0x22> putc(fd, c); } state = 0; } } } 621: c9 leave 622: c3 ret 623: 90 nop 00000624 <free>: static Header base; static Header *freep; void free(void *ap) { 624: 55 push %ebp 625: 89 e5 mov %esp,%ebp 627: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header*)ap - 1; 62a: 8b 45 08 mov 0x8(%ebp),%eax 62d: 83 e8 08 sub $0x8,%eax 630: 89 45 f8 mov %eax,-0x8(%ebp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 633: a1 c0 0a 00 00 mov 0xac0,%eax 638: 89 45 fc mov %eax,-0x4(%ebp) 63b: eb 24 jmp 661 <free+0x3d> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 63d: 8b 45 fc mov -0x4(%ebp),%eax 640: 8b 00 mov (%eax),%eax 642: 3b 45 fc cmp -0x4(%ebp),%eax 645: 77 12 ja 659 <free+0x35> 647: 8b 45 f8 mov -0x8(%ebp),%eax 64a: 3b 45 fc cmp -0x4(%ebp),%eax 64d: 77 24 ja 673 <free+0x4f> 64f: 8b 45 fc mov -0x4(%ebp),%eax 652: 8b 00 mov (%eax),%eax 654: 3b 45 f8 cmp -0x8(%ebp),%eax 657: 77 1a ja 673 <free+0x4f> free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 659: 8b 45 fc mov -0x4(%ebp),%eax 65c: 8b 00 mov (%eax),%eax 65e: 89 45 fc mov %eax,-0x4(%ebp) 661: 8b 45 f8 mov -0x8(%ebp),%eax 664: 3b 45 fc cmp -0x4(%ebp),%eax 667: 76 d4 jbe 63d <free+0x19> 669: 8b 45 fc mov -0x4(%ebp),%eax 66c: 8b 00 mov (%eax),%eax 66e: 3b 45 f8 cmp -0x8(%ebp),%eax 671: 76 ca jbe 63d <free+0x19> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ 673: 8b 45 f8 mov -0x8(%ebp),%eax 676: 8b 40 04 mov 0x4(%eax),%eax 679: c1 e0 03 shl $0x3,%eax 67c: 89 c2 mov %eax,%edx 67e: 03 55 f8 add -0x8(%ebp),%edx 681: 8b 45 fc mov -0x4(%ebp),%eax 684: 8b 00 mov (%eax),%eax 686: 39 c2 cmp %eax,%edx 688: 75 24 jne 6ae <free+0x8a> bp->s.size += p->s.ptr->s.size; 68a: 8b 45 f8 mov -0x8(%ebp),%eax 68d: 8b 50 04 mov 0x4(%eax),%edx 690: 8b 45 fc mov -0x4(%ebp),%eax 693: 8b 00 mov (%eax),%eax 695: 8b 40 04 mov 0x4(%eax),%eax 698: 01 c2 add %eax,%edx 69a: 8b 45 f8 mov -0x8(%ebp),%eax 69d: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 6a0: 8b 45 fc mov -0x4(%ebp),%eax 6a3: 8b 00 mov (%eax),%eax 6a5: 8b 10 mov (%eax),%edx 6a7: 8b 45 f8 mov -0x8(%ebp),%eax 6aa: 89 10 mov %edx,(%eax) 6ac: eb 0a jmp 6b8 <free+0x94> } else bp->s.ptr = p->s.ptr; 6ae: 8b 45 fc mov -0x4(%ebp),%eax 6b1: 8b 10 mov (%eax),%edx 6b3: 8b 45 f8 mov -0x8(%ebp),%eax 6b6: 89 10 mov %edx,(%eax) if(p + p->s.size == bp){ 6b8: 8b 45 fc mov -0x4(%ebp),%eax 6bb: 8b 40 04 mov 0x4(%eax),%eax 6be: c1 e0 03 shl $0x3,%eax 6c1: 03 45 fc add -0x4(%ebp),%eax 6c4: 3b 45 f8 cmp -0x8(%ebp),%eax 6c7: 75 20 jne 6e9 <free+0xc5> p->s.size += bp->s.size; 6c9: 8b 45 fc mov -0x4(%ebp),%eax 6cc: 8b 50 04 mov 0x4(%eax),%edx 6cf: 8b 45 f8 mov -0x8(%ebp),%eax 6d2: 8b 40 04 mov 0x4(%eax),%eax 6d5: 01 c2 add %eax,%edx 6d7: 8b 45 fc mov -0x4(%ebp),%eax 6da: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 6dd: 8b 45 f8 mov -0x8(%ebp),%eax 6e0: 8b 10 mov (%eax),%edx 6e2: 8b 45 fc mov -0x4(%ebp),%eax 6e5: 89 10 mov %edx,(%eax) 6e7: eb 08 jmp 6f1 <free+0xcd> } else p->s.ptr = bp; 6e9: 8b 45 fc mov -0x4(%ebp),%eax 6ec: 8b 55 f8 mov -0x8(%ebp),%edx 6ef: 89 10 mov %edx,(%eax) freep = p; 6f1: 8b 45 fc mov -0x4(%ebp),%eax 6f4: a3 c0 0a 00 00 mov %eax,0xac0 } 6f9: c9 leave 6fa: c3 ret 000006fb <morecore>: static Header* morecore(uint nu) { 6fb: 55 push %ebp 6fc: 89 e5 mov %esp,%ebp 6fe: 83 ec 28 sub $0x28,%esp char *p; Header *hp; if(nu < 4096) 701: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 708: 77 07 ja 711 <morecore+0x16> nu = 4096; 70a: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 711: 8b 45 08 mov 0x8(%ebp),%eax 714: c1 e0 03 shl $0x3,%eax 717: 89 04 24 mov %eax,(%esp) 71a: e8 51 fc ff ff call 370 <sbrk> 71f: 89 45 f4 mov %eax,-0xc(%ebp) if(p == (char*)-1) 722: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp) 726: 75 07 jne 72f <morecore+0x34> return 0; 728: b8 00 00 00 00 mov $0x0,%eax 72d: eb 22 jmp 751 <morecore+0x56> hp = (Header*)p; 72f: 8b 45 f4 mov -0xc(%ebp),%eax 732: 89 45 f0 mov %eax,-0x10(%ebp) hp->s.size = nu; 735: 8b 45 f0 mov -0x10(%ebp),%eax 738: 8b 55 08 mov 0x8(%ebp),%edx 73b: 89 50 04 mov %edx,0x4(%eax) free((void*)(hp + 1)); 73e: 8b 45 f0 mov -0x10(%ebp),%eax 741: 83 c0 08 add $0x8,%eax 744: 89 04 24 mov %eax,(%esp) 747: e8 d8 fe ff ff call 624 <free> return freep; 74c: a1 c0 0a 00 00 mov 0xac0,%eax } 751: c9 leave 752: c3 ret 00000753 <malloc>: void* malloc(uint nbytes) { 753: 55 push %ebp 754: 89 e5 mov %esp,%ebp 756: 83 ec 28 sub $0x28,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 759: 8b 45 08 mov 0x8(%ebp),%eax 75c: 83 c0 07 add $0x7,%eax 75f: c1 e8 03 shr $0x3,%eax 762: 83 c0 01 add $0x1,%eax 765: 89 45 ec mov %eax,-0x14(%ebp) if((prevp = freep) == 0){ 768: a1 c0 0a 00 00 mov 0xac0,%eax 76d: 89 45 f0 mov %eax,-0x10(%ebp) 770: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 774: 75 23 jne 799 <malloc+0x46> base.s.ptr = freep = prevp = &base; 776: c7 45 f0 b8 0a 00 00 movl $0xab8,-0x10(%ebp) 77d: 8b 45 f0 mov -0x10(%ebp),%eax 780: a3 c0 0a 00 00 mov %eax,0xac0 785: a1 c0 0a 00 00 mov 0xac0,%eax 78a: a3 b8 0a 00 00 mov %eax,0xab8 base.s.size = 0; 78f: c7 05 bc 0a 00 00 00 movl $0x0,0xabc 796: 00 00 00 } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 799: 8b 45 f0 mov -0x10(%ebp),%eax 79c: 8b 00 mov (%eax),%eax 79e: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 7a1: 8b 45 f4 mov -0xc(%ebp),%eax 7a4: 8b 40 04 mov 0x4(%eax),%eax 7a7: 3b 45 ec cmp -0x14(%ebp),%eax 7aa: 72 4d jb 7f9 <malloc+0xa6> if(p->s.size == nunits) 7ac: 8b 45 f4 mov -0xc(%ebp),%eax 7af: 8b 40 04 mov 0x4(%eax),%eax 7b2: 3b 45 ec cmp -0x14(%ebp),%eax 7b5: 75 0c jne 7c3 <malloc+0x70> prevp->s.ptr = p->s.ptr; 7b7: 8b 45 f4 mov -0xc(%ebp),%eax 7ba: 8b 10 mov (%eax),%edx 7bc: 8b 45 f0 mov -0x10(%ebp),%eax 7bf: 89 10 mov %edx,(%eax) 7c1: eb 26 jmp 7e9 <malloc+0x96> else { p->s.size -= nunits; 7c3: 8b 45 f4 mov -0xc(%ebp),%eax 7c6: 8b 40 04 mov 0x4(%eax),%eax 7c9: 89 c2 mov %eax,%edx 7cb: 2b 55 ec sub -0x14(%ebp),%edx 7ce: 8b 45 f4 mov -0xc(%ebp),%eax 7d1: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 7d4: 8b 45 f4 mov -0xc(%ebp),%eax 7d7: 8b 40 04 mov 0x4(%eax),%eax 7da: c1 e0 03 shl $0x3,%eax 7dd: 01 45 f4 add %eax,-0xc(%ebp) p->s.size = nunits; 7e0: 8b 45 f4 mov -0xc(%ebp),%eax 7e3: 8b 55 ec mov -0x14(%ebp),%edx 7e6: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 7e9: 8b 45 f0 mov -0x10(%ebp),%eax 7ec: a3 c0 0a 00 00 mov %eax,0xac0 return (void*)(p + 1); 7f1: 8b 45 f4 mov -0xc(%ebp),%eax 7f4: 83 c0 08 add $0x8,%eax 7f7: eb 38 jmp 831 <malloc+0xde> } if(p == freep) 7f9: a1 c0 0a 00 00 mov 0xac0,%eax 7fe: 39 45 f4 cmp %eax,-0xc(%ebp) 801: 75 1b jne 81e <malloc+0xcb> if((p = morecore(nunits)) == 0) 803: 8b 45 ec mov -0x14(%ebp),%eax 806: 89 04 24 mov %eax,(%esp) 809: e8 ed fe ff ff call 6fb <morecore> 80e: 89 45 f4 mov %eax,-0xc(%ebp) 811: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 815: 75 07 jne 81e <malloc+0xcb> return 0; 817: b8 00 00 00 00 mov $0x0,%eax 81c: eb 13 jmp 831 <malloc+0xde> nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 81e: 8b 45 f4 mov -0xc(%ebp),%eax 821: 89 45 f0 mov %eax,-0x10(%ebp) 824: 8b 45 f4 mov -0xc(%ebp),%eax 827: 8b 00 mov (%eax),%eax 829: 89 45 f4 mov %eax,-0xc(%ebp) return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } 82c: e9 70 ff ff ff jmp 7a1 <malloc+0x4e> } 831: c9 leave 832: c3 ret
; A165351: Numerator of 3n/2. ; 0,3,3,9,6,15,9,21,12,27,15,33,18,39,21,45,24,51,27,57,30,63,33,69,36,75,39,81,42,87,45,93,48,99,51,105,54,111,57,117,60,123,63,129,66,135,69,141,72,147,75,153,78,159,81,165,84,171,87,177,90,183,93,189,96,195,99,201,102,207,105,213,108,219,111,225,114,231,117,237,120,243,123,249,126,255,129,261,132,267,135,273,138,279,141,285,144,291,147,297,150,303,153,309,156,315,159,321,162,327,165,333,168,339,171,345,174,351,177,357,180,363,183,369,186,375,189,381,192,387,195,393,198,399,201,405,204,411,207,417,210,423,213,429,216,435,219,441,222,447,225,453,228,459,231,465,234,471,237,477,240,483,243,489,246,495,249,501,252,507,255,513,258,519,261,525,264,531,267,537,270,543,273,549,276,555,279,561,282,567,285,573,288,579,291,585,294,591,297,597,300,603,303,609,306,615,309,621,312,627,315,633,318,639,321,645,324,651,327,657,330,663,333,669,336,675,339,681,342,687,345,693,348,699,351,705,354,711,357,717,360,723,363,729,366,735,369,741,372,747 mov $1,$0 gcd $0,2 div $1,$0 mul $1,3
; size_t strlcat(char * restrict s1, const char * restrict s2, size_t n) SECTION code_clib SECTION code_string PUBLIC strlcat EXTERN asm_strlcat strlcat: IF __CPU_GBZ80__ | __CPU_INTEL__ ld hl,sp+2 ld c,(hl) inc hl ld b,(hl) inc hl ld e,(hl) inc hl ld d,(hl) inc hl ld a,(hl+) ld h,(hl) ld l,a call asm_strlcat ld d,h ld e,l ret ELSE pop af pop bc pop de pop hl push hl push de push bc push af jp asm_strlcat ENDIF ; SDCC bridge for Classic IF __CLASSIC PUBLIC _strlcat defc _strlcat = strlcat ENDIF
#include "rviz_marker/nodelet.h" namespace rviz_marker { void RvizMarkerNodelet::onInit() { ros::NodeHandle& private_nh = getPrivateNodeHandle(); // Define publishers ros::Publisher robot_visu_pub = private_nh.advertise<visualization_msgs::MarkerArray>("/robot_marker_array", 1000); ros::Publisher human_cylinder_visu_pub = private_nh.advertise<visualization_msgs::MarkerArray>( "/human_cylinder_marker_array", 1000); ros::Publisher human_reach_visu_pub_P = private_nh.advertise<visualization_msgs::MarkerArray>( "/human_reach_marker_array/P", 1000); ros::Publisher human_reach_visu_pub_V = private_nh.advertise<visualization_msgs::MarkerArray>( "/human_reach_marker_array/V", 1000); ros::Publisher human_reach_visu_pub_A = private_nh.advertise<visualization_msgs::MarkerArray>( "/human_reach_marker_array/A", 1000); // Create rviz marker object rviz_marker_ = RvizMarker(robot_visu_pub, human_cylinder_visu_pub, human_reach_visu_pub_P, human_reach_visu_pub_V, human_reach_visu_pub_A); // Define subscribers robot_capsule_sub_ = private_nh.subscribe("/robot_capsules", 1000, &RvizMarker::robot_callback, &rviz_marker_); advanced_robot_capsule_sub_ = private_nh.subscribe("/advanced_robot_capsules", 1000, &RvizMarker::advanced_robot_callback, &rviz_marker_); human_cylinder_sub_ = private_nh.subscribe("/human_polycapsules", 1000, &RvizMarker::human_cylinder_callback, &rviz_marker_); human_reach_sub_P_ = private_nh.subscribe("/human_reach_capsules/P", 1000, &RvizMarker::human_reach_callback_p, &rviz_marker_); human_reach_sub_V_ = private_nh.subscribe("/human_reach_capsules/V", 1000, &RvizMarker::human_reach_callback_v, &rviz_marker_); human_reach_sub_A_ = private_nh.subscribe("/human_reach_capsules/A", 1000, &RvizMarker::human_reach_callback_a, &rviz_marker_); } } // namespace rviz_marker PLUGINLIB_EXPORT_CLASS(rviz_marker::RvizMarkerNodelet, nodelet::Nodelet);
#include <qt/createcontract.h> #include <qt/forms/ui_createcontract.h> #include <qt/platformstyle.h> #include <qt/walletmodel.h> #include <qt/clientmodel.h> #include <qt/guiconstants.h> #include <qt/rpcconsole.h> #include <qt/execrpccommand.h> #include <qt/bitcoinunits.h> #include <qt/optionsmodel.h> #include <validation.h> #include <util/moneystr.h> #include <qt/addressfield.h> #include <qt/abifunctionfield.h> #include <qt/contractutil.h> #include <qt/tabbarinfo.h> #include <qt/contractresult.h> #include <qt/sendcoinsdialog.h> #include <qt/styleSheet.h> #include <interfaces/node.h> #include <QRegularExpressionValidator> namespace CreateContract_NS { // Contract data names static const QString PRC_COMMAND = "createcontract"; static const QString PARAM_BYTECODE = "bytecode"; static const QString PARAM_GASLIMIT = "gaslimit"; static const QString PARAM_GASPRICE = "gasprice"; static const QString PARAM_SENDER = "sender"; static const CAmount SINGLE_STEP = 0.00000001*COIN; static const CAmount HIGH_GASPRICE = 0.001*COIN; } using namespace CreateContract_NS; CreateContract::CreateContract(const PlatformStyle *platformStyle, QWidget *parent) : QWidget(parent), ui(new Ui::CreateContract), m_model(0), m_clientModel(0), m_execRPCCommand(0), m_ABIFunctionField(0), m_contractABI(0), m_tabInfo(0), m_results(1) { // Setup ui components Q_UNUSED(platformStyle); ui->setupUi(this); // Set stylesheet SetObjectStyleSheet(ui->pushButtonClearAll, StyleSheetNames::ButtonDark); setLinkLabels(); m_ABIFunctionField = new ABIFunctionField(platformStyle, ABIFunctionField::Create, ui->scrollAreaConstructor); ui->scrollAreaConstructor->setWidget(m_ABIFunctionField); ui->labelBytecode->setToolTip(tr("The bytecode of the contract")); ui->labelSenderAddress->setToolTip(tr("The cico address that will be used to create the contract.")); m_tabInfo = new TabBarInfo(ui->stackedWidget); m_tabInfo->addTab(0, tr("Create Contract")); // Set defaults ui->lineEditGasPrice->setValue(DEFAULT_GAS_PRICE); ui->lineEditGasPrice->setSingleStep(SINGLE_STEP); ui->lineEditGasLimit->setMinimum(MINIMUM_GAS_LIMIT); ui->lineEditGasLimit->setMaximum(DEFAULT_GAS_LIMIT_OP_CREATE); ui->lineEditGasLimit->setValue(DEFAULT_GAS_LIMIT_OP_CREATE); ui->pushButtonCreateContract->setEnabled(false); ui->lineEditSenderAddress->setSenderAddress(true); // Create new PRC command line interface QStringList lstMandatory; lstMandatory.append(PARAM_BYTECODE); QStringList lstOptional; lstOptional.append(PARAM_GASLIMIT); lstOptional.append(PARAM_GASPRICE); lstOptional.append(PARAM_SENDER); QMap<QString, QString> lstTranslations; lstTranslations[PARAM_BYTECODE] = ui->labelBytecode->text(); lstTranslations[PARAM_GASLIMIT] = ui->labelGasLimit->text(); lstTranslations[PARAM_GASPRICE] = ui->labelGasPrice->text(); lstTranslations[PARAM_SENDER] = ui->labelSenderAddress->text(); m_execRPCCommand = new ExecRPCCommand(PRC_COMMAND, lstMandatory, lstOptional, lstTranslations, this); m_contractABI = new ContractABI(); // Connect signals with slots connect(ui->pushButtonClearAll, &QPushButton::clicked, this, &CreateContract::on_clearAllClicked); connect(ui->pushButtonCreateContract, &QPushButton::clicked, this, &CreateContract::on_createContractClicked); connect(ui->textEditBytecode, &QValidatedTextEdit::textChanged, this, &CreateContract::on_updateCreateButton); connect(ui->textEditInterface, &QValidatedTextEdit::textChanged, this, &CreateContract::on_newContractABI); connect(ui->stackedWidget, &QStackedWidget::currentChanged, this, &CreateContract::on_updateCreateButton); // Set bytecode validator QRegularExpression regEx; regEx.setPattern(paternHex); QRegularExpressionValidator *bytecodeValidator = new QRegularExpressionValidator(ui->textEditBytecode); bytecodeValidator->setRegularExpression(regEx); ui->textEditBytecode->setCheckValidator(bytecodeValidator); } CreateContract::~CreateContract() { delete m_contractABI; delete ui; } void CreateContract::setLinkLabels() { ui->labelSolidity->setOpenExternalLinks(true); ui->labelSolidity->setText("<a href=\"https://qmix.coinicles.tech/\">Solidity compiler</a>"); } void CreateContract::setModel(WalletModel *_model) { m_model = _model; ui->lineEditSenderAddress->setWalletModel(m_model); if (m_model && m_model->getOptionsModel()) connect(m_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &CreateContract::updateDisplayUnit); // update the display unit, to not use the default ("CICO") updateDisplayUnit(); } bool CreateContract::isValidBytecode() { ui->textEditBytecode->checkValidity(); return ui->textEditBytecode->isValid(); } bool CreateContract::isValidInterfaceABI() { ui->textEditInterface->checkValidity(); return ui->textEditInterface->isValid(); } bool CreateContract::isDataValid() { bool dataValid = true; int func = m_ABIFunctionField->getSelectedFunction(); bool funcValid = func == -1 ? true : m_ABIFunctionField->isValid(); if(!isValidBytecode()) dataValid = false; if(!isValidInterfaceABI()) dataValid = false; if(!funcValid) dataValid = false; return dataValid; } void CreateContract::setClientModel(ClientModel *_clientModel) { m_clientModel = _clientModel; if (m_clientModel) { connect(m_clientModel, SIGNAL(gasInfoChanged(quint64, quint64, quint64)), this, SLOT(on_gasInfoChanged(quint64, quint64, quint64))); } } void CreateContract::on_clearAllClicked() { ui->textEditBytecode->clear(); ui->lineEditGasLimit->setValue(DEFAULT_GAS_LIMIT_OP_CREATE); ui->lineEditGasPrice->setValue(DEFAULT_GAS_PRICE); ui->lineEditSenderAddress->setCurrentIndex(-1); ui->textEditInterface->clear(); m_tabInfo->clear(); } void CreateContract::on_createContractClicked() { if(isDataValid()) { WalletModel::UnlockContext ctx(m_model->requestUnlock()); if(!ctx.isValid()) { return; } // Initialize variables QMap<QString, QString> lstParams; QVariant result; QString errorMessage; QString resultJson; int unit = BitcoinUnits::BTC; uint64_t gasLimit = ui->lineEditGasLimit->value(); CAmount gasPrice = ui->lineEditGasPrice->value(); int func = m_ABIFunctionField->getSelectedFunction(); // Check for high gas price if(gasPrice > HIGH_GASPRICE) { QString message = tr("The Gas Price is too high, are you sure you want to possibly spend a max of %1 for this transaction?"); if(QMessageBox::question(this, tr("High Gas price"), message.arg(BitcoinUnits::formatWithUnit(unit, gasLimit * gasPrice))) == QMessageBox::No) return; } // Append params to the list QString bytecode = ui->textEditBytecode->toPlainText() + toDataHex(func, errorMessage); ExecRPCCommand::appendParam(lstParams, PARAM_BYTECODE, bytecode); ExecRPCCommand::appendParam(lstParams, PARAM_GASLIMIT, QString::number(gasLimit)); ExecRPCCommand::appendParam(lstParams, PARAM_GASPRICE, BitcoinUnits::format(unit, gasPrice, false, BitcoinUnits::separatorNever)); ExecRPCCommand::appendParam(lstParams, PARAM_SENDER, ui->lineEditSenderAddress->currentText()); QString questionString = tr("Are you sure you want to create contract? <br />"); SendConfirmationDialog confirmationDialog(tr("Confirm contract creation."), questionString, "", "", SEND_CONFIRM_DELAY, this); confirmationDialog.exec(); QMessageBox::StandardButton retval = (QMessageBox::StandardButton)confirmationDialog.result(); if(retval == QMessageBox::Yes) { // Execute RPC command line if(errorMessage.isEmpty() && m_execRPCCommand->exec(m_model->node(), m_model, lstParams, result, resultJson, errorMessage)) { ContractResult *widgetResult = new ContractResult(ui->stackedWidget); widgetResult->setResultData(result, FunctionABI(), QList<QStringList>(), ContractResult::CreateResult); ui->stackedWidget->addWidget(widgetResult); int position = ui->stackedWidget->count() - 1; m_results = position == 1 ? 1 : m_results + 1; m_tabInfo->addTab(position, tr("Result %1").arg(m_results)); m_tabInfo->setCurrent(position); } else { QMessageBox::warning(this, tr("Create contract"), errorMessage); } } } } void CreateContract::on_gasInfoChanged(quint64 blockGasLimit, quint64 minGasPrice, quint64 nGasPrice) { Q_UNUSED(nGasPrice); ui->labelGasLimit->setToolTip(tr("Gas limit. Default = %1, Max = %2").arg(DEFAULT_GAS_LIMIT_OP_CREATE).arg(blockGasLimit)); ui->labelGasPrice->setToolTip(tr("Gas price: CICO price per gas unit. Default = %1, Min = %2").arg(QString::fromStdString(FormatMoney(DEFAULT_GAS_PRICE))).arg(QString::fromStdString(FormatMoney(minGasPrice)))); ui->lineEditGasPrice->SetMinValue(minGasPrice); ui->lineEditGasLimit->setMaximum(blockGasLimit); } void CreateContract::on_updateCreateButton() { bool enabled = true; if(ui->textEditBytecode->toPlainText().isEmpty()) { enabled = false; } enabled &= ui->stackedWidget->currentIndex() == 0; ui->pushButtonCreateContract->setEnabled(enabled); } void CreateContract::on_newContractABI() { std::string json_data = ui->textEditInterface->toPlainText().toStdString(); if(!m_contractABI->loads(json_data)) { m_contractABI->clean(); ui->textEditInterface->setIsValidManually(false); } else { ui->textEditInterface->setIsValidManually(true); } m_ABIFunctionField->setContractABI(m_contractABI); on_updateCreateButton(); } void CreateContract::updateDisplayUnit() { if(m_model && m_model->getOptionsModel()) { // Update gasPriceAmount with the current unit ui->lineEditGasPrice->setDisplayUnit(m_model->getOptionsModel()->getDisplayUnit()); } } QString CreateContract::toDataHex(int func, QString& errorMessage) { if(func == -1 || m_ABIFunctionField == NULL || m_contractABI == NULL) { return ""; } std::string strData; std::vector<std::vector<std::string>> values = m_ABIFunctionField->getValuesVector(); FunctionABI function = m_contractABI->functions[func]; std::vector<ParameterABI::ErrorType> errors; if(function.abiIn(values, strData, errors)) { return QString::fromStdString(strData); } else { errorMessage = ContractUtil::errorMessage(function, errors, true); } return ""; }
// wiredtiger_kv_engine_test.cpp /** * Copyright (C) 2014 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/db/storage/kv/kv_engine_test_harness.h" #include "mongo/db/storage/wiredtiger/wiredtiger_kv_engine.h" #include "mongo/db/storage/wiredtiger/wiredtiger_record_store.h" #include "mongo/stdx/memory.h" #include "mongo/unittest/temp_dir.h" #include "mongo/util/clock_source_mock.h" namespace mongo { class WiredTigerKVHarnessHelper : public KVHarnessHelper { public: WiredTigerKVHarnessHelper() : _dbpath("wt-kv-harness") { _engine.reset(new WiredTigerKVEngine( kWiredTigerEngineName, _dbpath.path(), _cs.get(), "", 1, false, false, false, false)); } virtual ~WiredTigerKVHarnessHelper() { _engine.reset(NULL); } virtual KVEngine* restartEngine() { _engine.reset(NULL); _engine.reset(new WiredTigerKVEngine( kWiredTigerEngineName, _dbpath.path(), _cs.get(), "", 1, false, false, false, false)); return _engine.get(); } virtual KVEngine* getEngine() { return _engine.get(); } private: const std::unique_ptr<ClockSource> _cs = stdx::make_unique<ClockSourceMock>(); unittest::TempDir _dbpath; std::unique_ptr<WiredTigerKVEngine> _engine; }; KVHarnessHelper* KVHarnessHelper::create() { return new WiredTigerKVHarnessHelper(); } }
; A261521: a(n) = n^2 + 2*n + 29. ; 29,32,37,44,53,64,77,92,109,128,149,172,197,224,253,284,317,352,389,428,469,512,557,604,653,704,757,812,869,928,989,1052,1117,1184,1253,1324,1397,1472,1549,1628,1709,1792,1877,1964,2053,2144,2237,2332,2429,2528 mov $1,$0 add $1,1 pow $1,2 add $1,28
;; 32bit asm functions for everything you need before loading your ;; 32bit kernel. ;; Note that this stuff does not include GDT or anything like that, ;; that is already defined in a file that is not in util/ ;; Fast reset A20 line, doesn't work on all processors _init_a20: in al, 0x92 or al, 2 out 0x92, al
;----------------------------------------------------------; ; BOS kernel Christoffer Bubach, 2004-2012. ; ;----------------------------------------------------------; ; ; ; floppy disk driver. ; ; ; ;----------------------------------------------------------; ;---------------------------; ; variables and contants ; ;---------------------------; fdd_int_done dw 0 ; is the IRQ done? fdd_motor_on db 0 ; fdd motor on=1, off=0 fdd_drivehead db 0 ; ((head*4)|drive) fdd_head db 0 fdd_track db 0 fdd_sector db 0 fdd_error db 0 ; should we recalibrate ; at next read/write? fdd_errorcode db 0 result_ST0 db 0 result_ST1 db 0 ; or pcn result_ST2 db 0 result_ST3 db 0 result_C db 0 result_H db 0 result_R db 0 result_N db 0 result_extra db 0 ;------------------------------------------------------; ; initializes the floppy disk driver ; ; ; ;------------------------------------------------------; fdc_init: push eax push ebx push ecx push edi push esi xor eax, eax ; get configuration mov al, 0x10 ; from CMOS. out 0x70, al in al, 0x71 shr al, 4 cmp al, 4 ; a 1.44mb? jnz .no_floppy mov cl, 0x26 ; hook IRQ 6 mov dx, 0x8 ; CS = 8 mov edi, floppy_irq call set_int mov cl, 6 ; enable IRQ6 call enable_irq call fdd_reset ; reset FDC .no_floppy: pop esi pop edi pop ecx pop ebx pop eax ret ;------------------------------------------------------; ; floppy IRQ ; ; ; ;------------------------------------------------------; floppy_irq: push ds push eax push ebx mov ax, 0x10 mov ds, ax mov [fdd_int_done], 1 mov al, 0x20 out 0x20, al pop ebx pop eax pop ds iret ;------------------------------------------------------; ; wait for a floppy int ; ; out: cf = 1 if timeout ; ;------------------------------------------------------; wait_int: push eax push ecx mov ecx, 150 ; 50 = 0.5 seconds. call active_delay ; timer.inc .l1: cmp dword [ecx], 0 ; timeup? je .error mov ax, [fdd_int_done] ; if not we check for int. or ax, ax jz .l1 clc jmp .end .error: stc .end: pop ecx pop eax ret ;------------------------------------------------------; ; fdd motor off ; ; out: nothing ; ;------------------------------------------------------; fdd_off: cmp [fdd_motor_on], 0 je .end push eax push edx mov dx, 0x3F2 mov al, 0x0c ; motor off out dx, al mov [fdd_motor_on], 0 pop edx pop eax .end: ret ;------------------------------------------------------; ; fdd motor on ; ; out: nothing ; ;------------------------------------------------------; fdd_on: cmp [fdd_motor_on], 1 je .end push eax push edx mov dx, 0x3F2 ; motor 0 on.. mov al, 0x1C out dx, al mov ecx, 20 ; 1/5 of a sec. to speed up call delay ; in timer.inc mov [fdd_motor_on], 1 pop edx pop eax .end: ret ;------------------------------------------------------; ; send a data byte to the FDC ; ; ; ; in: al = data byte ; ;------------------------------------------------------; fdc_sendbyte: push edx push ecx push eax mov ecx, 50 ; 50 = 0.5 seconds. call active_delay ; timer.inc .l1: cmp dword [ecx], 0 ; timeup? je .error mov dx, 0x3f4 ; check status reg in al, dx and al, 0xC0 cmp al, 0x80 ; ok to write? jnz .l1 pop eax pop ecx mov dx, 0x3F5 ; send byte out dx, al pop edx clc ret .error: pop eax pop ecx pop edx stc ret ;------------------------------------------------------; ; read a data byte from the FDC ; ; ; ; out: al = data byte ; ;------------------------------------------------------; fdc_getbyte: push edx push ecx push eax mov ecx, 50 ; 50 = 0.5 seconds. call active_delay ; timer.inc .l1: cmp dword [ecx], 0 ; timeup? je .error mov dx, 0x3f4 ; check status reg in al, dx and al, 0xD0 cmp al, 0xD0 ; ok to read? jnz .l1 pop eax pop ecx mov dx, 0x3F5 ; get the byte in al, dx pop edx clc ret .error: pop eax pop ecx pop edx stc ret ;------------------------------------------------------; ; sense interrupt status command ; ; ; ;------------------------------------------------------; sensei: push eax mov al, 0x08 ; fdc command call fdc_sendbyte call fdc_getbyte mov ah, al ; save ST0 in ah call fdc_getbyte ; read PCN clc test ah, 0x80 ; test for error: jz .end ; "invalid command" stc .end: pop eax ret ;------------------------------------------------------; ; reset controller ; ; ; ;------------------------------------------------------; fdd_reset: push eax push ecx push edx mov byte [fdd_motor_on], 0 mov dx, 0x3f2 mov al, 8 ; off with all motors, out dx, al ; dma,irq etc.. mov ecx, 5 call delay ; in timer.inc mov dx, 0x3f7 mov al, 0 out dx, al ; work at 500 kbit/s mov dx, 0x3f2 mov al, 0x0c out dx, al ; reenable interrupts mov [fdd_int_done], 0 call wait_int ; wait for floppy int. jc .error ; timeout? mov cx, 0x04 .status: ; 4 dummy-reads. call sensei loop .status mov al, 0x03 ; specify command call fdc_sendbyte mov al, 0xDF ; SRT, HUT call fdc_sendbyte mov al, 0x02 ; HLT, ND call fdc_sendbyte mov al, 1 call fdd_recal_seek jc .error call fdd_off clc jmp .end .error: call fdd_off stc .end: pop edx pop ecx pop eax ret ;------------------------------------------------------; ; fdd_recal_seek - fdd recalibrate/seek ; ;------------------------------------------------------; ; ; ; in: al = 0 on seek, 1 on recalibrate ; ; bl = (at seek) track ; ; bh = (at seek) ((head*4)|drive) ; ; ; ;------------------------------------------------------; fdd_recal_seek: push eax call fdd_on ; turn motor on cmp al, 0 jne .recalibrate clc cmp bl, [result_C] ; are we there yet? :D je .ok mov al, 0x0F ; seek command call fdc_sendbyte mov al, bh ; ((head*4)|drive) call fdc_sendbyte mov al, bl ; track call fdc_sendbyte mov [result_C], bl ; now on..? jmp .get_int .recalibrate: mov al, 0x07 ; recalibrate command call fdc_sendbyte mov al, 0 ; drive number call fdc_sendbyte mov [result_C], 0 ; now on track 0 .get_int: mov [fdd_int_done], 0 call wait_int jc .error call sensei ; sense interrupt status jc .error .ok: clc jmp .end .error: stc .end: pop eax ret ;------------------------------------------------------; ; fdd_read_write - fdd read/write ; ;------------------------------------------------------; ; input: bl = 0 read, 1 write ; ; ch = track/cylinder ; ; cl = sector ; ; dh = head ; ; edi = address to store or read the data ; ; output: al = status ; ; cf = 0 if ok, 1 if error ; ;------------------------------------------------------; fdd_read_write: pushad and dh, 1 ; head 0 or 1? mov [fdd_head], dh ; store it. shl dh, 2 or dh, 0 ; drive 0, fd0 mov [fdd_drivehead], dh ; dh = ((head*4)|drive) mov [fdd_errorcode], 0x04 ; basic error code cmp ch, 0x51 ; check for allowed jae .error ; track number. mov [fdd_track], ch cmp cl, 0x13 ; check for allowed jae .error ; sector number. mov [fdd_sector], cl cmp [fdd_error], 1 jne .no_previous_error mov al, 1 call fdd_recal_seek .no_previous_error: call fdd_on mov dx, 0x3F7 mov al, 0 ; 500Kb/sec mode out dx, al mov [fdd_errorcode], 0x80 ; error code xor ecx, ecx mov cx, 3 ; try seek 3 times .l2: mov al, 0 push ebx mov bl, [fdd_track] mov bh, [fdd_drivehead] ; ((head*4)|drive) call fdd_recal_seek pop ebx jnc .l3 ; ok, continue. loop .l2 jmp .error ; timeout. .l3: push ebx cmp bl, 0 je .read_fdd .write_fdd: push edi mov esi, edi mov edi, 0x80000 ; copy the stuff we will mov ecx, 128 ; write to the DMA buffer rep movsd ; 128*4=512 pop edi mov bl, 2 ; channel 2 mov esi, 512 ; bytes to write mov ecx, 0x80000 ; page & offset mov bh, 1 ; write floppy, read DMA call dma_transfer mov al, 0xC5 ; write sector command call fdc_sendbyte jmp .cont .read_fdd: mov bl, 2 ; channel 2 mov esi, 512 ; bytes to read mov ecx, 0x80000 ; page & offset mov bh, 0 ; read floppy, write DMA call dma_transfer mov al, 0xE6 ; read sector command call fdc_sendbyte .cont: pop ebx mov al, [fdd_drivehead] ; ((head*4)|drive) call fdc_sendbyte mov al, [fdd_track] ; track/cylinder call fdc_sendbyte mov al, [fdd_head] ; head/side 0 or 1 call fdc_sendbyte mov al, [fdd_sector] ; sector number call fdc_sendbyte mov al, 0x02 ; sector size, 512 bytes call fdc_sendbyte mov al, 0x12 ; sectors to a track call fdc_sendbyte mov al, 0x1B ; gap length call fdc_sendbyte mov al, 0xFF ; data length call fdc_sendbyte mov [fdd_int_done], 0 call wait_int jc .error call fdc_getbyte mov [result_ST0], al ; ST0 call fdc_getbyte mov [result_ST1], al ; ST1 call fdc_getbyte mov [result_ST2], al ; ST2 call fdc_getbyte mov [result_C], al ; cylinder call fdc_getbyte mov [result_H], al ; head call fdc_getbyte mov [result_R], al ; sector number. call fdc_getbyte mov [result_N], al ; sector size test [result_ST0], 0xc0 ; test if sr0 is 0xC0 jnz .error cmp bl, 1 ; did we write the disk? je .ok mov ecx, 512 ; sector size in bytes mov esi, 0x80000 ; copy to dest. in edi rep movsb .ok: mov [fdd_errorcode], 0 ; no error.. :D mov [fdd_error], 0 ; no recal. next time clc jmp .end .error: mov [fdd_error], 1 ; recalibrate next time stc .end: call fdd_off ; floppy motor off popad mov al, [fdd_errorcode] ; error status ret
; A157912: 64*n^2 + 16. ; Submitted by Christian Krause ; 80,272,592,1040,1616,2320,3152,4112,5200,6416,7760,9232,10832,12560,14416,16400,18512,20752,23120,25616,28240,30992,33872,36880,40016,43280,46672,50192,53840,57616,61520,65552,69712,74000,78416,82960,87632,92432,97360,102416,107600,112912,118352,123920,129616,135440,141392,147472,153680,160016,166480,173072,179792,186640,193616,200720,207952,215312,222800,230416,238160,246032,254032,262160,270416,278800,287312,295952,304720,313616,322640,331792,341072,350480,360016,369680,379472,389392,399440 add $0,1 pow $0,2 mul $0,8 add $0,2 mul $0,8
#include "DXUT.h" #include "CTimeManager.h" CTimeManager::CTimeManager() { //mutable } CTimeManager::~CTimeManager() { for (auto& iter : m_Timers) { SAFE_DELETE(iter.second); } m_Timers.clear(); } CTimer * CTimeManager::AddTimer(CRString _Key, CTimer * _pTimer) { auto find = m_Timers.find(_Key); if (find == m_Timers.end()) { m_Timers[_Key] = _pTimer; return _pTimer; } SAFE_DELETE(_pTimer); return m_Timers[_Key]; } CTimer * CTimeManager::FindTimer(CRString _Key) { auto find = m_Timers.find(_Key); if (find == m_Timers.end()) return nullptr; return find->second; } void CTimeManager::RemoveTimer(CRString _Key) { auto find = m_Timers.find(_Key); if (find != m_Timers.end()) { SAFE_DELETE(find->second); m_Timers.erase(find); } } void CTimeManager::Update() { //DeltaTime = DXUTGetElapsedTime(); for (auto iter = m_Timers.begin(); iter != m_Timers.end(); ) { (*iter).second->Update(); if (TRUE == (*iter).second->isDestroyed()) { SAFE_DELETE((*iter).second); iter = m_Timers.erase(iter); } else iter++; } }
; A260217: Number of base-3 n-digit pandigital numbers. ; 0,0,4,24,100,360,1204,3864,12100,37320,114004,346104,1046500,3155880,9500404,28566744,85831300,257756040,773792404,2322425784,6969374500,20912317800,62745342004,188252803224,564791964100,1694443001160,5083463221204,15250658099064 mov $3,1 lpb $0 sub $0,1 add $1,$3 mul $1,2 sub $1,2 mov $2,$3 mul $3,2 add $3,$2 lpe
lorom !FEATURE_SD2SNES ?= 1 !FEATURE_DEV ?= 0 !FEATURE_PAL ?= 1 !ORIGINAL_MESSAGE_TEXT ?= 0 !PRESERVE_WRAM_DURING_SPACETIME ?= 1 !RAW_TILE_GRAPHICS ?= 1 !VERSION_MAJOR = 2 !VERSION_MINOR = 4 !VERSION_BUILD = 2 !VERSION_REV_1 = 0 !VERSION_REV_2 = 0 table ../resources/normal.tbl incsrc macros.asm incsrc defines.asm print "" if !FEATURE_SD2SNES print "SD2SNES ENABLED" incsrc save.asm else print "SD2SNES DISABLED" endif incsrc gamemode.asm incsrc minimap.asm incsrc menu.asm incsrc infohud.asm incsrc rng.asm incsrc custompresets.asm incsrc presets.asm incsrc misc.asm incsrc layout.asm incsrc cutscenes.asm incsrc init.asm incsrc fanfare.asm incsrc spriteprio.asm incsrc spritefeat.asm if !RAW_TILE_GRAPHICS incsrc tilegraphics.asm endif ; Make sure the ROM expands to 4MB org $FFFFFF : db $FF
SECTION code_fp_math32 PUBLIC ___fs2schar_callee EXTERN cm32_sdcc___fs2schar_callee defc ___fs2schar_callee = cm32_sdcc___fs2schar_callee
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/media_session/public/cpp/test/audio_focus_test_util.h" #include "base/bind.h" namespace media_session { namespace test { namespace { void ReceivedSessionInfo(media_session::mojom::MediaSessionInfoPtr* info_out, base::RepeatingClosure callback, media_session::mojom::MediaSessionInfoPtr result) { *info_out = std::move(result); std::move(callback).Run(); } } // namespace TestAudioFocusObserver::TestAudioFocusObserver() {} TestAudioFocusObserver::~TestAudioFocusObserver() = default; void TestAudioFocusObserver::OnFocusGained( media_session::mojom::AudioFocusRequestStatePtr session) { focus_gained_session_ = std::move(session); notifications_.push_back(NotificationType::kFocusGained); if (wait_for_gained_) run_loop_.Quit(); } void TestAudioFocusObserver::OnFocusLost( media_session::mojom::AudioFocusRequestStatePtr session) { focus_lost_session_ = std::move(session); notifications_.push_back(NotificationType::kFocusLost); if (wait_for_lost_) run_loop_.Quit(); } void TestAudioFocusObserver::WaitForGainedEvent() { if (!focus_gained_session_.is_null()) return; wait_for_gained_ = true; run_loop_.Run(); } void TestAudioFocusObserver::WaitForLostEvent() { if (!focus_lost_session_.is_null()) return; wait_for_lost_ = true; run_loop_.Run(); } mojo::PendingRemote<media_session::mojom::AudioFocusObserver> TestAudioFocusObserver::BindNewPipeAndPassRemote() { return receiver_.BindNewPipeAndPassRemote(); } media_session::mojom::MediaSessionInfoPtr GetMediaSessionInfoSync( media_session::mojom::MediaSession* session) { media_session::mojom::MediaSessionInfoPtr session_info; base::RunLoop run_loop; session->GetMediaSessionInfo(base::BindOnce( &ReceivedSessionInfo, &session_info, run_loop.QuitClosure())); return session_info; } } // namespace test } // namespace media_session
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Geoworks 1995 -- All Rights Reserved PROJECT: GEOS MODULE: Appl/GeoWrite FILE: uiPrint.asm AUTHOR: Don Reeves, May 2, 1995 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- Don 5/ 2/95 Initial revision DESCRIPTION: Implements the DWPPrintControlClass $Id: uiPrint.asm,v 1.1 97/04/04 15:55:54 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GeoWriteClassStructures segment resource WritePrintCtrlClass GeoWriteClassStructures ends DocPrint segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% WritePrintCtrlInitiateOutputUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Initiate the print or fax dialog box CALLED BY: GLOBAL (MSG_PRINT_CONTROL_INITIATE_OUTPUT_UI) PASS: ES = Segment of WritePrintCtrlClass *DS:SI = WritePrintCtrlClass object DS:DI = WritePrintCtrlClassInstance CL = PrinterDriverType RETURN: see documentation for MSG_PRINT_CONTROL_INITIATE_OUTPUT_UI DESTROYED: see documentation for MSG_PRINT_CONTROL_INITIATE_OUTPUT_UI PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Don 5/ 2/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ WritePrintCtrlInitiateOutputUI method dynamic WritePrintCtrlClass, MSG_PRINT_CONTROL_INITIATE_OUTPUT_UI ; ; If we are faxing, then don't display any merge options. ; Otherwise, display them. ; push cx, dx, bp, si mov ax, MSG_GEN_SET_NOT_USABLE cmp cl, PDT_FACSIMILE je sendMessage mov ax, MSG_GEN_SET_USABLE sendMessage: GetResourceHandleNS PrintUI, bx mov si, offset PrintUI:InnerPrintGroup mov dl, VUM_DELAYED_VIA_UI_QUEUE mov di, mask MF_FIXUP_DS call ObjMessage ; ; If we are faxing, always turn the merge option off ; cmp cl, PDT_FACSIMILE jne callSuper mov ax, MSG_GEN_ITEM_GROUP_SET_SINGLE_SELECTION mov cx, MT_NONE ; turn off merging clr dx ; determinate mov si, offset PrintUI:MergeList mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage ; ; Call our superclass to do the real work ; callSuper: pop cx, dx, bp, si mov ax, MSG_PRINT_CONTROL_INITIATE_OUTPUT_UI mov di, offset WritePrintCtrlClass GOTO ObjCallSuperNoLock WritePrintCtrlInitiateOutputUI endm DocPrint ends
; A008747: Expansion of (1+x^4)/((1-x)*(1-x^2)*(1-x^3)). ; 1,1,2,3,5,6,9,11,14,17,21,24,29,33,38,43,49,54,61,67,74,81,89,96,105,113,122,131,141,150,161,171,182,193,205,216,229,241,254,267,281,294,309,323,338,353,369,384,401,417,434,451,469,486,505,523,542,561,581,600,621,641,662,683,705,726,749,771,794,817,841,864,889,913,938,963,989,1014,1041,1067,1094,1121,1149,1176,1205,1233,1262,1291,1321,1350,1381,1411,1442,1473,1505,1536,1569,1601,1634,1667 mov $1,$0 add $0,2 mul $0,$1 div $0,6 add $0,1
; A016996: a(n) = (7*n + 1)^4. ; 1,4096,50625,234256,707281,1679616,3418801,6250000,10556001,16777216,25411681,37015056,52200625,71639296,96059601,126247696,163047361,207360000,260144641,322417936,395254161,479785216,577200625,688747536,815730721,959512576,1121513121,1303210000,1506138481,1731891456,1982119441,2258530576,2562890625,2897022976,3262808641,3662186256,4097152081,4569760000,5082121521,5636405776,6234839521,6879707136,7573350625,8318169616,9116621361,9971220736,10884540241,11859210000,12897917761,14003408896 mul $0,7 add $0,1 pow $0,4
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/animation/scrollbar_animation_controller.h" #include <algorithm> #include "base/time/time.h" namespace cc { ScrollbarAnimationController::ScrollbarAnimationController( ScrollbarAnimationControllerClient* client, base::TimeDelta delay_before_starting, base::TimeDelta resize_delay_before_starting, base::TimeDelta duration) : client_(client), delay_before_starting_(delay_before_starting), resize_delay_before_starting_(resize_delay_before_starting), duration_(duration), is_animating_(false), currently_scrolling_(false), scroll_gesture_has_scrolled_(false), weak_factory_(this) { } ScrollbarAnimationController::~ScrollbarAnimationController() { } void ScrollbarAnimationController::Animate(base::TimeTicks now) { if (!is_animating_) return; if (last_awaken_time_.is_null()) last_awaken_time_ = now; float progress = AnimationProgressAtTime(now); RunAnimationFrame(progress); if (is_animating_) { delayed_scrollbar_fade_.Cancel(); client_->SetNeedsScrollbarAnimationFrame(); } } float ScrollbarAnimationController::AnimationProgressAtTime( base::TimeTicks now) { base::TimeDelta delta = now - last_awaken_time_; float progress = delta.InSecondsF() / duration_.InSecondsF(); return std::max(std::min(progress, 1.f), 0.f); } void ScrollbarAnimationController::DidScrollBegin() { currently_scrolling_ = true; } void ScrollbarAnimationController::DidScrollUpdate(bool on_resize) { StopAnimation(); delayed_scrollbar_fade_.Cancel(); // As an optimization, we avoid spamming fade delay tasks during active fast // scrolls. But if we're not within one, we need to post every scroll update. if (!currently_scrolling_) PostDelayedFade(on_resize); else scroll_gesture_has_scrolled_ = true; } void ScrollbarAnimationController::DidScrollEnd() { if (scroll_gesture_has_scrolled_) { PostDelayedFade(false); scroll_gesture_has_scrolled_ = false; } currently_scrolling_ = false; } void ScrollbarAnimationController::PostDelayedFade(bool on_resize) { base::TimeDelta delay = on_resize ? resize_delay_before_starting_ : delay_before_starting_; delayed_scrollbar_fade_.Reset( base::Bind(&ScrollbarAnimationController::StartAnimation, weak_factory_.GetWeakPtr())); client_->PostDelayedScrollbarFade(delayed_scrollbar_fade_.callback(), delay); } void ScrollbarAnimationController::StartAnimation() { delayed_scrollbar_fade_.Cancel(); is_animating_ = true; last_awaken_time_ = base::TimeTicks(); client_->SetNeedsScrollbarAnimationFrame(); } void ScrollbarAnimationController::StopAnimation() { is_animating_ = false; } } // namespace cc
.global s_prepare_buffers s_prepare_buffers: push %r14 push %r8 push %r9 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_A_ht+0x2cd4, %rsi lea addresses_WC_ht+0x154d8, %rdi sub %r8, %r8 mov $98, %rcx rep movsw sub %r9, %r9 lea addresses_WT_ht+0xcd30, %rsi lea addresses_D_ht+0x1e398, %rdi clflush (%rsi) clflush (%rdi) nop nop nop nop sub $32400, %rbx mov $55, %rcx rep movsq nop cmp $37921, %r8 lea addresses_WC_ht+0x190d8, %rcx sub $55670, %r14 mov (%rcx), %r8w nop nop sub %rdi, %rdi lea addresses_normal_ht+0xb4d8, %rsi lea addresses_WT_ht+0x11f78, %rdi nop nop nop nop xor %rbx, %rbx mov $63, %rcx rep movsb nop nop xor %rbx, %rbx lea addresses_A_ht+0x84d8, %rsi lea addresses_A_ht+0x54c8, %rdi nop nop sub $13350, %rbp mov $53, %rcx rep movsq xor $29959, %rbx lea addresses_WC_ht+0x15618, %rdi cmp %r9, %r9 mov (%rdi), %bx nop nop nop nop nop sub %rcx, %rcx lea addresses_WC_ht+0x64d8, %r14 nop nop nop nop add %rdi, %rdi and $0xffffffffffffffc0, %r14 movntdqa (%r14), %xmm6 vpextrq $1, %xmm6, %rsi nop nop nop add $20930, %r9 lea addresses_A_ht+0x2ad8, %rsi lea addresses_WC_ht+0xdc2a, %rdi nop nop cmp $19108, %r14 mov $13, %rcx rep movsw nop inc %r9 lea addresses_normal_ht+0x8c78, %rsi dec %r14 movups (%rsi), %xmm7 vpextrq $0, %xmm7, %rdi nop nop nop nop and $27285, %rbp lea addresses_A_ht+0x11e10, %r14 xor %r9, %r9 vmovups (%r14), %ymm3 vextracti128 $0, %ymm3, %xmm3 vpextrq $0, %xmm3, %rbx and $14490, %rbp lea addresses_UC_ht+0x1a898, %r14 nop nop nop xor $27973, %rbp movb (%r14), %bl nop nop nop nop nop sub %r14, %r14 pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r9 pop %r8 pop %r14 ret .global s_faulty_load s_faulty_load: push %r11 push %r14 push %r9 push %rax push %rbp push %rdx push %rsi // Store lea addresses_PSE+0x11cd8, %rbp sub %rax, %rax mov $0x5152535455565758, %r11 movq %r11, %xmm6 vmovups %ymm6, (%rbp) nop nop nop nop nop dec %r11 // Store lea addresses_WT+0x15a08, %rax clflush (%rax) nop xor $11808, %rsi mov $0x5152535455565758, %r11 movq %r11, (%rax) // Exception!!! nop nop mov (0), %rax nop sub %rsi, %rsi // Store lea addresses_WT+0xfed8, %rax nop add $1965, %r9 movw $0x5152, (%rax) nop nop nop nop cmp %rdx, %rdx // Store mov $0x89cbc0000000598, %rdx nop nop and %r9, %r9 movb $0x51, (%rdx) nop nop and $49575, %r9 // Store lea addresses_RW+0xf4d8, %rax nop nop nop nop nop dec %rsi mov $0x5152535455565758, %r9 movq %r9, %xmm7 movups %xmm7, (%rax) cmp $21771, %r11 // Faulty Load lea addresses_PSE+0x11cd8, %r11 nop inc %rax movups (%r11), %xmm4 vpextrq $1, %xmm4, %rbp lea oracles, %r11 and $0xff, %rbp shlq $12, %rbp mov (%r11,%rbp,1), %rbp pop %rsi pop %rdx pop %rbp pop %rax pop %r9 pop %r14 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 3, 'size': 8, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 9, 'size': 2, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': True, 'congruent': 6, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 10, 'size': 16, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 8, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 6, 'size': 2, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': True, 'congruent': 6, 'size': 2, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 11, 'size': 16, 'same': False, 'NT': True}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 5, 'size': 16, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 3, 'size': 32, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 3, 'size': 1, '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 */
loc ;****************************************************************** ;* MODO_CONFIG - standby mode. Load the respective message on the ;* screen for this mode and turn off the two upper 7 segment ;* display segments. The other two display the parameter to be ;* configured (LengthOK). The parameter is configured with the ;* button array and won't change until the value is validated. ;* ;* Calling convention: ;* jsr MODO_CONFIG ;* ;* Calls: Cargar_LCD, TAREA_TECLADO, BCD_BIN ;* Changes: X, Y, BIN1, BIN2, TICK_EN, TICK_DIS, Banderas ;****************************************************************** MODO_CONFIG: brset POSITION,$02,skip_load` movb #$02,POSITION movb #$02,LEDS ldx #MSGMC_U ldy #MSGMC_D jsr Cargar_LCD movb NumVueltas,BIN1 movb #$BB,BIN2 skip_load`: bclr Banderas,$04 ; ARRAY_OK = 0 movw #0,TICK_EN movw #0,TICK_DIS jsr TAREA_TECLADO brclr Banderas,$04,return` ; if(!ARRAY_OK){ return } ; swi jsr BCD_BIN ldaa ValorVueltas cmpa #3 blo return` cmpa #23 bhi return` movb ValorVueltas,NumVueltas movb NumVueltas,BIN1 bra return` return`: clr ValorVueltas ; reset keypad data structures rts
; =============================================================== ; Dec 2013 ; =============================================================== ; ; void *_falloc(void *p, size_t size) ; ; Attempt to allocate size bytes from the thread's heap at ; fixed address p. Returns p or 0 with carry set on failure. ; ; Returns 0 if size = 0 without indicating error. ; ; =============================================================== INCLUDE "clib_cfg.asm" SECTION code_alloc_malloc ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $01 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC asm__falloc EXTERN __malloc_heap EXTERN asm_heap_alloc_fixed asm__falloc: ; Attempt to allocate memory from the thread's default heap ; at a fixed address ; ; enter : bc = void *p ; hl = size ; ; exit : success ; ; hl = void *p (zero size allocation will occur) ; carry reset ; ; fail on lock acquisition ; ; hl = 0 ; carry set, errono = ENOLCK ; ; fail on insufficient memory ; ; hl = 0 ; carry set, errno = ENOMEM ; ; uses : af, bc, de, hl ld de,(__malloc_heap) jp asm_heap_alloc_fixed ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC asm__falloc EXTERN asm__falloc_unlocked defc asm__falloc = asm__falloc_unlocked ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: TMPro namespace TMPro { // Forward declaring type: KerningPair class KerningPair; // Forward declaring type: GlyphValueRecord_Legacy struct GlyphValueRecord_Legacy; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Completed forward declares // Type namespace: TMPro namespace TMPro { // Forward declaring type: KerningTable class KerningTable; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::TMPro::KerningTable); DEFINE_IL2CPP_ARG_TYPE(::TMPro::KerningTable*, "TMPro", "KerningTable"); // Type namespace: TMPro namespace TMPro { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: TMPro.KerningTable // [TokenAttribute] Offset: FFFFFFFF class KerningTable : public ::Il2CppObject { public: // Nested type: ::TMPro::KerningTable::$$c__DisplayClass3_0 class $$c__DisplayClass3_0; // Nested type: ::TMPro::KerningTable::$$c__DisplayClass4_0 class $$c__DisplayClass4_0; // Nested type: ::TMPro::KerningTable::$$c__DisplayClass5_0 class $$c__DisplayClass5_0; // Nested type: ::TMPro::KerningTable::$$c class $$c; #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // public System.Collections.Generic.List`1<TMPro.KerningPair> kerningPairs // Size: 0x8 // Offset: 0x10 ::System::Collections::Generic::List_1<::TMPro::KerningPair*>* kerningPairs; // Field size check static_assert(sizeof(::System::Collections::Generic::List_1<::TMPro::KerningPair*>*) == 0x8); public: // Creating conversion operator: operator ::System::Collections::Generic::List_1<::TMPro::KerningPair*>* constexpr operator ::System::Collections::Generic::List_1<::TMPro::KerningPair*>*() const noexcept { return kerningPairs; } // Get instance field reference: public System.Collections.Generic.List`1<TMPro.KerningPair> kerningPairs ::System::Collections::Generic::List_1<::TMPro::KerningPair*>*& dyn_kerningPairs(); // public System.Void AddKerningPair() // Offset: 0xA481A0 void AddKerningPair(); // public System.Int32 AddKerningPair(System.UInt32 first, System.UInt32 second, System.Single offset) // Offset: 0xA482E8 int AddKerningPair(uint first, uint second, float offset); // public System.Int32 AddGlyphPairAdjustmentRecord(System.UInt32 first, TMPro.GlyphValueRecord_Legacy firstAdjustments, System.UInt32 second, TMPro.GlyphValueRecord_Legacy secondAdjustments) // Offset: 0xA48464 int AddGlyphPairAdjustmentRecord(uint first, ::TMPro::GlyphValueRecord_Legacy firstAdjustments, uint second, ::TMPro::GlyphValueRecord_Legacy secondAdjustments); // public System.Void RemoveKerningPair(System.Int32 left, System.Int32 right) // Offset: 0xA48620 void RemoveKerningPair(int left, int right); // public System.Void RemoveKerningPair(System.Int32 index) // Offset: 0xA48754 void RemoveKerningPair(int index); // public System.Void SortKerningPairs() // Offset: 0xA487B8 void SortKerningPairs(); // public System.Void .ctor() // Offset: 0xA48124 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static KerningTable* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::TMPro::KerningTable::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<KerningTable*, creationType>())); } }; // TMPro.KerningTable #pragma pack(pop) static check_size<sizeof(KerningTable), 16 + sizeof(::System::Collections::Generic::List_1<::TMPro::KerningPair*>*)> __TMPro_KerningTableSizeCheck; static_assert(sizeof(KerningTable) == 0x18); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: TMPro::KerningTable::AddKerningPair // Il2CppName: AddKerningPair template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (TMPro::KerningTable::*)()>(&TMPro::KerningTable::AddKerningPair)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(TMPro::KerningTable*), "AddKerningPair", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: TMPro::KerningTable::AddKerningPair // Il2CppName: AddKerningPair template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (TMPro::KerningTable::*)(uint, uint, float)>(&TMPro::KerningTable::AddKerningPair)> { static const MethodInfo* get() { static auto* first = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg; static auto* second = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg; static auto* offset = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(TMPro::KerningTable*), "AddKerningPair", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{first, second, offset}); } }; // Writing MetadataGetter for method: TMPro::KerningTable::AddGlyphPairAdjustmentRecord // Il2CppName: AddGlyphPairAdjustmentRecord template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (TMPro::KerningTable::*)(uint, ::TMPro::GlyphValueRecord_Legacy, uint, ::TMPro::GlyphValueRecord_Legacy)>(&TMPro::KerningTable::AddGlyphPairAdjustmentRecord)> { static const MethodInfo* get() { static auto* first = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg; static auto* firstAdjustments = &::il2cpp_utils::GetClassFromName("TMPro", "GlyphValueRecord_Legacy")->byval_arg; static auto* second = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg; static auto* secondAdjustments = &::il2cpp_utils::GetClassFromName("TMPro", "GlyphValueRecord_Legacy")->byval_arg; return ::il2cpp_utils::FindMethod(classof(TMPro::KerningTable*), "AddGlyphPairAdjustmentRecord", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{first, firstAdjustments, second, secondAdjustments}); } }; // Writing MetadataGetter for method: TMPro::KerningTable::RemoveKerningPair // Il2CppName: RemoveKerningPair template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (TMPro::KerningTable::*)(int, int)>(&TMPro::KerningTable::RemoveKerningPair)> { static const MethodInfo* get() { static auto* left = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* right = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(TMPro::KerningTable*), "RemoveKerningPair", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{left, right}); } }; // Writing MetadataGetter for method: TMPro::KerningTable::RemoveKerningPair // Il2CppName: RemoveKerningPair template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (TMPro::KerningTable::*)(int)>(&TMPro::KerningTable::RemoveKerningPair)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(TMPro::KerningTable*), "RemoveKerningPair", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index}); } }; // Writing MetadataGetter for method: TMPro::KerningTable::SortKerningPairs // Il2CppName: SortKerningPairs template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (TMPro::KerningTable::*)()>(&TMPro::KerningTable::SortKerningPairs)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(TMPro::KerningTable*), "SortKerningPairs", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: TMPro::KerningTable::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
; Pics are defined in gfx/pics.asm TrainerPicPointers:: ; entries correspond to trainer classes (see constants/trainer_constants.asm) dba FalknerPic dba WhitneyPic dba BugsyPic dba MortyPic dba PrycePic dba JasminePic dba ChuckPic dba ClairPic dba Rival1Pic dba PokemonProfPic dba WillPic dba CalPic dba BrunoPic dba KarenPic dba KogaPic dba ChampionPic dba BrockPic dba MistyPic dba LtSurgePic dba ScientistPic dba ErikaPic dba YoungsterPic dba SchoolboyPic dba BirdKeeperPic dba LassPic dba JaninePic dba CooltrainermPic dba CooltrainerfPic dba BeautyPic dba PokemaniacPic dba GruntmPic dba GentlemanPic dba SkierPic dba TeacherPic dba SabrinaPic dba BugCatcherPic dba FisherPic dba SwimmermPic dba SwimmerfPic dba SailorPic dba SuperNerdPic dba Rival2Pic dba GuitaristPic dba HikerPic dba BikerPic dba BlainePic dba BurglarPic dba FirebreatherPic dba JugglerPic dba BlackbeltTPic dba ExecutivemPic dba PsychicTPic dba PicnickerPic dba CamperPic dba ExecutivefPic dba SagePic dba MediumPic dba BoarderPic dba PokefanmPic dba KimonoGirlPic dba TwinsPic dba PokefanfPic dba RedPic dba BluePic dba OfficerPic dba GruntfPic dba RocketAgentsPic
; A021431: Decimal expansion of 1/427. ; Submitted by Jamie Morken(m2) ; 0,0,2,3,4,1,9,2,0,3,7,4,7,0,7,2,5,9,9,5,3,1,6,1,5,9,2,5,0,5,8,5,4,8,0,0,9,3,6,7,6,8,1,4,9,8,8,2,9,0,3,9,8,1,2,6,4,6,3,7,0,0,2,3,4,1,9,2,0,3,7,4,7,0,7,2,5,9,9,5,3,1,6,1,5,9,2,5,0,5,8,5,4,8,0,0,9,3,6 seq $0,83811 ; Numbers n such that 2n+1 is the digit reversal of n+1. div $0,1708 mod $0,10
extern puts extern printf extern strlen %define BAD_ARG_EXIT_CODE -1 section .data filename: db "./input0.dat", 0 inputlen: dd 2263 fmtstr: db "Key: %d",0xa, 0 usage: db "Usage: %s <task-no> (task-no can be 1,2,3,4,5,6)", 10, 0 error_no_file: db "Error: No input file %s", 10, 0 error_cannot_read: db "Error: Cannot read input file %s", 10, 0 section .text global main xor_strings: ; TODO TASK 1 push ebp mov ebp, esp mov esi, [ebp + 8] ;folosesc esi pentru mesaj mov edi, [ebp + 12] ;folosesc edi pentru cheie xor_byte_by_byte: mov al, byte [esi] ;iau un byte din esi si il pun in al cmp al, 0x00 ;verific daca am ajuns la sfarsit je end_xor_strings ;daca da, ies din functie mov bl, byte [edi] ;iau un byte din edi si il pun in bl cmp bl, 0x00 ;verific daca am ajuns la sfarsit je end_xor_strings ;daca da, ies din functie xor al, bl ;fac xor byte cu byte intre mesaj si cheie mov byte[esi], al ;suprascriu inc esi ;avansez in mesaj inc edi ;avansez in cheie jmp xor_byte_by_byte ;repet procesul end_xor_strings: leave ret ;===============================================================; rolling_xor: ; TODO TASK 2 push ebp mov ebp, esp mov esi, [ebp + 8] ;folosesc esi pentru mesaj mov ah, byte [esi] ;salvez in ah primul octet din mesaj, adica m1 rolling_xor_byte_by_byte: inc esi ;avansez in mesaj, ma mut pe octetul m2 cmp byte[esi], 0x00 ;verific daca am ajuns la sfarsitul sirului je end_rolling_xor ;daca da, ies din functie mov bh, byte[esi] ;salvez pe c1 pentru urmatorul pas xor byte[esi], ah ;fac xor intre octetul curent si cel anterior mov ah, bh ;actualizez rezultatul jmp rolling_xor_byte_by_byte ;repet procesul end_rolling_xor: leave ret ;===============================================================; convert: push ebp mov ebp, esp mov esi, [ebp + 8] ;folosesc esi pentru mesaj xor edx, edx ;contor pentru parcurgere din 2 in 2 xor edi, edi ;contor pentru parcurgere din 1 in 1 move: mov al, byte [esi + edx] ;folosesc al pentru cate doi octeti cmp al, 0x00 ;verific daca am ajuns la finalul sirului je end_xor_hex_strings ;daca da, am terminat mov ah, byte [esi + edx + 1] ;folosesc ah pentru un octet cmp al, '9' ;pentru a verifica daca e cifra jle digit ;daca da,sar la label-ul digit jg letter ;daca nu,inseamna ca e litera cmp_for_ah: cmp ah, '9' ;pentru a verifica daca e cifra jle digit2 ;daca da,sar la label-ul digit2 jge letter2 ;daca nu,inseamna ca e litera repeat_process: shl al, 4 ;inmultesc al cu 16 pentru urmatorii doi octeti add al, ah ;imi trebuie urmatorul mesaj mov byte [esi + edi], al ;suprascriu inc edi ;cresc edi add edx, 2 ;cresc edx (merge din 2 in 2) jmp move digit: sub al, '0' ;converteste din caracter in cifra jmp cmp_for_ah letter: sub al, 'a' add al, 10 jmp cmp_for_ah digit2: sub ah, '0' ;converteste din caracter in cifra jmp repeat_process letter2: sub ah, 'a' add ah, 10 jmp repeat_process xor_hex_strings: ; TODO TASK 3 push ebp mov ebp, esp mov esi, [ebp + 8] ;folosesc esi pentru mesaj mov edi, [ebp + 12] ;folosesc edi pentru cheie xor_hex_byte_by_byte: mov al, byte [esi] ;iau un byte din esi si il pun in al cmp al, 0x00 ;verific daca am ajuns la sfarsit je end_xor_hex_strings ;daca da, ies din functie mov bl, byte [edi] ;iau un byte din edi si il pun in bl cmp bl, 0x00 ;verific daca am ajuns la final je end_xor_hex_strings ;daca da, ies din functie xor al, bl ;fac xor byte cu byte intre mesaj si cheie mov byte[esi], al ;suprascriu inc esi ;avansez in mesaj inc edi ;avansez in cheie jmp xor_hex_byte_by_byte ;repeta procesul end_xor_hex_strings: leave ret ;===============================================================; base32_to_value: ; daca e litera scade din aceasta valoarea ascii a lui 'A' push ebp ; daca e numar, scade '2' si aduna 26 mov ebp, esp mov eax, [ebp + 8] sub eax, '=' jz base32_to_value_exit ; daca este '=' se pune 0 in eax mov eax, [ebp + 8] cmp eax, 'A' jl base32_to_value_number sub eax, 'A' jmp base32_to_value_exit base32_to_value_number: sub eax, '2' add eax, 26 base32_to_value_exit: ; rezultatul este pus in eax pop ebp ret base32decode: ; TODO TASK 4 push ebp mov ebp, esp mov edi, [ebp + 8] ; parcurge stringul codat mov esi, [ebp + 8] ; scrie stringul decodat cate un caracter base32decode_iteration: xor edx, edx xor eax, eax mov al, byte [edi] ; se ia primul caracter si se decodifica push eax call base32_to_value add esp, 4 mov dl, al ; in dl se construieste primul byte din numar shl dl, 3 ; mai raman 3 biti de "umplut" mov al, byte [edi + 1] push eax call base32_to_value add esp, 4 mov ah, al shr al, 2 ; se pun doar 3/5 biti in dl pentru completare or dl, al ; acum primul byte este in dl mov [esi], dl ; se scrie in esi pentru a se putea refolosi dl inc esi xor edx, edx shl ah, 3 ; se sterg bitii care au fost folositi anterior shr ah, 3 mov dl, ah ; se pun cei 2 ramasi in dl urmand sa se construiasca shl edx, 30 ; in edx restul de 4 bytes, adica 6 caractere din sir xor eax, eax mov al, byte [edi + 2] push eax call base32_to_value add esp, 4 shl eax, 25 ; se shifteaza eax cu 30-5 biti or edx, eax ; si se pune rezultatul in edx xor eax, eax mov al, byte [edi + 3] push eax call base32_to_value add esp, 4 shl eax, 20 ; se shifteaza eax cu 25-5 biti or edx, eax xor eax, eax mov al, byte [edi + 4] push eax call base32_to_value add esp, 4 shl eax, 15 ; se shifteaza eax cu 20-5 biti or edx, eax xor eax, eax mov al, byte [edi + 5] push eax call base32_to_value add esp, 4 shl eax, 10 ; se shifteaza eax cu 15-5 biti or edx, eax xor eax, eax mov al, byte [edi + 6] push eax call base32_to_value add esp, 4 shl eax, 5 ; se shifteaza eax cu 10-5 biti or edx, eax xor eax, eax mov al, byte [edi + 7] push eax call base32_to_value add esp, 4 or edx, eax ; nu mai este nevoie de shiftare mov byte [esi + 3], dl ; se scriu in sir caracterele in ordine inversa mov byte [esi + 2], dh shr edx, 16 mov byte [esi + 1], dl mov byte [esi], dh add esi, 4 ; fiecare 8 caractere codificate reprezinta 5 bytes add edi, 8 ; unul din ei fiind scris mai sus cmp byte [edi], 0 jne base32decode_iteration mov byte [esi], 0 pop ebp ret ;===============================================================; bruteforce_singlebyte_xor: ; TODO TASK 5 push ebp mov ebp, esp mov esi, ecx ;pun sirul in esi xor edx, edx ;verific sa am registrele goale xor edi, edi xor eax, eax xor ebx, ebx case_f: mov bh, byte [esi] ;iau un byte din mesaj xor bh, al ;construiesc cheia cmp bh, 'f' ;daca am gasit 'f' je case_o ;vreau sa vad daca am 'o' jmp fail ;nu am gasit 'f' case_o: mov bh, byte [esi + 1] ;iau urmatorul byte xor bh, al ;construiesc cheia cmp bh, 'o';daca am gasit 'o' je case_r ;vreau sa vad daca am 'r' jmp fail ;nu am gasit 'o' case_r: mov bh, byte [esi + 2] ;iau urmatorul byte xor bh, al ;construiesc cheia cmp bh, 'r' ;daca am gasit 'r' je case_c ;vreau sa vad daca am 'c' jmp fail ;nu am gasit 'r' case_c: mov bh, byte [esi + 3] ;iau urmatorul byte xor bh, al ;construiesc cheia cmp bh, 'c' ;daca am gasit 'c' je case_e ;vreau sa vad daca am 'e' jmp fail ;nu am gasit 'c' case_e: mov bh, byte[esi + 4] ;iau urmatorul byte xor bh, al ;construiesc cheia cmp bh, 'e' ;daca am gasit 'e' je end_try ;reiau procesul jmp fail ;nu am gasit 'e' fail: inc eax ;creste cheia cmp eax, 255 ;daca am ajuns la final jne case_f ;daca nu, verifica din nou xor eax, eax ;refa eax inc esi ;avanseaza in sir jmp case_f ;sare la inceput end_try: mov esi, ecx continue: cmp byte [esi], 0x00 ;daca am ajuns la finalul sirului je end_bruteforce ;iesi din functie xor byte [esi], al ;fac xor intre un byte din mesaj si cheie inc esi ;avanseaza in sir jmp continue ;reia procesul end_bruteforce: leave ret ;===============================================================; decode_vigenere: ; TODO TASK 6 push ebp mov ebp, esp mov esi, [ebp + 8] ;retin in esi mesajul mov edi, [ebp + 12] ;retin in edi cheia check_byte: mov bh, byte [edi] ;iau un byte din esi si il pun in bh mov bl, byte [esi] ;iau un byte din edi si il pun in bl cmp bl, 0x00 ;verific daca am ajuns la final je end_decode ;daca da, ies din functie cmp bl, 'a' jb next_step cmp bl, 'z' ja next_step sub bh, 'a' ;aflu offset pentru cheie sub bl, 'a' ;aflu offset pentru mesaj cmp bl, bh ;compar cele doua offset-uri jge ok ;daca bl>=bh, sar la label-ul ok jl not_ok ;daca bl<bh, sar la labe-ul not_ok not_ok: sub bl, bh ;scad din bl ce am in bh add bl, '{' ;adaug urmatorul caracter dupa z jmp ok2 ok: sub bl, bh add bl, 'a' ;pot sa adaug 'a' jmp ok2 ok2: mov byte [esi], bl ;reiau verificarea de la ok inc edi ;avansez in cheie cmp byte [edi], 0x00 ;verific daca am ajuns la final je reset ;daca da, resetez cheia jmp next_step ;avansez in mesaj reset: mov edi, [ebp + 12] jmp next_step next_step: inc esi jmp check_byte end_decode: leave ret ;===============================================================; main: push ebp mov ebp, esp sub esp, 2300 ; test argc mov eax, [ebp + 8] cmp eax, 2 jne exit_bad_arg ; get task no mov ebx, [ebp + 12] mov eax, [ebx + 4] xor ebx, ebx mov bl, [eax] sub ebx, '0' push ebx ; verify if task no is in range cmp ebx, 1 jb exit_bad_arg cmp ebx, 6 ja exit_bad_arg ; create the filename lea ecx, [filename + 7] add bl, '0' mov byte [ecx], bl ; fd = open("./input{i}.dat", O_RDONLY): mov eax, 5 mov ebx, filename xor ecx, ecx xor edx, edx int 0x80 cmp eax, 0 jl exit_no_input ; read(fd, ebp - 2300, inputlen): mov ebx, eax mov eax, 3 lea ecx, [ebp-2300] mov edx, [inputlen] int 0x80 cmp eax, 0 jl exit_cannot_read ; close(fd): mov eax, 6 int 0x80 ; all input{i}.dat contents are now in ecx (address on stack) pop eax cmp eax, 1 je task1 cmp eax, 2 je task2 cmp eax, 3 je task3 cmp eax, 4 je task4 cmp eax, 5 je task5 cmp eax, 6 je task6 jmp task_done task1: ; TASK 1: Simple XOR between two byte streams ; TODO TASK 1: find the address for the string and the key ; TODO TASK 1: call the xor_strings function push ecx ;salvez ecx pe stiva deoarece este alterat de strlen push ecx call strlen add esp, 4 pop ecx ;dupa apelul strlen nu uit sa scot ecx pe stiva mov ebx, ecx ;salvez ecx pentru apelul puts inc eax add ecx, eax ;actualizez ecx pentru fiecare pas push ebx ;salvez de fapt ecx pe stiva push ecx ;pun parametrii in ordine inversa pe stiva push ebx call xor_strings add esp, 8 call puts add esp, 4 jmp task_done task2: ; TASK 2: Rolling XOR ; TODO TASK 2: call the rolling_xor function push ecx ;pune sirul pe stiva call rolling_xor ;aplica functia add esp, 4 push ecx ;pune sirul de afisat in ecx call puts add esp, 4 jmp task_done task3: ; TASK 3: XORing strings represented as hex strings ; TODO TASK 1: find the addresses of both strings ; TODO TASK 1: call the xor_hex_strings function push ecx ;ecx poate fi alterat de strlen deci il salvez push ecx call strlen add esp, 4 pop ecx ;nu uit sa il scot de pe stiva mov ebx, ecx ;salvez ecx curent in ebx inc eax add ebx, eax ;actualizez ecx pentru fiecare pas push ecx ;convertesc mesajul call convert add esp, 4 push ebx ;convertesc cheia call convert add esp, 4 push ebx ;pun parametrii in ordine inversa pe stiva push ecx call xor_hex_strings add esp,8 push ecx ;rezultatul o sa fie pus in ecx call puts add esp, 4 jmp task_done task4: ; TASK 4: decoding a base32-encoded string ; TODO TASK 4: call the base32decode function push ecx call base32decode ; se apeleaza functia de decodificare add esp, 4 push ecx call puts ; se afiseaza sirul decodificat pop ecx jmp task_done task5: ; TASK 5: Find the single-byte key used in a XOR encoding ; TODO TASK 5: call the bruteforce_singlebyte_xor function call bruteforce_singlebyte_xor push eax ;salveaza eax din cauza puts push ecx call puts pop ecx pop eax ;nu uit sa il scot de pe stiva push eax ;eax = key value push fmtstr call printf ;print key value add esp, 8 jmp task_done task6: ; TASK 6: decode Vignere cipher ; TODO TASK 6: find the addresses for the input string and key ; TODO TASK 6: call the decode_vigenere function push ecx ;pune ecx pe stiva din cauza strlen push ecx call strlen add esp, 4 pop ecx ;nu uit sa il scot de pe stiva add eax, ecx inc eax push eax ;pune parametrii in ordine inversa pe stiva push ecx call decode_vigenere add esp, 8 push ecx ;afiseaza mesajul decriptat call puts add esp, 4 jmp task_done task_done: xor eax, eax jmp exit exit_bad_arg: mov ebx, [ebp + 12] mov ecx , [ebx] push ecx push usage call printf add esp, 8 jmp exit exit_no_input: push filename push error_no_file call printf add esp, 8 jmp exit exit_cannot_read: push filename push error_cannot_read call printf add esp, 8 jmp exit exit: mov esp, ebp pop ebp ret
SECTION code_driver SECTION code_driver_character_input PUBLIC _acia_flush_Rx_di PUBLIC _acia_flush_Rx EXTERN asm_z80_push_di, asm_z80_pop_ei EXTERN aciaRxCount, aciaRxBuffer, aciaRxIn, aciaRxOut _acia_flush_Rx_di: push af push hl call asm_z80_push_di ; di call _acia_flush_Rx call asm_z80_pop_ei ; ei pop hl pop af ret _acia_flush_Rx: xor a ld (aciaRxCount),a ; reset the Rx counter (set 0) ld hl,aciaRxBuffer ; load Rx buffer pointer home ld (aciaRxIn),hl ld (aciaRxOut),hl ret EXTERN _acia_need defc NEED = _acia_need
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace Federation; using namespace ServiceModel; using namespace Reliability; using namespace Reliability::FailoverManagerComponent; NodeCache::NodeCache( FailoverManager & fm, vector<NodeInfoSPtr> & nodes) : fm_(fm) , lastNodeUpTime_(DateTime::Zero) , isClusterStable_(false) , upCount_(0) , nodeCount_(0) , ackedSequence_(FABRIC_INVALID_SEQUENCE_NUMBER) , healthInitialized_(false) , healthSequence_(0) , initialSequence_(0) , invalidateSequence_(0) { for (size_t i = 0; i < nodes.size(); i++) { auto nodeCopy = nodes[i]; if (nodeCopy->HealthSequence >= healthSequence_) { healthSequence_ = nodeCopy->HealthSequence + 1; } InitializeNode(move(nodeCopy)); } // Currently we only need health report from FM, not FMM. if (!fm.IsMaster) { initialSequence_ = healthSequence_; fm.HealthClient->HealthPreInitialize(*ServiceModel::Constants::HealthReportFMSource, FABRIC_HEALTH_REPORT_KIND_NODE, fm_.PreOpenFMServiceEpoch.DataLossVersion); fm.WriteInfo(Constants::NodeCacheSource, "Loaded health sequence: {0}", healthSequence_); } } void NodeCache::InitializeNode(NodeInfoSPtr && node) { AddUpgradeDomain(*node); if (node->IsUp) { if (node->LastUpdated > lastNodeUpTime_) { lastNodeUpTime_ = node->LastUpdated; } upCount_++; } node->InitializeNodeName(); node->DeactivationInfo.Initialize(); DateTime stableTime = lastNodeUpTime_ + FailoverConfig::GetConfig().ClusterStableWaitDuration; isClusterStable_ = (stableTime < DateTime::Now()); Federation::NodeId const& nodeId = node->NodeInstance.Id; nodes_.insert(make_pair(nodeId, make_shared<CacheEntry<NodeInfo>>(move(node)))); nodeCount_++; } bool NodeCache::get_IsClusterStable() const { AcquireReadLock grab(lock_); // Once a cluster is stable, it never becomes unstable again. if (!isClusterStable_) { DateTime stableTime = lastNodeUpTime_ + FailoverConfig::GetConfig().ClusterStableWaitDuration; isClusterStable_ = (stableTime < DateTime::Now()); } return isClusterStable_; } bool NodeCache::get_IsClusterPaused() const { return !fm_.IsMaster && UpCount < static_cast<size_t>(FailoverConfig::GetConfig().ClusterPauseThreshold); } void NodeCache::Initialize(vector<NodeInfo> && nodes) { ASSERT_IF( nodes_.size() > 0u, "Initialize should only be called when the NodeCache is empty: {0}", nodes_.size()); for (size_t i = 0; i < nodes.size(); ++i) { NodeInfoSPtr node = make_shared<NodeInfo>(move(nodes[i])); int64 plbDuration; fm_.PLB.UpdateNode(node->GetPLBNodeDescription(), plbDuration); InitializeNode(move(node)); } } void NodeCache::StartPeriodicTask() { fm_.Events.PeriodicTaskBeginNoise(fm_.Id, PeriodicTaskName::NodeCache); auto startTime = Stopwatch::Now(); NodePeriodicTaskCounts taskCounts; ProcessNodes(taskCounts); ProcessHealth(); auto duration = Stopwatch::Now() - startTime; fm_.Events.NodePeriodicTaskEnd(fm_.Id, duration, taskCounts); } void NodeCache::ProcessHealth() { if (fm_.IsMaster) { healthInitialized_ = true; return; } vector<CacheEntrySPtr> nodesToUpdate; { AcquireWriteLock grab(lock_); FABRIC_SEQUENCE_NUMBER progress; ErrorCode error = fm_.HealthClient->HealthGetProgress(*ServiceModel::Constants::HealthReportFMSource, FABRIC_HEALTH_REPORT_KIND_NODE, progress); if (!error.IsSuccess()) { return; } ackedSequence_ = progress; if (!healthInitialized_) { InitializeHealthState(); } else if (invalidateSequence_ != FABRIC_INVALID_SEQUENCE_NUMBER) { for (auto it = nodes_.begin(); it != nodes_.end(); ++it) { NodeInfoSPtr const& nodeInfo = it->second->Get(); if (!nodeInfo->IsUnknown && nodeInfo->HealthSequence < invalidateSequence_) { nodesToUpdate.push_back(it->second); } } if (nodesToUpdate.size() == 0) { invalidateSequence_ = FABRIC_INVALID_SEQUENCE_NUMBER; } } } TimeoutHelper timeout(TimeSpan::FromSeconds(1)); for (auto it = nodesToUpdate.begin(); it != nodesToUpdate.end() && !timeout.IsExpired; ++it) { LockedNodeInfo lockedNodeInfo; ErrorCode error = (*it)->Lock(*it, lockedNodeInfo, TimeSpan::Zero); if (error.IsSuccess() && lockedNodeInfo->HealthSequence < invalidateSequence_) { NodeInfoSPtr newNodeInfo = make_shared<NodeInfo>(*lockedNodeInfo); newNodeInfo->HealthSequence = InterlockedIncrement64(&healthSequence_) - 1; newNodeInfo->PersistenceState = PersistenceState::ToBeUpdated; auto lockedNodeInfoMover = MoveUPtr<LockedNodeInfo>(move(make_unique<LockedNodeInfo>(move(lockedNodeInfo)))); fm_.Store.BeginUpdateData( *newNodeInfo, [this, newNodeInfo, lockedNodeInfoMover](AsyncOperationSPtr const& operation) mutable { int64 commitDuration(0); ErrorCode error = fm_.Store.EndUpdateData(*newNodeInfo, operation, commitDuration); ReportHealthAfterNodeUpdate(newNodeInfo, error); if (error.IsSuccess()) { fm_.WriteInfo(Constants::NodeUpdateSource, newNodeInfo->IdString, "Health sequence updated: {0}Commit Duration = {1} ms", *newNodeInfo, commitDuration); auto lockedNodeInfo = lockedNodeInfoMover.TakeUPtr(); lockedNodeInfo->Commit(move(newNodeInfo)); } else { fm_.WriteWarning( Constants::NodeSource, newNodeInfo->IdString, "Update health sequence for node {0} failed with {1}\r\nCommit Duration = {2} ms", newNodeInfo->Id, error, commitDuration); } }, fm_.CreateAsyncOperationRoot()); } } } void NodeCache::InitializeHealthState() { FABRIC_SEQUENCE_NUMBER progress = ackedSequence_; fm_.WriteInfo(Constants::NodeCacheSource, "HealthGetProgress: {0}", progress); if (progress > initialSequence_) { fm_.WriteWarning( Constants::NodeCacheSource, "Progress retrieved {0} is larger than FM knows {1}", progress, initialSequence_); invalidateSequence_ = initialSequence_ = progress; FABRIC_SEQUENCE_NUMBER currentSequence = healthSequence_; while (currentSequence < progress) { FABRIC_SEQUENCE_NUMBER last = InterlockedCompareExchange64(&healthSequence_, progress, currentSequence); if (last == currentSequence) { fm_.WriteWarning( Constants::NodeCacheSource, "Updating sequence from {0} to {1}", currentSequence, progress); break; } else { currentSequence = last; } } } size_t reportCount = 0; if (initialSequence_ > progress) { vector<HealthReport> reports; for (auto it = nodes_.begin(); it != nodes_.end(); ++it) { NodeInfoSPtr const& nodeInfo = it->second->Get(); if (nodeInfo->HealthSequence >= progress && nodeInfo->HealthSequence < initialSequence_) { reports.push_back(fm_.HealthReportFactoryObj.GenerateNodeInfoHealthReport(nodeInfo)); } } reportCount = reports.size(); if (reportCount > 0) { fm_.HealthClient->AddHealthReports(move(reports)); } } FABRIC_SEQUENCE_NUMBER invalidateSequence = (invalidateSequence_ == 0 ? FABRIC_INVALID_SEQUENCE_NUMBER : invalidateSequence_); fm_.HealthClient->HealthPostInitialize(*ServiceModel::Constants::HealthReportFMSource, FABRIC_HEALTH_REPORT_KIND_NODE, initialSequence_, invalidateSequence); fm_.WriteInfo(Constants::NodeCacheSource, "HealthPostInitialize {0}/{1} with {2} reports", initialSequence_, invalidateSequence, reportCount); healthInitialized_ = true; } void NodeCache::GetNodes(vector<NodeInfo> & nodes) const { AcquireReadLock grab(lock_); for (auto it = nodes_.begin(); it != nodes_.end(); ++it) { NodeInfoSPtr const& nodeInfo = it->second->Get(); nodes.push_back(*nodeInfo); } } ErrorCode NodeCache::GetNodesForGFUMTransfer(__out vector<NodeInfo> & nodeInfos) const { ASSERT_IFNOT(fm_.IsMaster, "Only FMM request the nodes GFUM transfer"); AcquireReadLock grab(lock_); for (auto it = nodes_.begin(); it != nodes_.end(); ++it) { LockedNodeInfo lockedNodeInfo; ErrorCode error = it->second->Lock(it->second, lockedNodeInfo); if (!error.IsSuccess()) { return error; } nodeInfos.push_back(*lockedNodeInfo); } return ErrorCode::Success(); } void NodeCache::GetNodes(vector<NodeInfoSPtr> & nodes) const { AcquireReadLock grab(lock_); for (auto it = nodes_.begin(); it != nodes_.end(); it++) { NodeInfoSPtr const& nodeInfo = it->second->Get(); nodes.push_back(nodeInfo); } } void NodeCache::GetNodes(NodeId continuationToken, vector<NodeInfoSPtr> & nodes) const { AcquireReadLock grab(lock_); auto contTokenIt = nodes_.upper_bound(continuationToken); if (contTokenIt == nodes_.end()) { fm_.WriteInfo(Constants::NodeCacheSource, "Get nodes with continuation token {0} returned no results", continuationToken); return; } for (auto it = contTokenIt; it != nodes_.end(); it++) { NodeInfoSPtr const& nodeInfo = it->second->Get(); nodes.push_back(nodeInfo); } } NodeInfoSPtr NodeCache::GetNode(NodeId id) const { AcquireReadLock grab(lock_); auto it = nodes_.find(id); if (it == nodes_.end()) { return nullptr; } return it->second->Get(); } ErrorCode NodeCache::DeactivateNodes(map<NodeId, NodeDeactivationIntent::Enum> const& nodesToDeactivate, wstring const& batchId, int64 sequenceNumber) { vector<LockedNodeInfo> lockedNodeInfos; vector<NodeInfoSPtr> newNodeInfos; for (auto it = nodesToDeactivate.begin(); it != nodesToDeactivate.end(); ++it) { NodeId nodeId = it->first; NodeDeactivationIntent::Enum deactivationIntent = it->second; if (deactivationIntent == NodeDeactivationIntent::None) { fm_.WriteInfo(Constants::NodeSource, wformatString(nodeId), "DeactivateNodes processing for node {0} failed with Invalid Argument Exception: Deactivation intent 'None'", nodeId); return ErrorCodeValue::InvalidArgument; } bool isNewEntry; LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(it->first, lockedNodeInfo, true, isNewEntry); if (!error.IsSuccess()) { fm_.WriteInfo( Constants::NodeSource, wformatString(nodeId), "DeactivateNodes processing for node {0} failed with {1}", nodeId, error); return error; } if (lockedNodeInfo->DeactivationInfo.SequenceNumber >= sequenceNumber) { fm_.WriteInfo( Constants::NodeSource, lockedNodeInfo->IdString, "Ignoring stale/duplicate DeactivateNodes request for node {0}. SeqNum = {1}, Incoming = {2}", nodeId, lockedNodeInfo->DeactivationInfo.SequenceNumber, sequenceNumber); if (lockedNodeInfo->DeactivationInfo.SequenceNumber == sequenceNumber) { continue; } else { return ErrorCodeValue::StaleRequest; } } NodeInfoSPtr newNodeInfo = make_shared<NodeInfo>(*lockedNodeInfo); newNodeInfo->DeactivationInfo.AddBatch(batchId, deactivationIntent, sequenceNumber); if ((!newNodeInfo->IsUp && deactivationIntent != NodeDeactivationIntent::RemoveData && deactivationIntent != NodeDeactivationIntent::RemoveNode) || (deactivationIntent == NodeDeactivationIntent::Pause && !FailoverConfig::GetConfig().PerformSafetyChecksForNodeDeactivationIntentPause)) { newNodeInfo->DeactivationInfo.Status = NodeDeactivationStatus::DeactivationComplete; } if (isNewEntry) { newNodeInfo->PersistenceState = PersistenceState::ToBeInserted; } lockedNodeInfos.push_back(move(lockedNodeInfo)); newNodeInfos.push_back(move(newNodeInfo)); } ErrorCode error = fm_.Store.UpdateNodes(newNodeInfos); if (error.IsSuccess()) { for (size_t i = 0; i < newNodeInfos.size(); i++) { NodeInfoSPtr & newNodeInfo = newNodeInfos[i]; int64 plbElapsedTime; fm_.PLB.UpdateNode(newNodeInfo->GetPLBNodeDescription(), plbElapsedTime); fm_.WriteInfo( Constants::NodeUpdateSource, newNodeInfo->IdString, "Node deactivation started for batch {0}: {1}, PLB Duration = {2} ms", batchId, *newNodeInfo, plbElapsedTime); if (newNodeInfo->DeactivationInfo.Status == NodeDeactivationStatus::DeactivationComplete) { // Push this information to Event Store fm_.NodeEvents.DeactivateNodeCompletedOperational( Common::Guid::NewGuid(), newNodeInfo->Description.NodeName, newNodeInfo->NodeInstance.InstanceId, newNodeInfo->DeactivationInfo.Intent, newNodeInfo->DeactivationInfo.StartTime); } lockedNodeInfos[i].Commit(move(newNodeInfo)); } } else { for (size_t i = 0; i < newNodeInfos.size(); i++) { NodeInfoSPtr & newNodeInfo = newNodeInfos[i]; if (newNodeInfo->PersistenceState == PersistenceState::ToBeInserted) { AcquireWriteLock grab(lock_); lockedNodeInfos[i].IsDeleted = true; nodes_.erase(newNodeInfo->Id); } fm_.WriteInfo( Constants::NodeSource, newNodeInfo->IdString, "DeactivateNodes processing for batch {0} node {1} failed with {2}", batchId, newNodeInfo->Id, error); } } return error; } ErrorCode NodeCache::GetNodeDeactivationStatus( wstring const& batchId, __out NodeDeactivationStatus::Enum & nodeDeactivationStatus, __out vector<NodeProgress> & progressDetails) const { nodeDeactivationStatus = NodeDeactivationStatus::None; bool isFound = false; AcquireReadLock grab(lock_); for (auto it = nodes_.begin(); it != nodes_.end(); it++) { NodeInfoSPtr const& nodeInfo = it->second->Get(); if (nodeInfo->DeactivationInfo.ContainsBatch(batchId)) { isFound = true; if (nodeInfo->DeactivationInfo.Status <= nodeDeactivationStatus) { nodeDeactivationStatus = nodeInfo->DeactivationInfo.Status; if (!nodeInfo->DeactivationInfo.PendingSafetyChecks.empty()) { NodeProgress nodeProgress(nodeInfo->Id, nodeInfo->NodeName, nodeInfo->DeactivationInfo.PendingSafetyChecks); progressDetails.push_back(move(nodeProgress)); } } } } if (!isFound) { nodeDeactivationStatus = NodeDeactivationStatus::DeactivationComplete; } return ErrorCodeValue::Success; } ErrorCode NodeCache::RemoveNodeDeactivation(wstring const& batchId, int64 sequenceNumber) { vector<LockedNodeInfo> lockedNodeInfos; vector<NodeInfoSPtr> newNodeInfos; { AcquireReadLock grab(lock_); for (auto it = nodes_.begin(); it != nodes_.end(); ++it) { NodeInfoSPtr nodeInfo = it->second->Get(); if (nodeInfo->DeactivationInfo.ContainsBatch(batchId)) { LockedNodeInfo lockedNodeInfo; ErrorCode error = it->second->Lock(it->second, lockedNodeInfo); if (error.IsSuccess() && lockedNodeInfo->DeactivationInfo.ContainsBatch(batchId)) { NodeInfoSPtr newNodeInfo = make_shared<NodeInfo>(*lockedNodeInfo); newNodeInfo->DeactivationInfo.RemoveBatch(batchId, sequenceNumber, newNodeInfo->IsUp); lockedNodeInfos.push_back(move(lockedNodeInfo)); newNodeInfos.push_back(move(newNodeInfo)); } else if (!error.IsSuccess()) { fm_.WriteInfo( Constants::NodeSource, wformatString(nodeInfo->Id), "RemoveNodeDeactivation processing for batch {0} node {1} failed with {2}", batchId, nodeInfo->Id, error); return error; } } } } ErrorCode error = fm_.Store.UpdateNodes(newNodeInfos); if (error.IsSuccess()) { for (size_t i = 0; i < newNodeInfos.size(); i++) { NodeInfoSPtr & newNodeInfo = newNodeInfos[i]; int64 plbElapsedTime; fm_.PLB.UpdateNode(newNodeInfo->GetPLBNodeDescription(), plbElapsedTime); fm_.WriteInfo( Constants::NodeUpdateSource, newNodeInfo->IdString, "Node deactivation removed for batch {0}: {1}, PLB duration = {2} ms", batchId, *newNodeInfo, plbElapsedTime); lockedNodeInfos[i].Commit(move(newNodeInfo)); } } else { for (size_t i = 0; i < newNodeInfos.size(); i++) { NodeInfoSPtr & newNodeInfo = newNodeInfos[i]; fm_.WriteInfo( Constants::NodeSource, newNodeInfo->IdString, "RemoveNodeDeactivation processing for batch {0} node {1} failed with {2}", batchId, newNodeInfo->Id, error); } } return error; } ErrorCode NodeCache::UpdateNodeDeactivationStatus( NodeId nodeId, NodeDeactivationIntent::Enum deactivationIntent, NodeDeactivationStatus::Enum deactivationStatus, map<NodeId, NodeUpgradeProgress> && pending, map<NodeId, pair<NodeUpgradeProgress, NodeInfoSPtr>> && ready, map<NodeId, NodeUpgradeProgress> && waiting) { LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeId, lockedNodeInfo); if (!error.IsSuccess()) { fm_.WriteInfo( Constants::NodeSource, wformatString(nodeId), "UpdateNodeDeactivationStatus processing for node {0} failed with {1}", nodeId, error); return error; } if (!lockedNodeInfo->IsUp && lockedNodeInfo->DeactivationInfo.IsRemove && deactivationStatus == NodeDeactivationStatus::DeactivationSafetyCheckComplete) { deactivationStatus = NodeDeactivationStatus::DeactivationComplete; } lockedNodeInfo->DeactivationInfo.UpdateProgressDetails(nodeId, move(pending), move(ready), move(waiting), deactivationStatus == NodeDeactivationStatus::DeactivationComplete); if (lockedNodeInfo->DeactivationInfo.Intent == deactivationIntent && (lockedNodeInfo->DeactivationInfo.Status != deactivationStatus || (lockedNodeInfo->IsPendingDeactivateNode && deactivationStatus == NodeDeactivationStatus::DeactivationComplete))) { NodeInfoSPtr newNodeInfo = make_shared<NodeInfo>(*lockedNodeInfo); newNodeInfo->DeactivationInfo.Status = deactivationStatus; if (deactivationStatus == NodeDeactivationStatus::DeactivationComplete) { newNodeInfo->IsPendingDeactivateNode = false; } int64 commitDuration; error = fm_.Store.UpdateData(*newNodeInfo, commitDuration); if (error.IsSuccess()) { int64 plbElapsedTime; fm_.PLB.UpdateNode(newNodeInfo->GetPLBNodeDescription(), plbElapsedTime); fm_.WriteInfo( Constants::NodeUpdateSource, newNodeInfo->IdString, "Node deactivation status updated: {0}Commit Duration = {1} ms, PLB Duration = {2} ms", *newNodeInfo, commitDuration, plbElapsedTime); if (newNodeInfo->DeactivationInfo.Status == NodeDeactivationStatus::DeactivationComplete) { // Push this information to Event Store fm_.NodeEvents.DeactivateNodeCompletedOperational( Common::Guid::NewGuid(), newNodeInfo->Description.NodeName, newNodeInfo->NodeInstance.InstanceId, newNodeInfo->DeactivationInfo.Intent, newNodeInfo->DeactivationInfo.StartTime); } lockedNodeInfo.Commit(move(newNodeInfo)); } else { fm_.WriteInfo( Constants::NodeSource, wformatString(nodeId), "UpdateNodeDeactivationStatus processing for node {0} failed with {1}\r\nCommit Duration = {2} ms", nodeId, error, commitDuration); } } return error; } void NodeCache::ProcessNodeDeactivateReplyAsync(NodeId const& nodeId, int64 sequenceNumber) { LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeId, lockedNodeInfo); if (!error.IsSuccess()) { fm_.WriteInfo( Constants::NodeSource, wformatString(nodeId), "NodeDeactivateReply processing for node {0} failed with {1}", nodeId, error); return; } ASSERT_IF( sequenceNumber > lockedNodeInfo->DeactivationInfo.SequenceNumber, "Deactivation sequence number in reply from from node {0} cannot be greater than what FM has: SeqNum={1}, Incoming={2}", nodeId, lockedNodeInfo->DeactivationInfo.SequenceNumber, sequenceNumber); if (sequenceNumber < lockedNodeInfo->DeactivationInfo.SequenceNumber) { fm_.WriteInfo( Constants::NodeSource, lockedNodeInfo->IdString, "Ignoring stale NodeDeactivateReply message from node {0}: SeqNum={1}, Incoming={2}", nodeId, lockedNodeInfo->DeactivationInfo.SequenceNumber, sequenceNumber); return; } if (lockedNodeInfo->DeactivationInfo.IsRemove && lockedNodeInfo->DeactivationInfo.IsSafetyCheckComplete) { NodeInfoSPtr newNodeInfo = make_shared<NodeInfo>(*lockedNodeInfo); newNodeInfo->DeactivationInfo.Status = NodeDeactivationStatus::DeactivationComplete; newNodeInfo->IsPendingDeactivateNode = false; auto lockedNodeInfoMover = MoveUPtr<LockedNodeInfo>(move(make_unique<LockedNodeInfo>(move(lockedNodeInfo)))); fm_.Store.BeginUpdateData( *newNodeInfo, [this, newNodeInfo, lockedNodeInfoMover](AsyncOperationSPtr const& operation) mutable { int64 commitDuration(0); ErrorCode error = fm_.Store.EndUpdateData(*newNodeInfo, operation, commitDuration); if (error.IsSuccess()) { int64 plbElapsedTime; fm_.PLB.UpdateNode(newNodeInfo->GetPLBNodeDescription(), plbElapsedTime); fm_.WriteInfo( Constants::NodeUpdateSource, newNodeInfo->IdString, "Node deactivation complete: {0}Commit Duration = {1} ms, PLB Duration = {2} ms", *newNodeInfo, commitDuration, plbElapsedTime); // Push data to Event store. fm_.NodeEvents.DeactivateNodeCompletedOperational( Common::Guid::NewGuid(), newNodeInfo->Description.NodeName, newNodeInfo->NodeInstance.InstanceId, newNodeInfo->DeactivationInfo.Intent, newNodeInfo->DeactivationInfo.StartTime); auto lockedNodeInfo = lockedNodeInfoMover.TakeUPtr(); lockedNodeInfo->Commit(move(newNodeInfo)); } else { fm_.WriteInfo( Constants::NodeSource, newNodeInfo->IdString, "NodeDeactivateReply processing for node {0} failed with {1}\r\nCommit Duration = {2} ms", newNodeInfo->Id, error, commitDuration); } }, fm_.CreateAsyncOperationRoot()); } } void NodeCache::ProcessNodeActivateReplyAsync(NodeId const& nodeId, int64 sequenceNumber) { LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeId, lockedNodeInfo); if (!error.IsSuccess()) { fm_.WriteInfo( Constants::NodeSource, wformatString(nodeId), "NodeActivateReply processing for node {0} failed with {1}", nodeId, error); return; } ASSERT_IF( sequenceNumber > lockedNodeInfo->DeactivationInfo.SequenceNumber, "Deactivation sequence number in reply from from node {0} cannot be greater than what FM has: SeqNum={1}, Incoming={2}", nodeId, lockedNodeInfo->DeactivationInfo.SequenceNumber, sequenceNumber); if (sequenceNumber < lockedNodeInfo->DeactivationInfo.SequenceNumber) { fm_.WriteInfo( Constants::NodeSource, lockedNodeInfo->IdString, "Ignoring stale NodeActivateReply message from node {0}: SeqNum={1}, Incoming={2}", nodeId, lockedNodeInfo->DeactivationInfo.SequenceNumber, sequenceNumber); return; } if (!lockedNodeInfo->DeactivationInfo.IsDeactivated && lockedNodeInfo->DeactivationInfo.IsActivationInProgress) { NodeInfoSPtr newNodeInfo = make_shared<NodeInfo>(*lockedNodeInfo); newNodeInfo->DeactivationInfo.Status = NodeDeactivationStatus::None; newNodeInfo->IsPendingDeactivateNode = false; auto lockedNodeInfoMover = MoveUPtr<LockedNodeInfo>(move(make_unique<LockedNodeInfo>(move(lockedNodeInfo)))); fm_.Store.BeginUpdateData( *newNodeInfo, [this, newNodeInfo, lockedNodeInfoMover](AsyncOperationSPtr const& operation) mutable { int64 commitDuration(0); ErrorCode error = fm_.Store.EndUpdateData(*newNodeInfo, operation, commitDuration); if (error.IsSuccess()) { int64 plbElapsedTime; fm_.PLB.UpdateNode(newNodeInfo->GetPLBNodeDescription(), plbElapsedTime); fm_.WriteInfo( Constants::NodeUpdateSource, newNodeInfo->IdString, "Node activativation complete: {0}Commit Duration = {1} ms, PLB Duration = {2} ms", *newNodeInfo, commitDuration, plbElapsedTime); auto lockedNodeInfo = lockedNodeInfoMover.TakeUPtr(); lockedNodeInfo->Commit(move(newNodeInfo)); } else { fm_.WriteInfo( Constants::NodeSource, newNodeInfo->IdString, "NodeActivateReply processing for node {0} failed with {1}\r\nCommit Duration = {2} ms", newNodeInfo->Id, error, commitDuration); } }, fm_.CreateAsyncOperationRoot()); } } NodeDeactivationInfo NodeCache::GetNodeDeactivationInfo(Federation::NodeId const& nodeId) const { AcquireReadLock grab(lock_); auto it = nodes_.find(nodeId); if (it != nodes_.end()) { NodeInfoSPtr const& nodeInfo = it->second->Get(); return nodeInfo->DeactivationInfo; } return NodeDeactivationInfo(); } void NodeCache::AddDeactivateNodeContext(vector<BackgroundThreadContextUPtr> & contexts) const { map<wstring, map<NodeId, NodeDeactivationIntent::Enum>> deactivateBatches; { AcquireReadLock grab(lock_); for (auto it = nodes_.begin(); it != nodes_.end(); ++it) { NodeInfoSPtr const& nodeInfo = it->second->Get(); if (nodeInfo->DeactivationInfo.IsDeactivated && !nodeInfo->DeactivationInfo.IsDeactivationComplete) { for (wstring const& batchId : nodeInfo->DeactivationInfo.BatchIds) { auto it1 = deactivateBatches.find(batchId); if (it1 == deactivateBatches.end()) { map<NodeId, NodeDeactivationIntent::Enum> nodesToDeactivate; nodesToDeactivate[nodeInfo->Id] = nodeInfo->DeactivationInfo.Intent; deactivateBatches[batchId] = move(nodesToDeactivate); } else { deactivateBatches[batchId][nodeInfo->Id] = nodeInfo->DeactivationInfo.Intent; } } } } } if (!deactivateBatches.empty()) { // Randomly pick a batch auto it = deactivateBatches.begin(); int r = Random().Next(static_cast<int>(deactivateBatches.size())); for (int i = 0; i < r; i++) { it++; } auto context = make_unique<DeactivateNodesContext>(it->second, it->first); context->CheckSeedNodes(fm_); contexts.push_back(move(context)); } } AsyncOperationSPtr NodeCache::BeginUpdateNodeSequenceNumber( NodeInstance const& nodeInstance, uint64 sequenceNumber, AsyncCallback const& callback, AsyncOperationSPtr const& state) { LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeInstance.Id, lockedNodeInfo); if (!error.IsSuccess()) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(error, callback, state); } if (lockedNodeInfo->NodeInstance != nodeInstance || lockedNodeInfo->SequenceNumber >= sequenceNumber) { fm_.NodeEvents.UpdateNodeSequenceNumberStale(nodeInstance.Id); return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(ErrorCodeValue::StaleRequest, callback, state); } NodeInfoSPtr newNodeInfo = make_shared<NodeInfo>(*lockedNodeInfo); newNodeInfo->SequenceNumber = sequenceNumber; auto newNodeInfoPtr = newNodeInfo.get(); pair<LockedNodeInfo, NodeInfoSPtr> context(move(lockedNodeInfo), move(newNodeInfo)); return fm_.Store.BeginUpdateData( *newNodeInfoPtr, OperationContextCallback<pair<LockedNodeInfo, NodeInfoSPtr>>(callback, move(context)), state); } ErrorCode NodeCache::EndUpdateNodeSequenceNumber(AsyncOperationSPtr const& operation) { unique_ptr<OperationContext<pair<LockedNodeInfo, NodeInfoSPtr>>> context = operation->PopOperationContext<pair<LockedNodeInfo, NodeInfoSPtr>>(); if (context) { LockedNodeInfo & lockedNodeInfo = context->Context.first; NodeInfoSPtr & newNodeInfo = context->Context.second; int64 commitDuration; ErrorCode error = fm_.Store.EndUpdateData(*newNodeInfo, operation, commitDuration); if (error.IsSuccess()) { fm_.WriteInfo( Constants::NodeUpdateSource, newNodeInfo->IdString, "SequenceNumber updated: {0}Commit Duration = {1} ms", *newNodeInfo, commitDuration); lockedNodeInfo.Commit(move(newNodeInfo)); } return error; } return CompletedAsyncOperation::End(operation); } AsyncOperationSPtr NodeCache::BeginPartitionNotification( std::vector<PartitionId> && disabledPartitions, uint64 sequenceNumber, Federation::NodeInstance const& nodeInstance, Common::AsyncCallback const& callback, Common::AsyncOperationSPtr const& state) { LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeInstance.Id, lockedNodeInfo); if (!error.IsSuccess()) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(error, callback, state); } if (lockedNodeInfo->NodeInstance != nodeInstance || lockedNodeInfo->SequenceNumber >= sequenceNumber) { fm_.NodeEvents.PartitionNotificationSequenceNumberStale(nodeInstance.Id); return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(ErrorCodeValue::StaleRequest, callback, state); } NodeInfoSPtr newNodeInfo = make_shared<NodeInfo>(*lockedNodeInfo); newNodeInfo->SequenceNumber = sequenceNumber; newNodeInfo->DisabledPartitions = move(disabledPartitions); auto newNodeInfoPtr = newNodeInfo.get(); pair<LockedNodeInfo, NodeInfoSPtr> context(move(lockedNodeInfo), move(newNodeInfo)); return fm_.Store.BeginUpdateData( *newNodeInfoPtr, OperationContextCallback<pair<LockedNodeInfo, NodeInfoSPtr>>(callback, move(context)), state); } ErrorCode NodeCache::EndPartitionNotification(AsyncOperationSPtr const& operation) { unique_ptr<OperationContext<pair<LockedNodeInfo, NodeInfoSPtr>>> context = operation->PopOperationContext<pair<LockedNodeInfo, NodeInfoSPtr>>(); if (context) { LockedNodeInfo & lockedNodeInfo = context->Context.first; NodeInfoSPtr & newNodeInfo = context->Context.second; int64 commitDuration; ErrorCode error = fm_.Store.EndUpdateData(*newNodeInfo, operation, commitDuration); if (error.IsSuccess()) { fm_.WriteInfo( Constants::NodeUpdateSource, newNodeInfo->IdString, "DisabledPartitions updated: {0}Commit Duration = {1} ms", *newNodeInfo, commitDuration); lockedNodeInfo.Commit(move(newNodeInfo)); } return error; } return CompletedAsyncOperation::End(operation); } void NodeCache::UpdateVersionInstanceAsync(NodeInstance const& nodeInstance, FabricVersionInstance const& versionInstance) { LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeInstance.Id, lockedNodeInfo); if (!error.IsSuccess()) { fm_.WriteInfo( Constants::NodeSource, wformatString(nodeInstance.Id), "UpdateVersionInstance processing for node {0} failed with {1}", nodeInstance, error); return; } if (!lockedNodeInfo->IsPendingFabricUpgrade && lockedNodeInfo->Description.VersionInstance == versionInstance) { return; } NodeDescription nodeDescription( versionInstance, lockedNodeInfo->UpgradeDomainId, lockedNodeInfo->FaultDomainIds, lockedNodeInfo->NodeProperties, lockedNodeInfo->NodeCapacityRatios, lockedNodeInfo->NodeCapacities, lockedNodeInfo->NodeName, lockedNodeInfo->NodeType, lockedNodeInfo->IpAddressOrFQDN, lockedNodeInfo->Description.ClusterConnectionPort); NodeInfoSPtr newNodeInfo = make_shared<NodeInfo>(*lockedNodeInfo); newNodeInfo->Description = nodeDescription; newNodeInfo->IsPendingFabricUpgrade = false; newNodeInfo->PersistenceState = PersistenceState::ToBeUpdated; auto lockedNodeInfoMover = MoveUPtr<LockedNodeInfo>(move(make_unique<LockedNodeInfo>(move(lockedNodeInfo)))); fm_.Store.BeginUpdateData( *newNodeInfo, [this, newNodeInfo, lockedNodeInfoMover](AsyncOperationSPtr const& operation) mutable { int64 commitDuration(0); ErrorCode error = fm_.Store.EndUpdateData(*newNodeInfo, operation, commitDuration); if (error.IsSuccess()) { fm_.WriteInfo( Constants::NodeUpdateSource, newNodeInfo->IdString, "VersionInstance updated: {0}Commit Duration = {1} ms", *newNodeInfo, commitDuration); auto lockedNodeInfo = lockedNodeInfoMover.TakeUPtr(); lockedNodeInfo->Commit(move(newNodeInfo)); } else { fm_.WriteInfo( Constants::NodeSource, newNodeInfo->IdString, "UpdateVersionInstance update for node {0} failed with {1}", newNodeInfo->NodeInstance, error); } }, fm_.CreateAsyncOperationRoot()); } ErrorCode NodeCache::NodeUp(NodeInfoSPtr && node) { NodeInstance nodeInstance = node->NodeInstance; bool isNewEntry; LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeInstance.Id, lockedNodeInfo, true, isNewEntry); if (!error.IsSuccess()) { return error; } if ((lockedNodeInfo->NodeInstance.InstanceId < node->NodeInstance.InstanceId) || (lockedNodeInfo->NodeInstance.InstanceId == node->NodeInstance.InstanceId && lockedNodeInfo->IsUp && !lockedNodeInfo->IsReplicaUploaded && node->IsReplicaUploaded)) { if (lockedNodeInfo->IsUp) { node->NodeDownTime = DateTime::Now(); } else { node->NodeDownTime = lockedNodeInfo->NodeDownTime; } node->NodeUpTime = DateTime::Now(); node->DeactivationInfo = lockedNodeInfo->DeactivationInfo; if (!fm_.IsMaster) { node->HealthSequence = InterlockedIncrement64(&healthSequence_) - 1; } if (!isNewEntry) { node->PersistenceState = PersistenceState::ToBeUpdated; } int64 commitDuration; error = fm_.Store.UpdateData(*node, commitDuration); ReportHealthAfterNodeUpdate(node, error); if (error.IsSuccess()) { lastNodeUpTime_ = DateTime::Now(); if (!fm_.IsMaster) { fm_.NodeEvents.NodeUp(node->IdString, node->NodeInstance.InstanceId); // Push data to Event store. fm_.NodeEvents.NodeUpOperational(Common::Guid::NewGuid(), node->Description.NodeName, node->NodeInstance.InstanceId, node->NodeDownTime); } fm_.NodeEvents.NodeAddedToGFUM(node->Id, node->NodeInstance.InstanceId); int64 plbElapsedTime; fm_.PLB.UpdateNode(node->GetPLBNodeDescription(), plbElapsedTime); fm_.WriteInfo(Constants::NodeUpdateSource, wformatString(nodeInstance.Id), "NodeUp: {0}Commit Duration = {1} ms, PLB Duration = {2} ms", *node, commitDuration, plbElapsedTime); AddUpgradeDomain(*node); if (isNewEntry) { nodeCount_++; } if (!lockedNodeInfo->IsUp) { uint64 oldUpCount = upCount_++; if (!fm_.IsMaster) { if (oldUpCount == FailoverConfig::GetConfig().ClusterPauseThreshold - 1) { fm_.Events.ClusterEndPauseState(oldUpCount + 1); } else if (oldUpCount < FailoverConfig::GetConfig().ClusterPauseThreshold - 1) { fm_.Events.ClusterInPauseState(oldUpCount + 1); } } } lockedNodeInfo.Commit(move(node)); } else if (isNewEntry) { AcquireWriteLock lock(lock_); lockedNodeInfo.IsDeleted = true; nodes_.erase(nodeInstance.Id); } } if (error.IsSuccess()) { error = fm_.ServiceCacheObj.RemoveFromDisabledNodes(0, nodeInstance.Id); } return error; } AsyncOperationSPtr NodeCache::BeginReplicaUploaded( NodeInstance const& nodeInstance, AsyncCallback const& callback, AsyncOperationSPtr const& state) { LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeInstance.Id, lockedNodeInfo); TESTASSERT_IF(error.IsError(ErrorCodeValue::NodeNotFound), "{0} not found for ReplicaUploaded", nodeInstance); if (!error.IsSuccess()) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(error, callback, state); } if (lockedNodeInfo->NodeInstance.InstanceId > nodeInstance.InstanceId || lockedNodeInfo->IsReplicaUploaded) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(ErrorCodeValue::Success, callback, state); } TESTASSERT_IF( lockedNodeInfo->NodeInstance.InstanceId != nodeInstance.InstanceId, "{0} not match {1} for ReplicaUploaded", nodeInstance, *lockedNodeInfo); NodeInfoSPtr newNode = make_shared<NodeInfo>(*lockedNodeInfo); newNode->IsReplicaUploaded = true; auto newNodeInfoPtr = newNode.get(); pair<LockedNodeInfo, NodeInfoSPtr> context(move(lockedNodeInfo), move(newNode)); return fm_.Store.BeginUpdateData( *newNodeInfoPtr, OperationContextCallback<pair<LockedNodeInfo, NodeInfoSPtr>>(callback, move(context)), state); } ErrorCode NodeCache::EndReplicaUploaded(AsyncOperationSPtr const& operation) { auto context = operation->PopOperationContext<pair<LockedNodeInfo, NodeInfoSPtr>>(); if (context) { LockedNodeInfo & lockedNodeInfo = context->Context.first; NodeInfoSPtr & newNode = context->Context.second; int64 commitDuration; ErrorCode error = fm_.Store.EndUpdateData(*newNode, operation, commitDuration); if (error.IsSuccess()) { fm_.WriteInfo(Constants::NodeUpdateSource, newNode->IdString, "Replicas uploaded: {0}Commit Duration = {1} ms", *newNode, commitDuration); lockedNodeInfo.Commit(move(newNode)); } return error; } return CompletedAsyncOperation::End(operation); } ErrorCode NodeCache::NodeDown(NodeInstance const& nodeInstance) { // First check if an update is needed without locking the NodeInfo. // NodeInfo can be stale, but if the incoming message is even staler // then we can safely ignore it. NodeInfoSPtr nodeInfo = GetNode(nodeInstance.Id); if (nodeInfo && (nodeInfo->NodeInstance.InstanceId > nodeInstance.InstanceId || (nodeInfo->NodeInstance.InstanceId == nodeInstance.InstanceId && !nodeInfo->IsUp))) { return ErrorCodeValue::Success; } // // An upate may be needed. Lock NodeInfo and check again if the update is needed. // bool isNewEntry; LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeInstance.Id, lockedNodeInfo, true, isNewEntry); if (!error.IsSuccess()) { return error; } if ((lockedNodeInfo->NodeInstance.InstanceId > nodeInstance.InstanceId) || (!isNewEntry && lockedNodeInfo->NodeInstance.InstanceId == nodeInstance.InstanceId && !lockedNodeInfo->IsUp)) { return ErrorCodeValue::Success; } NodeInfoSPtr node = make_shared<NodeInfo>( nodeInstance, NodeDescription(lockedNodeInfo->Description), false, // IsUp false, // IsReplicaUploaded false, // IsNodeStateRemoved DateTime::Now()); // LastUpdated node->NodeUpTime = lockedNodeInfo->NodeUpTime; node->NodeDownTime = DateTime::Now(); node->DeactivationInfo = lockedNodeInfo->DeactivationInfo; if (node->DeactivationInfo.IsActivated) { node->DeactivationInfo.Status = NodeDeactivationStatus::None; } else if (!node->DeactivationInfo.IsRemove) { node->DeactivationInfo.Status = NodeDeactivationStatus::DeactivationComplete; } if (!fm_.IsMaster) { node->HealthSequence = InterlockedIncrement64(&healthSequence_) - 1; } if (!isNewEntry) { node->PersistenceState = PersistenceState::ToBeUpdated; } int64 commitDuration; error = fm_.Store.UpdateData(*node, commitDuration); ReportHealthAfterNodeUpdate(node, error); if (error.IsSuccess()) { if (!fm_.IsMaster) { fm_.NodeEvents.NodeDown(node->IdString, node->NodeInstance.InstanceId); // Push data to Event Store. fm_.NodeEvents.NodeDownOperational(Common::Guid::NewGuid(), node->Description.NodeName, node->NodeInstance.InstanceId, node->NodeUpTime); } fm_.NodeEvents.NodeRemovedFromGFUM(node->Id, node->NodeInstance.InstanceId); int64 plbElapsedTime; fm_.PLB.UpdateNode(node->GetPLBNodeDescription(), plbElapsedTime); fm_.WriteInfo(Constants::NodeUpdateSource, wformatString(nodeInstance.Id), "NodeDown: {0}Commit Duration = {1} ms PLB Duration = {2} ms", node, commitDuration, plbElapsedTime); if (isNewEntry) { nodeCount_--; } if (lockedNodeInfo->IsUp) { uint64 oldUpCount = upCount_--; if (!fm_.IsMaster && oldUpCount <= FailoverConfig::GetConfig().ClusterPauseThreshold) { fm_.Events.ClusterInPauseState(oldUpCount - 1); } } lockedNodeInfo.Commit(move(node)); } else if (isNewEntry) { AcquireWriteLock lock(lock_); lockedNodeInfo.IsDeleted = true; nodes_.erase(nodeInstance.Id); } if (error.IsSuccess()) { error = fm_.ServiceCacheObj.RemoveFromDisabledNodes(0, nodeInstance.Id); if (fm_.IsReady) { fm_.BackgroundManagerObj.ScheduleRun(); } } if (!error.IsSuccess()) { fm_.WriteWarning( Constants::NodeSource, wformatString(nodeInstance.Id), "Node down for node {0} failed with {1}", nodeInstance, error); } return error; } AsyncOperationSPtr NodeCache::BeginNodeStateRemoved( NodeId const& nodeId, AsyncCallback const& callback, AsyncOperationSPtr const& state) { LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeId, lockedNodeInfo); ASSERT_IF( error.IsError(ErrorCodeValue::NodeNotFound), "{0} not found for NodeStateRemoved.", nodeId); if (!error.IsSuccess()) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(error, callback, state); } if (lockedNodeInfo->IsNodeStateRemoved) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(callback, state); } NodeInfoSPtr newNode = make_shared<NodeInfo>(*lockedNodeInfo); newNode->IsNodeStateRemoved = true; if (!fm_.IsMaster) { newNode->HealthSequence = InterlockedIncrement64(&healthSequence_) - 1; } auto newNodePtr = newNode.get(); pair<LockedNodeInfo, NodeInfoSPtr> context(move(lockedNodeInfo), newNode); return fm_.Store.BeginUpdateData( *newNodePtr, OperationContextCallback<pair<LockedNodeInfo, NodeInfoSPtr>>(callback, move(context)), state); } ErrorCode NodeCache::EndNodeStateRemoved(AsyncOperationSPtr const& operation) { auto context = operation->PopOperationContext<pair<LockedNodeInfo, NodeInfoSPtr>>(); if (context) { LockedNodeInfo & lockedNodeInfo = context->Context.first; NodeInfoSPtr & newNode = context->Context.second; int64 commitDuration(0); ErrorCode error = fm_.Store.EndUpdateData(*newNode, operation, commitDuration); ReportHealthAfterNodeUpdate(newNode, error); if (error.IsSuccess()) { wstring upgradeDomain = newNode->ActualUpgradeDomainId; if (!fm_.IsMaster) { fm_.NodeEvents.NodeStateRemoved(newNode->IdString, newNode->NodeInstance.InstanceId); } fm_.WriteInfo(Constants::NodeUpdateSource, newNode->IdString, "NodeStateRemoved: {0}Commit Duration = {1} ms", *newNode, commitDuration); lockedNodeInfo.Commit(move(newNode)); // Update the set of upgrade domains RemoveUpgradeDomain(upgradeDomain); } return error; } return CompletedAsyncOperation::End(operation); } UpgradeDomainsCSPtr NodeCache::GetUpgradeDomains(UpgradeDomainSortPolicy::Enum sortPolicy) { { AcquireReadLock lock(lock_); auto it = upgradeDomains_.find(sortPolicy); if (it != upgradeDomains_.end()) { return it->second; } } AcquireWriteLock lock(lock_); auto it = upgradeDomains_.find(sortPolicy); if (it == upgradeDomains_.end()) { UpgradeDomains const& upgradeDomains = *(upgradeDomains_.begin()->second); UpgradeDomainsSPtr newUpgradeDomains = make_shared<UpgradeDomains>(upgradeDomains, sortPolicy); upgradeDomains_[sortPolicy] = move(newUpgradeDomains); return upgradeDomains_[sortPolicy]; } else { return it->second; } } void NodeCache::AddUpgradeDomain(NodeInfo const& nodeInfo) { if (nodeInfo.IsUnknown || nodeInfo.IsNodeStateRemoved) { return; } AcquireWriteLock grab(lock_); if (upgradeDomains_.empty()) { UpgradeDomainSortPolicy::Enum sortPolicy = (FailoverConfig::GetConfig().SortUpgradeDomainNamesAsNumbers ? UpgradeDomainSortPolicy::DigitsAsNumbers : UpgradeDomainSortPolicy::Lexicographical); UpgradeDomainsSPtr upgradeDomains = make_shared<UpgradeDomains>(sortPolicy); upgradeDomains->AddUpgradeDomain(nodeInfo.ActualUpgradeDomainId); upgradeDomains_[sortPolicy] = move(upgradeDomains); return; } for (auto it = upgradeDomains_.begin(); it != upgradeDomains_.end(); it++) { UpgradeDomains & upgradeDomains = *(it->second); if (!upgradeDomains.Exists(nodeInfo.ActualUpgradeDomainId)) { UpgradeDomainsSPtr newUpgradeDomains = make_shared<UpgradeDomains>(upgradeDomains); newUpgradeDomains->AddUpgradeDomain(nodeInfo.ActualUpgradeDomainId); upgradeDomains.IsStale = true; it->second = move(newUpgradeDomains); } } } void NodeCache::RemoveUpgradeDomain(wstring const& upgradeDomain) { AcquireWriteLock grab(lock_); for (auto const& node : nodes_) { NodeInfoSPtr const& n = node.second->Get(); if (!n->IsNodeStateRemoved && n->ActualUpgradeDomainId == upgradeDomain) { return; } } for (auto it = upgradeDomains_.begin(); it != upgradeDomains_.end(); it++) { UpgradeDomains & upgradeDomains = *(it->second); if (upgradeDomains.Exists(upgradeDomain)) { UpgradeDomainsSPtr newUpgradeDomains = make_shared<UpgradeDomains>(upgradeDomains); newUpgradeDomains->RemoveUpgradeDomain(upgradeDomain); upgradeDomains.IsStale = true; it->second = move(newUpgradeDomains); } } } bool NodeCache::IsNodeUp(NodeInstance const& nodeInstance) const { AcquireReadLock grab(lock_); auto it = nodes_.find(nodeInstance.Id); if (it != nodes_.end()) { NodeInfoSPtr const& nodeInfo = it->second->Get(); return (nodeInfo->NodeInstance == nodeInstance && nodeInfo->IsUp); } return false; } void NodeCache::ReportHealthAfterNodeUpdate(NodeInfoSPtr const & nodeInfo, ErrorCode error, bool isUpgrade) { if (fm_.IsMaster) { return; } if (error.IsSuccess()) { auto e1 = fm_.HealthClient->AddHealthReport(fm_.HealthReportFactoryObj.GenerateNodeInfoHealthReport(nodeInfo, isUpgrade)); fm_.WriteInfo(Constants::NodeSource, wformatString(nodeInfo->Id), "AddHealthReport for node {0} completed with {1}", nodeInfo->Id, e1); } else { fm_.HealthClient->HealthSkipSequence(*ServiceModel::Constants::HealthReportFMSource, FABRIC_HEALTH_REPORT_KIND_NODE, nodeInfo->HealthSequence); } } void NodeCache::ReportHealthForNodeDeactivation(NodeInfoSPtr const & nodeInfo, ErrorCode error, bool isDeactivationComplete) { if (error.IsSuccess()) { auto e1 = fm_.HealthClient->AddHealthReport(fm_.HealthReportFactoryObj.GenerateNodeDeactivationHealthReport(nodeInfo, isDeactivationComplete)); fm_.WriteInfo( Constants::NodeSource, wformatString(nodeInfo->Id), "AddHealthReport for node {0} completed with {1}", nodeInfo->Id, e1); } else { fm_.HealthClient->HealthSkipSequence( *ServiceModel::Constants::HealthReportFMSource, FABRIC_HEALTH_REPORT_KIND_NODE, nodeInfo->HealthSequence); } } ErrorCode NodeCache::SetPendingDeactivateNode(NodeInstance const& nodeInstance, bool value) { LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeInstance.Id, lockedNodeInfo); ASSERT_IF(error.IsError(ErrorCodeValue::NodeNotFound), "{0} not found for SetPendingDeactivateNode", nodeInstance); if (!error.IsSuccess()) { return error; } if (lockedNodeInfo->NodeInstance.InstanceId > nodeInstance.InstanceId) { return ErrorCodeValue::StaleRequest; } ASSERT_IF( lockedNodeInfo->NodeInstance.InstanceId != nodeInstance.InstanceId, "{0} not match {1} for SetPendingDeactivateNode", nodeInstance, *lockedNodeInfo); if (lockedNodeInfo->IsPendingDeactivateNode == value) { return ErrorCodeValue::Success; } NodeInfoSPtr newNode = make_shared<NodeInfo>(*lockedNodeInfo); newNode->IsPendingDeactivateNode = value; int64 commitDuration; error = fm_.Store.UpdateData(*newNode, commitDuration); if (error.IsSuccess()) { fm_.WriteInfo(Constants::NodeUpdateSource, wformatString(nodeInstance.Id), "NodeInfo updated: {0}Commit Duration = {1} ms", *newNode, commitDuration); lockedNodeInfo.Commit(move(newNode)); } return error; } AsyncOperationSPtr NodeCache::BeginSetPendingFabricUpgrade( NodeInfo const& nodeInfo, bool value, AsyncCallback const& callback, AsyncOperationSPtr const& state) { if (nodeInfo.IsPendingFabricUpgrade == value) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(callback, state); } LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeInfo.Id, lockedNodeInfo); ASSERT_IF(error.IsError(ErrorCodeValue::NodeNotFound), "Node not found for SetPendingFabricUpgrade {0}: ", nodeInfo); if (!error.IsSuccess()) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(error, callback, state); } if (lockedNodeInfo->NodeInstance.InstanceId > nodeInfo.NodeInstance.InstanceId) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(ErrorCodeValue::StaleRequest, callback, state); } ASSERT_IF( lockedNodeInfo->NodeInstance.InstanceId != nodeInfo.NodeInstance.InstanceId, "{0} not match {1} for SetPendingFabricUpgrade", nodeInfo.NodeInstance.InstanceId, *lockedNodeInfo); if (lockedNodeInfo->IsPendingFabricUpgrade == value) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(callback, state); } NodeInfoSPtr newNodeInfo = make_shared<NodeInfo>(*lockedNodeInfo); newNodeInfo->IsPendingFabricUpgrade = value; auto newNodeInfoPtr = newNodeInfo.get(); return fm_.Store.BeginUpdateData( *newNodeInfoPtr, OperationContextCallback<pair<NodeInfoSPtr, LockedNodeInfo>>(callback, move(make_pair(move(newNodeInfo), move(lockedNodeInfo)))), state); } ErrorCode NodeCache::EndSetPendingFabricUpgrade(AsyncOperationSPtr const& operation) { unique_ptr<OperationContext<pair<NodeInfoSPtr, LockedNodeInfo>>> context = operation->PopOperationContext<pair<NodeInfoSPtr, LockedNodeInfo>>(); if (context) { NodeInfoSPtr & newNodeInfo = context->Context.first; LockedNodeInfo & lockedNodeInfo = context->Context.second; int64 commitDuration; ErrorCode error = fm_.Store.EndUpdateData(*newNodeInfo, operation, commitDuration); if (error.IsSuccess()) { fm_.WriteInfo( Constants::NodeUpdateSource, newNodeInfo->IdString, "NodeInfo updated: {0}Commit Duration = {1} ms", *newNodeInfo, commitDuration); lockedNodeInfo.Commit(move(newNodeInfo)); } return error; } return CompletedAsyncOperation::End(operation); } AsyncOperationSPtr NodeCache::BeginAddPendingApplicationUpgrade( NodeInfo const& nodeInfo, ServiceModel::ApplicationIdentifier const& applicationId, AsyncCallback const& callback, AsyncOperationSPtr const& state) { if (nodeInfo.IsPendingApplicationUpgrade(applicationId)) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(callback, state); } LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeInfo.Id, lockedNodeInfo); ASSERT_IF(error.IsError(ErrorCodeValue::NodeNotFound), "Node not found for AddPendingApplicationUpgrade: {0}", nodeInfo); if (!error.IsSuccess()) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(error, callback, state); } if (lockedNodeInfo->NodeInstance.InstanceId > nodeInfo.NodeInstance.InstanceId) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(ErrorCodeValue::StaleRequest, callback, state); } ASSERT_IF( lockedNodeInfo->NodeInstance.InstanceId != nodeInfo.NodeInstance.InstanceId, "{0} not match {1} for AddPendingApplicationUpgrade", nodeInfo.NodeInstance.InstanceId, *lockedNodeInfo); if (lockedNodeInfo->IsPendingApplicationUpgrade(applicationId)) { return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(callback, state); } NodeInfoSPtr newNodeInfo = make_shared<NodeInfo>(*lockedNodeInfo); newNodeInfo->AddPendingApplicationUpgrade(applicationId); auto newNodeInfoPtr = newNodeInfo.get(); return fm_.Store.BeginUpdateData( *newNodeInfoPtr, OperationContextCallback<pair<NodeInfoSPtr, LockedNodeInfo>>(callback, move(make_pair(move(newNodeInfo), move(lockedNodeInfo)))), state); } ErrorCode NodeCache::EndAddPendingApplicationUpgrade(AsyncOperationSPtr const& operation) { unique_ptr<OperationContext<pair<NodeInfoSPtr, LockedNodeInfo>>> context = operation->PopOperationContext<pair<NodeInfoSPtr, LockedNodeInfo>>(); if (context) { NodeInfoSPtr & newNodeInfo = context->Context.first; LockedNodeInfo & lockedNodeInfo = context->Context.second; int64 commitDuration; ErrorCode error = fm_.Store.EndUpdateData(*newNodeInfo, operation, commitDuration); if (error.IsSuccess()) { fm_.WriteInfo( Constants::NodeUpdateSource, newNodeInfo->IdString, "NodeInfo updated: {0}Commit Duration = {1} ms", *newNodeInfo, commitDuration); lockedNodeInfo.Commit(move(newNodeInfo)); } return error; } return CompletedAsyncOperation::End(operation); } ErrorCode NodeCache::RemovePendingApplicationUpgrade(NodeInstance const& nodeInstance, ServiceModel::ApplicationIdentifier const& applicationId) { LockedNodeInfo lockedNodeInfo; ErrorCode error = GetLockedNode(nodeInstance.Id, lockedNodeInfo); ASSERT_IF(error.IsError(ErrorCodeValue::NodeNotFound), "{0} not found for RemovePendingApplicationUpgrade", nodeInstance); if (!error.IsSuccess()) { return error; } if (lockedNodeInfo->NodeInstance.InstanceId > nodeInstance.InstanceId) { return ErrorCodeValue::StaleRequest; } ASSERT_IF( lockedNodeInfo->NodeInstance.InstanceId != nodeInstance.InstanceId, "{0} not match {1} for RemovePendingApplicationUpgrade", nodeInstance, *lockedNodeInfo); if (!lockedNodeInfo->IsPendingApplicationUpgrade(applicationId)) { return ErrorCodeValue::Success; } NodeInfoSPtr newNode = make_shared<NodeInfo>(*lockedNodeInfo); newNode->RemovePendingApplicationUpgrade(applicationId); int64 commitDuration; error = fm_.Store.UpdateData(*newNode, commitDuration); if (error.IsSuccess()) { fm_.WriteInfo(Constants::NodeUpdateSource, wformatString(nodeInstance.Id), "NodeInfo updated: {0}Commit Duration = {1} ms", *newNode, commitDuration); lockedNodeInfo.Commit(move(newNode)); } return error; } void NodeCache::ProcessNodes(NodePeriodicTaskCounts & taskCounts) { vector<LockedNodeInfo> nodesToRemove; // Tracing vector<NodeInstance> upNodes; NodeCounts counts; counts.NodeCount = nodes_.size(); // Health reporting DateTime upgradeStartTime; bool shouldReportFabricUpgradeHealth = !fm_.IsMaster && fm_.FabricUpgradeManager.GetUpgradeStartTime(upgradeStartTime); vector<CacheEntrySPtr> nodesToReportFabricUpgradeHealth; vector<CacheEntrySPtr> nodesToReportDeactivationStuck; vector<CacheEntrySPtr> nodesToReportDeactivationComplete; { AcquireReadLock grab(lock_); for (auto it = nodes_.begin(); it != nodes_.end(); ++it) { NodeInfoSPtr nodeInfo = it->second->Get(); ProcessNodeForCleanup( taskCounts, nodeInfo, it->second, nodesToRemove); ProcessNodeForActivation(nodeInfo); ProcessNodeForCounts(nodeInfo, counts, upNodes); if (healthInitialized_) { ProcessNodeForHealthReporting( nodeInfo, it->second, shouldReportFabricUpgradeHealth, upgradeStartTime, nodesToReportFabricUpgradeHealth, nodesToReportDeactivationStuck, nodesToReportDeactivationComplete); } } } RemoveNodesAsync(taskCounts, nodesToRemove); TraceNodeCounts(counts, upNodes); if (healthInitialized_) { ReportHealthForNodes( taskCounts, shouldReportFabricUpgradeHealth, nodesToReportFabricUpgradeHealth, nodesToReportDeactivationStuck, nodesToReportDeactivationComplete); } } void NodeCache::ProcessNodeForCleanup( NodePeriodicTaskCounts & taskCounts, NodeInfoSPtr const& nodeInfo, CacheEntrySPtr const& cacheEntry, vector<LockedNodeInfo> & nodesToRemove) const { bool isDeleteNeeded = (nodeInfo->IsUnknown && DateTime::Now() - nodeInfo->LastUpdated >= FailoverConfig::GetConfig().UnknownNodeKeepDuration); isDeleteNeeded |= (nodeInfo->IsNodeStateRemoved && DateTime::Now() - nodeInfo->LastUpdated >= FailoverConfig::GetConfig().RemovedNodeKeepDuration); if (isDeleteNeeded && nodeInfo->HealthSequence + 1 < ackedSequence_) { LockedNodeInfo lockedNodeInfo; ErrorCode error = cacheEntry->Lock(cacheEntry, lockedNodeInfo, TimeSpan::Zero); if (error.IsSuccess() && lockedNodeInfo->OperationLSN == nodeInfo->OperationLSN) { ASSERT_IF(nodeInfo->IsUp, "An unknown/removed node should be down: {0}", *lockedNodeInfo); nodesToRemove.push_back(move(lockedNodeInfo)); taskCounts.NodesToRemove++; } } } void NodeCache::ProcessNodeForActivation(NodeInfoSPtr const& nodeInfo) const { if (nodeInfo->IsUp && nodeInfo->DeactivationInfo.IsActivationInProgress) { ASSERT_IF(nodeInfo->DeactivationInfo.IsDeactivated, "A node cannot be in a deactivated state while activation is in progress: {0}", *nodeInfo); // Send NodeActivateRequest message to RA NodeActivateRequestMessageBody body(nodeInfo->DeactivationInfo.SequenceNumber, fm_.IsMaster); Transport::MessageUPtr request = RSMessage::GetNodeActivateRequest().CreateMessage(move(body)); GenerationHeader header(fm_.Generation, fm_.IsMaster); request->Headers.Add(header); fm_.SendToNodeAsync(move(request), nodeInfo->NodeInstance); } } void NodeCache::RemoveNodesAsync( NodePeriodicTaskCounts & taskCounts, vector<LockedNodeInfo> & nodesToRemove) { for (auto it = nodesToRemove.begin(); it != nodesToRemove.end(); ++it) { LockedNodeInfo & lockedNodeInfo = *it; lockedNodeInfo->PersistenceState = PersistenceState::ToBeDeleted; auto mover = MoveUPtr<LockedNodeInfo>(move(make_unique<LockedNodeInfo>(move(lockedNodeInfo)))); NodeInfo & nodeInfo = *mover->Get(); fm_.Store.BeginUpdateData( nodeInfo, [this, mover](AsyncOperationSPtr const& updateOperation) mutable { int64 commitDuration; ErrorCode error = fm_.Store.EndUpdateData(*mover->Get(), updateOperation, commitDuration); if (error.IsSuccess()) { RemoveNodeCommitJobItemUPtr commitJobItem = make_unique<RemoveNodeCommitJobItem>(move(*mover.TakeUPtr()), commitDuration); fm_.CommitQueue.Enqueue(move(commitJobItem)); } }, fm_.CreateAsyncOperationRoot()); taskCounts.NodesRemovesStarted++; } } void NodeCache::ProcessNodeForCounts( NodeInfoSPtr const& nodeInfo, NodeCounts & counts, vector<NodeInstance> & upNodes) const { if (nodeInfo->DeactivationInfo.IsDeactivated || nodeInfo->IsPendingUpgrade) { fm_.WriteInfo(Constants::NodeStateSource, wformatString(nodeInfo->Id), "{0}", *nodeInfo); } if (nodeInfo->IsUp) { counts.UpNodeCount++; if (fm_.BackgroundManagerObj.IsStateTraceEnabled) { upNodes.push_back(nodeInfo->NodeInstance); } } else { counts.DownNodeCount++; } if (nodeInfo->DeactivationInfo.IsDeactivated) { counts.DeactivatedCount++; if (nodeInfo->DeactivationInfo.Intent == NodeDeactivationIntent::Pause) { counts.PauseIntentCount++; } if (nodeInfo->DeactivationInfo.Intent == NodeDeactivationIntent::Restart) { counts.RestartIntentCount++; } if (nodeInfo->DeactivationInfo.Intent == NodeDeactivationIntent::RemoveData) { counts.RemoveDataIntentCount++; } if (nodeInfo->DeactivationInfo.Intent == NodeDeactivationIntent::RemoveNode) { counts.RemoveNodeIntentCount++; } } if (nodeInfo->IsUnknown) { counts.UnknownCount++; } if (nodeInfo->IsNodeStateRemoved) { counts.RemovedNodeCount++; } if (nodeInfo->IsPendingDeactivateNode) { counts.PendingDeactivateNode++; } if (nodeInfo->IsPendingFabricUpgrade) { counts.PendingFabricUpgrade++; } } void NodeCache::TraceNodeCounts( NodeCounts const& counts, vector<NodeInstance> const& upNodes) const { fm_.NodeEvents.NodeCounts(counts); if (fm_.BackgroundManagerObj.IsStateTraceEnabled) { int32 total = static_cast<int>(upNodes.size()); const int32 nodesPerRecord = 50; int32 first = 0; while (first < total) { int32 last = min(first + nodesPerRecord, total); string result; StringWriterA writer(result); int32 index = first; writer.Write(upNodes[index]); for (++index; index < last; ++index) { writer.Write(", "); writer.Write(upNodes[index]); } fm_.Events.Nodes(result, first + 1, last, total); first = last; } } } void NodeCache::ProcessNodeForHealthReporting( NodeInfoSPtr const& nodeInfo, CacheEntrySPtr const& cacheEntry, bool shouldReportFabricUpgradeHealth, DateTime const& upgradeStartTime, vector<CacheEntrySPtr> & nodesToReportFabricUpgradeHealth, vector<CacheEntrySPtr> & nodesToReportDeactivationStuck, vector<CacheEntrySPtr> & nodesToReportDeactivationComplete) const { if (shouldReportFabricUpgradeHealth && !nodeInfo->IsUp && !nodeInfo->IsNodeHealthReportedDuringUpgrade && nodeInfo->LastUpdated > upgradeStartTime && nodeInfo->LastUpdated + FailoverConfig::GetConfig().ExpectedNodeFabricUpgradeDuration < DateTime::Now()) { nodesToReportFabricUpgradeHealth.push_back(cacheEntry); } if (nodeInfo->IsNodeHealthReportedDuringDeactivate) { if (nodeInfo->DeactivationInfo.Status == NodeDeactivationStatus::None || nodeInfo->DeactivationInfo.Status == NodeDeactivationStatus::ActivationInProgress || nodeInfo->DeactivationInfo.Status == NodeDeactivationStatus::DeactivationComplete) { nodesToReportDeactivationComplete.push_back(cacheEntry); } } else { if (nodeInfo->DeactivationInfo.Status != NodeDeactivationStatus::None && nodeInfo->DeactivationInfo.Status != NodeDeactivationStatus::ActivationInProgress && nodeInfo->DeactivationInfo.Status != NodeDeactivationStatus::DeactivationComplete && nodeInfo->DeactivationInfo.StartTime + FailoverConfig::GetConfig().ExpectedNodeDeactivationDuration < DateTime::Now()) { nodesToReportDeactivationStuck.push_back(cacheEntry); } } } void NodeCache::ReportHealthForNodes( NodePeriodicTaskCounts & taskCounts, bool shouldReportFabricUpgradeHealth, vector<CacheEntrySPtr> & nodesToReportFabricUpgradeHealth, vector<CacheEntrySPtr> & nodesToReportDeactivationStuck, vector<CacheEntrySPtr> & nodesToReportDeactivationComplete) { if (shouldReportFabricUpgradeHealth) { for (auto it = nodesToReportFabricUpgradeHealth.begin(); it != nodesToReportFabricUpgradeHealth.end(); ++it) { LockedNodeInfo lockedNode; ErrorCode error = (*it)->Lock(*it, lockedNode, TimeSpan::Zero); if (error.IsSuccess() && !lockedNode->IsUp && !lockedNode->IsNodeHealthReportedDuringUpgrade) { NodeInfoSPtr node = make_shared<NodeInfo>(*lockedNode); node->HealthSequence = InterlockedIncrement64(&healthSequence_) - 1; node->IsNodeHealthReportedDuringUpgrade = true; node->PersistenceState = PersistenceState::ToBeUpdated; int64 commitDuration; error = fm_.Store.UpdateData(*node, commitDuration); ReportHealthAfterNodeUpdate(node, error, true); if (!error.IsSuccess()) { fm_.WriteWarning( Constants::NodeSource, node->IdString, "Health report during fabric upgrade for node {0} failed with {1}\r\nCommit Duration = {1} ms", node->Id, error, commitDuration); return; } fm_.WriteInfo(Constants::NodeUpdateSource, node->IdString, "Health reported during fabric upgrade: {0}Commit Duration = {1} ms", *node, commitDuration); taskCounts.UpgradeHealthReports++; lockedNode.Commit(move(node)); } } } // Health reporting for node deactivation for (auto it = nodesToReportDeactivationStuck.begin(); it != nodesToReportDeactivationStuck.end(); ++it) { ReportNodeDeactivationHealth(taskCounts, *it, false); } for (auto it = nodesToReportDeactivationComplete.begin(); it != nodesToReportDeactivationComplete.end(); ++it) { ReportNodeDeactivationHealth(taskCounts, *it, true); } } void NodeCache::ReportNodeDeactivationHealth( NodePeriodicTaskCounts & taskCounts, CacheEntrySPtr & cacheEntry, bool isDeactivationComplete) { LockedNodeInfo lockedNode; ErrorCode error = cacheEntry->Lock(cacheEntry, lockedNode, TimeSpan::Zero); if (error.IsSuccess()) { NodeInfoSPtr node = make_shared<NodeInfo>(*lockedNode); node->HealthSequence = InterlockedIncrement64(&healthSequence_) - 1; node->IsNodeHealthReportedDuringDeactivate = !isDeactivationComplete; node->PersistenceState = PersistenceState::ToBeUpdated; int64 commitDuration; error = fm_.Store.UpdateData(*node, commitDuration); ReportHealthForNodeDeactivation(node, error, isDeactivationComplete); if (!error.IsSuccess()) { fm_.WriteWarning( Constants::NodeSource, node->IdString, "Health report during deactivation for node {0} failed with {1}\r\nCommit Duration = {1} ms", node->Id, error, commitDuration); return; } fm_.WriteInfo( Constants::NodeUpdateSource, node->IdString, "Health reported during node deactivation: {0}Commit Duration = {1} ms", *node, commitDuration); if (isDeactivationComplete) { taskCounts.DeactivationCompleteHealthReports++; } else { taskCounts.DeactivationStuckHealthReports++; } lockedNode.Commit(move(node)); } } void NodeCache::FinishRemoveNode(LockedNodeInfo & lockedNodeInfo, int64 commitDuration) { AcquireWriteLock grab(lock_); lockedNodeInfo.IsDeleted = true; nodes_.erase(lockedNodeInfo->Id); nodeCount_--; fm_.WriteInfo(Constants::NodeUpdateSource, lockedNodeInfo->IdString, "Node removed: {0}\r\nCommit Duration = {1} ms", *lockedNodeInfo, commitDuration); } void NodeCache::WriteTo(TextWriter& writer, FormatOptions const&) const { for (auto const& pair : nodes_) { writer.Write("{0} ", *pair.second->Get()); } } ErrorCode NodeCache::GetLockedNode(NodeId const& nodeId, LockedNodeInfo & lockedNodeInfo) { bool isNewEntry = false; return GetLockedNode(nodeId, lockedNodeInfo, false, isNewEntry); } ErrorCode NodeCache::GetLockedNode( NodeId const& nodeId, LockedNodeInfo & lockedNodeInfo, bool createNewEntry, __out bool & isNewEntry) { isNewEntry = false; CacheEntrySPtr entry; { // No need to acquire write lock when the node already exists, or // when we are not adding a new node. AcquireReadLock grab(lock_); auto it = nodes_.find(nodeId); if (it != nodes_.end()) { entry = it->second; } else if (!createNewEntry) { return ErrorCodeValue::NodeNotFound; } } if (entry) { return entry->Lock(entry, lockedNodeInfo); } AcquireWriteLock grab(lock_); // We need to check again for the existence of the node because it may have been created by a different thread. auto it = nodes_.find(nodeId); if (it == nodes_.end()) { TESTASSERT_IFNOT(createNewEntry, "createNewEntry is not true"); NodeInfoSPtr nodeInfo = make_shared<NodeInfo>(NodeInstance(nodeId, 0), NodeDescription(nodeId), false, false, false, DateTime::Now()); CacheEntrySPtr entry1 = make_shared<CacheEntry<NodeInfo>>(move(nodeInfo)); it = nodes_.insert(make_pair(nodeId, move(entry1))).first; isNewEntry = true; } // We use timeout of zero trying to lock node entry under write lock. return it->second->Lock(it->second, lockedNodeInfo, TimeSpan::Zero); } void NodeCache::SortUpgradeDomains(UpgradeDomainSortPolicy::Enum sortPolicy, __inout std::vector<std::wstring> & upgradeDomains) { sort( upgradeDomains.begin(), upgradeDomains.end(), [sortPolicy](wstring const& upgradeDomain1, wstring const& upgradeDomain2) { return CompareUpgradeDomains(sortPolicy, upgradeDomain1, upgradeDomain2); }); } bool NodeCache::CompareUpgradeDomains(UpgradeDomainSortPolicy::Enum sortPolicy, wstring const& upgradeDomain1, wstring const& upgradeDomain2) { switch (sortPolicy) { case UpgradeDomainSortPolicy::DigitsAsNumbers: return (StringUtility::CompareDigitsAsNumbers(upgradeDomain1.c_str(), upgradeDomain2.c_str()) < 0); case UpgradeDomainSortPolicy::Lexicographical: return (upgradeDomain1 < upgradeDomain2); default: Assert::TestAssert("Unknown UpgradeDomainSortPolicy: {0}", static_cast<int>(sortPolicy)); return (upgradeDomain1 < upgradeDomain2); } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync_file_system/drive_backend/sync_task_token.h" #include "base/bind.h" #include "base/debug/trace_event.h" #include "chrome/browser/sync_file_system/drive_backend/sync_task_manager.h" #include "chrome/browser/sync_file_system/drive_backend/task_dependency_manager.h" namespace sync_file_system { namespace drive_backend { const int64 SyncTaskToken::kTestingTaskTokenID = -1; const int64 SyncTaskToken::kForegroundTaskTokenID = 0; const int64 SyncTaskToken::kMinimumBackgroundTaskTokenID = 1; // static scoped_ptr<SyncTaskToken> SyncTaskToken::CreateForTesting( const SyncStatusCallback& callback) { return make_scoped_ptr(new SyncTaskToken( base::WeakPtr<SyncTaskManager>(), kTestingTaskTokenID, scoped_ptr<BlockingFactor>(), callback)); } // static scoped_ptr<SyncTaskToken> SyncTaskToken::CreateForForegroundTask( const base::WeakPtr<SyncTaskManager>& manager) { return make_scoped_ptr(new SyncTaskToken( manager, kForegroundTaskTokenID, scoped_ptr<BlockingFactor>(), SyncStatusCallback())); } // static scoped_ptr<SyncTaskToken> SyncTaskToken::CreateForBackgroundTask( const base::WeakPtr<SyncTaskManager>& manager, int64 token_id, scoped_ptr<BlockingFactor> blocking_factor) { return make_scoped_ptr(new SyncTaskToken( manager, token_id, blocking_factor.Pass(), SyncStatusCallback())); } void SyncTaskToken::UpdateTask(const tracked_objects::Location& location, const SyncStatusCallback& callback) { DCHECK(callback_.is_null()); location_ = location; callback_ = callback; DVLOG(2) << "Token updated: " << location_.ToString(); } SyncTaskToken::~SyncTaskToken() { // All task on Client must hold TaskToken instance to ensure // no other tasks are running. Also, as soon as a task finishes to work, // it must return the token to TaskManager. // Destroying a token with valid |client| indicates the token was // dropped by a task without returning. if (manager_.get() && manager_->IsRunningTask(token_id_)) { NOTREACHED() << "Unexpected TaskToken deletion from: " << location_.ToString(); // Reinitializes the token. SyncTaskManager::NotifyTaskDone( make_scoped_ptr(new SyncTaskToken( manager_, token_id_, blocking_factor_.Pass(), SyncStatusCallback())), SYNC_STATUS_OK); } } // static SyncStatusCallback SyncTaskToken::WrapToCallback( scoped_ptr<SyncTaskToken> token) { return base::Bind(&SyncTaskManager::NotifyTaskDone, base::Passed(&token)); } void SyncTaskToken::set_blocking_factor( scoped_ptr<BlockingFactor> blocking_factor) { blocking_factor_ = blocking_factor.Pass(); } const BlockingFactor* SyncTaskToken::blocking_factor() const { return blocking_factor_.get(); } void SyncTaskToken::clear_blocking_factor() { blocking_factor_.reset(); } void SyncTaskToken::InitializeTaskLog(const std::string& task_description) { task_log_.reset(new TaskLogger::TaskLog); task_log_->start_time = base::TimeTicks::Now(); task_log_->task_description = task_description; TRACE_EVENT_ASYNC_BEGIN1( TRACE_DISABLED_BY_DEFAULT("SyncFileSystem"), "SyncTask", task_log_->log_id, "task_description", task_description); } void SyncTaskToken::FinalizeTaskLog(const std::string& result_description) { TRACE_EVENT_ASYNC_END1( TRACE_DISABLED_BY_DEFAULT("SyncFileSystem"), "SyncTask", task_log_->log_id, "result_description", result_description); DCHECK(task_log_); task_log_->result_description = result_description; task_log_->end_time = base::TimeTicks::Now(); } void SyncTaskToken::RecordLog(const std::string& message) { DCHECK(task_log_); task_log_->details.push_back(message); } void SyncTaskToken::SetTaskLog(scoped_ptr<TaskLogger::TaskLog> task_log) { task_log_ = task_log.Pass(); } scoped_ptr<TaskLogger::TaskLog> SyncTaskToken::PassTaskLog() { return task_log_.Pass(); } SyncTaskToken::SyncTaskToken(const base::WeakPtr<SyncTaskManager>& manager, int64 token_id, scoped_ptr<BlockingFactor> blocking_factor, const SyncStatusCallback& callback) : manager_(manager), token_id_(token_id), callback_(callback), blocking_factor_(blocking_factor.Pass()) { } } // namespace drive_backend } // namespace sync_file_system