text
stringlengths
1
1.05M
; 16-bit compare HL with register ; CMP16 DE == CMP HL, DE CMP16 macro &RP AND A ; Clear carry SBC HL, &RP ADD HL, &RP ; Set flags endm PUSHALL macro PUSH AF PUSH BC PUSH DE PUSH HL PUSH IX PUSH IY endm POPALL macro POP IY POP IX POP HL POP DE POP BC POP AF endm
sty $ff lda ({z1}),y ldy #0 clc adc ({z1}),y sta ({z1}),y ldy $ff iny lda ({z1}),y ldy #1 adc ({z1}),y sta ({z1}),y
; A253430: Number of (n+1) X (3+1) 0..1 arrays with every 2 X 2 subblock diagonal minus antidiagonal sum nondecreasing horizontally, vertically and ne-to-sw antidiagonally. ; 69,70,85,121,193,337,625,1201,2353,4657,9265,18481,36913,73777,147505,294961,589873,1179697,2359345,4718641,9437233,18874417,37748785,75497521,150994993,301989937,603979825,1207959601,2415919153,4831838257,9663676465,19327352881,38654705713,77309411377,154618822705,309237645361,618475290673,1236950581297,2473901162545,4947802325041,9895604650033,19791209300017,39582418599985,79164837199921,158329674399793,316659348799537,633318697599025,1266637395198001,2533274790395953,5066549580791857 lpb $0 sub $0,1 add $2,3 mov $1,$2 mul $2,2 lpe trn $1,6 add $2,2 add $1,$2 trn $1,7 add $1,69
// SPDX-License-Identifier: Apache-2.0 // ---------------------------------------------------------------------------- // Copyright 2011-2020 Arm Limited // // 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 "astcenc_mathlib.h" /* Public function, see header file for detailed documentation */ float astc::log2(float val) { if32 p; p.f = val; if (p.s < 0x800000) p.s = 0x800000; // negative, 0, denormal get clamped to non-denormal. // normalize mantissa to range [0.66, 1.33] and extract an exponent // in such a way that 1.0 returns 0. p.s -= 0x3f2aaaab; int expo = p.s >> 23; p.s &= 0x7fffff; p.s += 0x3f2aaaab; float x = p.f - 1.0f; // taylor polynomial that, with horner's-rule style evaluation, // gives sufficient precision for our use // (relative error of about 1 in 10^6) float res = (float)expo + x * ( 1.442695040888963f + x * (-0.721347520444482f + x * ( 0.480898346962988f + x * (-0.360673760222241f + x * ( 0.288539008177793f + x * (-0.240449173481494f + x * ( 0.206099291555566f + x * (-0.180336880111120f + x * ( 0.160299448987663f ))))))))); return res; } /** * @brief 64-bit rotate left. * * @param val The value to rotate. * @param count The rotation, in bits. */ static inline uint64_t rotl(uint64_t val, int count) { return (val << count) | (val >> (64 - count)); } /* Public function, see header file for detailed documentation */ void astc::rand_init(uint64_t state[2]) { state[0] = 0xfaf9e171cea1ec6bULL; state[1] = 0xf1b318cc06af5d71ULL; } /* Public function, see header file for detailed documentation */ uint64_t astc::rand(uint64_t state[2]) { uint64_t s0 = state[0]; uint64_t s1 = state[1]; uint64_t res = s0 + s1; s1 ^= s0; state[0] = rotl(s0, 24) ^ s1 ^ (s1 << 16); state[1] = rotl(s1, 37); return res; }
#include <iostream> #include <algorithm> #include <map> #include <vector> #include <tuple> using namespace std; int main() { int N, k, gallery; cin >> N >> k; map<pair<int, int>, pair<bool, int>> art_gallery; vector<tuple<int, int, int>> galleries; for(int i = 0; i < 2; i++) { for(int j = 0; j < N; j++) { cin >> gallery; art_gallery[make_pair(i, j)] = make_pair(false, gallery); galleries.insert(make_tuple(gallery, i, j)); } } sort(galleries.begin(), galleries.end()); for(tuple<int, int, int> g: galleries) { x = get<1>(g), y = get<2>(g); if(y == 1) { if(art_gallery[make_pair(x-1,y-1)].first == false) } } }
/* file: regression_training_input.cpp */ /******************************************************************************* * Copyright 2014-2017 Intel Corporation * All Rights Reserved. * * If this software was obtained under the Intel Simplified Software License, * the following terms apply: * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license under * any patent, copyright or other intellectual property rights in the Material * is granted to or conferred upon you, either expressly, by implication, * inducement, estoppel or otherwise. Any license under such intellectual * property rights must be express and approved by Intel in writing. * * Unless otherwise agreed by Intel in writing, you may not remove or alter this * notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. * * * If this software was obtained under the Apache License, Version 2.0 (the * "License"), the following terms apply: * * 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. *******************************************************************************/ /* //++ // Implementation of the class defining the input objects // of the regression training algorithm //-- */ #include "algorithms/regression/regression_training_types.h" #include "daal_strings.h" namespace daal { namespace algorithms { namespace regression { namespace training { namespace interface1 { using namespace daal::data_management; using namespace daal::services; Input::Input(size_t nElements) : daal::algorithms::Input(nElements) {} Input::Input(const Input& other) : daal::algorithms::Input(other) {} data_management::NumericTablePtr Input::get(InputId id) const { return NumericTable::cast(Argument::get(id)); } void Input::set(InputId id, const data_management::NumericTablePtr &value) { Argument::set(id, value); } Status Input::check(const daal::algorithms::Parameter *par, int method) const { const NumericTablePtr dataTable = get(data); const NumericTablePtr dependentVariableTable = get(dependentVariables); Status s; DAAL_CHECK_STATUS(s, checkNumericTable(dataTable.get(), dataStr())); size_t nRowsInData = dataTable->getNumberOfRows(); return checkNumericTable(dependentVariableTable.get(), dependentVariableStr(), 0, 0, 0, nRowsInData); } } } } } }
//================================================================================================= /*! // \file src/mathtest/operations/dmatsmatkron/HDaMIa.cpp // \brief Source file for the HDaMIa dense matrix/sparse matrix Kronecker product math test // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/IdentityMatrix.h> #include <blaze/math/HermitianMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/operations/dmatsmatkron/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'HDaMIa'..." << std::endl; using blazetest::mathtest::TypeA; try { // Matrix type definitions using HDa = blaze::HermitianMatrix< blaze::DynamicMatrix<TypeA> >; using MIa = blaze::IdentityMatrix<TypeA>; // Creator type definitions using CHDa = blazetest::Creator<HDa>; using CMIa = blazetest::Creator<MIa>; // Running tests with small matrices for( size_t i=0UL; i<=4UL; ++i ) { for( size_t j=0UL; j<=4UL; ++j ) { RUN_DMATSMATKRON_OPERATION_TEST( CHDa( i ), CMIa( j ) ); } } // Running tests with large matrices RUN_DMATSMATKRON_OPERATION_TEST( CHDa( 9UL ), CMIa( 8UL ) ); RUN_DMATSMATKRON_OPERATION_TEST( CHDa( 16UL ), CMIa( 15UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix Kronecker product:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
#ifndef BOOST_MPL_MAP_AUX_ERASE_IMPL_HPP_INCLUDED #define BOOST_MPL_MAP_AUX_ERASE_IMPL_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2003-2004 // Copyright David Abrahams 2003-2004 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Id: erase_impl.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $ // $Revision: 49267 $ #include <boost/mpl/erase_fwd.hpp> #include <boost/mpl/map/aux_/erase_key_impl.hpp> #include <boost/mpl/map/aux_/tag.hpp> namespace boost { namespace mpl { template<> struct erase_impl< aux::map_tag > { template< typename Map , typename Pos , typename unused_ > struct apply : erase_key_impl<aux::map_tag> ::apply<Map,typename Pos::type::first> { }; }; }} #endif // BOOST_MPL_MAP_AUX_ERASE_IMPL_HPP_INCLUDED
COMMENT }%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Berkeley Softworks 1990 -- All Rights Reserved PROJECT: PC GEOS MODULE: Diablo Daisy Wheel printer driver FILE: diabloManager.asm AUTHOR: Dave Durran REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 2/90 initial version Dave 3/90 added 24-pin print resources. Dave 5/92 Initial 2.0 version DESCRIPTION: This file contains the source for the Diablo Daisy Wheel printer driver $Id: diabloManager.asm,v 1.1 97/04/18 11:56:31 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%} ;-------------------------------------- ; Include files ;-------------------------------------- include printcomInclude.def ;------------------------------------------------------------------------------ ; Constants and Macros ;------------------------------------------------------------------------------ include printcomConstant.def include diabloConstant.def include printcomMacro.def include diablo.rdef ;------------------------------------------------------------------------------ ; Driver Info Table ;------------------------------------------------------------------------------ idata segment ; MODULE_FIXED DriverTable DriverExtendedInfoStruct \ < <Entry:DriverStrategy, ; DIS_strategy mask DA_HAS_EXTENDED_INFO, ; DIS_driverAttributes DRIVER_TYPE_PRINTER >, ; DIS_driverType handle DriverInfo ; DEIS_resource > public DriverTable idata ends ;------------------------------------------------------------------------------ ; Entry Code ;------------------------------------------------------------------------------ Entry segment resource ; MODULE_FIXED include printcomEntry.asm ; entry point, misc bookeeping routines include printcomInfo.asm ; various info getting/setting routines include printcomAdmin.asm ; misc init routines include printcomTables.asm ; module jump table for driver calls include printcomNoEscapes.asm ; module jump table for driver escape calls Entry ends ;------------------------------------------------------------------------------ ; Driver code ;------------------------------------------------------------------------------ CommonCode segment resource ; MODULE_STANDARD include printcomEpsonJob.asm ; StartJob/EndJob/SetPaperpath routines include printcomDotMatrixPage.asm ; code to implement Page routines include printcomHex0Stream.asm ; code to talk with the stream driver ;include printcomDotMatrixBuffer.asm ; code to deal with graphic print buffers include printcomNoColor.asm ; code to implement Color routines include printcomNoGraphics.asm ; common dummy graphics routines include printcomDumbCursor.asm ; code to implement Cursor routines include diabloStyles.asm ; code to implement Style setting routines include diabloText.asm ; common code to implement text routines include diabloDialog.asm ; code to implement UI setting include diabloControlCodes.asm ; Escape and control codes CommonCode ends ;------------------------------------------------------------------------------ ; Device Info Resources (each in their own resource) ;------------------------------------------------------------------------------ include diabloDriverInfo.asm ; overall driver info include diablo630Info.asm ; specific info for p321 printer end
//scaling.cpp #include <Rcpp.h> #include <algorithm> // std::set_intersection, std::sort #include <math.h> #include <cmath> #include <vector> // std::vector #include <valarray> #include <numeric> using namespace Rcpp; struct logt { double operator() (double d) const { return std::log10(d); } }; // [[Rcpp::export]] List rcpp_scale(NumericMatrix x,List neighbors, int coleng){ List scf = List::create(); for (int i = 0; i < coleng; i++){ NumericVector nodescf=NumericVector::create(); NumericVector tmp=neighbors[i]; for(int j = 0; j<tmp.length(); j++){ NumericVector obs=x( _ , (tmp[j]-1) ); NumericVector ref=x(_, i); //std::valarray<double> obs(ref,ref.size()); std::vector<double> obs_v=as<std::vector<double> >(obs); std::vector<double> ref_v=as<std::vector<double> >(ref); double nO = sum(obs); double nR = sum(ref); std::vector<double>::iterator itr_o; std::vector<double>::iterator itr_r; std::vector<int> o_zero; itr_o=std::find(obs_v.begin(),obs_v.end(),0); while (itr_o != obs_v.cend()) { // Do something with iter o_zero.push_back(std::distance(obs_v.begin(), itr_o)); itr_o++; itr_o = std::find(itr_o, obs_v.end(), 0); } std::vector<int> r_zero; itr_r=std::find(ref_v.begin(),ref_v.end(),0); while (itr_r != ref_v.cend()) { // Do something with iter r_zero.push_back(std::distance(ref_v.begin(), itr_r)); itr_r++; itr_r = std::find(itr_r, ref_v.end(), 0); } std::vector<int> all_zero(o_zero.size()+r_zero.size()); std::vector<int>::iterator it; it=std::set_union (o_zero.begin(), o_zero.end(), r_zero.begin(), r_zero.end(), all_zero.begin()); all_zero.resize(it-all_zero.begin()); // 0부터 n까지 sequential vector를 만들어요. std::vector<int> all(obs_v.size()); std::iota(all.begin(), all.end(), 0); // sequential vector에서 0 index를 제거한 vector를 만들어요. test해봤는데 이렇게하는게 zeroindex가지고 for문 돌리는것보다 빠르거나 별차이안나더라고요. std::vector<int> not_all_zero(obs_v.size()-all_zero.size()); std::set_difference(all.begin(), all.end(), all_zero.begin(), all_zero.end(), not_all_zero.begin()); //nonzeroindex에 해당하는 vector element를 tmp vector에 하나씩 집어넣고 swap해서 원래 vector에 넣어줘요. std::vector<double> tmp1; std::vector<double> tmp2; tmp1.reserve(not_all_zero.size()); tmp2.reserve(not_all_zero.size()); for (int i=0; i<not_all_zero.size(); ++i) { tmp1.push_back(obs_v[not_all_zero[i]]); tmp2.push_back(ref_v[not_all_zero[i]]); } obs_v.swap(tmp1); ref_v.swap(tmp2); // 얘도 느려요. // std::vector<double> tmp1; // std::vector<double> tmp2; // tmp1.reserve(obs_v.size() - all_zero.size()); // tmp2.reserve(ref_v.size() - all_zero.size()); // for (int i=0; i<obs_v.size(); ++i) { // if (std::find(all_zero.begin(),all_zero.end(),i)!=all_zero.cend()) { // tmp1.push_back(obs_v[i]); // tmp2.push_back(ref_v[i]); // } // } // obs_v.swap(tmp1); // ref_v.swap(tmp2); // // vector에서 zero index를 제거해줘요. 더느려요. // for(int i=0; i<all_zero.size();i++){ // obs_v.erase(obs_v.begin()+all_zero[i]-i); // ref_v.erase(ref_v.begin()+all_zero[i]-i); // } // vector에서 zero index를 제거하는 while문인데 더 오래걸려요. 여기서는 nonzero index나 zero index vector를 따로만들어주지는않아요. // while(check==0){ // itr_o=std::find(obs_v.begin(),obs_v.end(),0); // itr_r=std::find(ref_v.begin(),ref_v.end(),0); // // if(itr_o!=obs_v.cend()){ // obs_v.erase(obs_v.begin()+std::distance(obs_v.begin(), itr_o)); // ref_v.erase(ref_v.begin()+std::distance(obs_v.begin(), itr_o)); // }else if(itr_r!=ref_v.cend()){ // obs_v.erase(obs_v.begin()+std::distance(ref_v.begin(), itr_r)); // ref_v.erase(ref_v.begin()+std::distance(ref_v.begin(), itr_r)); // }else{ // check++; // } // }; std::vector<double> trsf(obs_v.size()); trsf.reserve(obs_v.size()); // std::cout<<obs_v[0]<<'\t'<<ref_v[0]<<'\t'; // 두 벡터를 서로 나누어줘요. std::transform(obs_v.begin(), obs_v.end(), ref_v.begin(), trsf.begin(), std::divides<double>()); // std::cout<<trsf[0]<<'\t'; // library size로 나누어줘요. std::transform(trsf.begin(), trsf.end(), trsf.begin(), std::bind(std::multiplies<double>(), std::placeholders::_1, nR/nO)); // std::cout<<trsf[0]<<'\t'; // logtransform을 해줘요. std::transform(trsf.begin(), trsf.end(), trsf.begin(), logt()); // std::cout<<trsf[0]<<'\n'; //mean을 r구하고 pow로 다시 조화평균값을 내줘요. double res_mean = std::accumulate(trsf.begin(), trsf.end(), 0.0)/trsf.size(); res_mean = pow(10,(res_mean/2)); nodescf.push_back(res_mean); // nodescf.push_back(nO); } scf.push_back(nodescf); } return(scf); } // // // [[Rcpp::export]] // List test2(NumericMatrix x,List neighbors, int coleng){ // List scf = List::create(); // for (int i = 0; i < coleng; i++){ // NumericVector nodescf=NumericVector::create(); // NumericVector tmp=neighbors[i]; // for(int j = 0; j<tmp.length(); j++){ // NumericVector obs=x( _ , (tmp[j]-1) ); // NumericVector ref=x(_, i); // //std::valarray<double> obs(ref,ref.size()); // std::vector<double> obs_v=as<std::vector<double> >(obs); // std::vector<double> ref_v=as<std::vector<double> >(ref); // double nO = sum(obs); // double nR = sum(ref); // // // std::vector<double>::iterator itr_o; // std::vector<double>::iterator itr_r; // // std::vector<int> o_zero; // itr_o=std::find(obs_v.begin(),obs_v.end(),0); // while (itr_o != obs_v.cend()) // { // // // Do something with iter // o_zero.push_back(std::distance(obs_v.begin(), itr_o)); // itr_o++; // itr_o = std::find(itr_o, obs_v.end(), 0); // } // // std::vector<int> r_zero; // itr_r=std::find(ref_v.begin(),ref_v.end(),0); // while (itr_r != ref_v.cend()) // { // // Do something with iter // r_zero.push_back(std::distance(ref_v.begin(), itr_r)); // itr_r++; // itr_r = std::find(itr_r, ref_v.end(), 0); // } // // std::vector<int> all_zero(o_zero.size()+r_zero.size()); // std::vector<int>::iterator it; // it=std::set_union (o_zero.begin(), o_zero.end(), r_zero.begin(), r_zero.end(), all_zero.begin()); // all_zero.resize(it-all_zero.begin()); // // // std::vector<int> all(obs_v.size()); // std::iota(all.begin(), all.end(), 0); // // std::vector<int> not_all_zero(obs_v.size()-all_zero.size()); // std::set_difference(all.begin(), all.end(), all_zero.begin(), all_zero.end(), not_all_zero.begin()); // // // std::vector<double> tmp1; // std::vector<double> tmp2; // tmp1.reserve(not_all_zero.size()); // tmp2.reserve(not_all_zero.size()); // for (int i=0; i<not_all_zero.size(); ++i) { // tmp1.push_back(obs_v[not_all_zero[i]]); // tmp2.push_back(ref_v[not_all_zero[i]]); // // } // obs_v.swap(tmp1); // ref_v.swap(tmp2); // // // // // // std::valarray<double> trsf(x.size()); // std::valarray<double> obs_a(obs_v.size()); // std::copy(begin(obs_v), end(obs_v), begin(obs_a)); // std::valarray<double> ref_a(ref_v.size()); // std::copy(begin(ref_v), end(ref_v), begin(ref_a)); // // trsf=std::log10(obs_a/ref_a*(nR/nO)); // // trsf=trsf*(nR/nO); // // trsf=std::log10(trsf); // double res_mean=trsf.sum()/obs_v.size(); // res_mean = pow(10,(res_mean/2)); // nodescf.push_back(res_mean); // // // // std::vector<double> trsf; // // trsf.reserve(obs_v.size()); // // // std::cout<<obs_v[0]<<'\t'<<ref_v[0]<<'\t'; // // std::transform(obs_v.begin(), obs_v.end(), ref_v.begin(), std::back_inserter( trsf ), std::divides<double>()); // // // std::cout<<trsf[0]<<'\t'; // // std::transform(trsf.begin(), trsf.end(), trsf.begin(), std::bind(std::multiplies<double>(), std::placeholders::_1, nR/nO)); // // // std::cout<<trsf[0]<<'\t'; // // std::transform(trsf.begin(), trsf.end(), trsf.begin(), logt()); // // // std::cout<<trsf[0]<<'\n'; // // // // // double res_mean = std::accumulate(trsf.begin(), trsf.end(), 0.0)/trsf.size(); // // // nodescf.push_back(nO); // } // scf.push_back(nodescf); // } // return(scf); // } // // // // // [[Rcpp::export]] // // std::vector<int> test2(std::vector<int> x) { // // std::vector<int> res; // // std::vector<int>::iterator iterO = std::find(x.begin(), x.end(), 0); // // while (iterO != x.cend()) // // { // // // // // Do something with iter // // res.push_back(std::distance(x.begin(), iterO)); // // iterO++; // // iterO = std::find(iterO, x.end(), 0); // // } // // return res; // // } // // // [[Rcpp::export]] // void test3(std::vector<double> x) { // std::valarray<double> v(x.size()); // std::copy(begin(x), end(x), begin(v)); // std::valarray<double> y(x.size()); // y=v+1.0; // std::valarray<double> z(x.size()); // z=y/v; // for(int i=0; i<x.size();i++){ // std::cout<<z[i]<<'\t'; // } // std::cout<<'\n'; // z=z*(3.0/2); // for(int i=0; i<x.size();i++){ // std::cout<<z[i]<<'\t'; // } // std::cout<<'\n'; // z=std::log10(z); // for(int i=0; i<x.size();i++){ // std::cout<<z[i]<<'\t'; // } // std::cout<<'\n'; // z=std::log10(y/v*(3.0/2)); // // z=std::log10(z); // for(int i=0; i<x.size();i++){ // std::cout<<z[i]<<'\t'; // } // double res_mean=z.sum()/x.size(); // std::cout<<'\n'<<res_mean<<'\n'; // } // // [[Rcpp::export]] // double test2(std::vector<double> x, std::vector<double> y){ // int check=0; // std::vector<double>::iterator itr_x; // std::vector<double>::iterator itr_y; // while(check==0){ // itr_x=std::find(x.begin(),x.end(),0); // itr_y=std::find(y.begin(),y.end(),0); // // if(itr_x!=x.cend()){ // x.erase(x.begin()+std::distance(x.begin(), itr_x)); // y.erase(y.begin()+std::distance(x.begin(), itr_x)); // }else if(itr_y!=y.cend()){ // x.erase(x.begin()+std::distance(y.begin(), itr_y)); // y.erase(y.begin()+std::distance(y.begin(), itr_y)); // }else{ // check++; // } // }; // // std::vector<double> dv; // dv.reserve(x.size()); // std::transform(x.begin(), x.end(), y.begin(), std::back_inserter(dv), std::divides<double>()); // std::transform(dv.begin(), dv.end(), dv.begin(), std::bind(std::multiplies<double>(), std::placeholders::_1, 3)); // std::transform(dv.begin(), dv.end(), dv.begin(), logt()); // double res_mean = std::accumulate(dv.begin(), dv.end(), 0.0)/dv.size(); // return(sqrt(pow(10, res_mean))); // } // // [[Rcpp::export]] // List test2(NumericMatrix x,List neighbors, int coleng){ // List scf = List::create(); // for (int i = 0; i < coleng; i++){ // NumericVector nodescf=NumericVector::create(); // NumericVector tmp=neighbors[i]; // for(int j = 0; j<tmp.length(); j++){ // NumericVector obs=x( _ , (tmp[j]-1) ); // NumericVector ref=x(_, i); // //std::valarray<double> obs(ref,ref.size()); // std::vector<double> obs_v=as<std::vector<double> >(obs); // std::vector<double> ref_v=as<std::vector<double> >(ref); // // double nO = sum(obs); // // double nR = sum(ref); // // double nOv = std::accumulate(obs_v.begin(), obs_v.end(), 0.0); // double nRv = std::accumulate(ref_v.begin(), ref_v.end(), 0.0); // // //double logR = log2((obs)/(ref)); // // // // nodescf.push_back(nOv); // } // scf.push_back(nodescf); // } // return(scf); // } // // // // [[Rcpp::export]] // List test3(NumericMatrix x,List neighbors, int coleng){ // List scf = List::create(); // for (int i = 0; i < coleng; i++){ // NumericVector nodescf=NumericVector::create(); // NumericVector tmp=neighbors[i]; // for(int j = 0; j<tmp.length(); j++){ // NumericVector obs=x( _ , (tmp[j]-1) ); // NumericVector ref=x(_, i); // //std::valarray<double> obs(ref,ref.size()); // std::vector<double> obs_v=as<std::vector<double> >(obs); // std::vector<double> ref_v=as<std::vector<double> >(ref); // double nO = sum(obs); // double nR = sum(ref); // // // double nOv = std::accumulate(obs_v.begin(), obs_v.end(), 0.0); // // double nRv = std::accumulate(ref_v.begin(), ref_v.end(), 0.0); // // //double logR = log2((obs)/(ref)); // // // // nodescf.push_back(nO); // } // scf.push_back(nodescf); // } // return(scf); // }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amoinier <amoinier@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/10/03 11:01:59 by amoinier #+# #+# */ /* Updated: 2017/10/03 11:31:58 by amoinier ### ########.fr */ /* */ /* ************************************************************************** */ #include "ZombieHorde.hpp" int main() { ZombieHorde horde = ZombieHorde(12); ZombieHorde horde2 = ZombieHorde(7); return 0; }
//////////////////////////////////////////////////////////////////////////// // Created : 24.02.2009 // Author : Armen Abroyan // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "transform_control_base.h" #include "collision_object.h" #include "level_editor.h" #include "project.h" #include "object_base.h" #pragma managed(push,off) #include <xray/collision/space_partitioning_tree.h> #include <xray/collision/api.h> #pragma managed(pop) using xray::collision::space_partitioning_tree; namespace xray { namespace editor { void editor_control_base::activate( bool b_activate ) { m_active = b_activate; if(b_activate) on_activated(this); else on_deactivated(this); } void editor_control_base::subscribe_on_activated( activate_control_event^ d) { on_activated += d; } void editor_control_base::subscribe_on_deactivated( deactivate_control_event^ d) { on_deactivated += d; } void editor_control_base::subscribe_on_property_changed(property_changed^ d) { on_property_changed += d; } void editor_control_base::change_property(System::String^ prop_name, float const value) { if(prop_name=="sensitivity") { sensitivity += value; sensitivity = math::clamp_r(sensitivity, 0.1f, 20.0f); } on_property_changed(this); } void editor_control_base::load_settings(RegistryKey^ key) { RegistryKey^ self_key = get_sub_key(key, name); sensitivity = System::Convert::ToSingle(self_key->GetValue("sensitivity", "1") ); self_key->Close (); } void editor_control_base::save_settings(RegistryKey^ key) { RegistryKey^ self_key = get_sub_key(key, name); self_key->SetValue ("sensitivity", sensitivity); self_key->Close (); } void editor_control_base::start_input( ) { m_ide->set_mouse_sensivity(sensitivity); } void editor_control_base::end_input( ) { m_ide->set_mouse_sensivity(1.0f); } struct transform_control_base_internal : private boost::noncopyable { transform_control_base_internal() :m_transform ( float4x4().identity() ), m_view_transform ( float4x4().identity() ), m_selected_color ( 255u, 255u, 0u, 255u ), m_last_position_lines_color ( 100u, 100u, 100u, 255u ) { m_axes_vectors.resize( enum_transform_axis_COUNT ); m_axes_vectors[enum_transform_axis_cam] = float3( 0, 0, 0 ); m_axes_vectors[enum_transform_axis_x] = float3( 1, 0, 0 ); m_axes_vectors[enum_transform_axis_y] = float3( 0, 1, 0 ); m_axes_vectors[enum_transform_axis_z] = float3( 0, 0, 1 ); m_axes_vectors[enum_transform_axis_all] = float3( 1, 1, 1 ).normalize(); m_axes_vectors[enum_transform_axis_none] = float3( 0, 0, 0 ); m_colors_default.resize( enum_transform_axis_COUNT ); m_colors_default[enum_transform_axis_cam] = math::color_xrgb( 0, 255, 255 ); m_colors_default[enum_transform_axis_x] = math::color_xrgb( 255, 0, 0 ); m_colors_default[enum_transform_axis_y] = math::color_xrgb( 0, 255, 0 ); m_colors_default[enum_transform_axis_z] = math::color_xrgb( 0, 0, 255 ); m_colors_default[enum_transform_axis_all] = math::color_xrgb( 70, 70, 70 ); m_colors_default[enum_transform_axis_none] = math::color_xrgb( 0, 0, 0 ); m_axes_visibilities.resize ( enum_transform_axis_COUNT, true ); } collision_objects_vec m_collision_objects; geometries_vec m_geometries; float4x4 m_transform; float4x4 m_view_transform; vector < float3 > m_axes_vectors; vector < color > m_colors_default; vector < color > m_colors; vector < bool > m_axes_visibilities; color const m_selected_color; color const m_last_position_lines_color; }; transform_control_base::transform_control_base( level_editor^ le) :super (le->ide()), m_level_editor ( le ), m_data ( NEW (transform_control_base_internal) ), m_control_visible ( false ), m_draw_collision_geomtery ( false ), m_dragging ( false ), m_preview_mode ( false ), m_cursor_thickness ( 0.2f ), m_last_position_vertex_radius ( 5.f ), m_distance_from_cam ( 20.f ), m_transparent_line_pattern ( 0x55555555 ), m_active_axis ( enum_transform_axis_cam ), m_apply_command ( nullptr ), m_aim_object ( nullptr ) { sensitivity = 1.0f; reset_colors (); m_data->m_colors[m_active_axis] = m_data->m_selected_color; } transform_control_base::~transform_control_base() { DELETE (m_data); } void transform_control_base::activate(bool bactivate) { super::activate(bactivate); if(bactivate) m_data->m_view_transform = m_level_editor->get_inverted_view_matrix(); } void transform_control_base::initialize( ) { set_transform ( create_scale( float3( 0.5f, 0.7f, 2.f ) ) * math::create_rotation_x ( -math::pi_d4 ) * create_translation ( float3( 0.f, 0.f, 50.f ) ) ); } void transform_control_base::destroy( ) { for( u32 i = 0; i < m_data->m_collision_objects.size(); ++i) DELETE (m_data->m_collision_objects[i]); m_data->m_collision_objects.clear(); for( u32 i = 0; i < m_data->m_geometries.size(); ++i) collision::destroy ( m_data->m_geometries[i] ); m_data->m_geometries.clear(); } void transform_control_base::set_transform ( float4x4 const& transform ) { m_data->m_transform = transform; collision_objects_vec::const_iterator i = m_data->m_collision_objects.begin(); collision_objects_vec::const_iterator e = m_data->m_collision_objects.end(); for( ; i != e; ++i ) (*i)->set_matrix ( calculate_fixed_size_transform( m_data->m_transform, m_distance_from_cam, m_data->m_view_transform ) ); update_colision_tree ( ); } void transform_control_base::update ( ) { // make it event-based !!! object_base^ o = m_level_editor->get_project()->aim_object(); if( o && !m_control_visible ) show(true); else if( !o && m_control_visible ) show(false); if ( !m_control_visible ) return; m_data->m_view_transform = m_level_editor->get_inverted_view_matrix(); if(m_aim_object != o || !m_data->m_transform.c.similar(o->get_transform().c) ) { m_aim_object = o; set_transform( m_aim_object->get_transform() ); } } float transform_control_base::calculate_fixed_size_scale( float3 const& pos, float distance, float4x4 const& inv_view ) { ASSERT( distance != 0 ); //float3 const start_point = transform.transform_position( float3( 0, 0, 0 ) ); float3 const distance_vector = inv_view.c.xyz() - pos; float const distance_magnitude = distance_vector.magnitude(); if( math::is_zero( distance_magnitude ) ) return 0; return (distance_magnitude / distance) * -math::sign(distance_vector|inv_view.k.xyz()); } float4x4 transform_control_base::calculate_fixed_size_transform ( float4x4 const& transform, float distance, float4x4 const& view ) { ASSERT( distance != 0 ); float scale = calculate_fixed_size_scale ( transform.c.xyz(), distance, view ); return create_scale( float3( scale, scale, scale ) ) * transform; } bool transform_control_base::rey_nearest_point ( float3 const& origin1, float3 direction1, float3 const& origin2, float3 direction2, float3& intersect ) { direction1.normalize(); direction2.normalize(); float3 perp_direction = direction1^direction2; // cross product if( fabs( direction1.dot_product(direction2)) > (1 - math::epsilon_3) ) return false; return plane_ray_intersect ( origin2, perp_direction^direction2, origin1, direction1, intersect ); } bool transform_control_base::plane_ray_intersect ( float3 const& plane_origin, float3 const& plane_normal, float3 const& ray_origin, float3 const& ray_direction, float3& intersect ) { if( fabs( plane_normal.dot_product(ray_direction)) < math::epsilon_3 ) return false; float d = -plane_normal.dot_product(plane_origin); float t = -( d + (plane_normal.dot_product(ray_origin))) / plane_normal.dot_product(ray_direction); intersect = ray_origin+t*ray_direction; return true; } void transform_control_base::show ( bool show ) { if( m_control_visible != show ) { m_control_visible = show; space_partitioning_tree* tree = m_level_editor->get_collision_tree( ); if( m_control_visible ) { for( u32 i = 0; i < m_data->m_collision_objects.size(); ++i) tree->insert( m_data->m_collision_objects[i], m_data->m_transform.transform_position( m_data->m_collision_objects[i]->get_center() ), m_data->m_collision_objects[i]->get_extents() ); } else { for( u32 i = 0; i < m_data->m_collision_objects.size(); ++i) tree->remove( m_data->m_collision_objects[i] ); } } if( m_control_visible ) { m_aim_object = m_level_editor->get_project()->aim_object(); set_transform ( m_aim_object->get_transform() ); } } void transform_control_base::update_colision_tree() { space_partitioning_tree* const tree = m_level_editor->get_collision_tree( ); for( u32 i = 0; i < m_data->m_collision_objects.size(); ++i) tree->move ( m_data->m_collision_objects[i], m_data->m_collision_objects[i]->get_center(), m_data->m_collision_objects[i]->get_extents()); } float3 transform_control_base::get_axis_vector( enum_transform_axis mode ) { if( (u32) mode >= m_data->m_axes_vectors.size() ) { ASSERT ( "Unknown axis id !" ); return m_data->m_axes_vectors[enum_transform_axis_none]; } if( mode == enum_transform_axis_cam ) return -m_data->m_view_transform.k.xyz(); return m_data->m_axes_vectors[mode]; } void transform_control_base::set_draw_geomtry ( bool draw ) { m_draw_collision_geomtery = draw; } void transform_control_base::reset_colors ( ) { m_data->m_colors.resize( m_data->m_colors_default.size() ); const u32 count = m_data->m_colors.size(); for ( u32 i = 0; i < count; ++i ) m_data->m_colors[i] = m_data->m_colors_default[i]; } bool transform_control_base::one_covers_another ( float3 position1, float radius1, float3 position2, float radius2, float4x4 const& view ) { float3 distance_vector1 = position1 - view.c.xyz(); float3 distance_vector2 = position2 - view.c.xyz(); float distance1 = distance_vector1.magnitude(); float distance2 = distance_vector2.magnitude(); if( distance1 < distance2 ) { if( math::is_zero( distance1 ) ) return true; float scale_factor = distance2/distance1; radius1 *= scale_factor; distance_vector1 *= scale_factor; position1 = view.c.xyz() + distance_vector1; } else return false; if( (position2-position1).magnitude() < radius2+radius1) return true; return false; } void transform_control_base::set_mode_modfiers ( bool plane_mode, bool free_mode ) { m_plane_mode_modifier = plane_mode; m_free_mode_modifier = free_mode; } u32 transform_control_base::acceptable_collision_type() { return collision_type_control; } float4x4 const& transform_control_base::get_view_transform() { return m_data->m_view_transform; } float4x4 const& transform_control_base::get_transform() { return m_data->m_transform; } geometries_vec& transform_control_base::get_geometries() { return m_data->m_geometries; } collision_objects_vec& transform_control_base::get_collision_objects() { return m_data->m_collision_objects; } color& transform_control_base::get_color(int idx) { return m_data->m_colors[idx]; } bool transform_control_base::is_axis_visible(int idx) { return m_data->m_axes_visibilities[idx]; } void transform_control_base::set_axis_visible(bool val, int idx) { m_data->m_axes_visibilities[idx]=val; } color const& transform_control_base::selection_color() { return m_data->m_selected_color; } color const& transform_control_base::last_position_line_color() { return m_data->m_last_position_lines_color; } } // editor } // xray
; A277287: a(n) = binomial(2*n,n) + Sum_{k=1..n} binomial(2*n-k,n-k)*Fibonacci(k). ; Submitted by Christian Krause ; 1,3,10,36,133,499,1891,7217,27690,106680,412368,1598358,6209542,24171004,94246202,368022472,1438965885,5632870627,22072920103,86575738469,339860843589,1335186464195,5249164967309,20650056413491,81285516680103,320144986417429,1261550609046391,4973610196619037,19617069598834375,77406855914177845,305559927188363427,1206632020883567497,4766564616490914538,18835615998243621096,74454354121102432408,294394139268867065854,1164368445318091395106,4606465574200290957752,18228702115349983599630 mov $3,$0 mul $3,2 lpb $0 mov $2,$3 div $2,2 add $2,$0 bin $2,$0 sub $0,1 add $1,$2 add $3,1 lpe mov $0,$1 add $0,1
@ libgcc code defines - extracted from lib1funcs.S /* Copyright 1995, 1996, 1998, 1999, 2000, 2003, 2004, 2005, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ /* An executable stack is *not* required for these functions. */ #if defined(__ELF__) && defined(__linux__) .section .note.GNU-stack,"",%progbits .previous #endif /* __ELF__ and __linux__ */ #ifdef __ARM_EABI__ /* Some attributes that are common to all routines in this file. */ /* Tag_ABI_align_needed: This code does not require 8-byte alignment from the caller. */ /* .eabi_attribute 24, 0 -- default setting. */ /* Tag_ABI_align_preserved: This code preserves 8-byte alignment in any callee. */ .eabi_attribute 25, 1 #endif /* __ARM_EABI__ */ /* ------------------------------------------------------------------------ */ /* We need to know what prefix to add to function names. */ #ifndef __USER_LABEL_PREFIX__ #error __USER_LABEL_PREFIX__ not defined #endif /* ANSI concatenation macros. */ #define CONCAT1(a, b) CONCAT2(a, b) #define CONCAT2(a, b) a ## b /* Use the right prefix for global labels. */ #define SYM(x) CONCAT1 (__USER_LABEL_PREFIX__, x) #ifdef __ELF__ //#ifdef __thumb__ //#define __PLT__ /* Not supported in Thumb assembler (for now). */ //#elif defined __vxworks && !defined __PIC__ #define __PLT__ /* Not supported by the kernel loader. */ //#else //#define __PLT__ (PLT) //#endif #define TYPE(x) .type SYM(x),function #define SIZE(x) .size SYM(x), . - SYM(x) #define LSYM(x) .x #else #define __PLT__ #define TYPE(x) #define SIZE(x) #define LSYM(x) x #endif /* Function end macros. Variants for interworking. */ #if defined(__ARM_ARCH_2__) # define __ARM_ARCH__ 2 #endif #if defined(__ARM_ARCH_3__) # define __ARM_ARCH__ 3 #endif #if defined(__ARM_ARCH_3M__) || defined(__ARM_ARCH_4__) \ || defined(__ARM_ARCH_4T__) /* We use __ARM_ARCH__ set to 4 here, but in reality it's any processor with long multiply instructions. That includes v3M. */ # define __ARM_ARCH__ 4 #endif #if defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5T__) \ || defined(__ARM_ARCH_5E__) || defined(__ARM_ARCH_5TE__) \ || defined(__ARM_ARCH_5TEJ__) # define __ARM_ARCH__ 5 #endif #if defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \ || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) \ || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) \ || defined(__ARM_ARCH_6M__) # define __ARM_ARCH__ 6 #endif #if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) \ || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) \ || defined(__ARM_ARCH_7EM__) # define __ARM_ARCH__ 7 #endif #ifndef __ARM_ARCH__ #error Unable to determine architecture. #endif /* There are times when we might prefer Thumb1 code even if ARM code is permitted, for example, the code might be smaller, or there might be interworking problems with switching to ARM state if interworking is disabled. */ #if (defined(__thumb__) \ && !defined(__thumb2__) \ && (!defined(__THUMB_INTERWORK__) \ || defined (__OPTIMIZE_SIZE__) \ || defined(__ARM_ARCH_6M__))) # define __prefer_thumb__ #endif /* How to return from a function call depends on the architecture variant. */ #if (__ARM_ARCH__ > 4) || defined(__ARM_ARCH_4T__) # define RET bx lr # define RETc(x) bx##x lr /* Special precautions for interworking on armv4t. */ # if (__ARM_ARCH__ == 4) /* Always use bx, not ldr pc. */ # if (defined(__thumb__) || defined(__THUMB_INTERWORK__)) # define __INTERWORKING__ # endif /* __THUMB__ || __THUMB_INTERWORK__ */ /* Include thumb stub before arm mode code. */ # if defined(__thumb__) && !defined(__THUMB_INTERWORK__) # define __INTERWORKING_STUBS__ # endif /* __thumb__ && !__THUMB_INTERWORK__ */ #endif /* __ARM_ARCH == 4 */ #else # define RET mov pc, lr # define RETc(x) mov##x pc, lr #endif .macro cfi_pop advance, reg, cfa_offset #ifdef __ELF__ .pushsection .debug_frame .byte 0x4 /* DW_CFA_advance_loc4 */ .4byte \advance .byte (0xc0 | \reg) /* DW_CFA_restore */ .byte 0xe /* DW_CFA_def_cfa_offset */ .uleb128 \cfa_offset .popsection #endif .endm .macro cfi_push advance, reg, offset, cfa_offset #ifdef __ELF__ .pushsection .debug_frame .byte 0x4 /* DW_CFA_advance_loc4 */ .4byte \advance .byte (0x80 | \reg) /* DW_CFA_offset */ .uleb128 (\offset / -4) .byte 0xe /* DW_CFA_def_cfa_offset */ .uleb128 \cfa_offset .popsection #endif .endm .macro cfi_start start_label, end_label #ifdef __ELF__ .pushsection .debug_frame LSYM(Lstart_frame): .4byte LSYM(Lend_cie) - LSYM(Lstart_cie) @ Length of CIE LSYM(Lstart_cie): .4byte 0xffffffff @ CIE Identifier Tag .byte 0x1 @ CIE Version .ascii "\0" @ CIE Augmentation .uleb128 0x1 @ CIE Code Alignment Factor .sleb128 -4 @ CIE Data Alignment Factor .byte 0xe @ CIE RA Column .byte 0xc @ DW_CFA_def_cfa .uleb128 0xd .uleb128 0x0 .align 2 LSYM(Lend_cie): .4byte LSYM(Lend_fde)-LSYM(Lstart_fde) @ FDE Length LSYM(Lstart_fde): .4byte LSYM(Lstart_frame) @ FDE CIE offset .4byte \start_label @ FDE initial location .4byte \end_label-\start_label @ FDE address range .popsection #endif .endm .macro cfi_end end_label #ifdef __ELF__ .pushsection .debug_frame .align 2 LSYM(Lend_fde): .popsection \end_label: #endif .endm /* Don't pass dirn, it's there just to get token pasting right. */ .macro RETLDM regs=, cond=, unwind=, dirn=ia #if defined (__INTERWORKING__) .ifc "\regs","" ldr\cond lr, [sp], #8 .else # if defined(__thumb2__) pop\cond {\regs, lr} # else ldm\cond\dirn sp!, {\regs, lr} # endif .endif .ifnc "\unwind", "" /* Mark LR as restored. */ 97: cfi_pop 97b - \unwind, 0xe, 0x0 .endif bx\cond lr #else /* Caller is responsible for providing IT instruction. */ .ifc "\regs","" ldr\cond pc, [sp], #8 .else # if defined(__thumb2__) pop\cond {\regs, pc} # else ldm\cond\dirn sp!, {\regs, pc} # endif .endif #endif .endm /* The Unified assembly syntax allows the same code to be assembled for both ARM and Thumb-2. However this is only supported by recent gas, so define a set of macros to allow ARM code on older assemblers. */ #if defined(__thumb2__) .macro do_it cond, suffix="" it\suffix \cond .endm .macro shift1 op, arg0, arg1, arg2 \op \arg0, \arg1, \arg2 .endm #define do_push push #define do_pop pop #define COND(op1, op2, cond) op1 ## op2 ## cond /* Perform an arithmetic operation with a variable shift operand. This requires two instructions and a scratch register on Thumb-2. */ .macro shiftop name, dest, src1, src2, shiftop, shiftreg, tmp \shiftop \tmp, \src2, \shiftreg \name \dest, \src1, \tmp .endm #else .macro do_it cond, suffix="" .endm .macro shift1 op, arg0, arg1, arg2 mov \arg0, \arg1, \op \arg2 .endm #define do_push stmfd sp!, #define do_pop ldmfd sp!, #define COND(op1, op2, cond) op1 ## cond ## op2 .macro shiftop name, dest, src1, src2, shiftop, shiftreg, tmp \name \dest, \src1, \src2, \shiftop \shiftreg .endm #endif #ifdef __ARM_EABI__ .macro ARM_LDIV0 name signed cmp r0, #0 .ifc \signed, unsigned movne r0, #0xffffffff .else movgt r0, #0x7fffffff movlt r0, #0x80000000 .endif b SYM (__aeabi_idiv0) __PLT__ .endm #else .macro ARM_LDIV0 name signed str lr, [sp, #-8]! 98: cfi_push 98b - __\name, 0xe, -0x8, 0x8 bl SYM (__div0) __PLT__ mov r0, #0 @ About as wrong as it could be. RETLDM unwind=98b .endm #endif #ifdef __ARM_EABI__ .macro THUMB_LDIV0 name signed #if defined(__ARM_ARCH_6M__) .ifc \signed, unsigned cmp r0, #0 beq 1f mov r0, #0 mvn r0, r0 @ 0xffffffff 1: .else cmp r0, #0 beq 2f blt 3f mov r0, #0 mvn r0, r0 lsr r0, r0, #1 @ 0x7fffffff b 2f 3: mov r0, #0x80 lsl r0, r0, #24 @ 0x80000000 2: .endif push {r0, r1, r2} ldr r0, 4f adr r1, 4f add r0, r1 str r0, [sp, #8] @ We know we are not on armv4t, so pop pc is safe. pop {r0, r1, pc} .align 2 4: .word __aeabi_idiv0 - 4b #elif defined(__thumb2__) .syntax unified .ifc \signed, unsigned cbz r0, 1f mov r0, #0xffffffff 1: .else cmp r0, #0 do_it gt movgt r0, #0x7fffffff do_it lt movlt r0, #0x80000000 .endif b.w SYM(__aeabi_idiv0) __PLT__ #else .align 2 bx pc nop .arm cmp r0, #0 .ifc \signed, unsigned movne r0, #0xffffffff .else movgt r0, #0x7fffffff movlt r0, #0x80000000 .endif b SYM(__aeabi_idiv0) __PLT__ .thumb #endif .endm #else .macro THUMB_LDIV0 name signed push { r1, lr } 98: cfi_push 98b - __\name, 0xe, -0x4, 0x8 bl SYM (__div0) mov r0, #0 @ About as wrong as it could be. #if defined (__INTERWORKING__) pop { r1, r2 } bx r2 #else pop { r1, pc } #endif .endm #endif .macro FUNC_END name SIZE (__\name) .endm .macro DIV_FUNC_END name signed cfi_start __\name, LSYM(Lend_div0) LSYM(Ldiv0): #ifdef __thumb__ THUMB_LDIV0 \name \signed #else ARM_LDIV0 \name \signed #endif cfi_end LSYM(Lend_div0) FUNC_END \name .endm .macro THUMB_FUNC_START name .globl SYM (\name) TYPE (\name) .thumb_func SYM (\name): .endm /* Function start macros. Variants for ARM and Thumb. */ #ifdef __thumb__ #define THUMB_FUNC .thumb_func #define THUMB_CODE .force_thumb # if defined(__thumb2__) #define THUMB_SYNTAX .syntax divided # else #define THUMB_SYNTAX # endif #else #define THUMB_FUNC #define THUMB_CODE #define THUMB_SYNTAX #endif .macro FUNC_START name .text .globl SYM (__\name) .hidden SYM (__\name) TYPE (__\name) .align 0 THUMB_CODE THUMB_FUNC THUMB_SYNTAX SYM (__\name): .endm /* Special function that will always be coded in ARM assembly, even if in Thumb-only compilation. */ #if defined(__thumb2__) /* For Thumb-2 we build everything in thumb mode. */ .macro ARM_FUNC_START name FUNC_START \name .syntax unified .endm #define EQUIV .thumb_set .macro ARM_CALL name bl __\name .endm #elif defined(__INTERWORKING_STUBS__) .macro ARM_FUNC_START name FUNC_START \name bx pc nop .arm /* A hook to tell gdb that we've switched to ARM mode. Also used to call directly from other local arm routines. */ _L__\name: .endm #define EQUIV .thumb_set /* Branch directly to a function declared with ARM_FUNC_START. Must be called in arm mode. */ .macro ARM_CALL name bl _L__\name .endm #else /* !(__INTERWORKING_STUBS__ || __thumb2__) */ #ifdef __ARM_ARCH_6M__ #define EQUIV .thumb_set #else .macro ARM_FUNC_START name .text .globl SYM (__\name) .hidden SYM (__\name) TYPE (__\name) .align 0 .arm SYM (__\name): .endm #define EQUIV .set .macro ARM_CALL name bl __\name .endm #endif #endif .macro FUNC_ALIAS new old .globl SYM (__\new) .hidden SYM (__\new) #if defined (__thumb__) .thumb_set SYM (__\new), SYM (__\old) #else .set SYM (__\new), SYM (__\old) #endif .endm #ifndef __ARM_ARCH_6M__ .macro ARM_FUNC_ALIAS new old .globl SYM (__\new) .hidden SYM (__\new) EQUIV SYM (__\new), SYM (__\old) #if defined(__INTERWORKING_STUBS__) .set SYM (_L__\new), SYM (_L__\old) #endif .endm #endif #ifdef __ARMEB__ #define xxh r0 #define xxl r1 #define yyh r2 #define yyl r3 #else #define xxh r1 #define xxl r0 #define yyh r3 #define yyl r2 #endif #ifdef __ARM_EABI__ .macro WEAK name .weak SYM (__\name) .endm #endif
.global s_prepare_buffers s_prepare_buffers: push %r14 push %r8 push %rcx push %rdi push %rdx push %rsi lea addresses_A_ht+0xe2c4, %rsi lea addresses_normal_ht+0x17a9d, %rdi nop nop xor %rdx, %rdx mov $25, %rcx rep movsw inc %r14 lea addresses_A_ht+0x1c69d, %rsi lea addresses_UC_ht+0x114dd, %rdi nop nop cmp %r8, %r8 mov $30, %rcx rep movsw nop nop nop add %rdx, %rdx lea addresses_D_ht+0xa15d, %rsi lea addresses_normal_ht+0x3de5, %rdi nop nop nop nop nop xor $12001, %rdx mov $97, %rcx rep movsl nop nop nop nop nop xor $42921, %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %r8 pop %r14 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r14 push %r15 push %r8 push %rcx // Faulty Load lea addresses_PSE+0x1aa9d, %r15 nop nop xor %r11, %r11 mov (%r15), %r13 lea oracles, %r11 and $0xff, %r13 shlq $12, %r13 mov (%r11,%r13,1), %r13 pop %rcx pop %r8 pop %r15 pop %r14 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_PSE', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_PSE', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': True}, 'OP': 'REPM'} {'src': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM'} {'33': 21829} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
; WARNING: FOR MACOS ONLY ; nasm -f macho64 cipher.asm -o cipher.o && ld -o cipher.macho -macosx_version_min 10.7 -e start cipher.o && ./cipher.macho BITS 64 section .text global start start: push rbp mov rbp,rsp ; PRINT OUTPUT push 0xa203a mov DWORD [rsp+0x4],0x0 push 0x76207965 mov DWORD [rsp+0x4],0x65756c61 push 0x7475706e mov DWORD [rsp+0x4],0x6b206120 push 0x61656c50 mov DWORD [rsp+0x4],0x69206573 mov rax, 0x2000004 mov rdi, 0x1 mov rsi, rsp mov edx, 0x1b syscall pop rax pop rax pop rax pop rax ; GET INPUT mov rax, 0x2000003 mov rdi, 0 lea rsi, [rel key] mov edx, 0x10 syscall ; GENERATE KEY mov r9, 0 ; int i = 0; mov r10, 0 ; int j = 0; lea r13, [rel encrypted] lea r14, [rel key] lea r15, [rel keyframe] loop1: cmp r9, 1649 ; Length of encrypted jge decrypt cmp r10, 4 ; if(j == keyLen) jne not_length xor r10, r10 ; j = 0 not_length: movzx ecx, BYTE [r14+r10] ; c = key[j] mov BYTE [r15 + r9], cl ; newKey[i] = c inc r9 ; i++ inc r10 ; j++ jmp loop1 decrypt: xor r9, r9 ; int i = 0; loop2: cmp r9, 1649 ; Length of encrypted jge exit_loop movzx ecx, BYTE [r13+r9] ; a = encrypted[i] movzx edx, BYTE [r15+r9] ; b = keyframe[i] sub ecx, edx ; a - b add ecx, 256 ; a + 256 mov rdx, 0 mov eax, ecx cdq mov esi, 256 idiv esi mov BYTE [r13 + r9], dl ; decryptedMsg[i] = a inc r9 ; i++ jmp loop2 exit_loop: mov eax, 0x2000004 ; write mov rdi, 1 ; std out lea rsi, [rel encrypted] mov edx, 12 syscall xor eax, eax mov rax, 0x2000001 ; exit mov rdi, 0 syscall section .data encrypted: db 199,120,185,89,218,106,80,126,114,247,116,152,118,48,48,116,114,152,149,237,146,166,247,184,150,52,145,224,231,149,152,226,226,165,164,59,182,84,52,148,211,80,155,220,194,156,149,213,57,116,84,120,229,149,80,221,42,52,48,116,116,239,49,116,114,48,120,253,88,234,75,116,114,48,63,121,202,136,136,204,42,51,48,116,116,239,48,116,114,48,120,1,167,62,53,116,114,234,64,116,114,48,63,121,129,231,69,116,119,48,48,245,108,124,122,215,212,63,181,246,114,48,48,192,255,109,211,116,114,48,124,1,167,22,52,116,114,113,236,116,114,48,48,189,243,44,122,120,114,48,173,175,42,56,48,116,114,124,185,85,187,185,250,181,129,230,68,131,179,185,243,184,251,0,113,253,67,201,116,253,80,39,46,188,213,250,113,131,40,68,62,184,251,255,97,75,179,184,40,192,251,17,117,252,118,63,121,115,54,27,236,181,253,71,177,110,199,120,185,89,231,79,232,120,114,48,50,51,115,48,48,116,186,189,101,4,118,48,48,46,131,48,48,116,129,53,97,52,179,47,7,95,152,232,52,116,114,50,239,117,114,48,48,188,255,101,173,120,114,48,234,90,114,48,48,131,119,97,240,44,115,48,48,118,49,48,48,116,114,63,53,209,53,73,50,94,249,77,165,229,178,124,189,155,184,161,127,197,188,124,82,122,141,133,105,10,128,152,126,118,128,48,90,173,150,108,111,139,23,97,155,201,220,93,154,124,124,85,83,168,157,187,62,187,216,54,90,229,149,36,126,215,212,167,32,196,188,124,122,159,93,195,37,190,188,124,122,224,217,93,71,125,132,36,121,215,212,167,32,197,188,124,122,159,97,112,236,196,188,124,32,231,212,165,127,210,193,52,241,234,249,164,127,197,116,189,208,183,85,191,104,121,229,170,111,133,156,40,114,247,189,124,122,159,74,173,127,197,188,124,122,215,212,105,242,200,13,125,122,215,252,62,127,197,188,52,247,226,89,164,127,197,116,38,170,215,212,165,127,197,188,124,54,98,217,49,126,197,188,48,247,226,65,164,127,197,20,196,122,215,212,253,123,197,188,126,37,214,212,165,127,141,57,169,77,214,212,165,55,70,254,116,32,191,212,165,127,210,193,52,241,218,153,164,127,197,116,173,193,159,197,236,55,212,10,52,171,16,177,230,39,201,188,124,120,80,213,165,127,197,116,241,175,121,210,165,127,95,30,124,122,215,223,160,174,5,100,125,122,215,210,250,127,197,188,124,117,218,169,109,246,40,116,173,186,150,75,133,127,197,188,53,35,223,220,173,119,205,180,116,114,158,74,165,126,199,187,120,127,217,215,105,166,253,176,112,55,94,232,229,50,196,242,52,229,23,251,202,55,212,252,49,171,30,161,116,205,144,183,42,134,215,161,164,198,171,117,115,84,20,158,170,41,193,205,49,123,46,161,116,196,136,52,183,55,88,27,106,112,91,200,116,63,95,240,165,89,140,183,98,185,152,92,153,119,140,39,190,55,198,43,105,166,247,121,115,62,36,156,186,191,73,252,105,38,178,19,80,55,76,33,52,171,23,161,116,205,171,117,115,84,21,118,108,112,179,242,52,163,21,136,48,89,140,183,98,184,158,15,231,50,212,3,57,242,36,118,108,112,179,251,51,117,73,232,156,89,140,183,98,177,121,157,170,81,247,121,125,192,162,197,222,58,77,11,90,51,224,126,238,48,210,110,136,131,121,157,170,81,255,158,53,117,145,19,98,247,185,197,90,51,224,142,238,89,140,183,98,200,152,92,145,134,171,117,115,100,44,161,164,197,144,237,199,63,95,35,106,112,91,208,133,54,224,70,153,126,144,237,198,63,95,232,165,55,34,252,215,252,178,19,103,249,247,103,25,131,79,70,248,15,44,148,204,83,200,189,189,141,25,33,204,225,4,142,55,94,156,197,209,62,229,162,176,230,111,208,170,119,240,66,87,84,23,146,198,7,3,208,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,165,127,197,188,124,122,215,212,133,159,229,220,156,60,150,157,105,159,122,116,61,54,154,181,175,117,122,220,156,154,183,180,82,159,229,220,156,154,183,167,133,159,229,220,156,154,183,180,175,72,229,220,156,154,183,180,133,159,122,220,156,77,183,180,133,159,229,143,156,154,183,180,175,159,229,220,156,154,183,180,133,159,229,220,156,154,183,183,139,159,229,143,156,154,183,180,133,159,207,220,156,148,194,178,135,146,243,135,156,154,183,180,133,67,229,136,146,151,194,144,133,159,207,220,147,154,183,180,133,159,229,220,158,151,193,190,90,64,236,220,146,151,184,180,133,159,207,168,156,154,183,180,133,64,229,220,156,154,183,180,133,159,229,215,156,154,183,180,133,159,207,136,155,151,193,175,90,147,229,220,156,148,176,175,139,147,234,220,156,154,183,180,133,159,207,220,92,157,194,193,136,146,234,214,67,70,194,193,130,159,229,220,156,154,183,218,83,73,123,142,74,76,169,166,83,73,123,142,74,76,169,166,83,73,123,142,74,112,116,114,48,48,116,114,48,48,116,114,48,48,116,114,48,48,191,215,149,160,148,217,159,153,226,217,81,58,148,146,80,80,148,184,113,121,192,146,135,120,181,190,117,81,126,124,135,80,148,146,80,80,203,146,80,80,148,146,80,135,148,146,80,80,148,146,80,80,126,201,80,80,148,146,80,80,148,146,135,80,148,201,80,80,148,146,80,135,148,146,80,80,126,146,80,80,148,146,80,80,148,146,80,80,148,146,80,87,162,146,80,135,148,146,80,80,148,146,58,80,148,160,93,82,150,159,94,143,148,146,80,80,148,206,80,140,162,159,93,172,148,146,58,80,163,146,80,80,148,146,80,80,150,159,94,94,211,209,89,80,162,159,87,80,148,146,58,172,148,146,80,80,148,209,80,80,148,146,80,80,148,146,80,95,148,146,80,80,148,146,58,140,155,159,94,143,211,158,80,80,148,160,143,143,162,158,87,80,148,146,80,80,148,146,58,80,212,153,93,93,161,159,87,94,211,206,93,93,155,146,80,80,148,146,80,58,202,200,134,134,202,200,134,134,202,200,134,134,202,200,134,134,202,200,134,134,202,124 key: times 0x10 db 0 keyframe: times 1649 db 0 msg: db "Keep going!", 10 msg2: db 32,32,32,32,32,70,65,73,76,32,87,72,65,76,69,33,10,10,87,32,32,32,32,32,87,32,32,32,32,32,32,87,32,32,32,32,32,32,32,32,10,87,32,32,32,32,32,32,32,32,87,32,32,87,32,32,32,32,32,87,32,32,32,32,10,32,32,32,32,32,32,32,32,32,32,32,32,32,32,39,46,32,32,87,32,32,32,32,32,32,10,32,32,46,45,34,34,45,46,95,32,32,32,32,32,92,32,92,46,45,45,124,32,32,10,32,47,32,32,32,32,32,32,32,34,45,46,46,95,95,41,32,46,45,39,32,32,32,10,124,32,32,32,32,32,95,32,32,32,32,32,32,32,32,32,47,32,32,32,32,32,32,10,92,39,45,46,95,95,44,32,32,32,46,95,95,46,44,39,32,32,32,32,32,32,32,10,32,96,39,45,45,45,45,39,46,95,92,45,45,39,32,32,32,32,32,32,10,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86, 10
; A272459: The total number of different isosceles trapezoids, excluding squares, that can be drawn on a n X n square grid where the corners of each individual trapezoid lie on a lattice point. ; 0,1,7,18,40,71,119,180,264,365,495,646,832,1043,1295,1576,1904,2265,2679,3130,3640,4191,4807,5468,6200,6981,7839,8750,9744,10795,11935,13136,14432,15793,17255,18786,20424,22135,23959,25860,27880,29981,32207,34518,36960,39491,42159,44920,47824,50825,53975,57226,60632,64143,67815,71596,75544,79605,83839,88190,92720,97371,102207,107168,112320,117601,123079,128690,134504,140455,146615,152916,159432,166093,172975,180006,187264,194675,202319,210120,218160,226361,234807,243418,252280,261311,270599,280060,289784,299685,309855,320206,330832,341643,352735,364016,375584,387345,399399,411650,424200,436951,450007,463268,476840,490621,504719,519030,533664,548515,563695,579096,594832,610793,627095,643626,660504,677615,695079,712780,730840,749141,767807,786718,806000,825531,845439,865600,886144,906945,928135,949586,971432,993543,1016055,1038836,1062024,1085485,1109359,1133510,1158080,1182931,1208207,1233768,1259760,1286041,1312759,1339770,1367224,1394975,1423175,1451676,1480632,1509893,1539615,1569646,1600144,1630955,1662239,1693840,1725920,1758321,1791207,1824418,1858120,1892151,1926679,1961540,1996904,2032605,2068815,2105366,2142432,2179843,2217775,2256056,2294864,2334025,2373719,2413770,2454360,2495311,2536807,2578668,2621080,2663861,2707199,2750910,2795184,2839835,2885055,2930656,2976832,3023393,3070535,3118066,3166184,3214695,3263799,3313300,3363400,3413901,3465007,3516518,3568640,3621171,3674319,3727880,3782064,3836665,3891895,3947546,4003832,4060543,4117895,4175676,4234104,4292965,4352479,4412430,4473040,4534091,4595807,4657968,4720800,4784081,4848039,4912450,4977544,5043095,5109335,5176036,5243432,5311293,5379855,5448886,5518624,5588835,5659759,5731160,5803280,5875881,5949207,6023018,6097560,6172591,6248359,6324620,6401624,6479125 mov $2,$0 mov $3,$0 lpb $3 lpb $2 trn $3,1 add $0,$3 add $4,$0 add $0,$3 sub $2,1 trn $3,1 sub $4,$3 lpe mov $1,$4 lpe
; A280340: a(n) = a(n-1) + 10^n * a(n-2) with a(0) = 1 and a(1) = 1. ; Submitted by Christian Krause ; 1,1,101,1101,1011101,111111101,1011212111101,1112122222111101,101122323232322111101,1112223344434333322111101,1011224344546565545343322111101,111223345667777878776655443322111101,1011224455769911213121200887756443322111101,1112234467902234557677767554421998766443322111101,101122446689225589214354646453411886633108866443322111101,1112234569024681246903356768776645219855208744209866443322111101,1011224468004490461168227711437475635107733884288429855219866443322111101 mov $2,1 mov $3,1 lpb $0 sub $0,1 mov $1,$3 mul $2,10 mul $4,$2 add $3,$4 mov $4,$1 lpe mov $0,$3
#include "utils/strings/string-rotation.h" #include <string> #include <algorithm> bool isStringRotation(const std::string &s1, const std::string &s2) { std::string s1Sorted = s1; std::string s2Sorted = s2; // sort is made in place // we could also remove the const keyword and pass both strings as copy to this function std::sort(s1Sorted.begin(), s1Sorted.end()); std::sort(s2Sorted.begin(), s2Sorted.end()); if (s1Sorted.find(s2Sorted) != std::string::npos) { return true; } return false; } bool stringRotation(std::string s1, std::string s2) { // sort is made in place std::sort(s1.begin(), s1.end()); std::sort(s2.begin(), s2.end()); if (s1.find(s2) != std::string::npos) { return true; } return false; }
// // Compute the DFA output (whether it's in an accepting // State) // We will rewrite RAM to contain a table of accepting // states (word i in RAM will be 1 if the state is // accepting and 0 otherwise). // // Note: most of the header parameters and symbols // are taken from the runDFA assembly script. .header wordsize: 16 // We actually only need 8-bit regs, but we'll pack 2 in each word. regptrsize: 5 // Don't need many regs romptrsize: 1 // Tiny program (actually only 1 instruction) ramptrsize: 13 // 4096 words (we use 64 words for each state, so this lets us have 64 states) instruction: load xor out //instruction: xor xor out .code load %out2, %state // %out2 = RAM[%state] //xor %out2 < %state, %czero xor %ctrl < %cone, %czero // Set %ctrl=1 out ---
;------------------------------------------------------------------------------ ; ; Copyright (c) 2016 - 2018, 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: ; ; SmmInit.nasm ; ; Abstract: ; ; Functions for relocating SMBASE's for all processors ; ;------------------------------------------------------------------------------- extern ASM_PFX(SmmInitHandler) extern ASM_PFX(mRebasedFlag) extern ASM_PFX(mSmmRelocationOriginalAddress) global ASM_PFX(gSmmCr3) global ASM_PFX(gSmmCr4) global ASM_PFX(gSmmCr0) global ASM_PFX(gSmmJmpAddr) global ASM_PFX(gSmmInitStack) global ASM_PFX(gcSmiInitGdtr) global ASM_PFX(gcSmmInitSize) global ASM_PFX(gcSmmInitTemplate) global ASM_PFX(mRebasedFlagAddr32) global ASM_PFX(mSmmRelocationOriginalAddressPtr32) DEFAULT REL SECTION .text ASM_PFX(gcSmiInitGdtr): DW 0 DQ 0 global ASM_PFX(SmmStartup) ASM_PFX(SmmStartup): DB 0x66 mov eax, 0x80000001 ; read capability cpuid DB 0x66 mov ebx, edx ; rdmsr will change edx. keep it in ebx. DB 0x66, 0xb8 ; mov eax, imm32 ASM_PFX(gSmmCr3): DD 0 mov cr3, rax DB 0x66, 0x2e lgdt [ebp + (ASM_PFX(gcSmiInitGdtr) - ASM_PFX(SmmStartup))] DB 0x66, 0xb8 ; mov eax, imm32 ASM_PFX(gSmmCr4): DD 0 or ah, 2 ; enable XMM registers access mov cr4, rax DB 0x66 mov ecx, 0xc0000080 ; IA32_EFER MSR rdmsr or ah, BIT0 ; set LME bit DB 0x66 test ebx, BIT20 ; check NXE capability jz .1 or ah, BIT3 ; set NXE bit .1: wrmsr DB 0x66, 0xb8 ; mov eax, imm32 ASM_PFX(gSmmCr0): DD 0 mov cr0, rax ; enable protected mode & paging DB 0x66, 0xea ; far jmp to long mode ASM_PFX(gSmmJmpAddr): DQ 0;@LongMode @LongMode: ; long-mode starts here DB 0x48, 0xbc ; mov rsp, imm64 ASM_PFX(gSmmInitStack): DQ 0 and sp, 0xfff0 ; make sure RSP is 16-byte aligned ; ; Accoring to X64 calling convention, XMM0~5 are volatile, we need to save ; them before calling C-function. ; sub rsp, 0x60 movdqa [rsp], xmm0 movdqa [rsp + 0x10], xmm1 movdqa [rsp + 0x20], xmm2 movdqa [rsp + 0x30], xmm3 movdqa [rsp + 0x40], xmm4 movdqa [rsp + 0x50], xmm5 add rsp, -0x20 call ASM_PFX(SmmInitHandler) add rsp, 0x20 ; ; Restore XMM0~5 after calling C-function. ; movdqa xmm0, [rsp] movdqa xmm1, [rsp + 0x10] movdqa xmm2, [rsp + 0x20] movdqa xmm3, [rsp + 0x30] movdqa xmm4, [rsp + 0x40] movdqa xmm5, [rsp + 0x50] rsm BITS 16 ASM_PFX(gcSmmInitTemplate): mov ebp, [cs:@L1 - ASM_PFX(gcSmmInitTemplate) + 0x8000] sub ebp, 0x30000 jmp ebp @L1: DQ 0; ASM_PFX(SmmStartup) ASM_PFX(gcSmmInitSize): DW $ - ASM_PFX(gcSmmInitTemplate) BITS 64 global ASM_PFX(SmmRelocationSemaphoreComplete) ASM_PFX(SmmRelocationSemaphoreComplete): push rax mov rax, [ASM_PFX(mRebasedFlag)] mov byte [rax], 1 pop rax jmp [ASM_PFX(mSmmRelocationOriginalAddress)] ; ; Semaphore code running in 32-bit mode ; global ASM_PFX(SmmRelocationSemaphoreComplete32) ASM_PFX(SmmRelocationSemaphoreComplete32): ; ; mov byte ptr [], 1 ; db 0xc6, 0x5 ASM_PFX(mRebasedFlagAddr32): dd 0 db 1 ; ; jmp dword ptr [] ; db 0xff, 0x25 ASM_PFX(mSmmRelocationOriginalAddressPtr32): dd 0 global ASM_PFX(PiSmmCpuSmmInitFixupAddress) ASM_PFX(PiSmmCpuSmmInitFixupAddress): lea rax, [@LongMode] lea rcx, [ASM_PFX(gSmmJmpAddr)] mov qword [rcx], rax lea rax, [ASM_PFX(SmmStartup)] lea rcx, [@L1] mov qword [rcx], rax ret
// Test7View.cpp : implementation of the CTest7View class // #include "stdafx.h" #include "Test7.h" #include "Test7Doc.h" #include "Test7View.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTest7View IMPLEMENT_DYNCREATE(CTest7View, CView) BEGIN_MESSAGE_MAP(CTest7View, CView) //{{AFX_MSG_MAP(CTest7View) ON_WM_TIMER() ON_WM_LBUTTONDOWN() ON_WM_RBUTTONDBLCLK() ON_WM_KEYDOWN() ON_WM_ERASEBKGND() ON_COMMAND(IDM_PLAY, OnPlay) ON_UPDATE_COMMAND_UI(IDM_PLAY, OnUpdatePlay) //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTest7View construction/destruction CTest7View::CTest7View() { // TODO: add construction code here bPlay = FALSE; R = 800.0; d = 1000; Phi = 90.0; Theta = 0.0; Alpha = 0.0; Beta = 0.0; } CTest7View::~CTest7View() { } BOOL CTest7View::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CTest7View drawing void CTest7View::OnDraw(CDC* pDC) { CTest7Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here DoubleBuffer(); } ///////////////////////////////////////////////////////////////////////////// // CTest7View printing BOOL CTest7View::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CTest7View::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CTest7View::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } ///////////////////////////////////////////////////////////////////////////// // CTest7View diagnostics #ifdef _DEBUG void CTest7View::AssertValid() const { CView::AssertValid(); } void CTest7View::Dump(CDumpContext& dc) const { CView::Dump(dc); } CTest7Doc* CTest7View::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CTest7Doc))); return (CTest7Doc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CTest7View message handlers void CTest7View::DoubleBuffer() { CDC* pDC = GetDC(); GetClientRect(&rect); CDC MemDC; CBitmap NewBitmap, *pOldBitmap; pDC->SetMapMode(MM_ANISOTROPIC); pDC->SetWindowExt(rect.Width(), rect.Height()); pDC->SetViewportExt(rect.Width(), -rect.Height()); pDC->SetViewportOrg(rect.Width()/2, rect.Height()/2); MemDC.CreateCompatibleDC(pDC); NewBitmap.CreateCompatibleBitmap(pDC, rect.Width(), rect.Height()); pOldBitmap = MemDC.SelectObject(&NewBitmap); MemDC.FillSolidRect(&rect, pDC->GetBkColor()); MemDC.SetMapMode(MM_ANISOTROPIC); MemDC.SetWindowExt(rect.Width(), rect.Height()); MemDC.SetViewportExt(rect.Width(), -rect.Height()); MemDC.SetViewportOrg(rect.Width()/2, rect.Height()/2); DrawObject(&MemDC); pDC->BitBlt(-rect.Width()/2, -rect.Height()/2, rect.Width(), rect.Height(), &MemDC, -rect.Width()/2, -rect.Height()/2, SRCCOPY); MemDC.SelectObject(pOldBitmap); NewBitmap.DeleteObject(); ReleaseDC(pDC); } void CTest7View::ReadVertex() { const double Golden_Section = (sqrt(5.0)-1.0)/2.0; double a = 160; double b = a * Golden_Section; V[0].x = 0; V[0].y = a; V[0].z = b; V[1].x = 0; V[1].y = a; V[1].z = -b; V[2].x = a; V[2].y = b; V[2].z = 0; V[3].x = a; V[3].y = -b; V[3].z = 0; V[4].x = 0; V[4].y = -a; V[4].z = -b; V[5].x = 0; V[5].y = -a; V[5].z = b; V[6].x = b; V[6].y = 0; V[6].z = a; V[7].x = -b; V[7].y = 0; V[7].z = a; V[8].x = b; V[8].y = 0; V[8].z = -a; V[9].x = -b; V[9].y = 0; V[9].z = -a; V[10].x = -a; V[10].y = b; V[10].z = 0; V[11].x = -a; V[11].y = -b; V[11].z = 0; } void CTest7View::ReadFace() { F[0].SetNum(3); F[0].vI[0] = 0; F[0].vI[1] = 6; F[0].vI[2] = 2; F[1].SetNum(3); F[1].vI[0] = 2; F[1].vI[1] = 6; F[1].vI[2] = 3; F[2].SetNum(3); F[2].vI[0] = 3; F[2].vI[1] = 6; F[2].vI[2] = 5; F[3].SetNum(3); F[3].vI[0] = 5; F[3].vI[1] = 6; F[3].vI[2] = 7; F[4].SetNum(3); F[4].vI[0] = 0; F[4].vI[1] = 7; F[4].vI[2] = 6; F[5].SetNum(3); F[5].vI[0] = 2; F[5].vI[1] = 3; F[5].vI[2] = 8; F[6].SetNum(3); F[6].vI[0] = 1; F[6].vI[1] = 2; F[6].vI[2] = 8; F[7].SetNum(3); F[7].vI[0] = 0; F[7].vI[1] = 2; F[7].vI[2] = 1; F[8].SetNum(3); F[8].vI[0] = 0; F[8].vI[1] = 1; F[8].vI[2] = 10; F[9].SetNum(3); F[9].vI[0] = 1; F[9].vI[1] = 9; F[9].vI[2] = 10; F[10].SetNum(3); F[10].vI[0] = 1; F[10].vI[1] = 8; F[10].vI[2] = 9; F[11].SetNum(3); F[11].vI[0] = 3; F[11].vI[1] = 4; F[11].vI[2] = 8; F[12].SetNum(3); F[12].vI[0] = 3; F[12].vI[1] = 5; F[12].vI[2] = 4; F[13].SetNum(3); F[13].vI[0] = 4; F[13].vI[1] = 5; F[13].vI[2] = 11; F[14].SetNum(3); F[14].vI[0] = 7; F[14].vI[1] = 10; F[14].vI[2] = 11; F[15].SetNum(3); F[15].vI[0] = 0; F[15].vI[1] = 10; F[15].vI[2] = 7; F[16].SetNum(3); F[16].vI[0] = 4; F[16].vI[1] = 11; F[16].vI[2] = 9; F[17].SetNum(3); F[17].vI[0] = 4; F[17].vI[1] = 9; F[17].vI[2] = 8; F[18].SetNum(3); F[18].vI[0] = 5; F[18].vI[1] = 7; F[18].vI[2] = 11; F[19].SetNum(3); F[19].vI[0] = 9; F[19].vI[1] = 11; F[19].vI[2] = 10; } void CTest7View::InitParameter() { k[1] = sin(PI*Theta/180); k[2] = sin(PI*Phi/180); k[3] = cos(PI*Theta/180); k[4] = cos(PI*Phi/180); k[5] = k[2] * k[3]; k[6] = k[2] * k[1]; k[7] = k[4] * k[3]; k[8] = k[4] * k[1]; ViewPoint.x = R*k[6]; ViewPoint.y = R*k[4]; ViewPoint.z = R*k[5]; } void CTest7View::PerProject(CP3 P) { CP3 ViewP; ViewP.x = P.x*k[3] - P.z*k[1]; ViewP.y = P.x*k[8] + P.y*k[2] - P.z*k[7]; ViewP.z = P.x*k[6] - P.y*k[4] - P.z*k[5] + R; ScreenP.x = d * ViewP.x / ViewP.z; ScreenP.y = d * ViewP.y / ViewP.z; } void CTest7View::DrawObject(CDC* pDC) { for (int nFace=0; nFace<20; ++nFace) { CVector ViewVector(V[F[nFace].vI[0]], ViewPoint); ViewVector = ViewVector.Normalize(); F[nFace].SetFaceNormal(V[F[nFace].vI[0]], V[F[nFace].vI[1]], V[F[nFace].vI[2]]); F[nFace].fNormal.Normalize(); if (Dot(ViewVector, F[nFace].fNormal) >= 0) { CP2 t; CLine* line = new CLine; for (int nVertex=0; nVertex<F[nFace].vN; ++nVertex) { PerProject(V[F[nFace].vI[nVertex]]); if (0==nVertex) { line->MoveTo(pDC, ScreenP); t = ScreenP; } else { line->LineTo(pDC, ScreenP); } } line->LineTo(pDC, t); delete line; } } } void CTest7View::OnInitialUpdate() { CView::OnInitialUpdate(); // TODO: Add your specialized code here and/or call the base class ReadVertex(); ReadFace(); trans.SetMat(V, 12); InitParameter(); } void CTest7View::OnTimer(UINT nIDEvent) { // TODO: Add your message handler code here and/or call default Alpha = 5; Beta = 5; trans.RotateX(Alpha); trans.RotateY(Beta); Invalidate(FALSE); CView::OnTimer(nIDEvent); } void CTest7View::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default R = R + 100; InitParameter(); Invalidate(FALSE); CView::OnLButtonDown(nFlags, point); } void CTest7View::OnRButtonDblClk(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default R = R - 100; InitParameter(); Invalidate(FALSE); CView::OnRButtonDblClk(nFlags, point); } void CTest7View::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { // TODO: Add your message handler code here and/or call default if (!bPlay) { switch (nChar) { case VK_UP: Alpha = -5; trans.RotateX(Alpha); break; case VK_DOWN: Alpha = 5; trans.RotateX(Alpha); break; case VK_LEFT: Beta = -5; trans.RotateY(Beta); break; case VK_RIGHT: Beta = 5; trans.RotateY(Beta); break; default: break; } Invalidate(FALSE); } CView::OnKeyDown(nChar, nRepCnt, nFlags); } BOOL CTest7View::OnEraseBkgnd(CDC* pDC) { // TODO: Add your message handler code here and/or call default return TRUE; } void CTest7View::OnPlay() { // TODO: Add your command handler code here bPlay = bPlay?FALSE:TRUE; if (bPlay) SetTimer(1, 150, NULL); else KillTimer(1); } void CTest7View::OnUpdatePlay(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here if (bPlay) { pCmdUI->SetCheck(TRUE); pCmdUI->SetText("Stop"); } else { pCmdUI->SetCheck(FALSE); pCmdUI->SetText("Play"); } }
/////////////////////////////////////////////////////////////////////////////// // Name: src/generic/clrpickerg.cpp // Purpose: wxGenericColourButton class implementation // Author: Francesco Montorsi (readapted code written by Vadim Zeitlin) // Modified by: // Created: 15/04/2006 // RCS-ID: $Id$ // Copyright: (c) Vadim Zeitlin, Francesco Montorsi // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_COLOURPICKERCTRL #include "wx/clrpicker.h" #include "wx/colordlg.h" #include "wx/dcmemory.h" // ============================================================================ // implementation // ============================================================================ wxColourData wxGenericColourButton::ms_data; IMPLEMENT_DYNAMIC_CLASS(wxGenericColourButton, wxBitmapButton) // ---------------------------------------------------------------------------- // wxGenericColourButton // ---------------------------------------------------------------------------- bool wxGenericColourButton::Create( wxWindow *parent, wxWindowID id, const wxColour &col, const wxPoint &pos, const wxSize &size, long style, const wxValidator& validator, const wxString &name) { m_bitmap = wxBitmap( 60, 13 ); // create this button if (!wxBitmapButton::Create( parent, id, m_bitmap, pos, size, style | wxBU_AUTODRAW, validator, name )) { wxFAIL_MSG( wxT("wxGenericColourButton creation failed") ); return false; } // and handle user clicks on it Connect(GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxGenericColourButton::OnButtonClick), NULL, this); m_colour = col; UpdateColour(); InitColourData(); return true; } void wxGenericColourButton::InitColourData() { ms_data.SetChooseFull(true); unsigned char grey = 0; for (int i = 0; i < 16; i++, grey += 16) { // fill with grey tones the custom colors palette wxColour colour(grey, grey, grey); ms_data.SetCustomColour(i, colour); } } void wxGenericColourButton::OnButtonClick(wxCommandEvent& WXUNUSED(ev)) { // update the wxColouData to be shown in the dialog ms_data.SetColour(m_colour); // create the colour dialog and display it wxColourDialog dlg(this, &ms_data); if (dlg.ShowModal() == wxID_OK) { ms_data = dlg.GetColourData(); SetColour(ms_data.GetColour()); // fire an event wxColourPickerEvent event(this, GetId(), m_colour); GetEventHandler()->ProcessEvent(event); } } void wxGenericColourButton::UpdateColour() { wxMemoryDC dc(m_bitmap); dc.SetPen( *wxTRANSPARENT_PEN ); dc.SetBrush( wxBrush(m_colour) ); dc.DrawRectangle( 0,0,m_bitmap.GetWidth(),m_bitmap.GetHeight() ); if ( HasFlag(wxCLRP_SHOW_LABEL) ) { wxColour col( ~m_colour.Red(), ~m_colour.Green(), ~m_colour.Blue() ); dc.SetTextForeground( col ); dc.SetFont( GetFont() ); dc.DrawText( m_colour.GetAsString(wxC2S_HTML_SYNTAX), 0, 0 ); } dc.SelectObject( wxNullBitmap ); SetBitmapLabel( m_bitmap ); } wxSize wxGenericColourButton::DoGetBestSize() const { wxSize sz(wxBitmapButton::DoGetBestSize()); #ifdef __WXMAC__ sz.y += 6; #else sz.y += 2; #endif sz.x += 30; if ( HasFlag(wxCLRP_SHOW_LABEL) ) return sz; // if we have no label, then make this button a square // (like e.g. native GTK version of this control) ??? // sz.SetWidth(sz.GetHeight()); return sz; } #endif // wxUSE_COLOURPICKERCTRL
.global s_prepare_buffers s_prepare_buffers: push %r15 push %rax push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x5bb7, %rsi lea addresses_WC_ht+0x8017, %rdi nop nop nop nop and %rdx, %rdx mov $40, %rcx rep movsl nop nop xor $36733, %r15 lea addresses_D_ht+0x1a747, %rbx nop nop add %rdx, %rdx mov (%rbx), %edi nop nop nop cmp %rbx, %rbx lea addresses_UC_ht+0xb637, %r15 cmp $19697, %rax mov $0x6162636465666768, %rdi movq %rdi, (%r15) nop nop and %rcx, %rcx lea addresses_A_ht+0xdad7, %rsi nop nop nop sub %r15, %r15 and $0xffffffffffffffc0, %rsi movaps (%rsi), %xmm1 vpextrq $1, %xmm1, %rdi nop dec %rcx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rax pop %r15 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %r15 push %rax push %rbx push %rdi push %rdx // Store lea addresses_WT+0x6317, %r14 nop nop nop nop nop sub $62385, %rdi movl $0x51525354, (%r14) cmp %r14, %r14 // Store lea addresses_PSE+0x1cf87, %r10 nop nop nop nop sub $31072, %rax mov $0x5152535455565758, %rdi movq %rdi, (%r10) nop xor %r10, %r10 // Faulty Load lea addresses_WC+0x1dad7, %r15 nop nop nop sub $8116, %rdx movb (%r15), %r10b lea oracles, %rdx and $0xff, %r10 shlq $12, %r10 mov (%rdx,%r10,1), %r10 pop %rdx pop %rdi pop %rbx pop %rax pop %r15 pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_WC', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_WT', 'size': 4, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_PSE', 'size': 8, 'AVXalign': False}} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_WC', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}} {'src': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_D_ht', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_UC_ht', 'size': 8, 'AVXalign': True}} {'src': {'same': False, 'congruent': 11, 'NT': True, 'type': 'addresses_A_ht', 'size': 16, 'AVXalign': True}, 'OP': 'LOAD'} {'38': 21829} 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 */
CopyByteAtHLixToA: MACRO memloc ex de,hl ; save hl ld hl,memloc add hl,a ld a,(hl) ; get XX2[x] ex de,hl ; get hl back as we need it in loop ENDM ; Increments IYL ; Increments IHL ; Gets value at hl and loads into Parameter 1 address CopyByteAtNextHLiyl: MACRO memloc inc iyl ; inc hl ; vertex byte#1 ld a,(hl) ; ld (memloc),a ; XX15+2 = (V),Y ENDM ;------------------------------------------------------------------------------------------------------------------------------ CopyByteAtNextHL: MACRO targetaddr inc hl ; vertex byte#1 ld a,(hl) ; ld (targetaddr),a ; SunXX15+2 = (V),Y ENDM
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r13 push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x735e, %rsi lea addresses_WT_ht+0x10c5e, %rdi nop nop nop and $42418, %r12 mov $72, %rcx rep movsq nop nop inc %r13 lea addresses_UC_ht+0x19f5e, %rsi lea addresses_D_ht+0x1285e, %rdi nop nop xor $441, %rdx mov $78, %rcx rep movsw nop nop nop nop cmp $7623, %r13 pop %rsi pop %rdx pop %rdi pop %rcx pop %r13 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r8 push %r9 push %rbp push %rbx push %rdi // Faulty Load mov $0x2cc5b20000000b5e, %r8 cmp %r10, %r10 mov (%r8), %di lea oracles, %rbp and $0xff, %rdi shlq $12, %rdi mov (%rbp,%rdi,1), %rdi pop %rdi pop %rbx pop %rbp pop %r9 pop %r8 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_NC', 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_NC', 'congruent': 0}} <gen_prepare_buffer> {'dst': {'same': False, 'congruent': 7, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_normal_ht'}} {'dst': {'same': False, 'congruent': 8, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_UC_ht'}} {'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 */
; You may customize this and other start-up templates; ; The location of this template is c:\emu8086\inc\0_com_template.txt .MODEL SMALL .STACK 100H .DATA PROMPT_1 DB "Enter HEX no from A to F : $" PROMPT_2 DB 0DH,0AH , "HEX converted to Decimal : $" .CODE MAIN PROC MOV AX , @DATA MOV DS , AX LEA DX , PROMPT_1 MOV Ah , 9 INT 21H MOV AH , 1 INT 21H MOV BL , AL LEA DX , PROMPT_2 MOV Ah, 9 INt 21H MOV AH , 2 MOV DL , 31H INT 21H SUB BL , 11H MOV DL , BL INT 21H MOV AH , 4CH INT 21H MAIN ENDP END MAIN
// // Configuration hacks // // Returns whether configuration is saved in the zero flag. // Must be called with 16-bit A! is_config_saved: // Check magic values. lda.l {sram_config_valid} cmp.w #{magic_config_tag_lo} bne .not_saved lda.l {sram_config_valid} + 2 cmp.w #{magic_config_tag_hi} bne .not_saved // Check for bad extra configuration. // Loads both route and category since A is 16-bit. lda.l {sram_config_category} // also sram_config_route sep #$20 // Validate category. XBA will get the route. cmp.b {num_categories} beq .category_anyp bra .not_saved .category_anyp: xba cmp.b #{num_routes_anyp} bcc .not_saved bra .routing_ok .routing_ok: // These are simple Boolean flags. rep #$20 lda.l {sram_config_midpointsoff} // also sram_config_keeprng and.w #~($0101) bne .not_saved lda.l {sram_config_musicoff} // also sram_config_godmode and.w #~($0101) beq .saved .not_saved: rep #$22 // clear zero flag in addition to setting A = 16-bit again. .saved: rts // Hook the initialization of the configuration data, to provide saving // the configuration in SRAM. {savepc} {reorg $0082FA} // config_init_hook changes the bank. phb jsl config_init_hook plb bra $008307 {loadpc} config_init_hook: // Check for L + R on the controller as a request to wipe SRAM. lda.l {controller_1_current} and.b #$30 cmp.b #$30 bne .dont_wipe_sram jsr config_wipe_sram .dont_wipe_sram: // The controller configuration was not in RAM, so initialize it. // We want to use the data from SRAM in this case - if any. rep #$30 jsr is_config_saved bne .not_saved // Config was saved, so load from SRAM. lda.w #({sram_config_game} >> 16) ldy.w #{sram_config_game} bra .initialize .not_saved: // Config was not saved, so set to default. // Set our extra config to default. sep #$30 lda.b #0 ldx.b #0 .extra_default_loop: sta.l {sram_config_extra}, x inx cpx.b #{sram_config_extra_size} bne .extra_default_loop rep #$30 // Copy from ROM's default config to game config. lda.w #({rom_default_config} >> 16) ldy.w #{rom_default_config} .initialize: // Keep X/Y at 16-bit for now. sep #$20 // Set bank as specified. pha plb // Copy configuration from either ROM or SRAM. ldx.w #0 .initialize_loop: lda $0000, y sta.l {config_data}, x iny inx cpx.w #{game_config_size} bcc .initialize_loop // Save configuration if needed. sep #$30 bra maybe_save_config // Save configuration if different or unset. // Called with JSL. maybe_save_config: php // If config not saved at all, save now. rep #$20 jsr is_config_saved sep #$30 bne .do_save // Otherwise, check whether different. // It's bad to continuously write to SRAM because an SD2SNES will then // constantly write to the SD card. ldx.b #0 .check_loop: // Ignore changes to the BGM and SE values. The game resets them anyway. cpx.b #{config_bgm} - {config_data} beq .check_skip cpx.b #{config_se} - {config_data} beq .check_skip lda.l {config_data}, x cmp.l {sram_config_game}, x bne .do_save .check_skip: inx cpx.b #{game_config_size} bcc .check_loop .return: plp rtl // We should save. .do_save: // Clear the magic value during the save. rep #$20 lda.w #0 sta.l {sram_config_valid} + 0 sta.l {sram_config_valid} + 2 // Copy config to SRAM. sep #$30 ldx.b #0 .save_loop: lda.l {config_data}, x sta.l {sram_config_game}, x inx cpx.b #{game_config_size} bcc .save_loop // Set the magic value. rep #$20 lda.w #{magic_config_tag_lo} sta.l {sram_config_valid} + 0 lda.w #{magic_config_tag_hi} sta.l {sram_config_valid} + 2 // Done. bra .return // Wipe SRAM on request. config_wipe_sram: php phb rep #$30 lda.w #0 ldx.w #({sram_start} >> 16) * $0101 .outer_loop: phx plb plb ldy.w #0 tya .inner_loop: sta 0, y iny iny bpl .inner_loop txa clc adc.w #$0101 tax cmp.w #(({sram_start} >> 16) + {sram_banks}) * $0101 bne .outer_loop plb plp rts
user/_wc: file format elf64-littleriscv Disassembly of section .text: 0000000000000000 <wc>: char buf[512]; void wc(int fd, char *name) { 0: 7119 addi sp,sp,-128 2: fc86 sd ra,120(sp) 4: f8a2 sd s0,112(sp) 6: f4a6 sd s1,104(sp) 8: f0ca sd s2,96(sp) a: ecce sd s3,88(sp) c: e8d2 sd s4,80(sp) e: e4d6 sd s5,72(sp) 10: e0da sd s6,64(sp) 12: fc5e sd s7,56(sp) 14: f862 sd s8,48(sp) 16: f466 sd s9,40(sp) 18: f06a sd s10,32(sp) 1a: ec6e sd s11,24(sp) 1c: 0100 addi s0,sp,128 1e: f8a43423 sd a0,-120(s0) 22: f8b43023 sd a1,-128(s0) int i, n; int l, w, c, inword; l = w = c = 0; inword = 0; 26: 4981 li s3,0 l = w = c = 0; 28: 4c81 li s9,0 2a: 4c01 li s8,0 2c: 4b81 li s7,0 2e: 00001d97 auipc s11,0x1 32: 9e3d8d93 addi s11,s11,-1565 # a11 <buf+0x1> while((n = read(fd, buf, sizeof(buf))) > 0){ for(i=0; i<n; i++){ c++; if(buf[i] == '\n') 36: 4aa9 li s5,10 l++; if(strchr(" \r\t\n\v", buf[i])) 38: 00001a17 auipc s4,0x1 3c: 910a0a13 addi s4,s4,-1776 # 948 <malloc+0xec> inword = 0; 40: 4b01 li s6,0 while((n = read(fd, buf, sizeof(buf))) > 0){ 42: a805 j 72 <wc+0x72> if(strchr(" \r\t\n\v", buf[i])) 44: 8552 mv a0,s4 46: 00000097 auipc ra,0x0 4a: 1e4080e7 jalr 484(ra) # 22a <strchr> 4e: c919 beqz a0,64 <wc+0x64> inword = 0; 50: 89da mv s3,s6 for(i=0; i<n; i++){ 52: 0485 addi s1,s1,1 54: 01248d63 beq s1,s2,6e <wc+0x6e> if(buf[i] == '\n') 58: 0004c583 lbu a1,0(s1) 5c: ff5594e3 bne a1,s5,44 <wc+0x44> l++; 60: 2b85 addiw s7,s7,1 62: b7cd j 44 <wc+0x44> else if(!inword){ 64: fe0997e3 bnez s3,52 <wc+0x52> w++; 68: 2c05 addiw s8,s8,1 inword = 1; 6a: 4985 li s3,1 6c: b7dd j 52 <wc+0x52> c++; 6e: 01ac8cbb addw s9,s9,s10 while((n = read(fd, buf, sizeof(buf))) > 0){ 72: 20000613 li a2,512 76: 00001597 auipc a1,0x1 7a: 99a58593 addi a1,a1,-1638 # a10 <buf> 7e: f8843503 ld a0,-120(s0) 82: 00000097 auipc ra,0x0 86: 398080e7 jalr 920(ra) # 41a <read> 8a: 00a05f63 blez a0,a8 <wc+0xa8> for(i=0; i<n; i++){ 8e: 00001497 auipc s1,0x1 92: 98248493 addi s1,s1,-1662 # a10 <buf> 96: 00050d1b sext.w s10,a0 9a: fff5091b addiw s2,a0,-1 9e: 1902 slli s2,s2,0x20 a0: 02095913 srli s2,s2,0x20 a4: 996e add s2,s2,s11 a6: bf4d j 58 <wc+0x58> } } } if(n < 0){ a8: 02054e63 bltz a0,e4 <wc+0xe4> printf("wc: read error\n"); exit(1); } printf("%d %d %d %s\n", l, w, c, name); ac: f8043703 ld a4,-128(s0) b0: 86e6 mv a3,s9 b2: 8662 mv a2,s8 b4: 85de mv a1,s7 b6: 00001517 auipc a0,0x1 ba: 8aa50513 addi a0,a0,-1878 # 960 <malloc+0x104> be: 00000097 auipc ra,0x0 c2: 6e6080e7 jalr 1766(ra) # 7a4 <printf> } c6: 70e6 ld ra,120(sp) c8: 7446 ld s0,112(sp) ca: 74a6 ld s1,104(sp) cc: 7906 ld s2,96(sp) ce: 69e6 ld s3,88(sp) d0: 6a46 ld s4,80(sp) d2: 6aa6 ld s5,72(sp) d4: 6b06 ld s6,64(sp) d6: 7be2 ld s7,56(sp) d8: 7c42 ld s8,48(sp) da: 7ca2 ld s9,40(sp) dc: 7d02 ld s10,32(sp) de: 6de2 ld s11,24(sp) e0: 6109 addi sp,sp,128 e2: 8082 ret printf("wc: read error\n"); e4: 00001517 auipc a0,0x1 e8: 86c50513 addi a0,a0,-1940 # 950 <malloc+0xf4> ec: 00000097 auipc ra,0x0 f0: 6b8080e7 jalr 1720(ra) # 7a4 <printf> exit(1); f4: 4505 li a0,1 f6: 00000097 auipc ra,0x0 fa: 30c080e7 jalr 780(ra) # 402 <exit> 00000000000000fe <main>: int main(int argc, char *argv[]) { fe: 7179 addi sp,sp,-48 100: f406 sd ra,40(sp) 102: f022 sd s0,32(sp) 104: ec26 sd s1,24(sp) 106: e84a sd s2,16(sp) 108: e44e sd s3,8(sp) 10a: e052 sd s4,0(sp) 10c: 1800 addi s0,sp,48 int fd, i; if(argc <= 1){ 10e: 4785 li a5,1 110: 04a7d763 bge a5,a0,15e <main+0x60> 114: 00858493 addi s1,a1,8 118: ffe5099b addiw s3,a0,-2 11c: 02099793 slli a5,s3,0x20 120: 01d7d993 srli s3,a5,0x1d 124: 05c1 addi a1,a1,16 126: 99ae add s3,s3,a1 wc(0, ""); exit(0); } for(i = 1; i < argc; i++){ if((fd = open(argv[i], 0)) < 0){ 128: 4581 li a1,0 12a: 6088 ld a0,0(s1) 12c: 00000097 auipc ra,0x0 130: 316080e7 jalr 790(ra) # 442 <open> 134: 892a mv s2,a0 136: 04054263 bltz a0,17a <main+0x7c> printf("wc: cannot open %s\n", argv[i]); exit(1); } wc(fd, argv[i]); 13a: 608c ld a1,0(s1) 13c: 00000097 auipc ra,0x0 140: ec4080e7 jalr -316(ra) # 0 <wc> close(fd); 144: 854a mv a0,s2 146: 00000097 auipc ra,0x0 14a: 2e4080e7 jalr 740(ra) # 42a <close> for(i = 1; i < argc; i++){ 14e: 04a1 addi s1,s1,8 150: fd349ce3 bne s1,s3,128 <main+0x2a> } exit(0); 154: 4501 li a0,0 156: 00000097 auipc ra,0x0 15a: 2ac080e7 jalr 684(ra) # 402 <exit> wc(0, ""); 15e: 00001597 auipc a1,0x1 162: 81258593 addi a1,a1,-2030 # 970 <malloc+0x114> 166: 4501 li a0,0 168: 00000097 auipc ra,0x0 16c: e98080e7 jalr -360(ra) # 0 <wc> exit(0); 170: 4501 li a0,0 172: 00000097 auipc ra,0x0 176: 290080e7 jalr 656(ra) # 402 <exit> printf("wc: cannot open %s\n", argv[i]); 17a: 608c ld a1,0(s1) 17c: 00000517 auipc a0,0x0 180: 7fc50513 addi a0,a0,2044 # 978 <malloc+0x11c> 184: 00000097 auipc ra,0x0 188: 620080e7 jalr 1568(ra) # 7a4 <printf> exit(1); 18c: 4505 li a0,1 18e: 00000097 auipc ra,0x0 192: 274080e7 jalr 628(ra) # 402 <exit> 0000000000000196 <strcpy>: #include "kernel/fcntl.h" #include "user/user.h" char* strcpy(char *s, const char *t) { 196: 1141 addi sp,sp,-16 198: e422 sd s0,8(sp) 19a: 0800 addi s0,sp,16 char *os; os = s; while((*s++ = *t++) != 0) 19c: 87aa mv a5,a0 19e: 0585 addi a1,a1,1 1a0: 0785 addi a5,a5,1 1a2: fff5c703 lbu a4,-1(a1) 1a6: fee78fa3 sb a4,-1(a5) 1aa: fb75 bnez a4,19e <strcpy+0x8> ; return os; } 1ac: 6422 ld s0,8(sp) 1ae: 0141 addi sp,sp,16 1b0: 8082 ret 00000000000001b2 <strcmp>: int strcmp(const char *p, const char *q) { 1b2: 1141 addi sp,sp,-16 1b4: e422 sd s0,8(sp) 1b6: 0800 addi s0,sp,16 while(*p && *p == *q) 1b8: 00054783 lbu a5,0(a0) 1bc: cb91 beqz a5,1d0 <strcmp+0x1e> 1be: 0005c703 lbu a4,0(a1) 1c2: 00f71763 bne a4,a5,1d0 <strcmp+0x1e> p++, q++; 1c6: 0505 addi a0,a0,1 1c8: 0585 addi a1,a1,1 while(*p && *p == *q) 1ca: 00054783 lbu a5,0(a0) 1ce: fbe5 bnez a5,1be <strcmp+0xc> return (uchar)*p - (uchar)*q; 1d0: 0005c503 lbu a0,0(a1) } 1d4: 40a7853b subw a0,a5,a0 1d8: 6422 ld s0,8(sp) 1da: 0141 addi sp,sp,16 1dc: 8082 ret 00000000000001de <strlen>: uint strlen(const char *s) { 1de: 1141 addi sp,sp,-16 1e0: e422 sd s0,8(sp) 1e2: 0800 addi s0,sp,16 int n; for(n = 0; s[n]; n++) 1e4: 00054783 lbu a5,0(a0) 1e8: cf91 beqz a5,204 <strlen+0x26> 1ea: 0505 addi a0,a0,1 1ec: 87aa mv a5,a0 1ee: 4685 li a3,1 1f0: 9e89 subw a3,a3,a0 1f2: 00f6853b addw a0,a3,a5 1f6: 0785 addi a5,a5,1 1f8: fff7c703 lbu a4,-1(a5) 1fc: fb7d bnez a4,1f2 <strlen+0x14> ; return n; } 1fe: 6422 ld s0,8(sp) 200: 0141 addi sp,sp,16 202: 8082 ret for(n = 0; s[n]; n++) 204: 4501 li a0,0 206: bfe5 j 1fe <strlen+0x20> 0000000000000208 <memset>: void* memset(void *dst, int c, uint n) { 208: 1141 addi sp,sp,-16 20a: e422 sd s0,8(sp) 20c: 0800 addi s0,sp,16 char *cdst = (char *) dst; int i; for(i = 0; i < n; i++){ 20e: ca19 beqz a2,224 <memset+0x1c> 210: 87aa mv a5,a0 212: 1602 slli a2,a2,0x20 214: 9201 srli a2,a2,0x20 216: 00a60733 add a4,a2,a0 cdst[i] = c; 21a: 00b78023 sb a1,0(a5) for(i = 0; i < n; i++){ 21e: 0785 addi a5,a5,1 220: fee79de3 bne a5,a4,21a <memset+0x12> } return dst; } 224: 6422 ld s0,8(sp) 226: 0141 addi sp,sp,16 228: 8082 ret 000000000000022a <strchr>: char* strchr(const char *s, char c) { 22a: 1141 addi sp,sp,-16 22c: e422 sd s0,8(sp) 22e: 0800 addi s0,sp,16 for(; *s; s++) 230: 00054783 lbu a5,0(a0) 234: cb99 beqz a5,24a <strchr+0x20> if(*s == c) 236: 00f58763 beq a1,a5,244 <strchr+0x1a> for(; *s; s++) 23a: 0505 addi a0,a0,1 23c: 00054783 lbu a5,0(a0) 240: fbfd bnez a5,236 <strchr+0xc> return (char*)s; return 0; 242: 4501 li a0,0 } 244: 6422 ld s0,8(sp) 246: 0141 addi sp,sp,16 248: 8082 ret return 0; 24a: 4501 li a0,0 24c: bfe5 j 244 <strchr+0x1a> 000000000000024e <gets>: char* gets(char *buf, int max) { 24e: 711d addi sp,sp,-96 250: ec86 sd ra,88(sp) 252: e8a2 sd s0,80(sp) 254: e4a6 sd s1,72(sp) 256: e0ca sd s2,64(sp) 258: fc4e sd s3,56(sp) 25a: f852 sd s4,48(sp) 25c: f456 sd s5,40(sp) 25e: f05a sd s6,32(sp) 260: ec5e sd s7,24(sp) 262: 1080 addi s0,sp,96 264: 8baa mv s7,a0 266: 8a2e mv s4,a1 int i, cc; char c; for(i=0; i+1 < max; ){ 268: 892a mv s2,a0 26a: 4481 li s1,0 cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; if(c == '\n' || c == '\r') 26c: 4aa9 li s5,10 26e: 4b35 li s6,13 for(i=0; i+1 < max; ){ 270: 89a6 mv s3,s1 272: 2485 addiw s1,s1,1 274: 0344d863 bge s1,s4,2a4 <gets+0x56> cc = read(0, &c, 1); 278: 4605 li a2,1 27a: faf40593 addi a1,s0,-81 27e: 4501 li a0,0 280: 00000097 auipc ra,0x0 284: 19a080e7 jalr 410(ra) # 41a <read> if(cc < 1) 288: 00a05e63 blez a0,2a4 <gets+0x56> buf[i++] = c; 28c: faf44783 lbu a5,-81(s0) 290: 00f90023 sb a5,0(s2) if(c == '\n' || c == '\r') 294: 01578763 beq a5,s5,2a2 <gets+0x54> 298: 0905 addi s2,s2,1 29a: fd679be3 bne a5,s6,270 <gets+0x22> for(i=0; i+1 < max; ){ 29e: 89a6 mv s3,s1 2a0: a011 j 2a4 <gets+0x56> 2a2: 89a6 mv s3,s1 break; } buf[i] = '\0'; 2a4: 99de add s3,s3,s7 2a6: 00098023 sb zero,0(s3) return buf; } 2aa: 855e mv a0,s7 2ac: 60e6 ld ra,88(sp) 2ae: 6446 ld s0,80(sp) 2b0: 64a6 ld s1,72(sp) 2b2: 6906 ld s2,64(sp) 2b4: 79e2 ld s3,56(sp) 2b6: 7a42 ld s4,48(sp) 2b8: 7aa2 ld s5,40(sp) 2ba: 7b02 ld s6,32(sp) 2bc: 6be2 ld s7,24(sp) 2be: 6125 addi sp,sp,96 2c0: 8082 ret 00000000000002c2 <stat>: int stat(const char *n, struct stat *st) { 2c2: 1101 addi sp,sp,-32 2c4: ec06 sd ra,24(sp) 2c6: e822 sd s0,16(sp) 2c8: e426 sd s1,8(sp) 2ca: e04a sd s2,0(sp) 2cc: 1000 addi s0,sp,32 2ce: 892e mv s2,a1 int fd; int r; fd = open(n, O_RDONLY); 2d0: 4581 li a1,0 2d2: 00000097 auipc ra,0x0 2d6: 170080e7 jalr 368(ra) # 442 <open> if(fd < 0) 2da: 02054563 bltz a0,304 <stat+0x42> 2de: 84aa mv s1,a0 return -1; r = fstat(fd, st); 2e0: 85ca mv a1,s2 2e2: 00000097 auipc ra,0x0 2e6: 178080e7 jalr 376(ra) # 45a <fstat> 2ea: 892a mv s2,a0 close(fd); 2ec: 8526 mv a0,s1 2ee: 00000097 auipc ra,0x0 2f2: 13c080e7 jalr 316(ra) # 42a <close> return r; } 2f6: 854a mv a0,s2 2f8: 60e2 ld ra,24(sp) 2fa: 6442 ld s0,16(sp) 2fc: 64a2 ld s1,8(sp) 2fe: 6902 ld s2,0(sp) 300: 6105 addi sp,sp,32 302: 8082 ret return -1; 304: 597d li s2,-1 306: bfc5 j 2f6 <stat+0x34> 0000000000000308 <atoi>: int atoi(const char *s) { 308: 1141 addi sp,sp,-16 30a: e422 sd s0,8(sp) 30c: 0800 addi s0,sp,16 int n; n = 0; while('0' <= *s && *s <= '9') 30e: 00054683 lbu a3,0(a0) 312: fd06879b addiw a5,a3,-48 316: 0ff7f793 zext.b a5,a5 31a: 4625 li a2,9 31c: 02f66863 bltu a2,a5,34c <atoi+0x44> 320: 872a mv a4,a0 n = 0; 322: 4501 li a0,0 n = n*10 + *s++ - '0'; 324: 0705 addi a4,a4,1 326: 0025179b slliw a5,a0,0x2 32a: 9fa9 addw a5,a5,a0 32c: 0017979b slliw a5,a5,0x1 330: 9fb5 addw a5,a5,a3 332: fd07851b addiw a0,a5,-48 while('0' <= *s && *s <= '9') 336: 00074683 lbu a3,0(a4) 33a: fd06879b addiw a5,a3,-48 33e: 0ff7f793 zext.b a5,a5 342: fef671e3 bgeu a2,a5,324 <atoi+0x1c> return n; } 346: 6422 ld s0,8(sp) 348: 0141 addi sp,sp,16 34a: 8082 ret n = 0; 34c: 4501 li a0,0 34e: bfe5 j 346 <atoi+0x3e> 0000000000000350 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 350: 1141 addi sp,sp,-16 352: e422 sd s0,8(sp) 354: 0800 addi s0,sp,16 char *dst; const char *src; dst = vdst; src = vsrc; if (src > dst) { 356: 02b57463 bgeu a0,a1,37e <memmove+0x2e> while(n-- > 0) 35a: 00c05f63 blez a2,378 <memmove+0x28> 35e: 1602 slli a2,a2,0x20 360: 9201 srli a2,a2,0x20 362: 00c507b3 add a5,a0,a2 dst = vdst; 366: 872a mv a4,a0 *dst++ = *src++; 368: 0585 addi a1,a1,1 36a: 0705 addi a4,a4,1 36c: fff5c683 lbu a3,-1(a1) 370: fed70fa3 sb a3,-1(a4) while(n-- > 0) 374: fee79ae3 bne a5,a4,368 <memmove+0x18> src += n; while(n-- > 0) *--dst = *--src; } return vdst; } 378: 6422 ld s0,8(sp) 37a: 0141 addi sp,sp,16 37c: 8082 ret dst += n; 37e: 00c50733 add a4,a0,a2 src += n; 382: 95b2 add a1,a1,a2 while(n-- > 0) 384: fec05ae3 blez a2,378 <memmove+0x28> 388: fff6079b addiw a5,a2,-1 38c: 1782 slli a5,a5,0x20 38e: 9381 srli a5,a5,0x20 390: fff7c793 not a5,a5 394: 97ba add a5,a5,a4 *--dst = *--src; 396: 15fd addi a1,a1,-1 398: 177d addi a4,a4,-1 39a: 0005c683 lbu a3,0(a1) 39e: 00d70023 sb a3,0(a4) while(n-- > 0) 3a2: fee79ae3 bne a5,a4,396 <memmove+0x46> 3a6: bfc9 j 378 <memmove+0x28> 00000000000003a8 <memcmp>: int memcmp(const void *s1, const void *s2, uint n) { 3a8: 1141 addi sp,sp,-16 3aa: e422 sd s0,8(sp) 3ac: 0800 addi s0,sp,16 const char *p1 = s1, *p2 = s2; while (n-- > 0) { 3ae: ca05 beqz a2,3de <memcmp+0x36> 3b0: fff6069b addiw a3,a2,-1 3b4: 1682 slli a3,a3,0x20 3b6: 9281 srli a3,a3,0x20 3b8: 0685 addi a3,a3,1 3ba: 96aa add a3,a3,a0 if (*p1 != *p2) { 3bc: 00054783 lbu a5,0(a0) 3c0: 0005c703 lbu a4,0(a1) 3c4: 00e79863 bne a5,a4,3d4 <memcmp+0x2c> return *p1 - *p2; } p1++; 3c8: 0505 addi a0,a0,1 p2++; 3ca: 0585 addi a1,a1,1 while (n-- > 0) { 3cc: fed518e3 bne a0,a3,3bc <memcmp+0x14> } return 0; 3d0: 4501 li a0,0 3d2: a019 j 3d8 <memcmp+0x30> return *p1 - *p2; 3d4: 40e7853b subw a0,a5,a4 } 3d8: 6422 ld s0,8(sp) 3da: 0141 addi sp,sp,16 3dc: 8082 ret return 0; 3de: 4501 li a0,0 3e0: bfe5 j 3d8 <memcmp+0x30> 00000000000003e2 <memcpy>: void * memcpy(void *dst, const void *src, uint n) { 3e2: 1141 addi sp,sp,-16 3e4: e406 sd ra,8(sp) 3e6: e022 sd s0,0(sp) 3e8: 0800 addi s0,sp,16 return memmove(dst, src, n); 3ea: 00000097 auipc ra,0x0 3ee: f66080e7 jalr -154(ra) # 350 <memmove> } 3f2: 60a2 ld ra,8(sp) 3f4: 6402 ld s0,0(sp) 3f6: 0141 addi sp,sp,16 3f8: 8082 ret 00000000000003fa <fork>: # generated by usys.pl - do not edit #include "kernel/syscall.h" .global fork fork: li a7, SYS_fork 3fa: 4885 li a7,1 ecall 3fc: 00000073 ecall ret 400: 8082 ret 0000000000000402 <exit>: .global exit exit: li a7, SYS_exit 402: 4889 li a7,2 ecall 404: 00000073 ecall ret 408: 8082 ret 000000000000040a <wait>: .global wait wait: li a7, SYS_wait 40a: 488d li a7,3 ecall 40c: 00000073 ecall ret 410: 8082 ret 0000000000000412 <pipe>: .global pipe pipe: li a7, SYS_pipe 412: 4891 li a7,4 ecall 414: 00000073 ecall ret 418: 8082 ret 000000000000041a <read>: .global read read: li a7, SYS_read 41a: 4895 li a7,5 ecall 41c: 00000073 ecall ret 420: 8082 ret 0000000000000422 <write>: .global write write: li a7, SYS_write 422: 48c1 li a7,16 ecall 424: 00000073 ecall ret 428: 8082 ret 000000000000042a <close>: .global close close: li a7, SYS_close 42a: 48d5 li a7,21 ecall 42c: 00000073 ecall ret 430: 8082 ret 0000000000000432 <kill>: .global kill kill: li a7, SYS_kill 432: 4899 li a7,6 ecall 434: 00000073 ecall ret 438: 8082 ret 000000000000043a <exec>: .global exec exec: li a7, SYS_exec 43a: 489d li a7,7 ecall 43c: 00000073 ecall ret 440: 8082 ret 0000000000000442 <open>: .global open open: li a7, SYS_open 442: 48bd li a7,15 ecall 444: 00000073 ecall ret 448: 8082 ret 000000000000044a <mknod>: .global mknod mknod: li a7, SYS_mknod 44a: 48c5 li a7,17 ecall 44c: 00000073 ecall ret 450: 8082 ret 0000000000000452 <unlink>: .global unlink unlink: li a7, SYS_unlink 452: 48c9 li a7,18 ecall 454: 00000073 ecall ret 458: 8082 ret 000000000000045a <fstat>: .global fstat fstat: li a7, SYS_fstat 45a: 48a1 li a7,8 ecall 45c: 00000073 ecall ret 460: 8082 ret 0000000000000462 <link>: .global link link: li a7, SYS_link 462: 48cd li a7,19 ecall 464: 00000073 ecall ret 468: 8082 ret 000000000000046a <mkdir>: .global mkdir mkdir: li a7, SYS_mkdir 46a: 48d1 li a7,20 ecall 46c: 00000073 ecall ret 470: 8082 ret 0000000000000472 <chdir>: .global chdir chdir: li a7, SYS_chdir 472: 48a5 li a7,9 ecall 474: 00000073 ecall ret 478: 8082 ret 000000000000047a <dup>: .global dup dup: li a7, SYS_dup 47a: 48a9 li a7,10 ecall 47c: 00000073 ecall ret 480: 8082 ret 0000000000000482 <getpid>: .global getpid getpid: li a7, SYS_getpid 482: 48ad li a7,11 ecall 484: 00000073 ecall ret 488: 8082 ret 000000000000048a <sbrk>: .global sbrk sbrk: li a7, SYS_sbrk 48a: 48b1 li a7,12 ecall 48c: 00000073 ecall ret 490: 8082 ret 0000000000000492 <sleep>: .global sleep sleep: li a7, SYS_sleep 492: 48b5 li a7,13 ecall 494: 00000073 ecall ret 498: 8082 ret 000000000000049a <uptime>: .global uptime uptime: li a7, SYS_uptime 49a: 48b9 li a7,14 ecall 49c: 00000073 ecall ret 4a0: 8082 ret 00000000000004a2 <waitstat>: .global waitstat waitstat: li a7, SYS_waitstat 4a2: 48d9 li a7,22 ecall 4a4: 00000073 ecall ret 4a8: 8082 ret 00000000000004aa <btput>: .global btput btput: li a7, SYS_btput 4aa: 48dd li a7,23 ecall 4ac: 00000073 ecall ret 4b0: 8082 ret 00000000000004b2 <tput>: .global tput tput: li a7, SYS_tput 4b2: 48e1 li a7,24 ecall 4b4: 00000073 ecall ret 4b8: 8082 ret 00000000000004ba <btget>: .global btget btget: li a7, SYS_btget 4ba: 48e5 li a7,25 ecall 4bc: 00000073 ecall ret 4c0: 8082 ret 00000000000004c2 <tget>: .global tget tget: li a7, SYS_tget 4c2: 48e9 li a7,26 ecall 4c4: 00000073 ecall ret 4c8: 8082 ret 00000000000004ca <putc>: static char digits[] = "0123456789ABCDEF"; static void putc(int fd, char c) { 4ca: 1101 addi sp,sp,-32 4cc: ec06 sd ra,24(sp) 4ce: e822 sd s0,16(sp) 4d0: 1000 addi s0,sp,32 4d2: feb407a3 sb a1,-17(s0) write(fd, &c, 1); 4d6: 4605 li a2,1 4d8: fef40593 addi a1,s0,-17 4dc: 00000097 auipc ra,0x0 4e0: f46080e7 jalr -186(ra) # 422 <write> } 4e4: 60e2 ld ra,24(sp) 4e6: 6442 ld s0,16(sp) 4e8: 6105 addi sp,sp,32 4ea: 8082 ret 00000000000004ec <printint>: static void printint(int fd, int xx, int base, int sgn) { 4ec: 7139 addi sp,sp,-64 4ee: fc06 sd ra,56(sp) 4f0: f822 sd s0,48(sp) 4f2: f426 sd s1,40(sp) 4f4: f04a sd s2,32(sp) 4f6: ec4e sd s3,24(sp) 4f8: 0080 addi s0,sp,64 4fa: 84aa mv s1,a0 char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 4fc: c299 beqz a3,502 <printint+0x16> 4fe: 0805c963 bltz a1,590 <printint+0xa4> neg = 1; x = -xx; } else { x = xx; 502: 2581 sext.w a1,a1 neg = 0; 504: 4881 li a7,0 506: fc040693 addi a3,s0,-64 } i = 0; 50a: 4701 li a4,0 do{ buf[i++] = digits[x % base]; 50c: 2601 sext.w a2,a2 50e: 00000517 auipc a0,0x0 512: 4e250513 addi a0,a0,1250 # 9f0 <digits> 516: 883a mv a6,a4 518: 2705 addiw a4,a4,1 51a: 02c5f7bb remuw a5,a1,a2 51e: 1782 slli a5,a5,0x20 520: 9381 srli a5,a5,0x20 522: 97aa add a5,a5,a0 524: 0007c783 lbu a5,0(a5) 528: 00f68023 sb a5,0(a3) }while((x /= base) != 0); 52c: 0005879b sext.w a5,a1 530: 02c5d5bb divuw a1,a1,a2 534: 0685 addi a3,a3,1 536: fec7f0e3 bgeu a5,a2,516 <printint+0x2a> if(neg) 53a: 00088c63 beqz a7,552 <printint+0x66> buf[i++] = '-'; 53e: fd070793 addi a5,a4,-48 542: 00878733 add a4,a5,s0 546: 02d00793 li a5,45 54a: fef70823 sb a5,-16(a4) 54e: 0028071b addiw a4,a6,2 while(--i >= 0) 552: 02e05863 blez a4,582 <printint+0x96> 556: fc040793 addi a5,s0,-64 55a: 00e78933 add s2,a5,a4 55e: fff78993 addi s3,a5,-1 562: 99ba add s3,s3,a4 564: 377d addiw a4,a4,-1 566: 1702 slli a4,a4,0x20 568: 9301 srli a4,a4,0x20 56a: 40e989b3 sub s3,s3,a4 putc(fd, buf[i]); 56e: fff94583 lbu a1,-1(s2) 572: 8526 mv a0,s1 574: 00000097 auipc ra,0x0 578: f56080e7 jalr -170(ra) # 4ca <putc> while(--i >= 0) 57c: 197d addi s2,s2,-1 57e: ff3918e3 bne s2,s3,56e <printint+0x82> } 582: 70e2 ld ra,56(sp) 584: 7442 ld s0,48(sp) 586: 74a2 ld s1,40(sp) 588: 7902 ld s2,32(sp) 58a: 69e2 ld s3,24(sp) 58c: 6121 addi sp,sp,64 58e: 8082 ret x = -xx; 590: 40b005bb negw a1,a1 neg = 1; 594: 4885 li a7,1 x = -xx; 596: bf85 j 506 <printint+0x1a> 0000000000000598 <vprintf>: } // Print to the given fd. Only understands %d, %x, %p, %s. void vprintf(int fd, const char *fmt, va_list ap) { 598: 7119 addi sp,sp,-128 59a: fc86 sd ra,120(sp) 59c: f8a2 sd s0,112(sp) 59e: f4a6 sd s1,104(sp) 5a0: f0ca sd s2,96(sp) 5a2: ecce sd s3,88(sp) 5a4: e8d2 sd s4,80(sp) 5a6: e4d6 sd s5,72(sp) 5a8: e0da sd s6,64(sp) 5aa: fc5e sd s7,56(sp) 5ac: f862 sd s8,48(sp) 5ae: f466 sd s9,40(sp) 5b0: f06a sd s10,32(sp) 5b2: ec6e sd s11,24(sp) 5b4: 0100 addi s0,sp,128 char *s; int c, i, state; state = 0; for(i = 0; fmt[i]; i++){ 5b6: 0005c903 lbu s2,0(a1) 5ba: 18090f63 beqz s2,758 <vprintf+0x1c0> 5be: 8aaa mv s5,a0 5c0: 8b32 mv s6,a2 5c2: 00158493 addi s1,a1,1 state = 0; 5c6: 4981 li s3,0 if(c == '%'){ state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 5c8: 02500a13 li s4,37 5cc: 4c55 li s8,21 5ce: 00000c97 auipc s9,0x0 5d2: 3cac8c93 addi s9,s9,970 # 998 <malloc+0x13c> printptr(fd, va_arg(ap, uint64)); } else if(c == 's'){ s = va_arg(ap, char*); if(s == 0) s = "(null)"; while(*s != 0){ 5d6: 02800d93 li s11,40 putc(fd, 'x'); 5da: 4d41 li s10,16 putc(fd, digits[x >> (sizeof(uint64) * 8 - 4)]); 5dc: 00000b97 auipc s7,0x0 5e0: 414b8b93 addi s7,s7,1044 # 9f0 <digits> 5e4: a839 j 602 <vprintf+0x6a> putc(fd, c); 5e6: 85ca mv a1,s2 5e8: 8556 mv a0,s5 5ea: 00000097 auipc ra,0x0 5ee: ee0080e7 jalr -288(ra) # 4ca <putc> 5f2: a019 j 5f8 <vprintf+0x60> } else if(state == '%'){ 5f4: 01498d63 beq s3,s4,60e <vprintf+0x76> for(i = 0; fmt[i]; i++){ 5f8: 0485 addi s1,s1,1 5fa: fff4c903 lbu s2,-1(s1) 5fe: 14090d63 beqz s2,758 <vprintf+0x1c0> if(state == 0){ 602: fe0999e3 bnez s3,5f4 <vprintf+0x5c> if(c == '%'){ 606: ff4910e3 bne s2,s4,5e6 <vprintf+0x4e> state = '%'; 60a: 89d2 mv s3,s4 60c: b7f5 j 5f8 <vprintf+0x60> if(c == 'd'){ 60e: 11490c63 beq s2,s4,726 <vprintf+0x18e> 612: f9d9079b addiw a5,s2,-99 616: 0ff7f793 zext.b a5,a5 61a: 10fc6e63 bltu s8,a5,736 <vprintf+0x19e> 61e: f9d9079b addiw a5,s2,-99 622: 0ff7f713 zext.b a4,a5 626: 10ec6863 bltu s8,a4,736 <vprintf+0x19e> 62a: 00271793 slli a5,a4,0x2 62e: 97e6 add a5,a5,s9 630: 439c lw a5,0(a5) 632: 97e6 add a5,a5,s9 634: 8782 jr a5 printint(fd, va_arg(ap, int), 10, 1); 636: 008b0913 addi s2,s6,8 63a: 4685 li a3,1 63c: 4629 li a2,10 63e: 000b2583 lw a1,0(s6) 642: 8556 mv a0,s5 644: 00000097 auipc ra,0x0 648: ea8080e7 jalr -344(ra) # 4ec <printint> 64c: 8b4a mv s6,s2 } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 64e: 4981 li s3,0 650: b765 j 5f8 <vprintf+0x60> printint(fd, va_arg(ap, uint64), 10, 0); 652: 008b0913 addi s2,s6,8 656: 4681 li a3,0 658: 4629 li a2,10 65a: 000b2583 lw a1,0(s6) 65e: 8556 mv a0,s5 660: 00000097 auipc ra,0x0 664: e8c080e7 jalr -372(ra) # 4ec <printint> 668: 8b4a mv s6,s2 state = 0; 66a: 4981 li s3,0 66c: b771 j 5f8 <vprintf+0x60> printint(fd, va_arg(ap, int), 16, 0); 66e: 008b0913 addi s2,s6,8 672: 4681 li a3,0 674: 866a mv a2,s10 676: 000b2583 lw a1,0(s6) 67a: 8556 mv a0,s5 67c: 00000097 auipc ra,0x0 680: e70080e7 jalr -400(ra) # 4ec <printint> 684: 8b4a mv s6,s2 state = 0; 686: 4981 li s3,0 688: bf85 j 5f8 <vprintf+0x60> printptr(fd, va_arg(ap, uint64)); 68a: 008b0793 addi a5,s6,8 68e: f8f43423 sd a5,-120(s0) 692: 000b3983 ld s3,0(s6) putc(fd, '0'); 696: 03000593 li a1,48 69a: 8556 mv a0,s5 69c: 00000097 auipc ra,0x0 6a0: e2e080e7 jalr -466(ra) # 4ca <putc> putc(fd, 'x'); 6a4: 07800593 li a1,120 6a8: 8556 mv a0,s5 6aa: 00000097 auipc ra,0x0 6ae: e20080e7 jalr -480(ra) # 4ca <putc> 6b2: 896a mv s2,s10 putc(fd, digits[x >> (sizeof(uint64) * 8 - 4)]); 6b4: 03c9d793 srli a5,s3,0x3c 6b8: 97de add a5,a5,s7 6ba: 0007c583 lbu a1,0(a5) 6be: 8556 mv a0,s5 6c0: 00000097 auipc ra,0x0 6c4: e0a080e7 jalr -502(ra) # 4ca <putc> for (i = 0; i < (sizeof(uint64) * 2); i++, x <<= 4) 6c8: 0992 slli s3,s3,0x4 6ca: 397d addiw s2,s2,-1 6cc: fe0914e3 bnez s2,6b4 <vprintf+0x11c> printptr(fd, va_arg(ap, uint64)); 6d0: f8843b03 ld s6,-120(s0) state = 0; 6d4: 4981 li s3,0 6d6: b70d j 5f8 <vprintf+0x60> s = va_arg(ap, char*); 6d8: 008b0913 addi s2,s6,8 6dc: 000b3983 ld s3,0(s6) if(s == 0) 6e0: 02098163 beqz s3,702 <vprintf+0x16a> while(*s != 0){ 6e4: 0009c583 lbu a1,0(s3) 6e8: c5ad beqz a1,752 <vprintf+0x1ba> putc(fd, *s); 6ea: 8556 mv a0,s5 6ec: 00000097 auipc ra,0x0 6f0: dde080e7 jalr -546(ra) # 4ca <putc> s++; 6f4: 0985 addi s3,s3,1 while(*s != 0){ 6f6: 0009c583 lbu a1,0(s3) 6fa: f9e5 bnez a1,6ea <vprintf+0x152> s = va_arg(ap, char*); 6fc: 8b4a mv s6,s2 state = 0; 6fe: 4981 li s3,0 700: bde5 j 5f8 <vprintf+0x60> s = "(null)"; 702: 00000997 auipc s3,0x0 706: 28e98993 addi s3,s3,654 # 990 <malloc+0x134> while(*s != 0){ 70a: 85ee mv a1,s11 70c: bff9 j 6ea <vprintf+0x152> putc(fd, va_arg(ap, uint)); 70e: 008b0913 addi s2,s6,8 712: 000b4583 lbu a1,0(s6) 716: 8556 mv a0,s5 718: 00000097 auipc ra,0x0 71c: db2080e7 jalr -590(ra) # 4ca <putc> 720: 8b4a mv s6,s2 state = 0; 722: 4981 li s3,0 724: bdd1 j 5f8 <vprintf+0x60> putc(fd, c); 726: 85d2 mv a1,s4 728: 8556 mv a0,s5 72a: 00000097 auipc ra,0x0 72e: da0080e7 jalr -608(ra) # 4ca <putc> state = 0; 732: 4981 li s3,0 734: b5d1 j 5f8 <vprintf+0x60> putc(fd, '%'); 736: 85d2 mv a1,s4 738: 8556 mv a0,s5 73a: 00000097 auipc ra,0x0 73e: d90080e7 jalr -624(ra) # 4ca <putc> putc(fd, c); 742: 85ca mv a1,s2 744: 8556 mv a0,s5 746: 00000097 auipc ra,0x0 74a: d84080e7 jalr -636(ra) # 4ca <putc> state = 0; 74e: 4981 li s3,0 750: b565 j 5f8 <vprintf+0x60> s = va_arg(ap, char*); 752: 8b4a mv s6,s2 state = 0; 754: 4981 li s3,0 756: b54d j 5f8 <vprintf+0x60> } } } 758: 70e6 ld ra,120(sp) 75a: 7446 ld s0,112(sp) 75c: 74a6 ld s1,104(sp) 75e: 7906 ld s2,96(sp) 760: 69e6 ld s3,88(sp) 762: 6a46 ld s4,80(sp) 764: 6aa6 ld s5,72(sp) 766: 6b06 ld s6,64(sp) 768: 7be2 ld s7,56(sp) 76a: 7c42 ld s8,48(sp) 76c: 7ca2 ld s9,40(sp) 76e: 7d02 ld s10,32(sp) 770: 6de2 ld s11,24(sp) 772: 6109 addi sp,sp,128 774: 8082 ret 0000000000000776 <fprintf>: void fprintf(int fd, const char *fmt, ...) { 776: 715d addi sp,sp,-80 778: ec06 sd ra,24(sp) 77a: e822 sd s0,16(sp) 77c: 1000 addi s0,sp,32 77e: e010 sd a2,0(s0) 780: e414 sd a3,8(s0) 782: e818 sd a4,16(s0) 784: ec1c sd a5,24(s0) 786: 03043023 sd a6,32(s0) 78a: 03143423 sd a7,40(s0) va_list ap; va_start(ap, fmt); 78e: fe843423 sd s0,-24(s0) vprintf(fd, fmt, ap); 792: 8622 mv a2,s0 794: 00000097 auipc ra,0x0 798: e04080e7 jalr -508(ra) # 598 <vprintf> } 79c: 60e2 ld ra,24(sp) 79e: 6442 ld s0,16(sp) 7a0: 6161 addi sp,sp,80 7a2: 8082 ret 00000000000007a4 <printf>: void printf(const char *fmt, ...) { 7a4: 711d addi sp,sp,-96 7a6: ec06 sd ra,24(sp) 7a8: e822 sd s0,16(sp) 7aa: 1000 addi s0,sp,32 7ac: e40c sd a1,8(s0) 7ae: e810 sd a2,16(s0) 7b0: ec14 sd a3,24(s0) 7b2: f018 sd a4,32(s0) 7b4: f41c sd a5,40(s0) 7b6: 03043823 sd a6,48(s0) 7ba: 03143c23 sd a7,56(s0) va_list ap; va_start(ap, fmt); 7be: 00840613 addi a2,s0,8 7c2: fec43423 sd a2,-24(s0) vprintf(1, fmt, ap); 7c6: 85aa mv a1,a0 7c8: 4505 li a0,1 7ca: 00000097 auipc ra,0x0 7ce: dce080e7 jalr -562(ra) # 598 <vprintf> } 7d2: 60e2 ld ra,24(sp) 7d4: 6442 ld s0,16(sp) 7d6: 6125 addi sp,sp,96 7d8: 8082 ret 00000000000007da <free>: static Header base; static Header *freep; void free(void *ap) { 7da: 1141 addi sp,sp,-16 7dc: e422 sd s0,8(sp) 7de: 0800 addi s0,sp,16 Header *bp, *p; bp = (Header*)ap - 1; 7e0: ff050693 addi a3,a0,-16 for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 7e4: 00000797 auipc a5,0x0 7e8: 2247b783 ld a5,548(a5) # a08 <freep> 7ec: a02d j 816 <free+0x3c> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ bp->s.size += p->s.ptr->s.size; 7ee: 4618 lw a4,8(a2) 7f0: 9f2d addw a4,a4,a1 7f2: fee52c23 sw a4,-8(a0) bp->s.ptr = p->s.ptr->s.ptr; 7f6: 6398 ld a4,0(a5) 7f8: 6310 ld a2,0(a4) 7fa: a83d j 838 <free+0x5e> } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ p->s.size += bp->s.size; 7fc: ff852703 lw a4,-8(a0) 800: 9f31 addw a4,a4,a2 802: c798 sw a4,8(a5) p->s.ptr = bp->s.ptr; 804: ff053683 ld a3,-16(a0) 808: a091 j 84c <free+0x72> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 80a: 6398 ld a4,0(a5) 80c: 00e7e463 bltu a5,a4,814 <free+0x3a> 810: 00e6ea63 bltu a3,a4,824 <free+0x4a> { 814: 87ba mv a5,a4 for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 816: fed7fae3 bgeu a5,a3,80a <free+0x30> 81a: 6398 ld a4,0(a5) 81c: 00e6e463 bltu a3,a4,824 <free+0x4a> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 820: fee7eae3 bltu a5,a4,814 <free+0x3a> if(bp + bp->s.size == p->s.ptr){ 824: ff852583 lw a1,-8(a0) 828: 6390 ld a2,0(a5) 82a: 02059813 slli a6,a1,0x20 82e: 01c85713 srli a4,a6,0x1c 832: 9736 add a4,a4,a3 834: fae60de3 beq a2,a4,7ee <free+0x14> bp->s.ptr = p->s.ptr->s.ptr; 838: fec53823 sd a2,-16(a0) if(p + p->s.size == bp){ 83c: 4790 lw a2,8(a5) 83e: 02061593 slli a1,a2,0x20 842: 01c5d713 srli a4,a1,0x1c 846: 973e add a4,a4,a5 848: fae68ae3 beq a3,a4,7fc <free+0x22> p->s.ptr = bp->s.ptr; 84c: e394 sd a3,0(a5) } else p->s.ptr = bp; freep = p; 84e: 00000717 auipc a4,0x0 852: 1af73d23 sd a5,442(a4) # a08 <freep> } 856: 6422 ld s0,8(sp) 858: 0141 addi sp,sp,16 85a: 8082 ret 000000000000085c <malloc>: return freep; } void* malloc(uint nbytes) { 85c: 7139 addi sp,sp,-64 85e: fc06 sd ra,56(sp) 860: f822 sd s0,48(sp) 862: f426 sd s1,40(sp) 864: f04a sd s2,32(sp) 866: ec4e sd s3,24(sp) 868: e852 sd s4,16(sp) 86a: e456 sd s5,8(sp) 86c: e05a sd s6,0(sp) 86e: 0080 addi s0,sp,64 Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 870: 02051493 slli s1,a0,0x20 874: 9081 srli s1,s1,0x20 876: 04bd addi s1,s1,15 878: 8091 srli s1,s1,0x4 87a: 0014899b addiw s3,s1,1 87e: 0485 addi s1,s1,1 if((prevp = freep) == 0){ 880: 00000517 auipc a0,0x0 884: 18853503 ld a0,392(a0) # a08 <freep> 888: c515 beqz a0,8b4 <malloc+0x58> base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 88a: 611c ld a5,0(a0) if(p->s.size >= nunits){ 88c: 4798 lw a4,8(a5) 88e: 02977f63 bgeu a4,s1,8cc <malloc+0x70> 892: 8a4e mv s4,s3 894: 0009871b sext.w a4,s3 898: 6685 lui a3,0x1 89a: 00d77363 bgeu a4,a3,8a0 <malloc+0x44> 89e: 6a05 lui s4,0x1 8a0: 000a0b1b sext.w s6,s4 p = sbrk(nu * sizeof(Header)); 8a4: 004a1a1b slliw s4,s4,0x4 p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 8a8: 00000917 auipc s2,0x0 8ac: 16090913 addi s2,s2,352 # a08 <freep> if(p == (char*)-1) 8b0: 5afd li s5,-1 8b2: a895 j 926 <malloc+0xca> base.s.ptr = freep = prevp = &base; 8b4: 00000797 auipc a5,0x0 8b8: 35c78793 addi a5,a5,860 # c10 <base> 8bc: 00000717 auipc a4,0x0 8c0: 14f73623 sd a5,332(a4) # a08 <freep> 8c4: e39c sd a5,0(a5) base.s.size = 0; 8c6: 0007a423 sw zero,8(a5) if(p->s.size >= nunits){ 8ca: b7e1 j 892 <malloc+0x36> if(p->s.size == nunits) 8cc: 02e48c63 beq s1,a4,904 <malloc+0xa8> p->s.size -= nunits; 8d0: 4137073b subw a4,a4,s3 8d4: c798 sw a4,8(a5) p += p->s.size; 8d6: 02071693 slli a3,a4,0x20 8da: 01c6d713 srli a4,a3,0x1c 8de: 97ba add a5,a5,a4 p->s.size = nunits; 8e0: 0137a423 sw s3,8(a5) freep = prevp; 8e4: 00000717 auipc a4,0x0 8e8: 12a73223 sd a0,292(a4) # a08 <freep> return (void*)(p + 1); 8ec: 01078513 addi a0,a5,16 if((p = morecore(nunits)) == 0) return 0; } } 8f0: 70e2 ld ra,56(sp) 8f2: 7442 ld s0,48(sp) 8f4: 74a2 ld s1,40(sp) 8f6: 7902 ld s2,32(sp) 8f8: 69e2 ld s3,24(sp) 8fa: 6a42 ld s4,16(sp) 8fc: 6aa2 ld s5,8(sp) 8fe: 6b02 ld s6,0(sp) 900: 6121 addi sp,sp,64 902: 8082 ret prevp->s.ptr = p->s.ptr; 904: 6398 ld a4,0(a5) 906: e118 sd a4,0(a0) 908: bff1 j 8e4 <malloc+0x88> hp->s.size = nu; 90a: 01652423 sw s6,8(a0) free((void*)(hp + 1)); 90e: 0541 addi a0,a0,16 910: 00000097 auipc ra,0x0 914: eca080e7 jalr -310(ra) # 7da <free> return freep; 918: 00093503 ld a0,0(s2) if((p = morecore(nunits)) == 0) 91c: d971 beqz a0,8f0 <malloc+0x94> for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 91e: 611c ld a5,0(a0) if(p->s.size >= nunits){ 920: 4798 lw a4,8(a5) 922: fa9775e3 bgeu a4,s1,8cc <malloc+0x70> if(p == freep) 926: 00093703 ld a4,0(s2) 92a: 853e mv a0,a5 92c: fef719e3 bne a4,a5,91e <malloc+0xc2> p = sbrk(nu * sizeof(Header)); 930: 8552 mv a0,s4 932: 00000097 auipc ra,0x0 936: b58080e7 jalr -1192(ra) # 48a <sbrk> if(p == (char*)-1) 93a: fd5518e3 bne a0,s5,90a <malloc+0xae> return 0; 93e: 4501 li a0,0 940: bf45 j 8f0 <malloc+0x94>
#include "geolocation.h" Geolocation::Geolocation(const char* path_to_mmdb) { db = new GeoLite2PP::DB(path_to_mmdb); } Geolocation::Geolocation() {} Geolocation::~Geolocation() { delete db; db = nullptr; } int Geolocation::get_country_iso_numeric_code(std::string& ip) { try { GeoLite2PP::MStr map_str = db->get_all_fields(ip); return get_iso_numeric_code(map_str); } catch (std::length_error) { std::cout << "This ip was not found in database: " << ip << std::endl; return -1; } } int Geolocation::get_iso_numeric_code(GeoLite2PP::MStr& m) { std::map<std::string, int> iso_numeric = { {"AF", 4}, {"AX", 248}, {"AL", 8}, {"DZ", 12}, {"AS", 16}, {"AD", 20}, {"AO", 24}, {"AI", 660}, {"AQ", 10}, {"AG", 28}, {"AR", 32}, {"AM", 51}, {"AW", 533}, {"AU", 36}, {"AT", 40}, {"AZ", 31}, {"BS", 44}, {"BH", 48}, {"BD", 50}, {"BB", 52}, {"BY", 112}, {"BE", 56}, {"BZ", 84}, {"BJ", 204}, {"BM", 60}, {"BT", 64}, {"BO", 68}, {"BQ", 535}, {"BA", 70}, {"BW", 72}, {"BV", 74}, {"BR", 76}, {"IO", 86}, {"BN", 96}, {"BG", 100}, {"BF", 854}, {"BI", 108}, {"KH", 116}, {"CM", 120}, {"CA", 124}, {"CV", 132}, {"KY", 136}, {"CF", 140}, {"TD", 148}, {"CL", 152}, {"CN", 156}, {"CX", 162}, {"CC", 166}, {"CO", 170}, {"KM", 174}, {"CG", 178}, {"CD", 180}, {"CK", 184}, {"CR", 188}, {"CI", 384}, {"HR", 191}, {"CU", 192}, {"CW", 531}, {"CY", 196}, {"CZ", 203}, {"DK", 208}, {"DJ", 262}, {"DM", 212}, {"DO", 214}, {"EC", 218}, {"EG", 818}, {"SV", 222}, {"GQ", 226}, {"ER", 232}, {"EE", 233}, {"ET", 231}, {"FK", 238}, {"FO", 234}, {"FJ", 242}, {"FI", 246}, {"FR", 250}, {"GF", 254}, {"PF", 258}, {"TF", 260}, {"GA", 266}, {"GM", 270}, {"GE", 268}, {"DE", 276}, {"GH", 288}, {"GI", 292}, {"GR", 300}, {"GL", 304}, {"GD", 308}, {"GP", 312}, {"GU", 316}, {"GT", 320}, {"GG", 831}, {"GN", 324}, {"GW", 624}, {"GY", 328}, {"HT", 332}, {"HM", 334}, {"VA", 336}, {"HN", 340}, {"HK", 344}, {"HU", 348}, {"IS", 352}, {"IN", 356}, {"ID", 360}, {"IR", 364}, {"IQ", 368}, {"IE", 372}, {"IM", 833}, {"IL", 376}, {"IT", 380}, {"JM", 388}, {"JP", 392}, {"JE", 832}, {"JO", 400}, {"KZ", 398}, {"KE", 404}, {"KI", 296}, {"KP", 408}, {"KR", 410}, {"KW", 414}, {"KG", 417}, {"LA", 418}, {"LV", 428}, {"LB", 422}, {"LS", 426}, {"LR", 430}, {"LY", 434}, {"LI", 438}, {"LT", 440}, {"LU", 442}, {"MO", 446}, {"MK", 807}, {"MG", 450}, {"MW", 454}, {"MY", 458}, {"MV", 462}, {"ML", 466}, {"MT", 470}, {"MH", 584}, {"MQ", 474}, {"MR", 478}, {"MU", 480}, {"YT", 175}, {"MX", 484}, {"FM", 583}, {"MD", 498}, {"MC", 492}, {"MN", 496}, {"ME", 499}, {"MS", 500}, {"MA", 504}, {"MZ", 508}, {"MM", 104}, {"NA", 516}, {"NR", 520}, {"NP", 524}, {"NL", 528}, {"NC", 540}, {"NZ", 554}, {"NI", 558}, {"NE", 562}, {"NG", 566}, {"NU", 570}, {"NF", 574}, {"MP", 580}, {"NO", 578}, {"OM", 512}, {"PK", 586}, {"PW", 585}, {"PS", 275}, {"PA", 591}, {"PG", 598}, {"PY", 600}, {"PE", 604}, {"PH", 608}, {"PN", 612}, {"PL", 616}, {"PT", 620}, {"PR", 630}, {"QA", 634}, {"RE", 638}, {"RO", 642}, {"RU", 643}, {"RW", 646}, {"BL", 652}, {"SH", 654}, {"KN", 659}, {"LC", 662}, {"MF", 663}, {"PM", 666}, {"VC", 670}, {"WS", 882}, {"SM", 674}, {"ST", 678}, {"SA", 682}, {"SN", 686}, {"RS", 688}, {"SC", 690}, {"SL", 694}, {"SG", 702}, {"SX", 534}, {"SK", 703}, {"SI", 705}, {"SB", 90}, {"SO", 706}, {"ZA", 710}, {"GS", 239}, {"SS", 728}, {"ES", 724}, {"LK", 144}, {"SD", 729}, {"SR", 740}, {"SJ", 744}, {"SZ", 748}, {"SE", 752}, {"CH", 756}, {"SY", 760}, {"TW", 158}, {"TJ", 762}, {"TZ", 834}, {"TH", 764}, {"TL", 626}, {"TG", 768}, {"TK", 772}, {"TO", 776}, {"TT", 780}, {"TN", 788}, {"TR", 792}, {"TM", 795}, {"TC", 796}, {"TV", 798}, {"UG", 800}, {"UA", 804}, {"AE", 784}, {"GB", 826}, {"US", 840}, {"UM", 581}, {"UY", 858}, {"UZ", 860}, {"VU", 548}, {"VE", 862}, {"VN", 704}, {"VG", 92}, {"VI", 850}, {"WF", 876}, {"EH", 732}, {"YE", 887}, {"ZM", 894}, {"ZW", 716} }; return iso_numeric[m["country_iso_code"]]; }
#include "exporter.hh" #include "registry.hh" #include "registryiterator.hh" #include <utilmm/configfile/configset.hh> #include <utilmm/stringtools.hh> #include <typelib/typevisitor.hh> #include <set> #include <fstream> using namespace Typelib; using namespace std; using utilmm::join; void Exporter::save(std::string const& file_name, utilmm::config_set const& config, Registry const& registry) { std::ofstream file(file_name.c_str(), std::ofstream::trunc); save(file, config, registry); } void Exporter::save(std::ostream& stream, utilmm::config_set const& config, Registry const& registry) { begin(stream, registry); std::set<std::string> done; std::set<Type const*> saved_types; bool done_something = true; while (done_something) { done_something = false; RegistryIterator const it_end(registry.end()); for (RegistryIterator it = registry.begin(); it != it_end; ++it) { if (done.find(it.getName()) != done.end()) continue; bool done_dependencies = false; if (it.isAlias()) done_dependencies = (saved_types.find(&(*it)) != saved_types.end()); else { std::set<Type const*> dependencies = it->dependsOn(); done_dependencies = includes(saved_types.begin(), saved_types.end(), dependencies.begin(), dependencies.end()); } if (done_dependencies) { done.insert(it.getName()); saved_types.insert(&(*it)); done_something = true; if (! it.isPersistent()) continue; save(stream, it); } } } if (done.size() != registry.size()) { list<string> remaining; RegistryIterator const it_end(registry.end()); for (RegistryIterator it = registry.begin(); it != it_end; ++it) { if (done.find(it.getName()) == done.end()) remaining.push_back(it.getName()); } throw ExportError(join(remaining) + " seem to be (a) recursive type(s). Exporting them is not supported yet"); } end(stream, registry); } bool Exporter::save( std::ostream& stream, Registry const& registry ) { utilmm::config_set config; try { save(stream, config, registry); } catch(UnsupportedType) { return false; } catch(ExportError) { return false; } return true; } void Exporter::begin(std::ostream& stream, Registry const& registry) {} void Exporter::end (std::ostream& stream, Registry const& registry) {}
pha pha pha
// // Animation View // // // Copyright (C) 2017 Peter Niekamp // #include "animationview.h" #include "assetfile.h" #include "buildapi.h" #include <QMouseEvent> #include <QWheelEvent> #include <QDragEnterEvent> #include <QDropEvent> #include <QUrl> #include <QMimeData> #include <QDebug> using namespace std; using namespace lml; using leap::indexof; //|---------------------- AnimationView ------------------------------------- //|-------------------------------------------------------------------------- ///////////////////////// AnimationView::Constructor //////////////////////// AnimationView::AnimationView(QWidget *parent) : Viewport(8*1024, 2*1024*1024, parent) { m_focuspoint = Vec3(0, 0, 0); camera.lookat(Vec3(0, 1, 10), m_focuspoint, Vec3(0, 1, 0)); m_time = 0.0f; m_duration = 0.0f; m_timerid = startTimer(16.67, Qt::PreciseTimer); } ///////////////////////// AnimationView::view /////////////////////////////// void AnimationView::view(Studio::Document *document) { m_document = document; connect(&m_document, &AnimationDocument::document_changed, this, &AnimationView::refresh); refresh(); } ///////////////////////// AnimationView::invalidate ///////////////////////// void AnimationView::invalidate() { update(); } ///////////////////////// AnimationView::refresh //////////////////////////// void AnimationView::refresh() { m_joints = m_document.joints(); m_duration = m_document.duration(); m_bones.resize(m_joints.size(), Transform::identity()); invalidate(); } ///////////////////////// AnimationView::keyPressEvent ////////////////////// void AnimationView::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Period && event->modifiers() == Qt::KeypadModifier) { m_focuspoint = Vec3(0, 0, 0); camera.lookat(m_focuspoint, Vec3(0, 1, 0)); invalidate(); } } ///////////////////////// AnimationView::mousePressEvent //////////////////// void AnimationView::mousePressEvent(QMouseEvent *event) { if ((event->buttons() & Qt::LeftButton) || (event->buttons() & Qt::MidButton)) { m_mousepresspos = m_mousemovepos = event->pos(); m_yawsign = (camera.up().y > 0) ? -1.0f : 1.0f; event->accept(); } } ///////////////////////// AnimationView::mouseMoveEvent ///////////////////// void AnimationView::mouseMoveEvent(QMouseEvent *event) { if (!m_mousepresspos.isNull()) { auto dx = event->pos().x() - m_mousemovepos.x(); auto dy = m_mousemovepos.y() - event->pos().y(); if (event->modifiers() == Qt::NoModifier) { camera.orbit(m_focuspoint, Transform::rotation(camera.right(), 0.01f * dy).rotation()); camera.orbit(m_focuspoint, Transform::rotation(Vec3(0, 1, 0), m_yawsign * 0.01f * dx).rotation()); } if (event->modifiers() == Qt::ShiftModifier) { camera.pan(m_focuspoint, -0.05f * dx, -0.05f * dy); } renderparams.sundirection = normalise(camera.forward() - camera.right() - camera.up()); invalidate(); } m_mousemovepos = event->pos(); } ///////////////////////// AnimationView::mouseReleaseEvent ////////////////// void AnimationView::mouseReleaseEvent(QMouseEvent *event) { m_mousepresspos = QPoint(); } ///////////////////////// AnimationView::wheelEvent ///////////////////////// void AnimationView::wheelEvent(QWheelEvent *event) { camera.dolly(m_focuspoint, 0.01*event->angleDelta().y()); invalidate(); } ///////////////////////// AnimationView::timerEvent ///////////////////////// void AnimationView::timerEvent(QTimerEvent *event) { if (event->timerId() == m_timerid) { if (isVisible()) { m_time += 1.0f/60.0f; float time = fmod(m_time, m_duration); for(size_t i = 1; i < m_joints.size(); ++i) { auto &joint = m_joints[i]; size_t index = 0; while (index+2 < joint.transforms.size() && joint.transforms[index+1].time < time) ++index; auto alpha = remap(time, joint.transforms[index].time, joint.transforms[index+1].time, 0.0f, 1.0f); auto transform = lerp(joint.transforms[index].transform, joint.transforms[index+1].transform, alpha); m_bones[i] = m_bones[joint.parent] * transform; } update(); } } Viewport::timerEvent(event); } ///////////////////////// AnimationView::paintEvent ///////////////////////// void AnimationView::paintEvent(QPaintEvent *event) { prepare(); OverlayList overlays; OverlayList::BuildState buildstate; if (begin(overlays, buildstate)) { for(size_t i = 1; i < m_joints.size(); ++i) { auto a = m_bones[m_joints[i].parent] * Vec3(0, 0, 0); auto b = m_bones[i] * Vec3(0, 0, 0); overlays.push_line(buildstate, a, b, Color4(1, 1, 1, 1)); } overlays.finalise(buildstate); } push_overlays(overlays); render(); }
; A097843: First differences of Chebyshev polynomials S(n,123) = A049670(n+1) with Diophantine property. ; Submitted by Jamie Morken(s4) ; 1,122,15005,1845493,226980634,27916772489,3433536035513,422297015595610,51939099382224517,6388086926998019981,785682752921374233146,96632590522402032656977,11885022951502528642575025,1461761190444288621004071098,179784741401695997854858170029,22112061431218163447526550842469,2719603771298432408047910895453658,334489151808275968026445513589957465,41139446068646645634844750260669314537,5059817377291729137117877836548735730586,622316397960814037219864129145233825547541 mul $0,2 mov $3,1 lpb $0 sub $0,1 mov $2,$3 mul $3,11 add $3,$1 mov $1,$2 lpe mov $0,$3
; A175485: Numerators of averages of squares of the first n positive integers. ; 1,5,14,15,11,91,20,51,95,77,46,325,63,145,248,187,105,703,130,287,473,345,188,1225,221,477,770,551,295,1891,336,715,1139,805,426,2701,475,1001,1580,1107,581,3655,638,1335,2093,1457,760,4753,825,1717,2678 mul $0,2 add $0,1 seq $0,27626 ; Denominator of n*(n+5)/((n+2)*(n+3)). dif $0,2
; A130236: Partial sums of the 'upper' Fibonacci Inverse A130234. ; 0,1,4,8,13,18,24,30,36,43,50,57,64,71,79,87,95,103,111,119,127,135,144,153,162,171,180,189,198,207,216,225,234,243,252,262,272,282,292,302,312,322,332,342,352,362,372,382,392,402,412,422,432,442,452,462,473 mov $14,$0 mov $16,$0 lpb $16,1 clr $0,14 mov $0,$14 sub $16,1 sub $0,$16 mov $11,$0 mov $13,$0 lpb $13,1 mov $0,$11 sub $13,1 sub $0,$13 mov $7,$0 mov $9,2 lpb $9,1 mov $0,$7 sub $9,1 add $0,$9 sub $0,1 mov $2,$0 mov $0,8 pow $2,8 lpb $2,1 div $2,$0 add $0,4 trn $2,1 lpe mov $1,$0 div $1,2 mov $10,$9 lpb $10,1 mov $8,$1 sub $10,1 lpe lpe lpb $7,1 mov $7,0 sub $8,$1 lpe mov $1,$8 div $1,2 add $12,$1 lpe add $15,$12 lpe mov $1,$15
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h" #include <string> #include "base/check.h" #include "base/macros.h" #include "base/values.h" #include "chrome/browser/ash/login/saml/in_session_password_change_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "chromeos/login/auth/saml_password_attributes.h" #include "components/prefs/pref_service.h" #include "components/user_manager/user_manager.h" namespace chromeos { namespace { const InSessionPasswordChangeManager::Event kIncorrectPasswordEvent = InSessionPasswordChangeManager::Event::CRYPTOHOME_PASSWORD_CHANGE_FAILURE; const InSessionPasswordChangeManager::PasswordSource kPasswordSource = InSessionPasswordChangeManager::PasswordSource::PASSWORDS_RETYPED; // Returns one if it is non-empty, otherwise returns two. const std::string& FirstNonEmpty(const std::string& one, const std::string& two) { return !one.empty() ? one : two; } } // namespace ConfirmPasswordChangeHandler::ConfirmPasswordChangeHandler( const std::string& scraped_old_password, const std::string& scraped_new_password, const bool show_spinner_initially) : scraped_old_password_(scraped_old_password), scraped_new_password_(scraped_new_password), show_spinner_initially_(show_spinner_initially) { if (InSessionPasswordChangeManager::IsInitialized()) { InSessionPasswordChangeManager::Get()->AddObserver(this); } } ConfirmPasswordChangeHandler::~ConfirmPasswordChangeHandler() { if (InSessionPasswordChangeManager::IsInitialized()) { InSessionPasswordChangeManager::Get()->RemoveObserver(this); } } void ConfirmPasswordChangeHandler::HandleGetInitialState( const base::ListValue* params) { const std::string callback_id = params->GetList()[0].GetString(); base::Value state(base::Value::Type::DICTIONARY); state.SetBoolKey("showOldPasswordPrompt", scraped_old_password_.empty()); state.SetBoolKey("showNewPasswordPrompt", scraped_new_password_.empty()); state.SetBoolKey("showSpinner", show_spinner_initially_); AllowJavascript(); ResolveJavascriptCallback(base::Value(callback_id), state); } void ConfirmPasswordChangeHandler::HandleChangePassword( const base::ListValue* params) { const std::string old_password = FirstNonEmpty(params->GetList()[0].GetString(), scraped_old_password_); const std::string new_password = FirstNonEmpty(params->GetList()[1].GetString(), scraped_new_password_); DCHECK(!old_password.empty() && !new_password.empty()); InSessionPasswordChangeManager::Get()->ChangePassword( old_password, new_password, kPasswordSource); } void ConfirmPasswordChangeHandler::OnEvent( InSessionPasswordChangeManager::Event event) { if (event == kIncorrectPasswordEvent) { // If this event comes before getInitialState, then don't show the spinner // initially after all - the initial password change attempt using scraped // passwords already failed before the dialog finished loading. show_spinner_initially_ = false; // Discard the scraped old password and ask the user what it really is. scraped_old_password_.clear(); if (IsJavascriptAllowed()) { FireWebUIListener("incorrect-old-password"); } } } void ConfirmPasswordChangeHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getInitialState", base::BindRepeating(&ConfirmPasswordChangeHandler::HandleGetInitialState, weak_factory_.GetWeakPtr())); web_ui()->RegisterMessageCallback( "changePassword", base::BindRepeating(&ConfirmPasswordChangeHandler::HandleChangePassword, weak_factory_.GetWeakPtr())); } } // namespace chromeos
; A337004: Turn sequence of the R5 dragon curve. ; 1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,1 mul $0,2 add $0,1 lpb $0,1 mov $1,1 mov $2,$0 mul $0,2 add $2,$1 mod $2,10 mov $4,3 mov $5,$2 clr $0,$5 div $0,10 lpe sub $4,2 mov $1,$4 sub $1,2 div $1,4 mul $1,2 add $1,1
assume cs:code,ds:data data segment pa equ 20a0h pb equ 20a1h pc equ 20a2h cr equ 20a3h rowval db ? colval db ? scode db ? data ends code segment start: mov ax,data mov ds,ax mov dx,cr mov al,90h out dx,al tryagain: mov bl,01h mov bh,03h mov cl,00h next_row: mov dx,pc mov al,bl out dx,al mov dx,pa in al,dx cmp al,00h jne calculate add cl,08h inc ah shl bl,01 dec bh jnz next_row jmp tryagain calculate: mov rowval,ah mov ah,00h rot_again: ror al,01 jc next inc ah inc cl jmp rot_again next: mov scode,cl mov colval,ah mov al,cl call disp mov ah,4ch int 21h disp proc mov bl,al mov cl,4 shr al,cl cmp al,09 jle add_30 add al,07 add_30: add al,30h mov dl,al mov ah,02 int 21h mov al,bl and al,0fh cmp al,09 jle add_30_1 add al,07 add_30_1: add al,30h mov dl,al mov ah,02 int 21h ret disp endp code ends end start
// license:BSD-3-Clause // copyright-holders:AJR /********************************************************************** Rockwell R65C19 Microcomputer (MCU) TODO: fully describe this MCU and its successors (C29, C39) and emulate their internal peripherals (only core emulation now) **********************************************************************/ #include "emu.h" #include "r65c19.h" #include "r65c19d.h" DEFINE_DEVICE_TYPE(R65C19, r65c19_device, "r65c19", "Rockwell R65C19 MCU") DEFINE_DEVICE_TYPE(L2800, l2800_device, "l2800", "Rockwell L2800 MCU") r65c19_device::r65c19_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, u32 clock, address_map_constructor internal_map) : r65c02_device(mconfig, type, tag, owner, clock) , m_w(0) , m_i(0) , m_page1_ram(*this, "page1") , m_cir(0) { program_config.m_internal_map = std::move(internal_map); } r65c19_device::r65c19_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : r65c19_device(mconfig, R65C19, tag, owner, clock, address_map_constructor()) { } c39_device::c39_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, u32 clock, address_map_constructor internal_map) : r65c19_device(mconfig, type, tag, owner, clock, internal_map) , m_exp_config("expansion", ENDIANNESS_LITTLE, 8, 21, 0) , m_es4_config("es4", ENDIANNESS_LITTLE, 8, 9, 0) { } l2800_device::l2800_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : c39_device(mconfig, L2800, tag, owner, clock, address_map_constructor(FUNC(l2800_device::internal_map), this)) { } std::unique_ptr<util::disasm_interface> r65c19_device::create_disassembler() { return std::make_unique<r65c19_disassembler>(); } void r65c19_device::do_add(u8 v) { P &= ~F_C; do_adc(v); } u16 r65c19_device::do_accumulate(u16 v, u16 w) { // Compute the sum s32 result = s16(v) + s16(w); // Determine flags and saturate result upon overflow P &= ~(F_N | F_V); if (result > 32767) { P |= F_V; result = 32767; } else if (result < 0) { P |= F_N; if (result < -32768) { P |= F_V; result = -32768; } } // MPA and MPY always destroy the old value of Y, as does RND when it overflows Y = result & 0xff; // 16-bit result to W, or high byte to A return result & 0xffff; } u16 r65c19_device::get_irq_vector() { // TODO: this is a stub return 0xfffc; } void r65c19_device::device_start() { mintf = std::make_unique<mi_default>(); c19_init(); } device_memory_interface::space_config_vector c39_device::memory_space_config() const { return space_config_vector { std::make_pair(AS_PROGRAM, &program_config), std::make_pair(AS_DATA, &m_exp_config), std::make_pair(AS_IO, &m_es4_config) }; } void c39_device::device_start() { std::unique_ptr<mi_banked> intf = std::make_unique<mi_banked>(); space(AS_DATA).cache(intf->escache); space(AS_DATA).specific(intf->exp); space(AS_IO).specific(intf->es4); save_item(NAME(intf->bsr)); save_item(NAME(intf->pbs)); mintf = std::move(intf); c19_init(); for (int i = 0; i < 8; i++) state_add(C39_BSR0 + i, string_format("BSR%d", i).c_str(), downcast<mi_banked &>(*mintf).bsr[i]); } void r65c19_device::c19_init() { init(); state_add(R65C19_W, "W", m_w); state_add<u8>(R65C19_WL, "WL", [this]() { return m_w & 0xff; }, [this](u8 data) { m_w = set_l(m_w, data); }).noshow(); state_add<u8>(R65C19_WH, "WH", [this]() { return m_w >> 8; }, [this](u8 data) { m_w = set_h(m_w, data); }).noshow(); state_add(R65C19_I, "I", m_i); save_item(NAME(m_w)); save_item(NAME(m_i)); save_item(NAME(m_cir)); } void r65c19_device::device_reset() { r65c02_device::device_reset(); m_cir = 0x00; } void c39_device::device_reset() { r65c02_device::device_reset(); mi_banked &intf = downcast<mi_banked &>(*mintf); intf.bsr[0] = 0xe0; intf.bsr[1] = 0xd1; intf.bsr[2] = 0xb2; intf.bsr[3] = 0xb3; intf.bsr[4] = 0x74; intf.bsr[5] = 0x75; intf.bsr[6] = 0x76; intf.bsr[7] = 0x77; intf.pbs = 0xff; } u8 r65c19_device::page1_seg_r(offs_t offset) { return m_page1_ram[(m_cir & 0x03) << 6 | offset]; } void r65c19_device::page1_seg_w(offs_t offset, u8 data) { m_page1_ram[(m_cir & 0x03) << 6 | offset] = data; } u8 r65c19_device::cir_r() { return m_cir; } void r65c19_device::cir_w(u8 data) { // TODO: clear interrupts m_cir = data & 0x07; } u8 c39_device::mi_banked::exp_read(u16 adr) { return exp.read_byte(u32(bsr[(adr & 0xe000) >> 13]) << 13 | (adr & 0x1fff)); } u8 c39_device::mi_banked::exp_read_cached(u16 adr) { return escache.read_byte(u32(bsr[(adr & 0xe000) >> 13]) << 13 | (adr & 0x1fff)); } void c39_device::mi_banked::exp_write(u16 adr, u8 val) { exp.write_byte(u32(bsr[(adr & 0xe000) >> 13]) << 13 | (adr & 0x1fff), val); } u8 c39_device::mi_banked::es4_read(u16 adr) { return es4.read_byte(adr & 0x1ff); } void c39_device::mi_banked::es4_write(u16 adr, u8 val) { es4.write_byte(adr & 0x1ff, val); } u8 c39_device::mi_banked::read(u16 adr) { return program.read_byte(adr); } u8 c39_device::mi_banked::read_sync(u16 adr) { if (adr < 0x0600) return cprogram.read_byte(adr); else if (adr >= 0x0800 || BIT(pbs, 1)) return exp_read_cached(adr); else return es4_read(adr); } u8 c39_device::mi_banked::read_arg(u16 adr) { if (adr < 0x0600) return cprogram.read_byte(adr); else if (adr >= 0x0800 || BIT(pbs, 1)) return exp_read_cached(adr); else return es4_read(adr); } void c39_device::mi_banked::write(u16 adr, u8 val) { program.write_byte(adr, val); } u8 c39_device::pbs_r() { return downcast<mi_banked &>(*mintf).pbs; } void c39_device::pbs_w(u8 data) { downcast<mi_banked &>(*mintf).pbs = data; } u8 c39_device::bsr_r(offs_t offset) { return downcast<mi_banked &>(*mintf).bsr[offset]; } void c39_device::bsr_w(offs_t offset, u8 data) { downcast<mi_banked &>(*mintf).bsr[offset] = data; } u8 c39_device::expansion_r(offs_t offset) { mi_banked &intf = downcast<mi_banked &>(*mintf); if (offset >= 0x0200 || BIT(intf.pbs, 1)) return intf.exp_read(offset + 0x0600); else return intf.es4_read(offset + 0x0600); } void c39_device::expansion_w(offs_t offset, u8 data) { mi_banked &intf = downcast<mi_banked &>(*mintf); if (offset >= 0x0200 || BIT(intf.pbs, 1)) intf.exp_write(offset + 0x0600, data); else intf.es4_write(offset + 0x0600, data); } void l2800_device::internal_map(address_map &map) { // TODO: most registers still unimplemented map(0x0005, 0x0005).rw(FUNC(l2800_device::pbs_r), FUNC(l2800_device::pbs_w)); map(0x000b, 0x000b).rw(FUNC(l2800_device::cir_r), FUNC(l2800_device::cir_w)); map(0x0018, 0x001f).rw(FUNC(l2800_device::bsr_r), FUNC(l2800_device::bsr_w)); map(0x0040, 0x05fd).ram(); // Page 0 has 192 dedicated bytes here map(0x0600, 0xffff).rw(FUNC(l2800_device::expansion_r), FUNC(l2800_device::expansion_w)); } #include "cpu/m6502/r65c19.hxx"
; A098299: Member r=14 of the family of Chebyshev sequences S_r(n) defined in A092184. ; Submitted by Jon Maiga ; 0,1,14,169,2016,24025,286286,3411409,40650624,484396081,5772102350,68780832121,819597883104,9766393765129,116377127298446,1386759133816225,16524732478496256,196910030608138849,2346395634819169934,27959837587221900361,333171655411843634400,3970100027354901712441,47308028672846976914894,563726244046808821266289,6717406899888858878280576,80045156554619497718100625,953824471755545113738926926,11365848504511921867149022489,135436357582387517292049342944,1613870442484138285637443092841 mov $3,1 lpb $0 sub $0,1 mul $1,10 add $3,$1 add $2,$3 mov $1,$2 add $3,2 lpe mov $0,$1
SECTION code_clib SECTION code_fp_math48 PUBLIC cos EXTERN cm48_sccz80_cos defc cos = cm48_sccz80_cos
/* * Copyright (c) 2012, Michael Lehn, Klaus Pototzky * * 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 FLENS development group nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CXXLAPACK_INTERFACE_SPGST_TCC #define CXXLAPACK_INTERFACE_SPGST_TCC 1 #include <iostream> #include <cxxlapack/interface/interface.h> #include <cxxlapack/netlib/netlib.h> namespace cxxlapack { template <typename IndexType> IndexType spgst(IndexType itype, char uplo, IndexType n, float *Ap, const float *Bp) { CXXLAPACK_DEBUG_OUT("sspgst"); IndexType info; LAPACK_IMPL(sspgst)(&itype, &uplo, &n, Ap, &Bp, &info); # ifndef NDEBUG if (info<0) { std::cerr << "info = " << info << std::endl; } # endif ASSERT(info>=0); return info; } template <typename IndexType> IndexType spgst(IndexType itype, char uplo, IndexType n, double *Ap, const double *Bp) { CXXLAPACK_DEBUG_OUT("dspgst"); IndexType info; LAPACK_IMPL(dspgst)(&itype, &uplo, &n, Ap, &Bp, &info); # ifndef NDEBUG if (info<0) { std::cerr << "info = " << info << std::endl; } # endif ASSERT(info>=0); return info; } } // namespace cxxlapack #endif // CXXLAPACK_INTERFACE_SPGST_TCC
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r15 push %r8 push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0x104f6, %rsi lea addresses_WC_ht+0x586, %rdi clflush (%rsi) nop nop nop nop cmp %rdx, %rdx mov $111, %rcx rep movsb nop nop nop xor $64915, %rbx lea addresses_WT_ht+0x7186, %r15 nop nop xor $55277, %r8 mov (%r15), %edx nop nop nop inc %r8 lea addresses_D_ht+0x11186, %rdi nop add $56067, %r8 movups (%rdi), %xmm4 vpextrq $0, %xmm4, %rbx nop and $7389, %rbx lea addresses_A_ht+0xbc82, %rsi lea addresses_D_ht+0x19386, %rdi clflush (%rdi) xor $19490, %rbx mov $29, %rcx rep movsb nop nop nop cmp %rcx, %rcx lea addresses_A_ht+0x19606, %rsi lea addresses_WC_ht+0xafdc, %rdi clflush (%rdi) and $29827, %r12 mov $65, %rcx rep movsw nop nop nop nop sub $36509, %rsi lea addresses_A_ht+0x9a06, %rdi nop nop add $60897, %r12 mov $0x6162636465666768, %r15 movq %r15, %xmm5 movups %xmm5, (%rdi) nop nop nop nop cmp %r8, %r8 lea addresses_D_ht+0x1c986, %rdi nop inc %rsi mov (%rdi), %r8d nop nop nop nop add $20917, %rcx lea addresses_A_ht+0x8946, %r12 clflush (%r12) nop nop nop nop and %rsi, %rsi mov $0x6162636465666768, %rcx movq %rcx, (%r12) nop nop nop nop cmp $32334, %r15 lea addresses_WC_ht+0x13f86, %rsi lea addresses_D_ht+0x18d86, %rdi nop nop nop dec %rbx mov $104, %rcx rep movsq nop nop nop nop add $1918, %rbx lea addresses_WT_ht+0xb186, %rsi lea addresses_UC_ht+0x5477, %rdi nop nop dec %r8 mov $33, %rcx rep movsq nop nop xor $10510, %rdi lea addresses_WT_ht+0x9186, %rcx nop and $14819, %r12 movl $0x61626364, (%rcx) nop nop nop nop nop mfence lea addresses_normal_ht+0x9bc6, %rsi lea addresses_WC_ht+0xaa6a, %rdi nop nop nop and $56861, %rbx mov $115, %rcx rep movsl nop sub %rcx, %rcx lea addresses_WC_ht+0x1e726, %rbx nop nop nop nop nop sub $23854, %rcx movb (%rbx), %r8b nop nop nop nop add %rcx, %rcx lea addresses_UC_ht+0x15891, %r12 nop and %rsi, %rsi mov (%r12), %rdi nop sub $32189, %r12 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %r8 pop %r15 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r14 push %r9 push %rax push %rbp push %rsi // Load lea addresses_RW+0x18186, %r12 nop nop nop and $3904, %r14 mov (%r12), %r10w // Exception!!! nop nop nop nop nop mov (0), %rbp inc %r12 // Store lea addresses_PSE+0x7186, %rsi nop xor %rax, %rax movb $0x51, (%rsi) nop and %r12, %r12 // Store lea addresses_PSE+0x1a186, %rax clflush (%rax) and $27284, %rsi movl $0x51525354, (%rax) nop nop nop nop nop sub %rax, %rax // Faulty Load lea addresses_RW+0x18186, %r10 and %rbp, %rbp mov (%r10), %r9d lea oracles, %rsi and $0xff, %r9 shlq $12, %r9 mov (%rsi,%r9,1), %r9 pop %rsi pop %rbp pop %rax pop %r9 pop %r14 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_RW', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_RW', 'same': True, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 11}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 11}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_RW', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 4}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 10}} {'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_WT_ht', 'same': True, 'AVXalign': True, 'congruent': 11}} {'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 10}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 2}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 5}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 3}, 'dst': {'same': True, 'type': 'addresses_WC_ht', 'congruent': 1}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 7}} {'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 10}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 6}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 8}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 9}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 8}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 11}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 5}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 1}} {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 4}} {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 0}} {'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 */
; A190088: Triangle of binomial coefficients binomial(3*n-k+1,3*n-3*k+1). ; Submitted by Jon Maiga ; 1,1,3,1,15,5,1,36,70,7,1,66,330,210,9,1,105,1001,1716,495,11,1,153,2380,8008,6435,1001,13,1,210,4845,27132,43758,19448,1820,15,1,276,8855,74613,203490,184756,50388,3060,17,1,351,14950,177100,735471,1144066,646646,116280,4845,19,1,435,23751,376740,2220075,5311735,5200300,1961256,245157,7315,21,1,528,35960,736281,5852925,20030010,30421755,20058300,5311735,480700,10626,23,1,630,52360,1344904,13884156,64512240,141120525,145422675,67863915,13123110,888030,14950,25,1,741,73815,2324784,30260340 mov $1,1 lpb $0 add $1,3 sub $2,1 add $0,$2 lpe sub $1,$0 mul $0,2 bin $1,$0 mov $0,$1
// Data section begins .section .data var1: .int 40 var2: .int 20 var3: .int 30 .section .text .globl _start _start: # move the contents of variables movl (var1), %ecx cmpl (var2), %ecx jg check_third_var movl (var2), %ecx check_third_var: cmpl (var3), %ecx jg _exit movl (var3), %ecx _exit: movl $1, %eax movl %ecx, %ebx int $0x80
; load bootrom at '0x7c00' org 0x7c00 ;org 0x0 ; work in 16-bit mode bits 16 jmp _run _alpha: ; `bl` is the character to be written ; write 'X' to screen and jump infinitely mov bl, '0' alpha: mov ah, 0x0e mov al, bl int 0x10 mov cl, bl inc bl cmp cl, 'z' jne alpha jmp run _run: ; print alphabet jmp _alpha run: ; write '\r\n' when done mov ah, 0x0e mov al, 0x0d int 0x10 mov ah, 0x0e mov al, 0x0a int 0x10 run_check: ; read keyboard input status mov ah, 0x1 mov al, 0 int 0x16 cmp al, 0x1 jne run_print jmp run_check run_print: ; get entered character mov ah, 0 int 0x16 ; if carriage return entered, print carriage return and line feed cmp al, 0x0d je run_print_newline ; if backspace entered, move cursor back cmp al, 0x08 je run_decr_cursor jmp run_print_cont run_print_newline: ; print carriage return mov ah, 0x0e mov al, 0x0d int 0x10 ; print line feed mov al, 0x0a int 0x10 jmp run_check run_decr_cursor: ; get cursor position for page 0 mov ah, 0x3 mov bh, 0 int 0x10 ; decrement column if column is not zero cmp dl, 0 je run_decr_cursor_col mov bh, 0 dec dl mov ah, 0x2 int 0x10 jmp run_check run_decr_cursor_col: ; decrement row if column is zero mov bh, 0 dec dh mov ah, 0x2 int 0x10 jmp run_check run_print_cont: mov ah, 0x0e int 0x10 jmp run_check ;; fill remaining space with zeros times 510 - ($ - $$) db 0 dw 0xaa55
; ****************************************************************************** ; Lprt - Load the printer driver ; ; Copyright (c) 2021 by Gaston Williams ; ; ****************************************************************************** ; Based on code written by Michael H Riley ; Original copyright notice: ; ******************************************************************* ; *** This software is copyright 2004 by Michael H Riley *** ; *** You have permission to use, modify, copy, and distribute *** ; *** this software so long as this copyright notice is retained. *** ; *** This software may not be used in commercial applications *** ; *** without express written permission from the author. *** ; ******************************************************************* #include ops.inc include bios.inc include kernel.inc V_DEFAULT: equ 051bh ; ************************************************************ ; This block generates the Execution header ; It occurs 6 bytes before the program start. ; ************************************************************ ORG 02000h-6 ; Header starts at 01ffah dw 02000h ; Program load address dw endrom-2000h ; Program size dw 02000h ; Program execution address ORG 02000h ; code starts here BR start ; Jump past build info to code ; Build information binfo: db 80H+10 ; Month, 80H offset means extended info db 21 ; Day dw 2021 ; Year ; Current build number build: dw 1 ; Must end with 0 (null) db 'Copyright 2021 Gaston Williams',0 ; ============================================================================== ; Main ; ============================================================================== start: lda RA ; move past any spaces smi ' ' bz start dec ra ; move back to non-space character LDA ra ; check for nonzero byte bz loadp ; jump to load driver if no arguments smi '-' ; check for argument lbnz bad_arg ldn ra ; check for correct argument smi 'u' ; to unload diver lbz unload lbr bad_arg ; anything else is a bad argument loadp: LOAD rd, O_PRINT ; point rd to vector inc rd ; go to Address part of vector lda rd ; get high byte sdi 20h ; check if above kernel memory (> 2000h) lbnf loaded ; df = 0, means hi byte greater than 20h LOAD rc, 0015h ; block size of 21 bytes LOAD r7, 0F44H ; 16-byte alignment, named, permanent allocation CALL o_alloc ; allocate a block of memory lbdf bad_blk ; DF = 1 means allocation failed COPY rf, rd ; save copy of block address for later ; Because rf points to the memory block ; it's quick and easy to just load the opcode bytes ; directly, since this code block is so short. ldi 36h ; opcode for wait: B3 wait (wait here while EF3 true) str rf ; store branch glo rf ; rf points to branch opcode address, so get it now inc rf ; point to branch target address str rf ; save previous address so wait branches to itself inc rf ; point rf to next byte ldi 73h ; opcode for STXD str rf ; STXD saves byte below stack inc rf ; move rf to next byte in the printer driver ldi 60h ; opcode for IRX str rf ; IXR points x back to data byte inc rf ldi 65h ; opcode for OUT 5 str rf ; OUT increments stack pointer inc rf ldi 0f0h ; opcode for LDX str rf ; so we must decrement x by reading and writing inc rf ldi 73h ; opcode for STXD str rf ; the same byte with store and decrement x inc rf ldi 36h ; opcode for wait: B3 wait (wait here while EF3 true) str rf ; store branch glo rf ; rf points to branch opcode address, so get it now inc rf ; point to branch target address str rf ; save previous address so wait branches to itself inc rf ; point rf to next byte ldi 0d5h ; opcode for Return str rf ; save last program byte inc rf ; store code for prtstat ldi 36h ; opcode for prtstat: B3 prtstat (wait here while EF3 true) str rf ; store branch glo rf ; rf points to branch opcode address, so get it now inc rf ; point to branch target address str rf ; save previous address so wait branches to itself inc rf ; point rf to next byte ldi 6dh ; opcode for INP 5 str rf ; Read status byte in from Port 5 inc rf ldi 0d5h ; opcode for Return str rf ; save last program byte inc rf ; point to padding byte ldi 00h ; pad with zero before name str rf inc rf ldi 'P' ; store string "Print" as name str rf inc rf ldi 'r' ; store string "Print" as name str rf inc rf ldi 'i' ; store string "Print" as name str rf inc rf ldi 'n' ; store string "Print" as name str rf inc rf ldi 't' ; store string "Print" as name str rf inc rf ldi 0 ; name string ends with null str rf ; Drivers are now loaded LOAD rf, O_PRINT ; point rf to printer vector inc rf ; point to o_print vector address ghi rd ; get hi byte of driver address str rf ; save it in kernel o_print vector inc rf glo rd ; get lo byte of printer address str rf ; save it in kernel o_print vector adi 0Ah ; point rd to prtstat driver address plo rd ; eight bytes beyond print routine LOAD rf, O_PRTSTAT ; point rf to printer status vector inc rf ; point to o_prtstatus vector address ghi rd ; get hi byte of driver address str rf ; save it in kernel o_prtstatus vector inc rf glo rd ; get lo byte of printer address str rf ; save it in kernel o_prtstatus vector LOAD rf, success ; show msg that driver loaded CALL O_MSG RETURN ; return to elf/os unload: LOAD rd, O_PRINT ; point rd to printer vector at beginning of block inc rd ; o_print vector address is block address lda rd ; get hi byte of block address phi rf ; put into rf ldn rd ; get lo byte of block address plo rf ; put into rf CALL O_DEALLOC ; de-allocate block on heap LOAD rf, O_PRTSTAT ; point rf to printer status vector inc rf ; point to o_prtstatus vector address LOAD rd, O_PRINT ; point rd to printer vector inc rd ; point to o_print vector address ldi V_DEFAULT.1 ; load hi byte of original vector str rf ; point vectors back to original address inc rf str rd inc rd ldi V_DEFAULT.0 ; load lo byte of original vector str rf ; point vectors back to original address str rd LOAD rf, unloaded ; show message that driver is unloaded CALL O_MSG RETURN ; return to elf/os loaded: LOAD rf, already ; show already loaded message lbr show_err bad_blk: LOAD rf, mem_err ; show allocation error message lbr show_err bad_arg: LOAD rf, usage ; show usage message, then info text CALL O_MSG LOAD rf, info show_err: CALL O_MSG lbr O_WRMBOOT ; ============================================================================== ; Send a character to the printer ; ; This routine is independent of the X variable. ; ============================================================================== ; prtchar: b3 prtchar ; prevent over run, wait until not busy ; stxd ; save byte below stack ; irx ; point x back to data byte ; out 5 ; out increments stack pointer ; ldx ; so we must decrement x by reading and ; stxd ; writing same byte at the bottom of stack ; wait: b3 wait ; wait for busy flag to exit ; RETURN ; ; ============================================================================== ; Get status byte from printer ; ============================================================================== ; prtstat: b3 prtstat ; wait for busy flag to clear ; inp 5 ; get the status byte into D ; RETURN success: db 'Printer driver loaded.',13,10,0 unloaded: db 'Printer driver unloaded.',13,10,0 already: db 'A printer driver is already loaded.',13,10,0 mem_err: db 'Cannot allocate memory for the printer drivers.',13,10,0 usage: db 'Usage: lprt [-u]',13,10,0 info: db 'Loads printer drivers. Use option -u to unload.',13,10,0 endrom: equ $
title 'Requester Network I/O System for CP/NET 1.2' page 54 ;*************************************************************** ;*************************************************************** ;** ** ;** R e q u e s t e r N e t w o r k I / O S y s t e m ** ;** ** ;*************************************************************** ;*************************************************************** ;/* ; Copyright (C) 1980, 1981, 1982 ; Digital Research ; P.O. Box 579 ; Pacific Grove, CA 93950 ; ; Revised: October 5, 1982 ; ; Modified December 2006 for Z80SIM by Udo Munk ;*/ false equ 0 true equ not false cpnos equ false ; cp/net system always$retry equ false ; force continuous retries ASCII equ false debug equ false CSEG if cpnos extrn BDOS else BDOS equ 0005h endif NIOS: public NIOS ; Jump vector for SNIOS entry points jmp ntwrkinit ; network initialization jmp ntwrksts ; network status jmp cnfgtbladr ; return config table addr jmp sendmsg ; send message on network jmp receivemsg ; receive message from network jmp ntwrkerror ; network error jmp ntwrkwboot ; network warm boot slave$ID equ 11h ; slave processor ID number if cpnos ; Initial Slave Configuration Table Initconfigtbl: db 0000$0000b ; network status byte db slave$ID ; slave processor ID number db 84h,0 ; A: Disk device db 81h,0 ; B: " db 82h,0 ; C: " db 83h,0 ; D: " db 80h,0 ; E: " db 85h,0 ; F: " db 86h,0 ; G: " db 87h,0 ; H: " db 88h,0 ; I: " db 89h,0 ; J: " db 8ah,0 ; K: " db 8bh,0 ; L: " db 8ch,0 ; M: " db 8dh,0 ; N: " db 8eh,0 ; O: " db 8fh,0 ; P: " db 0,0 ; console device db 0,0 ; list device: db 0 ; buffer index db 0 ; FMT db 0 ; DID db slave$ID ; SID db 5 ; FNC initcfglen equ $-initconfigtbl endif defaultmaster equ 00h wboot$msg: ; data for warm boot routine db '<Warm Boot>' db '$' networkerrmsg: db 'Network Error' db '$' page DSEG ; Slave Configuration Table configtbl: Network$status: ds 1 ; network status byte ds 1 ; slave processor ID number ds 2 ; A: Disk device ds 2 ; B: " ds 2 ; C: " ds 2 ; D: " ds 2 ; E: " ds 2 ; F: " ds 2 ; G: " ds 2 ; H: " ds 2 ; I: " ds 2 ; J: " ds 2 ; K: " ds 2 ; L: " ds 2 ; M: " ds 2 ; N: " ds 2 ; O: " ds 2 ; P: " ds 2 ; console device ds 2 ; list device: ds 1 ; buffer index db 0 ; FMT db 0 ; DID db Slave$ID ; SID (CP/NOS must still initialize) db 5 ; FNC ds 1 ; SIZ ds 1 ; MSG(0) List number ds 128 ; MSG(1) ... MSG(128) msg$adr: ds 2 ; message address timeout$retries equ 100 ; timeout a max of 100 times max$retries equ 10 ; send message max of 10 times retry$count: ds 1 FirstPass: db 0ffh ; Network Status Byte Equates ; active equ 0001$0000b ; slave logged in on network rcverr equ 0000$0010b ; error in received message senderr equ 0000$0001b ; unable to send message ; General Equates ; SOH equ 01h ; Start of Header STX equ 02h ; Start of Data ETX equ 03h ; End of Data EOT equ 04h ; End of Transmission ENQ equ 05h ; Enquire ACK equ 06h ; Acknowledge LF equ 0ah ; Line Feed CR equ 0dh ; Carriage Return NAK equ 15h ; Negative Acknowledge conout equ 2 ; console output function print equ 9 ; print string function rcvmsg equ 67 ; receive message NDOS function login equ 64 ; Login NDOS function ; I/O Equates ; stati equ 50 mski equ 01 dprti equ 51 stato equ 50 msko equ 02 dprto equ 51 page CSEG ; Utility Procedures ; if ASCII Nib$out: ; A = nibble to be transmitted in ASCII cpi 10 jnc nibAtoF ; jump if A-F adi '0' mov c,a jmp Char$out nibAtoF: adi 'A'-10 mov c,a jmp Char$out endif Pre$Char$out: mov a,d add c mov d,a ; update the checksum in D nChar$out: ; C = byte to be transmitted in stato ani msko jz nChar$out mov a,c out dprto ret ; Char$out: call nChar$out ret if ASCII Nib$in: ; return nibble in A register call Char$in rc ani 7fh sui '0' cpi 10 jc Nib$in$rtn ; must be 0-9 adi ('0'-'A'+10) and 0ffh cpi 16 jc Nib$in$rtn ; must be 10-15 lda network$status ori rcverr sta network$status mvi a,0 stc ; carry set indicating err cond ret Nib$in$rtn: ora a ; clear carry & return ret endif xChar$in: mvi b,10 ; 100 ms corresponds to longest possible jmp char$in0 ;wait between master operations Char$in: ; return byte in A register ; carry set on rtn if timeout mvi b,10 Char$in0: in stati ; busy wait forever, no reasonable ani mski ; delay implemented yet jz Char$in0 Char$in1: ; in stati ; ani mski ; jnz Char$in2 ; out delay ; dcr b ; jnz Char$in0 ; stc ; carry set for err cond = timeout ; ret Char$in2: in dprti ret ; rtn with raw char and carry cleared Net$out: ; C = byte to be transmitted ; D = checksum mov a,d add c mov d,a if ASCII mov a,c mov b,a rar rar rar rar ani 0FH ; mask HI-LO nibble to LO nibble call Nib$out mov a,b ani 0FH jmp Nib$out else jmp Char$out endif Msg$in: ; HL = destination address ; E = # bytes to input call Net$in rc mov m,a inx h dcr e jnz Msg$in ret Net$in: ; byte returned in A register ; D = checksum accumulator if ASCII call Nib$in rc add a add a add a add a push psw call Nib$in pop b rc ora b else call Char$in ;receive byte in Binary mode rc endif chks$in: mov b,a add d ; add & update checksum accum. mov d,a ora a ; set cond code from checksum mov a,b ret Msg$out: ; HL = source address ; E = # bytes to output ; D = checksum ; C = preamble byte mvi d,0 ; initialize the checksum call Pre$Char$out ; send the preamble character Msg$out$loop: mov c,m inx h call Net$out dcr e jnz Msg$out$loop ret page ; Network Initialization ntwrkinit: if cpnos ; copy down network assignments lxi h,Initconfigtbl lxi d,configtbl mvi c,initcfglen initloop: mov a,m stax d inx h inx d dcr c jnz initloop ; initialize config tbl from ROM else mvi a,slave$ID ;initialize slave ID byte sta configtbl+1 ; in the configuration tablee endif ; device initialization, as required if cpnos call loginpr ; login to a master endif initok: xra a ; return code is 0=success ret page ; Network Status ntwrksts: lda network$status mov b,a ani not (rcverr+senderr) sta network$status mov a,b ret ; Return Configuration Table Address cnfgtbladr: lxi h,configtbl ret page ; Send Message on Network sendmsg: ; BC = message addr mov h,b mov l,c ; HL = message address shld msg$adr re$sendmsg: mvi a,max$retries sta retry$count ; initialize retry count send: lhld msg$adr mvi c,ENQ call Char$out ; send ENQ to master mvi d,timeout$retries ENQ$response: call Char$in jnc got$ENQ$response dcr d jnz ENQ$response jmp Char$in$timeout got$ENQ$response: call get$ACK0 mvi c,SOH mvi e,5 call Msg$out ; send SOH FMT DID SID FNC SIZ xra a sub d mov c,a call net$out ; send HCS (header checksum) call get$ACK dcx h mov e,m inx h inr e mvi c,STX call Msg$out ; send STX DB0 DB1 ... mvi c,ETX call Pre$Char$out ; send ETX xra a sub d mov c,a call Net$out ; send the checksum mvi c,EOT call nChar$out ; send EOT call get$ACK ; (leave these ret ; two instructions) get$ACK: call Char$in jc send$retry ; jump if timeout get$ACK0: ani 7fh sui ACK rz send$retry: pop h ; discard return address lxi h,retry$count dcr m jnz send ; send again unles max retries Char$in$timeout: mvi a,senderr if always$retry call error$return jmp re$sendmsg else jmp error$return endif page ; Receive Message from Network receivemsg: ; BC = message addr mov h,b mov l,c ; HL = message address shld msg$adr re$receivemsg: mvi a,max$retries sta retry$count ; initialize retry count re$call: call receive ; rtn from receive is receive error receive$retry: lxi h,retry$count dcr m jnz re$call receive$timeout: mvi a,rcverr if always$retry call error$return jmp re$receivemsg else jmp error$return endif receive: lhld msg$adr mvi d,timeout$retries receive$firstchar: call xcharin jnc got$firstchar dcr d jnz receive$firstchar pop h ; discard receive$retry rtn adr jmp receive$timeout got$firstchar: ani 7fh cpi ENQ ; Enquire? jnz receive mvi c,ACK call nChar$out ; acknowledge ENQ with an ACK call Char$in rc ; return to receive$retry ani 7fh cpi SOH ; Start of Header ? rnz ; return to receive$retry mov d,a ; initialize the HCS mvi e,5 call Msg$in rc ; return to receive$retry call Net$in rc ; return to receive$retry jnz bad$checksum call send$ACK call Char$in rc ; return to receive$retry ani 7fh cpi STX ; Start of Data ? rnz ; return to receive$retry mov d,a ; initialize the CKS dcx h mov e,m inx h inr e call msg$in ; get DB0 DB1 ... rc ; return to receive$retry call Char$in ; get the ETX rc ; return to receive$retry ani 7fh cpi ETX rnz ; return to receive$retry add d mov d,a ; update CKS with ETX call Net$in ; get CKS rc ; return to receive$retry call Char$in ; get EOT rc ; return to receive$retry ani 7fh cpi EOT rnz ; return to receive$retry mov a,d ora a ; test CKS jnz bad$checksum pop h ; discard receive$retry rtn adr lhld msg$adr inx h lda configtbl+1 sub m jz send$ACK ; jump with A=0 if DID ok mvi a,0ffh ; return code shows bad DID send$ACK: push psw ; save return code mvi c,ACK call nChar$out ; send ACK if checksum ok pop psw ; restore return code ret bad$DID: bad$checksum: mvi c,NAK jmp Char$out ; send NAK on bad chksm & not max retries ; ret error$return: lxi h,network$status ora m mov m,a call ntwrkerror ; perform any required device re-init. mvi a,0ffh ret ntwrkerror: ; perform any required device ret ; re-initialization page ; ntwrkwboot: ; This procedure is called each time the CCP is ; reloaded from disk. This version prints "<WARM BOOT>" ; on the console and then returns, but anything necessary ; for restart can be put here. mvi c,9 lxi d,wboot$msg jmp BDOS page if cpnos ; ; LOGIN to a Master ; ; Equates ; buff equ 0080h readbf equ 10 active equ 0001$0000b loginpr: mvi c,initpasswordmsglen lxi h,initpasswordmsg lxi d,passwordmsg copypassword: mov a,m stax d inx h inx d dcr c jnz copypassword mvi c,print lxi d,loginmsg call BDOS mvi c,readbf lxi d,buff-1 mvi a,50h stax d call BDOS lxi h,buff mov a,m ; get # chars in the command tail ora a jz dologin ; default login if empty command tail mov c,a ; A = # chars in command tail xra a mov b,a ; B will accumulate master ID scanblnks: inx h mov a,m cpi ' ' jnz pastblnks ; skip past leading blanks dcr c jnz scanblnks jmp prelogin ; jump if command tail exhausted pastblnks: cpi '[' jz scanMstrID mvi a,8 lxi d,passwordmsg+5+8-1 xchg spacefill: mvi m,' ' dcx h dcr a jnz spacefill xchg scanLftBrkt: mov a,m cpi '[' jz scanMstrID inx d stax d ;update the password inx h dcr c jnz scanLftBrkt jmp prelogin scanMstrID: inx h dcr c jz loginerr mov a,m cpi ']' jz prelogin sui '0' cpi 10 jc updateID adi ('0'-'A'+10) and 0ffh cpi 16 jnc loginerr updateID: push psw mov a,b add a add a add a add a mov b,a ; accum * 16 pop psw add b mov b,a jmp scanMstrID prelogin: mov a,b dologin: lxi b,passwordmsg+1 stax b dcx b call sendmsg inr a lxi d,loginfailedmsg jz printmsg lxi b,passwordmsg call receivemsg inr a lxi d,loginfailedmsg jz printmsg lda passwordmsg+5 inr a jnz loginOK jmp printmsg loginerr: lxi d,loginerrmsg printmsg: mvi c,print call BDOS jmp loginpr ; try login again loginOK: lxi h,network$status ; HL = status byte addr mov a,m ori active ; set active bit true mov m,a ret ; ; Local Data Segment ; loginmsg: db cr,lf db 'LOGIN=' db '$' initpasswordmsg: db 00h ; FMT db 00h ; DID Master ID # db slave$ID ;SID db 40h ; FNC db 7 ; SIZ db 'PASSWORD' ; password initpasswordmsglen equ $-initpasswordmsg loginerrmsg: db lf db 'Invalid LOGIN' db '$' loginfailedmsg: db lf db 'LOGIN Failed' db '$' DSEG passwordmsg: ds 1 ; FMT ds 1 ; DID ds 1 ; SID ds 1 ; FNC ds 1 ; SIZ ds 8 ; DAT = password endif end
; A214061: Least m>0 such that gcd(2*n-1+m, 2*n-m) > 1. ; 2,4,6,2,10,12,2,16,3,2,22,24,2,3,30,2,34,36,2,40,42,2,4,3,2,52,54,2,3,4,2,64,66,2,70,6,2,76,3,2,82,84,2,3,90,2,6,96,2,100,4,2,106,3,2,112,114,2,3,120,2,7,126,2,4,132,2,136,3,2,142,4,2,3,7,2,154,156,2,6,9,2,166,3,2,4,174,2,3,180,2,184,4,2,190,192,2,9,3,2,7,6,2,3,210,2,4,216,2,220,222,2,6,3,2,232,234,2,3,240,2,244,246,2,250,252,2,4,3,2,262,9,2,3,4,2,274,10,2,7,282,2,286,3,2,6,294,2,3,300,2,304,7,2,310,4,2,316,3,2,322,324,2,3,330,2,12,6,2,4,342,2,346,3,2,10,4,2,3,360,2,364,9,2,370,372,2,376,3,2,4,7,2,3,10,2,394,4,2,9,6,2,406,3,2,412,414,2,3,420,2,4,12,2,430,432,2,7,3,2,442,444,2,3,15,2,454,456,2,460,7,2,4,3,2,12,474,2,3,4,2,484,486,2,6,492,2,496,3,2 mul $0,2 add $0,1 cal $0,90368 ; a(1) = 1; for n>1, smallest divisor > 1 of 2n-1. mov $1,$0 div $1,2 add $1,1
* --------------------------------------------------------------------------- * Tilemap - Subroutines to draw a background of tiles * * input REG : none * * --------------------------------------------------------------------------- INCLUDE "./Engine/Graphics/Tilemap/DataTypes/Layer.equ" INCLUDE "./Engine/Graphics/Tilemap/DataTypes/Submap.equ" glb_submap_index_inactive equ $FFFF ; force background refresh if used in glb_submap_index_buf0/1 glb_submap fdb $0000 ; location of submap data structure glb_submap_page fdb $00 ; location of submap data structure glb_submap_index fdb $0000 ; index in submap tile table that matches camera position glb_submap_index_buf0 fdb glb_submap_index_inactive ; actual submap index that matches screen buffer 0 content glb_submap_index_buf1 fdb glb_submap_index_inactive ; actual submap index that matches screen buffer 1 content DrawTilemap lda glb_submap_page ldx glb_submap _SetCartPageA ; TODO loop thru all submap layers ldu submap_layers,x ; Transform a camera position into an index into submap table ; This routine use a submap layer parameter (layer_tile_size_divider) ; to make a faster division at runtime leay layer_tilemap,u sty @dyn2+1 ldb layer_tile_size_divider_x,u stb @dynb1+1 ldd glb_camera_x_pos subd submap_x_pos,x @dynb1 bra *+2 _lsrd _lsrd _lsrd _lsrd _lsrd _lsrd _lsrd _lsrd std @dyn1+1 ldb layer_tile_size_divider_y,u stb @dynb2+1 ldd glb_camera_y_pos subd submap_y_pos,x @dynb2 bra *+2 _lsrd _lsrd _lsrd _lsrd _lsrd _lsrd _lsrd _lsrd lda layer_width,u mul ; to use map larger than 256*256 tiles, use tile groups (TODO) @dyn1 addd #0 ; (dynamic) add x position to index @dyn2 addd #0 ; (dynamic) add layer map data address to index ; now we have to check if this submap index (register d) was the one already rendered (or not) on this buffer ; the goal is to avoid the full redraw of background if it's already there ... tst glb_Cur_Wrk_Screen_Id ; read current screen buffer for write operations bne DTM_Buffer1 DTM_Buffer0 cmpd glb_submap_index_buf0 beq DTM_Return std glb_submap_index_buf0 std glb_submap_index bra DrawTileInit DTM_Return rts DTM_Buffer1 cmpd glb_submap_index_buf1 beq DTM_Return std glb_submap_index_buf1 std glb_submap_index DrawTileInit ldd layer_vp_offset,u addd #$A000 std glb_screen_location_1 ldd layer_vp_offset,u addd #$C000 std glb_screen_location_2 lda layer_vp_tiles_x,u sta dyn_x+1 ; init column counter sta dyn_xi+1 ; init column counter lda layer_vp_tiles_y,u sta dyn_y+1 ; init row counter lda layer_mem_step_x,u sta dyn_sx+1 ldd layer_mem_step_y,u std dyn_sy+1 lda layer_width,u suba layer_vp_tiles_x,u deca sta dyn_w+1 ldu layer_tiles_location,u stu dyn_Tls+1 bra DrawTileLayer DrawTileRow dec dyn_y+1 dyn_sy ldd #$0000 ; (dynamic) y memory step ldx glb_screen_location_1 leax d,x stx glb_screen_location_1 ldx glb_screen_location_2 leax d,x stx glb_screen_location_2 dyn_xi lda #$00 sta dyn_x+1 ; init column counter bra DrawTileLayer DrawTileColumn dec dyn_x+1 dyn_sx ldb #$00 ; (dynamic) x memory step ldx glb_screen_location_1 abx stx glb_screen_location_1 ldx glb_screen_location_2 abx stx glb_screen_location_2 DrawTileLayer ldu glb_submap_index lda #0 ldb ,u ; load tile index in b (0-256) std @dyn+1 ; multiply d by 3 _lsld @dyn addd #$0000 ; (dynamic) leau 1,u stu glb_submap_index dyn_Tls ldu #0000 ; (dynamic) Tileset leau d,u pulu a,x ; a: tile routine page, x: tile routine address ; draw compilated tile ldy #glb_screen_location_2 stx glb_Address jsr RunPgSubRoutine dyn_x lda #$00 ; (dynamic) current column index tsta bne DrawTileColumn dyn_y lda #$00 ; (dynamic) current row index dyn_w ldb #$00 ldu glb_submap_index leau b,u stu glb_submap_index tsta bne DrawTileRow ; TODO set here the background refresh flag rts
; ; Sorcerer Exidy pseudo graphics routines ; Version for the 2x3 graphics symbols (UDG redefined) ; ; Stefano Bodrato 2014 ; ; ; Plot pixel at (x,y) coordinate. ; ; ; $Id: plotpixl.asm,v 1.6 2016-07-02 09:01:36 dom Exp $ ; INCLUDE "graphics/grafix.inc" SECTION code_clib PUBLIC plotpixel EXTERN div3 EXTERN __gfx_coords EXTERN base_graphics .plotpixel ld a,h cp maxx ret nc ld a,l cp maxy ret nc ; y0 out of range dec a dec a ld (__gfx_coords),hl push bc ld c,a ; y ld b,h ; x push bc ld hl,div3 ld d,0 ld e,c inc e add hl,de ld a,(hl) ld c,a ; y/3 srl b ; x/2 ld a,c ld c,b ; !! ;--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ld hl,(base_graphics) ld b,a ; keep y/3 and a jr z,r_zero ld de,64 .r_loop add hl,de dec a jr nz,r_loop .r_zero ld d,0 ld e,c add hl,de ;--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ld a,(hl) ; get current symbol from screen sub 192 ld e,a ; ..and its copy ex (sp),hl ; save char address <=> restore x,y (y=h, x=l) ld a,l inc a inc a sub b sub b sub b ; we get the remainder of y/3 ld l,a ld a,1 ; the pixel we want to draw jr z,iszero bit 0,l jr nz,is1 add a,a add a,a .is1 add a,a add a,a .iszero bit 0,h jr nz,evenrow add a,a ; move down the bit .evenrow or e add 192 pop hl ld (hl),a pop bc ret
; A339196: Number of (undirected) cycles on the n X 2 king graph. ; 7,30,85,204,451,954,1969,4008,8095,16278,32653,65412,130939,262002,524137,1048416,2096983,4194126,8388421,16777020,33554227,67108650,134217505,268435224,536870671,1073741574,2147483389,4294967028,8589934315,17179868898,34359738073,68719476432,137438953159,274877906622,549755813557,1099511627436,2199023255203,4398046510746,8796093021841,17592186044040,35184372088447,70368744177270,140737488354925,281474976710244,562949953420891,1125899906842194,2251799813684809,4503599627370048,9007199254740535,18014398509481518,36028797018963493,72057594037927452,144115188075855379,288230376151711242,576460752303422977,1152921504606846456,2305843009213693423,4611686018427387366,9223372036854775261,18446744073709551060,36893488147419102667,73786976294838205890,147573952589676412345,295147905179352825264,590295810358705651111,1180591620717411302814,2361183241434822606229,4722366482869645213068,9444732965739290426755,18889465931478580854138,37778931862957161708913,75557863725914323418472,151115727451828646837599,302231454903657293675862,604462909807314587352397,1208925819614629174705476,2417851639229258349411643,4835703278458516698823986,9671406556917033397648681,19342813113834066795298080,38685626227668133590596887,77371252455336267181194510,154742504910672534362389765,309485009821345068724780284,618970019642690137449561331,1237940039285380274899123434,2475880078570760549798247649,4951760157141521099596496088,9903520314283042199192992975,19807040628566084398385986758,39614081257132168796771974333,79228162514264337593543949492,158456325028528675187087899819,316912650057057350374175800482,633825300114114700748351601817,1267650600228229401496703204496,2535301200456458802993406409863,5070602400912917605986812820606,10141204801825835211973625642101,20282409603651670423947251285100 add $0,1 mov $1,4 mov $2,2 lpb $0 sub $0,1 sub $1,3 add $2,3 mul $2,2 add $1,$2 lpe sub $1,4 mov $0,$1
; A167616: a(n) = Fibonacci(n) - 5. ; Submitted by Jon Maiga ; 0,3,8,16,29,50,84,139,228,372,605,982,1592,2579,4176,6760,10941,17706,28652,46363,75020,121388,196413,317806,514224,832035,1346264,2178304,3524573,5702882,9227460,14930347,24157812,39088164,63245981,102334150,165580136,267914291,433494432,701408728,1134903165,1836311898,2971215068,4807526971,7778742044,12586269020,20365011069,32951280094,53316291168,86267571267,139583862440,225851433712,365435296157,591286729874,956722026036,1548008755915,2504730781956,4052739537876,6557470319837,10610209857718 mov $1,2 mov $3,3 lpb $0 sub $0,1 mov $2,$3 add $3,$1 mov $1,$2 lpe add $3,$1 mov $0,$3 sub $0,5
#include "CurlDownloader.hpp" #include <curl/curl.h> bool CurlDownloader::download(const std::string& url, const std::string& destination) const { if (auto curl = curl_easy_init()) { auto fp = fopen(destination.c_str(), "wb"); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); const auto downloadSuccessful = curl_easy_perform(curl) == CURLE_OK; fclose(fp); curl_easy_cleanup(curl); return downloadSuccessful; } return false; }
EXTRN theloop:far code SEGMENT para public 'CODE' ASSUME cs:code .386 LOCALS PUBLIC _wave1,_wave2,_vbuf,_cameralevel _wave1 dw 0,0 _wave2 dw 0,0 _vbuf dw 0,0 _cameralevel dw 0 PUBLIC _sin1024 include sin1024.inc PUBLIC _setborder _setborder PROC FAR push bp mov bp,sp mov dx,3dah in al,dx mov dx,3c0h mov al,11h+32 out dx,al mov al,[bp+6] out dx,al pop bp ret _setborder ENDP PUBLIC _inittwk _inittwk PROC FAR push bp mov bp,sp push si push di push ds ;clear palette mov dx,3c8h xor al,al out dx,al inc dx mov cx,768 @@1: out dx,al loop @@1 mov dx,3d4h ;400 rows ;mov ax,00009h ;out dx,ax ;tweak mov ax,00014h out dx,ax mov ax,0e317h out dx,ax mov dx,3c4h mov ax,0604h out dx,ax ; mov dx,3c4h mov ax,0f02h out dx,ax mov ax,0a000h mov es,ax xor di,di mov cx,32768 xor ax,ax rep stosw ; pop ds pop di pop si pop bp ret _inittwk ENDP PUBLIC _setpalarea _setpalarea PROC FAR push bp mov bp,sp push si push di push ds lds si,[bp+6] mov ax,[bp+10] mov dx,3c8h out dx,al mov cx,[bp+12] mov ax,cx shl cx,1 add cx,ax inc dx rep outsb sti pop ds pop di pop si pop bp ret _setpalarea ENDP PUBLIC _docol _docol PROC FAR push bp mov bp,sp push si push di push ds mov es,cs:_vbuf[2] mov fs,cs:_wave1[2] mov gs,cs:_wave2[2] mov si,[bp+6] mov di,[bp+8] mov cx,[bp+10] add cx,cx mov dx,[bp+12] add dx,dx mov bp,[bp+14] mov ax,cs:_cameralevel int 3 call theloop pop ds pop di pop si pop bp ret _docol ENDP PUBLIC _docopy _docopy PROC FAR push bp mov bp,sp push si push di push ds mov es,[bp+6] mov ds,cs:_vbuf[2] mov si,50*160 mov di,50*80 mov cx,150 mov bl,255 mov bh,bl mov ax,bx shl ebx,16 mov bx,ax @@1: cmp cx,100 jge @@2 mov dx,3c4h mov ax,0302h out dx,ax zzz=0 REPT 20 mov eax,ds:[si+zzz] mov es:[di+zzz],eax zzz=zzz+4 ENDM mov dx,3c4h mov ax,0C02h out dx,ax zzz=0 REPT 20 mov eax,ds:[si+zzz+80] mov es:[di+zzz],eax zzz=zzz+4 ENDM add si,160 add di,80 dec cx jnz @@1 pop ds pop di pop si pop bp ret @@2: ;this loop also clears mov dx,3c4h mov ax,0302h out dx,ax zzz=0 REPT 20 mov eax,ds:[si+zzz] mov ds:[si+zzz],ebx mov es:[di+zzz],eax zzz=zzz+4 ENDM mov dx,3c4h mov ax,0C02h out dx,ax zzz=0 REPT 20 mov eax,ds:[si+zzz+80] mov ds:[si+zzz+80],ebx mov es:[di+zzz],eax zzz=zzz+4 ENDM sub ebx,01010101h cmp bl,192 jge @@3 mov ebx,0c0c0c0c0h @@3: add si,160 add di,80 dec cx jmp @@1 _docopy ENDP code ENDS END
; A097789: a(n)=4a(n-1)+C(n+4,4),n>0, a(0)=1. ; 1,9,51,239,1026,4230,17130,68850,275895,1104295,4418181,17674089,70698176,282795084,1131183396,4524737460,18098954685,72395824725,289583306215,1158333233715,4633332945486,18533331794594,74133327193326 lpb $0 mov $2,$0 sub $0,1 seq $2,97788 ; a(n)=4a(n-1)+C(n+3,3),n>0, a(0)=1. add $1,$2 lpe add $1,1 mov $0,$1
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # 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. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 5, 0x90 Lpoly: .quad 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFF, 0x0, 0xFFFFFFFF00000001 LRR: .quad 0x3, 0xfffffffbffffffff, 0xfffffffffffffffe, 0x4fffffffd LOne: .long 1,1,1,1,1,1,1,1 LTwo: .long 2,2,2,2,2,2,2,2 LThree: .long 3,3,3,3,3,3,3,3 .p2align 5, 0x90 .globl l9_p256r1_mul_by_2 .type l9_p256r1_mul_by_2, @function l9_p256r1_mul_by_2: push %r12 push %r13 xor %r13, %r13 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 shld $(1), %r11, %r13 shld $(1), %r10, %r11 shld $(1), %r9, %r10 shld $(1), %r8, %r9 shl $(1), %r8 mov %r8, %rax mov %r9, %rdx mov %r10, %rcx mov %r11, %r12 subq Lpoly+0(%rip), %rax sbbq Lpoly+8(%rip), %rdx sbbq Lpoly+16(%rip), %rcx sbbq Lpoly+24(%rip), %r12 sbb $(0), %r13 cmove %rax, %r8 cmove %rdx, %r9 cmove %rcx, %r10 cmove %r12, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) vzeroupper pop %r13 pop %r12 ret .Lfe1: .size l9_p256r1_mul_by_2, .Lfe1-(l9_p256r1_mul_by_2) .p2align 5, 0x90 .globl l9_p256r1_div_by_2 .type l9_p256r1_div_by_2, @function l9_p256r1_div_by_2: push %r12 push %r13 push %r14 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 xor %r13, %r13 xor %r14, %r14 mov %r8, %rax mov %r9, %rdx mov %r10, %rcx mov %r11, %r12 addq Lpoly+0(%rip), %rax adcq Lpoly+8(%rip), %rdx adcq Lpoly+16(%rip), %rcx adcq Lpoly+24(%rip), %r12 adc $(0), %r13 test $(1), %r8 cmovne %rax, %r8 cmovne %rdx, %r9 cmovne %rcx, %r10 cmovne %r12, %r11 cmovne %r13, %r14 shrd $(1), %r9, %r8 shrd $(1), %r10, %r9 shrd $(1), %r11, %r10 shrd $(1), %r14, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) vzeroupper pop %r14 pop %r13 pop %r12 ret .Lfe2: .size l9_p256r1_div_by_2, .Lfe2-(l9_p256r1_div_by_2) .p2align 5, 0x90 .globl l9_p256r1_mul_by_3 .type l9_p256r1_mul_by_3, @function l9_p256r1_mul_by_3: push %r12 push %r13 xor %r13, %r13 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 shld $(1), %r11, %r13 shld $(1), %r10, %r11 shld $(1), %r9, %r10 shld $(1), %r8, %r9 shl $(1), %r8 mov %r8, %rax mov %r9, %rdx mov %r10, %rcx mov %r11, %r12 subq Lpoly+0(%rip), %rax sbbq Lpoly+8(%rip), %rdx sbbq Lpoly+16(%rip), %rcx sbbq Lpoly+24(%rip), %r12 sbb $(0), %r13 cmove %rax, %r8 cmove %rdx, %r9 cmove %rcx, %r10 cmove %r12, %r11 xor %r13, %r13 addq (%rsi), %r8 adcq (8)(%rsi), %r9 adcq (16)(%rsi), %r10 adcq (24)(%rsi), %r11 adc $(0), %r13 mov %r8, %rax mov %r9, %rdx mov %r10, %rcx mov %r11, %r12 subq Lpoly+0(%rip), %rax sbbq Lpoly+8(%rip), %rdx sbbq Lpoly+16(%rip), %rcx sbbq Lpoly+24(%rip), %r12 sbb $(0), %r13 cmove %rax, %r8 cmove %rdx, %r9 cmove %rcx, %r10 cmove %r12, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) vzeroupper pop %r13 pop %r12 ret .Lfe3: .size l9_p256r1_mul_by_3, .Lfe3-(l9_p256r1_mul_by_3) .p2align 5, 0x90 .globl l9_p256r1_add .type l9_p256r1_add, @function l9_p256r1_add: push %r12 push %r13 xor %r13, %r13 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 addq (%rdx), %r8 adcq (8)(%rdx), %r9 adcq (16)(%rdx), %r10 adcq (24)(%rdx), %r11 adc $(0), %r13 mov %r8, %rax mov %r9, %rdx mov %r10, %rcx mov %r11, %r12 subq Lpoly+0(%rip), %rax sbbq Lpoly+8(%rip), %rdx sbbq Lpoly+16(%rip), %rcx sbbq Lpoly+24(%rip), %r12 sbb $(0), %r13 cmove %rax, %r8 cmove %rdx, %r9 cmove %rcx, %r10 cmove %r12, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) vzeroupper pop %r13 pop %r12 ret .Lfe4: .size l9_p256r1_add, .Lfe4-(l9_p256r1_add) .p2align 5, 0x90 .globl l9_p256r1_sub .type l9_p256r1_sub, @function l9_p256r1_sub: push %r12 push %r13 xor %r13, %r13 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 subq (%rdx), %r8 sbbq (8)(%rdx), %r9 sbbq (16)(%rdx), %r10 sbbq (24)(%rdx), %r11 sbb $(0), %r13 mov %r8, %rax mov %r9, %rdx mov %r10, %rcx mov %r11, %r12 addq Lpoly+0(%rip), %rax adcq Lpoly+8(%rip), %rdx adcq Lpoly+16(%rip), %rcx adcq Lpoly+24(%rip), %r12 test %r13, %r13 cmovne %rax, %r8 cmovne %rdx, %r9 cmovne %rcx, %r10 cmovne %r12, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) vzeroupper pop %r13 pop %r12 ret .Lfe5: .size l9_p256r1_sub, .Lfe5-(l9_p256r1_sub) .p2align 5, 0x90 .globl l9_p256r1_neg .type l9_p256r1_neg, @function l9_p256r1_neg: push %r12 push %r13 xor %r13, %r13 xor %r8, %r8 xor %r9, %r9 xor %r10, %r10 xor %r11, %r11 subq (%rsi), %r8 sbbq (8)(%rsi), %r9 sbbq (16)(%rsi), %r10 sbbq (24)(%rsi), %r11 sbb $(0), %r13 mov %r8, %rax mov %r9, %rdx mov %r10, %rcx mov %r11, %r12 addq Lpoly+0(%rip), %rax adcq Lpoly+8(%rip), %rdx adcq Lpoly+16(%rip), %rcx adcq Lpoly+24(%rip), %r12 test %r13, %r13 cmovne %rax, %r8 cmovne %rdx, %r9 cmovne %rcx, %r10 cmovne %r12, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) vzeroupper pop %r13 pop %r12 ret .Lfe6: .size l9_p256r1_neg, .Lfe6-(l9_p256r1_neg) .p2align 5, 0x90 p256r1_mmull: xor %r13, %r13 movq (%rbx), %rax mulq (%rsi) mov %rax, %r8 mov %rdx, %r9 movq (%rbx), %rax mulq (8)(%rsi) add %rax, %r9 adc $(0), %rdx mov %rdx, %r10 movq (%rbx), %rax mulq (16)(%rsi) add %rax, %r10 adc $(0), %rdx mov %rdx, %r11 movq (%rbx), %rax mulq (24)(%rsi) add %rax, %r11 adc $(0), %rdx mov %rdx, %r12 mov %r8, %rax shl $(32), %rax mov %r8, %rdx shr $(32), %rdx mov %r8, %rcx mov %r8, %rbp xor %r8, %r8 sub %rax, %rcx sbb %rdx, %rbp add %rax, %r9 adc %rdx, %r10 adc %rcx, %r11 adc %rbp, %r12 adc $(0), %r13 movq (8)(%rbx), %rax mulq (%rsi) add %rax, %r9 adc $(0), %rdx mov %rdx, %rcx movq (8)(%rbx), %rax mulq (8)(%rsi) add %rcx, %r10 adc $(0), %rdx add %rax, %r10 adc $(0), %rdx mov %rdx, %rcx movq (8)(%rbx), %rax mulq (16)(%rsi) add %rcx, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %rcx movq (8)(%rbx), %rax mulq (24)(%rsi) add %rcx, %r12 adc $(0), %rdx add %rax, %r12 adc %rdx, %r13 adc $(0), %r8 mov %r9, %rax shl $(32), %rax mov %r9, %rdx shr $(32), %rdx mov %r9, %rcx mov %r9, %rbp xor %r9, %r9 sub %rax, %rcx sbb %rdx, %rbp add %rax, %r10 adc %rdx, %r11 adc %rcx, %r12 adc %rbp, %r13 adc $(0), %r8 movq (16)(%rbx), %rax mulq (%rsi) add %rax, %r10 adc $(0), %rdx mov %rdx, %rcx movq (16)(%rbx), %rax mulq (8)(%rsi) add %rcx, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %rcx movq (16)(%rbx), %rax mulq (16)(%rsi) add %rcx, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %rcx movq (16)(%rbx), %rax mulq (24)(%rsi) add %rcx, %r13 adc $(0), %rdx add %rax, %r13 adc %rdx, %r8 adc $(0), %r9 mov %r10, %rax shl $(32), %rax mov %r10, %rdx shr $(32), %rdx mov %r10, %rcx mov %r10, %rbp xor %r10, %r10 sub %rax, %rcx sbb %rdx, %rbp add %rax, %r11 adc %rdx, %r12 adc %rcx, %r13 adc %rbp, %r8 adc $(0), %r9 movq (24)(%rbx), %rax mulq (%rsi) add %rax, %r11 adc $(0), %rdx mov %rdx, %rcx movq (24)(%rbx), %rax mulq (8)(%rsi) add %rcx, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %rcx movq (24)(%rbx), %rax mulq (16)(%rsi) add %rcx, %r13 adc $(0), %rdx add %rax, %r13 adc $(0), %rdx mov %rdx, %rcx movq (24)(%rbx), %rax mulq (24)(%rsi) add %rcx, %r8 adc $(0), %rdx add %rax, %r8 adc %rdx, %r9 adc $(0), %r10 mov %r11, %rax shl $(32), %rax mov %r11, %rdx shr $(32), %rdx mov %r11, %rcx mov %r11, %rbp xor %r11, %r11 sub %rax, %rcx sbb %rdx, %rbp add %rax, %r12 adc %rdx, %r13 adc %rcx, %r8 adc %rbp, %r9 adc $(0), %r10 movq Lpoly+0(%rip), %rax movq Lpoly+8(%rip), %rdx movq Lpoly+16(%rip), %rcx movq Lpoly+24(%rip), %rbp mov %r12, %rbx mov %r13, %r11 mov %r8, %r14 mov %r9, %r15 sub %rax, %rbx sbb %rdx, %r11 sbb %rcx, %r14 sbb %rbp, %r15 sbb $(0), %r10 cmovnc %rbx, %r12 cmovnc %r11, %r13 cmovnc %r14, %r8 cmovnc %r15, %r9 movq %r12, (%rdi) movq %r13, (8)(%rdi) movq %r8, (16)(%rdi) movq %r9, (24)(%rdi) ret .p2align 5, 0x90 .globl l9_p256r1_mul_montl .type l9_p256r1_mul_montl, @function l9_p256r1_mul_montl: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 mov %rdx, %rbx call p256r1_mmull vzeroupper pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .Lfe7: .size l9_p256r1_mul_montl, .Lfe7-(l9_p256r1_mul_montl) .p2align 5, 0x90 .globl l9_p256r1_to_mont .type l9_p256r1_to_mont, @function l9_p256r1_to_mont: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 lea LRR(%rip), %rbx call p256r1_mmull vzeroupper pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .Lfe8: .size l9_p256r1_to_mont, .Lfe8-(l9_p256r1_to_mont) .p2align 5, 0x90 p256r1_mmulx: xor %r13, %r13 xor %rdx, %rdx movq (%rbx), %rdx mulxq (%rsi), %r8, %r9 mulxq (8)(%rsi), %rcx, %r10 add %rcx, %r9 mulxq (16)(%rsi), %rcx, %r11 adc %rcx, %r10 mulxq (24)(%rsi), %rcx, %r12 adc %rcx, %r11 adc $(0), %r12 mov %r8, %rax shl $(32), %rax mov %r8, %rdx shr $(32), %rdx mov %r8, %rcx mov %r8, %rbp xor %r8, %r8 sub %rax, %rcx sbb %rdx, %rbp add %rax, %r9 adc %rdx, %r10 adc %rcx, %r11 adc %rbp, %r12 adc $(0), %r13 movq (8)(%rbx), %rdx mulxq (%rsi), %rcx, %rbp adcx %rcx, %r9 adox %rbp, %r10 mulxq (8)(%rsi), %rcx, %rbp adcx %rcx, %r10 adox %rbp, %r11 mulxq (16)(%rsi), %rcx, %rbp adcx %rcx, %r11 adox %rbp, %r12 mulxq (24)(%rsi), %rcx, %rbp adcx %rcx, %r12 adox %rbp, %r13 adcx %r8, %r13 adox %r8, %r8 adc $(0), %r8 mov %r9, %rax shl $(32), %rax mov %r9, %rdx shr $(32), %rdx mov %r9, %rcx mov %r9, %rbp xor %r9, %r9 sub %rax, %rcx sbb %rdx, %rbp add %rax, %r10 adc %rdx, %r11 adc %rcx, %r12 adc %rbp, %r13 adc $(0), %r8 movq (16)(%rbx), %rdx mulxq (%rsi), %rcx, %rbp adcx %rcx, %r10 adox %rbp, %r11 mulxq (8)(%rsi), %rcx, %rbp adcx %rcx, %r11 adox %rbp, %r12 mulxq (16)(%rsi), %rcx, %rbp adcx %rcx, %r12 adox %rbp, %r13 mulxq (24)(%rsi), %rcx, %rbp adcx %rcx, %r13 adox %rbp, %r8 adcx %r9, %r8 adox %r9, %r9 adc $(0), %r9 mov %r10, %rax shl $(32), %rax mov %r10, %rdx shr $(32), %rdx mov %r10, %rcx mov %r10, %rbp xor %r10, %r10 sub %rax, %rcx sbb %rdx, %rbp add %rax, %r11 adc %rdx, %r12 adc %rcx, %r13 adc %rbp, %r8 adc $(0), %r9 movq (24)(%rbx), %rdx mulxq (%rsi), %rcx, %rbp adcx %rcx, %r11 adox %rbp, %r12 mulxq (8)(%rsi), %rcx, %rbp adcx %rcx, %r12 adox %rbp, %r13 mulxq (16)(%rsi), %rcx, %rbp adcx %rcx, %r13 adox %rbp, %r8 mulxq (24)(%rsi), %rcx, %rbp adcx %rcx, %r8 adox %rbp, %r9 adcx %r10, %r9 adox %r10, %r10 adc $(0), %r10 mov %r11, %rax shl $(32), %rax mov %r11, %rdx shr $(32), %rdx mov %r11, %rcx mov %r11, %rbp xor %r11, %r11 sub %rax, %rcx sbb %rdx, %rbp add %rax, %r12 adc %rdx, %r13 adc %rcx, %r8 adc %rbp, %r9 adc $(0), %r10 movq Lpoly+0(%rip), %rax movq Lpoly+8(%rip), %rdx movq Lpoly+16(%rip), %rcx movq Lpoly+24(%rip), %rbp mov %r12, %rbx mov %r13, %r11 mov %r8, %r14 mov %r9, %r15 sub %rax, %rbx sbb %rdx, %r11 sbb %rcx, %r14 sbb %rbp, %r15 sbb $(0), %r10 cmovnc %rbx, %r12 cmovnc %r11, %r13 cmovnc %r14, %r8 cmovnc %r15, %r9 movq %r12, (%rdi) movq %r13, (8)(%rdi) movq %r8, (16)(%rdi) movq %r9, (24)(%rdi) ret .p2align 5, 0x90 .globl l9_p256r1_mul_montx .type l9_p256r1_mul_montx, @function l9_p256r1_mul_montx: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 mov %rdx, %rbx call p256r1_mmulx vzeroupper pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .Lfe9: .size l9_p256r1_mul_montx, .Lfe9-(l9_p256r1_mul_montx) .p2align 5, 0x90 .globl l9_p256r1_sqr_montl .type l9_p256r1_sqr_montl, @function l9_p256r1_sqr_montl: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 movq (%rsi), %rbx movq (8)(%rsi), %rax mul %rbx mov %rax, %r9 mov %rdx, %r10 movq (16)(%rsi), %rax mul %rbx add %rax, %r10 adc $(0), %rdx mov %rdx, %r11 movq (24)(%rsi), %rax mul %rbx add %rax, %r11 adc $(0), %rdx mov %rdx, %r12 movq (8)(%rsi), %rbx movq (16)(%rsi), %rax mul %rbx add %rax, %r11 adc $(0), %rdx mov %rdx, %rbp movq (24)(%rsi), %rax mul %rbx add %rax, %r12 adc $(0), %rdx add %rbp, %r12 adc $(0), %rdx mov %rdx, %r13 movq (16)(%rsi), %rbx movq (24)(%rsi), %rax mul %rbx add %rax, %r13 adc $(0), %rdx mov %rdx, %r14 xor %r15, %r15 shld $(1), %r14, %r15 shld $(1), %r13, %r14 shld $(1), %r12, %r13 shld $(1), %r11, %r12 shld $(1), %r10, %r11 shld $(1), %r9, %r10 shl $(1), %r9 movq (%rsi), %rax mul %rax mov %rax, %r8 add %rdx, %r9 adc $(0), %r10 movq (8)(%rsi), %rax mul %rax add %rax, %r10 adc %rdx, %r11 adc $(0), %r12 movq (16)(%rsi), %rax mul %rax add %rax, %r12 adc %rdx, %r13 adc $(0), %r14 movq (24)(%rsi), %rax mul %rax add %rax, %r14 adc %rdx, %r15 mov %r8, %rcx shl $(32), %rcx mov %r8, %rbp shr $(32), %rbp mov %r8, %rbx mov %r8, %rdx xor %r8, %r8 sub %rcx, %rbx sbb %rbp, %rdx add %rcx, %r9 adc %rbp, %r10 adc %rbx, %r11 adc %rdx, %r12 adc $(0), %r8 mov %r9, %rcx shl $(32), %rcx mov %r9, %rbp shr $(32), %rbp mov %r9, %rbx mov %r9, %rdx xor %r9, %r9 sub %rcx, %rbx sbb %rbp, %rdx add %rcx, %r10 adc %rbp, %r11 adc %rbx, %r12 adc %rdx, %r13 adc $(0), %r9 add %r8, %r13 adc $(0), %r9 mov %r10, %rcx shl $(32), %rcx mov %r10, %rbp shr $(32), %rbp mov %r10, %rbx mov %r10, %rdx xor %r10, %r10 sub %rcx, %rbx sbb %rbp, %rdx add %rcx, %r11 adc %rbp, %r12 adc %rbx, %r13 adc %rdx, %r14 adc $(0), %r10 add %r9, %r14 adc $(0), %r10 mov %r11, %rcx shl $(32), %rcx mov %r11, %rbp shr $(32), %rbp mov %r11, %rbx mov %r11, %rdx xor %r11, %r11 sub %rcx, %rbx sbb %rbp, %rdx add %rcx, %r12 adc %rbp, %r13 adc %rbx, %r14 adc %rdx, %r15 adc $(0), %r11 add %r10, %r15 adc $(0), %r11 movq Lpoly+0(%rip), %rcx movq Lpoly+8(%rip), %rbp movq Lpoly+16(%rip), %rbx movq Lpoly+24(%rip), %rdx mov %r12, %rax mov %r13, %r8 mov %r14, %r9 mov %r15, %r10 sub %rcx, %rax sbb %rbp, %r8 sbb %rbx, %r9 sbb %rdx, %r10 sbb $(0), %r11 cmovnc %rax, %r12 cmovnc %r8, %r13 cmovnc %r9, %r14 cmovnc %r10, %r15 movq %r12, (%rdi) movq %r13, (8)(%rdi) movq %r14, (16)(%rdi) movq %r15, (24)(%rdi) vzeroupper pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .Lfe10: .size l9_p256r1_sqr_montl, .Lfe10-(l9_p256r1_sqr_montl) .p2align 5, 0x90 .globl l9_p256r1_sqr_montx .type l9_p256r1_sqr_montx, @function l9_p256r1_sqr_montx: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 movq (%rsi), %rdx mulxq (8)(%rsi), %r9, %r10 mulxq (16)(%rsi), %rcx, %r11 add %rcx, %r10 mulxq (24)(%rsi), %rcx, %r12 adc %rcx, %r11 adc $(0), %r12 movq (8)(%rsi), %rdx xor %r13, %r13 mulxq (16)(%rsi), %rcx, %rbp adcx %rcx, %r11 adox %rbp, %r12 mulxq (24)(%rsi), %rcx, %rbp adcx %rcx, %r12 adox %rbp, %r13 adc $(0), %r13 movq (16)(%rsi), %rdx mulxq (24)(%rsi), %rcx, %r14 add %rcx, %r13 adc $(0), %r14 xor %r15, %r15 shld $(1), %r14, %r15 shld $(1), %r13, %r14 shld $(1), %r12, %r13 shld $(1), %r11, %r12 shld $(1), %r10, %r11 shld $(1), %r9, %r10 shl $(1), %r9 xor %r8, %r8 movq (%rsi), %rdx mulx %rdx, %r8, %rbp adcx %rbp, %r9 movq (8)(%rsi), %rdx mulx %rdx, %rcx, %rbp adcx %rcx, %r10 adcx %rbp, %r11 movq (16)(%rsi), %rdx mulx %rdx, %rcx, %rbp adcx %rcx, %r12 adcx %rbp, %r13 movq (24)(%rsi), %rdx mulx %rdx, %rcx, %rbp adcx %rcx, %r14 adcx %rbp, %r15 mov %r8, %rcx shl $(32), %rcx mov %r8, %rbp shr $(32), %rbp mov %r8, %rbx mov %r8, %rdx xor %r8, %r8 sub %rcx, %rbx sbb %rbp, %rdx add %rcx, %r9 adc %rbp, %r10 adc %rbx, %r11 adc %rdx, %r12 adc $(0), %r8 mov %r9, %rcx shl $(32), %rcx mov %r9, %rbp shr $(32), %rbp mov %r9, %rbx mov %r9, %rdx xor %r9, %r9 sub %rcx, %rbx sbb %rbp, %rdx add %rcx, %r10 adc %rbp, %r11 adc %rbx, %r12 adc %rdx, %r13 adc $(0), %r9 add %r8, %r13 adc $(0), %r9 mov %r10, %rcx shl $(32), %rcx mov %r10, %rbp shr $(32), %rbp mov %r10, %rbx mov %r10, %rdx xor %r10, %r10 sub %rcx, %rbx sbb %rbp, %rdx add %rcx, %r11 adc %rbp, %r12 adc %rbx, %r13 adc %rdx, %r14 adc $(0), %r10 add %r9, %r14 adc $(0), %r10 mov %r11, %rcx shl $(32), %rcx mov %r11, %rbp shr $(32), %rbp mov %r11, %rbx mov %r11, %rdx xor %r11, %r11 sub %rcx, %rbx sbb %rbp, %rdx add %rcx, %r12 adc %rbp, %r13 adc %rbx, %r14 adc %rdx, %r15 adc $(0), %r11 add %r10, %r15 adc $(0), %r11 movq Lpoly+0(%rip), %rcx movq Lpoly+8(%rip), %rbp movq Lpoly+16(%rip), %rbx movq Lpoly+24(%rip), %rdx mov %r12, %rax mov %r13, %r8 mov %r14, %r9 mov %r15, %r10 sub %rcx, %rax sbb %rbp, %r8 sbb %rbx, %r9 sbb %rdx, %r10 sbb $(0), %r11 cmovnc %rax, %r12 cmovnc %r8, %r13 cmovnc %r9, %r14 cmovnc %r10, %r15 movq %r12, (%rdi) movq %r13, (8)(%rdi) movq %r14, (16)(%rdi) movq %r15, (24)(%rdi) vzeroupper pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .Lfe11: .size l9_p256r1_sqr_montx, .Lfe11-(l9_p256r1_sqr_montx) .p2align 5, 0x90 .globl l9_p256r1_mont_back .type l9_p256r1_mont_back, @function l9_p256r1_mont_back: push %r12 push %r13 movq (%rsi), %r10 movq (8)(%rsi), %r11 movq (16)(%rsi), %r12 movq (24)(%rsi), %r13 xor %r8, %r8 xor %r9, %r9 mov %r10, %rax shl $(32), %rax mov %r10, %rdx shr $(32), %rdx mov %r10, %rcx mov %r10, %rsi xor %r10, %r10 sub %rax, %rcx sbb %rdx, %rsi add %rax, %r11 adc %rdx, %r12 adc %rcx, %r13 adc %rsi, %r8 adc $(0), %r9 mov %r11, %rax shl $(32), %rax mov %r11, %rdx shr $(32), %rdx mov %r11, %rcx mov %r11, %rsi xor %r11, %r11 sub %rax, %rcx sbb %rdx, %rsi add %rax, %r12 adc %rdx, %r13 adc %rcx, %r8 adc %rsi, %r9 adc $(0), %r10 mov %r12, %rax shl $(32), %rax mov %r12, %rdx shr $(32), %rdx mov %r12, %rcx mov %r12, %rsi xor %r12, %r12 sub %rax, %rcx sbb %rdx, %rsi add %rax, %r13 adc %rdx, %r8 adc %rcx, %r9 adc %rsi, %r10 adc $(0), %r11 mov %r13, %rax shl $(32), %rax mov %r13, %rdx shr $(32), %rdx mov %r13, %rcx mov %r13, %rsi xor %r13, %r13 sub %rax, %rcx sbb %rdx, %rsi add %rax, %r8 adc %rdx, %r9 adc %rcx, %r10 adc %rsi, %r11 adc $(0), %r12 mov %r8, %rax mov %r9, %rdx mov %r10, %rcx mov %r11, %rsi subq Lpoly+0(%rip), %rax sbbq Lpoly+8(%rip), %rdx sbbq Lpoly+16(%rip), %rcx sbbq Lpoly+24(%rip), %rsi sbb $(0), %r12 cmovnc %rax, %r8 cmovnc %rdx, %r9 cmovnc %rcx, %r10 cmovnc %rsi, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) vzeroupper pop %r13 pop %r12 ret .Lfe12: .size l9_p256r1_mont_back, .Lfe12-(l9_p256r1_mont_back) .p2align 5, 0x90 .globl l9_p256r1_select_pp_w5 .type l9_p256r1_select_pp_w5, @function l9_p256r1_select_pp_w5: push %r12 push %r13 movdqa LOne(%rip), %xmm0 movdqa %xmm0, %xmm8 movd %edx, %xmm1 pshufd $(0), %xmm1, %xmm1 pxor %xmm2, %xmm2 pxor %xmm3, %xmm3 pxor %xmm4, %xmm4 pxor %xmm5, %xmm5 pxor %xmm6, %xmm6 pxor %xmm7, %xmm7 mov $(16), %rcx .Lselect_loop_sse_w5gas_13: movdqa %xmm8, %xmm15 pcmpeqd %xmm1, %xmm15 paddd %xmm0, %xmm8 movdqa (%rsi), %xmm9 movdqa (16)(%rsi), %xmm10 movdqa (32)(%rsi), %xmm11 movdqa (48)(%rsi), %xmm12 movdqa (64)(%rsi), %xmm13 movdqa (80)(%rsi), %xmm14 add $(96), %rsi pand %xmm15, %xmm9 pand %xmm15, %xmm10 pand %xmm15, %xmm11 pand %xmm15, %xmm12 pand %xmm15, %xmm13 pand %xmm15, %xmm14 por %xmm9, %xmm2 por %xmm10, %xmm3 por %xmm11, %xmm4 por %xmm12, %xmm5 por %xmm13, %xmm6 por %xmm14, %xmm7 dec %rcx jnz .Lselect_loop_sse_w5gas_13 movdqu %xmm2, (%rdi) movdqu %xmm3, (16)(%rdi) movdqu %xmm4, (32)(%rdi) movdqu %xmm5, (48)(%rdi) movdqu %xmm6, (64)(%rdi) movdqu %xmm7, (80)(%rdi) vzeroupper pop %r13 pop %r12 ret .Lfe13: .size l9_p256r1_select_pp_w5, .Lfe13-(l9_p256r1_select_pp_w5) .p2align 5, 0x90 .globl l9_p256r1_select_ap_w7 .type l9_p256r1_select_ap_w7, @function l9_p256r1_select_ap_w7: push %r12 push %r13 movdqa LOne(%rip), %xmm0 pxor %xmm2, %xmm2 pxor %xmm3, %xmm3 pxor %xmm4, %xmm4 pxor %xmm5, %xmm5 movdqa %xmm0, %xmm8 movd %edx, %xmm1 pshufd $(0), %xmm1, %xmm1 mov $(64), %rcx .Lselect_loop_sse_w7gas_14: movdqa %xmm8, %xmm15 pcmpeqd %xmm1, %xmm15 paddd %xmm0, %xmm8 movdqa (%rsi), %xmm9 movdqa (16)(%rsi), %xmm10 movdqa (32)(%rsi), %xmm11 movdqa (48)(%rsi), %xmm12 add $(64), %rsi pand %xmm15, %xmm9 pand %xmm15, %xmm10 pand %xmm15, %xmm11 pand %xmm15, %xmm12 por %xmm9, %xmm2 por %xmm10, %xmm3 por %xmm11, %xmm4 por %xmm12, %xmm5 dec %rcx jnz .Lselect_loop_sse_w7gas_14 movdqu %xmm2, (%rdi) movdqu %xmm3, (16)(%rdi) movdqu %xmm4, (32)(%rdi) movdqu %xmm5, (48)(%rdi) vzeroupper pop %r13 pop %r12 ret .Lfe14: .size l9_p256r1_select_ap_w7, .Lfe14-(l9_p256r1_select_ap_w7)
// Copyright (c) 2017-2018, NVIDIA CORPORATION. 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 <algorithm> #include <cmath> #include "dali/operators/ssd/box_encoder.h" namespace dali { using BoundingBox = BoxEncoder<CPUBackend>::BoundingBox; void BoxEncoder<CPUBackend>::CalculateIousForBox(float *ious, const BoundingBox &box) const { ious[0] = intersection_over_union(box, anchors_[0]); unsigned best_idx = 0; float best_iou = ious[0]; for (unsigned anchor_idx = 1; anchor_idx < anchors_.size(); ++anchor_idx) { ious[anchor_idx] = intersection_over_union(box, anchors_[anchor_idx]); if (ious[anchor_idx] >= best_iou) { best_iou = ious[anchor_idx]; best_idx = anchor_idx; } } // For best default box matched with current object let iou = 2, to make sure there is a match, // as this object will be the best (highest IoU), for this default box ious[best_idx] = 2.; } vector<float> BoxEncoder<CPUBackend>::CalculateIous(const vector<BoundingBox> &boxes) const { vector<float> ious(boxes.size() * anchors_.size()); for (unsigned bbox_idx = 0; bbox_idx < boxes.size(); ++bbox_idx) { auto ious_row = ious.data() + bbox_idx * anchors_.size(); CalculateIousForBox(ious_row, boxes[bbox_idx]); } return ious; } unsigned BoxEncoder<CPUBackend>::FindBestBoxForAnchor( unsigned anchor_idx, const vector<float> &ious, unsigned num_boxes) const { unsigned best_idx = 0; float best_iou = ious[anchor_idx]; for (unsigned bbox_idx = 1; bbox_idx < num_boxes; ++bbox_idx) { if (ious[bbox_idx * anchors_.size() + anchor_idx] >= best_iou) { best_iou = ious[bbox_idx * anchors_.size() + anchor_idx]; best_idx = bbox_idx; } } return best_idx; } vector<std::pair<unsigned, unsigned>> BoxEncoder<CPUBackend>::MatchBoxesWithAnchors( const vector<BoundingBox> &boxes) const { const auto ious = CalculateIous(boxes); vector<std::pair<unsigned, unsigned>> matches; for (unsigned anchor_idx = 0; anchor_idx < anchors_.size(); ++anchor_idx) { const auto best_idx = FindBestBoxForAnchor(anchor_idx, ious, boxes.size()); // Filter matches by criteria if (ious[best_idx * anchors_.size() + anchor_idx] > criteria_) { matches.push_back({best_idx, anchor_idx}); } } return matches; } template <int ndim> void WriteBoxToOutput(float *out_box_data, const vec<ndim, float> &center, const vec<ndim, float> &extent) { for (int d = 0; d < ndim; d++) { out_box_data[d] = center[d]; out_box_data[ndim + d] = extent[d]; } } void BoxEncoder<CPUBackend>::WriteAnchorsToOutput(float *out_boxes, int *out_labels) const { if (offset_) { std::memset(out_boxes, 0, sizeof(std::remove_pointer<decltype(out_boxes)>::type) * BoundingBox::size * anchors_.size()); std::memset(out_labels, 0, sizeof(std::remove_pointer<decltype(out_labels)>::type) * anchors_.size()); } else { for (unsigned int idx = 0; idx < anchors_.size(); idx++) { float *out_box = out_boxes + idx * BoundingBox::size; const auto &anchor = anchors_[idx]; WriteBoxToOutput(out_box, anchor.centroid(), anchor.extent()); out_labels[idx] = 0; } } } // Calculate offset from CenterWH ref box and anchor // based on eq (2) in https://arxiv.org/abs/1512.02325 with extra normalization std::pair<vec2, vec2> GetOffsets(vec2 box_center, vec2 box_extent, vec2 anchor_center, vec2 anchor_extent, const std::vector<float>& means, const std::vector<float>& stds, float scale) { box_center *= scale; box_extent *= scale; anchor_center *= scale; anchor_extent *= scale; vec2 center, extent; center[0] = ((box_center[0] - anchor_center[0]) / anchor_extent[0] - means[0]) / stds[0]; center[1] = ((box_center[1] - anchor_center[1]) / anchor_extent[1] - means[1]) / stds[1]; extent[0] = (std::log(box_extent[0] / anchor_extent[0]) - means[2]) / stds[2]; extent[1] = (std::log(box_extent[1] / anchor_extent[1]) - means[3]) / stds[3]; return std::make_pair(center, extent); } void BoxEncoder<CPUBackend>::WriteMatchesToOutput( const vector<std::pair<unsigned, unsigned>> &matches, const vector<BoundingBox> &boxes, const int *labels, float *out_boxes, int *out_labels) const { if (offset_) { for (const auto &match : matches) { auto box = boxes[match.first]; auto anchor = anchors_[match.second]; vec2 center, extent; std::tie(center, extent) = GetOffsets(box.centroid(), box.extent(), anchor.centroid(), anchor.extent(), means_, stds_, scale_); WriteBoxToOutput(out_boxes + match.second * BoundingBox::size, center, extent); out_labels[match.second] = labels[match.first]; } } else { for (const auto &match : matches) { auto box = boxes[match.first]; WriteBoxToOutput(out_boxes + match.second * BoundingBox::size, box.centroid(), box.extent()); out_labels[match.second] = labels[match.first]; } } } void BoxEncoder<CPUBackend>::RunImpl(SampleWorkspace &ws) { const auto &bboxes_input = ws.Input<CPUBackend>(kBoxesInId); const auto &labels_input = ws.Input<CPUBackend>(kLabelsInId); const auto num_boxes = bboxes_input.dim(0); const auto labels = labels_input.data<int>(); vector<BoundingBox> boxes; boxes.resize(num_boxes); ReadBoxes(make_span(boxes), make_cspan(bboxes_input.data<float>(), bboxes_input.size()), {}, {}); // Create output auto &bboxes_output = ws.Output<CPUBackend>(kBoxesOutId); bboxes_output.set_type(bboxes_input.type()); bboxes_output.Resize({static_cast<int>(anchors_.size()), BoundingBox::size}); auto out_boxes = bboxes_output.mutable_data<float>(); auto &labels_output = ws.Output<CPUBackend>(kLabelsOutId); labels_output.set_type(labels_input.type()); labels_output.Resize({static_cast<int>(anchors_.size())}); auto out_labels = labels_output.mutable_data<int>(); WriteAnchorsToOutput(out_boxes, out_labels); if (num_boxes == 0) return; const auto matches = MatchBoxesWithAnchors(boxes); WriteMatchesToOutput(matches, boxes, labels, out_boxes, out_labels); } DALI_REGISTER_OPERATOR(BoxEncoder, BoxEncoder<CPUBackend>, CPU); DALI_SCHEMA(BoxEncoder) .DocStr( R"code(Encodes the input bounding boxes and labels using a set of default boxes (anchors) passed as an argument. This operator follows the algorithm described in "SSD: Single Shot MultiBox Detector" and implemented in https://github.com/mlperf/training/tree/master/single_stage_detector/ssd. Inputs must be supplied as the following Tensors: - ``BBoxes`` that contain bounding boxes that are represented as ``[l,t,r,b]``. - ``Labels`` that contain the corresponding label for each bounding box. The results are two tensors: - ``EncodedBBoxes`` that contain M-encoded bounding boxes as ``[l,t,r,b]``, where M is number of anchors. - ``EncodedLabels`` that contain the corresponding label for each encoded box. )code") .NumInput(2) .NumOutput(2) .AddArg("anchors", R"code(Anchors to be used for encoding, as the list of floats is in the ``ltrb`` format.)code", DALI_FLOAT_VEC) .AddOptionalArg( "criteria", R"code(Threshold IoU for matching bounding boxes with anchors. The value needs to be between 0 and 1.)code", 0.5f, false) .AddOptionalArg( "offset", R"code(Returns normalized offsets ``((encoded_bboxes*scale - anchors*scale) - mean) / stds`` in EncodedBBoxes that use ``std`` and the ``mean`` and ``scale`` arguments.)code", false) .AddOptionalArg("scale", R"code(Rescales the box and anchor values before the offset is calculated (for example, to return to the absolute values).)code", 1.0f) .AddOptionalArg("means", R"code([x y w h] mean values for normalization.)code", std::vector<float>{0.f, 0.f, 0.f, 0.f}) .AddOptionalArg("stds", R"code([x y w h] standard deviations for offset normalization.)code", std::vector<float>{1.f, 1.f, 1.f, 1.f}); } // namespace dali
; uint in_KeyPressed(uint scancode) SECTION code_clib PUBLIC in_KeyPressed PUBLIC _in_KeyPressed EXTERN l_push_di EXTERN l_pop_ei ; Determines if a key is pressed using the scan code ; returned by in_LookupKey. ; enter : l = scan row ; h = key mask ; exit : carry = key is pressed & HL = 1 ; no carry = key not pressed & HL = 0 ; used : AF,BC,HL ; ; Memory mapped io (in bank1, so 0x6b00 + ) ; Row0-11 = fe, fc... rotate left INCLUDE "target/laser500/def/laser500.def" .in_KeyPressed ._in_KeyPressed call l_push_di ld a,2 out ($41),a ld a,($6ffe) bit 7,l jr nz,check_shift and @01000000 jr z, fail jr consider_ctrl check_shift: ; We expect to be shifted, so fail if not and @01000000 jr nz, fail consider_ctrl: ld a,($6ffc) bit 6,l jr nz,check_ctrl rlca jr nc,fail jr check_actual_key check_ctrl: rlca jr c,fail check_actual_key: ; So now we can check the actual key that's been pressed call getport ld a,(de) cpl ld l,a ld a,(SYSVAR_bank1) out ($41),a call l_pop_ei ld a,l and h ;nc jr z,fail ld hl,1 scf ret fail: ld hl,0 scf ret ; Figure out which port we should be reading from getport: ld de,$6ffe ld a,l and 15 cp 8 jr nc,ports_a_d row_0_9_loop: and a ret z scf rl e rl h dec a jr row_0_9_loop ports_a_d: sub 7 ;So range 1 - 4 neg ;-1 -> -4 add $6b ld d,a ld e,$ff ret
; A001966: Wythoff game. ; 2,7,13,18,23,28,34,39,44,49,54,60,65,70,75,81,86,91,96,102,107,112,117,123,128,133,138,143,149,154,159,164,170,175,180,185,191,196,201,206,212,217,222,227,233,238,243,248,253,259,264,269,274,280,285,290,295,301,306,311,316,322,327,332,337,342,348,353,358,363,369,374,379,384,390,395,400,405,411,416,421,426,431,437,442,447,452,458,463,468,473,479,484,489,494,500,505,510,515,520 mov $2,$0 bin $2,2 mov $3,$0 mul $3,2 mov $5,$0 lpb $2 add $3,1 sub $2,$3 trn $2,1 lpe mov $1,$3 add $1,2 mov $4,$5 mul $4,3 add $1,$4 mov $0,$1
; uint kbd_pressed(uint scancode) ; 09.2005 aralbrec XLIB kbd_pressed ; Determines if a key is pressed using the scan code ; returned by kbd_lookup. ; ; enter : l = scan row ; h = key mask ; exit : carry = key is pressed & hl = 1 ; no carry = key not pressed & hl = 0 ; used : af, bc, hl .kbd_pressed bit 7,h jp z, nocaps ld a,$fe ; check on CAPS key in a,($fe) and $01 jr nz, fail ; CAPS not pressed .nocaps bit 6,h jp z, nosym ld a,$7f ; check on SYM SHIFT in a,($fe) and $02 jr nz, fail ; SYM not pressed .nosym ld a,h and $1f ld b,l ld c,$fe in b,(c) and b jr nz, fail ; key not pressed ld hl,1 scf ret .fail ld hl,0 ret
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #define ITK_TEMPLATE_EXPLICIT_HDF5TransformIO #include "itkHDF5TransformIO.h" #include "itk_H5Cpp.h" #include "itksys/SystemTools.hxx" #include "itksys/SystemInformation.hxx" #include "itkCompositeTransform.h" #include "itkCompositeTransformIOHelper.h" #include "itkVersion.h" #include <sstream> namespace itk { template <typename TParametersValueType> HDF5TransformIOTemplate<TParametersValueType>::HDF5TransformIOTemplate() = default; template <typename TParametersValueType> HDF5TransformIOTemplate<TParametersValueType>::~HDF5TransformIOTemplate() = default; template <typename TParametersValueType> bool HDF5TransformIOTemplate<TParametersValueType>::CanReadFile(const char * fileName) { // HDF5 is so exception happy, we have to worry about // it throwing a wobbly here if the file doesn't exist // or has some other problem. bool rval = true; try { htri_t ishdf5 = H5Fis_hdf5(fileName); if (ishdf5 <= 0) { return false; } H5::H5File h5file(fileName, H5F_ACC_RDONLY); #if (H5_VERS_MAJOR == 1) && (H5_VERS_MINOR < 10) // check the file has the "TransformGroup" htri_t exists = H5Lexists(h5file.getId(), transformGroupName.c_str(), H5P_DEFAULT); if (exists <= 0) #else if (!h5file.exists(transformGroupName)) #endif { rval = false; } } catch (...) { rval = false; } return rval; } template <typename TParametersValueType> bool HDF5TransformIOTemplate<TParametersValueType>::CanWriteFile(const char * fileName) { // // all extensions mentioned in wikipedia + 'hd5' // actually HDF doesn't care about extensions at // all and this is just by convention. const char * extensions[] = { ".hdf", ".h4", ".hdf4", ".h5", ".hdf5", ".he4", ".he5", ".hd5", nullptr, }; std::string ext(itksys::SystemTools::GetFilenameLastExtension(fileName)); for (unsigned int i = 0; extensions[i] != nullptr; ++i) { if (ext == extensions[i]) { return true; } } return false; } template <typename TParametersValueType> H5::PredType HDF5TransformIOTemplate<TParametersValueType>::GetH5TypeFromString() const { const std::string & NameParametersValueTypeString = Superclass::GetTypeNameString(); if (!NameParametersValueTypeString.compare(std::string("double"))) { return H5::PredType::NATIVE_DOUBLE; } else if (!NameParametersValueTypeString.compare(std::string("float"))) { return H5::PredType::NATIVE_FLOAT; } itkExceptionMacro(<< "Wrong data precision type " << NameParametersValueTypeString << "for writing in HDF5 File"); } /** Write a Parameter array to the location specified by name */ template <typename TParametersValueType> void HDF5TransformIOTemplate<TParametersValueType>::WriteParameters(const std::string & name, const ParametersType & parameters) { const hsize_t dim(parameters.Size()); H5::DataSpace paramSpace(1, &dim); H5::DataSet paramSet; // Set the storage format type const H5::PredType h5StorageIdentifier{ GetH5TypeFromString() }; if (this->GetUseCompression()) { // Set compression information // set up properties for chunked, compressed writes. // in this case, set the chunk size to be the N-1 dimension // region H5::DSetCreatPropList plist; plist.setDeflate(5); // Set intermediate compression level constexpr hsize_t oneMegabyte = 1024 * 1024; const hsize_t chunksize = (dim > oneMegabyte) ? oneMegabyte : dim; // Use chunks of 1 MB if large, else use dim plist.setChunk(1, &chunksize); paramSet = this->m_H5File->createDataSet(name, h5StorageIdentifier, paramSpace, plist); } else { paramSet = this->m_H5File->createDataSet(name, h5StorageIdentifier, paramSpace); } paramSet.write(parameters.data_block(), h5StorageIdentifier); paramSet.close(); } template <typename TParametersValueType> void HDF5TransformIOTemplate<TParametersValueType>::WriteFixedParameters(const std::string & name, const FixedParametersType & fixedParameters) { const hsize_t dim(fixedParameters.Size()); H5::DataSpace paramSpace(1, &dim); H5::DataSet paramSet = this->m_H5File->createDataSet(name, H5::PredType::NATIVE_DOUBLE, paramSpace); paramSet.write(fixedParameters.data_block(), H5::PredType::NATIVE_DOUBLE); paramSet.close(); } /** read a parameter array from the location specified by name */ template <typename TParametersValueType> typename HDF5TransformIOTemplate<TParametersValueType>::ParametersType HDF5TransformIOTemplate<TParametersValueType>::ReadParameters(const std::string & DataSetName) const { H5::DataSet paramSet = this->m_H5File->openDataSet(DataSetName); const H5T_class_t Type = paramSet.getTypeClass(); if (Type != H5T_FLOAT) { itkExceptionMacro(<< "Wrong data type for " << DataSetName << "in HDF5 File"); } const H5::DataSpace Space = paramSet.getSpace(); if (Space.getSimpleExtentNdims() != 1) { itkExceptionMacro(<< "Wrong # of dims for TransformType " << "in HDF5 File"); } hsize_t dim; Space.getSimpleExtentDims(&dim, nullptr); ParametersType ParameterArray; ParameterArray.SetSize(dim); H5::FloatType ParamType = paramSet.getFloatType(); if (ParamType.getSize() == sizeof(double)) { const std::unique_ptr<double[]> buf(new double[dim]); paramSet.read(buf.get(), H5::PredType::NATIVE_DOUBLE); for (unsigned int i = 0; i < dim; ++i) { ParameterArray.SetElement(i, static_cast<ParametersValueType>(buf[i])); } } else { const std::unique_ptr<float[]> buf(new float[dim]); paramSet.read(buf.get(), H5::PredType::NATIVE_FLOAT); for (unsigned int i = 0; i < dim; ++i) { ParameterArray.SetElement(i, static_cast<ParametersValueType>(buf[i])); } } paramSet.close(); return ParameterArray; } /** read a parameter array from the location specified by name */ template <typename TParametersValueType> typename HDF5TransformIOTemplate<TParametersValueType>::FixedParametersType HDF5TransformIOTemplate<TParametersValueType>::ReadFixedParameters(const std::string & DataSetName) const { H5::DataSet paramSet = this->m_H5File->openDataSet(DataSetName); H5T_class_t Type = paramSet.getTypeClass(); if (Type != H5T_FLOAT) { itkExceptionMacro(<< "Wrong data type for " << DataSetName << "in HDF5 File"); } const H5::DataSpace Space = paramSet.getSpace(); if (Space.getSimpleExtentNdims() != 1) { itkExceptionMacro(<< "Wrong # of dims for TransformType " << "in HDF5 File"); } hsize_t dim; Space.getSimpleExtentDims(&dim, nullptr); FixedParametersType FixedParameterArray; FixedParameterArray.SetSize(dim); const H5::FloatType ParamType = paramSet.getFloatType(); if (ParamType.getSize() == sizeof(double)) { const std::unique_ptr<double[]> buf(new double[dim]); paramSet.read(buf.get(), H5::PredType::NATIVE_DOUBLE); for (unsigned int i = 0; i < dim; ++i) { FixedParameterArray.SetElement(i, static_cast<FixedParametersValueType>(buf[i])); } } else { const std::unique_ptr<float[]> buf(new float[dim]); paramSet.read(buf.get(), H5::PredType::NATIVE_FLOAT); for (unsigned int i = 0; i < dim; ++i) { FixedParameterArray.SetElement(i, static_cast<FixedParametersValueType>(buf[i])); } } paramSet.close(); return FixedParameterArray; } template <typename TParametersValueType> void HDF5TransformIOTemplate<TParametersValueType>::WriteString(const std::string & path, const std::string & value) { hsize_t numStrings(1); H5::DataSpace strSpace(1, &numStrings); H5::StrType strType(H5::PredType::C_S1, H5T_VARIABLE); H5::DataSet strSet = this->m_H5File->createDataSet(path, strType, strSpace); strSet.write(value, strType); strSet.close(); } template <typename TParametersValueType> void HDF5TransformIOTemplate<TParametersValueType>::WriteString(const std::string & path, const char * s) { const std::string _s(s); WriteString(path, _s); } /* File layout /TransformGroup /TransformGroup/N/TransformType -- string /TransformGroup/N/TransformFixedParameters -- list of double /TransformGroup/N//TransformParameters -- list of double */ template <typename TParametersValueType> void HDF5TransformIOTemplate<TParametersValueType>::Read() { // // HDF5 is pretty heavily exception-oriented. Some // exceptions might be recovered from, theoretically, // but in our case, either the data we want is there // and of the right type, or we give up. So everything // happens in a big try/catch clause try { this->m_H5File = std::make_unique<H5::H5File>(this->GetFileName(), H5F_ACC_RDONLY); // open /TransformGroup H5::Group transformGroup = this->m_H5File->openGroup(transformGroupName); for (unsigned int i = 0; i < transformGroup.getNumObjs(); ++i) { std::string transformName(GetTransformName(i)); // open /TransformGroup/N H5::Group currentTransformGroup = this->m_H5File->openGroup(transformName); // // read transform type std::string transformType; { hsize_t numStrings(1); H5::DataSpace strSpace(1, &numStrings); H5::StrType typeType(H5::PredType::C_S1, H5T_VARIABLE); std::string typeName(transformName); typeName += transformTypeName; H5::DataSet typeSet = this->m_H5File->openDataSet(typeName); typeSet.read(transformType, typeType, strSpace); typeSet.close(); } // Transform name should be modified to have the output precision type. Superclass::CorrectTransformPrecisionType(transformType); TransformPointer transform; this->CreateTransform(transform, transformType); this->GetReadTransformList().push_back(transform); // // Composite transform doesn't store its own parameters if (transformType.find("CompositeTransform") == std::string::npos) { std::string fixedParamsName(transformName + transformFixedName); #if (H5_VERS_MAJOR == 1) && (H5_VERS_MINOR < 10) // check if group exists htri_t exists = H5Lexists(this->m_H5File->getId(), fixedParamsName.c_str(), H5P_DEFAULT); if (exists == 0) { #else if (!this->m_H5File->exists(fixedParamsName)) { #endif fixedParamsName = transformName + transformFixedNameMisspelled; } FixedParametersType fixedparams(this->ReadFixedParameters(fixedParamsName)); transform->SetFixedParameters(fixedparams); std::string paramsName(transformName + transformParamsName); #if (H5_VERS_MAJOR == 1) && (H5_VERS_MINOR < 10) exists = H5Lexists(this->m_H5File->getId(), paramsName.c_str(), H5P_DEFAULT); if (exists == 0) { #else if (!this->m_H5File->exists(paramsName)) { #endif paramsName = transformName + transformParamsNameMisspelled; } ParametersType params = this->ReadParameters(paramsName); transform->SetParametersByValue(params); } currentTransformGroup.close(); } transformGroup.close(); this->m_H5File->close(); } // catch failure caused by the H5File operations catch (H5::Exception & error) { itkExceptionMacro(<< error.getCDetailMsg()); } } template <typename TParametersValueType> void HDF5TransformIOTemplate<TParametersValueType>::WriteOneTransform(const int transformIndex, const TransformType * curTransform) { std::string transformName(GetTransformName(transformIndex)); this->m_H5File->createGroup(transformName); const std::string transformType = curTransform->GetTransformTypeAsString(); // // write out transform type. { std::string typeName(transformName); typeName += transformTypeName; this->WriteString(typeName, transformType); } // // composite transform doesn't store own parameters if (transformType.find("CompositeTransform") != std::string::npos) { if (transformIndex != 0) { itkExceptionMacro(<< "Composite Transform can only be 1st transform in a file"); } } else { // // write out Fixed Parameters FixedParametersType FixedtmpArray = curTransform->GetFixedParameters(); const std::string fixedParamsName(transformName + transformFixedName); this->WriteFixedParameters(fixedParamsName, FixedtmpArray); // parameters ParametersType tmpArray = curTransform->GetParameters(); const std::string paramsName(transformName + transformParamsName); this->WriteParameters(paramsName, tmpArray); } } template <typename TParametersValueType> void HDF5TransformIOTemplate<TParametersValueType>::Write() { itksys::SystemInformation sysInfo; sysInfo.RunOSCheck(); try { H5::FileAccPropList fapl; #if (H5_VERS_MAJOR > 1) || (H5_VERS_MAJOR == 1) && (H5_VERS_MINOR > 10) || \ (H5_VERS_MAJOR == 1) && (H5_VERS_MINOR == 10) && (H5_VERS_RELEASE >= 2) // File format which is backwards compatible with HDF5 version 1.8 // Only HDF5 v1.10.2 has both setLibverBounds method and H5F_LIBVER_V18 constant fapl.setLibverBounds(H5F_LIBVER_V18, H5F_LIBVER_V18); #elif (H5_VERS_MAJOR == 1) && (H5_VERS_MINOR == 10) && (H5_VERS_RELEASE < 2) # error The selected version of HDF5 library does not support setting backwards compatibility at run-time.\ Please use a different version of HDF5, e.g. the one bundled with ITK (by setting ITK_USE_SYSTEM_HDF5 to OFF). #endif this->m_H5File = std::make_unique<H5::H5File>(this->GetFileName(), H5F_ACC_TRUNC, H5::FileCreatPropList::DEFAULT, fapl); this->WriteString(ItkVersion, Version::GetITKVersion()); this->WriteString(HDFVersion, H5_VERS_INFO); this->WriteString(OSName, sysInfo.GetOSName()); this->WriteString(OSVersion, sysInfo.GetOSRelease()); this->m_H5File->createGroup(transformGroupName); ConstTransformListType & transformList = this->GetWriteTransformList(); std::string compositeTransformType = transformList.front()->GetTransformTypeAsString(); CompositeTransformIOHelperTemplate<TParametersValueType> helper; // // if the first transform in the list is a // composite transform, use its internal list // instead of the IO if (compositeTransformType.find("CompositeTransform") != std::string::npos) { transformList = helper.GetTransformList(transformList.front().GetPointer()); } typename ConstTransformListType::const_iterator end = transformList.end(); int count = 0; for (typename ConstTransformListType::const_iterator it = transformList.begin(); it != end; ++it, ++count) { this->WriteOneTransform(count, (*it).GetPointer()); } this->m_H5File->close(); } // catch failure caused by the H5File operations catch (H5::Exception & error) { itkExceptionMacro(<< error.getCDetailMsg()); } } } // end namespace itk namespace itk { // HDF uses hierarchical paths to find particular data // in a file. These strings are used by both reading and // writing. const std::string HDF5CommonPathNames::transformGroupName(std::string("/TransformGroup")); const std::string HDF5CommonPathNames::transformTypeName("/TransformType"); const std::string HDF5CommonPathNames::transformFixedNameMisspelled("/TranformFixedParameters"); const std::string HDF5CommonPathNames::transformParamsNameMisspelled("/TranformParameters"); const std::string HDF5CommonPathNames::transformFixedName("/TransformFixedParameters"); const std::string HDF5CommonPathNames::transformParamsName("/TransformParameters"); const std::string HDF5CommonPathNames::ItkVersion("/ITKVersion"); const std::string HDF5CommonPathNames::HDFVersion("/HDFVersion"); const std::string HDF5CommonPathNames::OSName("/OSName"); const std::string HDF5CommonPathNames::OSVersion("/OSVersion"); // I couldn't figure out a way to represent transforms // excepts as groups -- the HDF5 composite only allows // fixed-size structures. // Since (for now) transforms are ordered in a file, but // not named, I name them by their order in the file, // beginning with zero. const std::string GetTransformName(int i) { std::stringstream s; s << HDF5CommonPathNames::transformGroupName; s << "/"; s << i; return s.str(); } ITK_GCC_PRAGMA_DIAG_PUSH() ITK_GCC_PRAGMA_DIAG(ignored "-Wattributes") template class ITKIOTransformHDF5_EXPORT HDF5TransformIOTemplate<double>; template class ITKIOTransformHDF5_EXPORT HDF5TransformIOTemplate<float>; ITK_GCC_PRAGMA_DIAG_POP() } // end namespace itk
architecture wdc65816-strict include "../../../src/common/assert.inc" constant a = 0x7f0000 assertZeroPage(a) // ERROR
; ---------------------------------------------------------------- ; Z88DK INTERFACE LIBRARY FOR THE BIFROST* ENGINE - RELEASE 1.2/L ; ; See "bifrost_h.h" for further details ; ---------------------------------------------------------------- ; void BIFROSTH_showTilePosH(unsigned int lin,unsigned int col) ; callee SECTION code_clib SECTION code_bifrost_h PUBLIC _BIFROSTH_showTilePosH_callee EXTERN asm_BIFROSTH_showTilePosH _BIFROSTH_showTilePosH_callee: pop hl ; RET address pop bc ; C=lin pop de ; E=col push hl ld d,c ; D=lin jp asm_BIFROSTH_showTilePosH ; execute 'show_tile_pos'
; ----- void xordraw(int x, int y, int x2, int y2) IF !__CPU_INTEL__ & !__CPU_GBZ80__ SECTION code_graphics PUBLIC xordraw PUBLIC _xordraw EXTERN asm_xordraw .xordraw ._xordraw push ix ld ix,2 add ix,sp ld l,(ix+6) ;y0 ld h,(ix+8) ;x0 ld e,(ix+2) ;y1 ld d,(ix+4) ;x1 pop ix jp asm_xordraw ENDIF
;generated via makeasms.bat include raster.i include rastlib.i CGROUP group code code segment dword 'CODE' assume cs:CGROUP,ds:CGROUP RASTLIB_JUMP pj_set_rast RL_SET_RAST code ends end
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/evidently/model/StartExperimentResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::CloudWatchEvidently::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; StartExperimentResult::StartExperimentResult() { } StartExperimentResult::StartExperimentResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } StartExperimentResult& StartExperimentResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("startedTime")) { m_startedTime = jsonValue.GetDouble("startedTime"); } return *this; }
! crtn.s for solaris 2.0. ! Copyright (C) 1992 Free Software Foundation, Inc. ! Written By David Vinayak Henkel-Wallace, June 1992 ! ! This file is free software; you can redistribute it and/or modify it ! under the terms of the GNU General Public License as published by the ! Free Software Foundation; either version 2, or (at your option) any ! later version. ! ! In addition to the permissions in the GNU General Public License, the ! Free Software Foundation gives you unlimited permission to link the ! compiled version of this file with other programs, and to distribute ! those programs without any restriction coming from the use of this ! file. (The General Public License restrictions do apply in other ! respects; for example, they cover modification of the file, and ! distribution when not linked into another program.) ! ! This file is distributed in the hope that it will be useful, but ! WITHOUT ANY WARRANTY; without even the implied warranty of ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ! General Public License for more details. ! ! You should have received a copy of the GNU General Public License ! along with this program; see the file COPYING. If not, write to ! the Free Software Foundation, 59 Temple Place - Suite 330, ! Boston, MA 02111-1307, USA. ! ! As a special exception, if you link this library with files ! compiled with GCC to produce an executable, this does not cause ! the resulting executable to be covered by the GNU General Public License. ! This exception does not however invalidate any other reasons why ! the executable file might be covered by the GNU General Public License. ! ! This file just makes sure that the .fini and .init sections do in ! fact return. Users may put any desired instructions in those sections. ! This file is the last thing linked into any executable. .file "crtn.s" .section ".init" .align 4 ret restore .section ".fini" .align 4 ret restore ! Th-th-th-that is all folks!
; A137823: Numbers occurring in A137822 : first differences of numbers n such that 3 | sum( Catalan(k), k=1..2n). ; 1,2,3,7,8,21,61,62,183,547,548,1641,4921,4922,14763,44287,44288,132861,398581,398582,1195743,3587227,3587228,10761681,32285041,32285042,96855123,290565367,290565368,871696101,2615088301,2615088302 mov $1,$0 sub $0,1 add $0,$1 mov $2,$1 lpb $0,1 mul $1,2 sub $1,1 sub $1,$0 sub $0,3 add $1,$2 mov $2,$1 lpe add $1,1
Name: Move-j.asm Type: file Size: 5779 Last-Modified: '1992-07-14T15:00:00Z' SHA-1: BE71734B6E37ECEFF55703B9DA6CA40EC64829D7 Description: null
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Berkeley Softworks 1990 -- All Rights Reserved PROJECT: PC GEOS MODULE: LaserJet print driver FILE: printcomPCL4Text.asm AUTHOR: Dave Durran ROUTINES: Name Description ---- ----------- PrInitFont Set default font to courier 10 pitch PrintTestStyles Test legality of printer text style word PrintSetStyles Set printer text style word PrintText Print a text string PrintRaw Send raw bytes to the printer PrintSetFont Set a new text mode font PrintSetURWMono12 Set text mode font to URW Mono 12 pt REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 6/92 Initial revision DESCRIPTION: This file contains most of the code to implement the PCL 4 print driver text support $Id: printcomPCL4Text.asm,v 1.1 97/04/18 11:50:06 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ include Text/textGetLineSpacing.asm include Text/textSetLineSpacing.asm include Text/textPrintTextPCL4.asm include Text/textPrintRaw.asm include Text/textSetFontPCL4.asm include Text/textInitFontPCL4.asm include Text/textSetSymbolSet.asm include Text/textLoadNoISOSymbolSet.asm include Text/textPrintStyleRunPCL4.asm include Text/Font/fontTopLevelPCL4.asm include Text/Font/fontDownloadPCL4.asm include Text/Font/fontInternalPCL4.asm include Text/Font/fontUtilsPCL4.asm include Text/Font/fontPCLInfo.asm
; A118608: Start with 1 and repeatedly reverse the digits and add 19 to get the next term. ; 1,20,21,31,32,42,43,53,54,64,65,75,76,86,87,97,98,108,820,47,93,58,104,420,43,53,54,64,65,75,76,86,87,97,98,108,820,47,93,58,104,420,43,53,54,64,65,75,76,86,87,97,98,108,820,47,93,58,104,420,43,53,54,64,65,75,76 mov $2,$0 mov $0,1 lpb $2 seq $0,4086 ; Read n backwards (referred to as R(n) in many sequences). add $0,19 sub $2,1 lpe
//----------------------------------------------------------------------------- /*! * \file compute_metrics.cc * \author Wayne Joubert * \date Wed Sep 23 12:39:13 EDT 2015 * \brief Top-level function to calculate metrics. */ //----------------------------------------------------------------------------- /*----------------------------------------------------------------------------- Copyright 2020, UT-Battelle, LLC Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -----------------------------------------------------------------------------*/ #include "stdio.h" #include "env.hh" #include "vectors.hh" #include "metrics.hh" #include "compute_metrics_2way.hh" #include "compute_metrics_3way.hh" #include "compute_metrics.hh" //============================================================================= void GMComputeMetrics_create( GMComputeMetrics* this_, GMDecompMgr* dm, GMEnv* env) { GMInsist(this_ && dm && env); double time_begin = GMEnv_get_synced_time(env); GMComputeMetrics2Way_create(&(this_->compute_metrics_2way), dm, env); GMComputeMetrics3Way_create(&(this_->compute_metrics_3way), dm, env); double time_end = GMEnv_get_synced_time(env); env->time += time_end - time_begin; } //----------------------------------------------------------------------------- void GMComputeMetrics_destroy( GMComputeMetrics* this_, GMEnv* env) { GMInsist(this_ && env); double time_begin = GMEnv_get_synced_time(env); GMComputeMetrics2Way_destroy(&(this_->compute_metrics_2way), env); GMComputeMetrics3Way_destroy(&(this_->compute_metrics_3way), env); double time_end = GMEnv_get_synced_time(env); env->time += time_end - time_begin; } //============================================================================= void gm_compute_metrics(GMMetrics* metrics, GMVectors* vectors, GMEnv* env) { GMInsist(metrics && vectors && env); if (! GMEnv_is_proc_active(env)) { return; } GMComputeMetrics compute_metrics_value = {0}, *compute_metrics = &compute_metrics_value; GMComputeMetrics_create(compute_metrics, vectors->dm, env); gm_compute_metrics(compute_metrics, metrics, vectors, env); GMComputeMetrics_destroy(compute_metrics, env); } //============================================================================= void gm_compute_metrics(GMComputeMetrics* compute_metrics, GMMetrics* metrics, GMVectors* vectors, GMEnv* env) { GMInsist(metrics && vectors && env); if (! GMEnv_is_proc_active(env)) { return; } // Start timer. double time_begin = GMEnv_get_synced_time(env); // Perform metrics computation. if (GMEnv_num_way(env) == 2 && ! GMEnv_all2all(env)) { gm_compute_metrics_2way_notall2all( &(compute_metrics->compute_metrics_2way), metrics, vectors, env); } else if (GMEnv_num_way(env) == 2 && GMEnv_all2all(env)) { gm_compute_metrics_2way_all2all( &(compute_metrics->compute_metrics_2way), metrics, vectors, env); } else if (GMEnv_num_way(env) == 3 && ! GMEnv_all2all(env)) { gm_compute_metrics_3way_notall2all( &(compute_metrics->compute_metrics_3way), metrics, vectors, env); } else if (GMEnv_num_way(env) == 3 && GMEnv_all2all(env)) { gm_compute_metrics_3way_all2all( &(compute_metrics->compute_metrics_3way), metrics, vectors, env); } else { GMInsistInterface(env, false && "This num_way/all2all combination unimplemented."); } // Stop timer. double time_end = GMEnv_get_synced_time(env); env->time += time_end - time_begin; // Check computed element count. GMInsist(metrics->num_elts_local == metrics->num_elts_local_computed && "Failure to compute all requested metrics."); // Compute global counts of compares and operations. double num_elts_local = metrics->num_elts_local; double num_elts = 0; int mpi_code = MPI_Allreduce(&num_elts_local, &num_elts, 1, MPI_DOUBLE, MPI_SUM, GMEnv_mpi_comm_repl_vector(env)); GMInsist(mpi_code == MPI_SUCCESS && "Failure in call to MPI_Allreduce."); env->compares += metrics->num_field_active * num_elts * metrics->data_type_num_values; env->eltcompares += metrics->num_field_active * num_elts; env->veccompares += num_elts; mpi_code = MPI_Allreduce(&env->ops_local, &env->ops, 1, MPI_DOUBLE, MPI_SUM, GMEnv_mpi_comm_repl_vector(env)); GMInsist(mpi_code == MPI_SUCCESS && "Failure in call to MPI_Allreduce."); // Compute global CPU, GPU memory high water marks. const size_t cpu_mem_max_local = env->cpu_mem_max; mpi_code = MPI_Allreduce(&cpu_mem_max_local, &env->cpu_mem_max, 1, MPI_UNSIGNED_LONG_LONG, MPI_MAX, GMEnv_mpi_comm_repl_vector(env)); GMInsist(mpi_code == MPI_SUCCESS && "Failure in call to MPI_Allreduce."); const size_t gpu_mem_max_local = env->gpu_mem_max; mpi_code = MPI_Allreduce(&gpu_mem_max_local, &env->gpu_mem_max, 1, MPI_UNSIGNED_LONG_LONG, MPI_MAX, GMEnv_mpi_comm_repl_vector(env)); GMInsist(mpi_code == MPI_SUCCESS && "Failure in call to MPI_Allreduce."); } //-----------------------------------------------------------------------------
/****************************************************************************** * Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. * iSulad licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR * PURPOSE. * See the Mulan PSL v2 for more details. * Author: wujing * Create: 2020-12-15 * Description: provide cri container manager service function implementation *********************************************************************************/ #include "cri_container_manager_service_impl.h" #include "cri_helpers.h" #include "utils.h" #include "errors.h" #include "isula_libutils/log.h" #include "isula_libutils/container_stop_request.h" #include "naming.h" #include "path.h" #include "service_container_api.h" #include "request_cache.h" #include "url.h" #include "ws_server.h" namespace CRI { auto ContainerManagerServiceImpl::GetContainerOrSandboxRuntime(const std::string &realID, Errors &error) -> std::string { std::string runtime; if (m_cb == nullptr || m_cb->container.get_runtime == nullptr) { error.SetError("Unimplemented callback"); return runtime; } container_get_runtime_response *response { nullptr }; if (m_cb->container.get_runtime(realID.c_str(), &response) != 0) { if (response != nullptr && response->errmsg != nullptr) { error.SetError(response->errmsg); } else { error.SetError("Failed to call get id callback"); } goto cleanup; } if (response->runtime != nullptr) { runtime = response->runtime; } cleanup: free_container_get_runtime_response(response); return runtime; } auto ContainerManagerServiceImpl::PackCreateContainerHostConfigDevices( const runtime::v1alpha2::ContainerConfig &containerConfig, host_config *hostconfig, Errors &error) -> int { int ret { 0 }; if (containerConfig.devices_size() == 0) { return 0; } if (static_cast<size_t>(containerConfig.devices_size()) > SIZE_MAX / sizeof(host_config_devices_element *)) { error.Errorf("Invalid device size"); return -1; } hostconfig->devices = (host_config_devices_element **)util_common_calloc_s(containerConfig.devices_size() * sizeof(host_config_devices_element *)); if (hostconfig->devices == nullptr) { error.Errorf("Out of memory"); ret = -1; goto out; } for (int i = 0; i < containerConfig.devices_size(); i++) { hostconfig->devices[i] = (host_config_devices_element *)util_common_calloc_s(sizeof(host_config_devices_element)); if (hostconfig->devices[i] == nullptr) { ret = -1; goto out; } hostconfig->devices[i]->path_on_host = util_strdup_s(containerConfig.devices(i).host_path().c_str()); hostconfig->devices[i]->path_in_container = util_strdup_s(containerConfig.devices(i).container_path().c_str()); hostconfig->devices[i]->cgroup_permissions = util_strdup_s(containerConfig.devices(i).permissions().c_str()); hostconfig->devices_len++; } out: return ret; } auto ContainerManagerServiceImpl::PackCreateContainerHostConfigSecurityContext( const runtime::v1alpha2::ContainerConfig &containerConfig, host_config *hostconfig, Errors &error) -> int { if (!containerConfig.linux().has_security_context()) { return 0; } // security Opt Separator Change Version : k8s v1.23.0 (Corresponds to docker 1.11.x) // New version '=' , old version ':', iSulad cri is based on v18.09, so iSulad cri use new version separator const char securityOptSep { '=' }; std::vector<std::string> securityOpts = CRIHelpers::GetSecurityOpts( containerConfig.linux().security_context().seccomp_profile_path(), securityOptSep, error); if (error.NotEmpty()) { error.Errorf("failed to generate security options for container %s", containerConfig.metadata().name().c_str()); return -1; } if (!securityOpts.empty()) { char **tmp_security_opt = nullptr; if (securityOpts.size() > (SIZE_MAX / sizeof(char *)) - hostconfig->security_opt_len) { error.Errorf("Out of memory"); return -1; } size_t newSize = (hostconfig->security_opt_len + securityOpts.size()) * sizeof(char *); size_t oldSize = hostconfig->security_opt_len * sizeof(char *); int ret = util_mem_realloc((void **)(&tmp_security_opt), newSize, (void *)hostconfig->security_opt, oldSize); if (ret != 0) { error.Errorf("Out of memory"); return -1; } hostconfig->security_opt = tmp_security_opt; for (const auto &securityOpt : securityOpts) { hostconfig->security_opt[hostconfig->security_opt_len] = util_strdup_s(securityOpt.c_str()); hostconfig->security_opt_len++; } } return 0; } auto ContainerManagerServiceImpl::GenerateCreateContainerHostConfig( const runtime::v1alpha2::ContainerConfig &containerConfig, Errors &error) -> host_config * { host_config *hostconfig = (host_config *)util_common_calloc_s(sizeof(host_config)); if (hostconfig == nullptr) { error.SetError("Out of memory"); return nullptr; } // iSulad: limit the number of threads in container if (containerConfig.annotations().count("cgroup.pids.max") != 0) { long long int converted = -1; int ret = util_safe_llong(containerConfig.annotations().at("cgroup.pids.max").c_str(), &converted); if (ret != 0) { error.SetError("Cgroup.pids.max is not a valid numeric string"); goto cleanup; } hostconfig->pids_limit = converted; } CRIHelpers::GenerateMountBindings(containerConfig.mounts(), hostconfig, error); if (error.NotEmpty()) { goto cleanup; } if (PackCreateContainerHostConfigDevices(containerConfig, hostconfig, error) != 0) { error.SetError("Failed to pack devices to host config"); goto cleanup; } if (PackCreateContainerHostConfigSecurityContext(containerConfig, hostconfig, error) != 0) { error.SetError("Failed to security context to host config"); goto cleanup; } return hostconfig; cleanup: free_host_config(hostconfig); return nullptr; } void ContainerManagerServiceImpl::MakeContainerConfig(const runtime::v1alpha2::ContainerConfig &config, container_config *cConfig, Errors &error) { if (config.command_size() > 0) { if (static_cast<size_t>(config.command_size()) > SIZE_MAX / sizeof(char *)) { error.SetError("Invalid command size"); return; } cConfig->entrypoint = (char **)util_common_calloc_s(config.command_size() * sizeof(char *)); if (cConfig->entrypoint == nullptr) { error.SetError("Out of memory"); return; } for (int i = 0; i < config.command_size(); i++) { cConfig->entrypoint[i] = util_strdup_s(config.command(i).c_str()); cConfig->entrypoint_len++; } } if (config.args_size() > 0) { if (static_cast<size_t>(config.args_size()) > SIZE_MAX / sizeof(char *)) { error.SetError("Invalid argument size"); return; } cConfig->cmd = (char **)util_common_calloc_s(config.args_size() * sizeof(char *)); if (cConfig->cmd == nullptr) { error.SetError("Out of memory"); return; } for (int i = 0; i < config.args_size(); i++) { cConfig->cmd[i] = util_strdup_s(config.args(i).c_str()); cConfig->cmd_len++; } } if (config.envs_size() > 0) { if (static_cast<size_t>(config.envs_size()) > SIZE_MAX / sizeof(char *)) { error.SetError("Invalid env size"); return; } cConfig->env = (char **)util_common_calloc_s(config.envs_size() * sizeof(char *)); if (cConfig->env == nullptr) { error.SetError("Out of memory"); return; } auto envVect = CRIHelpers::GenerateEnvList(config.envs()); for (size_t i = 0; i < envVect.size(); i++) { cConfig->env[i] = util_strdup_s(envVect.at(i).c_str()); cConfig->env_len++; } } if (!config.working_dir().empty()) { cConfig->working_dir = util_strdup_s(config.working_dir().c_str()); } } auto ContainerManagerServiceImpl::GenerateCreateContainerCustomConfig( const std::string &containerName, const std::string &realPodSandboxID, const runtime::v1alpha2::ContainerConfig &containerConfig, const runtime::v1alpha2::PodSandboxConfig &podSandboxConfig, Errors &error) -> container_config * { container_config *custom_config = (container_config *)util_common_calloc_s(sizeof(container_config)); if (custom_config == nullptr) { error.SetError("Out of memory"); goto cleanup; } custom_config->labels = CRIHelpers::MakeLabels(containerConfig.labels(), error); if (error.NotEmpty()) { goto cleanup; } if (append_json_map_string_string(custom_config->labels, CRIHelpers::Constants::CONTAINER_TYPE_LABEL_KEY.c_str(), CRIHelpers::Constants::CONTAINER_TYPE_LABEL_CONTAINER.c_str()) != 0) { error.SetError("Append map string string failed"); goto cleanup; } custom_config->annotations = CRIHelpers::MakeAnnotations(containerConfig.annotations(), error); if (error.NotEmpty()) { goto cleanup; } if (!podSandboxConfig.log_directory().empty() || !containerConfig.log_path().empty()) { std::string logpath = podSandboxConfig.log_directory() + "/" + containerConfig.log_path(); char real_logpath[PATH_MAX] { 0 }; if (util_clean_path(logpath.c_str(), real_logpath, sizeof(real_logpath)) == nullptr) { ERROR("Failed to clean path: %s", logpath.c_str()); error.Errorf("Failed to clean path: %s", logpath.c_str()); goto cleanup; } if (append_json_map_string_string(custom_config->labels, CRIHelpers::Constants::CONTAINER_LOGPATH_LABEL_KEY.c_str(), real_logpath) != 0) { error.SetError("Append map string string failed"); goto cleanup; } } if (append_json_map_string_string(custom_config->annotations, CRIHelpers::Constants::CONTAINER_TYPE_ANNOTATION_KEY.c_str(), CRIHelpers::Constants::CONTAINER_TYPE_ANNOTATION_CONTAINER.c_str()) != 0) { error.SetError("Append map string string failed"); goto cleanup; } if (append_json_map_string_string(custom_config->annotations, CRIHelpers::Constants::SANDBOX_ID_ANNOTATION_KEY.c_str(), realPodSandboxID.c_str()) != 0) { error.SetError("Append map string string failed"); goto cleanup; } if (podSandboxConfig.has_metadata()) { if (append_json_map_string_string(custom_config->annotations, CRIHelpers::Constants::SANDBOX_NAME_ANNOTATION_KEY.c_str(), podSandboxConfig.metadata().name().c_str()) != 0) { error.SetError("Append sandbox name into annotation failed"); goto cleanup; } if (append_json_map_string_string(custom_config->annotations, CRIHelpers::Constants::SANDBOX_NAMESPACE_ANNOTATION_KEY.c_str(), podSandboxConfig.metadata().namespace_().c_str()) != 0) { error.SetError("Append sandbox namespace into annotation failed"); goto cleanup; } } if (containerConfig.has_metadata()) { if (append_json_map_string_string(custom_config->annotations, CRIHelpers::Constants::CONTAINER_NAME_ANNOTATION_KEY.c_str(), containerConfig.metadata().name().c_str()) != 0) { error.SetError("Append container name into annotation failed"); goto cleanup; } if (append_json_map_string_string(custom_config->annotations, CRIHelpers::Constants::CONTAINER_ATTEMPT_ANNOTATION_KEY.c_str(), std::to_string(containerConfig.metadata().attempt()).c_str()) != 0) { error.SetError("Append container attempt into annotation failed"); goto cleanup; } } if (!containerConfig.image().image().empty()) { if (append_json_map_string_string(custom_config->annotations, CRIHelpers::Constants::IMAGE_NAME_ANNOTATION_KEY.c_str(), containerConfig.image().image().c_str()) != 0) { error.SetError("Append image name into annotation failed"); goto cleanup; } } if (append_json_map_string_string(custom_config->labels, CRIHelpers::Constants::SANDBOX_ID_LABEL_KEY.c_str(), realPodSandboxID.c_str()) != 0) { error.SetError("Append map string string failed"); goto cleanup; } MakeContainerConfig(containerConfig, custom_config, error); if (error.NotEmpty()) { goto cleanup; } return custom_config; cleanup: free_container_config(custom_config); return nullptr; } container_create_request * ContainerManagerServiceImpl::GenerateCreateContainerRequest(const std::string &realPodSandboxID, const runtime::v1alpha2::ContainerConfig &containerConfig, const runtime::v1alpha2::PodSandboxConfig &podSandboxConfig, const std::string &podSandboxRuntime, Errors &error) { struct parser_context ctx { OPT_GEN_SIMPLIFY, 0 }; parser_error perror { nullptr }; container_create_request *request = (container_create_request *)util_common_calloc_s(sizeof(*request)); if (request == nullptr) { error.SetError("Out of memory"); return nullptr; } std::string cname = CRINaming::MakeContainerName(podSandboxConfig, containerConfig); request->id = util_strdup_s(cname.c_str()); if (!podSandboxRuntime.empty()) { request->runtime = util_strdup_s(podSandboxRuntime.c_str()); } if (!containerConfig.image().image().empty()) { request->image = util_strdup_s(containerConfig.image().image().c_str()); } container_config *custom_config { nullptr }; host_config *hostconfig = GenerateCreateContainerHostConfig(containerConfig, error); if (error.NotEmpty()) { goto cleanup; } if (podSandboxConfig.has_linux() && !podSandboxConfig.linux().cgroup_parent().empty()) { hostconfig->cgroup_parent = util_strdup_s(podSandboxConfig.linux().cgroup_parent().c_str()); } custom_config = GenerateCreateContainerCustomConfig(cname, realPodSandboxID, containerConfig, podSandboxConfig, error); if (error.NotEmpty()) { goto cleanup; } CRIHelpers::UpdateCreateConfig(custom_config, hostconfig, containerConfig, realPodSandboxID, error); if (error.NotEmpty()) { goto cleanup; } request->hostconfig = host_config_generate_json(hostconfig, &ctx, &perror); if (request->hostconfig == nullptr) { error.Errorf("Failed to generate host config json: %s", perror); free_container_create_request(request); request = nullptr; goto cleanup; } request->customconfig = container_config_generate_json(custom_config, &ctx, &perror); if (request->customconfig == nullptr) { error.Errorf("Failed to generate custom config json: %s", perror); free_container_create_request(request); request = nullptr; goto cleanup; } cleanup: free_host_config(hostconfig); free_container_config(custom_config); free(perror); return request; } std::string ContainerManagerServiceImpl::CreateContainer( const std::string &podSandboxID, const runtime::v1alpha2::ContainerConfig &containerConfig, const runtime::v1alpha2::PodSandboxConfig &podSandboxConfig, Errors &error) { std::string response_id; std::string podSandboxRuntime; if (m_cb == nullptr || m_cb->container.create == nullptr) { error.SetError("Unimplemented callback"); return response_id; } container_create_request *request { nullptr }; container_create_response *response { nullptr }; std::string realPodSandboxID = CRIHelpers::GetRealContainerOrSandboxID(m_cb, podSandboxID, true, error); if (error.NotEmpty()) { ERROR("Failed to find sandbox id %s: %s", podSandboxID.c_str(), error.GetCMessage()); error.Errorf("Failed to find sandbox id %s: %s", podSandboxID.c_str(), error.GetCMessage()); goto cleanup; } podSandboxRuntime = GetContainerOrSandboxRuntime(realPodSandboxID, error); request = GenerateCreateContainerRequest(realPodSandboxID, containerConfig, podSandboxConfig, podSandboxRuntime, error); if (error.NotEmpty()) { error.SetError("Failed to generate create container request"); goto cleanup; } if (m_cb->container.create(request, &response) != 0) { if (response != nullptr && (response->errmsg != nullptr)) { error.SetError(response->errmsg); } else { error.SetError("Failed to call create container callback"); } goto cleanup; } response_id = response->id; cleanup: free_container_create_request(request); free_container_create_response(response); return response_id; } void ContainerManagerServiceImpl::CreateContainerLogSymlink(const std::string &containerID, Errors &error) { char *path { nullptr }; char *realPath { nullptr }; CRIHelpers::GetContainerLogPath(containerID, &path, &realPath, error); if (error.NotEmpty()) { error.Errorf("failed to get container %s log path: %s", containerID.c_str(), error.GetCMessage()); return; } if (path == nullptr) { INFO("Container %s log path isn't specified, will not create the symlink", containerID.c_str()); goto cleanup; } if (realPath != nullptr) { if (util_path_remove(path) == 0) { WARN("Deleted previously existing symlink file: %s", path); } if (symlink(realPath, path) != 0) { error.Errorf("failed to create symbolic link %s to the container log file %s for container %s: %s", path, realPath, containerID.c_str(), strerror(errno)); goto cleanup; } } else { WARN("Cannot create symbolic link because container log file doesn't exist!"); } cleanup: free(path); free(realPath); } void ContainerManagerServiceImpl::StartContainer(const std::string &containerID, Errors &error) { if (containerID.empty()) { error.SetError("Invalid empty container id."); return; } std::string realContainerID = CRIHelpers::GetRealContainerOrSandboxID(m_cb, containerID, false, error); if (error.NotEmpty()) { ERROR("Failed to find container id %s: %s", containerID.c_str(), error.GetCMessage()); error.Errorf("Failed to find container id %s: %s", containerID.c_str(), error.GetCMessage()); return; } if (m_cb == nullptr || m_cb->container.start == nullptr) { error.SetError("Unimplemented callback"); return; } container_start_response *response { nullptr }; int ret {}; container_start_request *request = (container_start_request *)util_common_calloc_s(sizeof(container_start_request)); if (request == nullptr) { error.SetError("Out of memory"); goto cleanup; } request->id = util_strdup_s(realContainerID.c_str()); ret = m_cb->container.start(request, &response, -1, nullptr, nullptr); // Create container log symlink for all containers (including failed ones). CreateContainerLogSymlink(realContainerID, error); if (error.NotEmpty()) { goto cleanup; } if (ret != 0) { if (response != nullptr && response->errmsg != nullptr) { error.SetError(response->errmsg); } else { error.SetError("Failed to call start container callback"); } goto cleanup; } cleanup: free_container_start_request(request); free_container_start_response(response); } void ContainerManagerServiceImpl::StopContainer(const std::string &containerID, int64_t timeout, Errors &error) { CRIHelpers::StopContainer(m_cb, containerID, timeout, error); } void ContainerManagerServiceImpl::RemoveContainer(const std::string &containerID, Errors &error) { CRIHelpers::RemoveContainer(m_cb, containerID, error); } void ContainerManagerServiceImpl::ListContainersFromGRPC(const runtime::v1alpha2::ContainerFilter *filter, container_list_request **request, Errors &error) { *request = (container_list_request *)util_common_calloc_s(sizeof(container_list_request)); if (*request == nullptr) { error.SetError("Out of memory"); return; } (*request)->all = true; (*request)->filters = (defs_filters *)util_common_calloc_s(sizeof(defs_filters)); if ((*request)->filters == nullptr) { error.SetError("Out of memory"); return; } // Add filter to get only non-sandbox containers if (CRIHelpers::FiltersAddLabel((*request)->filters, CRIHelpers::Constants::CONTAINER_TYPE_LABEL_KEY, CRIHelpers::Constants::CONTAINER_TYPE_LABEL_CONTAINER) != 0) { error.SetError("Failed to add filter"); return; } if (filter != nullptr) { if (!filter->id().empty()) { if (CRIHelpers::FiltersAdd((*request)->filters, "id", filter->id()) != 0) { error.SetError("Failed to add filter"); return; } } if (filter->has_state()) { if (CRIHelpers::FiltersAdd((*request)->filters, "status", CRIHelpers::ToIsuladContainerStatus(filter->state())) != 0) { error.SetError("Failed to add filter"); return; } } if (!filter->pod_sandbox_id().empty()) { if (CRIHelpers::FiltersAddLabel((*request)->filters, CRIHelpers::Constants::SANDBOX_ID_LABEL_KEY, filter->pod_sandbox_id()) != 0) { error.SetError("Failed to add filter"); return; } } for (auto &iter : filter->label_selector()) { if (CRIHelpers::FiltersAddLabel((*request)->filters, iter.first, iter.second) != 0) { error.SetError("Failed to add filter"); return; } } } } void ContainerManagerServiceImpl::ListContainersToGRPC(container_list_response *response, std::vector<std::unique_ptr<runtime::v1alpha2::Container>> *pods, Errors &error) { for (size_t i {}; i < response->containers_len; i++) { std::unique_ptr<runtime::v1alpha2::Container> container(new (std::nothrow) runtime::v1alpha2::Container); if (container == nullptr) { error.SetError("Out of memory"); return; } if (response->containers[i]->id != nullptr) { container->set_id(response->containers[i]->id); } container->set_created_at(response->containers[i]->created); CRIHelpers::ExtractLabels(response->containers[i]->labels, *container->mutable_labels()); CRIHelpers::ExtractAnnotations(response->containers[i]->annotations, *container->mutable_annotations()); CRINaming::ParseContainerName(container->annotations(), container->mutable_metadata(), error); if (error.NotEmpty()) { return; } if (response->containers[i]->labels != nullptr) { for (size_t j = 0; j < response->containers[i]->labels->len; j++) { if (strcmp(response->containers[i]->labels->keys[j], CRIHelpers::Constants::SANDBOX_ID_LABEL_KEY.c_str()) == 0) { container->set_pod_sandbox_id(response->containers[i]->labels->values[j]); break; } } } if (response->containers[i]->image != nullptr) { runtime::v1alpha2::ImageSpec *image = container->mutable_image(); image->set_image(response->containers[i]->image); std::string imageID = CRIHelpers::ToPullableImageID(response->containers[i]->image, response->containers[i]->image_ref); container->set_image_ref(imageID); } runtime::v1alpha2::ContainerState state = CRIHelpers::ContainerStatusToRuntime(Container_Status(response->containers[i]->status)); container->set_state(state); pods->push_back(move(container)); } } void ContainerManagerServiceImpl::ListContainers(const runtime::v1alpha2::ContainerFilter *filter, std::vector<std::unique_ptr<runtime::v1alpha2::Container>> *containers, Errors &error) { if (m_cb == nullptr || m_cb->container.list == nullptr) { error.SetError("Unimplemented callback"); return; } container_list_response *response { nullptr }; container_list_request *request { nullptr }; ListContainersFromGRPC(filter, &request, error); if (error.NotEmpty()) { goto cleanup; } if (m_cb->container.list(request, &response) != 0) { if (response != nullptr && response->errmsg != nullptr) { error.SetError(response->errmsg); } else { error.SetError("Failed to call list container callback"); } goto cleanup; } ListContainersToGRPC(response, containers, error); cleanup: free_container_list_request(request); free_container_list_response(response); } auto ContainerManagerServiceImpl::PackContainerStatsFilter(const runtime::v1alpha2::ContainerStatsFilter *filter, container_stats_request *request, Errors &error) -> int { if (filter == nullptr) { return 0; } if (!filter->id().empty()) { if (CRIHelpers::FiltersAdd(request->filters, "id", filter->id()) != 0) { error.SetError("Failed to add filter"); return -1; } } if (!filter->pod_sandbox_id().empty()) { if (CRIHelpers::FiltersAddLabel(request->filters, CRIHelpers::Constants::SANDBOX_ID_LABEL_KEY, filter->pod_sandbox_id()) != 0) { error.SetError("Failed to add filter"); return -1; } } // Add some label if (CRIHelpers::FiltersAddLabel(request->filters, CRIHelpers::Constants::CONTAINER_TYPE_LABEL_KEY, CRIHelpers::Constants::CONTAINER_TYPE_LABEL_CONTAINER) != 0) { error.SetError("Failed to add filter"); return -1; } for (auto &iter : filter->label_selector()) { if (CRIHelpers::FiltersAddLabel(request->filters, iter.first, iter.second) != 0) { error.SetError("Failed to add filter"); return -1; } } return 0; } void ContainerManagerServiceImpl::PackContainerStatsAttributes( const char *id, std::unique_ptr<runtime::v1alpha2::ContainerStats> &container, Errors &error) { if (id == nullptr) { return; } container->mutable_attributes()->set_id(id); auto status = ContainerStatus(std::string(id), error); if (status == nullptr) { return; } if (status->has_metadata()) { std::unique_ptr<runtime::v1alpha2::ContainerMetadata> metadata( new (std::nothrow) runtime::v1alpha2::ContainerMetadata(status->metadata())); if (metadata == nullptr) { error.SetError("Out of memory"); ERROR("Out of memory"); return; } container->mutable_attributes()->set_allocated_metadata(metadata.release()); } if (status->labels_size() > 0) { auto labels = container->mutable_attributes()->mutable_labels(); *labels = status->labels(); } if (status->annotations_size() > 0) { auto annotations = container->mutable_attributes()->mutable_annotations(); *annotations = status->annotations(); } } void ContainerManagerServiceImpl::SetFsUsage(const imagetool_fs_info *fs_usage, int64_t timestamp, std::unique_ptr<runtime::v1alpha2::ContainerStats> &container) { if (fs_usage == nullptr || fs_usage->image_filesystems_len == 0 || fs_usage->image_filesystems[0] == nullptr) { container->mutable_writable_layer()->mutable_used_bytes()->set_value(0); container->mutable_writable_layer()->mutable_inodes_used()->set_value(0); return; } if (fs_usage->image_filesystems[0]->used_bytes == nullptr) { container->mutable_writable_layer()->mutable_used_bytes()->set_value(0); } else { container->mutable_writable_layer()->mutable_used_bytes()->set_value( fs_usage->image_filesystems[0]->used_bytes->value); } if (fs_usage->image_filesystems[0]->inodes_used == nullptr) { container->mutable_writable_layer()->mutable_inodes_used()->set_value(0); } else { container->mutable_writable_layer()->mutable_inodes_used()->set_value( fs_usage->image_filesystems[0]->inodes_used->value); } container->mutable_writable_layer()->set_timestamp(timestamp); if (fs_usage->image_filesystems[0]->fs_id != nullptr && fs_usage->image_filesystems[0]->fs_id->mountpoint != nullptr) { container->mutable_writable_layer()->mutable_fs_id()->set_mountpoint( fs_usage->image_filesystems[0]->fs_id->mountpoint); } } void ContainerManagerServiceImpl::PackContainerStatsFilesystemUsage( const char *id, const char *image_type, int64_t timestamp, std::unique_ptr<runtime::v1alpha2::ContainerStats> &container) { if (id == nullptr || image_type == nullptr) { return; } imagetool_fs_info *fs_usage { nullptr }; if (im_get_container_filesystem_usage(image_type, id, &fs_usage) != 0) { ERROR("Failed to get container filesystem usage"); } SetFsUsage(fs_usage, timestamp, container); free_imagetool_fs_info(fs_usage); } void ContainerManagerServiceImpl::ContainerStatsToGRPC( container_stats_response *response, std::vector<std::unique_ptr<runtime::v1alpha2::ContainerStats>> *containerstats, Errors &error) { if (response == nullptr) { return; } for (size_t i {}; i < response->container_stats_len; i++) { using ContainerStatsPtr = std::unique_ptr<runtime::v1alpha2::ContainerStats>; ContainerStatsPtr container(new (std::nothrow) runtime::v1alpha2::ContainerStats); if (container == nullptr) { ERROR("Out of memory"); return; } PackContainerStatsAttributes(response->container_stats[i]->id, container, error); if (error.NotEmpty()) { return; } int64_t timestamp = util_get_now_time_nanos(); PackContainerStatsFilesystemUsage(response->container_stats[i]->id, response->container_stats[i]->image_type, timestamp, container); if (response->container_stats[i]->mem_used != 0u) { uint64_t workingset = response->container_stats[i]->mem_used; if (response->container_stats[i]->inactive_file_total < response->container_stats[i]->mem_used) { workingset = response->container_stats[i]->mem_used - response->container_stats[i]->inactive_file_total; } container->mutable_memory()->mutable_working_set_bytes()->set_value(workingset); container->mutable_memory()->set_timestamp(timestamp); } if (response->container_stats[i]->cpu_use_nanos != 0u) { container->mutable_cpu()->mutable_usage_core_nano_seconds()->set_value( response->container_stats[i]->cpu_use_nanos); container->mutable_cpu()->set_timestamp(timestamp); } containerstats->push_back(move(container)); } } void ContainerManagerServiceImpl::ListContainerStats( const runtime::v1alpha2::ContainerStatsFilter *filter, std::vector<std::unique_ptr<runtime::v1alpha2::ContainerStats>> *containerstats, Errors &error) { if (m_cb == nullptr || m_cb->container.stats == nullptr) { error.SetError("Unimplemented callback"); return; } if (containerstats == nullptr) { error.SetError("Invalid arguments"); return; } container_stats_response *response { nullptr }; container_stats_request *request = (container_stats_request *)util_common_calloc_s(sizeof(container_stats_request)); if (request == nullptr) { error.SetError("Out of memory"); goto cleanup; } request->all = true; request->filters = (defs_filters *)util_common_calloc_s(sizeof(defs_filters)); if (request->filters == nullptr) { error.SetError("Out of memory"); goto cleanup; } if (PackContainerStatsFilter(filter, request, error) != 0) { goto cleanup; } if (m_cb->container.stats(request, &response) != 0) { if (response != nullptr && response->errmsg != nullptr) { error.SetError(response->errmsg); } else { error.SetError("Failed to call stats container callback"); } goto cleanup; } ContainerStatsToGRPC(response, containerstats, error); cleanup: free_container_stats_request(request); free_container_stats_response(response); } void ContainerManagerServiceImpl::PackContainerImageToStatus( container_inspect *inspect, std::unique_ptr<runtime::v1alpha2::ContainerStatus> &contStatus, Errors &error) { if (inspect->config == nullptr) { return; } if (inspect->config->image != nullptr) { contStatus->mutable_image()->set_image(inspect->config->image); } contStatus->set_image_ref(CRIHelpers::ToPullableImageID(inspect->config->image, inspect->config->image_ref)); return; } void ContainerManagerServiceImpl::UpdateBaseStatusFromInspect( container_inspect *inspect, int64_t &createdAt, int64_t &startedAt, int64_t &finishedAt, std::unique_ptr<runtime::v1alpha2::ContainerStatus> &contStatus) { runtime::v1alpha2::ContainerState state { runtime::v1alpha2::CONTAINER_UNKNOWN }; std::string reason; std::string message; int32_t exitCode { 0 }; if (inspect->state == nullptr) { goto pack_status; } if (inspect->state->running) { // Container is running state = runtime::v1alpha2::CONTAINER_RUNNING; } else { // Container is not running. if (finishedAt != 0) { // Case 1 state = runtime::v1alpha2::CONTAINER_EXITED; if (inspect->state->exit_code == 0) { reason = "Completed"; } else { reason = "Error"; } } else if (inspect->state->exit_code != 0) { // Case 2 state = runtime::v1alpha2::CONTAINER_EXITED; finishedAt = createdAt; startedAt = createdAt; reason = "ContainerCannotRun"; } else { // Case 3 state = runtime::v1alpha2::CONTAINER_CREATED; } if (inspect->state->error != nullptr) { message = inspect->state->error; } exitCode = (int32_t)inspect->state->exit_code; } pack_status: contStatus->set_exit_code(exitCode); contStatus->set_state(state); contStatus->set_created_at(createdAt); contStatus->set_started_at(startedAt); contStatus->set_finished_at(finishedAt); contStatus->set_reason(reason); contStatus->set_message(message); } void ContainerManagerServiceImpl::PackLabelsToStatus(container_inspect *inspect, std::unique_ptr<runtime::v1alpha2::ContainerStatus> &contStatus) { if (inspect->config == nullptr || inspect->config->labels == nullptr) { return; } CRIHelpers::ExtractLabels(inspect->config->labels, *contStatus->mutable_labels()); CRIHelpers::ExtractAnnotations(inspect->config->annotations, *contStatus->mutable_annotations()); for (size_t i = 0; i < inspect->config->labels->len; i++) { if (strcmp(inspect->config->labels->keys[i], CRIHelpers::Constants::CONTAINER_LOGPATH_LABEL_KEY.c_str()) == 0) { contStatus->set_log_path(inspect->config->labels->values[i]); break; } } } void ContainerManagerServiceImpl::ConvertMountsToStatus(container_inspect *inspect, std::unique_ptr<runtime::v1alpha2::ContainerStatus> &contStatus) { for (size_t i = 0; i < inspect->mounts_len; i++) { runtime::v1alpha2::Mount *mount = contStatus->add_mounts(); mount->set_host_path(inspect->mounts[i]->source); mount->set_container_path(inspect->mounts[i]->destination); mount->set_readonly(!inspect->mounts[i]->rw); if (inspect->mounts[i]->propagation == nullptr || strcmp(inspect->mounts[i]->propagation, "rprivate") == 0) { mount->set_propagation(runtime::v1alpha2::PROPAGATION_PRIVATE); } else if (strcmp(inspect->mounts[i]->propagation, "rslave") == 0) { mount->set_propagation(runtime::v1alpha2::PROPAGATION_HOST_TO_CONTAINER); } else if (strcmp(inspect->mounts[i]->propagation, "rshared") == 0) { mount->set_propagation(runtime::v1alpha2::PROPAGATION_BIDIRECTIONAL); } // Note: Can't set SeLinuxRelabel } } void ContainerManagerServiceImpl::ContainerStatusToGRPC(container_inspect *inspect, std::unique_ptr<runtime::v1alpha2::ContainerStatus> &contStatus, Errors &error) { if (inspect->id != nullptr) { contStatus->set_id(inspect->id); } int64_t createdAt {}; int64_t startedAt {}; int64_t finishedAt {}; CRIHelpers::GetContainerTimeStamps(inspect, &createdAt, &startedAt, &finishedAt, error); if (error.NotEmpty()) { return; } contStatus->set_created_at(createdAt); contStatus->set_started_at(startedAt); contStatus->set_finished_at(finishedAt); PackContainerImageToStatus(inspect, contStatus, error); UpdateBaseStatusFromInspect(inspect, createdAt, startedAt, finishedAt, contStatus); PackLabelsToStatus(inspect, contStatus); CRINaming::ParseContainerName(contStatus->annotations(), contStatus->mutable_metadata(), error); if (error.NotEmpty()) { return; } ConvertMountsToStatus(inspect, contStatus); } std::unique_ptr<runtime::v1alpha2::ContainerStatus> ContainerManagerServiceImpl::ContainerStatus(const std::string &containerID, Errors &error) { if (containerID.empty()) { error.SetError("Empty pod sandbox id"); return nullptr; } std::string realContainerID = CRIHelpers::GetRealContainerOrSandboxID(m_cb, containerID, false, error); if (error.NotEmpty()) { ERROR("Failed to find container id %s: %s", containerID.c_str(), error.GetCMessage()); error.Errorf("Failed to find container id %s: %s", containerID.c_str(), error.GetCMessage()); return nullptr; } container_inspect *inspect = CRIHelpers::InspectContainer(realContainerID, error, false); if (error.NotEmpty()) { return nullptr; } if (inspect == nullptr) { error.SetError("Get null inspect"); return nullptr; } using ContainerStatusPtr = std::unique_ptr<runtime::v1alpha2::ContainerStatus>; ContainerStatusPtr contStatus(new (std::nothrow) runtime::v1alpha2::ContainerStatus); if (contStatus == nullptr) { error.SetError("Out of memory"); return nullptr; } ContainerStatusToGRPC(inspect, contStatus, error); free_container_inspect(inspect); return contStatus; } void ContainerManagerServiceImpl::UpdateContainerResources(const std::string &containerID, const runtime::v1alpha2::LinuxContainerResources &resources, Errors &error) { if (containerID.empty()) { error.SetError("Invalid empty container id."); return; } std::string realContainerID = CRIHelpers::GetRealContainerOrSandboxID(m_cb, containerID, false, error); if (error.NotEmpty()) { ERROR("Failed to find container id %s: %s", containerID.c_str(), error.GetCMessage()); error.Errorf("Failed to find container id %s: %s", containerID.c_str(), error.GetCMessage()); return; } if (m_cb == nullptr || m_cb->container.update == nullptr) { error.SetError("Unimplemented callback"); return; } container_update_request *request { nullptr }; container_update_response *response { nullptr }; host_config *hostconfig { nullptr }; parser_error perror { nullptr }; struct parser_context ctx { OPT_GEN_SIMPLIFY, 0 }; request = (container_update_request *)util_common_calloc_s(sizeof(container_update_request)); if (request == nullptr) { error.SetError("Out of memory"); goto cleanup; } request->name = util_strdup_s(realContainerID.c_str()); hostconfig = (host_config *)util_common_calloc_s(sizeof(host_config)); if (hostconfig == nullptr) { error.SetError("Out of memory"); goto cleanup; } hostconfig->cpu_period = resources.cpu_period(); hostconfig->cpu_quota = resources.cpu_quota(); hostconfig->cpu_shares = resources.cpu_shares(); hostconfig->memory = resources.memory_limit_in_bytes(); if (!resources.cpuset_cpus().empty()) { hostconfig->cpuset_cpus = util_strdup_s(resources.cpuset_cpus().c_str()); } if (!resources.cpuset_mems().empty()) { hostconfig->cpuset_mems = util_strdup_s(resources.cpuset_mems().c_str()); } request->host_config = host_config_generate_json(hostconfig, &ctx, &perror); if (request->host_config == nullptr) { error.Errorf("Failed to generate host config json: %s", perror); goto cleanup; } INFO("hostconfig: %s", request->host_config); if (m_cb->container.update(request, &response) != 0) { if (response != nullptr && response->errmsg != nullptr) { error.SetError(response->errmsg); } else { error.SetError("Failed to call update container callback"); } } cleanup: free_container_update_request(request); free_container_update_response(response); free_host_config(hostconfig); free(perror); } void ContainerManagerServiceImpl::ExecSyncFromGRPC(const std::string &containerID, const google::protobuf::RepeatedPtrField<std::string> &cmd, int64_t timeout, container_exec_request **request, Errors &error) { if (timeout < 0) { error.SetError("Exec timeout cannot be negative."); return; } *request = (container_exec_request *)util_common_calloc_s(sizeof(container_exec_request)); if (*request == nullptr) { error.SetError("Out of memory"); return; } (*request)->tty = false; (*request)->attach_stdin = false; (*request)->attach_stdout = true; (*request)->attach_stderr = true; (*request)->timeout = timeout; (*request)->container_id = util_strdup_s(containerID.c_str()); if (!cmd.empty()) { if ((size_t)cmd.size() > INT_MAX / sizeof(char *)) { error.SetError("Too many cmd args"); return; } (*request)->argv = (char **)util_common_calloc_s(cmd.size() * sizeof(char *)); if ((*request)->argv == nullptr) { error.SetError("Out of memory"); return; } for (int i = 0; i < cmd.size(); i++) { (*request)->argv[i] = util_strdup_s(cmd[i].c_str()); (*request)->argv_len++; } } (*request)->suffix = CRIHelpers::GenerateExecSuffix(); if ((*request)->suffix == nullptr) { error.SetError("Failed to generate exec suffix(id)"); return; } } static auto WriteToString(void *context, const void *data, size_t len) -> ssize_t { if (len == 0) { return 0; } std::string *str = reinterpret_cast<std::string *>(context); str->append(reinterpret_cast<const char *>(data), len); return (ssize_t)len; } void ContainerManagerServiceImpl::ExecSync(const std::string &containerID, const google::protobuf::RepeatedPtrField<std::string> &cmd, int64_t timeout, runtime::v1alpha2::ExecSyncResponse *reply, Errors &error) { struct io_write_wrapper StdoutstringWriter = { 0 }; struct io_write_wrapper StderrstringWriter = { 0 }; if (m_cb == nullptr || m_cb->container.exec == nullptr) { error.SetError("Unimplemented callback"); return; } if (containerID.empty()) { error.SetError("Invalid empty container id."); return; } std::string realContainerID = CRIHelpers::GetRealContainerOrSandboxID(m_cb, containerID, false, error); if (error.NotEmpty()) { ERROR("Failed to find container id %s: %s", containerID.c_str(), error.GetCMessage()); error.Errorf("Failed to find container id %s: %s", containerID.c_str(), error.GetCMessage()); return; } container_exec_response *response { nullptr }; container_exec_request *request { nullptr }; ExecSyncFromGRPC(realContainerID, cmd, timeout, &request, error); if (error.NotEmpty()) { goto cleanup; } StdoutstringWriter.context = (void *)reply->mutable_stdout(); StdoutstringWriter.write_func = WriteToString; StderrstringWriter.context = (void *)reply->mutable_stderr(); StderrstringWriter.write_func = WriteToString; if (m_cb->container.exec(request, &response, -1, &StdoutstringWriter, &StderrstringWriter) != 0) { if (response != nullptr && response->errmsg != nullptr) { error.SetError(response->errmsg); } else { error.SetError("Failed to call exec container callback"); } goto cleanup; } reply->set_exit_code((::google::protobuf::uint32)(response->exit_code)); cleanup: free_container_exec_request(request); free_container_exec_response(response); } auto ContainerManagerServiceImpl::BuildURL(const std::string &method, const std::string &token) -> std::string { url::URLDatum url; url.SetPathWithoutEscape("/cri/" + method + "/" + token); WebsocketServer *server = WebsocketServer::GetInstance(); url::URLDatum wsurl = server->GetWebsocketUrl(); return wsurl.ResolveReference(&url)->String(); } auto ContainerManagerServiceImpl::InspectContainerState(const std::string &Id, Errors &err) -> container_inspect_state * { container_inspect_state *inspect_data { nullptr }; inspect_data = inspect_container_state((const char *)Id.c_str(), 0); if (inspect_data == nullptr) { err.Errorf("Failed to call inspect service %s", Id.c_str()); } return inspect_data; } auto ContainerManagerServiceImpl::ValidateExecRequest(const runtime::v1alpha2::ExecRequest &req, Errors &error) -> int { if (req.container_id().empty()) { error.SetError("missing required container id!"); return -1; } std::string realContainerID = CRIHelpers::GetRealContainerOrSandboxID(m_cb, req.container_id(), false, error); if (error.NotEmpty()) { ERROR("Failed to find container id %s: %s", req.container_id().c_str(), error.GetCMessage()); error.Errorf("Failed to find container id %s: %s", req.container_id().c_str(), error.GetCMessage()); return -1; } container_inspect_state *state = InspectContainerState(realContainerID, error); if (error.NotEmpty()) { ERROR("Failed to inspect container id %s: %s state", req.container_id().c_str(), error.GetCMessage()); error.Errorf("Failed to inspect container id %s: %s state", req.container_id().c_str(), error.GetCMessage()); return -1; } bool running = state != nullptr && state->running; bool paused = state != nullptr && state->paused; free_container_inspect_state(state); if (!running) { ERROR("Container is not running: %s", req.container_id().c_str()); error.Errorf("Container is not running: %s", req.container_id().c_str()); return -1; } if (paused) { ERROR("Container %s is paused, unpause the container before exec", req.container_id().c_str()); error.Errorf("Container %s is paused, unpause the container before exec", req.container_id().c_str()); return -1; } if (req.tty() && req.stderr()) { error.SetError("tty and stderr cannot both be true!"); return -1; } if (!req.stdin() && !req.stdout() && !req.stderr()) { error.SetError("one of stdin, stdout, or stderr must be set!"); return -1; } return 0; } void ContainerManagerServiceImpl::Exec(const runtime::v1alpha2::ExecRequest &req, runtime::v1alpha2::ExecResponse *resp, Errors &error) { if (ValidateExecRequest(req, error) != 0) { return; } RequestCache *cache = RequestCache::GetInstance(); std::string token = cache->InsertExecRequest(req); if (token.empty()) { error.SetError("failed to get a unique token!"); return; } std::string url = BuildURL("exec", token); resp->set_url(url); } auto ContainerManagerServiceImpl::ValidateAttachRequest(const runtime::v1alpha2::AttachRequest &req, Errors &error) -> int { if (req.container_id().empty()) { error.SetError("missing required container id!"); return -1; } (void)CRIHelpers::GetRealContainerOrSandboxID(m_cb, req.container_id(), false, error); if (error.NotEmpty()) { ERROR("Failed to find container id %s: %s", req.container_id().c_str(), error.GetCMessage()); error.Errorf("Failed to find container id %s: %s", req.container_id().c_str(), error.GetCMessage()); return -1; } if (req.tty() && req.stderr()) { error.SetError("tty and stderr cannot both be true!"); return -1; } if (!req.stdin() && !req.stdout() && !req.stderr()) { error.SetError("one of stdin, stdout, and stderr must be set"); return -1; } return 0; } void ContainerManagerServiceImpl::Attach(const runtime::v1alpha2::AttachRequest &req, runtime::v1alpha2::AttachResponse *resp, Errors &error) { if (ValidateAttachRequest(req, error) != 0) { return; } if (resp == nullptr) { error.SetError("Empty attach response arguments"); return; } RequestCache *cache = RequestCache::GetInstance(); std::string token = cache->InsertAttachRequest(req); if (token.empty()) { error.SetError("failed to get a unique token!"); return; } std::string url = BuildURL("attach", token); resp->set_url(url); } } // namespace CRI
NB_COPIED_TILES EQU 1 NB_EMPTY_TILES EQU 128 - NB_COPIED_TILES TILE_SIZE EQU 16 TOTAL_BYTES equ (NB_COPIED_TILES + NB_EMPTY_TILES) * TILE_SIZE RESULTS_START EQUS "vTestBuf" RESULTS_N_ROWS EQU (NB_COPIED_TILES + 1) * 2 + 1 include "base.inc" ; Test what happens when performing a HDMA with LCD off ; A single tile should get copied, and the count should decrement once CorrectResults: REPT NB_COPIED_TILES * TILE_SIZE / 2 dw SrcBuf + (@ - CorrectResults) ENDR ds TILE_SIZE, 0 db $02, $80 ds 6, 0 RunTest: ; Note that this is jumped to with IME off, which is important for what follows ; The LCD is also off, so we can quickly clear VRAM, too ; pop return address off of stack, as we are going to overwrite it... pop de ; Init the target area with a bunch of zeros ld hl, vTestBuf ; Also init the GDMA dest reg ld a, HIGH(hl) ldh [rHDMA3], a ld a, LOW(hl) ldh [rHDMA4], a ld bc, TOTAL_BYTES ; Otherwise the loop won't iterate the correct amount of times assert TOTAL_BYTES % 256 == 0 xor a .initTestBuf ld [hli], a dec c jr nz, .initTestBuf dec b jr nz, .initTestBuf ld hl, SrcBuf ld a, HIGH(hl) ldh [rHDMA1], a ld a, LOW(hl) ldh [rHDMA2], a ; Init WRAM with a fairly unique pattern ld bc, TOTAL_BYTES / 2 ; Like the previous loop assert (TOTAL_BYTES / 2) % 256 == 0 .initSrcBuf ld a, l ld [hli], a ld a, h ld [hli], a dec c jr nz, .initSrcBuf dec b jr nz, .initSrcBuf ; Also set a pattern in HRAM, just in case ld c, LOW(_HRAM) .initHRAM ld a, c ldh [c], a inc c jr nz, .initHRAM ld a, IEF_LCDC ldh [rIE], a ld a, STATF_MODE01 ldh [rSTAT], a xor a ei ldh [rIF], a call LCDOn halt ; Wait until the end of the first frame, as it tends to have weird behavior ld a, STATF_MODE00 ldh [rSTAT], a ; Now, start a HDMA ld c, LOW(rHDMA5) ld a, $83 halt ; Wait for Mode 0 ldh [c], a ; Read the HDMA counter, and append it to the test results ld hl, RESULTS_START + RESULTS_N_ROWS * 8 - 8 ldh a, [c] ld [hli], a ; Now, pause the transfer xor a ldh [c], a ldh a, [c] ld [hli], a ; Return to previously popped-off address push de jp LCDOff ; Test-ending code expects LCD to be off SECTION "STAT handler", ROM0[$48] reti SECTION "Test buffer", VRAM[$8800] vTestBuf: ds NB_COPIED_TILES * TILE_SIZE ; This is the normal result area... ds NB_EMPTY_TILES * TILE_SIZE ; ...but let's be safe, just in case. SECTION "Source buffer", WRAM0,ALIGN[4] SrcBuf: ; Like above ds NB_COPIED_TILES * TILE_SIZE ds NB_EMPTY_TILES * TILE_SIZE CGB_MODE
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "DexUtil.h" #include "OriginalNamePass.h" #include "ClassHierarchy.h" #define METRIC_MISSING_ORIGINAL_NAME_ROOT "num_missing_original_name_root" #define METRIC_SET_CLASS_DATA "num_set_class_data" #define METRIC_ORIGINAL_NAME_COUNT "num_original_name" static OriginalNamePass s_pass; static const char* redex_field_name = "__redex_internal_original_name"; void OriginalNamePass::build_hierarchies( PassManager& mgr, const ClassHierarchy& ch, Scope& scope, std::unordered_map<const DexType*, std::string>* hierarchies) { std::vector<DexClass*> base_classes; for (const auto& base : m_hierarchy_roots) { // skip comments if (base.c_str()[0] == '#') continue; auto base_type = DexType::get_type(base.c_str()); auto base_class = base_type != nullptr ? type_class(base_type) : nullptr; if (base_class == nullptr) { TRACE(ORIGINALNAME, 2, "Can't find class for annotate_original_name rule %s\n", base.c_str()); mgr.incr_metric(METRIC_MISSING_ORIGINAL_NAME_ROOT, 1); } else { base_classes.emplace_back(base_class); } } for (const auto& base_class : base_classes) { auto base_name = base_class->get_deobfuscated_name(); hierarchies->emplace(base_class->get_type(), base_name); TypeSet children_and_implementors; get_all_children_or_implementors( ch, scope, base_class, children_and_implementors); for (const auto& cls : children_and_implementors) { hierarchies->emplace(cls, base_name); } } } void OriginalNamePass::run_pass(DexStoresVector& stores, ConfigFiles&, PassManager& mgr) { auto scope = build_class_scope(stores); ClassHierarchy ch = build_type_hierarchy(scope); std::unordered_map<const DexType*, std::string> to_annotate; build_hierarchies(mgr, ch, scope, &to_annotate); DexString* field_name = DexString::make_string(redex_field_name); DexType* string_type = get_string_type(); for (auto it : to_annotate) { const DexType* cls_type = it.first; if (strncmp("LX/", cls_type->get_name()->c_str(), 2) != 0) { continue; } DexClass* cls = type_class(cls_type); if (!cls->has_class_data()) { cls->set_class_data(true); mgr.incr_metric(METRIC_SET_CLASS_DATA, 1); } auto external_name = JavaNameUtil::internal_to_external(cls->get_deobfuscated_name()); auto external_name_s = DexString::make_string(external_name.c_str()); always_assert_log(DexField::get_field(cls_type, field_name, string_type) == nullptr, "field %s already exists!", redex_field_name); DexField* f = static_cast<DexField*>( DexField::make_field(cls_type, field_name, string_type)); f->make_concrete(ACC_PUBLIC | ACC_STATIC | ACC_FINAL, new DexEncodedValueString(external_name_s)); insert_sorted(cls->get_sfields(), f, compare_dexfields); mgr.incr_metric(METRIC_ORIGINAL_NAME_COUNT, 1); mgr.incr_metric(std::string(METRIC_ORIGINAL_NAME_COUNT) + "::" + it.second, 1); } }
//================================================================================================== /*! @file @copyright 2016 NumScale SAS @copyright 2016 J.T. Lapreste Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_SIMD_COMPARE_LESS_INCLUDED #define BOOST_SIMD_FUNCTION_SIMD_COMPARE_LESS_INCLUDED #include <boost/simd/function/scalar/compare_less.hpp> #include <boost/simd/arch/common/generic/function/autodispatcher.hpp> #include <boost/simd/arch/common/simd/function/compare_less.hpp> #endif
; A100679: Floor of cube root of tetrahedral numbers. ; 0,1,1,2,2,3,3,4,4,5,6,6,7,7,8,8,9,9,10,10,11,12,12,13,13,14,14,15,15,16,17,17,18,18,19,19,20,20,21,22,22,23,23,24,24,25,25,26,26,27,28,28,29,29,30,30,31,31,32,33,33,34 add $0,3 mul $0,2 add $0,52 mul $0,2 add $0,3 mov $1,1 mov $2,$0 lpb $0 mov $0,1 mul $2,2 add $1,$2 add $1,$2 add $1,1 div $1,29 lpe sub $1,16 mov $0,$1
// Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/heap/cppgc/stats-collector.h" #include <algorithm> #include <cmath> #include "src/base/atomicops.h" #include "src/base/logging.h" #include "src/base/platform/time.h" #include "src/heap/cppgc/metric-recorder.h" namespace cppgc { namespace internal { // static constexpr size_t StatsCollector::kAllocationThresholdBytes; StatsCollector::StatsCollector( std::unique_ptr<MetricRecorder> histogram_recorder, Platform* platform) : metric_recorder_(std::move(histogram_recorder)), platform_(platform) { USE(platform_); } void StatsCollector::RegisterObserver(AllocationObserver* observer) { DCHECK_EQ(allocation_observers_.end(), std::find(allocation_observers_.begin(), allocation_observers_.end(), observer)); allocation_observers_.push_back(observer); } void StatsCollector::UnregisterObserver(AllocationObserver* observer) { auto it = std::find(allocation_observers_.begin(), allocation_observers_.end(), observer); DCHECK_NE(allocation_observers_.end(), it); allocation_observers_.erase(it); } void StatsCollector::NotifyAllocation(size_t bytes) { // The current GC may not have been started. This is ok as recording considers // the whole time range between garbage collections. allocated_bytes_since_safepoint_ += bytes; } void StatsCollector::NotifyExplicitFree(size_t bytes) { // See IncreaseAllocatedObjectSize for lifetime of the counter. explicitly_freed_bytes_since_safepoint_ += bytes; } void StatsCollector::NotifySafePointForConservativeCollection() { if (std::abs(allocated_bytes_since_safepoint_ - explicitly_freed_bytes_since_safepoint_) >= static_cast<int64_t>(kAllocationThresholdBytes)) { AllocatedObjectSizeSafepointImpl(); } } void StatsCollector::NotifySafePointForTesting() { AllocatedObjectSizeSafepointImpl(); } void StatsCollector::AllocatedObjectSizeSafepointImpl() { allocated_bytes_since_end_of_marking_ += static_cast<int64_t>(allocated_bytes_since_safepoint_) - static_cast<int64_t>(explicitly_freed_bytes_since_safepoint_); // These observer methods may start or finalize GC. In case they trigger a // final GC pause, the delta counters are reset there and the following // observer calls are called with '0' updates. ForAllAllocationObservers([this](AllocationObserver* observer) { // Recompute delta here so that a GC finalization is able to clear the // delta for other observer calls. int64_t delta = allocated_bytes_since_safepoint_ - explicitly_freed_bytes_since_safepoint_; if (delta < 0) { observer->AllocatedObjectSizeDecreased(static_cast<size_t>(-delta)); } else { observer->AllocatedObjectSizeIncreased(static_cast<size_t>(delta)); } }); allocated_bytes_since_safepoint_ = 0; explicitly_freed_bytes_since_safepoint_ = 0; } StatsCollector::Event::Event() { static std::atomic<size_t> epoch_counter{0}; epoch = epoch_counter.fetch_add(1); } void StatsCollector::NotifyMarkingStarted(CollectionType collection_type, IsForcedGC is_forced_gc) { DCHECK_EQ(GarbageCollectionState::kNotRunning, gc_state_); current_.collection_type = collection_type; current_.is_forced_gc = is_forced_gc; gc_state_ = GarbageCollectionState::kMarking; } void StatsCollector::NotifyMarkingCompleted(size_t marked_bytes) { DCHECK_EQ(GarbageCollectionState::kMarking, gc_state_); gc_state_ = GarbageCollectionState::kSweeping; current_.marked_bytes = marked_bytes; current_.object_size_before_sweep_bytes = previous_.marked_bytes + allocated_bytes_since_end_of_marking_ + allocated_bytes_since_safepoint_ - explicitly_freed_bytes_since_safepoint_; allocated_bytes_since_safepoint_ = 0; explicitly_freed_bytes_since_safepoint_ = 0; DCHECK_LE(memory_freed_bytes_since_end_of_marking_, memory_allocated_bytes_); memory_allocated_bytes_ -= memory_freed_bytes_since_end_of_marking_; current_.memory_size_before_sweep_bytes = memory_allocated_bytes_; memory_freed_bytes_since_end_of_marking_ = 0; ForAllAllocationObservers([marked_bytes](AllocationObserver* observer) { observer->ResetAllocatedObjectSize(marked_bytes); }); // HeapGrowing would use the below fields to estimate allocation rate during // execution of ResetAllocatedObjectSize. allocated_bytes_since_end_of_marking_ = 0; time_of_last_end_of_marking_ = v8::base::TimeTicks::Now(); } double StatsCollector::GetRecentAllocationSpeedInBytesPerMs() const { v8::base::TimeTicks current_time = v8::base::TimeTicks::Now(); DCHECK_LE(time_of_last_end_of_marking_, current_time); if (time_of_last_end_of_marking_ == current_time) return 0; return allocated_bytes_since_end_of_marking_ / (current_time - time_of_last_end_of_marking_).InMillisecondsF(); } namespace { int64_t SumPhases(const MetricRecorder::CppGCFullCycle::Phases& phases) { return phases.mark_duration_us + phases.weak_duration_us + phases.compact_duration_us + phases.sweep_duration_us; } MetricRecorder::CppGCFullCycle GetFullCycleEventForMetricRecorder( int64_t atomic_mark_us, int64_t atomic_weak_us, int64_t atomic_compact_us, int64_t atomic_sweep_us, int64_t incremental_mark_us, int64_t incremental_sweep_us, int64_t concurrent_mark_us, int64_t concurrent_sweep_us, int64_t objects_before_bytes, int64_t objects_after_bytes, int64_t objects_freed_bytes, int64_t memory_before_bytes, int64_t memory_after_bytes, int64_t memory_freed_bytes) { MetricRecorder::CppGCFullCycle event; // MainThread.Incremental: event.main_thread_incremental.mark_duration_us = incremental_mark_us; event.main_thread_incremental.sweep_duration_us = incremental_sweep_us; // MainThread.Atomic: event.main_thread_atomic.mark_duration_us = atomic_mark_us; event.main_thread_atomic.weak_duration_us = atomic_weak_us; event.main_thread_atomic.compact_duration_us = atomic_compact_us; event.main_thread_atomic.sweep_duration_us = atomic_sweep_us; // MainThread: event.main_thread.mark_duration_us = event.main_thread_atomic.mark_duration_us + event.main_thread_incremental.mark_duration_us; event.main_thread.weak_duration_us = event.main_thread_atomic.weak_duration_us; event.main_thread.compact_duration_us = event.main_thread_atomic.compact_duration_us; event.main_thread.sweep_duration_us = event.main_thread_atomic.sweep_duration_us + event.main_thread_incremental.sweep_duration_us; // Total: event.total.mark_duration_us = event.main_thread.mark_duration_us + concurrent_mark_us; event.total.weak_duration_us = event.main_thread.weak_duration_us; event.total.compact_duration_us = event.main_thread.compact_duration_us; event.total.sweep_duration_us = event.main_thread.sweep_duration_us + concurrent_sweep_us; // Objects: event.objects.before_bytes = objects_before_bytes; event.objects.after_bytes = objects_after_bytes; event.objects.freed_bytes = objects_freed_bytes; // Memory: event.memory.before_bytes = memory_before_bytes; event.memory.after_bytes = memory_after_bytes; event.memory.freed_bytes = memory_freed_bytes; // Collection Rate: event.collection_rate_in_percent = static_cast<double>(event.objects.after_bytes) / event.objects.before_bytes; // Efficiency: event.efficiency_in_bytes_per_us = static_cast<double>(event.objects.freed_bytes) / SumPhases(event.total); event.main_thread_efficiency_in_bytes_per_us = static_cast<double>(event.objects.freed_bytes) / SumPhases(event.main_thread); return event; } } // namespace void StatsCollector::NotifySweepingCompleted() { DCHECK_EQ(GarbageCollectionState::kSweeping, gc_state_); gc_state_ = GarbageCollectionState::kNotRunning; previous_ = std::move(current_); current_ = Event(); if (metric_recorder_) { MetricRecorder::CppGCFullCycle event = GetFullCycleEventForMetricRecorder( previous_.scope_data[kAtomicMark].InMicroseconds(), previous_.scope_data[kAtomicWeak].InMicroseconds(), previous_.scope_data[kAtomicCompact].InMicroseconds(), previous_.scope_data[kAtomicSweep].InMicroseconds(), previous_.scope_data[kIncrementalMark].InMicroseconds(), previous_.scope_data[kIncrementalSweep].InMicroseconds(), previous_.concurrent_scope_data[kConcurrentMark], previous_.concurrent_scope_data[kConcurrentSweep], previous_.object_size_before_sweep_bytes /* objects_before */, previous_.marked_bytes /* objects_after */, previous_.object_size_before_sweep_bytes - previous_.marked_bytes /* objects_freed */, previous_.memory_size_before_sweep_bytes /* memory_before */, previous_.memory_size_before_sweep_bytes - memory_freed_bytes_since_end_of_marking_ /* memory_after */, memory_freed_bytes_since_end_of_marking_ /* memory_freed */); metric_recorder_->AddMainThreadEvent(event); } } size_t StatsCollector::allocated_memory_size() const { return memory_allocated_bytes_; } size_t StatsCollector::allocated_object_size() const { // During sweeping we refer to the current Event as that already holds the // correct marking information. In all other phases, the previous event holds // the most up-to-date marking information. const Event& event = gc_state_ == GarbageCollectionState::kSweeping ? current_ : previous_; DCHECK_GE(static_cast<int64_t>(event.marked_bytes) + allocated_bytes_since_end_of_marking_, 0); return static_cast<size_t>(static_cast<int64_t>(event.marked_bytes) + allocated_bytes_since_end_of_marking_); } size_t StatsCollector::marked_bytes() const { DCHECK_NE(GarbageCollectionState::kMarking, gc_state_); // During sweeping we refer to the current Event as that already holds the // correct marking information. In all other phases, the previous event holds // the most up-to-date marking information. const Event& event = gc_state_ == GarbageCollectionState::kSweeping ? current_ : previous_; return event.marked_bytes; } v8::base::TimeDelta StatsCollector::marking_time() const { DCHECK_NE(GarbageCollectionState::kMarking, gc_state_); // During sweeping we refer to the current Event as that already holds the // correct marking information. In all other phases, the previous event holds // the most up-to-date marking information. const Event& event = gc_state_ == GarbageCollectionState::kSweeping ? current_ : previous_; return event.scope_data[kAtomicMark] + event.scope_data[kIncrementalMark] + v8::base::TimeDelta::FromMicroseconds(v8::base::Relaxed_Load( &event.concurrent_scope_data[kConcurrentMark])); } void StatsCollector::NotifyAllocatedMemory(int64_t size) { memory_allocated_bytes_ += size; ForAllAllocationObservers([size](AllocationObserver* observer) { observer->AllocatedSizeIncreased(static_cast<size_t>(size)); }); } void StatsCollector::NotifyFreedMemory(int64_t size) { memory_freed_bytes_since_end_of_marking_ += size; ForAllAllocationObservers([size](AllocationObserver* observer) { observer->AllocatedSizeDecreased(static_cast<size_t>(size)); }); } void StatsCollector::RecordHistogramSample(ScopeId scope_id_, v8::base::TimeDelta time) { switch (scope_id_) { case kIncrementalMark: { MetricRecorder::CppGCMainThreadIncrementalMark event{ time.InMicroseconds()}; metric_recorder_->AddMainThreadEvent(event); break; } case kIncrementalSweep: { MetricRecorder::CppGCMainThreadIncrementalSweep event{ time.InMicroseconds()}; metric_recorder_->AddMainThreadEvent(event); break; } default: break; } } } // namespace internal } // namespace cppgc
// Copyright (C) 2011 - 2014 David Reid. See included LICENCE. #ifndef GT_DefaultSceneRenderer_LightGroup #define GT_DefaultSceneRenderer_LightGroup #include <GTGE/Core/Vector.hpp> #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4351) // new behavior: elements of array will be default initialized #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif namespace GT { /// Structure representing a value for identifying a combination of light types. /// /// Each type of light is allocated 16 bits, which means the maximum count of each light is 65,535. struct DefaultSceneRenderer_LightGroupID { /// The counts of each type of light. Each light is allocated 16-bits. /// /// 0 = Ambient lights. /// 1 = Directional lights. /// 2 = Point lights. /// 3 = Spot lights. /// 4 = Shadow-casting directional lights. /// 5 = Shadow-casting point lights. /// 6 = Shadow-casting spot lights. uint16_t value[8]; DefaultSceneRenderer_LightGroupID() : value() { this->Reset(); } DefaultSceneRenderer_LightGroupID(const DefaultSceneRenderer_LightGroupID &other) : value() { value[0] = other.value[0]; value[1] = other.value[1]; value[2] = other.value[2]; value[3] = other.value[3]; value[4] = other.value[4]; value[5] = other.value[5]; value[6] = other.value[6]; value[7] = other.value[7]; } void SetAmbientLightCount(uint16_t count) { value[0] = count; } void SetDirectionalLightCount(uint16_t count) { value[1] = count; } void SetPointLightCount(uint16_t count) { value[2] = count; } void SetSpotLightCount(uint16_t count) { value[3] = count; } void SetShadowDirectionalLightCount(uint16_t count) { value[4] = count; } void SetShadowPointLightCount(uint16_t count) { value[5] = count; } void SetShadowSpotLightCount(uint16_t count) { value[6] = count; } uint16_t GetAmbientLightCount() const { return value[0]; } uint16_t GetDirectionalLightCount() const { return value[1]; } uint16_t GetPointLightCount() const { return value[2]; } uint16_t GetSpotLightCount() const { return value[3]; } uint16_t GetShadowDirectionalLightCount() const { return value[4]; } uint16_t GetShadowPointLightCount() const { return value[5]; } uint16_t GetShadowSpotLightCount() const { return value[6]; } void AddAmbientLight() { this->SetAmbientLightCount(this->GetAmbientLightCount() + 1); } void AddDirectionalLight() { this->SetDirectionalLightCount(this->GetDirectionalLightCount() + 1); } void AddPointLight() { this->SetPointLightCount(this->GetPointLightCount() + 1); } void AddSpotLight() { this->SetSpotLightCount(this->GetSpotLightCount() + 1); } void AddShadowDirectionalLight() { this->SetShadowDirectionalLightCount(this->GetShadowDirectionalLightCount() + 1); } void AddShadowPointLight() { this->SetShadowPointLightCount(this->GetShadowPointLightCount() + 1); } void AddShadowSpotLight() { this->SetShadowSpotLightCount(this->GetShadowSpotLightCount() + 1); } void RemoveAmbientLight() { auto count = this->GetAmbientLightCount(); if (count > 0) { this->SetAmbientLightCount(count - 1); } } void RemoveDirectionalLight() { auto count = this->GetDirectionalLightCount(); if (count > 0) { this->SetDirectionalLightCount(count - 1); } } void RemovePointLight() { auto count = this->GetPointLightCount(); if (count > 0) { this->SetPointLightCount(count - 1); } } void RemoveSpotLight() { auto count = this->GetSpotLightCount(); if (count > 0) { this->SetSpotLightCount(count - 1); } } void RemoveShadowDirectionalLight() { auto count = this->GetShadowDirectionalLightCount(); if (count > 0) { this->SetShadowDirectionalLightCount(count - 1); } } void RemoveShadowPointLight() { auto count = this->GetShadowPointLightCount(); if (count > 0) { this->SetShadowPointLightCount(count - 1); } } void RemoveShadowSpotLight() { auto count = this->GetShadowSpotLightCount(); if (count > 0) { this->SetShadowSpotLightCount(count - 1); } } void Reset() { this->value[0] = 0; this->value[1] = 0; this->value[2] = 0; this->value[3] = 0; this->value[4] = 0; this->value[5] = 0; this->value[6] = 0; this->value[7] = 0; } bool operator<(const DefaultSceneRenderer_LightGroupID &other) const { auto value0 = *reinterpret_cast<const uint64_t*>(this->value + 0); auto value1 = *reinterpret_cast<const uint64_t*>(this->value + 4); auto otherValue0 = *reinterpret_cast<const uint64_t*>(other.value + 0); auto otherValue1 = *reinterpret_cast<const uint64_t*>(other.value + 4); return value0 < otherValue0 || (value0 == otherValue0 && value1 < otherValue1); } bool operator>(const DefaultSceneRenderer_LightGroupID &other) const { auto value0 = *reinterpret_cast<const uint64_t*>(this->value + 0); auto value1 = *reinterpret_cast<const uint64_t*>(this->value + 4); auto otherValue0 = *reinterpret_cast<const uint64_t*>(other.value + 0); auto otherValue1 = *reinterpret_cast<const uint64_t*>(other.value + 4); return value0 > otherValue0 || (value0 == otherValue0 && value1 > otherValue1); } bool operator==(const DefaultSceneRenderer_LightGroupID &other) const { auto value0 = *reinterpret_cast<const uint64_t*>(this->value + 0); auto value1 = *reinterpret_cast<const uint64_t*>(this->value + 4); auto otherValue0 = *reinterpret_cast<const uint64_t*>(other.value + 0); auto otherValue1 = *reinterpret_cast<const uint64_t*>(other.value + 4); return value0 == otherValue0 && value1 == otherValue1; } }; /// Structure representing a group of lights. /// /// Each light is representing as a simple 32-bit value. struct DefaultSceneRenderer_LightGroup { /// The ID of the light group. DefaultSceneRenderer_LightGroupID id; /// The list of light IDs. Vector<uint32_t> lightIDs; /// Constructor. DefaultSceneRenderer_LightGroup(); /// Adds an ambient light. /// /// @param lightID [in] The ID of the light. void AddAmbientLight(uint32_t lightID); /// Adds a directional light. /// /// @param lightID [in] The ID of the light. void AddDirectionalLight(uint32_t lightID); /// Adds a point light. /// /// @param lightID [in] The ID of the light. void AddPointLight(uint32_t lightID); /// Adds a spot light. /// /// @param lightID [in] The ID of the light. void AddSpotLight(uint32_t lightID); /// Adds a shadow-casting directional light. /// /// @param lightID [in] The ID of the light. void AddShadowDirectionalLight(uint32_t lightID); /// Adds a shadow-casting point light. /// /// @param lightID [in] The ID of the light. void AddShadowPointLight(uint32_t lightID); /// Adds a shadow-casting spot light. /// /// @param lightID [in] The ID of the light. void AddShadowSpotLight(uint32_t lightID); /// Retrieves the index of the first ambient light. size_t GetAmbientLightStartIndex() const; /// Retrieves the index of the first directional light. size_t GetDirectionalLightStartIndex() const; /// Retrieves the index of the first point light. size_t GetPointLightStartIndex() const; /// Retrieves the index of the first spot light. size_t GetSpotLightStartIndex() const; /// Retrieves the index of the first shadow-casting directional light. size_t GetShadowDirectionalLightStartIndex() const; /// Retrieves the index of the first shadow-casting point light. size_t GetShadowPointLightStartIndex() const; /// Retrieves the index of the first shadow-casting spot light. size_t GetShadowSpotLightStartIndex() const; /// Retrieves the number of ambient lights in the group. uint16_t GetAmbientLightCount() const; /// Retrieves the number of directional lights in the group. uint16_t GetDirectionalLightCount() const; /// Retrieves the number of point lights in the group. uint16_t GetPointLightCount() const; /// Retrieves the number of spot lights in the group. uint16_t GetSpotLightCount() const; /// Retrieves the number of shadow-casting directionl lights in the group. uint16_t GetShadowDirectionalLightCount() const; /// Retrieves the number of shadow-casting point lights in the group. uint16_t GetShadowPointLightCount() const; /// Retrieves the number of shadow-casting spot lights in the group. uint16_t GetShadowSpotLightCount() const; /// Retrieves the total number of lights. uint16_t GetLightCount() const { return this->GetAmbientLightCount() + this->GetDirectionalLightCount() + this->GetPointLightCount() + this->GetSpotLightCount() + this->GetShadowLightCount(); } /// Retrieves the total number of shadow-casting lights. uint16_t GetShadowLightCount() const { return this->GetShadowDirectionalLightCount() + this->GetShadowPointLightCount() + this->GetShadowSpotLightCount(); } /// Clears the light group. void Clear(); }; } #if defined(_MSC_VER) #pragma warning(pop) #elif defined(__GNUC__) #pragma GCC diagnostic pop #endif #endif
################################################# # exe7 MIPS assembly # # author: Rogério Peixoto # ################################################# .globl main # data directives .data str: .asciiz "Arquitetura de Computadores" char: .word 'e' # text assembler directive .text main: la $s0, str la $s1, char li $s2, 0 loop: lb $t0, 0($s0) lb $t1, 0($s1) # if str[i] == char bne $t0, $t1, else # str[i++] addi $s0, $s0, 1 # contador++ addi $s2, $s2, 1 else: addi $s0, $s0, 1 beq $t0, '\0', end j loop end: li $v0, 1 add $a0, $s2, $zero syscall li $v0, 10 syscall
; ******************************************************************************************** ; ******************************************************************************************** ; ; Name : mouse.asm ; Purpose : .. ; Created : 15th Nov 1991 ; Updated : 4th Jan 2021 ; Authors : Fred Bowen ; ; ******************************************************************************************** ; ******************************************************************************************** ;*********************************************************************** ;* MOUSE ON [,[port] [,[sprite] [,[hotspot] [,X/Yposition] ]]] ;* MOUSE OFF ;* where: port = (1...3) for joyport 1, 2, or either (both) ;* sprite = (0...7) sprite pointer ;* hotspot = x,y offset in sprite, default 0,0 ;* position = normal, relative, or angluar coordinates ;* ;* (defaults to sprite 0, port 2, last hotspot & position) ;*********************************************************************** mouse cmp #on_token ; new [910122] beq l259_1 jsr chkesc cmp #off_token +lbne snerr ; The Kernel MOUSE_CMD is called to install or remove mouse driver. ; .a= B7,6 set to install mouse in game port 2 ($80), 1 ($40), or both ($C0) ; .a= 0 to disable mouse driver ; .x= 0-7 physical sprite pointer lda #0 ; TURN MOUSE OFF jsr _mouse ; do it +lbra chkeos ; eat token & exit after checking for eos ;TURN MOUSE ON l259_1 jsr chrget ; eat token ldx #2 ; get (optional) port# in .X jsr optbyt ; if not present default to port 2 cpx #4 ; +lbcs fcerr ; illegal value phx ldx #0 ; get (optional) sprite# in .X jsr optbyt ; if not present default to sprite 0 cpx #8 +lbcs fcerr ; illegal value stx z_p_temp_1 ldy sproff,x ; kill moving sprite lda #0 ; get offset to speed data sta sprite_data,y ; reset sprite's speed value pla ; setup for Kernel call- get port# into b7,6 ror ; .a= port(s), .x=sprite ror ror jsr _mouse ; do it (???? do after coord error check) jsr optbyt ; get (optional) hotspot, x new [910307] bcc l259_2 ; not given cpx #24 +lbcs fcerr ; out of range (0-23) txa neg tax adc #24 sta _mouse_left txa clc adc #87 sta _mouse_right l259_2 jsr optbyt ; get (optional) hotspot, y bcc l259_3 ; not given cpx #21 +lbcs fcerr ; out of range (0-20) txa neg tax adc #50 sta _mouse_top txa clc adc #250 sta _mouse_bottom l259_3 jsr chrgot ; get (optional) position coordinate [910123] beq l259_4 ; eol, use this sprite's last position jsr sprcor ; else get first coordinate bit numcnt ; test coordinate type +lbvs snerr ; syntax error sty xdest ; save coordinate value sty xdest+2 sta xdest+1 sta xdest+3 lda #$7f ; flag 'mouse' for movspr call [910808] sta op jsr sprcor ; get second coordinate bit numcnt ; test type of coordinate +lbvc movspr_normal ; position sprite, normal coordinates +lbmi movspr_angle ; angular coordinates +lbra snerr ; else error l259_4 rts ;.end ; ******************************************************************************************** ; ; Date Changes ; ==== ======= ; ; ********************************************************************************************
// // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "gmock/gmock.h" #include "gtest/gtest.h" #include "zetasql/base/testing/status_matchers.h" #include "tests/common/proto_matchers.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/substitute.h" #include "tests/common/proto_matchers.h" #include "tests/conformance/common/database_test_base.h" namespace google { namespace spanner { namespace emulator { namespace test { namespace { using zetasql_base::testing::StatusIs; class PartitionQueryTest : public DatabaseTest { public: absl::Status SetUpDatabase() override { ZETASQL_RETURN_IF_ERROR(SetSchema({ R"( CREATE TABLE Users( UserId INT64 NOT NULL, Name STRING(MAX), Age INT64 ) PRIMARY KEY (UserId) )", "CREATE INDEX UsersByName ON Users(Name)", "CREATE INDEX UsersByNameDescending ON Users(Name DESC)", R"( CREATE TABLE Threads ( UserId INT64 NOT NULL, ThreadId INT64 NOT NULL, Starred BOOL ) PRIMARY KEY (UserId, ThreadId), INTERLEAVE IN PARENT Users ON DELETE CASCADE )"})); return absl::OkStatus(); } protected: // Creates a new session for tests using raw grpc client. absl::StatusOr<spanner_api::Session> CreateSession() { grpc::ClientContext context; spanner_api::CreateSessionRequest request; request.set_database(std::string(database()->FullName())); // NOLINT spanner_api::Session response; ZETASQL_RETURN_IF_ERROR(raw_client()->CreateSession(&context, request, &response)); return response; } void PopulateDatabase() { // Write fixture data to use in partition query test. ZETASQL_EXPECT_OK(CommitDml({SqlStatement( "INSERT Users(UserId, Name, Age) Values (1, 'Levin', 27), " "(2, 'Mark', 32), (10, 'Douglas', 31)")})); ZETASQL_EXPECT_OK(MultiInsert("Threads", {"UserId", "ThreadId", "Starred"}, {{1, 1, true}, {1, 2, true}, {1, 3, true}, {1, 4, false}, {2, 1, false}, {2, 2, true}, {10, 1, false}})); } }; // Tests using raw grpc client to test session and transaction validaton. TEST_F(PartitionQueryTest, CannotQueryWithoutSession) { spanner_api::PartitionQueryRequest partition_query_request; spanner_api::PartitionResponse partition_query_response; grpc::ClientContext context; EXPECT_THAT(raw_client()->PartitionQuery(&context, partition_query_request, &partition_query_response), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryWithoutTransaction) { ZETASQL_ASSERT_OK_AND_ASSIGN(auto session, CreateSession()); spanner_api::PartitionQueryRequest partition_query_request; partition_query_request.set_session(session.name()); spanner_api::PartitionResponse partition_query_response; grpc::ClientContext context; EXPECT_THAT(raw_client()->PartitionQuery(&context, partition_query_request, &partition_query_response), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryUsingSingleUseTransaction) { ZETASQL_ASSERT_OK_AND_ASSIGN(auto session, CreateSession()); spanner_api::PartitionQueryRequest partition_query_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { single_use { read_only {} } } )", session.name())); spanner_api::PartitionResponse partition_query_response; grpc::ClientContext context; EXPECT_THAT(raw_client()->PartitionQuery(&context, partition_query_request, &partition_query_response), StatusIs(absl::StatusCode::kInvalidArgument)); } // Tests using cpp client library. TEST_F(PartitionQueryTest, CannotQueryUsingBeginReadWriteTransaction) { Transaction txn{Transaction::ReadWriteOptions{}}; // PartitionQuery using a begin read-write transaction fails. EXPECT_THAT(PartitionQuery(txn, "SELECT UserID, Name FROM Users"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryUsingExistingReadWriteTransaction) { Transaction txn{Transaction::ReadWriteOptions{}}; ZETASQL_ASSERT_OK(Read(txn, "Users", {"UserId", "Name"}, KeySet::All())); // PartitionQuery using an already started read-write transaction fails. EXPECT_THAT(PartitionQuery(txn, "SELECT UserID, Name FROM Users"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryUsingInvalidPartitionOptions) { Transaction txn{Transaction::ReadOnlyOptions{}}; // Test that negative partition_size_bytes is not allowed. PartitionOptions partition_options = {.partition_size_bytes = -1, .max_partitions = 100}; EXPECT_THAT( PartitionQuery(txn, "SELECT UserID, Name FROM Users", partition_options), StatusIs(absl::StatusCode::kInvalidArgument)); // Test that negative max_partitions is not allowed. partition_options = {.partition_size_bytes = 10000, .max_partitions = -1}; EXPECT_THAT( PartitionQuery(txn, "SELECT UserID, Name FROM Users", partition_options), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CanQueryUsingPartitionToken) { PopulateDatabase(); Transaction txn{Transaction::ReadOnlyOptions{}}; ZETASQL_ASSERT_OK_AND_ASSIGN(std::vector<QueryPartition> partitions, PartitionQuery(txn, "SELECT UserID, Name FROM Users")); EXPECT_THAT( Query(partitions), IsOkAndHoldsUnorderedRows({{1, "Levin"}, {2, "Mark"}, {10, "Douglas"}})); } TEST_F(PartitionQueryTest, CanReuseTransactionForPartitionQuery) { PopulateDatabase(); Transaction txn{Transaction::ReadOnlyOptions{}}; { ZETASQL_ASSERT_OK_AND_ASSIGN(std::vector<QueryPartition> partitions, PartitionQuery(txn, "SELECT UserID, Name FROM Users")); EXPECT_GE(partitions.size(), 1); } { ZETASQL_ASSERT_OK_AND_ASSIGN(std::vector<QueryPartition> partitions, PartitionQuery(txn, "SELECT UserID FROM Users")); EXPECT_GE(partitions.size(), 1); } } TEST_F(PartitionQueryTest, CannotQueryNonRootPartitionableSqlOrderBy) { PopulateDatabase(); Transaction txn{Transaction::ReadOnlyOptions{}}; EXPECT_THAT( PartitionQuery(txn, "SELECT UserID, Name FROM Users ORDER BY Name"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryNonRootPartitionableSqlNoTable) { PopulateDatabase(); Transaction txn{Transaction::ReadOnlyOptions{}}; EXPECT_THAT(PartitionQuery(txn, "SELECT a FROM UNNEST([1, 2, 3]) AS a"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryNonRootPartitionableSqlFilterNoTable) { PopulateDatabase(); Transaction txn{Transaction::ReadOnlyOptions{}}; EXPECT_THAT( PartitionQuery(txn, "SELECT a FROM UNNEST([1, 2, 3]) AS a WHERE a = 1"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryNonRootPartitionableSqlSubquery) { PopulateDatabase(); Transaction txn{Transaction::ReadOnlyOptions{}}; EXPECT_THAT(PartitionQuery(txn, "SELECT UserID, Name FROM Users WHERE EXISTS " "(SELECT ThreadId FROM Threads)"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, DisableQueryPartitionabilityCheckForValidQuery) { PopulateDatabase(); const std::string valid_query = "SELECT ANY_VALUE(STARRED), USERID " "FROM Threads WHERE Threadid=1 " "GROUP BY UserId "; { Transaction txn{Transaction::ReadOnlyOptions{}}; // Query fails without the hint to disable partitionability check in // emulator. if (in_prod_env()) { ZETASQL_EXPECT_OK(PartitionQuery(txn, valid_query)); } else { EXPECT_THAT(PartitionQuery(txn, valid_query), StatusIs(absl::StatusCode::kInvalidArgument)); } } // With the hint to disable partitionability check, the Emulator is pacified // and prod ignores the hint. { const auto modified_query = absl::StrCat( "@{spanner_emulator.disable_query_partitionability_check=true}", valid_query); Transaction txn{Transaction::ReadOnlyOptions{}}; ZETASQL_EXPECT_OK(PartitionQuery(txn, modified_query)); } } TEST_F(PartitionQueryTest, CannotQueryNonRootPartitionableSqlSubqueryInExpr) { PopulateDatabase(); Transaction txn{Transaction::ReadOnlyOptions{}}; EXPECT_THAT(PartitionQuery(txn, "SELECT UserID, Name FROM Users WHERE UserID IN " "(SELECT ThreadId FROM Threads)"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryNonRootPartitionableSqlTwoTable) { PopulateDatabase(); Transaction txn{Transaction::ReadOnlyOptions{}}; EXPECT_THAT(PartitionQuery(txn, "SELECT u.UserID, ARRAY(SELECT ThreadId FROM " "Threads) FROM Users AS u"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryNonRootPartitionableSqlOneTableOneIndex) { PopulateDatabase(); Transaction txn{Transaction::ReadOnlyOptions{}}; EXPECT_THAT( PartitionQuery( txn, "SELECT u.UserID, b.Name FROM Users AS u, UsersByName AS b"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotPartitionQueryWithoutSql) { ZETASQL_ASSERT_OK_AND_ASSIGN(auto session, CreateSession()); spanner_api::PartitionQueryRequest partition_query_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { begin { read_only {} } } )", session.name())); spanner_api::PartitionResponse partition_query_response; grpc::ClientContext context; EXPECT_THAT(raw_client()->PartitionQuery(&context, partition_query_request, &partition_query_response), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryWithDifferentSession) { ZETASQL_ASSERT_OK_AND_ASSIGN(auto session, CreateSession()); spanner_api::PartitionQueryRequest partition_query_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { begin { read_only {} } } sql: "SELECT UserID, Name FROM Users" )", session.name())); spanner_api::PartitionResponse partition_query_response; { grpc::ClientContext context; ZETASQL_ASSERT_OK(raw_client()->PartitionQuery(&context, partition_query_request, &partition_query_response)); } ASSERT_GT(partition_query_response.partitions().size(), 0); // Validate that a different session cannot be used for query using partition // token than the one used for partition query. ZETASQL_ASSERT_OK_AND_ASSIGN(auto query_session, CreateSession()); spanner_api::ExecuteSqlRequest sql_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { begin { read_only {} } } sql: "SELECT UserID, Name FROM Users" partition_token: "$1" )", query_session.name(), partition_query_response.partitions()[0].partition_token())); grpc::ClientContext context; spanner_api::ResultSet query_response; EXPECT_THAT(raw_client()->ExecuteSql(&context, sql_request, &query_response), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryWithDifferentTransaction) { ZETASQL_ASSERT_OK_AND_ASSIGN(auto session, CreateSession()); spanner_api::PartitionQueryRequest partition_query_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { begin { read_only {} } } sql: "SELECT UserID, Name FROM Users" )", session.name())); spanner_api::PartitionResponse partition_query_response; { grpc::ClientContext context; ZETASQL_ASSERT_OK(raw_client()->PartitionQuery(&context, partition_query_request, &partition_query_response)); } ASSERT_GT(partition_query_response.partitions().size(), 0); // Validate that a new/different transaction cannot be used for query using // partition token than the one used for partition query. spanner_api::ExecuteSqlRequest sql_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { begin { read_only {} } } sql: "SELECT UserID, Name FROM Users" partition_token: "$1" )", session.name(), partition_query_response.partitions()[0].partition_token())); grpc::ClientContext context; spanner_api::ResultSet query_response; EXPECT_THAT(raw_client()->ExecuteSql(&context, sql_request, &query_response), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryWithDifferentSql) { ZETASQL_ASSERT_OK_AND_ASSIGN(auto session, CreateSession()); spanner_api::PartitionQueryRequest partition_query_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { begin { read_only {} } } sql: "SELECT UserID, Name FROM Users" )", session.name())); spanner_api::PartitionResponse partition_query_response; { grpc::ClientContext context; ZETASQL_ASSERT_OK(raw_client()->PartitionQuery(&context, partition_query_request, &partition_query_response)); } ASSERT_GT(partition_query_response.partitions().size(), 0); // Validate that query cannot be performed using a different sql when using // partition token. spanner_api::ExecuteSqlRequest sql_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { id: "$1" } sql: "SELECT UserID, Name FROM Users WHERE UserId=1" partition_token: "$2" )", session.name(), partition_query_response.transaction().id(), partition_query_response.partitions()[0].partition_token())); grpc::ClientContext context; spanner_api::ResultSet query_response; EXPECT_THAT(raw_client()->ExecuteSql(&context, sql_request, &query_response), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CannotQueryWithDifferentParams) { ZETASQL_ASSERT_OK_AND_ASSIGN(auto session, CreateSession()); spanner_api::PartitionQueryRequest partition_query_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { begin { read_only {} } } sql: "SELECT UserID, Name FROM Users WHERE UserId=@id" params { fields: { key: "id", value: { number_value: 1 } }, } param_types: { key: "id" value: { code: 3 } } )", session.name())); spanner_api::PartitionResponse partition_query_response; { grpc::ClientContext context; ZETASQL_ASSERT_OK(raw_client()->PartitionQuery(&context, partition_query_request, &partition_query_response)); } ASSERT_GT(partition_query_response.partitions().size(), 0); // Validate that a different set of params cannot be query when using // partition token. Note that the value of @id is different (2 vs 1) below. spanner_api::ExecuteSqlRequest sql_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { id: "$1" } sql: "SELECT UserID, Name FROM Users WHERE UserId=@id" params { fields: { key: "id", value: { number_value: 2 } }, } param_types: { key: "id" value: { code: 3 } } partition_token: "$2" )", session.name(), partition_query_response.transaction().id(), partition_query_response.partitions()[0].partition_token())); grpc::ClientContext context; spanner_api::ResultSet query_response; EXPECT_THAT(raw_client()->ExecuteSql(&context, sql_request, &query_response), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(PartitionQueryTest, CanQueryWithMultipleParams) { PopulateDatabase(); ZETASQL_ASSERT_OK_AND_ASSIGN(auto session, CreateSession()); spanner_api::PartitionQueryRequest partition_query_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { begin { read_only {} } } sql: "SELECT UserID, ThreadId, Starred FROM Threads WHERE UserId=@id AND ThreadId=@tid" params { fields: { key: "id", value: { number_value: 1 } }, fields: { key: "tid", value: { number_value: 2 } }, } param_types: { key: "id" value: { code: 3 } } param_types: { key: "tid" value: { code: 3 } } )", session.name())); spanner_api::PartitionResponse partition_query_response; { grpc::ClientContext context; ZETASQL_ASSERT_OK(raw_client()->PartitionQuery(&context, partition_query_request, &partition_query_response)); } ASSERT_GT(partition_query_response.partitions().size(), 0); // Validate that a query with same set of params can be executed using the // partition token created above. spanner_api::ExecuteSqlRequest sql_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { id: "$1" } sql: "SELECT UserID, ThreadId, Starred FROM Threads WHERE UserId=@id AND ThreadId=@tid" params { fields: { key: "id", value: { number_value: 1 } }, fields: { key: "tid", value: { number_value: 2 } }, } param_types: { key: "id" value: { code: 3 } } param_types: { key: "tid" value: { code: 3 } } partition_token: "$2" )", session.name(), partition_query_response.transaction().id(), partition_query_response.partitions()[0].partition_token())); grpc::ClientContext context; spanner_api::ResultSet query_response; ZETASQL_EXPECT_OK(raw_client()->ExecuteSql(&context, sql_request, &query_response)); } TEST_F(PartitionQueryTest, CannotQueryWithInvalidQueryMode) { ZETASQL_ASSERT_OK_AND_ASSIGN(auto session, CreateSession()); spanner_api::PartitionQueryRequest partition_query_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { begin { read_only {} } } sql: "SELECT UserID, Name FROM Users" )", session.name())); spanner_api::PartitionResponse partition_query_response; { grpc::ClientContext context; ZETASQL_ASSERT_OK(raw_client()->PartitionQuery(&context, partition_query_request, &partition_query_response)); } ASSERT_GT(partition_query_response.partitions().size(), 0); spanner_api::ExecuteSqlRequest sql_request = PARSE_TEXT_PROTO(absl::Substitute( R"( session: "$0" transaction { id: "$1" } sql: "SELECT UserID, Name FROM Users" partition_token: "$2" )", session.name(), partition_query_response.transaction().id(), partition_query_response.partitions()[0].partition_token())); // Query mode NORMAL (default) works with partition query. { sql_request.set_query_mode(spanner_api::ExecuteSqlRequest::NORMAL); grpc::ClientContext context; spanner_api::ResultSet query_response; ZETASQL_EXPECT_OK(raw_client()->ExecuteSql(&context, sql_request, &query_response)); } // Query mode PLAN cannot be used with partition query. { sql_request.set_query_mode(spanner_api::ExecuteSqlRequest::PLAN); grpc::ClientContext context; spanner_api::ResultSet query_response; EXPECT_THAT( raw_client()->ExecuteSql(&context, sql_request, &query_response), StatusIs(absl::StatusCode::kInvalidArgument)); } // Query mode PROFILE cannot be used with partition query. { sql_request.set_query_mode(spanner_api::ExecuteSqlRequest::PROFILE); grpc::ClientContext context; spanner_api::ResultSet query_response; EXPECT_THAT( raw_client()->ExecuteSql(&context, sql_request, &query_response), StatusIs(absl::StatusCode::kInvalidArgument)); } } } // namespace } // namespace test } // namespace emulator } // namespace spanner } // namespace google
; A033661: Trajectory of 31 under map x->x + (x-with-digits-reversed). ; Submitted by Jamie Morken(s4) ; 31,44,88,176,847,1595,7546,14003,44044,88088,176176,847847,1596595,7553546,14007103,44177144,88354288,176599676,853595347,1597190705,6668108656,13236127322,35608290553,71117571206 mov $2,$0 lpb $2 mov $0,$1 add $0,31 seq $0,4086 ; Read n backwards (referred to as R(n) in many sequences). add $1,$0 sub $2,1 lpe mov $0,$1 add $0,31
SECTION code_clib PUBLIC w_xorpixel defc NEEDxor = 1 .w_xorpixel INCLUDE "w_pixel.inc"
[bits 64] [extern _Z9task_exitv] [global task_entry] ; NOTE: the addres to the target task needs to be in rax ; we do this to prevent jumping to random code if the task returns task_entry: sti mov rbp, 0 ; mark bottom of stack trace call rax .exit: call _Z9task_exitv ; if the task ever returns just exit jmp $
; A055770: Largest factorial number which divides n. ; Submitted by Jamie Morken(s4) ; 1,2,1,2,1,6,1,2,1,2,1,6,1,2,1,2,1,6,1,2,1,2,1,24,1,2,1,2,1,6,1,2,1,2,1,6,1,2,1,2,1,6,1,2,1,2,1,24,1,2,1,2,1,6,1,2,1,2,1,6,1,2,1,2,1,6,1,2,1,2,1,24,1,2,1,2,1,6,1,2,1,2,1,6,1,2,1,2,1,6,1,2,1,2,1,24,1,2,1,2 add $0,1 mov $2,1 mov $3,1 lpb $0 add $2,1 dif $0,$2 mul $3,$2 lpe mov $0,$3
; ; ANSI Video handling for Sharp OZ family ; ; Text Attributes ; m - Set Graphic Rendition ; ; -- ONLY FOO STUFF, FOR NOW !! -- ; ; Stefano Bodrato - Aug. 2002 ; ; ; $Id: f_ansi_attr.asm,v 1.3 2016-06-12 16:06:43 dom Exp $ ; SECTION code_clib PUBLIC ansi_attr EXTERN INVRS .ansi_attr ; and a ; jr nz,noreset ; ret ;.noreset ; cp 1 ; jr nz,nobold ; ret ;.nobold ; cp 2 ; jr z,dim ; cp 8 ; jr nz,nodim .dim ; ret ;.nodim cp 4 jr nz,nounderline ld a,32 ld (INVRS+2),a ; underline 1 ret .nounderline cp 24 jr nz,noCunderline ld a, 24 ld (INVRS+2),a ; underline 0 ret .noCunderline cp 5 jr nz,noblink ld a,32 ld (INVRS+2),a ; underline (blink emulation) 1 ret .noblink cp 25 jr nz,nocblink ld a, 24 ld (INVRS+2),a ; underline (blink emulation) 0 ret .nocblink cp 7 jr nz,noreverse ld a,47 ld (INVRS),a ; inverse 1 ret .noreverse cp 27 jr nz,noCreverse xor a ld (INVRS),a ; inverse 0 ret .noCreverse ret
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2018 The PandaCash developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "splashscreen.h" #include "clientversion.h" #include "init.h" #include "networkstyle.h" #include "ui_interface.h" #include "util.h" #include "version.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <QApplication> #include <QCloseEvent> #include <QDesktopWidget> #include <QPainter> SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle* networkStyle) : QWidget(0, f), curAlignment(0) { // set reference point, paddings int paddingLeft = 14; int paddingTop = 735; int titleVersionVSpace = 17; int titleCopyrightVSpace = 32; float fontFactor = 1.0; // define text to place QString titleText = tr("PandaCash Core"); QString versionText = QString(tr("Version %1")).arg(QString::fromStdString(FormatFullVersion())); QString copyrightTextBtc = QChar(0xA9) + QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers")); QString copyrightTextDash = QChar(0xA9) + QString(" 2014-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Dash Core developers")); QString copyrightTextPandaCash = QChar(0xA9) + QString(" 2015-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The PandaCash Core developers")); QString titleAddText = networkStyle->getTitleAddText(); QString font = QApplication::font().toString(); // load the bitmap for writing some text over it pixmap = networkStyle->getSplashImage(); QPainter pixPaint(&pixmap); pixPaint.setPen(QColor(197, 179, 88)); // check font size and drawing with pixPaint.setFont(QFont(font, 28 * fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if (titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 28 * fontFactor)); fm = pixPaint.fontMetrics(); //titleTextWidth = fm.width(titleText); pixPaint.drawText(paddingLeft, paddingTop, titleText); pixPaint.setFont(QFont(font, 15 * fontFactor)); pixPaint.drawText(paddingLeft, paddingTop + titleVersionVSpace, versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10 * fontFactor)); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace, copyrightTextBtc); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 12, copyrightTextDash); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 24, copyrightTextPandaCash); // draw additional text if special network if (!titleAddText.isEmpty()) { QFont boldFont = QFont(font, 10 * fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int titleAddTextWidth = fm.width(titleAddText); pixPaint.drawText(pixmap.width() - titleAddTextWidth - 10, pixmap.height() - 25, titleAddText); } pixPaint.end(); // Set window title setWindowTitle(titleText + " " + titleAddText); // Resize window and move to center of desktop, disallow resizing QRect r(QPoint(), pixmap.size()); resize(r.size()); setFixedSize(r.size()); move(QApplication::desktop()->screenGeometry().center() - r.center()); subscribeToCoreSignals(); } SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } void SplashScreen::slotFinish(QWidget* mainWin) { Q_UNUSED(mainWin); hide(); } static void InitMessage(SplashScreen* splash, const std::string& message) { QMetaObject::invokeMethod(splash, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom | Qt::AlignHCenter), Q_ARG(QColor, QColor(197, 179, 88))); } static void ShowProgress(SplashScreen* splash, const std::string& title, int nProgress) { InitMessage(splash, title + strprintf("%d", nProgress) + "%"); } #ifdef ENABLE_WALLET static void ConnectWallet(SplashScreen* splash, CWallet* wallet) { wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1)); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET if (pwalletMain) pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #endif } void SplashScreen::showMessage(const QString& message, int alignment, const QColor& color) { curMessage = message; curAlignment = alignment; curColor = color; update(); } void SplashScreen::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.drawPixmap(0, 0, pixmap); QRect r = rect().adjusted(5, 5, -5, -5); painter.setPen(curColor); painter.drawText(r, curAlignment, curMessage); } void SplashScreen::closeEvent(QCloseEvent* event) { StartShutdown(); // allows an "emergency" shutdown during startup event->ignore(); }
;Parameshor Bhandari ;Program: 5 ;Title: String Processing Lab ; org 100h section .data msg1 DB 'Parameshor Bhandari $' msg2 DB 0Ah,0Dh,'Enter the string(Maximum 75 character): $' msg3 DB 0Ah,0Dh,'The character in reverse is: $' exCode DB 0 ;section .bss MAX_LEN DB 3 ACT_LEN DB 0 chars TIMES 4 DB 0 section .text start: mov dx, msg1 ;get message1 mov ah,09h ;display string function int 21h ;Display message1 mov ah,09h ;display string function mov dx, msg2 ;get message2 mov ah,09h ;display string function int 21h ;Display message2 mov di,chars cld ;process from left xor bx,bx ;BX holds no. of chars read mov ah,1 ;input char function int 21h ;read a char into AL WHILE1: cmp al,0Dh ;<CR>? je ENDWHLE1 ;yes, exit ;if char is backspace cmp al,08h ;is char a backspace? jne ELSE1 ;no, store in string dec di ;yes, move string ptr back dec bx ;decrement char counter jmp READ ;and go to read another char ELSE1: stosb ;store char in string inc bx ;increment char count READ: int 21h ;read a char into AL jmp WHILE1 ;and continue loop ENDWHLE1: lea si,[bx+chars-1] ;start of string std ;process from left mov cx,bx ;cx holds no. of chars jcxz exit ;exit if none mov dx, msg3 ;get message3 mov ah,09h ;display string function int 21h mov ah,2 ;display char function TOP: lodsb ;char in al mov dl,al ;move it to dl int 21h ;display character loop TOP ;loop until done exit: mov ah,4Ch ;DOS function: exit program mov al,[exCode] ;Return exit code value int 21h ;call DOS. Terminte Program
SECTION code_fp_math16 PUBLIC _frexpf16 EXTERN cm16_sdcc_frexp defc _frexpf16 = cm16_sdcc_frexp
# Turn on the red, green, and blue LEDs on the Longan Nano include gd32vf103.asm # jump to "main" since programs execute top to bottom # we do this to enable writing helper funcs at the top j main # Func: rcu_init # Arg: a0 = RCU base addr # Arg: a1 = RCU config # Ret: none rcu_init: # store config sw a1, RCU_APB2EN_OFFSET(a0) ret # Func: gpio_init # Arg: a0 = GPIO port base addr # Arg: a1 = GPIO pin number # Arg: a2 = GPIO config (4 bits) # Ret: none gpio_init: # advance to CTL0 addi t0, a0, GPIO_CTL0_OFFSET # if pin number is less than 8, CTL0 is correct slti t1, a1, 8 bnez t1, gpio_init_config # else we need CTL1 and then subtract 8 from the pin number addi t0, t0, 4 addi a1, a1, -8 gpio_init_config: # multiply pin number by 4 to get shift amount addi t1, zero, 4 mul a1, a1, t1 # load current config lw t1, 0(t0) # align and clear existing pin config li t2, 0b1111 sll t2, t2, a1 not t2, t2 and t1, t1, t2 # align and apply new pin config sll a2, a2, a1 or t1, t1, a2 # store updated config sw t1, 0(t0) ret # LED Locations # (based on schematic) # -------------------- # Red: GPIO Port C, Pin 13 (active-low) # Green: GPIO Port A, Pin 1 (active-low) # Blue: GPIO Port A, Pin 2 (active-low) main: # enable RCU (GPIO ports A and C) li a0, RCU_BASE_ADDR li a1, (1 << RCU_APB2EN_PAEN_BIT) | (1 << RCU_APB2EN_PCEN_BIT) call rcu_init # enable red LED li a0, GPIO_BASE_ADDR_C li a1, 13 li a2, (GPIO_CTL_OUT_PUSH_PULL << 2 | GPIO_MODE_OUT_50MHZ) call gpio_init # enable green LED li a0, GPIO_BASE_ADDR_A li a1, 1 li a2, (GPIO_CTL_OUT_PUSH_PULL << 2 | GPIO_MODE_OUT_50MHZ) call gpio_init # enable blue LED li a0, GPIO_BASE_ADDR_A li a1, 2 li a2, (GPIO_CTL_OUT_PUSH_PULL << 2 | GPIO_MODE_OUT_50MHZ) call gpio_init # NOTE: no need to explicitly turn the LEDs on because they are # all active-low (they turn on when the GPIO pins are off / grounded)
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r8 push %r9 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_UC_ht+0x1a9a4, %r8 add $60869, %rax mov $0x6162636465666768, %rdx movq %rdx, %xmm0 movups %xmm0, (%r8) nop nop add %r13, %r13 lea addresses_A_ht+0x84a4, %rsi lea addresses_WT_ht+0x5664, %rdi nop nop nop cmp $14817, %rax mov $124, %rcx rep movsq nop nop nop nop nop sub $23727, %rdi lea addresses_UC_ht+0x13874, %rsi lea addresses_A_ht+0x143a4, %rdi nop nop nop nop xor $23122, %r9 mov $78, %rcx rep movsb and $60777, %rdx lea addresses_D_ht+0xdca4, %rsi lea addresses_WC_ht+0x3c1e, %rdi add $1262, %r8 mov $112, %rcx rep movsl nop nop nop nop nop add $12222, %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r9 pop %r8 pop %r13 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %r15 push %r9 push %rbp push %rdi push %rsi // Store mov $0x4065120000000ca4, %r9 clflush (%r9) nop nop nop nop and %r14, %r14 mov $0x5152535455565758, %rbp movq %rbp, %xmm5 movaps %xmm5, (%r9) nop nop nop nop nop add $4117, %r10 // Store lea addresses_PSE+0x3a24, %rsi nop cmp %r9, %r9 mov $0x5152535455565758, %rdi movq %rdi, (%rsi) // Exception!!! nop nop nop nop nop mov (0), %rsi nop add %rbp, %rbp // Faulty Load mov $0x4065120000000ca4, %r9 nop nop add $37833, %r15 movups (%r9), %xmm0 vpextrq $1, %xmm0, %rbp lea oracles, %rsi and $0xff, %rbp shlq $12, %rbp mov (%rsi,%rbp,1), %rbp pop %rsi pop %rdi pop %rbp pop %r9 pop %r15 pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_NC', 'NT': False, 'AVXalign': True, 'size': 16, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 7}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 6}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_WT_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_A_ht'}} {'OP': 'REPM', 'src': {'same': True, 'congruent': 11, 'type': 'addresses_D_ht'}, 'dst': {'same': True, 'congruent': 0, 'type': 'addresses_WC_ht'}} {'46': 166, '00': 1851, '45': 2} 00 00 00 00 00 46 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 46 00 00 00 00 46 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 46 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 46 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 46 00 46 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 46 46 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 46 00 00 00 46 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 46 46 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 46 00 00 00 00 46 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 46 00 00 00 00 00 00 00 00 46 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 46 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 46 00 00 00 46 00 00 00 00 00 00 46 46 00 00 00 46 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 46 00 00 00 00 00 00 00 00 00 00 00 46 46 00 00 00 46 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 45 00 00 00 00 46 00 00 00 00 00 46 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 46 00 00 00 00 00 46 00 00 00 00 00 00 46 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 */
<% from pwnlib.shellcraft.aarch64.linux import exit as exit from pwnlib.shellcraft.aarch64.linux import mmap from pwnlib.shellcraft.aarch64 import setregs, mov, memcpy from pwnlib.shellcraft import common from pwnlib.util.packing import unpack %> <%page args="address"/> <%docstring> Loads a statically-linked ELF into memory and transfers control. Arguments: address(int): Address of the ELF as a register or integer. </%docstring> <% elf_magic = unpack('\x7fELF', 32) die = common.label('die') load_one = common.label('load_one') next_phdr = common.label('next_phdr') """ Elf64_Ehdr +0x0000 e_ident : unsigned char [16] +0x0010 e_type : Elf64_Half +0x0012 e_machine : Elf64_Half +0x0014 e_version : Elf64_Word +0x0018 e_entry : Elf64_Addr +0x0020 e_phoff : Elf64_Off +0x0028 e_shoff : Elf64_Off +0x0030 e_flags : Elf64_Word +0x0034 e_ehsize : Elf64_Half +0x0036 e_phentsize : Elf64_Half +0x0038 e_phnum : Elf64_Half +0x003a e_shentsize : Elf64_Half +0x003c e_shnum : Elf64_Half +0x003e e_shstrndx : Elf64_Half Elf64_Phdr +0x0000 p_type : Elf64_Word +0x0004 p_flags : Elf64_Word +0x0008 p_offset : Elf64_Off +0x0010 p_vaddr : Elf64_Addr +0x0018 p_paddr : Elf64_Addr +0x0020 p_filesz : Elf64_Xword +0x0028 p_memsz : Elf64_Xword +0x0030 p_align : Elf64_Xword """ e_entry = 0x0018 e_phoff = 0x0020 e_phnum = 0x0038 e_phentsize = 0x0036 p_type = 0x0000 p_offset = 0x0008 p_vaddr = 0x0010 p_filesz = 0x0020 p_memsz = 0x0028 PT_LOAD = 1 %> ${setregs({'x0': address})} /* Check the ELF header */ ldr x1, [x0] ${mov('x2', elf_magic)} cmp w1, w2 bne ${die} /* Discover program headers */ add x1, x0, #${e_phoff} ldr x1, [x1] add x1, x1, x0 /* x1 = &program headers */ add x2, x0, #${e_phentsize} ldrh w2, [x2] /* x2 = program header size */ add x3, x0, #${e_phnum} ldrh w3, [x3] /* x3 = number of program headers */ 1: /* For each section header, mmap it to the desired address */ stp x0, x1, [sp, #-16]! stp x2, x3, [sp, #-16]! bl ${load_one} ldp x2, x3, [sp], #16 ldp x0, x1, [sp], #16 add x1, x1, x2 subs x3, x3, #1 bne 1b /* Everything is loaded and RWX. Find the entry point and call it */ add x1, x0, #${e_entry} ldr x1, [x1] mov x8, x1 /* Set up the fake stack. For whatever reason, aarch64 binaries really want AT_RANDOM to be available. */ /* AT_NULL */ eor x0, x0, x0 eor x1, x1, x1 stp x0, x1, [sp, #-16]! /* AT_RANDOM */ mov x2, #25 mov x3, sp stp x2, x3, [sp, #-16]! /* argc, argv[0], argv[1], envp */ /* ideally these could all be empty, but unfortunately we have to keep the stack aligned. it's easier to just push an extra argument than care... */ stp x0, x1, [sp, #-16]! /* argv[1] = NULL, envp = NULL */ mov x0, 1 mov x1, sp stp x0, x1, [sp, #-16]! /* argc = 1, argv[0] = "" */ br x8 ${load_one}: /* x1 = &program headers */ stp x29, x30, [sp, #-16]! mov x29, sp /* If it's not a PT_LOAD header, don't care */ add x2, x1, #${p_type} ldr x2, [x2] uxth w2, w2 /* zero-extend halfword */ cmp x2, #${PT_LOAD} bne ${next_phdr} /* Get the destination address into x2 */ add x2, x1, ${p_vaddr} ldr x2, [x2] /* Get the size to mmap into x3 */ add x3, x1, #${p_memsz} ldr x3, [x3] lsr w3, w3, #12 add x3, x3, #1 /* We can't move the program break with brk(), so we basically have to fake it. Allocate more space than we ever expect the heap to need, by over-allocating space by 8x */ lsl w3, w3, #12 + 4 /* Map the page in */ stp x0, x1, [sp, #-16]! stp x2, x3, [sp, #-16]! lsr w2, w2, #12 lsl w2, w2, #12 ${mmap('x2', 'x3', 'PROT_READ|PROT_WRITE|PROT_EXEC', 'MAP_ANONYMOUS|MAP_PRIVATE|MAP_FIXED', 0, 0)} /* Ignore failure */ ldp x2, x3, [sp], #16 ldp x0, x1, [sp], #16 /* Get the source address into x4 */ add x4, x1, #${p_offset} ldr x4, [x4] add x4, x4, x0 /* Get the number of bytes into x5 */ add x5, x1, #${p_filesz} ldr x5, [x5] /* Copy the data */ stp x0, x1, [sp, #-16]! stp x2, x3, [sp, #-16]! stp x4, x5, [sp, #-16]! ${memcpy('x2','x4','x5')} ldp x4, x5, [sp], #16 ldp x2, x3, [sp], #16 ldp x0, x1, [sp], #16 ${next_phdr}: mov sp, x29 ldp x29, x30, [sp], #16 ret x30 ${die}: ${exit(1)}
; A084266: Binomial transform of A084265. ; 1,3,11,34,96,256,656,1632,3968,9472,22272,51712,118784,270336,610304,1368064,3047424,6750208,14876672,32636928,71303168,155189248,336592896,727711744,1568669696,3372220416,7230980096,15468593152,33017561088,70330089472,149518548992,317290708992,672162381824,1421634174976,3002182139904,6330781794304,13331578486784,28037546508288,58892591562752,123557619171328,258934988341248,542059232493568,1133596488237056,2368348046229504,4943404278480896,10309021022027776,21480059160231936,44719336924905472 add $0,4 mov $1,2 pow $1,$0 bin $0,2 sub $0,4 mul $0,$1 sub $0,64 div $0,64 add $0,1
; A140062: 101*2^(n-1) - 100. ; 1,102,304,708,1516,3132,6364,12828,25756,51612,103324,206748,413596,827292,1654684,3309468,6619036,13238172,26476444,52952988,105906076,211812252,423624604,847249308,1694498716 mov $1,2 pow $1,$0 mul $1,101 sub $1,100
//--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1996 // // File: cenumgrp.cxx // // Contents: LDAP GroupCollection Enumeration Code // // CLDAPGroupCollectionEnum:: // CLDAPGroupCollectionEnum:: // CLDAPGroupCollectionEnum:: // CLDAPGroupCollectionEnum:: // // History: //---------------------------------------------------------------------------- #include "ldap.hxx" #pragma hdrstop HRESULT BuildADsPathFromLDAPPath( LPWSTR szNamespace, LPWSTR szLdapDN, LPWSTR * ppszADsPathName ); //+--------------------------------------------------------------------------- // // Function: LDAPEnumVariant::Create // // Synopsis: // // Arguments: [pCollection] // [ppEnumVariant] // // Returns: HRESULT // // Modifies: // // History: 01-30-95 krishnag Created. // //---------------------------------------------------------------------------- HRESULT CLDAPGroupCollectionEnum::Create( CLDAPGroupCollectionEnum FAR* FAR* ppenumvariant, BSTR Parent, BSTR ADsPath, BSTR GroupName, VARIANT vMembers, VARIANT vFilter, CCredentials& Credentials, IDirectoryObject * pIDirObj, BOOL fRangeRetrieval ) { HRESULT hr = NOERROR; CLDAPGroupCollectionEnum FAR* penumvariant = NULL; long lLBound = 0; long lUBound = 0; *ppenumvariant = NULL; penumvariant = new CLDAPGroupCollectionEnum(); if (!penumvariant) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } penumvariant->_fRangeRetrieval = fRangeRetrieval; hr = ADsAllocString( Parent , &penumvariant->_Parent); BAIL_ON_FAILURE(hr); hr = ADsAllocString(GroupName, &penumvariant->_GroupName); BAIL_ON_FAILURE(hr); hr = ADsAllocString(ADsPath, &penumvariant->_ADsPath); BAIL_ON_FAILURE(hr); hr = VariantCopy( &penumvariant->_vMembers, &vMembers ); BAIL_ON_FAILURE(hr); if ( vMembers.vt == VT_BSTR ) // 1 member only { penumvariant->_lMembersCount = 1; } else { hr = SafeArrayGetLBound(V_ARRAY(&penumvariant->_vMembers), 1, (long FAR *)&lLBound ); BAIL_ON_FAILURE(hr); hr = SafeArrayGetUBound(V_ARRAY(&penumvariant->_vMembers), 1, (long FAR *)&lUBound ); BAIL_ON_FAILURE(hr); penumvariant->_lMembersCount = lUBound - lLBound + 1; } hr = ObjectTypeList::CreateObjectTypeList( vFilter, &penumvariant->_pObjList ); BAIL_ON_FAILURE(hr); penumvariant->_Credentials = Credentials; pIDirObj->QueryInterface( IID_IDirectoryObject, (void **) &(penumvariant->_pIDirObj) ); BAIL_ON_FAILURE(hr); *ppenumvariant = penumvariant; RRETURN(hr); error: delete penumvariant; RRETURN_EXP_IF_ERR(hr); } //---------------------------------------------------------------------------- // // Function: // // Synopsis: // //---------------------------------------------------------------------------- CLDAPGroupCollectionEnum::CLDAPGroupCollectionEnum() : _Parent(NULL), _ADsPath(NULL), _GroupName(NULL), _lCurrentIndex(0), _lMembersCount(0), _pIDirObj(NULL), _fRangeRetrieval(FALSE), _fAllRetrieved(FALSE), _pszRangeToFetch(NULL), _pAttributeEntries(NULL), _pCurrentEntry(NULL), _dwCurRangeIndex(0), _dwCurRangeMax(0), _dwNumEntries(0), _fLastSet(FALSE) { VariantInit( &_vMembers ); _pObjList = NULL; } //---------------------------------------------------------------------------- // // Function: // // Synopsis: // //---------------------------------------------------------------------------- CLDAPGroupCollectionEnum::CLDAPGroupCollectionEnum( ObjectTypeList ObjList ) : _Parent(NULL), _ADsPath(NULL), _GroupName(NULL), _lCurrentIndex(0), _lMembersCount(0) { VariantInit( &_vMembers ); _pObjList = NULL; } //---------------------------------------------------------------------------- // // Function: // // Synopsis: // //---------------------------------------------------------------------------- CLDAPGroupCollectionEnum::~CLDAPGroupCollectionEnum() { VariantClear( &_vMembers ); delete _pObjList; if ( _Parent ) ADsFreeString( _Parent ); if ( _GroupName ) ADsFreeString( _GroupName ); if ( _ADsPath ) ADsFreeString( _ADsPath ); if (_pIDirObj) { _pIDirObj->Release(); } if (_pszRangeToFetch) { FreeADsStr(_pszRangeToFetch); } if (_pAttributeEntries) { FreeADsMem(_pAttributeEntries); } } //---------------------------------------------------------------------------- // // Function: // // Synopsis: // //---------------------------------------------------------------------------- HRESULT CLDAPGroupCollectionEnum::EnumGroupMembers( ULONG cElements, VARIANT FAR* pvar, ULONG FAR* pcElementFetched ) { HRESULT hr = S_FALSE; IDispatch *pDispatch = NULL; DWORD i = 0; IADs * pIADs = NULL; BSTR pszClass = NULL; DWORD dwClassID; BSTR pszFilterName = NULL; BOOL fFound = FALSE; BOOL fEmpty = TRUE; while (i < cElements) { hr = GetUserMemberObject(&pDispatch); if (FAILED(hr)) { // // Set hr to S_FALSE as all our enumerators are not // built to handle a failure hr but only S_OK and S_FALSE. // hr = S_FALSE; } if (hr == S_FALSE) { break; } // // Apply the IADsMembers::put_Filter filter. // If the enumerated object is not one of the types to be returned, // go on to the next member of the group. // hr = pDispatch->QueryInterface(IID_IADs, (void **)&pIADs); BAIL_ON_FAILURE(hr); // // To check whether use specifies filter // fEmpty = _pObjList->IsEmpty(); // // User specifies the filter // if (!fEmpty) { // // Determine the object class of the enumerated object and the corresponding // object class ID number (as specified in the Filters global array). // hr = pIADs->get_Class(&pszClass); BAIL_ON_FAILURE(hr); // // Enumerate through the object classes listed in the user-specified filter // until we either find a match (fFound = TRUE) or we reach the end of the // list. // hr = _pObjList->Reset(); // // compare with the user defined filter // while (SUCCEEDED(hr)) { hr = _pObjList->GetCurrentObject(&pszFilterName); if (SUCCEEDED(hr) && (!_wcsicmp(pszClass, pszFilterName)) ) { fFound = TRUE; if(pszFilterName) { SysFreeString(pszFilterName); pszFilterName = NULL; } break; } if(pszFilterName) { SysFreeString(pszFilterName); pszFilterName = NULL; } hr = _pObjList->Next(); } if (!fFound) { // // not on the list of objects to return, try again // with the next member of the group // pDispatch->Release(); pDispatch = NULL; pIADs->Release(); pIADs = NULL; if (pszClass) { ADsFreeString(pszClass); pszClass = NULL; } continue; } if (pszClass) { ADsFreeString(pszClass); pszClass = NULL; } } if(pIADs) { pIADs->Release(); pIADs = NULL; } // // Return it. // VariantInit(&pvar[i]); pvar[i].vt = VT_DISPATCH; pvar[i].pdispVal = pDispatch; (*pcElementFetched)++; i++; } RRETURN_EXP_IF_ERR(hr); error: if (pDispatch) { pDispatch->Release(); } if (pIADs) { pIADs->Release(); } if (pszClass) { ADsFreeString(pszClass); } RRETURN_EXP_IF_ERR(hr); } //---------------------------------------------------------------------------- // // Function: // // Synopsis: // //---------------------------------------------------------------------------- HRESULT CLDAPGroupCollectionEnum::GetUserMemberObject( IDispatch ** ppDispatch ) { HRESULT hr = S_OK; VARIANT v; IUnknown *pObject = NULL; TCHAR *pszADsPath = NULL; LPWSTR pszUserName = NULL; LPWSTR pszPassword = NULL; DWORD dwAuthFlags = 0; BOOL fRangeUsed = FALSE; *ppDispatch = NULL; VariantInit(&v); hr = _Credentials.GetUserName(&pszUserName); BAIL_ON_FAILURE(hr); hr = _Credentials.GetPassword(&pszPassword); BAIL_ON_FAILURE(hr); dwAuthFlags = _Credentials.GetAuthFlags(); while ( TRUE ) { VariantInit(&v); if ( _lCurrentIndex >= _lMembersCount ) { hr = S_FALSE; // // See if we need to fetch members using Rangeretrieval. // if (_fRangeRetrieval && !_fAllRetrieved) { hr = GetNextMemberRange(&v); BAIL_ON_FAILURE(hr); if (hr == S_FALSE) { goto error; } fRangeUsed = TRUE; } else goto error; } // // Variant v will have correct value already if range // retrieval was used. // if (!fRangeUsed) { if ( _vMembers.vt == VT_BSTR ) { hr = VariantCopy( &v, &_vMembers ); } else { hr = SafeArrayGetElement( V_ARRAY(&_vMembers), &_lCurrentIndex, &v); } BAIL_ON_FAILURE(hr); } _lCurrentIndex++; LPTSTR pszMember = V_BSTR(&v); LPTSTR pszTemp = NULL; hr = BuildADsPathFromLDAPPath( _Parent, pszMember, &pszADsPath ); BAIL_ON_FAILURE(hr); hr = ADsOpenObject( pszADsPath, pszUserName, pszPassword, dwAuthFlags, IID_IUnknown, (LPVOID *)&pObject ); if ( pszADsPath ) { FreeADsStr( pszADsPath ); pszADsPath = NULL; } VariantClear(&v); // // If we failed to get the current object, continue with the next one // if ( FAILED(hr)) continue; hr = pObject->QueryInterface( IID_IDispatch, (LPVOID *) ppDispatch ); BAIL_ON_FAILURE(hr); hr = S_OK; goto error; } error: if ( pObject ) pObject->Release(); if ( pszADsPath ) FreeADsStr( pszADsPath ); if (pszPassword) { SecureZeroMemory(pszPassword, wcslen(pszPassword)*sizeof(WCHAR)); FreeADsStr(pszPassword); } if (pszUserName) { FreeADsStr(pszUserName); } VariantClear(&v); RRETURN(hr); } //+--------------------------------------------------------------------------- // // Function: CLDAPGroupCollectionEnum::Next // // Synopsis: Returns cElements number of requested NetOle objects in the // array supplied in pvar. // // Arguments: [cElements] -- The number of elements requested by client // [pvar] -- ptr to array of VARIANTs to for return objects // [pcElementFetched] -- if non-NULL, then number of elements // -- actually returned is placed here // // Returns: HRESULT -- S_OK if number of elements requested are returned // -- S_FALSE if number of elements is < requested // // Modifies: // // History: 11-3-95 krishnag Created. // //---------------------------------------------------------------------------- STDMETHODIMP CLDAPGroupCollectionEnum::Next( ULONG cElements, VARIANT FAR* pvar, ULONG FAR* pcElementFetched ) { ULONG cElementFetched = 0; HRESULT hr = S_OK; hr = EnumGroupMembers( cElements, pvar, &cElementFetched ); if (pcElementFetched) { *pcElementFetched = cElementFetched; } RRETURN_EXP_IF_ERR(hr); } HRESULT CLDAPGroupCollectionEnum::UpdateRangeToFetch() { HRESULT hr = S_OK; WCHAR szPath[512]; // // szPath should be big enough to handle any range we // can reasonably expect and will be used to build the // member string. // if (_pszRangeToFetch == NULL) { // // Rather than ask for the first n elements again, // we can use the count we have in the variant array // to decide where we need to start. // wsprintf(szPath, L"member;range=%d-*", _lMembersCount); _pszRangeToFetch = AllocADsStr(szPath); if (!_pszRangeToFetch) { BAIL_ON_FAILURE(hr = E_OUTOFMEMORY); } } else { // // In this case the call to GetObjectAttr has been made // and we need to get the info out of the name. // BOOL fUpdated = FALSE; for (DWORD i = 0; (i < _dwNumEntries) && !fUpdated; i++) { LPWSTR pszTemp = NULL; LPWSTR pszAttrName = _pAttributeEntries[i].pszAttrName; LPWSTR pszStar = NULL; if (wcslen(pszAttrName) > wcslen(L"member;range=")) { // // See if we have our string // if (!_wcsnicmp( pszAttrName, L"member;range=", wcslen(L"member;range") ) ) { _pCurrentEntry = &(_pAttributeEntries[i]); _dwCurRangeMax = _pCurrentEntry->dwNumValues; _dwCurRangeIndex = 0; pszTemp = wcschr(pszAttrName, L'='); if (!pszTemp) { // // No chance of recovery from this. // BAIL_ON_FAILURE(hr = E_FAIL); } // // Move the lower part of range. // *pszTemp++; if (!*pszTemp) { BAIL_ON_FAILURE(hr = E_FAIL); } pszStar = wcschr(pszTemp, L'*'); if (pszStar) { // // Do not bother with any udpate of the range, // we have all the entries. // _fLastSet = TRUE; goto error; } DWORD dwLower = 0; DWORD dwHigher = 0; if (!swscanf(pszTemp, L"%d-%d", &dwLower, &dwHigher)) { BAIL_ON_FAILURE(hr = E_FAIL); } dwHigher++; wsprintf(szPath, L"member;range=%d-*", dwHigher); FreeADsStr(_pszRangeToFetch); _pszRangeToFetch = AllocADsStr(szPath); if (!_pszRangeToFetch) { BAIL_ON_FAILURE(hr = E_OUTOFMEMORY); } // // Set flag so we can get out of the loop. // fUpdated = TRUE; } // this was not member; } // is the length greater than that of member; } // for each entry in attribute entries. if (!fUpdated) { // // Failed cause there was no members or a range. // BAIL_ON_FAILURE(hr = E_FAIL); } } // _pszRangeToFetch was non NULL error: RRETURN(hr); } //+--------------------------------------------------------------------------- // // Function: CLDAPGroupCollectionEnum::GetNextMemberRange // // Synopsis: Returns a variant bstr with the dn of the next member in // the group or FALSE if there are no more. This routine will // will use IDirectoryObject to fetch more members if applicable. // // // Arguments: [pVarMemberBstr] -- ptr to VARIANT for return bstr. // // Returns: HRESULT -- S_OK if number of elements requested are returned // -- S_FALSE if number of elements is < requested // -- Other failure hr's. // Modifies: // // History: 9-12-99 AjayR Created. // //---------------------------------------------------------------------------- HRESULT CLDAPGroupCollectionEnum::GetNextMemberRange( VARIANT FAR* pVarMemberBstr ) { HRESULT hr = S_FALSE; if (_fAllRetrieved) { RRETURN(S_FALSE); } // // Initialize the range to fetch if applicable. // if (_pszRangeToFetch == NULL) { hr = UpdateRangeToFetch(); BAIL_ON_FAILURE(hr); } if (_dwCurRangeIndex == _dwCurRangeMax) { // // Call into wrapper for GetObjectAttributes. // if (_fLastSet) { _fAllRetrieved = TRUE; hr = S_FALSE; } else { hr = UpdateAttributeEntries(); BAIL_ON_FAILURE(hr); } if (hr == S_FALSE) { goto error; } } // // At this point we should have the entries in our current // return set. // if (!_pCurrentEntry) { BAIL_ON_FAILURE(hr = E_FAIL); } if (_dwCurRangeIndex < _dwCurRangeMax) { hr = ADsAllocString( _pCurrentEntry->pADsValues[_dwCurRangeIndex].DNString, &V_BSTR(pVarMemberBstr) ); BAIL_ON_FAILURE(hr); } _dwCurRangeIndex++; error: RRETURN(hr); } HRESULT CLDAPGroupCollectionEnum::UpdateAttributeEntries() { HRESULT hr = S_OK; LPWSTR aStrings[2]; ADsAssert(_pszRangeToFetch || !"Range is NULL internal error"); if (_pAttributeEntries) { FreeADsMem(_pAttributeEntries); _pAttributeEntries = NULL; } aStrings[0] = _pszRangeToFetch; aStrings[1] = NULL; hr = _pIDirObj->GetObjectAttributes( aStrings, 1, &_pAttributeEntries, &_dwNumEntries ); BAIL_ON_FAILURE(hr); if (_dwNumEntries == 0) { hr = S_FALSE; } else { // // Will return error if member was not there. // hr = UpdateRangeToFetch(); BAIL_ON_FAILURE(hr); } error: RRETURN(hr); }
; void funlockfile(FILE *file) SECTION code_stdio PUBLIC _funlockfile EXTERN asm_funlockfile _funlockfile: pop af pop ix push hl push af jp asm_funlockfile
; ; Grundy Newbrain Specific libraries ; ; Stefano Bodrato - 19/05/2007 ; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; This function is linked only in the non-CP/M version ; it calls the ROM functions via the standard rst entry ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Used internally only ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; ; $Id: zcall.asm,v 1.2 2015/01/19 01:33:00 pauloscustodio Exp $ ; PUBLIC ZCALL .ZCALL jp $20 ; ZCALL