text stringlengths 1 1.05M |
|---|
/*
* Copyright (c) 2017, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
L0:
mov (8|M0) acc0.0<1>:w 0x24060000:v
add (8|M0) acc0.0<1>:w acc0.0<8;8,1>:w 0x1C:uw
shl (4|M0) r22.4<1>:w acc0.4<4;4,1>:w 0x5:uw
mov (1|M0) r22.14<1>:uw 0xFF80:uw
mov (1|M0) f0.0<1>:uw r24.0<0;1,0>:ub
(W&~f0.0)jmpi L816
L96:
mov (8|M0) r16.0<1>:ud r0.0<8;8,1>:ud
mov (8|M0) r17.0<1>:ud r26.0<8;8,1>:ud
mov (1|M0) r16.2<1>:ud 0xE000:ud
cmp (1|M0) (eq)f1.0 null.0<1>:w r24.2<0;1,0>:ub 0x1:uw
mov (16|M0) r30.0<1>:uw 0xFFFF:uw
mov (16|M0) r31.0<1>:uw 0xFFFF:uw
mov (16|M0) r39.0<1>:uw 0xFFFF:uw
mov (16|M0) r40.0<1>:uw 0xFFFF:uw
add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x43EA100:ud
(~f1.0) mov (1|M0) r17.2<1>:f r9.6<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.4<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.1<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.4<0;1,0>:f
send (1|M0) r28:uw r16:ub 0x2 a0.0
(~f1.0) mov (1|M0) r17.2<1>:f r9.6<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.7<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.1<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.7<0;1,0>:f
send (1|M0) r37:uw r16:ub 0x2 a0.0
add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x43EA201:ud
(~f1.0) mov (1|M0) r17.2<1>:f r9.6<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.4<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.1<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.4<0;1,0>:f
send (1|M0) r32:uw r16:ub 0x2 a0.0
(~f1.0) mov (1|M0) r17.2<1>:f r9.6<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.7<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.1<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.7<0;1,0>:f
send (1|M0) r41:uw r16:ub 0x2 a0.0
add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x43EA302:ud
(~f1.0) mov (1|M0) r17.2<1>:f r9.6<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.4<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.1<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.4<0;1,0>:f
send (1|M0) r34:uw r16:ub 0x2 a0.0
(~f1.0) mov (1|M0) r17.2<1>:f r9.6<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.7<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.1<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.7<0;1,0>:f
send (1|M0) r43:uw r16:ub 0x2 a0.0
mov (1|M0) a0.8<1>:uw 0x380:uw
mov (1|M0) a0.9<1>:uw 0x400:uw
mov (1|M0) a0.10<1>:uw 0x440:uw
add (4|M0) a0.12<1>:uw a0.8<4;4,1>:uw 0x120:uw
L816:
nop
|
###############################################################################
# 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
.globl w7_ARCFourProcessData
.type w7_ARCFourProcessData, @function
w7_ARCFourProcessData:
push %ebp
mov %esp, %ebp
push %ebx
push %esi
push %edi
push %ebp
movl (16)(%ebp), %edx
movl (8)(%ebp), %esi
movl (12)(%ebp), %edi
movl (20)(%ebp), %ebp
test %edx, %edx
jz .Lquitgas_1
xor %eax, %eax
movzbl (4)(%ebp), %eax
xor %ebx, %ebx
movzbl (8)(%ebp), %ebx
lea (12)(%ebp), %ebp
inc %al
movzbl (%ebp,%eax), %ecx
lea (%esi,%edx), %edx
push %edx
.p2align 4, 0x90
.Lmain_loopgas_1:
add %cl, %bl
movzbl (%ebp,%ebx), %edx
movb %cl, (%ebp,%ebx)
movb %dl, (%ebp,%eax)
add %cl, %dl
movzbl (%ebp,%edx), %edx
add $(1), %al
xorb (%esi), %dl
lea (1)(%esi), %esi
movzbl (%ebp,%eax), %ecx
cmpl (%esp), %esi
movb %dl, (%edi)
lea (1)(%edi), %edi
jb .Lmain_loopgas_1
lea (-12)(%ebp), %ebp
pop %edx
dec %eax
movb %al, (4)(%ebp)
movb %bl, (8)(%ebp)
.Lquitgas_1:
pop %ebp
pop %edi
pop %esi
pop %ebx
pop %ebp
ret
.Lfe1:
.size w7_ARCFourProcessData, .Lfe1-(w7_ARCFourProcessData)
|
//code by Nikhil Nagrale
//nikhilnagrale2 on EveryPlatform
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int maxindex=0;
int minindex=0;
int maxvalue=INT_MIN;
int minvalue=INT_MAX;
for (int i = 0; i < n; i++)
{
int temp;
cin >> temp;
if(temp>maxvalue){
maxindex=i;
maxvalue=temp;
}
if(temp<=minvalue){
minindex=i;
minvalue=temp;
}
}
int ans=(maxindex)+(n-minindex-1);
if(minindex<maxindex){
cout<<ans-1<<endl;;
}else{
cout<<ans<<endl;
}
return 0;
} |
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkParticleSwarmOptimizer.h"
namespace itk
{
ParticleSwarmOptimizer ::ParticleSwarmOptimizer()
{
// magic numbers based on the analysis described in M. Clerc, J. Kennedy,
//"The particle swarm - explosion, stability, and convergence in a
// multidimensional complex space"
this->m_InertiaCoefficient = 0.7298;
this->m_PersonalCoefficient = 1.49609;
this->m_GlobalCoefficient = 1.49609;
}
ParticleSwarmOptimizer ::~ParticleSwarmOptimizer() = default;
void
ParticleSwarmOptimizer ::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << "Acceleration coefficients [inertia, personal, global]: ";
os << "[" << this->m_InertiaCoefficient << ", " << this->m_PersonalCoefficient << ", ";
os << this->m_GlobalCoefficient << "]\n";
}
void
ParticleSwarmOptimizer ::UpdateSwarm()
{
unsigned int j, k, n;
itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randomGenerator =
Statistics::MersenneTwisterRandomVariateGenerator::GetInstance();
n = static_cast<unsigned int>((GetCostFunction())->GetNumberOfParameters());
for (j = 0; j < m_NumberOfParticles; j++)
{
ParticleData & p = m_Particles[j];
ParametersType::ValueType phi1, phi2;
phi1 = randomGenerator->GetVariateWithClosedRange() * this->m_PersonalCoefficient;
phi2 = randomGenerator->GetVariateWithClosedRange() * this->m_GlobalCoefficient;
for (k = 0; k < n; k++)
{ // update velocity
p.m_CurrentVelocity[k] = m_InertiaCoefficient * p.m_CurrentVelocity[k] +
phi1 * (p.m_BestParameters[k] - p.m_CurrentParameters[k]) +
phi2 * (m_ParametersBestValue[k] - p.m_CurrentParameters[k]);
// update location and ensure that it stays
// inside the feasible region
p.m_CurrentParameters[k] += p.m_CurrentVelocity[k];
if (p.m_CurrentParameters[k] < m_ParameterBounds[k].first)
{
p.m_CurrentParameters[k] = m_ParameterBounds[k].first;
}
else if (p.m_CurrentParameters[k] > m_ParameterBounds[k].second)
{
p.m_CurrentParameters[k] = m_ParameterBounds[k].second;
}
} // evaluate function at new position
p.m_CurrentValue = m_CostFunction->GetValue(p.m_CurrentParameters);
if (p.m_CurrentValue < p.m_BestValue)
{
p.m_BestValue = p.m_CurrentValue;
p.m_BestParameters = p.m_CurrentParameters;
}
}
}
} // namespace itk
|
;my stackoverflow answer_link : https://stackoverflow.com/a/67801034/13939591
;Day 35 date-02 June,2021
;problem - convert lower case letter to upper case letter or upper case letter to lower case letter
; - without using subtraction , addition (using just bit manipulation)
; Here at first, @ indicating start of label and $ indicating start of procedure.
; If multiple label and procedure is present in assembly code.
; Then distinguishing label & procedure can be done easily.
; It's just my own way of coding. You may ignore this style.
.model small ; declaring this code will be consists of one data segment and one code segment
.stack 100h ; stack is initializeed to offset address at 100h
.data ; starting of Data segment
n_line db 0ah,0dh,"$" ; for new line
input_msg db "Input",20h,": $" ; 20h = 32d = ascii 'space'
output_msg db 0ah,0dh,"Output: $"
stop_msg db "Press 'esc' to Stop this Programme.",0ah,0dh,"$"
end_msg db 0ah,0dh,"Proramme Terminated. $"
warning_msg db 0ah,0dh,"Input is not a letter. Try agian.",0ah,0dh,"$"
.code ; starting of Code segment
main proc
mov ax,@data ; copying starting address of data segment into ax register
mov ds,ax ; by copying ax into ds we are initializing data segment
lea dx,stop_msg
mov ah,9
int 21h
@input:
mov cx,0
lea dx,input_msg
mov ah,9
int 21h
mov ah,1 ; taking single input charachter
int 21h
cmp al,27d ; cheking if it input is 'esc' or not
je @terminate
call $check_constraints ; procedure
cmp cx,1 ; cheking flag value
je @input
xor bx,bx ; XOR with self will always retun of all zero bit (means clearing a register)
mov bl,al
xor bl,32d ; Here is the trick
; visit - https://catonmat.net/ascii-case-conversion-trick
@output:
lea dx,output_msg
mov ah,9
int 21h
mov dl,bl ; output char was stored in bl
mov ah,2
int 21h
lea dx,n_line ; new line for next input
mov ah,9
int 21h
jmp @input
@terminate:
lea dx,end_msg
mov ah,9
int 21h
mov ah,4ch ; terminate program
int 21h
main endp ; ending of main procedure
$check_constraints proc
; if( (input<= 122d && input <= 97d) || (input<=90d && input <= 65d)) Then Proceed; otherwise Warning;
@first_if:
cmp al,122d ; or cmp al,'z'
jg @warning
cmp al,97d ; or cmp al,'a'
jge @setFlag
@second_if:
cmp al,90d ; or cmp al,'Z'
jg @warning
cmp al,65d ; or cmp al,'A'
jl @warning
@setFlag:
mov cx,0 ; i'm considering cx register as a flag
jmp @end_function
@warning:
mov cx,1 ; i'm considering cx register as a flag
lea dx,warning_msg
mov ah,9
int 21h
@end_function:
ret
$check_constraints endp
end main ; ending of code segment
|
; A282232: a(n) = ((3*n + 1)^6 - 1)/9.
; 0,455,13072,111111,536312,1864135,5227320,12597767,27126736,53543367,98611520,171644935,285080712,455111111,702373672,1052699655,1537920800,2196734407,3075626736,4229854727,5724486040,7635497415,10050931352,13072111111,16814914032,21411103175,27009717280
mul $0,3
add $0,1
pow $0,6
div $0,9
|
; A054586: Sum_{d|2n+1} phi(d)*mu(d).
; 1,-1,-3,-5,-1,-9,-11,3,-15,-17,5,-21,-3,-1,-27,-29,9,15,-35,11,-39,-41,3,-45,-5,15,-51,27,17,-57,-59,5,33,-65,21,-69,-71,3,45,-77,-1,-81,45,27,-87,55,29,51,-95,9,-99,-101,-15,-105,-107,35,-111,63,11,75,-9
mul $0,2
seq $0,276833 ; Sum of mu(d)*phi(d) over divisors d of n.
|
; A047586: Numbers that are congruent to {2, 3, 5, 6, 7} mod 8.
; 2,3,5,6,7,10,11,13,14,15,18,19,21,22,23,26,27,29,30,31,34,35,37,38,39,42,43,45,46,47,50,51,53,54,55,58,59,61,62,63,66,67,69,70,71,74,75,77,78,79,82,83,85,86,87,90,91,93,94,95,98,99,101,102,103
mov $1,$0
add $0,1
lpb $0,1
sub $0,1
trn $0,1
add $3,$1
add $1,1
add $1,$0
trn $2,$3
add $2,1
trn $0,$2
sub $1,$0
trn $0,2
add $1,1
lpe
|
momitem: MACRO
; money to trigger, cost, kind, item
dt \1
dt \2
db \3, \4
ENDM
MomItems_1:
momitem 0, 600, MOM_ITEM, SUPER_POTION
momitem 0, 90, MOM_ITEM, ANTIDOTE
momitem 0, 180, MOM_ITEM, POKE_BALL
momitem 0, 450, MOM_ITEM, ESCAPE_ROPE
momitem 0, 500, MOM_ITEM, GREAT_BALL
.End
MomItems_2:
momitem 900, 600, MOM_ITEM, SUPER_POTION
momitem 4000, 270, MOM_ITEM, REPEL
momitem 7000, 600, MOM_ITEM, SUPER_POTION
momitem 10000, 1800, MOM_DOLL, DECO_CHARMANDER_DOLL
momitem 15000, 3000, MOM_ITEM, MOON_STONE
momitem 19000, 600, MOM_ITEM, SUPER_POTION
momitem 30000, 4800, MOM_DOLL, DECO_CLEFAIRY_DOLL
momitem 40000, 900, MOM_ITEM, HYPER_POTION
momitem 50000, 8000, MOM_DOLL, DECO_PIKACHU_DOLL
momitem 100000, 22800, MOM_DOLL, DECO_BIG_SNORLAX_DOLL
.End
|
; $Id: bs3-mode-SwitchToPP16_32.asm $
;; @file
; BS3Kit - Bs3SwitchToPP16_32
;
;
; Copyright (C) 2007-2017 Oracle Corporation
;
; This file is part of VirtualBox Open Source Edition (OSE), as
; available from http://www.virtualbox.org. This file is free software;
; you can redistribute it and/or modify it under the terms of the GNU
; General Public License (GPL) as published by the Free Software
; Foundation, in version 2 as it comes in the "COPYING" file of the
; VirtualBox OSE distribution. VirtualBox OSE is distributed in the
; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
;
; The contents of this file may alternatively be used under the terms
; of the Common Development and Distribution License Version 1.0
; (CDDL) only, as it comes in the "COPYING.CDDL" file of the
; VirtualBox OSE distribution, in which case the provisions of the
; CDDL are applicable instead of those of the GPL.
;
; You may elect to license modified versions of this file under the
; terms and conditions of either the GPL or the CDDL or both.
;
%include "bs3kit-template-header.mac"
;;
; Switch to 32-bit code under 16-bit paged protected mode sys/tss from any other mode.
;
; @cproto BS3_DECL(void) Bs3SwitchToPP16_32(void);
;
; @uses Nothing (except high 32-bit register parts).
;
; @remarks Obviously returns to 32-bit mode, even if the caller was
; in 16-bit or 64-bit mode.
;
; @remarks Does not require 20h of parameter scratch space in 64-bit mode.
;
BS3_GLOBAL_NAME_EX TMPL_NM(Bs3SwitchToPP16_32_Safe), function, 0
BS3_PROC_BEGIN_MODE Bs3SwitchToPP16_32, BS3_PBC_NEAR
%ifdef TMPL_PP16_32
ret
%else
;
; Make sure we're in the 16-bit segment and then call Bs3SwitchToPP16.
;
%if TMPL_BITS != 16
jmp .sixteen_bit_segment
BS3_BEGIN_TEXT16
BS3_SET_BITS TMPL_BITS
BS3_GLOBAL_LOCAL_LABEL .sixteen_bit_segment
%endif
extern TMPL_NM(Bs3SwitchToPP16)
call TMPL_NM(Bs3SwitchToPP16)
BS3_SET_BITS 16
;
; Switch to 32-bit mode.
;
extern _Bs3SwitchTo32Bit_c16
%if TMPL_BITS == 16
jmp _Bs3SwitchTo32Bit_c16
%else
call _Bs3SwitchTo32Bit_c16
BS3_SET_BITS 32
%if TMPL_BITS == 32
ret
%else
ret 4 ; Return and pop 4 bytes of "parameters" (unused return address).
%endif
%endif
%endif
BS3_PROC_END_MODE Bs3SwitchToPP16_32
%if TMPL_BITS == 16
;;
; Custom far stub.
BS3_BEGIN_TEXT16_FARSTUBS
BS3_PROC_BEGIN_MODE Bs3SwitchToPP16_32, BS3_PBC_FAR
inc bp
push bp
mov bp, sp
; Call the real thing.
call TMPL_NM(Bs3SwitchToPP16_32)
BS3_SET_BITS 32
; Jmp to common code for the tedious conversion.
%if BS3_MODE_IS_RM_OR_V86(TMPL_MODE)
extern _Bs3SwitchHlpConvRealModeRetfPopBpDecBpAndReturn_c32
jmp _Bs3SwitchHlpConvRealModeRetfPopBpDecBpAndReturn_c32
%else
extern _Bs3SwitchHlpConvProtModeRetfPopBpDecBpAndReturn_c32
jmp _Bs3SwitchHlpConvProtModeRetfPopBpDecBpAndReturn_c32
%endif
BS3_SET_BITS 16
BS3_PROC_END_MODE Bs3SwitchToPP16_32
%endif
|
; A201279: a(n) = 6n^2 + 10n + 5.
; 5,21,49,89,141,205,281,369,469,581,705,841,989,1149,1321,1505,1701,1909,2129,2361,2605,2861,3129,3409,3701,4005,4321,4649,4989,5341,5705,6081,6469,6869,7281,7705,8141,8589,9049,9521,10005,10501,11009,11529,12061,12605,13161,13729,14309,14901,15505,16121,16749,17389,18041,18705,19381,20069,20769,21481,22205,22941,23689,24449,25221,26005,26801,27609,28429,29261,30105,30961,31829,32709,33601,34505,35421,36349,37289,38241,39205,40181,41169,42169,43181,44205,45241,46289,47349,48421,49505,50601,51709,52829,53961,55105,56261,57429,58609,59801,61005,62221,63449,64689,65941,67205,68481,69769,71069,72381,73705,75041,76389,77749,79121,80505,81901,83309,84729,86161,87605,89061,90529,92009,93501,95005,96521,98049,99589,101141,102705,104281,105869,107469,109081,110705,112341,113989,115649,117321,119005,120701,122409,124129,125861,127605,129361,131129,132909,134701,136505,138321,140149,141989,143841,145705,147581,149469,151369,153281,155205,157141,159089,161049,163021,165005,167001,169009,171029,173061,175105,177161,179229,181309,183401,185505,187621,189749,191889,194041,196205,198381,200569,202769,204981,207205,209441,211689,213949,216221,218505,220801,223109,225429,227761,230105,232461,234829,237209,239601,242005,244421,246849,249289,251741,254205,256681,259169,261669,264181,266705,269241,271789,274349,276921,279505,282101,284709,287329,289961,292605,295261,297929,300609,303301,306005,308721,311449,314189,316941,319705,322481,325269,328069,330881,333705,336541,339389,342249,345121,348005,350901,353809,356729,359661,362605,365561,368529,371509,374501
mov $1,6
mul $1,$0
add $1,10
mul $1,$0
add $1,5
|
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
#include <cstring>
#include <iostream>
#include "faodel-common/Debug.hh"
#include "SerdesParticleBundleObject.hh"
using namespace std;
SerdesParticleBundleObject::SerdesParticleBundleObject(
JobSerdes::params_t params,
std::function<int ()> f_prng) {
px.resize(params.num_items);
py.resize(params.num_items);
pz.resize(params.num_items);
vx.resize(params.num_items);
vy.resize(params.num_items);
vz.resize(params.num_items);
val1.resize(params.num_items);
val2.resize(params.num_items);
for(int i=0; i<params.num_items; i++) {
px[i]=(double)(i+10000); py[i]=(double)(i+20000); pz[i]=(double)(i+30000);
vx[i]=(double)(i+40000); vy[i]=(double)(i+50000); vz[i]=(double)(i+60000);
val1[i]=70000+i;
val2[i]=80000+1;
}
}
lunasa::DataObject SerdesParticleBundleObject::pup() const {
//Name for each component
vector<string> names = {"px","py","pz", "vx","vy","vz", "val1", "val2"};
//Pointers to each component
vector<const void *> ptrs = {
px.data(), py.data(), pz.data(),
vx.data(), vy.data(), vz.data(),
val1.data(), val2.data()
};
//Bytes for each component
size_t dvec_bytes = px.size() * sizeof(double);
vector<size_t> bytes = {
dvec_bytes, dvec_bytes, dvec_bytes,
dvec_bytes, dvec_bytes, dvec_bytes,
val1.size() * sizeof(uint32_t), val2.size() * sizeof(uint32_t)
};
//We can use whatever label we want here.
const uint8_t T_CHAR = 1;
const uint8_t T_INT =2;
const uint8_t T_FLOAT = 3;
const uint8_t T_DOUBLE = 4;
//Types for each component
vector<uint8_t> types = {
T_DOUBLE, T_DOUBLE, T_DOUBLE,
T_DOUBLE, T_DOUBLE, T_DOUBLE,
T_INT, T_INT
};
lunasa::DataObjectPacker packer(names, ptrs, bytes, types,
faodel::const_hash32("ParticleBundle"));
return packer.GetDataObject();
}
void SerdesParticleBundleObject::pup(const lunasa::DataObject &ldo) {
lunasa::DataObjectPacker u(ldo);
void *ptr; size_t bytes; uint8_t type;
if(!u.VerifyDataType(faodel::const_hash32("ParticleBundle"))) {
F_ASSERT(0, "Packed DataObject did not match the expected hash");
}
int rc=0;
//Dangerous if anything goes wrong, but should be fairly fast
rc|=u.GetVarPointer("px", &ptr, &bytes, &type); px.resize(bytes/sizeof(double)); std::memcpy(&px[0], ptr, bytes);
rc|=u.GetVarPointer("py", &ptr, &bytes, &type); py.resize(bytes/sizeof(double)); std::memcpy(&py[0], ptr, bytes);
rc|=u.GetVarPointer("pz", &ptr, &bytes, &type); pz.resize(bytes/sizeof(double)); std::memcpy(&pz[0], ptr, bytes);
rc|=u.GetVarPointer("vx", &ptr, &bytes, &type); vx.resize(bytes/sizeof(double)); std::memcpy(&vx[0], ptr, bytes);
rc|=u.GetVarPointer("vy", &ptr, &bytes, &type); vy.resize(bytes/sizeof(double)); std::memcpy(&vy[0], ptr, bytes);
rc|=u.GetVarPointer("vz", &ptr, &bytes, &type); vz.resize(bytes/sizeof(double)); std::memcpy(&vz[0], ptr, bytes);
rc|=u.GetVarPointer("val1", &ptr, &bytes, &type); val1.resize(bytes/sizeof(uint32_t)); std::memcpy(&val1[0], ptr, bytes);
rc|=u.GetVarPointer("val2", &ptr, &bytes, &type); val2.resize(bytes/sizeof(uint32_t)); std::memcpy(&val2[0], ptr, bytes);
if(rc!=0){ std::cerr<<"SerdesParticleBundleObject::pup detected an error\n"; }
} |
; Assembly for keyscan-native.bas
; compiled with mcbasic -native
; Equates for MC-10 MICROCOLOR BASIC 1.0
;
; Direct page equates
DP_LNUM .equ $E2 ; current line in BASIC
DP_TABW .equ $E4 ; current tab width on console
DP_LPOS .equ $E6 ; current line position on console
DP_LWID .equ $E7 ; current line width of console
;
; Memory equates
M_KBUF .equ $4231 ; keystrobe buffer (8 bytes)
M_PMSK .equ $423C ; pixel mask for SET, RESET and POINT
M_IKEY .equ $427F ; key code for INKEY$
M_CRSR .equ $4280 ; cursor location
M_LBUF .equ $42B2 ; line input buffer (130 chars)
M_MSTR .equ $4334 ; buffer for small string moves
M_CODE .equ $4346 ; start of program space
;
; ROM equates
R_BKMSG .equ $E1C1 ; 'BREAK' string location
R_ERROR .equ $E238 ; generate error and restore direct mode
R_BREAK .equ $E266 ; generate break and restore direct mode
R_RESET .equ $E3EE ; setup stack and disable CONT
R_SPACE .equ $E7B9 ; emit " " to console
R_QUEST .equ $E7BC ; emit "?" to console
R_REDO .equ $E7C1 ; emit "?REDO" to console
R_EXTRA .equ $E8AB ; emit "?EXTRA IGNORED" to console
R_DMODE .equ $F7AA ; display OK prompt and restore direct mode
R_KPOLL .equ $F879 ; if key is down, do KEYIN, else set Z CCR flag
R_KEYIN .equ $F883 ; poll key for key-down transition set Z otherwise
R_PUTC .equ $F9C9 ; write ACCA to console
R_MKTAB .equ $FA7B ; setup tabs for console
R_GETLN .equ $FAA4 ; get line, returning with X pointing to M_BUF-1
R_SETPX .equ $FB44 ; write pixel character to X
R_CLRPX .equ $FB59 ; clear pixel character in X
R_MSKPX .equ $FB7C ; get pixel screen location X and mask in R_PMSK
R_CLSN .equ $FBC4 ; clear screen with color code in ACCB
R_CLS .equ $FBD4 ; clear screen with space character
R_SOUND .equ $FFAB ; play sound with pitch in ACCA and duration in ACCB
R_MCXID .equ $FFDA ; ID location for MCX BASIC
; direct page registers
.org $80
strtcnt .block 1
strbuf .block 2
strend .block 2
strfree .block 2
strstop .block 2
dataptr .block 2
inptptr .block 2
redoptr .block 2
letptr .block 2
.org $a3
r1 .block 5
r2 .block 5
rend
rvseed .block 2
tmp1 .block 2
tmp2 .block 2
tmp3 .block 2
tmp4 .block 2
tmp5 .block 2
argv .block 10
; main program
.org M_CODE
jsr progbegin
jsr clear
LINE_10
; POKE 16925,0
ldab #0
jsr ld_ir1_pb
ldd #16925
jsr poke_pw_ir1
; POKE 16926,1
ldab #1
jsr ld_ir1_pb
ldd #16926
jsr poke_pw_ir1
; REM MAKE IT SNAPPY
LINE_20
; MC=16384
ldx #INTVAR_MC
ldd #16384
jsr ld_ix_pw
; KS=16945
ldx #INTVAR_KS
ldd #16945
jsr ld_ix_pw
LINE_30
; FOR I=0 TO 7
ldx #INTVAR_I
ldab #0
jsr for_ix_pb
ldab #7
jsr to_ip_pb
; POKE MC+I,PEEK(KS+I)
ldx #INTVAR_MC
jsr ld_ir1_ix
ldx #INTVAR_I
jsr add_ir1_ir1_ix
ldx #INTVAR_KS
jsr ld_ir2_ix
ldx #INTVAR_I
jsr add_ir2_ir2_ix
jsr peek_ir2_ir2
jsr poke_ir1_ir2
; NEXT
jsr next
LINE_40
; POKE 2,254
ldab #254
jsr ld_ir1_pb
ldab #2
jsr poke_pb_ir1
; POKE 16393,PEEK(3)
ldab #3
jsr peek_ir1_pb
ldd #16393
jsr poke_pw_ir1
; REM CONTROL
LINE_50
; POKE 2,251
ldab #251
jsr ld_ir1_pb
ldab #2
jsr poke_pb_ir1
; POKE 16394,PEEK(3)
ldab #3
jsr peek_ir1_pb
ldd #16394
jsr poke_pw_ir1
; REM BREAK
LINE_60
; POKE 2,127
ldab #127
jsr ld_ir1_pb
ldab #2
jsr poke_pb_ir1
; POKE 16395,PEEK(3)
ldab #3
jsr peek_ir1_pb
ldd #16395
jsr poke_pw_ir1
; REM SHIFT
LINE_70
; KY$=INKEY$
jsr inkey_sr1
ldx #STRVAR_KY
jsr ld_sx_sr1
; REM NEEDED FOR COMPILER ONLY
LINE_80
; GOTO 30
ldx #LINE_30
jsr goto_ix
LLAST
; END
jsr progend
.module mdalloc
; alloc D bytes in array memory.
; then relink strings.
alloc
std tmp1
ldx strfree
addd strfree
std strfree
ldd strend
addd tmp1
std strend
sts tmp2
subd tmp2
blo _ok
ldab #OM_ERROR
jmp error
_ok
lds strfree
des
_again
dex
dex
ldd ,x
pshb
psha
cpx strbuf
bhi _again
lds tmp2
ldx strbuf
ldd strbuf
addd tmp1
std strbuf
clra
_nxtz
staa ,x
inx
cpx strbuf
blo _nxtz
ldx strbuf
; relink permanent strings
; ENTRY: X points to offending link word in strbuf
; EXIT: X points to strend
strlink
cpx strend
bhs _rts
stx tmp1
ldd tmp1
addd #2
ldx ,x
std 1,x
ldab 0,x
ldx 1,x
abx
bra strlink
_rts
rts
.module mdpeek
; perform PEEK(X), emulating keypolling
; ENTRY: X holds storage byte
; EXIT: ACCB holds peeked byte
peek
cpx #M_KBUF
blo _peek
cpx #M_IKEY
bhi _peek
beq _poll
cpx #M_KBUF+7
bhi _peek
_poll
jsr R_KPOLL
beq _peek
staa M_IKEY
_peek
ldab ,x
rts
.module mdprint
print
_loop
ldaa ,x
jsr R_PUTC
inx
decb
bne _loop
rts
.module mdstrdel
; remove a permanent string
; then re-link trailing strings
strdel
ldd 1,x
subd strbuf
blo _rts
ldd 1,x
subd strend
bhs _rts
ldd strend
subd #2
subb 0,x
sbca #0
std strend
ldab 0,x
ldx 1,x
dex
dex
stx tmp1
abx
inx
inx
sts tmp2
txs
ldx tmp1
_nxtwrd
pula
pulb
std ,x
inx
inx
cpx strend
blo _nxtwrd
lds tmp2
ldx tmp1
jmp strlink
_rts
rts
.module mdstrprm
; make a permanent string
; ENTRY: argv - input string descriptor
; X - output string descriptor
strprm
stx tmp1
ldab 0+argv
beq _null
decb
beq _char
ldx 1+argv
cpx #M_LBUF
blo _const
cpx #M_MSTR
blo _trans
cpx strbuf
blo _const
_trans
ldx tmp1
ldab 0,x
ldx 1,x
cpx strbuf
blo _nalloc
cmpb 0+argv
beq _copyip
_nalloc
cpx 1+argv
bhs _notmp
ldx 1+argv
cpx strend
bhs _notmp
ldx strend
inx
inx
stx strfree
bsr _copy
ldd strfree
std 1+argv
_notmp
ldx tmp1
pshx
jsr strdel
pulx
stx tmp1
ldx strend
ldd tmp1
std ,x
inx
inx
stx strfree
cpx argv+1
beq _nocopy
bsr _copy
bra _ready
_nocopy
ldab 0+argv
abx
_ready
stx strend
ldd strfree
inx
inx
stx strfree
clr strtcnt
ldx tmp1
std 1,x
ldab 0+argv
stab 0,x
rts
_char
ldaa #1
ldx 1+argv
ldab ,x
_null
ldaa #1
std 1+argv
_const
ldx tmp1
pshx
jsr strdel
pulx
ldab 0+argv
stab 0,x
ldd 1+argv
std 1,x
clr strtcnt
rts
_copyip
dex
dex
ldd tmp1
std ,x
inx
inx
_copy
sts tmp2
ldab 0+argv
lds 1+argv
des
_nxtchr
pula
staa ,x
inx
decb
bne _nxtchr
lds tmp2
clr strtcnt
rts
.module mdtonat
; push for-loop record on stack
; ENTRY: ACCB contains size of record
; r1 contains stopping variable
; and is always fixedpoint.
; r1+3 must contain zero if an integer.
to
clra
std tmp3
pulx
stx tmp1
tsx
clrb
_nxtfor
abx
ldd 1,x
subd letptr
beq _oldfor
ldab ,x
cmpb #3
bhi _nxtfor
sts tmp2
ldd tmp2
subd tmp3
std tmp2
lds tmp2
tsx
ldab tmp3+1
stab 0,x
ldd letptr
std 1,x
_oldfor
ldd tmp1
std 3,x
ldab r1
stab 5,x
ldd r1+1
std 6,x
ldd r1+3
std 8,x
ldab tmp3+1
cmpb #15
beq _flt
inca
staa 10,x
bra _done
_flt
ldd #0
std 10,x
std 13,x
inca
staa 12,x
_done
ldx tmp1
jmp ,x
add_ir1_ir1_ix ; numCalls = 1
.module modadd_ir1_ir1_ix
ldd r1+1
addd 1,x
std r1+1
ldab r1
adcb 0,x
stab r1
rts
add_ir2_ir2_ix ; numCalls = 1
.module modadd_ir2_ir2_ix
ldd r2+1
addd 1,x
std r2+1
ldab r2
adcb 0,x
stab r2
rts
clear ; numCalls = 1
.module modclear
clra
ldx #bss
bra _start
_again
staa ,x
inx
_start
cpx #bes
bne _again
stx strbuf
stx strend
inx
inx
stx strfree
ldx #$8FFF
stx strstop
ldx #startdata
stx dataptr
rts
for_ix_pb ; numCalls = 1
.module modfor_ix_pb
stx letptr
clra
staa 0,x
std 1,x
rts
goto_ix ; numCalls = 1
.module modgoto_ix
ins
ins
jmp ,x
inkey_sr1 ; numCalls = 1
.module modinkey_sr1
ldd #$0101
std r1
ldaa M_IKEY
bne _gotkey
jsr R_KEYIN
_gotkey
clr M_IKEY
staa r1+2
bne _rts
staa r1
_rts
rts
ld_ir1_ix ; numCalls = 1
.module modld_ir1_ix
ldd 1,x
std r1+1
ldab 0,x
stab r1
rts
ld_ir1_pb ; numCalls = 5
.module modld_ir1_pb
stab r1+2
ldd #0
std r1
rts
ld_ir2_ix ; numCalls = 1
.module modld_ir2_ix
ldd 1,x
std r2+1
ldab 0,x
stab r2
rts
ld_ix_pw ; numCalls = 2
.module modld_ix_pw
std 1,x
ldab #0
stab 0,x
rts
ld_sx_sr1 ; numCalls = 1
.module modld_sx_sr1
ldab r1
stab 0+argv
ldd r1+1
std 1+argv
jmp strprm
next ; numCalls = 1
.module modnext
pulx
stx tmp1
tsx
ldab ,x
cmpb #3
bhi _ok
ldab #NF_ERROR
jmp error
_ok
cmpb #11
bne _flt
ldd 9,x
std r1+1
ldab 8,x
stab r1
ldx 1,x
ldd r1+1
addd 1,x
std r1+1
std 1,x
ldab r1
adcb ,x
stab r1
stab ,x
tsx
tst 8,x
bpl _iopp
ldd r1+1
subd 6,x
ldab r1
sbcb 5,x
blt _idone
ldx 3,x
jmp ,x
_iopp
ldd 6,x
subd r1+1
ldab 5,x
sbcb r1
blt _idone
ldx 3,x
jmp ,x
_idone
ldab #11
bra _done
_flt
ldd 13,x
std r1+3
ldd 11,x
std r1+1
ldab 10,x
stab r1
ldx 1,x
ldd r1+3
addd 3,x
std r1+3
std 3,x
ldd 1,x
adcb r1+2
adca r1+1
std r1+1
std 1,x
ldab r1
adcb ,x
stab r1
stab ,x
tsx
tst 10,x
bpl _fopp
ldd r1+3
subd 8,x
ldd r1+1
sbcb 7,x
sbca 6,x
ldab r1
sbcb 5,x
blt _fdone
ldx 3,x
jmp ,x
_fopp
ldd 8,x
subd r1+3
ldd 6,x
sbcb r1+2
sbca r1+1
ldab 5,x
sbcb r1
blt _fdone
ldx 3,x
jmp ,x
_fdone
ldab #15
_done
abx
txs
ldx tmp1
jmp ,x
peek_ir1_pb ; numCalls = 3
.module modpeek_ir1_pb
clra
std tmp1
ldx tmp1
ldab ,x
stab r1+2
ldd #0
std r1
rts
peek_ir2_ir2 ; numCalls = 1
.module modpeek_ir2_ir2
ldx r2+1
jsr peek
stab r2+2
ldd #0
std r2
rts
poke_ir1_ir2 ; numCalls = 1
.module modpoke_ir1_ir2
ldab r2+2
ldx r1+1
stab ,x
rts
poke_pb_ir1 ; numCalls = 3
.module modpoke_pb_ir1
clra
std tmp1
ldab r1+2
ldx tmp1
stab ,x
rts
poke_pw_ir1 ; numCalls = 5
.module modpoke_pw_ir1
std tmp1
ldab r1+2
ldx tmp1
stab ,x
rts
progbegin ; numCalls = 1
.module modprogbegin
ldx R_MCXID
cpx #'h'*256+'C'
bne _mcbasic
pulx
clrb
pshb
pshb
pshb
stab strtcnt
jmp ,x
_reqmsg .text "?MICROCOLOR BASIC ROM REQUIRED"
_mcbasic
ldx #_reqmsg
ldab #30
jsr print
pulx
rts
progend ; numCalls = 1
.module modprogend
pulx
pula
pula
pula
jsr R_RESET
jmp R_DMODE
NF_ERROR .equ 0
RG_ERROR .equ 4
OD_ERROR .equ 6
FC_ERROR .equ 8
OV_ERROR .equ 10
OM_ERROR .equ 12
BS_ERROR .equ 16
DD_ERROR .equ 18
LS_ERROR .equ 28
error
jmp R_ERROR
to_ip_pb ; numCalls = 1
.module modto_ip_pb
stab r1+2
ldd #0
std r1
std r1+3
ldab #11
jmp to
; data table
startdata
enddata
; block started by symbol
bss
; Numeric Variables
INTVAR_I .block 3
INTVAR_KS .block 3
INTVAR_MC .block 3
; String Variables
STRVAR_KY .block 3
; Numeric Arrays
; String Arrays
; block ended by symbol
bes
.end
|
icl '../../os/symbols.asm'
;
; MUSIC init & play
; example by Raster/C.P.U., 2003-2004
;
icl "rmtplayr.asm" ;include RMT player routine
MODUL equ $4000 ;address of RMT module
VLINE equ 16 ;screen line for synchronization
org BOOTADDR
start
lda #1
sta ROS7
lda #1
ldx #OS_SET_VIDEO_MODE
jsr OS_CALL
lda #$12
sta ATTRIB_DEFAULT
ldx #OS_ATTRIB_CLEAR
jsr OS_CALL
mwa #custom_palette SRC_ADDR
ldx #OS_SET_VIDEO_PALETTE
jsr OS_CALL
jsr display_credits
; paint Song Info area
mva #0 screen_margin_left
mva #40 screen_margin_right
mva #19 screen_margin_top
mva #24 screen_margin_bottom
lda #$34
jsr screen_fill_attrib
; paint Credits Info area
mva #25 screen_margin_left
mva #40 screen_margin_right
mva #0 screen_margin_top
mva #19 screen_margin_bottom
lda #$56
jsr screen_fill_attrib
jsr list_files
jsr display_files
jsr update_selected_line
loop
lda is_playing
beq skip_player
acpapx1 lda #$ff ;parameter overwrite (sync line counter value)
clc
acpapx2 adc #$ff ;parameter overwrite (sync line counter spacing)
cmp #156
bcc lop4
sbc #156
lop4
sta acpapx1+1
waipap
cmp VCOUNT ;vertical line counter synchro
bne waipap
lda #8
sta VBORDER
jsr RASTERMUSICTRACKER+3 ;1 play
lda #0
sta VBORDER
skip_player:
jsr process_keyboard
jmp loop
stop_player:
jmp RASTERMUSICTRACKER+9
tabpp dta 156,78,52,39 ;line counter spacing table for instrument speed from 1 to 4
.proc start_song
jsr stop_player
jsr clear_song_info
ldx #12
ldy #21
mwa #label_loading SRC_ADDR
jsr screen_print_at
clc
lda selected_line
adc files_offset
tax
jsr file_name_get
jsr load_song
; print song name at position 1, 22 with margins (1, 20) - (39, 22)
jsr clear_song_info
ldx #1
ldy #20
mwa #label_song SRC_ADDR
jsr screen_print_at
ldx #7
ldy #20
mwa song_text SRC_ADDR
jsr screen_print_at
ldx #<MODUL ;low byte of RMT module to X reg
ldy #>MODUL ;hi byte of RMT module to Y reg
lda #0 ;starting song line 0-255 to A reg
jsr RASTERMUSICTRACKER ;Init
;Init returns instrument speed (1..4 => from 1/screen to 4/screen)
tay
lda tabpp-1,y
sta acpapx2+1 ;sync counter spacing
lda #16+0
sta acpapx1+1 ;sync counter init
; Display MONO / STEREO label
mwa #label_mono SRC_ADDR
lda v_tracks
cmp #4
seq
mwa #label_stereo SRC_ADDR
ldx #1
ldy #22
jsr screen_position
jsr screen_print
setup_stereo_pokey:
lda v_tracks
cmp #4
beq set_pokey_mono
lda #$55
sta POKEY0_PANCTL
lda #$AA
sta POKEY1_PANCTL
jmp set_pokey_done
set_pokey_mono:
lda #$FF
sta POKEY0_PANCTL
lda #$00
sta POKEY1_PANCTL
set_pokey_done:
lda #1
sta is_playing
rts
.endp
.proc clear_song_info
lda #1
sta screen_margin_left
lda #39
sta screen_margin_right
lda #20
sta screen_margin_top
lda #24
sta screen_margin_bottom
jmp screen_clear
.endp
.proc process_keyboard
jsr keyb_read
cmp last_key
beq process_end
sta last_key
cmp #16
jeq key_up
cmp #17
jeq key_down
cmp #46
jeq key_enter
process_end:
rts
key_up:
lda selected_line
cmp #0
bne line_up
lda files_offset
beq process_end
jsr files_scroll_down
dec files_offset
ldx #1
ldy #1
jsr screen_position
ldx files_offset
jmp files_print_one
line_up
dec selected_line
jmp update_selected_line
key_down:
clc
lda selected_line
adc files_offset
adc #1
cmp files_read
beq process_end
lda selected_line
cmp #16
bne line_down
jsr files_scroll_up
inc files_offset
ldx #1
ldy #17
jsr screen_position
clc
lda files_offset
adc selected_line
tax
jsr files_print_one
jmp update_selected_line
line_down
inc selected_line
jmp update_selected_line
key_enter:
clc
lda files_offset
adc selected_line
tax
lda DIR_ENTRIES_TYPES,x
cmp #ST_TYPE_FILE
jeq start_song
txa
pha
lda #0
sta files_offset
sta selected_line
jsr update_selected_line
jsr files_display_clear
pla
tax
jsr files_change_folder
jsr list_files
jmp display_files
last_key .byte 0
.endp
.proc display_credits
next_info_string
lda info_string_ndx
asl
tax
mwa player_info_strings,x SRC_ADDR
lda SRC_ADDR
ora SRC_ADDR+1
sne
rts
ldx info_string_ndx
lda player_info_pos_y, x
tay
lda player_info_pos_x, x
tax
jsr screen_print_at
inc info_string_ndx
jmp next_info_string
info_string_ndx .byte 0
.endp
.proc update_selected_line
lda selected_line
jmp display_file_row
.endp
files_offset .byte 0
selected_line .byte 0
song_text:
.word 0
is_playing: .byte 0
label_song: .by 'SONG: ', 0
label_stereo: .by 'TYPE: STEREO', 0
label_mono: .by 'TYPE: MONO ', 0
label_loading .by 'Loading song...', 0
player_info_0 .by 'RMT player by', 0
player_info_1 .by 'Radek Sterba', 0
player_info_2 .by 'Raster/C.P.U.', 0
player_info_3 .by 'CLC88 port by', 0
player_info_4 .by 'Franco Catrin', 0
player_info_strings .word player_info_0, player_info_1, player_info_2, player_info_3, player_info_4, 0
player_info_pos_x .byte 26, 26, 26, 26, 26
player_info_pos_y .byte 6, 7, 8, 10, 11
custom_palette
.word $0000 ; border default
.word $2AAE ; file list background
.word $CE59 ; file list text
.word $1189 ; song info background
.word $ffff ; song info text
.word $0107 ; credits background
.word $EDE6 ; credits text
.word $FE25 ; highlight text
.word $640D ; player bars
custom_subpal
.byte 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
icl 'files.asm'
icl 'loader.asm'
icl '../../os/stdlib.asm'
|
#line 1 "P:/Google/Universidad/2018_II/Microprocesamiento/Tercer Seguimiento/Rbot-explorer/PIC/RbotController/RbotController.c"
#line 15 "P:/Google/Universidad/2018_II/Microprocesamiento/Tercer Seguimiento/Rbot-explorer/PIC/RbotController/RbotController.c"
void servo();
void setup();
void motion();
void gira(unsigned long grados);
void VDelay_us(unsigned time_us);
int pos=0;
unsigned int a;
char CW = 1 ;
void main(){
setup();
while(1){
servo();
}
}
void motion() {
switch (PORTD) {
case 0x00; :
PORTA = PORTD>>4;
break;
case ( 0x02; )
PORTA = 0x06; ;
delay_ms(20);
PORTA = 0x00; ;
break;
case ( 0x01; )
PORTA = ~0x06; ;
delay_ms(20);
PORTA = 0x00; ;
break;
}
}
void setup(){
ANSEL = 0X00;
TRISA = 0x00;
TRISD = 0XFF;
TRISB=0x00;
ANSELH=0x00;
PORTB=0x00;
PORTA = 0x00;
TRISB = 0X10;
T1CON = 0x10;
PORTA = 0x0A;
delay_ms(1000);
PORTA = 0x00;
delay_ms(20);
PORTA = ~0x0A;
delay_ms(1000);
PORTA = 0x00;
delay_ms(20);
PORTA = 0x06;
delay_ms(1000);
PORTA = 0x00;
delay_ms(20);
PORTA = ~0x06;
delay_ms(1000);
PORTA = 0x00;
delay_ms(20);
}
void servo(){
gira(pos);
if(CW){
pos+=5;
}else {
pos-=5;
}
if(pos==180){
CW = 0 ;
}
if(pos==0){
CW = 1 ;
}
}
void VDelay_us(unsigned time_us){
time_us/=16;
while(time_us--){
asm nop;
asm nop;
}
}
void gira(unsigned long grados){
int i,valor;
valor=((grados*1600)/180)+500;
for (i=0;i<=50;i++){
PORTB.F0=1;
VDelay_us(valor);
PORTB.F0=0;
VDelay_us(5000);
}
}
|
// pointer
#include <iostream>
#include <conio.h>
using namespace std;
main()
{
int a=2;
int *pa=&a;
*pa=7;
cout<<*pa<<endl;
cout<<a<<endl;
int b=3;
const int *pb=&b;
//*pb=8; //error
pb=&a;
cout<<*pb<<endl;
int c=4;
int * const pc=&c;
*pc=9;
// pc=&b; //error
cout<<*pc<<endl;
int d=4;
const int * const pd=&d;
//*pd=9; //error
// pd=&a; //error
cout<<*pd<<endl;
getch();
}
|
#include "boost/lexical_cast.hpp"
#include "StandardSaveManager.hpp"
#include "DataContainer.hpp"
#include "DataContainerSerializeUtility.hpp"
#include "FileManipulator.hpp"
#include "LogUtility.hpp"
#include "planeta/buildin/RCsv.hpp"
namespace {
constexpr char* CommonSaveDataFileName("common_save_data");
constexpr char* UserSaveDataFileName("user_save_data");
constexpr char* SaveDataInformationFileName("save_data_info");
}
namespace plnt {
namespace private_ {
//////////////////////////////////////////////////////////////////////////
//Impl_
//////////////////////////////////////////////////////////////////////////
class StandardSaveManager::Impl_ {
public:
std::unique_ptr<util::DataContainer> common_data_;
std::unique_ptr<util::DataContainer> current_user_data_;
std::shared_ptr<FileManipulator> file_accessor_;
int current_user_data_idx_ = -1; //-1で読み込んでいない
struct SaveDataInfo {
int user_save_data_count = 0;
int user_save_data_param_count = 0;
std::vector<std::pair<int,UserDataHeader>> user_data_info; //<番号,ユーザーデータ>
};
SaveDataInfo save_data_info_;
bool LoadSaveDataInformation() {
//セーブデータ情報の読み込み
auto file = file_accessor_->LoadFile(SaveDataInformationFileName);
if (file == nullptr) {
PE_LOG_ERROR("セーブデータ情報ファイルの取得に失敗しました。");
return false;
}
//実装中
return true;
}
bool LoadCommonSaveData() {
auto file = file_accessor_->LoadFile(CommonSaveDataFileName);
if (file == nullptr) {
PE_LOG_ERROR("共通セーブデータファイルの取得に失敗しました。");
return false;
}
try {
common_data_ = std::make_unique<util::DataContainer>(std::move(util::DeserializeDataContainer(file)));
} catch (std::runtime_error&) {
PE_LOG_ERROR("共通セーブデータの読み込みに失敗しました。");
return false;
}
return true;
}
bool LoadUserSaveData(int idx) {
if (idx < 0 || save_data_info_.user_save_data_count <= idx) {
PE_LOG_ERROR("範囲外のユーザーセーブデータ番号が指定されました。(", idx, ")");
return false;
}
std::string file_name = std::string(UserSaveDataFileName) + boost::lexical_cast<std::string>(save_data_info_.user_data_info[idx].first);
auto file = file_accessor_->LoadFile(file_name);
if (file == nullptr) {
PE_LOG_ERROR("ユーザーセーブデータ", idx, "ファイルの取得に失敗しました。");
return false;
}
try {
current_user_data_ = std::make_unique<util::DataContainer>(std::move(util::DeserializeDataContainer(file)));
} catch (std::runtime_error&) {
PE_LOG_ERROR("ユーザーセーブデータ", idx, "の読み込みに失敗しました。");
return false;
}
return true;
}
bool SaveSaveDataInformation() {
if (current_user_data_ < 0 || save_data_info_.user_save_data_count <= current_user_data_idx_) {
PE_LOG_ERROR("範囲外のユーザーセーブデータ番号が指定されました。(", current_user_data_idx_, ")");
return false;
}
assert(current_user_data_ != nullptr);
auto file = util::SerializeDataContainer(*current_user_data_);
if (file == nullptr) {
PE_LOG_ERROR("ユーザーセーブデータ", current_user_data_idx_, "のファイル作成に失敗しました。");
return false;
}
if (!file_accessor_->SaveFile(std::string(UserSaveDataFileName) + boost::lexical_cast<std::string>(current_user_data_idx_), std::move(*file))) {
PE_LOG_ERROR("ユーザーセーブデータ", current_user_data_idx_, "の保存に失敗しました。");
return false;
}
return true;
}
bool SaveCommonSaveData() {
auto file = util::SerializeDataContainer(*common_data_);
if (file == nullptr) {
PE_LOG_ERROR("共通セーブデータのファイル作成に失敗しました。");
return false;
}
if (!file_accessor_->SaveFile(CommonSaveDataFileName, std::move(*file))) {
PE_LOG_ERROR("共通セーブデータの保存に失敗しました。");
return false;
}
return true;
}
bool SaveCurrentUserSaveData() {
}
};
//////////////////////////////////////////////////////////////////////////
//SaveDataManager
//////////////////////////////////////////////////////////////////////////
StandardSaveManager::StandardSaveManager() :impl_(std::make_unique<Impl_>()) {}
StandardSaveManager::~StandardSaveManager() = default;
bool StandardSaveManager::Initialize() {
assert(impl_->file_accessor_ != nullptr);
//セーブデータ情報の読み込み
//if (!impl_->LoadSaveDataInformation()) { return false; }
//共通セーブデータのロード
//if (!impl_->LoadCommonSaveData()) { return false; }
//PE_LOG_MESSAGE("セーブデータを正常に読み込みました。");
PE_LOG_WARNING("SaveDataManagerは未実装です。");
return true;
}
void StandardSaveManager::Finalize() {
//Save();
}
void StandardSaveManager::SetFileManipurator_(const std::shared_ptr<FileManipulator>& file_accessor) {
impl_->file_accessor_ = file_accessor;
}
void StandardSaveManager::Save() {
//共通データ
impl_->SaveCommonSaveData();
//ユーザーデータ
//セーブデータリスト更新
impl_->SaveSaveDataInformation();
}
bool StandardSaveManager::LoadUserData(int idx) {
return impl_->LoadUserSaveData(idx);
}
int StandardSaveManager::GetUserDataConut() const {
return impl_->save_data_info_.user_save_data_count;
}
int StandardSaveManager::GetUserDataHeaderParamCount() const {
return impl_->save_data_info_.user_save_data_param_count;
}
const util::DataContainer& StandardSaveManager::GetCommonData() const {
assert(impl_->common_data_ != nullptr);
return *impl_->common_data_;
}
util::DataContainer& StandardSaveManager::GetCommonData() {
assert(impl_->common_data_ != nullptr);
return *impl_->common_data_;
}
boost::optional<const util::DataContainer&> StandardSaveManager::GetCurrentData() const {
if (impl_->current_user_data_idx_ >= 0) {
assert(impl_->current_user_data_ != nullptr);
return boost::optional<const util::DataContainer&>(*impl_->common_data_);
} else {
return boost::optional<const util::DataContainer&>();
}
}
boost::optional<util::DataContainer&> StandardSaveManager::GetCurrentData() {
if (impl_->current_user_data_idx_ >= 0) {
assert(impl_->current_user_data_ != nullptr);
return boost::optional<util::DataContainer&>(*impl_->common_data_);
} else {
return boost::optional<util::DataContainer&>();
}
}
}
} |
#include <Rcpp.h>
using namespace Rcpp;
#include "inclusion_probabilities_rcpp.h"
//' Sverchkov and Pfeffermann \ifelse{html}{\out{π}}{\eqn{\pi}}PS bootstrap
//'
//' The function generates bootstrap samples using Sverchkov and Pfeffermann
//' (2004, p. 85) bootstrap \ifelse{html}{\out{π}}{\eqn{\pi}}PS sampling
//'
//' @param x_sample Numeric vector. Positive values of an auxiliary variable for sample elements.
//' @param pi_sample Numeric vector. Values of inclusion probabilities for sample elements.
//' @param N Integer. Population size.
//' @param n_boots Integer. A number of bootstrap samples to be generated.
//' @param scheme Function. Implementation of a sampling scheme (takes a vector of inclusion probabilities as an argument and returns a sample: a vector of 0's and 1's of the same length as argument).
//'
//' @return Integer matrix with `n_boots` rows and `length(x_sample)` columns. Each row is a bootstrap sample, and the number in i-th column denotes the number of times i-th unit from the original sample occurs in the bootstrap sample.
//'
//' @references Sverchkov M. and Pfeffermann D. (2004). Prediction of Finite Population Totals Based on the Sample Distribution, \emph{Survey Methodology}, 30(1):79-92.
//'
//' @examples
//' boot_SP_pips_rcpp(1:3, c(0.005, 0.01, 0.015), 100, 10, UPbrewer_rcpp)
//' boot_SP_pips_rcpp(1:10, (1:10) * 2e-5, 1000, 4, UPbrewer_rcpp)
//'
//' @export
// [[Rcpp::export]]
IntegerMatrix boot_SP_pips_rcpp(const NumericVector & x_sample,
const NumericVector & pi_sample,
const int & N,
const int & n_boots,
const Rcpp::Function & scheme) {
int n = x_sample.size(); // sample size
// ni = a number of repetitions in pseudo-population
// don't try to use "sample", because we need the counts
// ni <- sampling::UPmultinomial(N / sum(inv_pi_sample) * inv_pi_sample)
// Obtaining namespace of Matrix package
// Environment pkg = Environment::namespace_env("Matrix");
// Picking up Matrix() function from Matrix package
// Function rmultinom = pkg["Matrix"];
Function rmultinom("rmultinom");
IntegerMatrix ni = rmultinom(1, N, 1/pi_sample); // that's what sampling::UPmultinomial really is
int nxb = 0;
for(int i = 0; i < n; i++) {
nxb += ni(i, 0);
}
NumericVector x_b (nxb); // x values in pseudo-population
int k = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < ni(i, 0); j++) {
x_b[k++] = x_sample[i]; // replicate i-th element of x_sample ni[i] times
}
}
// inclusion probabilities for pseudo-population
NumericVector pr_b = inclusion_probabilities_rcpp(x_b, n);
IntegerMatrix M (n_boots, n); // matrix for results
for(int row = 0; row < n_boots; row++) {
IntegerVector s = scheme(pr_b);
k = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < ni[i]; j++) {
M(row, i) += s[k++]; // sum-up occurences in the sample
}
}
}
return M;
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The Helmin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "clientversion.h"
#include "init.h"
#include "main.h"
#include "masternode-sync.h"
#include "net.h"
#include "netbase.h"
#include "rpcserver.h"
#include "spork.h"
#include "timedata.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif
#include <stdint.h>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
#include <boost/assign/list_of.hpp>
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
using namespace std;
/**
* @note Do not add or change anything in the information returned by this
* method. `getinfo` exists for backwards-compatibility only. It combines
* information from wildly different sources in the program, which is a mess,
* and is thus planned to be deprecated eventually.
*
* Based on the source of the information, new information should be added to:
* - `getblockchaininfo`,
* - `getnetworkinfo` or
* - `getwalletinfo`
*
* Or alternatively, create a specific query method for the information.
**/
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.\n"
"\nResult:\n"
"{\n"
" \"version\": xxxxx, (numeric) the server version\n"
" \"protocolversion\": xxxxx, (numeric) the protocol version\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total helmin balance of the wallet\n"
" \"Darksend_balance\": xxxxxx, (numeric) the anonymized helmin balance of the wallet\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"timeoffset\": xxxxx, (numeric) the time offset\n"
" \"connections\": xxxxx, (numeric) the number of connections\n"
" \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"testnet\": true|false, (boolean) if the server is using testnet or not\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee set in helmin/kb\n"
" \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in helmin/kb\n"
" \"staking status\": true|false, (boolean) if the wallet is staking or not\n"
" \"errors\": \"...\" (string) any error messages\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getinfo", "") + HelpExampleRpc("getinfo", ""));
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("version", CLIENT_VERSION));
obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
if (!fLiteMode)
obj.push_back(Pair("Darksend_balance", ValueFromAmount(pwalletMain->GetAnonymizedBalance())));
}
#endif
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("timeoffset", GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
#endif
obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
bool nStaking = false;
if (mapHashedBlocks.count(chainActive.Tip()->nHeight))
nStaking = true;
else if (mapHashedBlocks.count(chainActive.Tip()->nHeight - 1) && nLastCoinStakeSearchInterval)
nStaking = true;
obj.push_back(Pair("staking status", (nStaking ? "Staking Active" : "Staking Not Active")));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value mnsync(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"mnsync [status|reset]\n"
"Returns the sync status or resets sync.\n");
std::string strMode = params[0].get_str();
if (strMode == "status") {
Object obj;
obj.push_back(Pair("IsBlockchainSynced", masternodeSync.IsBlockchainSynced()));
obj.push_back(Pair("lastMasternodeList", masternodeSync.lastMasternodeList));
obj.push_back(Pair("lastMasternodeWinner", masternodeSync.lastMasternodeWinner));
obj.push_back(Pair("lastBudgetItem", masternodeSync.lastBudgetItem));
obj.push_back(Pair("lastFailure", masternodeSync.lastFailure));
obj.push_back(Pair("nCountFailures", masternodeSync.nCountFailures));
obj.push_back(Pair("sumMasternodeList", masternodeSync.sumMasternodeList));
obj.push_back(Pair("sumMasternodeWinner", masternodeSync.sumMasternodeWinner));
obj.push_back(Pair("sumBudgetItemProp", masternodeSync.sumBudgetItemProp));
obj.push_back(Pair("sumBudgetItemFin", masternodeSync.sumBudgetItemFin));
obj.push_back(Pair("countMasternodeList", masternodeSync.countMasternodeList));
obj.push_back(Pair("countMasternodeWinner", masternodeSync.countMasternodeWinner));
obj.push_back(Pair("countBudgetItemProp", masternodeSync.countBudgetItemProp));
obj.push_back(Pair("countBudgetItemFin", masternodeSync.countBudgetItemFin));
obj.push_back(Pair("RequestedMasternodeAssets", masternodeSync.RequestedMasternodeAssets));
obj.push_back(Pair("RequestedMasternodeAttempt", masternodeSync.RequestedMasternodeAttempt));
return obj;
}
if (strMode == "reset") {
masternodeSync.Reset();
return "success";
}
return "failure";
}
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
private:
isminetype mine;
public:
DescribeAddressVisitor(isminetype mineIn) : mine(mineIn) {}
Object operator()(const CNoDestination& dest) const { return Object(); }
Object operator()(const CKeyID& keyID) const
{
Object obj;
CPubKey vchPubKey;
obj.push_back(Pair("isscript", false));
if (mine == ISMINE_SPENDABLE) {
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
}
return obj;
}
Object operator()(const CScriptID& scriptID) const
{
Object obj;
obj.push_back(Pair("isscript", true));
if (mine != ISMINE_NO) {
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH (const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
}
return obj;
}
};
#endif
/*
Used for updating/reading spork settings on the network
*/
Value spork(const Array& params, bool fHelp)
{
if (params.size() == 1 && params[0].get_str() == "show") {
Object ret;
for (int nSporkID = SPORK_START; nSporkID <= SPORK_END; nSporkID++) {
if (sporkManager.GetSporkNameByID(nSporkID) != "Unknown")
ret.push_back(Pair(sporkManager.GetSporkNameByID(nSporkID), GetSporkValue(nSporkID)));
}
return ret;
} else if (params.size() == 1 && params[0].get_str() == "active") {
Object ret;
for (int nSporkID = SPORK_START; nSporkID <= SPORK_END; nSporkID++) {
if (sporkManager.GetSporkNameByID(nSporkID) != "Unknown")
ret.push_back(Pair(sporkManager.GetSporkNameByID(nSporkID), IsSporkActive(nSporkID)));
}
return ret;
} else if (params.size() == 2) {
int nSporkID = sporkManager.GetSporkIDByName(params[0].get_str());
if (nSporkID == -1) {
return "Invalid spork name";
}
// SPORK VALUE
int64_t nValue = params[1].get_int();
//broadcast new spork
if (sporkManager.UpdateSpork(nSporkID, nValue)) {
ExecuteSpork(nSporkID, nValue);
return "success";
} else {
return "failure";
}
}
throw runtime_error(
"spork <name> [<value>]\n"
"<name> is the corresponding spork name, or 'show' to show all current spork settings, active to show which sporks are active"
"<value> is a epoch datetime to enable or disable spork" +
HelpRequiringPassphrase());
}
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress \"helminaddress\"\n"
"\nReturn information about the given helmin address.\n"
"\nArguments:\n"
"1. \"helminaddress\" (string, required) The helmin address to validate\n"
"\nResult:\n"
"{\n"
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
" \"address\" : \"helminaddress\", (string) The helmin address validated\n"
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
" \"isscript\" : true|false, (boolean) If the key is a script\n"
" \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
" \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
" \"account\" : \"account\" (string) The account associated with the address, \"\" is the default account\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\""));
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid) {
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
#ifdef ENABLE_WALLET
isminetype mine = pwalletMain ? IsMine(*pwalletMain, dest) : ISMINE_NO;
ret.push_back(Pair("ismine", (mine & ISMINE_SPENDABLE) ? true : false));
if (mine != ISMINE_NO) {
ret.push_back(Pair("iswatchonly", (mine & ISMINE_WATCH_ONLY) ? true : false));
Object detail = boost::apply_visitor(DescribeAddressVisitor(mine), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name));
#endif
}
return ret;
}
/**
* Used by addmultisigaddress / createmultisig:
*/
CScript _createmultisig_redeemScript(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %u keys, but need at least %d to redeem)",
keys.size(), nRequired));
if (keys.size() > 16)
throw runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number");
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++) {
const std::string& ks = keys[i].get_str();
#ifdef ENABLE_WALLET
// Case 1: HLMN address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid()) {
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key", ks));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s", ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: " + ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else
#endif
if (IsHex(ks)) {
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: " + ks);
pubkeys[i] = vchPubKey;
} else {
throw runtime_error(" Invalid public key: " + ks);
}
}
CScript result = GetScriptForMultisig(nRequired, pubkeys);
if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)
throw runtime_error(
strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE));
return result;
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2) {
string msg = "createmultisig nrequired [\"key\",...]\n"
"\nCreates a multi-signature address with n signature of m keys required.\n"
"It returns a json object with the address and redeemScript.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keys\" (string, required) A json array of keys which are helmin addresses or hex-encoded public keys\n"
" [\n"
" \"key\" (string) helmin address or hex-encoded public key\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{\n"
" \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
"}\n"
"\nExamples:\n"
"\nCreate a multisig address from 2 addresses\n" +
HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"");
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID(inner);
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage \"helminaddress\" \"signature\" \"message\"\n"
"\nVerify a signed message\n"
"\nArguments:\n"
"1. \"helminaddress\" (string, required) The helmin address to use for the signature.\n"
"2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
"3. \"message\" (string, required) The message that was signed.\n"
"\nResult:\n"
"true|false (boolean) If the signature is verified or not.\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n" +
HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n" + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
"\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
"\nAs json rpc\n" + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\""));
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
Value setmocktime(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"setmocktime timestamp\n"
"\nSet the local time to given timestamp (-regtest only)\n"
"\nArguments:\n"
"1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n"
" Pass 0 to go back to using the system time.");
if (!Params().MineBlocksOnDemand())
throw runtime_error("setmocktime for regression testing (-regtest mode) only");
RPCTypeCheck(params, boost::assign::list_of(int_type));
SetMockTime(params[0].get_int64());
return Value::null;
}
#ifdef ENABLE_WALLET
Value getstakingstatus(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakingstatus\n"
"Returns an object containing various staking information.\n"
"\nResult:\n"
"{\n"
" \"validtime\": true|false, (boolean) if the chain tip is within staking phases\n"
" \"haveconnections\": true|false, (boolean) if network connections are present\n"
" \"walletunlocked\": true|false, (boolean) if the wallet is unlocked\n"
" \"mintablecoins\": true|false, (boolean) if the wallet has mintable coins\n"
" \"enoughcoins\": true|false, (boolean) if available coins are greater than reserve balance\n"
" \"mnsync\": true|false, (boolean) if masternode data is synced\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getstakingstatus", "") + HelpExampleRpc("getstakingstatus", ""));
Object obj;
obj.push_back(Pair("validtime", chainActive.Tip()->nTime > 1471482000));
obj.push_back(Pair("haveconnections", !vNodes.empty()));
if (pwalletMain) {
obj.push_back(Pair("walletunlocked", !pwalletMain->IsLocked()));
obj.push_back(Pair("mintablecoins", pwalletMain->MintableCoins()));
obj.push_back(Pair("enoughcoins", nReserveBalance <= pwalletMain->GetBalance()));
}
obj.push_back(Pair("mnsync", masternodeSync.IsSynced()));
return obj;
}
#endif // ENABLE_WALLET
|
; Copyright © 2018, VideoLAN and dav1d authors
; Copyright © 2018, Two Orioles, LLC
; Copyright © 2018, VideoLabs
; 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.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
; ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%include "config.asm"
%include "ext/x86/x86inc.asm"
SECTION_RODATA 16
pb_right_ext_mask: times 16 db 0xff
times 16 db 0
pb_14x0_1_2: times 14 db 0
db 1, 2
pb_0_to_15_min_n: db 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 13, 13
db 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14
pb_unpcklwdw: db 0, 1, 0, 1, 4, 5, 4, 5, 8, 9, 8, 9, 12, 13, 12, 13
pb_0: times 16 db 0
pb_2: times 16 db 2
pb_3: times 16 db 3
pb_4: times 16 db 4
pb_15: times 16 db 15
pb_0_1: times 8 db 0, 1
pb_6_7: times 8 db 6, 7
pb_14_15: times 8 db 14, 15
pb_0_1_2_3: times 4 db 0, 1, 2, 3
pb_4_5_6_7: times 4 db 4, 5, 6, 7
pw_1: times 8 dw 1
pw_16: times 8 dw 16
pw_128: times 8 dw 128
pw_255: times 8 dw 255
pw_256: times 8 dw 256
pw_2048: times 8 dw 2048
pw_16380: times 8 dw 16380
pw_5_6: times 4 dw 5, 6
pw_0_128: times 4 dw 0, 128
pd_1024: times 4 dd 1024
%if ARCH_X86_32
pd_256: times 4 dd 256
pd_512: times 4 dd 512
pd_2048: times 4 dd 2048
%endif
pd_0xF0080029: times 4 dd 0xF0080029
pd_0xF00801C7: times 4 dd 0XF00801C7
cextern sgr_x_by_x
SECTION .text
%if ARCH_X86_32
%define PIC_base_offset $$
%macro SETUP_PIC 1-3 1,0 ; PIC_reg, save_PIC_reg, restore_PIC_reg
%assign pic_reg_stk_off 4
%xdefine PIC_reg %1
%if %2 == 1
mov [esp], %1
%endif
LEA PIC_reg, PIC_base_offset
%if %3 == 1
XCHG_PIC_REG
%endif
%endmacro
%macro XCHG_PIC_REG 0
mov [esp+pic_reg_stk_off], PIC_reg
%assign pic_reg_stk_off (pic_reg_stk_off+4) % 8
mov PIC_reg, [esp+pic_reg_stk_off]
%endmacro
%define PIC_sym(sym) (PIC_reg+(sym)-PIC_base_offset)
%else
%macro XCHG_PIC_REG 0
%endmacro
%define PIC_sym(sym) (sym)
%endif
;;;;;;;;;;;;;;;;;;;;;;
;; wiener ;;
;;;;;;;;;;;;;;;;;;;;;;
INIT_XMM ssse3
%if ARCH_X86_64
cglobal wiener_filter_h, 5, 15, 16, dst, left, src, stride, fh, w, h, edge
mov edged, edgem
movifnidn wd, wm
mov hd, hm
movq m15, [fhq]
pshufb m12, m15, [pb_6_7]
pshufb m13, m15, [pb_4]
pshufb m14, m15, [pb_2]
pshufb m15, m15, [pb_0]
mova m11, [pw_2048]
mova m10, [pw_16380]
lea r11, [pb_right_ext_mask]
DEFINE_ARGS dst, left, src, stride, x, w, h, edge, srcptr, dstptr, xlim
%else
cglobal wiener_filter_h, 5, 7, 8, -100, dst, left, src, stride, fh, w, h, edge
mov wd, edgem
mov [esp+12], wd
mov wd, wm
mov hd, hm
SETUP_PIC hd
movq m0, [fhq]
pshufb m3, m0, [PIC_sym(pb_6_7)]
pshufb m2, m0, [PIC_sym(pb_4)]
pshufb m1, m0, [PIC_sym(pb_2)]
pshufb m0, m0, [PIC_sym(pb_0)]
DEFINE_ARGS dst, left, src, stride, x, w, h, edge
%define srcptrq srcq
%define dstptrq dstq
%define hd dword [esp]
%define edged dword [esp+12]
%define xlimd dword [esp+16]
%define m10 [PIC_sym(pw_16380)]
%define m11 [PIC_sym(pw_2048)]
%define m12 [esp+0x14]
%define m13 [esp+0x24]
%define m14 [esp+0x34]
%define m15 [esp+0x44]
mova m15, m0
mova m14, m1
mova m13, m2
mova m12, m3
%endif
; if (edge & has_right) align_w_to_16
; else w -= 3, and use that as limit in x loop
test edged, 2 ; has_right
jnz .align
mov xlimd, -3
jmp .loop
.align:
add wd, 15
and wd, ~15
%if ARCH_X86_64
xor xlimd, xlimd
%else
mov xlimd, 0
%endif
; main y loop for vertical filter
.loop:
%if ARCH_X86_64
mov srcptrq, srcq
mov dstptrq, dstq
lea xd, [wq+xlimq]
%else
mov [esp+8], srcq
mov [esp+4], dstq
mov xd, xlimd
add xd, wd
%endif
; load left edge pixels
test edged, 1 ; have_left
jz .emu_left
test leftq, leftq ; left == NULL for the edge-extended bottom/top
jz .load_left_combined
movd m0, [leftq]
movd m1, [srcq]
punpckldq m0, m1
pslldq m0, 9
add leftq, 4
jmp .left_load_done
.load_left_combined:
movq m0, [srcq-3]
pslldq m0, 10
jmp .left_load_done
.emu_left:
movd m0, [srcq]
pshufb m0, [PIC_sym(pb_14x0_1_2)]
; load right edge pixels
.left_load_done:
cmp xd, 16
jg .main_load
test xd, xd
jg .load_and_splat
je .splat_right
; for very small images (w=[1-2]), edge-extend the original cache,
; ugly, but only runs in very odd cases
add wd, wd
%if ARCH_X86_64
pshufb m0, [r11-pb_right_ext_mask+pb_0_to_15_min_n+wq*8-16]
%else
pshufb m0, [PIC_sym(pb_0_to_15_min_n)+wq*8-16]
%endif
shr wd, 1
; main x loop, mostly this starts in .main_load
.splat_right:
; no need to load new pixels, just extend them from the (possibly previously
; extended) previous load into m0
pshufb m1, m0, [PIC_sym(pb_15)]
jmp .main_loop
.load_and_splat:
; load new pixels and extend edge for right-most
movu m1, [srcptrq+3]
%if ARCH_X86_64
sub r11, xq
movu m2, [r11+16]
add r11, xq
%else
sub PIC_reg, xd
movu m2, [PIC_sym(pb_right_ext_mask)+16]
add PIC_reg, xd
%endif
movd m3, [srcptrq+2+xq]
pshufb m3, [PIC_sym(pb_0)]
pand m1, m2
pxor m2, [PIC_sym(pb_right_ext_mask)]
pand m3, m2
pxor m2, [PIC_sym(pb_right_ext_mask)]
por m1, m3
jmp .main_loop
.main_load:
; load subsequent line
movu m1, [srcptrq+3]
.main_loop:
palignr m2, m1, m0, 10
palignr m3, m1, m0, 11
palignr m4, m1, m0, 12
palignr m5, m1, m0, 13
palignr m6, m1, m0, 14
palignr m7, m1, m0, 15
%if ARCH_X86_32
mova [esp+0x54], m1
%define m8 m1
%endif
punpcklbw m0, m2, m1
punpckhbw m2, m1
punpcklbw m8, m3, m7
punpckhbw m3, m7
punpcklbw m7, m4, m6
punpckhbw m4, m6
pmaddubsw m0, m15
pmaddubsw m2, m15
pmaddubsw m8, m14
pmaddubsw m3, m14
pmaddubsw m7, m13
pmaddubsw m4, m13
paddw m0, m8
paddw m2, m3
pxor m3, m3
punpcklbw m6, m5, m3
punpckhbw m5, m3
psllw m8, m6, 7
psllw m3, m5, 7
psubw m8, m10
psubw m3, m10
pmullw m6, m12
pmullw m5, m12
paddw m0, m7
paddw m2, m4
paddw m0, m6
paddw m2, m5
paddsw m0, m8
paddsw m2, m3
psraw m0, 3
psraw m2, 3
paddw m0, m11
paddw m2, m11
mova [dstptrq+ 0], m0
mova [dstptrq+16], m2
%if ARCH_X86_64
mova m0, m1
%else
mova m0, [esp+0x54]
%endif
add srcptrq, 16
add dstptrq, 32
sub xd, 16
cmp xd, 16
jg .main_load
test xd, xd
jg .load_and_splat
cmp xd, xlimd
jg .splat_right
%if ARCH_X86_32
mov srcq, [esp+8]
mov dstq, [esp+4]
%endif
add srcq, strideq
add dstq, 384*2
dec hd
jg .loop
RET
%if ARCH_X86_64
cglobal wiener_filter_v, 4, 10, 16, dst, stride, mid, w, h, fv, edge
mov edged, edgem
movifnidn fvq, fvmp
movifnidn hd, hm
movq m15, [fvq]
pshufb m14, m15, [pb_4_5_6_7]
pshufb m15, m15, [pb_0_1_2_3]
paddw m14, [pw_0_128]
movd m12, [pd_1024]
pshufd m12, m12, 0
DEFINE_ARGS dst, stride, mid, w, h, y, edge, ylim, mptr, dstptr
mov ylimd, edged
and ylimd, 8 ; have_bottom
shr ylimd, 2
sub ylimd, 3
%else
cglobal wiener_filter_v, 5, 7, 8, -96, dst, stride, mid, w, h, fv, edge
%define ylimd [esp+12]
mov r5d, edgem
and r5d, 8
shr r5d, 2
sub r5d, 3
mov ylimd, r5d
mov fvq, fvmp
mov edged, edgem
SETUP_PIC edged
movq m0, [fvq]
pshufb m1, m0, [PIC_sym(pb_4_5_6_7)]
pshufb m0, m0, [PIC_sym(pb_0_1_2_3)]
paddw m1, [PIC_sym(pw_0_128)]
mova [esp+0x50], m0
mova [esp+0x40], m1
DEFINE_ARGS dst, stride, mid, w, h, y, edge
%define mptrq midq
%define dstptrq dstq
%define edged dword [esp]
%endif
; main x loop for vertical filter, does one column of 16 pixels
.loop_x:
mova m3, [midq] ; middle line
; load top pixels
test edged, 4 ; have_top
jz .emu_top
mova m0, [midq-384*4]
mova m2, [midq-384*2]
mova m1, m0
jmp .load_bottom_pixels
.emu_top:
mova m0, m3
mova m1, m3
mova m2, m3
; load bottom pixels
.load_bottom_pixels:
mov yd, hd
%if ARCH_X86_64
mov mptrq, midq
mov dstptrq, dstq
add yd, ylimd
%else
mov [esp+8], midq
mov [esp+4], dstq
add yd, ylimd
%endif
jg .load_threelines
; the remainder here is somewhat messy but only runs in very weird
; circumstances at the bottom of the image in very small blocks (h=[1-3]),
; so performance is not terribly important here...
je .load_twolines
cmp yd, -1
je .load_oneline
; h == 1 case
mova m5, m3
mova m4, m3
mova m6, m3
jmp .loop
.load_oneline:
; h == 2 case
mova m4, [midq+384*2]
mova m5, m4
mova m6, m4
jmp .loop
.load_twolines:
; h == 3 case
mova m4, [midq+384*2]
mova m5, [midq+384*4]
mova m6, m5
jmp .loop
.load_threelines:
; h > 3 case
mova m4, [midq+384*2]
mova m5, [midq+384*4]
; third line loaded in main loop below
; main y loop for vertical filter
.loop_load:
; load one line into m6. if that pixel is no longer available, do
; nothing, since m6 still has the data from the previous line in it. We
; try to structure the loop so that the common case is evaluated fastest
mova m6, [mptrq+384*6]
.loop:
%if ARCH_X86_64
paddw m7, m0, m6
paddw m8, m1, m5
paddw m9, m2, m4
punpcklwd m10, m7, m8
punpckhwd m7, m8
punpcklwd m11, m9, m3
punpckhwd m9, m3
pmaddwd m10, m15
pmaddwd m7, m15
pmaddwd m11, m14
pmaddwd m9, m14
paddd m10, m12
paddd m7, m12
paddd m10, m11
paddd m7, m9
psrad m10, 11
psrad m7, 11
packssdw m10, m7
packuswb m10, m10
movq [dstptrq], m10
%else
mova [esp+0x30], m1
mova [esp+0x20], m2
mova [esp+0x10], m3
paddw m0, m6
paddw m1, m5
paddw m2, m4
punpcklwd m7, m2, m3
punpckhwd m2, m3
punpcklwd m3, m0, m1
punpckhwd m0, m1
mova m1, [esp+0x50]
pmaddwd m3, m1
pmaddwd m0, m1
mova m1, [esp+0x40]
pmaddwd m7, m1
pmaddwd m2, m1
paddd m3, [PIC_sym(pd_1024)]
paddd m0, [PIC_sym(pd_1024)]
paddd m3, m7
paddd m0, m2
psrad m3, 11
psrad m0, 11
packssdw m3, m0
packuswb m3, m3
movq [dstq], m3
mova m1, [esp+0x30]
mova m2, [esp+0x20]
mova m3, [esp+0x10]
%endif
; shift pixels one position
mova m0, m1
mova m1, m2
mova m2, m3
mova m3, m4
mova m4, m5
mova m5, m6
add dstptrq, strideq
add mptrq, 384*2
dec yd
jg .loop_load
; for the bottom pixels, continue using m6 (as extended edge)
cmp yd, ylimd
jg .loop
%if ARCH_X86_32
mov midq, [esp+8]
mov dstq, [esp+4]
%endif
add dstq, 8
add midq, 16
sub wd, 8
jg .loop_x
RET
;;;;;;;;;;;;;;;;;;;;;;;;;;
;; self-guided ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;
%macro MULLD 2
pmulhuw m5, %1, %2
pmullw %1, %2
pslld m5, 16
paddd %1, m5
%endmacro
%macro GATHERDD 2
mova m5, m7
movd r6d, %2
%if ARCH_X86_64
movd %1, [r5+r6]
pextrw r6d, %2, 2
pinsrw m5, [r5+r6+2], 3
pextrw r6d, %2, 4
pinsrw %1, [r5+r6+2], 5
pextrw r6d, %2, 6
pinsrw m5, [r5+r6+2], 7
%else
movd %1, [PIC_sym(sgr_x_by_x-0xF03)+r6]
pextrw r6d, %2, 2
pinsrw m5, [PIC_sym(sgr_x_by_x-0xF03)+r6+2], 3
pextrw r6d, %2, 4
pinsrw %1, [PIC_sym(sgr_x_by_x-0xF03)+r6+2], 5
pextrw r6d, %2, 6
pinsrw m5, [PIC_sym(sgr_x_by_x-0xF03)+r6+2], 7
%endif
por %1, m5
%endmacro
%if ARCH_X86_64
cglobal sgr_box3_h, 5, 11, 8, sumsq, sum, left, src, stride, x, h, edge, w, xlim
mov xlimd, edgem
movifnidn xd, xm
mov hd, hm
mov edged, xlimd
and xlimd, 2 ; have_right
add xd, xlimd
xor xlimd, 2 ; 2*!have_right
%else
cglobal sgr_box3_h, 6, 7, 8, sumsq, sum, left, src, stride, x, h, edge, w, xlim
%define wq r0m
%define xlimd r1m
%define hd hmp
%define edged edgemp
mov r6, edgem
and r6, 2 ; have_right
add xd, r6
xor r6, 2 ; 2*!have_right
mov xlimd, r6
SETUP_PIC r6, 0
%endif
jnz .no_right
add xd, 7
and xd, ~7
.no_right:
pxor m1, m1
lea srcq, [srcq+xq]
lea sumq, [sumq+xq*2-2]
lea sumsqq, [sumsqq+xq*4-4]
neg xq
mov wq, xq
%if ARCH_X86_64
lea r10, [pb_right_ext_mask+16]
%endif
.loop_y:
mov xq, wq
; load left
test edged, 1 ; have_left
jz .no_left
test leftq, leftq
jz .load_left_from_main
movd m0, [leftq]
pslldq m0, 12
add leftq, 4
jmp .expand_x
.no_left:
movd m0, [srcq+xq]
pshufb m0, [PIC_sym(pb_0)]
jmp .expand_x
.load_left_from_main:
movd m0, [srcq+xq-2]
pslldq m0, 14
.expand_x:
punpckhbw xm0, xm1
; when we reach this, m0 contains left two px in highest words
cmp xq, -8
jle .loop_x
.partial_load_and_extend:
movd m3, [srcq-4]
pshufb m3, [PIC_sym(pb_3)]
movq m2, [srcq+xq]
punpcklbw m2, m1
punpcklbw m3, m1
%if ARCH_X86_64
movu m4, [r10+xq*2]
%else
movu m4, [PIC_sym(pb_right_ext_mask+16)+xd*2]
%endif
pand m2, m4
pandn m4, m3
por m2, m4
jmp .loop_x_noload
.right_extend:
pshufb m2, m0, [PIC_sym(pb_14_15)]
jmp .loop_x_noload
.loop_x:
movq m2, [srcq+xq]
punpcklbw m2, m1
.loop_x_noload:
palignr m3, m2, m0, 12
palignr m4, m2, m0, 14
punpcklwd m5, m3, m2
punpckhwd m6, m3, m2
paddw m3, m4
punpcklwd m7, m4, m1
punpckhwd m4, m1
pmaddwd m5, m5
pmaddwd m6, m6
pmaddwd m7, m7
pmaddwd m4, m4
paddd m5, m7
paddd m6, m4
paddw m3, m2
movu [sumq+xq*2], m3
movu [sumsqq+xq*4+ 0], m5
movu [sumsqq+xq*4+16], m6
mova m0, m2
add xq, 8
; if x <= -8 we can reload more pixels
; else if x < 0 we reload and extend (this implies have_right=0)
; else if x < xlimd we extend from previous load (this implies have_right=0)
; else we are done
cmp xd, -8
jle .loop_x
test xd, xd
jl .partial_load_and_extend
cmp xd, xlimd
jl .right_extend
add sumsqq, (384+16)*4
add sumq, (384+16)*2
add srcq, strideq
dec hd
jg .loop_y
RET
%if ARCH_X86_64
cglobal sgr_box3_v, 4, 10, 9, sumsq, sum, w, h, edge, x, y, sumsq_base, sum_base, ylim
movifnidn edged, edgem
%else
cglobal sgr_box3_v, 5, 7, 8, -28, sumsq, sum, w, h, edge, x, y
%define sumsq_baseq dword [esp+0]
%define sum_baseq dword [esp+4]
%define ylimd dword [esp+8]
%define m8 [esp+12]
%endif
mov xq, -2
%if ARCH_X86_64
mov ylimd, edged
and ylimd, 8 ; have_bottom
shr ylimd, 2
sub ylimd, 2 ; -2 if have_bottom=0, else 0
mov sumsq_baseq, sumsqq
mov sum_baseq, sumq
.loop_x:
mov sumsqq, sumsq_baseq
mov sumq, sum_baseq
lea yd, [hd+ylimd+2]
%else
mov yd, edged
and yd, 8 ; have_bottom
shr yd, 2
sub yd, 2 ; -2 if have_bottom=0, else 0
mov sumsq_baseq, sumsqq
mov sum_baseq, sumq
mov ylimd, yd
.loop_x:
mov sumsqd, sumsq_baseq
mov sumd, sum_baseq
lea yd, [hd+2]
add yd, ylimd
%endif
lea sumsqq, [sumsqq+xq*4+4-(384+16)*4]
lea sumq, [sumq+xq*2+2-(384+16)*2]
test edged, 4 ; have_top
jnz .load_top
movu m0, [sumsqq+(384+16)*4*1]
movu m1, [sumsqq+(384+16)*4*1+16]
mova m2, m0
mova m3, m1
mova m4, m0
mova m5, m1
movu m6, [sumq+(384+16)*2*1]
mova m7, m6
mova m8, m6
jmp .loop_y_noload
.load_top:
movu m0, [sumsqq-(384+16)*4*1] ; l2sq [left]
movu m1, [sumsqq-(384+16)*4*1+16] ; l2sq [right]
movu m2, [sumsqq-(384+16)*4*0] ; l1sq [left]
movu m3, [sumsqq-(384+16)*4*0+16] ; l1sq [right]
movu m6, [sumq-(384+16)*2*1] ; l2
movu m7, [sumq-(384+16)*2*0] ; l1
.loop_y:
%if ARCH_X86_64
movu m8, [sumq+(384+16)*2*1] ; l0
%else
movu m4, [sumq+(384+16)*2*1] ; l0
mova m8, m4
%endif
movu m4, [sumsqq+(384+16)*4*1] ; l0sq [left]
movu m5, [sumsqq+(384+16)*4*1+16] ; l0sq [right]
.loop_y_noload:
paddd m0, m2
paddd m1, m3
paddw m6, m7
paddd m0, m4
paddd m1, m5
paddw m6, m8
movu [sumsqq+ 0], m0
movu [sumsqq+16], m1
movu [sumq], m6
; shift position down by one
mova m0, m2
mova m1, m3
mova m2, m4
mova m3, m5
mova m6, m7
mova m7, m8
add sumsqq, (384+16)*4
add sumq, (384+16)*2
dec yd
jg .loop_y
cmp yd, ylimd
jg .loop_y_noload
add xd, 8
cmp xd, wd
jl .loop_x
RET
cglobal sgr_calc_ab1, 4, 7, 12, a, b, w, h, s
movifnidn sd, sm
sub aq, (384+16-1)*4
sub bq, (384+16-1)*2
add hd, 2
%if ARCH_X86_64
LEA r5, sgr_x_by_x-0xF03
%else
SETUP_PIC r5, 0
%endif
movd m6, sd
pshuflw m6, m6, q0000
punpcklqdq m6, m6
pxor m7, m7
DEFINE_ARGS a, b, w, h, x
%if ARCH_X86_64
mova m8, [pd_0xF00801C7]
mova m9, [pw_256]
psrld m10, m9, 13 ; pd_2048
mova m11, [pb_unpcklwdw]
%else
%define m8 [PIC_sym(pd_0xF00801C7)]
%define m9 [PIC_sym(pw_256)]
%define m10 [PIC_sym(pd_2048)]
%define m11 [PIC_sym(pb_unpcklwdw)]
%endif
.loop_y:
mov xq, -2
.loop_x:
movq m0, [bq+xq*2]
movq m1, [bq+xq*2+(384+16)*2]
punpcklwd m0, m7
punpcklwd m1, m7
movu m2, [aq+xq*4]
movu m3, [aq+xq*4+(384+16)*4]
pslld m4, m2, 3
pslld m5, m3, 3
paddd m2, m4 ; aa * 9
paddd m3, m5
pmaddwd m4, m0, m0
pmaddwd m5, m1, m1
pmaddwd m0, m8
pmaddwd m1, m8
psubd m2, m4 ; p = aa * 9 - bb * bb
psubd m3, m5
MULLD m2, m6
MULLD m3, m6
paddusw m2, m8
paddusw m3, m8
psrld m2, 20 ; z
psrld m3, 20
GATHERDD m4, m2 ; xx
GATHERDD m2, m3
psrld m4, 24
psrld m2, 24
packssdw m3, m4, m2
pshufb m4, m11
MULLD m0, m4
pshufb m2, m11
MULLD m1, m2
psubw m5, m9, m3
paddd m0, m10
paddd m1, m10
psrld m0, 12
psrld m1, 12
movq [bq+xq*2], m5
psrldq m5, 8
movq [bq+xq*2+(384+16)*2], m5
movu [aq+xq*4], m0
movu [aq+xq*4+(384+16)*4], m1
add xd, 4
cmp xd, wd
jl .loop_x
add aq, (384+16)*4*2
add bq, (384+16)*2*2
sub hd, 2
jg .loop_y
RET
%if ARCH_X86_64
cglobal sgr_finish_filter1, 5, 13, 16, t, src, stride, a, b, w, h, \
tmp_base, src_base, a_base, b_base, x, y
movifnidn wd, wm
mov hd, hm
mova m15, [pw_16]
mov tmp_baseq, tq
mov src_baseq, srcq
mov a_baseq, aq
mov b_baseq, bq
xor xd, xd
%else
cglobal sgr_finish_filter1, 7, 7, 8, -144, t, src, stride, a, b, x, y
%define tmp_baseq [esp+8]
%define src_baseq [esp+12]
%define a_baseq [esp+16]
%define b_baseq [esp+20]
%define wd [esp+24]
%define hd [esp+28]
mov tmp_baseq, tq
mov src_baseq, srcq
mov a_baseq, aq
mov b_baseq, bq
mov wd, xd
mov hd, yd
xor xd, xd
SETUP_PIC yd, 1, 1
jmp .loop_start
%endif
.loop_x:
mov tq, tmp_baseq
mov srcq, src_baseq
mov aq, a_baseq
mov bq, b_baseq
%if ARCH_X86_32
.loop_start:
movu m0, [bq+xq*2-(384+16)*2-2]
movu m2, [bq+xq*2-(384+16)*2+2]
mova m1, [bq+xq*2-(384+16)*2] ; b:top
paddw m0, m2 ; b:tl+tr
movu m2, [bq+xq*2-2]
movu m3, [bq+xq*2+2]
paddw m1, [bq+xq*2] ; b:top+ctr
paddw m2, m3 ; b:l+r
mova [esp+0x80], m0
mova [esp+0x70], m1
mova [esp+0x60], m2
%endif
movu m0, [aq+xq*4-(384+16)*4-4]
movu m2, [aq+xq*4-(384+16)*4+4]
mova m1, [aq+xq*4-(384+16)*4] ; a:top [first half]
paddd m0, m2 ; a:tl+tr [first half]
movu m2, [aq+xq*4-(384+16)*4-4+16]
movu m4, [aq+xq*4-(384+16)*4+4+16]
mova m3, [aq+xq*4-(384+16)*4+16] ; a:top [second half]
paddd m2, m4 ; a:tl+tr [second half]
movu m4, [aq+xq*4-4]
movu m5, [aq+xq*4+4]
paddd m1, [aq+xq*4] ; a:top+ctr [first half]
paddd m4, m5 ; a:l+r [first half]
movu m5, [aq+xq*4+16-4]
movu m6, [aq+xq*4+16+4]
paddd m3, [aq+xq*4+16] ; a:top+ctr [second half]
paddd m5, m6 ; a:l+r [second half]
%if ARCH_X86_64
movu m6, [bq+xq*2-(384+16)*2-2]
movu m8, [bq+xq*2-(384+16)*2+2]
mova m7, [bq+xq*2-(384+16)*2] ; b:top
paddw m6, m8 ; b:tl+tr
movu m8, [bq+xq*2-2]
movu m9, [bq+xq*2+2]
paddw m7, [bq+xq*2] ; b:top+ctr
paddw m8, m9 ; b:l+r
%endif
lea tq, [tq+xq*2]
lea srcq, [srcq+xq*1]
lea aq, [aq+xq*4+(384+16)*4]
lea bq, [bq+xq*2+(384+16)*2]
mov yd, hd
.loop_y:
%if ARCH_X86_64
movu m9, [bq-2]
movu m10, [bq+2]
paddw m7, [bq] ; b:top+ctr+bottom
paddw m9, m10 ; b:bl+br
paddw m10, m7, m8 ; b:top+ctr+bottom+l+r
paddw m6, m9 ; b:tl+tr+bl+br
psubw m7, [bq-(384+16)*2*2] ; b:ctr+bottom
paddw m10, m6
psllw m10, 2
psubw m10, m6 ; aa
pxor m14, m14
movq m12, [srcq]
punpcklbw m12, m14
punpcklwd m6, m10, m15
punpckhwd m10, m15
punpcklwd m13, m12, m15
punpckhwd m12, m15
pmaddwd m6, m13 ; aa*src[x]+256 [first half]
pmaddwd m10, m12 ; aa*src[x]+256 [second half]
%else
paddd m1, [aq] ; a:top+ctr+bottom [first half]
paddd m3, [aq+16] ; a:top+ctr+bottom [second half]
mova [esp+0x50], m1
mova [esp+0x40], m3
mova [esp+0x30], m4
movu m6, [aq-4]
movu m7, [aq+4]
paddd m1, m4 ; a:top+ctr+bottom+l+r [first half]
paddd m3, m5 ; a:top+ctr+bottom+l+r [second half]
paddd m6, m7 ; a:bl+br [first half]
movu m7, [aq+16-4]
movu m4, [aq+16+4]
paddd m7, m4 ; a:bl+br [second half]
paddd m0, m6 ; a:tl+tr+bl+br [first half]
paddd m2, m7 ; a:tl+tr+bl+br [second half]
paddd m1, m0
paddd m3, m2
pslld m1, 2
pslld m3, 2
psubd m1, m0 ; bb [first half]
psubd m3, m2 ; bb [second half]
%endif
%if ARCH_X86_64
movu m11, [aq-4]
movu m12, [aq+4]
paddd m1, [aq] ; a:top+ctr+bottom [first half]
paddd m11, m12 ; a:bl+br [first half]
movu m12, [aq+16-4]
movu m13, [aq+16+4]
paddd m3, [aq+16] ; a:top+ctr+bottom [second half]
paddd m12, m13 ; a:bl+br [second half]
paddd m13, m1, m4 ; a:top+ctr+bottom+l+r [first half]
paddd m14, m3, m5 ; a:top+ctr+bottom+l+r [second half]
paddd m0, m11 ; a:tl+tr+bl+br [first half]
paddd m2, m12 ; a:tl+tr+bl+br [second half]
paddd m13, m0
paddd m14, m2
pslld m13, 2
pslld m14, 2
psubd m13, m0 ; bb [first half]
psubd m14, m2 ; bb [second half]
psubd m1, [aq-(384+16)*4*2] ; a:ctr+bottom [first half]
psubd m3, [aq-(384+16)*4*2+16] ; a:ctr+bottom [second half]
%else
mova m4, [esp+0x80]
mova [esp+0x80], m5
mova m5, [esp+0x70]
mova [esp+0x70], m6
mova m6, [esp+0x60]
mova [esp+0x60], m7
mova [esp+0x20], m1
movu m7, [bq-2]
movu m1, [bq+2]
paddw m5, [bq] ; b:top+ctr+bottom
paddw m7, m1
paddw m1, m5, m6 ; b:top+ctr+bottom+l+r
paddw m4, m7 ; b:tl+tr+bl+br
psubw m5, [bq-(384+16)*2*2] ; b:ctr+bottom
paddw m1, m4
psllw m1, 2
psubw m1, m4 ; aa
movq m0, [srcq]
XCHG_PIC_REG
punpcklbw m0, [PIC_sym(pb_right_ext_mask)+16]
punpcklwd m4, m1, [PIC_sym(pw_16)]
punpckhwd m1, [PIC_sym(pw_16)]
punpcklwd m2, m0, [PIC_sym(pw_16)]
punpckhwd m0, [PIC_sym(pw_16)]
XCHG_PIC_REG
pmaddwd m4, m2 ; aa*src[x]+256 [first half]
pmaddwd m1, m0 ; aa*src[x]+256 [second half]
%endif
%if ARCH_X86_64
paddd m6, m13
paddd m10, m14
psrad m6, 9
psrad m10, 9
packssdw m6, m10
mova [tq], m6
%else
paddd m4, [esp+0x20]
paddd m1, m3
psrad m4, 9
psrad m1, 9
packssdw m4, m1
mova [tq], m4
%endif
; shift to next row
%if ARCH_X86_64
mova m0, m4
mova m2, m5
mova m4, m11
mova m5, m12
mova m6, m8
mova m8, m9
%else
mova m1, [esp+0x50]
mova m3, [esp+0x40]
mova m0, [esp+0x30]
mova m2, [esp+0x80]
mova m4, [esp+0x70]
mova [esp+0x70], m5
mova m5, [esp+0x60]
mova [esp+0x80], m6
mova [esp+0x60], m7
psubd m1, [aq-(384+16)*4*2] ; a:ctr+bottom [first half]
psubd m3, [aq-(384+16)*4*2+16] ; a:ctr+bottom [second half]
%endif
add aq, (384+16)*4
add bq, (384+16)*2
add tq, 384*2
add srcq, strideq
dec yd
jg .loop_y
add xd, 8
cmp xd, wd
jl .loop_x
RET
cglobal sgr_weighted1, 4, 7, 8, dst, stride, t, w, h, wt
movifnidn hd, hm
%if ARCH_X86_32
SETUP_PIC r6, 0
%endif
movd m0, wtm
pshufb m0, [PIC_sym(pb_0_1)]
psllw m0, 4
pxor m7, m7
DEFINE_ARGS dst, stride, t, w, h, idx
.loop_y:
xor idxd, idxd
.loop_x:
mova m1, [tq+idxq*2+ 0]
mova m4, [tq+idxq*2+16]
mova m5, [dstq+idxq]
punpcklbw m2, m5, m7
punpckhbw m5, m7
psllw m3, m2, 4
psllw m6, m5, 4
psubw m1, m3
psubw m4, m6
pmulhrsw m1, m0
pmulhrsw m4, m0
paddw m1, m2
paddw m4, m5
packuswb m1, m4
mova [dstq+idxq], m1
add idxd, 16
cmp idxd, wd
jl .loop_x
add dstq, strideq
add tq, 384 * 2
dec hd
jg .loop_y
RET
%if ARCH_X86_64
cglobal sgr_box5_h, 5, 11, 12, sumsq, sum, left, src, stride, w, h, edge, x, xlim
mov edged, edgem
movifnidn wd, wm
mov hd, hm
mova m10, [pb_0]
mova m11, [pb_0_1]
%else
cglobal sgr_box5_h, 7, 7, 8, sumsq, sum, left, src, xlim, x, h, edge
%define edged edgemp
%define wd xd
%define wq wd
%define wm r5m
%define strideq r4m
SUB esp, 8
SETUP_PIC sumsqd, 1, 1
%define m10 [PIC_sym(pb_0)]
%define m11 [PIC_sym(pb_0_1)]
%endif
test edged, 2 ; have_right
jz .no_right
xor xlimd, xlimd
add wd, 2
add wd, 15
and wd, ~15
jmp .right_done
.no_right:
mov xlimd, 3
dec wd
.right_done:
pxor m1, m1
lea srcq, [srcq+wq+1]
lea sumq, [sumq+wq*2-2]
lea sumsqq, [sumsqq+wq*4-4]
neg wq
%if ARCH_X86_64
lea r10, [pb_right_ext_mask+16]
%else
mov wm, xd
%define wq wm
%endif
.loop_y:
mov xq, wq
; load left
test edged, 1 ; have_left
jz .no_left
test leftq, leftq
jz .load_left_from_main
movd m0, [leftq]
movd m2, [srcq+xq-1]
pslldq m2, 4
por m0, m2
pslldq m0, 11
add leftq, 4
jmp .expand_x
.no_left:
movd m0, [srcq+xq-1]
XCHG_PIC_REG
pshufb m0, m10
XCHG_PIC_REG
jmp .expand_x
.load_left_from_main:
movd m0, [srcq+xq-4]
pslldq m0, 12
.expand_x:
punpckhbw m0, m1
; when we reach this, m0 contains left two px in highest words
cmp xq, -8
jle .loop_x
test xq, xq
jge .right_extend
.partial_load_and_extend:
XCHG_PIC_REG
movd m3, [srcq-1]
movq m2, [srcq+xq]
pshufb m3, m10
punpcklbw m3, m1
punpcklbw m2, m1
%if ARCH_X86_64
movu m4, [r10+xq*2]
%else
movu m4, [PIC_sym(pb_right_ext_mask+16)+xd*2]
XCHG_PIC_REG
%endif
pand m2, m4
pandn m4, m3
por m2, m4
jmp .loop_x_noload
.right_extend:
psrldq m2, m0, 14
XCHG_PIC_REG
pshufb m2, m11
XCHG_PIC_REG
jmp .loop_x_noload
.loop_x:
movq m2, [srcq+xq]
punpcklbw m2, m1
.loop_x_noload:
palignr m3, m2, m0, 8
palignr m4, m2, m0, 10
palignr m5, m2, m0, 12
palignr m6, m2, m0, 14
%if ARCH_X86_64
paddw m0, m3, m2
punpcklwd m7, m3, m2
punpckhwd m3, m2
paddw m0, m4
punpcklwd m8, m4, m5
punpckhwd m4, m5
paddw m0, m5
punpcklwd m9, m6, m1
punpckhwd m5, m6, m1
paddw m0, m6
pmaddwd m7, m7
pmaddwd m3, m3
pmaddwd m8, m8
pmaddwd m4, m4
pmaddwd m9, m9
pmaddwd m5, m5
paddd m7, m8
paddd m3, m4
paddd m7, m9
paddd m3, m5
movu [sumq+xq*2], m0
movu [sumsqq+xq*4+ 0], m7
movu [sumsqq+xq*4+16], m3
%else
paddw m0, m3, m2
paddw m0, m4
paddw m0, m5
paddw m0, m6
movu [sumq+xq*2], m0
punpcklwd m7, m3, m2
punpckhwd m3, m2
punpcklwd m0, m4, m5
punpckhwd m4, m5
punpckhwd m5, m6, m1
pmaddwd m7, m7
pmaddwd m3, m3
pmaddwd m0, m0
pmaddwd m4, m4
pmaddwd m5, m5
paddd m7, m0
paddd m3, m4
paddd m3, m5
punpcklwd m0, m6, m1
pmaddwd m0, m0
paddd m7, m0
movu [sumsqq+xq*4+ 0], m7
movu [sumsqq+xq*4+16], m3
%endif
mova m0, m2
add xq, 8
; if x <= -8 we can reload more pixels
; else if x < 0 we reload and extend (this implies have_right=0)
; else if x < xlimd we extend from previous load (this implies have_right=0)
; else we are done
cmp xq, -8
jle .loop_x
test xq, xq
jl .partial_load_and_extend
cmp xq, xlimq
jl .right_extend
add sumsqq, (384+16)*4
add sumq, (384+16)*2
add srcq, strideq
dec hd
jg .loop_y
%if ARCH_X86_32
ADD esp, 8
%endif
RET
%if ARCH_X86_64
cglobal sgr_box5_v, 4, 10, 15, sumsq, sum, w, h, edge, x, y, sumsq_ptr, sum_ptr, ylim
movifnidn edged, edgem
mov ylimd, edged
%else
cglobal sgr_box5_v, 5, 7, 8, -44, sumsq, sum, x, y, ylim, sumsq_ptr, sum_ptr
%define wm [esp+0]
%define hm [esp+4]
%define edgem [esp+8]
mov wm, xd
mov hm, yd
mov edgem, ylimd
%endif
and ylimd, 8 ; have_bottom
shr ylimd, 2
sub ylimd, 3 ; -3 if have_bottom=0, else -1
mov xq, -2
%if ARCH_X86_64
.loop_x:
lea yd, [hd+ylimd+2]
lea sumsq_ptrq, [sumsqq+xq*4+4-(384+16)*4]
lea sum_ptrq, [ sumq+xq*2+2-(384+16)*2]
test edged, 4 ; have_top
jnz .load_top
movu m0, [sumsq_ptrq+(384+16)*4*1]
movu m1, [sumsq_ptrq+(384+16)*4*1+16]
mova m2, m0
mova m3, m1
mova m4, m0
mova m5, m1
mova m6, m0
mova m7, m1
movu m10, [sum_ptrq+(384+16)*2*1]
mova m11, m10
mova m12, m10
mova m13, m10
jmp .loop_y_second_load
.load_top:
movu m0, [sumsq_ptrq-(384+16)*4*1] ; l3/4sq [left]
movu m1, [sumsq_ptrq-(384+16)*4*1+16] ; l3/4sq [right]
movu m4, [sumsq_ptrq-(384+16)*4*0] ; l2sq [left]
movu m5, [sumsq_ptrq-(384+16)*4*0+16] ; l2sq [right]
mova m2, m0
mova m3, m1
movu m10, [sum_ptrq-(384+16)*2*1] ; l3/4
movu m12, [sum_ptrq-(384+16)*2*0] ; l2
mova m11, m10
.loop_y:
movu m6, [sumsq_ptrq+(384+16)*4*1] ; l1sq [left]
movu m7, [sumsq_ptrq+(384+16)*4*1+16] ; l1sq [right]
movu m13, [sum_ptrq+(384+16)*2*1] ; l1
.loop_y_second_load:
test yd, yd
jle .emulate_second_load
movu m8, [sumsq_ptrq+(384+16)*4*2] ; l0sq [left]
movu m9, [sumsq_ptrq+(384+16)*4*2+16] ; l0sq [right]
movu m14, [sum_ptrq+(384+16)*2*2] ; l0
.loop_y_noload:
paddd m0, m2
paddd m1, m3
paddw m10, m11
paddd m0, m4
paddd m1, m5
paddw m10, m12
paddd m0, m6
paddd m1, m7
paddw m10, m13
paddd m0, m8
paddd m1, m9
paddw m10, m14
movu [sumsq_ptrq+ 0], m0
movu [sumsq_ptrq+16], m1
movu [sum_ptrq], m10
; shift position down by one
mova m0, m4
mova m1, m5
mova m2, m6
mova m3, m7
mova m4, m8
mova m5, m9
mova m10, m12
mova m11, m13
mova m12, m14
add sumsq_ptrq, (384+16)*4*2
add sum_ptrq, (384+16)*2*2
sub yd, 2
jge .loop_y
; l1 = l0
mova m6, m8
mova m7, m9
mova m13, m14
cmp yd, ylimd
jg .loop_y_noload
add xd, 8
cmp xd, wd
jl .loop_x
RET
.emulate_second_load:
mova m8, m6
mova m9, m7
mova m14, m13
jmp .loop_y_noload
%else
.sumsq_loop_x:
lea yd, [ylimd+2]
add yd, hm
lea sumsq_ptrq, [sumsqq+xq*4+4-(384+16)*4]
test dword edgem, 4 ; have_top
jnz .sumsq_load_top
movu m0, [sumsq_ptrq+(384+16)*4*1]
movu m1, [sumsq_ptrq+(384+16)*4*1+16]
mova m4, m0
mova m5, m1
mova m6, m0
mova m7, m1
mova [esp+0x1c], m0
mova [esp+0x0c], m1
jmp .sumsq_loop_y_second_load
.sumsq_load_top:
movu m0, [sumsq_ptrq-(384+16)*4*1] ; l3/4sq [left]
movu m1, [sumsq_ptrq-(384+16)*4*1+16] ; l3/4sq [right]
movu m4, [sumsq_ptrq-(384+16)*4*0] ; l2sq [left]
movu m5, [sumsq_ptrq-(384+16)*4*0+16] ; l2sq [right]
mova [esp+0x1c], m0
mova [esp+0x0c], m1
.sumsq_loop_y:
movu m6, [sumsq_ptrq+(384+16)*4*1] ; l1sq [left]
movu m7, [sumsq_ptrq+(384+16)*4*1+16] ; l1sq [right]
.sumsq_loop_y_second_load:
test yd, yd
jle .sumsq_emulate_second_load
movu m2, [sumsq_ptrq+(384+16)*4*2] ; l0sq [left]
movu m3, [sumsq_ptrq+(384+16)*4*2+16] ; l0sq [right]
.sumsq_loop_y_noload:
paddd m0, [esp+0x1c]
paddd m1, [esp+0x0c]
paddd m0, m4
paddd m1, m5
paddd m0, m6
paddd m1, m7
paddd m0, m2
paddd m1, m3
movu [sumsq_ptrq+ 0], m0
movu [sumsq_ptrq+16], m1
; shift position down by one
mova m0, m4
mova m1, m5
mova m4, m2
mova m5, m3
mova [esp+0x1c], m6
mova [esp+0x0c], m7
add sumsq_ptrq, (384+16)*4*2
sub yd, 2
jge .sumsq_loop_y
; l1 = l0
mova m6, m2
mova m7, m3
cmp yd, ylimd
jg .sumsq_loop_y_noload
add xd, 8
cmp xd, wm
jl .sumsq_loop_x
mov xd, -2
.sum_loop_x:
lea yd, [ylimd+2]
add yd, hm
lea sum_ptrq, [sumq+xq*2+2-(384+16)*2]
test dword edgem, 4 ; have_top
jnz .sum_load_top
movu m0, [sum_ptrq+(384+16)*2*1]
mova m1, m0
mova m2, m0
mova m3, m0
jmp .sum_loop_y_second_load
.sum_load_top:
movu m0, [sum_ptrq-(384+16)*2*1] ; l3/4
movu m2, [sum_ptrq-(384+16)*2*0] ; l2
mova m1, m0
.sum_loop_y:
movu m3, [sum_ptrq+(384+16)*2*1] ; l1
.sum_loop_y_second_load:
test yd, yd
jle .sum_emulate_second_load
movu m4, [sum_ptrq+(384+16)*2*2] ; l0
.sum_loop_y_noload:
paddw m0, m1
paddw m0, m2
paddw m0, m3
paddw m0, m4
movu [sum_ptrq], m0
; shift position down by one
mova m0, m2
mova m1, m3
mova m2, m4
add sum_ptrq, (384+16)*2*2
sub yd, 2
jge .sum_loop_y
; l1 = l0
mova m3, m4
cmp yd, ylimd
jg .sum_loop_y_noload
add xd, 8
cmp xd, wm
jl .sum_loop_x
RET
.sumsq_emulate_second_load:
mova m2, m6
mova m3, m7
jmp .sumsq_loop_y_noload
.sum_emulate_second_load:
mova m4, m3
jmp .sum_loop_y_noload
%endif
cglobal sgr_calc_ab2, 4, 7, 11, a, b, w, h, s
movifnidn sd, sm
sub aq, (384+16-1)*4
sub bq, (384+16-1)*2
add hd, 2
%if ARCH_X86_64
LEA r5, sgr_x_by_x-0xF03
%else
SETUP_PIC r5, 0
%endif
movd m6, sd
pshuflw m6, m6, q0000
punpcklqdq m6, m6
pxor m7, m7
DEFINE_ARGS a, b, w, h, x
%if ARCH_X86_64
mova m8, [pd_0xF0080029]
mova m9, [pw_256]
psrld m10, m9, 15 ; pd_512
%else
%define m8 [PIC_sym(pd_0xF0080029)]
%define m9 [PIC_sym(pw_256)]
%define m10 [PIC_sym(pd_512)]
%endif
.loop_y:
mov xq, -2
.loop_x:
movq m0, [bq+xq*2+0]
movq m1, [bq+xq*2+8]
punpcklwd m0, m7
punpcklwd m1, m7
movu m2, [aq+xq*4+ 0]
movu m3, [aq+xq*4+16]
pslld m4, m2, 3 ; aa * 8
pslld m5, m3, 3
paddd m2, m4 ; aa * 9
paddd m3, m5
paddd m4, m4 ; aa * 16
paddd m5, m5
paddd m2, m4 ; aa * 25
paddd m3, m5
pmaddwd m4, m0, m0
pmaddwd m5, m1, m1
psubd m2, m4 ; p = aa * 25 - bb * bb
psubd m3, m5
MULLD m2, m6
MULLD m3, m6
paddusw m2, m8
paddusw m3, m8
psrld m2, 20 ; z
psrld m3, 20
GATHERDD m4, m2 ; xx
GATHERDD m2, m3
psrld m4, 24
psrld m2, 24
packssdw m3, m4, m2
pmullw m4, m8
pmullw m2, m8
psubw m5, m9, m3
pmaddwd m0, m4
pmaddwd m1, m2
paddd m0, m10
paddd m1, m10
psrld m0, 10
psrld m1, 10
movu [bq+xq*2], m5
movu [aq+xq*4+ 0], m0
movu [aq+xq*4+16], m1
add xd, 8
cmp xd, wd
jl .loop_x
add aq, (384+16)*4*2
add bq, (384+16)*2*2
sub hd, 2
jg .loop_y
RET
%if ARCH_X86_64
cglobal sgr_finish_filter2, 5, 13, 14, t, src, stride, a, b, w, h, \
tmp_base, src_base, a_base, b_base, x, y
movifnidn wd, wm
mov hd, hm
mov tmp_baseq, tq
mov src_baseq, srcq
mov a_baseq, aq
mov b_baseq, bq
mova m9, [pw_5_6]
mova m12, [pw_256]
psrlw m10, m12, 8 ; pw_1
psrlw m11, m12, 1 ; pw_128
pxor m13, m13
%else
cglobal sgr_finish_filter2, 6, 7, 8, t, src, stride, a, b, x, y
%define tmp_baseq r0m
%define src_baseq r1m
%define a_baseq r3m
%define b_baseq r4m
%define wd r5m
%define hd r6m
SUB esp, 8
SETUP_PIC yd
%define m8 m5
%define m9 [PIC_sym(pw_5_6)]
%define m10 [PIC_sym(pw_1)]
%define m11 [PIC_sym(pw_128)]
%define m12 [PIC_sym(pw_256)]
%define m13 m0
%endif
xor xd, xd
.loop_x:
mov tq, tmp_baseq
mov srcq, src_baseq
mov aq, a_baseq
mov bq, b_baseq
movu m0, [aq+xq*4-(384+16)*4-4]
mova m1, [aq+xq*4-(384+16)*4]
movu m2, [aq+xq*4-(384+16)*4+4]
movu m3, [aq+xq*4-(384+16)*4-4+16]
mova m4, [aq+xq*4-(384+16)*4+16]
movu m5, [aq+xq*4-(384+16)*4+4+16]
paddd m0, m2
paddd m3, m5
paddd m0, m1
paddd m3, m4
pslld m2, m0, 2
pslld m5, m3, 2
paddd m2, m0
paddd m5, m3
paddd m0, m2, m1 ; prev_odd_b [first half]
paddd m1, m5, m4 ; prev_odd_b [second half]
movu m3, [bq+xq*2-(384+16)*2-2]
mova m4, [bq+xq*2-(384+16)*2]
movu m5, [bq+xq*2-(384+16)*2+2]
paddw m3, m5
punpcklwd m5, m3, m4
punpckhwd m3, m4
pmaddwd m5, m9
pmaddwd m3, m9
mova m2, m5
packssdw m2, m3 ; prev_odd_a
lea tq, [tq+xq*2]
lea srcq, [srcq+xq*1]
lea aq, [aq+xq*4+(384+16)*4]
lea bq, [bq+xq*2+(384+16)*2]
%if ARCH_X86_32
mov [esp], PIC_reg
%endif
mov yd, hd
XCHG_PIC_REG
.loop_y:
movu m3, [aq-4]
mova m4, [aq]
movu m5, [aq+4]
paddd m3, m5
paddd m3, m4
pslld m5, m3, 2
paddd m5, m3
paddd m5, m4 ; cur_odd_b [first half]
movu m3, [aq+16-4]
mova m6, [aq+16]
movu m7, [aq+16+4]
paddd m3, m7
paddd m3, m6
pslld m7, m3, 2
paddd m7, m3
paddd m4, m7, m6 ; cur_odd_b [second half]
movu m3, [bq-2]
mova m6, [bq]
movu m7, [bq+2]
paddw m3, m7
punpcklwd m7, m3, m6
punpckhwd m3, m6
pmaddwd m7, m9
pmaddwd m3, m9
packssdw m6, m7, m3 ; cur_odd_a
paddd m0, m5 ; cur_even_b [first half]
paddd m1, m4 ; cur_even_b [second half]
paddw m2, m6 ; cur_even_a
movq m3, [srcq]
%if ARCH_X86_64
punpcklbw m3, m13
%else
mova [td], m5
pxor m7, m7
punpcklbw m3, m7
%endif
punpcklwd m7, m3, m10
punpckhwd m3, m10
punpcklwd m8, m2, m12
punpckhwd m2, m12
pmaddwd m7, m8
pmaddwd m3, m2
paddd m7, m0
paddd m3, m1
psrad m7, 9
psrad m3, 9
%if ARCH_X86_32
pxor m13, m13
%endif
movq m8, [srcq+strideq]
punpcklbw m8, m13
punpcklwd m0, m8, m10
punpckhwd m8, m10
punpcklwd m1, m6, m11
punpckhwd m2, m6, m11
pmaddwd m0, m1
pmaddwd m8, m2
%if ARCH_X86_64
paddd m0, m5
%else
paddd m0, [td]
%endif
paddd m8, m4
psrad m0, 8
psrad m8, 8
packssdw m7, m3
packssdw m0, m8
%if ARCH_X86_32
mova m5, [td]
%endif
mova [tq+384*2*0], m7
mova [tq+384*2*1], m0
mova m0, m5
mova m1, m4
mova m2, m6
add aq, (384+16)*4*2
add bq, (384+16)*2*2
add tq, 384*2*2
lea srcq, [srcq+strideq*2]
%if ARCH_X86_64
sub yd, 2
%else
sub dword [esp+4], 2
%endif
jg .loop_y
add xd, 8
cmp xd, wd
jl .loop_x
%if ARCH_X86_32
ADD esp, 8
%endif
RET
cglobal sgr_weighted2, 4, 7, 12, dst, stride, t1, t2, w, h, wt
movifnidn wd, wm
mov wtq, wtmp
%if ARCH_X86_64
movifnidn hd, hm
mova m10, [pd_1024]
pxor m11, m11
%else
SETUP_PIC hd, 0
%define m10 [PIC_sym(pd_1024)]
%define m11 m7
%endif
movd m0, [wtq]
pshufd m0, m0, 0
DEFINE_ARGS dst, stride, t1, t2, w, h, idx
%if ARCH_X86_32
%define hd hmp
%endif
.loop_y:
xor idxd, idxd
.loop_x:
mova m1, [t1q+idxq*2+ 0]
mova m2, [t1q+idxq*2+16]
mova m3, [t2q+idxq*2+ 0]
mova m4, [t2q+idxq*2+16]
mova m6, [dstq+idxq]
%if ARCH_X86_32
pxor m11, m11
%endif
punpcklbw m5, m6, m11
punpckhbw m6, m11
psllw m7, m5, 4
psubw m1, m7
psubw m3, m7
psllw m7, m6, 4
psubw m2, m7
psubw m4, m7
punpcklwd m7, m1, m3
punpckhwd m1, m3
punpcklwd m3, m2, m4
punpckhwd m2, m4
pmaddwd m7, m0
pmaddwd m1, m0
pmaddwd m3, m0
pmaddwd m2, m0
paddd m7, m10
paddd m1, m10
paddd m3, m10
paddd m2, m10
psrad m7, 11
psrad m1, 11
psrad m3, 11
psrad m2, 11
packssdw m7, m1
packssdw m3, m2
paddw m7, m5
paddw m3, m6
packuswb m7, m3
mova [dstq+idxq], m7
add idxd, 16
cmp idxd, wd
jl .loop_x
add dstq, strideq
add t1q, 384 * 2
add t2q, 384 * 2
dec hd
jg .loop_y
RET
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r15
push %r9
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x185c0, %r12
nop
nop
nop
nop
nop
xor $34700, %rcx
movl $0x61626364, (%r12)
nop
add %r10, %r10
lea addresses_A_ht+0x15c0, %rsi
lea addresses_UC_ht+0x4900, %rdi
clflush (%rsi)
nop
nop
nop
cmp %r12, %r12
mov $67, %rcx
rep movsw
nop
nop
cmp %rsi, %rsi
lea addresses_WC_ht+0xd402, %rsi
nop
inc %rbp
movl $0x61626364, (%rsi)
nop
nop
dec %r10
lea addresses_A_ht+0x11640, %rbp
nop
nop
nop
dec %r12
movw $0x6162, (%rbp)
nop
nop
nop
nop
nop
xor $7112, %rdi
lea addresses_WT_ht+0x1ef80, %rdi
clflush (%rdi)
nop
nop
nop
nop
add $11914, %rbp
mov (%rdi), %esi
nop
nop
nop
nop
nop
and %rsi, %rsi
lea addresses_A_ht+0x1f20, %r12
nop
sub %rsi, %rsi
mov $0x6162636465666768, %rbp
movq %rbp, %xmm6
movups %xmm6, (%r12)
nop
and %r10, %r10
lea addresses_WT_ht+0xd01e, %rsi
lea addresses_UC_ht+0xe1c0, %rdi
nop
nop
nop
nop
add $42235, %r15
mov $102, %rcx
rep movsl
nop
nop
nop
nop
and $25603, %rsi
lea addresses_normal_ht+0xe1a8, %r12
clflush (%r12)
nop
nop
nop
cmp %r10, %r10
movw $0x6162, (%r12)
nop
nop
inc %r12
lea addresses_UC_ht+0x3220, %r12
nop
nop
nop
nop
add %rsi, %rsi
mov (%r12), %rbp
and $64075, %r10
lea addresses_D_ht+0x166c0, %r10
cmp %r9, %r9
mov (%r10), %r15
nop
nop
nop
nop
nop
xor %r10, %r10
lea addresses_UC_ht+0x1c1c0, %r10
nop
add %rsi, %rsi
movb $0x61, (%r10)
nop
nop
sub $41862, %r10
lea addresses_D_ht+0x1e7aa, %rdi
nop
nop
nop
nop
and %r9, %r9
mov (%rdi), %si
xor %r10, %r10
lea addresses_WT_ht+0x1a4c0, %r9
nop
sub %r12, %r12
vmovups (%r9), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $0, %xmm4, %rcx
nop
nop
add $56961, %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r9
pop %r15
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r14
push %r8
push %rax
push %rbx
push %rcx
// Store
lea addresses_PSE+0x41c0, %rax
clflush (%rax)
nop
nop
nop
nop
add $12695, %r11
movl $0x51525354, (%rax)
nop
nop
nop
sub $7731, %rax
// Load
mov $0x107a410000000640, %r8
nop
nop
nop
add $21859, %r11
movups (%r8), %xmm6
vpextrq $0, %xmm6, %r14
nop
nop
sub %r13, %r13
// Store
lea addresses_WC+0x18dc0, %r14
nop
nop
nop
nop
nop
xor $43957, %rbx
movw $0x5152, (%r14)
sub %rax, %rax
// Load
lea addresses_UC+0x9cc0, %r8
nop
nop
nop
dec %r13
vmovups (%r8), %ymm2
vextracti128 $0, %ymm2, %xmm2
vpextrq $0, %xmm2, %rax
nop
cmp $61365, %rax
// Store
lea addresses_A+0x71c0, %r8
nop
nop
add %rax, %rax
mov $0x5152535455565758, %rbx
movq %rbx, %xmm1
vmovups %ymm1, (%r8)
nop
nop
nop
nop
nop
and $23137, %r14
// Store
mov $0x5247d00000000dc0, %rcx
nop
nop
nop
nop
xor %r8, %r8
mov $0x5152535455565758, %r14
movq %r14, (%rcx)
nop
xor %r11, %r11
// Load
mov $0x16afe700000001c0, %r14
nop
nop
nop
cmp $41945, %rbx
mov (%r14), %r13
nop
nop
xor $36642, %r14
// Store
lea addresses_normal+0x1fac0, %r13
nop
nop
xor $32592, %r14
movb $0x51, (%r13)
and %r13, %r13
// Faulty Load
mov $0x5247d00000000dc0, %r14
nop
inc %rcx
mov (%r14), %r13
lea oracles, %r11
and $0xff, %r13
shlq $12, %r13
mov (%r11,%r13,1), %r13
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r14
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0, 'same': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 10, 'same': False, 'type': 'addresses_PSE'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 3, 'same': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 11, 'same': False, 'type': 'addresses_WC'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 8, 'same': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 10, 'same': False, 'type': 'addresses_A'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 0, 'same': True, 'type': 'addresses_NC'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 9, 'same': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 5, 'same': False, 'type': 'addresses_normal'}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'NT': True, 'AVXalign': True, 'size': 8, 'congruent': 0, 'same': True, 'type': 'addresses_NC'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 11, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 7, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 6, 'same': True, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 3, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}, 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 2, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 5, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 8, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 4, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 1, 'same': True, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 8, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'00': 3, '79': 19}
79 79 79 79 00 79 79 79 79 79 79 79 79 00 79 79 00 79 79 79 79 79
*/
|
; A116525: a(0)=1, a(1)=1, a(n) = 11*a(n/2) for even n, and a(n) = 10*a((n-1)/2) + a((n+1)/2) for odd n >= 3.
; 0,1,11,21,121,131,231,331,1331,1341,1441,1541,2541,2641,3641,4641,14641,14651,14751,14851,15851,15951,16951,17951,27951,28051,29051,30051,40051,41051,51051,61051,161051,161061,161161,161261,162261,162361,163361,164361,174361,174461,175461,176461,186461,187461,197461,207461,307461,307561,308561,309561,319561,320561,330561,340561,440561,441561,451561,461561,561561,571561,671561,771561,1771561,1771571,1771671,1771771,1772771,1772871,1773871,1774871,1784871,1784971,1785971,1786971,1796971,1797971,1807971,1817971,1917971,1918071,1919071,1920071,1930071,1931071,1941071,1951071,2051071,2052071,2062071,2072071,2172071,2182071,2282071,2382071,3382071,3382171,3383171,3384171,3394171,3395171,3405171,3415171,3515171,3516171,3526171,3536171,3636171,3646171,3746171,3846171,4846171,4847171,4857171,4867171,4967171,4977171,5077171,5177171,6177171,6187171,6287171,6387171,7387171,7487171,8487171,9487171,19487171,19487181,19487281,19487381,19488381,19488481,19489481,19490481,19500481,19500581,19501581,19502581,19512581,19513581,19523581,19533581,19633581,19633681,19634681,19635681,19645681,19646681,19656681,19666681,19766681,19767681,19777681,19787681,19887681,19897681,19997681,20097681,21097681,21097781,21098781,21099781,21109781,21110781,21120781,21130781,21230781,21231781,21241781,21251781,21351781,21361781,21461781,21561781,22561781,22562781,22572781,22582781,22682781,22692781,22792781,22892781,23892781,23902781,24002781,24102781,25102781,25202781,26202781,27202781,37202781,37202881,37203881,37204881,37214881,37215881,37225881,37235881,37335881,37336881,37346881,37356881,37456881,37466881,37566881,37666881,38666881,38667881,38677881,38687881,38787881,38797881,38897881,38997881,39997881,40007881,40107881,40207881,41207881,41307881,42307881,43307881,53307881,53308881,53318881,53328881,53428881,53438881,53538881,53638881,54638881,54648881,54748881,54848881,55848881,55948881,56948881,57948881,67948881,67958881,68058881,68158881,69158881,69258881,70258881,71258881,81258881,81358881
mov $2,$0
mov $5,$0
lpb $2,1
mov $0,$5
sub $2,1
sub $0,$2
sub $0,1
mul $0,2
mov $3,$0
lpb $0,1
div $3,2
sub $0,$3
mov $4,10
lpe
pow $4,$0
add $1,$4
lpe
|
; A164120: Partial sums of A162396.
; 5,7,17,21,41,49,89,105,185,217,377,441,761,889,1529,1785,3065,3577,6137,7161,12281,14329,24569,28665,49145,57337,98297,114681,196601,229369,393209,458745,786425,917497,1572857,1835001,3145721,3670009,6291449,7340025,12582905,14680057,25165817,29360121,50331641,58720249,100663289,117440505,201326585,234881017,402653177,469762041,805306361,939524089,1610612729,1879048185,3221225465,3758096377,6442450937,7516192761,12884901881,15032385529,25769803769,30064771065,51539607545,60129542137,103079215097,120259084281,206158430201,240518168569,412316860409,481036337145,824633720825,962072674297,1649267441657,1924145348601,3298534883321,3848290697209,6597069766649,7696581394425,13194139533305,15393162788857,26388279066617,30786325577721,52776558133241,61572651155449,105553116266489,123145302310905,211106232532985,246290604621817,422212465065977,492581209243641,844424930131961,985162418487289,1688849860263929,1970324836974585,3377699720527865,3940649673949177,6755399441055737,7881299347898361
mov $1,$0
mod $0,2
lpb $1
mul $0,2
add $0,6
sub $1,2
lpe
mul $0,2
add $0,5
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r8
push %rax
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x12581, %rsi
lea addresses_normal_ht+0x1c181, %rdi
nop
nop
nop
cmp %rbp, %rbp
mov $83, %rcx
rep movsq
nop
nop
nop
xor $25855, %rbx
lea addresses_normal_ht+0x3381, %r10
clflush (%r10)
inc %rcx
and $0xffffffffffffffc0, %r10
movntdqa (%r10), %xmm6
vpextrq $0, %xmm6, %rbx
nop
nop
nop
nop
nop
sub $48276, %rbp
lea addresses_normal_ht+0x150b3, %rcx
nop
cmp $42356, %r8
mov $0x6162636465666768, %rbx
movq %rbx, %xmm5
movups %xmm5, (%rcx)
nop
nop
nop
nop
xor $37172, %rbp
lea addresses_D_ht+0x16981, %rsi
lea addresses_UC_ht+0x9ab1, %rdi
nop
nop
and %rax, %rax
mov $53, %rcx
rep movsw
inc %rbp
lea addresses_normal_ht+0x1c5f4, %rsi
nop
nop
nop
nop
nop
cmp %rdi, %rdi
movw $0x6162, (%rsi)
nop
nop
nop
nop
nop
dec %rbp
lea addresses_UC_ht+0x1abe9, %rsi
lea addresses_UC_ht+0xcd8b, %rdi
cmp %rax, %rax
mov $125, %rcx
rep movsq
nop
nop
nop
nop
cmp $24323, %r8
lea addresses_normal_ht+0x11e41, %rbp
dec %r8
mov (%rbp), %rdi
nop
nop
nop
nop
add $12997, %rbx
lea addresses_WT_ht+0x17581, %rbx
nop
nop
nop
nop
sub $38281, %rax
movw $0x6162, (%rbx)
dec %rbx
lea addresses_A_ht+0x17181, %rbx
nop
nop
nop
nop
nop
sub %rcx, %rcx
mov $0x6162636465666768, %rsi
movq %rsi, %xmm7
movups %xmm7, (%rbx)
nop
nop
inc %rbp
lea addresses_A_ht+0x1521, %rsi
lea addresses_WC_ht+0x13591, %rdi
nop
nop
nop
sub $1243, %rax
mov $85, %rcx
rep movsl
dec %r8
lea addresses_D_ht+0x2ec1, %rbp
nop
nop
nop
add $40717, %rbx
mov $0x6162636465666768, %rdi
movq %rdi, %xmm2
movups %xmm2, (%rbp)
xor $23921, %r8
lea addresses_D_ht+0x12679, %r10
dec %rbp
mov $0x6162636465666768, %rdi
movq %rdi, %xmm3
vmovups %ymm3, (%r10)
nop
nop
nop
nop
nop
xor %rsi, %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r8
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r14
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
// REPMOV
mov $0x781, %rsi
lea addresses_WT+0xd397, %rdi
nop
nop
nop
nop
nop
and $42570, %rax
mov $88, %rcx
rep movsl
nop
nop
nop
nop
nop
sub %r11, %r11
// Faulty Load
lea addresses_US+0x5981, %rax
nop
nop
nop
nop
nop
cmp %r14, %r14
movups (%rax), %xmm1
vpextrq $1, %xmm1, %rsi
lea oracles, %r11
and $0xff, %rsi
shlq $12, %rsi
mov (%r11,%rsi,1), %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r14
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_US'}, 'OP': 'LOAD'}
{'src': {'congruent': 8, 'same': False, 'type': 'addresses_P'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_WT'}}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_US'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_normal_ht'}}
{'src': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 16, 'NT': True, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_normal_ht'}}
{'src': {'congruent': 11, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 3, 'same': False, 'type': 'addresses_UC_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_normal_ht'}}
{'src': {'congruent': 3, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_UC_ht'}}
{'src': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': True, 'size': 2, 'NT': False, 'type': 'addresses_WT_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_A_ht'}}
{'src': {'congruent': 4, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_WC_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_D_ht'}}
{'00': 118}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
/*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2016 The Khronos Group Inc.
* Copyright (c) 2016 Imagination Technologies Ltd.
*
* 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.
*
*//*!
* \file
* \brief Robust Vertex Buffer Access Tests
*//*--------------------------------------------------------------------*/
#include "vktRobustnessVertexAccessTests.hpp"
#include "vktRobustnessUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkBuilderUtil.hpp"
#include "vkImageUtil.hpp"
#include "vkMemUtil.hpp"
#include "vkPrograms.hpp"
#include "vkQueryUtil.hpp"
#include "vkRef.hpp"
#include "vkRefUtil.hpp"
#include "vkTypeUtil.hpp"
#include "tcuTestLog.hpp"
#include "deMath.h"
#include "deUniquePtr.hpp"
#include <vector>
namespace vkt
{
namespace robustness
{
using namespace vk;
typedef std::vector<VkVertexInputBindingDescription> BindingList;
typedef std::vector<VkVertexInputAttributeDescription> AttributeList;
class VertexAccessTest : public vkt::TestCase
{
public:
VertexAccessTest (tcu::TestContext& testContext,
const std::string& name,
const std::string& description,
VkFormat inputFormat,
deUint32 numVertexValues,
deUint32 numInstanceValues,
deUint32 numVertices,
deUint32 numInstances);
virtual ~VertexAccessTest (void) {}
void initPrograms (SourceCollections& programCollection) const;
TestInstance* createInstance (Context& context) const = 0;
protected:
const VkFormat m_inputFormat;
const deUint32 m_numVertexValues;
const deUint32 m_numInstanceValues;
const deUint32 m_numVertices;
const deUint32 m_numInstances;
};
class DrawAccessTest : public VertexAccessTest
{
public:
DrawAccessTest (tcu::TestContext& testContext,
const std::string& name,
const std::string& description,
VkFormat inputFormat,
deUint32 numVertexValues,
deUint32 numInstanceValues,
deUint32 numVertices,
deUint32 numInstances);
virtual ~DrawAccessTest (void) {}
TestInstance* createInstance (Context& context) const;
protected:
};
class DrawIndexedAccessTest : public VertexAccessTest
{
public:
enum IndexConfig
{
INDEX_CONFIG_LAST_INDEX_OUT_OF_BOUNDS,
INDEX_CONFIG_INDICES_OUT_OF_BOUNDS,
INDEX_CONFIG_TRIANGLE_OUT_OF_BOUNDS,
INDEX_CONFIG_COUNT
};
const static std::vector<deUint32> s_indexConfigs[INDEX_CONFIG_COUNT];
DrawIndexedAccessTest (tcu::TestContext& testContext,
const std::string& name,
const std::string& description,
VkFormat inputFormat,
IndexConfig indexConfig);
virtual ~DrawIndexedAccessTest (void) {}
TestInstance* createInstance (Context& context) const;
protected:
const IndexConfig m_indexConfig;
};
class VertexAccessInstance : public vkt::TestInstance
{
public:
VertexAccessInstance (Context& context,
Move<VkDevice> device,
VkFormat inputFormat,
deUint32 numVertexValues,
deUint32 numInstanceValues,
deUint32 numVertices,
deUint32 numInstances,
const std::vector<deUint32>& indices);
virtual ~VertexAccessInstance (void) {}
virtual tcu::TestStatus iterate (void);
virtual bool verifyResult (void);
private:
bool isValueWithinVertexBufferOrZero (void* vertexBuffer, VkDeviceSize vertexBufferSize, const void* value, deUint32 valueIndexa);
protected:
static bool isExpectedValueFromVertexBuffer (const void* vertexBuffer, deUint32 vertexIndex, VkFormat vertexFormat, const void* value);
static VkDeviceSize getBufferSizeInBytes (deUint32 numScalars, VkFormat format);
virtual void initVertexIds (deUint32 *indicesPtr, size_t indexCount) = 0;
virtual deUint32 getIndex (deUint32 vertexNum) const = 0;
Move<VkDevice> m_device;
const VkFormat m_inputFormat;
const deUint32 m_numVertexValues;
const deUint32 m_numInstanceValues;
const deUint32 m_numVertices;
const deUint32 m_numInstances;
AttributeList m_vertexInputAttributes;
BindingList m_vertexInputBindings;
Move<VkBuffer> m_vertexRateBuffer;
VkDeviceSize m_vertexRateBufferSize;
de::MovePtr<Allocation> m_vertexRateBufferAlloc;
VkDeviceSize m_vertexRateBufferAllocSize;
Move<VkBuffer> m_instanceRateBuffer;
VkDeviceSize m_instanceRateBufferSize;
de::MovePtr<Allocation> m_instanceRateBufferAlloc;
VkDeviceSize m_instanceRateBufferAllocSize;
Move<VkBuffer> m_vertexNumBuffer;
VkDeviceSize m_vertexNumBufferSize;
de::MovePtr<Allocation> m_vertexNumBufferAlloc;
Move<VkBuffer> m_indexBuffer;
VkDeviceSize m_indexBufferSize;
de::MovePtr<Allocation> m_indexBufferAlloc;
Move<VkBuffer> m_outBuffer; // SSBO
VkDeviceSize m_outBufferSize;
de::MovePtr<Allocation> m_outBufferAlloc;
Move<VkDescriptorPool> m_descriptorPool;
Move<VkDescriptorSetLayout> m_descriptorSetLayout;
Move<VkDescriptorSet> m_descriptorSet;
Move<VkFence> m_fence;
VkQueue m_queue;
de::MovePtr<GraphicsEnvironment> m_graphicsTestEnvironment;
};
class DrawAccessInstance : public VertexAccessInstance
{
public:
DrawAccessInstance (Context& context,
Move<VkDevice> device,
VkFormat inputFormat,
deUint32 numVertexValues,
deUint32 numInstanceValues,
deUint32 numVertices,
deUint32 numInstances);
virtual ~DrawAccessInstance (void) {}
protected:
virtual void initVertexIds (deUint32 *indicesPtr, size_t indexCount);
virtual deUint32 getIndex (deUint32 vertexNum) const;
};
class DrawIndexedAccessInstance : public VertexAccessInstance
{
public:
DrawIndexedAccessInstance (Context& context,
Move<VkDevice> device,
VkFormat inputFormat,
deUint32 numVertexValues,
deUint32 numInstanceValues,
deUint32 numVertices,
deUint32 numInstances,
const std::vector<deUint32>& indices);
virtual ~DrawIndexedAccessInstance (void) {}
protected:
virtual void initVertexIds (deUint32 *indicesPtr, size_t indexCount);
virtual deUint32 getIndex (deUint32 vertexNum) const;
const std::vector<deUint32> m_indices;
};
// VertexAccessTest
VertexAccessTest::VertexAccessTest (tcu::TestContext& testContext,
const std::string& name,
const std::string& description,
VkFormat inputFormat,
deUint32 numVertexValues,
deUint32 numInstanceValues,
deUint32 numVertices,
deUint32 numInstances)
: vkt::TestCase (testContext, name, description)
, m_inputFormat (inputFormat)
, m_numVertexValues (numVertexValues)
, m_numInstanceValues (numInstanceValues)
, m_numVertices (numVertices)
, m_numInstances (numInstances)
{
}
void VertexAccessTest::initPrograms (SourceCollections& programCollection) const
{
std::ostringstream attributeDeclaration;
std::ostringstream attributeUse;
std::ostringstream vertexShaderSource;
std::ostringstream fragmentShaderSource;
std::ostringstream attributeTypeStr;
const int numChannels = getNumUsedChannels(mapVkFormat(m_inputFormat).order);
const deUint32 numScalarsPerVertex = numChannels * 3; // Use 3 identical attributes
deUint32 numValues = 0;
const bool isR64 = (m_inputFormat == VK_FORMAT_R64_UINT || m_inputFormat == VK_FORMAT_R64_SINT);
if (numChannels == 1)
{
if (isUintFormat(m_inputFormat))
attributeTypeStr << "uint";
else if (isIntFormat(m_inputFormat))
attributeTypeStr << "int";
else
attributeTypeStr << "float";
attributeTypeStr << (isR64 ? "64_t" : " ");
}
else
{
if (isUintFormat(m_inputFormat))
attributeTypeStr << "uvec";
else if (isIntFormat(m_inputFormat))
attributeTypeStr << "ivec";
else
attributeTypeStr << "vec";
attributeTypeStr << numChannels;
}
for (int attrNdx = 0; attrNdx < 3; attrNdx++)
{
attributeDeclaration << "layout(location = " << attrNdx << ") in " << attributeTypeStr.str() << " attr" << attrNdx << ";\n";
for (int chanNdx = 0; chanNdx < numChannels; chanNdx++)
{
attributeUse << "\toutData[(gl_InstanceIndex * " << numScalarsPerVertex * m_numVertices
<< ") + (vertexNum * " << numScalarsPerVertex << " + " << numValues++ << ")] = attr" << attrNdx;
if (numChannels == 1)
attributeUse << ";\n";
else
attributeUse << "[" << chanNdx << "];\n";
}
}
attributeDeclaration << "layout(location = 3) in int vertexNum;\n";
attributeUse << "\n";
std::string outType = "";
if (isUintFormat(m_inputFormat))
outType = "uint";
else if (isIntFormat(m_inputFormat))
outType = "int";
else
outType = "float";
outType += isR64 ? "64_t" : "";
std::string extensions = "";
std::string version = "#version 310 es\n";
if (isR64)
{
extensions = "#extension GL_EXT_shader_explicit_arithmetic_types_int64 : require\n";
version = "#version 440\n";
}
vertexShaderSource <<
version <<
"precision highp float;\n"
<< extensions
<< attributeDeclaration.str() <<
"layout(set = 0, binding = 0, std430) buffer outBuffer\n"
"{\n"
"\t" << outType << " outData[" << (m_numVertices * numValues) * m_numInstances << "];\n"
"};\n\n"
"void main (void)\n"
"{\n"
<< attributeUse.str() <<
"\tgl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n"
"}\n";
programCollection.glslSources.add("vertex") << glu::VertexSource(vertexShaderSource.str());
fragmentShaderSource <<
"#version 310 es\n"
"precision highp float;\n"
"layout(location = 0) out vec4 fragColor;\n"
"void main (void)\n"
"{\n"
"\tfragColor = vec4(1.0);\n"
"}\n";
programCollection.glslSources.add("fragment") << glu::FragmentSource(fragmentShaderSource.str());
}
// DrawAccessTest
DrawAccessTest::DrawAccessTest (tcu::TestContext& testContext,
const std::string& name,
const std::string& description,
VkFormat inputFormat,
deUint32 numVertexValues,
deUint32 numInstanceValues,
deUint32 numVertices,
deUint32 numInstances)
: VertexAccessTest (testContext, name, description, inputFormat, numVertexValues, numInstanceValues, numVertices, numInstances)
{
}
TestInstance* DrawAccessTest::createInstance (Context& context) const
{
Move<VkDevice> device = createRobustBufferAccessDevice(context);
return new DrawAccessInstance(context,
device,
m_inputFormat,
m_numVertexValues,
m_numInstanceValues,
m_numVertices,
m_numInstances);
}
// DrawIndexedAccessTest
const deUint32 lastIndexOutOfBounds[] =
{
0, 1, 2, 3, 4, 100, // Indices of 100 and above are out of bounds
};
const deUint32 indicesOutOfBounds[] =
{
0, 100, 2, 101, 3, 102, // Indices of 100 and above are out of bounds
};
const deUint32 triangleOutOfBounds[] =
{
100, 101, 102, 3, 4, 5, // Indices of 100 and above are out of bounds
};
const std::vector<deUint32> DrawIndexedAccessTest::s_indexConfigs[INDEX_CONFIG_COUNT] =
{
std::vector<deUint32>(lastIndexOutOfBounds, lastIndexOutOfBounds + DE_LENGTH_OF_ARRAY(lastIndexOutOfBounds)),
std::vector<deUint32>(indicesOutOfBounds, indicesOutOfBounds + DE_LENGTH_OF_ARRAY(indicesOutOfBounds)),
std::vector<deUint32>(triangleOutOfBounds, triangleOutOfBounds + DE_LENGTH_OF_ARRAY(triangleOutOfBounds)),
};
DrawIndexedAccessTest::DrawIndexedAccessTest (tcu::TestContext& testContext,
const std::string& name,
const std::string& description,
VkFormat inputFormat,
IndexConfig indexConfig)
: VertexAccessTest (testContext,
name,
description,
inputFormat,
getNumUsedChannels(mapVkFormat(inputFormat).order) * (deUint32)s_indexConfigs[indexConfig].size() * 2, // numVertexValues
getNumUsedChannels(mapVkFormat(inputFormat).order), // numInstanceValues
(deUint32)s_indexConfigs[indexConfig].size(), // numVertices
1) // numInstances
, m_indexConfig (indexConfig)
{
}
TestInstance* DrawIndexedAccessTest::createInstance (Context& context) const
{
Move<VkDevice> device = createRobustBufferAccessDevice(context);
return new DrawIndexedAccessInstance(context,
device,
m_inputFormat,
m_numVertexValues,
m_numInstanceValues,
m_numVertices,
m_numInstances,
s_indexConfigs[m_indexConfig]);
}
// VertexAccessInstance
VertexAccessInstance::VertexAccessInstance (Context& context,
Move<VkDevice> device,
VkFormat inputFormat,
deUint32 numVertexValues,
deUint32 numInstanceValues,
deUint32 numVertices,
deUint32 numInstances,
const std::vector<deUint32>& indices)
: vkt::TestInstance (context)
, m_device (device)
, m_inputFormat (inputFormat)
, m_numVertexValues (numVertexValues)
, m_numInstanceValues (numInstanceValues)
, m_numVertices (numVertices)
, m_numInstances (numInstances)
{
const DeviceInterface& vk = context.getDeviceInterface();
const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex();
SimpleAllocator memAlloc (vk, *m_device, getPhysicalDeviceMemoryProperties(m_context.getInstanceInterface(), m_context.getPhysicalDevice()));
const deUint32 formatSizeInBytes = tcu::getPixelSize(mapVkFormat(m_inputFormat));
// Check storage support
if (!context.getDeviceFeatures().vertexPipelineStoresAndAtomics)
{
TCU_THROW(NotSupportedError, "Stores not supported in vertex stage");
}
if (m_inputFormat == VK_FORMAT_R64_UINT || m_inputFormat == VK_FORMAT_R64_SINT)
{
const VkFormatProperties formatProperties = getPhysicalDeviceFormatProperties(context.getInstanceInterface(), context.getPhysicalDevice(), m_inputFormat);
context.requireDeviceFunctionality("VK_EXT_shader_image_atomic_int64");
if ((formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) != VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT)
TCU_THROW(NotSupportedError, "VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT not supported");
}
const VkVertexInputAttributeDescription attributes[] =
{
// input rate: vertex
{
0u, // deUint32 location;
0u, // deUint32 binding;
m_inputFormat, // VkFormat format;
0u, // deUint32 offset;
},
{
1u, // deUint32 location;
0u, // deUint32 binding;
m_inputFormat, // VkFormat format;
formatSizeInBytes, // deUint32 offset;
},
// input rate: instance
{
2u, // deUint32 location;
1u, // deUint32 binding;
m_inputFormat, // VkFormat format;
0u, // deUint32 offset;
},
// Attribute for vertex number
{
3u, // deUint32 location;
2u, // deUint32 binding;
VK_FORMAT_R32_SINT, // VkFormat format;
0, // deUint32 offset;
},
};
const VkVertexInputBindingDescription bindings[] =
{
{
0u, // deUint32 binding;
formatSizeInBytes * 2, // deUint32 stride;
VK_VERTEX_INPUT_RATE_VERTEX // VkVertexInputRate inputRate;
},
{
1u, // deUint32 binding;
formatSizeInBytes, // deUint32 stride;
VK_VERTEX_INPUT_RATE_INSTANCE // VkVertexInputRate inputRate;
},
{
2u, // deUint32 binding;
sizeof(deInt32), // deUint32 stride;
VK_VERTEX_INPUT_RATE_VERTEX // VkVertexInputRate inputRate;
},
};
m_vertexInputBindings = std::vector<VkVertexInputBindingDescription>(bindings, bindings + DE_LENGTH_OF_ARRAY(bindings));
m_vertexInputAttributes = std::vector<VkVertexInputAttributeDescription>(attributes, attributes + DE_LENGTH_OF_ARRAY(attributes));
// Create vertex buffer for vertex input rate
{
VkMemoryRequirements bufferMemoryReqs;
m_vertexRateBufferSize = getBufferSizeInBytes(m_numVertexValues, m_inputFormat); // All formats used in this test suite are 32-bit based.
const VkBufferCreateInfo vertexRateBufferParams =
{
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // VkBufferCreateFlags flags;
m_vertexRateBufferSize, // VkDeviceSize size;
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, // VkBufferUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
1u, // deUint32 queueFamilyIndexCount;
&queueFamilyIndex // const deUint32* pQueueFamilyIndices;
};
m_vertexRateBuffer = createBuffer(vk, *m_device, &vertexRateBufferParams);
bufferMemoryReqs = getBufferMemoryRequirements(vk, *m_device, *m_vertexRateBuffer);
m_vertexRateBufferAllocSize = bufferMemoryReqs.size;
m_vertexRateBufferAlloc = memAlloc.allocate(bufferMemoryReqs, MemoryRequirement::HostVisible);
VK_CHECK(vk.bindBufferMemory(*m_device, *m_vertexRateBuffer, m_vertexRateBufferAlloc->getMemory(), m_vertexRateBufferAlloc->getOffset()));
populateBufferWithTestValues(m_vertexRateBufferAlloc->getHostPtr(), (deUint32)m_vertexRateBufferAllocSize, m_inputFormat);
flushMappedMemoryRange(vk, *m_device, m_vertexRateBufferAlloc->getMemory(), m_vertexRateBufferAlloc->getOffset(), VK_WHOLE_SIZE);
}
// Create vertex buffer for instance input rate
{
VkMemoryRequirements bufferMemoryReqs;
m_instanceRateBufferSize = getBufferSizeInBytes(m_numInstanceValues, m_inputFormat); // All formats used in this test suite are 32-bit based.
const VkBufferCreateInfo instanceRateBufferParams =
{
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // VkBufferCreateFlags flags;
m_instanceRateBufferSize, // VkDeviceSize size;
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, // VkBufferUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
1u, // deUint32 queueFamilyIndexCount;
&queueFamilyIndex // const deUint32* pQueueFamilyIndices;
};
m_instanceRateBuffer = createBuffer(vk, *m_device, &instanceRateBufferParams);
bufferMemoryReqs = getBufferMemoryRequirements(vk, *m_device, *m_instanceRateBuffer);
m_instanceRateBufferAllocSize = bufferMemoryReqs.size;
m_instanceRateBufferAlloc = memAlloc.allocate(bufferMemoryReqs, MemoryRequirement::HostVisible);
VK_CHECK(vk.bindBufferMemory(*m_device, *m_instanceRateBuffer, m_instanceRateBufferAlloc->getMemory(), m_instanceRateBufferAlloc->getOffset()));
populateBufferWithTestValues(m_instanceRateBufferAlloc->getHostPtr(), (deUint32)m_instanceRateBufferAllocSize, m_inputFormat);
flushMappedMemoryRange(vk, *m_device, m_instanceRateBufferAlloc->getMemory(), m_instanceRateBufferAlloc->getOffset(), VK_WHOLE_SIZE);
}
// Create vertex buffer that stores the vertex number (from 0 to m_numVertices - 1)
{
m_vertexNumBufferSize = 128 * sizeof(deInt32); // Allocate enough device memory for all indices (0 to 127).
const VkBufferCreateInfo vertexNumBufferParams =
{
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // VkBufferCreateFlags flags;
m_vertexNumBufferSize, // VkDeviceSize size;
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, // VkBufferUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
1u, // deUint32 queueFamilyIndexCount;
&queueFamilyIndex // const deUint32* pQueueFamilyIndices;
};
m_vertexNumBuffer = createBuffer(vk, *m_device, &vertexNumBufferParams);
m_vertexNumBufferAlloc = memAlloc.allocate(getBufferMemoryRequirements(vk, *m_device, *m_vertexNumBuffer), MemoryRequirement::HostVisible);
VK_CHECK(vk.bindBufferMemory(*m_device, *m_vertexNumBuffer, m_vertexNumBufferAlloc->getMemory(), m_vertexNumBufferAlloc->getOffset()));
}
// Create index buffer if required
if (!indices.empty())
{
m_indexBufferSize = sizeof(deUint32) * indices.size();
const VkBufferCreateInfo indexBufferParams =
{
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // VkBufferCreateFlags flags;
m_indexBufferSize, // VkDeviceSize size;
VK_BUFFER_USAGE_INDEX_BUFFER_BIT, // VkBufferUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
1u, // deUint32 queueFamilyIndexCount;
&queueFamilyIndex // const deUint32* pQueueFamilyIndices;
};
m_indexBuffer = createBuffer(vk, *m_device, &indexBufferParams);
m_indexBufferAlloc = memAlloc.allocate(getBufferMemoryRequirements(vk, *m_device, *m_indexBuffer), MemoryRequirement::HostVisible);
VK_CHECK(vk.bindBufferMemory(*m_device, *m_indexBuffer, m_indexBufferAlloc->getMemory(), m_indexBufferAlloc->getOffset()));
deMemcpy(m_indexBufferAlloc->getHostPtr(), indices.data(), (size_t)m_indexBufferSize);
flushMappedMemoryRange(vk, *m_device, m_indexBufferAlloc->getMemory(), m_indexBufferAlloc->getOffset(), VK_WHOLE_SIZE);
}
// Create result ssbo
{
const int numChannels = getNumUsedChannels(mapVkFormat(m_inputFormat).order);
m_outBufferSize = getBufferSizeInBytes(m_numVertices * m_numInstances * numChannels * 3, VK_FORMAT_R32_UINT);
const VkBufferCreateInfo outBufferParams =
{
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // VkBufferCreateFlags flags;
m_outBufferSize, // VkDeviceSize size;
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, // VkBufferUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
1u, // deUint32 queueFamilyIndexCount;
&queueFamilyIndex // const deUint32* pQueueFamilyIndices;
};
m_outBuffer = createBuffer(vk, *m_device, &outBufferParams);
m_outBufferAlloc = memAlloc.allocate(getBufferMemoryRequirements(vk, *m_device, *m_outBuffer), MemoryRequirement::HostVisible);
VK_CHECK(vk.bindBufferMemory(*m_device, *m_outBuffer, m_outBufferAlloc->getMemory(), m_outBufferAlloc->getOffset()));
deMemset(m_outBufferAlloc->getHostPtr(), 0xFF, (size_t)m_outBufferSize);
flushMappedMemoryRange(vk, *m_device, m_outBufferAlloc->getMemory(), m_outBufferAlloc->getOffset(), VK_WHOLE_SIZE);
}
// Create descriptor set data
{
DescriptorPoolBuilder descriptorPoolBuilder;
descriptorPoolBuilder.addType(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u);
m_descriptorPool = descriptorPoolBuilder.build(vk, *m_device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u);
DescriptorSetLayoutBuilder setLayoutBuilder;
setLayoutBuilder.addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_VERTEX_BIT);
m_descriptorSetLayout = setLayoutBuilder.build(vk, *m_device);
const VkDescriptorSetAllocateInfo descriptorSetAllocateInfo =
{
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
*m_descriptorPool, // VkDescriptorPool desciptorPool;
1u, // deUint32 setLayoutCount;
&m_descriptorSetLayout.get() // const VkDescriptorSetLayout* pSetLayouts;
};
m_descriptorSet = allocateDescriptorSet(vk, *m_device, &descriptorSetAllocateInfo);
const VkDescriptorBufferInfo outBufferDescriptorInfo = makeDescriptorBufferInfo(*m_outBuffer, 0ull, VK_WHOLE_SIZE);
DescriptorSetUpdateBuilder setUpdateBuilder;
setUpdateBuilder.writeSingle(*m_descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, &outBufferDescriptorInfo);
setUpdateBuilder.update(vk, *m_device);
}
// Create fence
{
const VkFenceCreateInfo fenceParams =
{
VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u // VkFenceCreateFlags flags;
};
m_fence = createFence(vk, *m_device, &fenceParams);
}
// Get queue
vk.getDeviceQueue(*m_device, queueFamilyIndex, 0, &m_queue);
// Setup graphics test environment
{
GraphicsEnvironment::DrawConfig drawConfig;
drawConfig.vertexBuffers.push_back(*m_vertexRateBuffer);
drawConfig.vertexBuffers.push_back(*m_instanceRateBuffer);
drawConfig.vertexBuffers.push_back(*m_vertexNumBuffer);
drawConfig.vertexCount = m_numVertices;
drawConfig.instanceCount = m_numInstances;
drawConfig.indexBuffer = *m_indexBuffer;
drawConfig.indexCount = (deUint32)(m_indexBufferSize / sizeof(deUint32));
m_graphicsTestEnvironment = de::MovePtr<GraphicsEnvironment>(new GraphicsEnvironment(m_context,
*m_device,
*m_descriptorSetLayout,
*m_descriptorSet,
GraphicsEnvironment::VertexBindings(bindings, bindings + DE_LENGTH_OF_ARRAY(bindings)),
GraphicsEnvironment::VertexAttributes(attributes, attributes + DE_LENGTH_OF_ARRAY(attributes)),
drawConfig));
}
}
tcu::TestStatus VertexAccessInstance::iterate (void)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const vk::VkCommandBuffer cmdBuffer = m_graphicsTestEnvironment->getCommandBuffer();
// Initialize vertex ids
{
deUint32 *bufferPtr = reinterpret_cast<deUint32*>(m_vertexNumBufferAlloc->getHostPtr());
deMemset(bufferPtr, 0, (size_t)m_vertexNumBufferSize);
initVertexIds(bufferPtr, (size_t)(m_vertexNumBufferSize / sizeof(deUint32)));
flushMappedMemoryRange(vk, *m_device, m_vertexNumBufferAlloc->getMemory(), m_vertexNumBufferAlloc->getOffset(), VK_WHOLE_SIZE);
}
// Submit command buffer
{
const VkSubmitInfo submitInfo =
{
VK_STRUCTURE_TYPE_SUBMIT_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // deUint32 waitSemaphoreCount;
DE_NULL, // const VkSemaphore* pWaitSemaphores;
DE_NULL, // const VkPIpelineStageFlags* pWaitDstStageMask;
1u, // deUint32 commandBufferCount;
&cmdBuffer, // const VkCommandBuffer* pCommandBuffers;
0u, // deUint32 signalSemaphoreCount;
DE_NULL // const VkSemaphore* pSignalSemaphores;
};
VK_CHECK(vk.resetFences(*m_device, 1, &m_fence.get()));
VK_CHECK(vk.queueSubmit(m_queue, 1, &submitInfo, *m_fence));
VK_CHECK(vk.waitForFences(*m_device, 1, &m_fence.get(), true, ~(0ull) /* infinity */));
}
// Prepare result buffer for read
{
const VkMappedMemoryRange outBufferRange =
{
VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, // VkStructureType sType;
DE_NULL, // const void* pNext;
m_outBufferAlloc->getMemory(), // VkDeviceMemory mem;
0ull, // VkDeviceSize offset;
m_outBufferSize, // VkDeviceSize size;
};
VK_CHECK(vk.invalidateMappedMemoryRanges(*m_device, 1u, &outBufferRange));
}
if (verifyResult())
return tcu::TestStatus::pass("All values OK");
else
return tcu::TestStatus::fail("Invalid value(s) found");
}
bool VertexAccessInstance::verifyResult (void)
{
std::ostringstream logMsg;
const DeviceInterface& vk = m_context.getDeviceInterface();
tcu::TestLog& log = m_context.getTestContext().getLog();
const deUint32 numChannels = getNumUsedChannels(mapVkFormat(m_inputFormat).order);
const deUint32 numScalarsPerVertex = numChannels * 3; // Use 3 identical attributes
void* outDataPtr = m_outBufferAlloc->getHostPtr();
const deUint32 outValueSize = static_cast<deUint32>((m_inputFormat == VK_FORMAT_R64_UINT || m_inputFormat == VK_FORMAT_R64_SINT)
? sizeof(deUint64) : sizeof(deUint32));
bool allOk = true;
const VkMappedMemoryRange outBufferRange =
{
VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, // VkStructureType sType;
DE_NULL, // const void* pNext;
m_outBufferAlloc->getMemory(), // VkDeviceMemory mem;
m_outBufferAlloc->getOffset(), // VkDeviceSize offset;
m_outBufferSize, // VkDeviceSize size;
};
VK_CHECK(vk.invalidateMappedMemoryRanges(*m_device, 1u, &outBufferRange));
for (deUint32 valueNdx = 0; valueNdx < m_outBufferSize / outValueSize; valueNdx++)
{
deUint32 numInBufferValues;
void* inBufferPtr;
VkDeviceSize inBufferAllocSize;
deUint32 inBufferValueIndex;
bool isOutOfBoundsAccess = false;
const deUint32 attributeIndex = (valueNdx / numChannels) % 3;
deUint32* ptr32 = (deUint32*)outDataPtr;
deUint64* ptr64 = (deUint64*)outDataPtr;
const void* outValuePtr = ((m_inputFormat == VK_FORMAT_R64_UINT || m_inputFormat == VK_FORMAT_R64_SINT) ?
(void*)(ptr64 + valueNdx) :
(void*)(ptr32 + valueNdx));
if (attributeIndex == 2)
{
// Instance rate
const deUint32 elementIndex = valueNdx / (numScalarsPerVertex * m_numVertices); // instance id
numInBufferValues = m_numInstanceValues;
inBufferPtr = m_instanceRateBufferAlloc->getHostPtr();
inBufferAllocSize = m_instanceRateBufferAllocSize;
inBufferValueIndex = (elementIndex * numChannels) + (valueNdx % numScalarsPerVertex) - (2 * numChannels);
}
else
{
// Vertex rate
const deUint32 vertexNdx = valueNdx / numScalarsPerVertex;
const deUint32 instanceNdx = vertexNdx / m_numVertices;
const deUint32 elementIndex = valueNdx / numScalarsPerVertex; // vertex id
numInBufferValues = m_numVertexValues;
inBufferPtr = m_vertexRateBufferAlloc->getHostPtr();
inBufferAllocSize = m_vertexRateBufferAllocSize;
inBufferValueIndex = (getIndex(elementIndex) * (numChannels * 2)) + (valueNdx % numScalarsPerVertex) - instanceNdx * (m_numVertices * numChannels * 2);
// Binding 0 contains two attributes, so bounds checking for attribute 0 must also consider attribute 1 to determine if the binding is out of bounds.
if ((attributeIndex == 0) && (numInBufferValues >= numChannels))
numInBufferValues -= numChannels;
}
isOutOfBoundsAccess = (inBufferValueIndex >= numInBufferValues);
const deInt32 distanceToOutOfBounds = (deInt32)outValueSize * ((deInt32)numInBufferValues - (deInt32)inBufferValueIndex);
if (!isOutOfBoundsAccess && (distanceToOutOfBounds < 16))
isOutOfBoundsAccess = (((inBufferValueIndex / numChannels) + 1) * numChannels > numInBufferValues);
// Log value information
{
// Vertex separator
if (valueNdx && valueNdx % numScalarsPerVertex == 0)
logMsg << "\n";
logMsg << "\n" << valueNdx << ": Value ";
// Result index and value
if (m_inputFormat == VK_FORMAT_A2B10G10R10_UNORM_PACK32)
logValue(logMsg, outValuePtr, VK_FORMAT_R32_SFLOAT, 4);
else
logValue(logMsg, outValuePtr, m_inputFormat, 4);
// Attribute name
logMsg << "\tfrom attr" << attributeIndex;
if (numChannels > 1)
logMsg << "[" << valueNdx % numChannels << "]";
// Input rate
if (attributeIndex == 2)
logMsg << "\tinstance rate";
else
logMsg << "\tvertex rate";
}
if (isOutOfBoundsAccess)
{
const bool isValidValue = isValueWithinVertexBufferOrZero(inBufferPtr, inBufferAllocSize, outValuePtr, inBufferValueIndex);
logMsg << "\t(out of bounds)";
if (!isValidValue)
{
// Check if we are satisfying the [0, 0, 0, x] pattern, where x may be either 0 or 1,
// or the maximum representable positive integer value (if the format is integer-based).
const bool canMatchVec4Pattern = ((valueNdx % numChannels == 3) || m_inputFormat == VK_FORMAT_A2B10G10R10_UNORM_PACK32);
bool matchesVec4Pattern = false;
if (canMatchVec4Pattern)
{
if (m_inputFormat == VK_FORMAT_A2B10G10R10_UNORM_PACK32)
matchesVec4Pattern = verifyOutOfBoundsVec4(outValuePtr, m_inputFormat);
else
matchesVec4Pattern = verifyOutOfBoundsVec4(((deUint32*)outValuePtr) - 3, m_inputFormat);
}
if (!canMatchVec4Pattern || !matchesVec4Pattern)
{
logMsg << ", Failed: expected a value within the buffer range or 0";
if (canMatchVec4Pattern)
logMsg << ", or the [0, 0, 0, x] pattern";
allOk = false;
}
}
}
else if (!isExpectedValueFromVertexBuffer(inBufferPtr, inBufferValueIndex, m_inputFormat, outValuePtr))
{
logMsg << ", Failed: unexpected value";
allOk = false;
}
}
log << tcu::TestLog::Message << logMsg.str() << tcu::TestLog::EndMessage;
return allOk;
}
bool VertexAccessInstance::isValueWithinVertexBufferOrZero(void* vertexBuffer, VkDeviceSize vertexBufferSize, const void* value, deUint32 valueIndex)
{
if (m_inputFormat == VK_FORMAT_A2B10G10R10_UNORM_PACK32)
{
const float normValue = *reinterpret_cast<const float*>(value);
const deUint32 scalarIndex = valueIndex % 4;
const bool isAlpha = (scalarIndex == 3);
deUint32 encodedValue;
if (isAlpha)
encodedValue = deMin32(deUint32(deFloatRound(normValue * 0x3u)), 0x3u);
else
encodedValue = deMin32(deUint32(deFloatRound(normValue * 0x3FFu)), 0x3FFu);
if (encodedValue == 0)
return true;
for (deUint32 i = 0; i < vertexBufferSize / 4; i++)
{
const deUint32 packedValue = reinterpret_cast<deUint32*>(vertexBuffer)[i];
deUint32 unpackedValue;
if (scalarIndex < 3)
unpackedValue = (packedValue >> (10 * scalarIndex)) & 0x3FFu;
else
unpackedValue = (packedValue >> 30) & 0x3u;
if (unpackedValue == encodedValue)
return true;
}
return false;
}
else
{
return isValueWithinBufferOrZero(vertexBuffer, vertexBufferSize, value, sizeof(deUint32));
}
}
bool VertexAccessInstance::isExpectedValueFromVertexBuffer (const void* vertexBuffer, deUint32 vertexIndex, VkFormat vertexFormat, const void* value)
{
if (isUintFormat(vertexFormat))
{
if (vertexFormat == VK_FORMAT_R64_UINT || vertexFormat == VK_FORMAT_R64_SINT)
{
const deUint64* bufferPtr = reinterpret_cast<const deUint64*>(vertexBuffer);
return bufferPtr[vertexIndex] == *reinterpret_cast<const deUint64 *>(value);
}
else
{
const deUint32* bufferPtr = reinterpret_cast<const deUint32*>(vertexBuffer);
return bufferPtr[vertexIndex] == *reinterpret_cast<const deUint32 *>(value);
}
}
else if (isIntFormat(vertexFormat))
{
if (vertexFormat == VK_FORMAT_R64_UINT || vertexFormat == VK_FORMAT_R64_SINT)
{
const deInt64* bufferPtr = reinterpret_cast<const deInt64*>(vertexBuffer);
return bufferPtr[vertexIndex] == *reinterpret_cast<const deInt64 *>(value);
}
else
{
const deInt32* bufferPtr = reinterpret_cast<const deInt32*>(vertexBuffer);
return bufferPtr[vertexIndex] == *reinterpret_cast<const deInt32 *>(value);
}
}
else if (isFloatFormat(vertexFormat))
{
const float* bufferPtr = reinterpret_cast<const float*>(vertexBuffer);
return areEqual(bufferPtr[vertexIndex], *reinterpret_cast<const float *>(value));
}
else if (vertexFormat == VK_FORMAT_A2B10G10R10_UNORM_PACK32)
{
const deUint32* bufferPtr = reinterpret_cast<const deUint32*>(vertexBuffer);
const deUint32 packedValue = bufferPtr[vertexIndex / 4];
const deUint32 scalarIndex = vertexIndex % 4;
float normValue;
if (scalarIndex < 3)
normValue = float((packedValue >> (10 * scalarIndex)) & 0x3FFu) / 0x3FFu;
else
normValue = float(packedValue >> 30) / 0x3u;
return areEqual(normValue, *reinterpret_cast<const float *>(value));
}
DE_ASSERT(false);
return false;
}
VkDeviceSize VertexAccessInstance::getBufferSizeInBytes (deUint32 numScalars, VkFormat format)
{
if (isUintFormat(format) || isIntFormat(format) || isFloatFormat(format))
{
return numScalars * ((format == VK_FORMAT_R64_UINT || format == VK_FORMAT_R64_SINT) ? 8 : 4);
}
else if (format == VK_FORMAT_A2B10G10R10_UNORM_PACK32)
{
DE_ASSERT(numScalars % 4 == 0);
return numScalars;
}
DE_ASSERT(false);
return 0;
}
// DrawAccessInstance
DrawAccessInstance::DrawAccessInstance (Context& context,
Move<VkDevice> device,
VkFormat inputFormat,
deUint32 numVertexValues,
deUint32 numInstanceValues,
deUint32 numVertices,
deUint32 numInstances)
: VertexAccessInstance (context,
device,
inputFormat,
numVertexValues,
numInstanceValues,
numVertices,
numInstances,
std::vector<deUint32>()) // No index buffer
{
}
void DrawAccessInstance::initVertexIds (deUint32 *indicesPtr, size_t indexCount)
{
for (deUint32 i = 0; i < indexCount; i++)
indicesPtr[i] = i;
}
deUint32 DrawAccessInstance::getIndex (deUint32 vertexNum) const
{
return vertexNum;
}
// DrawIndexedAccessInstance
DrawIndexedAccessInstance::DrawIndexedAccessInstance (Context& context,
Move<VkDevice> device,
VkFormat inputFormat,
deUint32 numVertexValues,
deUint32 numInstanceValues,
deUint32 numVertices,
deUint32 numInstances,
const std::vector<deUint32>& indices)
: VertexAccessInstance (context,
device,
inputFormat,
numVertexValues,
numInstanceValues,
numVertices,
numInstances,
indices)
, m_indices (indices)
{
}
void DrawIndexedAccessInstance::initVertexIds (deUint32 *indicesPtr, size_t indexCount)
{
DE_UNREF(indexCount);
for (deUint32 i = 0; i < m_indices.size(); i++)
{
DE_ASSERT(m_indices[i] < indexCount);
indicesPtr[m_indices[i]] = i;
}
}
deUint32 DrawIndexedAccessInstance::getIndex (deUint32 vertexNum) const
{
DE_ASSERT(vertexNum < (deUint32)m_indices.size());
return m_indices[vertexNum];
}
// Test node creation functions
static tcu::TestCaseGroup* createDrawTests (tcu::TestContext& testCtx, VkFormat format)
{
struct TestConfig
{
std::string name;
std::string description;
VkFormat inputFormat;
deUint32 numVertexValues;
deUint32 numInstanceValues;
deUint32 numVertices;
deUint32 numInstances;
};
const deUint32 numChannels = getNumUsedChannels(mapVkFormat(format).order);
const TestConfig testConfigs[] =
{
// name description format numVertexValues numInstanceValues numVertices numInstances
{ "vertex_out_of_bounds", "Create data for 6 vertices, draw 9 vertices", format, numChannels * 2 * 6, numChannels, 9, 1 },
{ "vertex_incomplete", "Create data for half a vertex, draw 3 vertices", format, numChannels, numChannels, 3, 1 },
{ "instance_out_of_bounds", "Create data for 1 instance, draw 3 instances", format, numChannels * 2 * 9, numChannels, 3, 3 },
};
de::MovePtr<tcu::TestCaseGroup> drawTests (new tcu::TestCaseGroup(testCtx, "draw", ""));
for (int i = 0; i < DE_LENGTH_OF_ARRAY(testConfigs); i++)
{
const TestConfig &config = testConfigs[i];
drawTests->addChild(new DrawAccessTest(testCtx, config.name, config.description, config.inputFormat,
config.numVertexValues, config.numInstanceValues,
config.numVertices, config.numInstances));
}
return drawTests.release();
}
static tcu::TestCaseGroup* createDrawIndexedTests (tcu::TestContext& testCtx, VkFormat format)
{
struct TestConfig
{
std::string name;
std::string description;
VkFormat inputFormat;
DrawIndexedAccessTest::IndexConfig indexConfig;
};
const TestConfig testConfigs[] =
{
// name description format indexConfig
{ "last_index_out_of_bounds", "Only last index is out of bounds", format, DrawIndexedAccessTest::INDEX_CONFIG_LAST_INDEX_OUT_OF_BOUNDS },
{ "indices_out_of_bounds", "Random indices out of bounds", format, DrawIndexedAccessTest::INDEX_CONFIG_INDICES_OUT_OF_BOUNDS },
{ "triangle_out_of_bounds", "First triangle is out of bounds", format, DrawIndexedAccessTest::INDEX_CONFIG_TRIANGLE_OUT_OF_BOUNDS },
};
de::MovePtr<tcu::TestCaseGroup> drawTests (new tcu::TestCaseGroup(testCtx, "draw_indexed", ""));
for (int i = 0; i < DE_LENGTH_OF_ARRAY(testConfigs); i++)
{
const TestConfig &config = testConfigs[i];
drawTests->addChild(new DrawIndexedAccessTest(testCtx, config.name, config.description, config.inputFormat, config.indexConfig));
}
return drawTests.release();
}
static void addVertexFormatTests (tcu::TestContext& testCtx, tcu::TestCaseGroup* parentGroup)
{
const VkFormat vertexFormats[] =
{
VK_FORMAT_R32_UINT,
VK_FORMAT_R32_SINT,
VK_FORMAT_R32_SFLOAT,
VK_FORMAT_R32G32_UINT,
VK_FORMAT_R32G32_SINT,
VK_FORMAT_R32G32_SFLOAT,
VK_FORMAT_R32G32B32_UINT,
VK_FORMAT_R32G32B32_SINT,
VK_FORMAT_R32G32B32_SFLOAT,
VK_FORMAT_R32G32B32A32_UINT,
VK_FORMAT_R32G32B32A32_SINT,
VK_FORMAT_R32G32B32A32_SFLOAT,
VK_FORMAT_R64_UINT,
VK_FORMAT_R64_SINT,
VK_FORMAT_A2B10G10R10_UNORM_PACK32
};
for (int i = 0; i < DE_LENGTH_OF_ARRAY(vertexFormats); i++)
{
const std::string formatName = getFormatName(vertexFormats[i]);
de::MovePtr<tcu::TestCaseGroup> formatGroup (new tcu::TestCaseGroup(testCtx, de::toLower(formatName.substr(10)).c_str(), ""));
formatGroup->addChild(createDrawTests(testCtx, vertexFormats[i]));
formatGroup->addChild(createDrawIndexedTests(testCtx, vertexFormats[i]));
parentGroup->addChild(formatGroup.release());
}
}
tcu::TestCaseGroup* createVertexAccessTests (tcu::TestContext& testCtx)
{
de::MovePtr<tcu::TestCaseGroup> vertexAccessTests (new tcu::TestCaseGroup(testCtx, "vertex_access", ""));
addVertexFormatTests(testCtx, vertexAccessTests.get());
return vertexAccessTests.release();
}
} // robustness
} // vkt
|
.text
.globl main
main:
li $t0,-3
li $t1,2
div $t0,$t1
mflo $a0
li $v0,1
syscall
mfhi $a0
li $v0,1
syscall |
Name: zel_rmdt09.asm
Type: file
Size: 172147
Last-Modified: '2016-05-13T04:27:09Z'
SHA-1: 8D4C35677AC1F9EAABEEDDCE8B9DF9C00AF150E9
Description: null
|
dnl AMD64 mpn_mul_basecase.
dnl Contributed to the GNU project by Torbjorn Granlund and David Harvey.
dnl Copyright 2008, 2012 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
C cycles/limb
C AMD K8,K9 2.375
C AMD K10 2.375
C Intel P4 15-16
C Intel core2 4.45
C Intel corei 4.35
C Intel atom ?
C VIA nano 4.5
C The inner loops of this code are the result of running a code generation and
C optimization tool suite written by David Harvey and Torbjorn Granlund.
C TODO
C * Use fewer registers. (how??? I can't see it -- david)
C * Avoid some "mov $0,r" and instead use "xor r,r".
C * Can the top of each L(addmul_outer_n) prologue be folded into the
C mul_1/mul_2 prologues, saving a LEA (%rip)? It would slow down the
C case where vn = 1 or 2; is it worth it?
C INPUT PARAMETERS
define(`rp', `%rdi')
define(`up', `%rsi')
define(`un_param',`%rdx')
define(`vp', `%rcx')
define(`vn', `%r8')
define(`v0', `%r12')
define(`v1', `%r9')
define(`w0', `%rbx')
define(`w1', `%r15')
define(`w2', `%rbp')
define(`w3', `%r10')
define(`n', `%r11')
define(`outer_addr', `%r14')
define(`un', `%r13')
ABI_SUPPORT(DOS64)
ABI_SUPPORT(STD64)
ASM_START()
TEXT
ALIGN(16)
PROLOGUE(mpn_mul_basecase)
FUNC_ENTRY(4)
IFDOS(` mov 56(%rsp), %r8d ')
push %rbx
push %rbp
push %r12
push %r13
push %r14
push %r15
xor R32(un), R32(un)
mov (up), %rax
mov (vp), v0
sub un_param, un C rdx used by mul
mov un, n
mov R32(un_param), R32(w0)
lea (rp,un_param,8), rp
lea (up,un_param,8), up
mul v0
test $1, R8(vn)
jz L(mul_2)
C ===========================================================
C mul_1 for vp[0] if vn is odd
L(mul_1):
and $3, R32(w0)
jz L(mul_1_prologue_0)
cmp $2, R32(w0)
jc L(mul_1_prologue_1)
jz L(mul_1_prologue_2)
L(mul_1_prologue_3):
add $-1, n
lea L(addmul_outer_3)(%rip), outer_addr
mov %rax, w3
mov %rdx, w0
jmp L(mul_1_entry_3)
L(mul_1_prologue_0):
mov %rax, w2
mov %rdx, w3 C note: already w0 == 0
lea L(addmul_outer_0)(%rip), outer_addr
jmp L(mul_1_entry_0)
L(mul_1_prologue_1):
cmp $-1, un
jne 2f
mov %rax, -8(rp)
mov %rdx, (rp)
jmp L(ret)
2: add $1, n
lea L(addmul_outer_1)(%rip), outer_addr
mov %rax, w1
mov %rdx, w2
xor R32(w3), R32(w3)
mov (up,n,8), %rax
jmp L(mul_1_entry_1)
L(mul_1_prologue_2):
add $-2, n
lea L(addmul_outer_2)(%rip), outer_addr
mov %rax, w0
mov %rdx, w1
mov 24(up,n,8), %rax
xor R32(w2), R32(w2)
xor R32(w3), R32(w3)
jmp L(mul_1_entry_2)
C this loop is 10 c/loop = 2.5 c/l on K8, for all up/rp alignments
ALIGN(16)
L(mul_1_top):
mov w0, -16(rp,n,8)
add %rax, w1
mov (up,n,8), %rax
adc %rdx, w2
L(mul_1_entry_1):
xor R32(w0), R32(w0)
mul v0
mov w1, -8(rp,n,8)
add %rax, w2
adc %rdx, w3
L(mul_1_entry_0):
mov 8(up,n,8), %rax
mul v0
mov w2, (rp,n,8)
add %rax, w3
adc %rdx, w0
L(mul_1_entry_3):
mov 16(up,n,8), %rax
mul v0
mov w3, 8(rp,n,8)
xor R32(w2), R32(w2) C zero
mov w2, w3 C zero
add %rax, w0
mov 24(up,n,8), %rax
mov w2, w1 C zero
adc %rdx, w1
L(mul_1_entry_2):
mul v0
add $4, n
js L(mul_1_top)
mov w0, -16(rp)
add %rax, w1
mov w1, -8(rp)
adc %rdx, w2
mov w2, (rp)
add $-1, vn C vn -= 1
jz L(ret)
mov 8(vp), v0
mov 16(vp), v1
lea 8(vp), vp C vp += 1
lea 8(rp), rp C rp += 1
jmp *outer_addr
C ===========================================================
C mul_2 for vp[0], vp[1] if vn is even
ALIGN(16)
L(mul_2):
mov 8(vp), v1
and $3, R32(w0)
jz L(mul_2_prologue_0)
cmp $2, R32(w0)
jz L(mul_2_prologue_2)
jc L(mul_2_prologue_1)
L(mul_2_prologue_3):
lea L(addmul_outer_3)(%rip), outer_addr
add $2, n
mov %rax, -16(rp,n,8)
mov %rdx, w2
xor R32(w3), R32(w3)
xor R32(w0), R32(w0)
mov -16(up,n,8), %rax
jmp L(mul_2_entry_3)
ALIGN(16)
L(mul_2_prologue_0):
add $3, n
mov %rax, w0
mov %rdx, w1
xor R32(w2), R32(w2)
mov -24(up,n,8), %rax
lea L(addmul_outer_0)(%rip), outer_addr
jmp L(mul_2_entry_0)
ALIGN(16)
L(mul_2_prologue_1):
mov %rax, w3
mov %rdx, w0
xor R32(w1), R32(w1)
lea L(addmul_outer_1)(%rip), outer_addr
jmp L(mul_2_entry_1)
ALIGN(16)
L(mul_2_prologue_2):
add $1, n
lea L(addmul_outer_2)(%rip), outer_addr
mov $0, R32(w0)
mov $0, R32(w1)
mov %rax, w2
mov -8(up,n,8), %rax
mov %rdx, w3
jmp L(mul_2_entry_2)
C this loop is 18 c/loop = 2.25 c/l on K8, for all up/rp alignments
ALIGN(16)
L(mul_2_top):
mov -32(up,n,8), %rax
mul v1
add %rax, w0
adc %rdx, w1
mov -24(up,n,8), %rax
xor R32(w2), R32(w2)
mul v0
add %rax, w0
mov -24(up,n,8), %rax
adc %rdx, w1
adc $0, R32(w2)
L(mul_2_entry_0):
mul v1
add %rax, w1
mov w0, -24(rp,n,8)
adc %rdx, w2
mov -16(up,n,8), %rax
mul v0
mov $0, R32(w3)
add %rax, w1
adc %rdx, w2
mov -16(up,n,8), %rax
adc $0, R32(w3)
mov $0, R32(w0)
mov w1, -16(rp,n,8)
L(mul_2_entry_3):
mul v1
add %rax, w2
mov -8(up,n,8), %rax
adc %rdx, w3
mov $0, R32(w1)
mul v0
add %rax, w2
mov -8(up,n,8), %rax
adc %rdx, w3
adc R32(w1), R32(w0) C adc $0, w0
L(mul_2_entry_2):
mul v1
add %rax, w3
mov w2, -8(rp,n,8)
adc %rdx, w0
mov (up,n,8), %rax
mul v0
add %rax, w3
adc %rdx, w0
adc $0, R32(w1)
L(mul_2_entry_1):
add $4, n
mov w3, -32(rp,n,8)
js L(mul_2_top)
mov -32(up,n,8), %rax C FIXME: n is constant
mul v1
add %rax, w0
mov w0, (rp)
adc %rdx, w1
mov w1, 8(rp)
add $-2, vn C vn -= 2
jz L(ret)
mov 16(vp), v0
mov 24(vp), v1
lea 16(vp), vp C vp += 2
lea 16(rp), rp C rp += 2
jmp *outer_addr
C ===========================================================
C addmul_2 for remaining vp's
C in the following prologues, we reuse un to store the
C adjusted value of n that is reloaded on each iteration
L(addmul_outer_0):
add $3, un
lea 0(%rip), outer_addr
mov un, n
mov -24(up,un,8), %rax
mul v0
mov %rax, w0
mov -24(up,un,8), %rax
mov %rdx, w1
xor R32(w2), R32(w2)
jmp L(addmul_entry_0)
L(addmul_outer_1):
mov un, n
mov (up,un,8), %rax
mul v0
mov %rax, w3
mov (up,un,8), %rax
mov %rdx, w0
xor R32(w1), R32(w1)
jmp L(addmul_entry_1)
L(addmul_outer_2):
add $1, un
lea 0(%rip), outer_addr
mov un, n
mov -8(up,un,8), %rax
mul v0
xor R32(w0), R32(w0)
mov %rax, w2
xor R32(w1), R32(w1)
mov %rdx, w3
mov -8(up,un,8), %rax
jmp L(addmul_entry_2)
L(addmul_outer_3):
add $2, un
lea 0(%rip), outer_addr
mov un, n
mov -16(up,un,8), %rax
xor R32(w3), R32(w3)
mul v0
mov %rax, w1
mov -16(up,un,8), %rax
mov %rdx, w2
jmp L(addmul_entry_3)
C this loop is 19 c/loop = 2.375 c/l on K8, for all up/rp alignments
ALIGN(16)
L(addmul_top):
add w3, -32(rp,n,8)
adc %rax, w0
mov -24(up,n,8), %rax
adc %rdx, w1
xor R32(w2), R32(w2)
mul v0
add %rax, w0
mov -24(up,n,8), %rax
adc %rdx, w1
adc R32(w2), R32(w2) C adc $0, w2
L(addmul_entry_0):
mul v1
xor R32(w3), R32(w3)
add w0, -24(rp,n,8)
adc %rax, w1
mov -16(up,n,8), %rax
adc %rdx, w2
mul v0
add %rax, w1
mov -16(up,n,8), %rax
adc %rdx, w2
adc $0, R32(w3)
L(addmul_entry_3):
mul v1
add w1, -16(rp,n,8)
adc %rax, w2
mov -8(up,n,8), %rax
adc %rdx, w3
mul v0
xor R32(w0), R32(w0)
add %rax, w2
adc %rdx, w3
mov $0, R32(w1)
mov -8(up,n,8), %rax
adc R32(w1), R32(w0) C adc $0, w0
L(addmul_entry_2):
mul v1
add w2, -8(rp,n,8)
adc %rax, w3
adc %rdx, w0
mov (up,n,8), %rax
mul v0
add %rax, w3
mov (up,n,8), %rax
adc %rdx, w0
adc $0, R32(w1)
L(addmul_entry_1):
mul v1
add $4, n
js L(addmul_top)
add w3, -8(rp)
adc %rax, w0
mov w0, (rp)
adc %rdx, w1
mov w1, 8(rp)
add $-2, vn C vn -= 2
jz L(ret)
lea 16(rp), rp C rp += 2
lea 16(vp), vp C vp += 2
mov (vp), v0
mov 8(vp), v1
jmp *outer_addr
ALIGN(16)
L(ret): pop %r15
pop %r14
pop %r13
pop %r12
pop %rbp
pop %rbx
FUNC_EXIT()
ret
EPILOGUE()
|
; A004998: a(n) = (6^n/n!) * Product_{k=0..n-1} ( 6*k + 11 ).
; Submitted by Christian Krause
; 1,66,3366,154836,6735366,282885372,11598300252,467245810152,18573020953542,730538824172652,28491014142733428,1103379274982221848,42480102086815541148,1627314679941087653208,62070431363467200486648,2358676391811753618492624,89334868339870168300408134,3373705027893920473462471884,127076222717337671167086440964,4775390685272584063857879939384,179077150697721902394670497726900,6702601926114734061057667200635400,250433581057559609008609201769195400,9342261415103745414321160657303028400
mov $1,1
mov $2,1
mov $3,$0
mul $3,2
lpb $3
mul $1,$3
mul $1,3
mul $2,5
add $1,$2
mul $1,3
mov $2,$1
sub $3,1
cmp $4,0
add $5,$4
div $1,$5
div $2,$5
add $2,$1
mul $1,2
sub $3,1
add $4,1
add $5,1
lpe
mov $0,$1
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "test_precomp.hpp"
namespace opencv_test { namespace {
using namespace cv::img_hash;
/**
*The expected results of this test case are come from the phash library,
*I use it as golden model
*/
class CV_RadialVarianceHashTest : public cvtest::BaseTest
{
public:
CV_RadialVarianceHashTest();
protected:
void run(int /* idx */);
//this test case do not use the original "golden data"
//of pHash library, I add a small value to nb_pixels in
//the function "ph_feature_vector" to avoid NaN value
void testComputeHash();
void testFeatures();
//void testHash(); // TODO unused
void testPixPerLine();
void testProjection();
cv::Mat input;
Ptr<cv::img_hash::RadialVarianceHash> rvh;
};
CV_RadialVarianceHashTest::CV_RadialVarianceHashTest()
{
input.create(8, 8, CV_8U);
uchar *inPtr = input.ptr<uchar>(0);
for(size_t i = 0; i != input.total(); ++i)
{
inPtr[i] = static_cast<uchar>(i);
}
rvh = RadialVarianceHash::create(1, 10);
}
void CV_RadialVarianceHashTest::testComputeHash()
{
cv::Mat hashOne(1, 40, CV_8U);
uchar buffer[] =
{
52, 41, 49, 64, 40, 67, 76, 71, 69,
55, 58, 68, 72, 78, 63, 73, 66, 77,
60, 57, 48, 59, 62, 74, 70, 47, 46,
51, 45, 44, 42, 61, 54, 75, 50, 79,
65, 43, 53, 56
};
cv::Mat hashTwo(1, 40, CV_8U, buffer);
for(uchar i = 0; i != 40; ++i)
{
hashOne.at<uchar>(0, i) = i;
}
double const actual = rvh->compare(hashOne, hashTwo);
ASSERT_NEAR(0.481051, actual, 0.0001);
}
void CV_RadialVarianceHashTest::testFeatures()
{
std::vector<double> const &features = rvh->getFeatures();
double const expectResult[] =
{-1.35784,-0.42703,0.908487,-1.39327,1.17313,
1.47515,-0.0156121,0.774335,-0.116755,-1.02059};
for(size_t i = 0; i != features.size(); ++i)
{
ASSERT_NEAR(features[i], expectResult[i], 0.0001);
}
}
#if 0 // unused
void CV_RadialVarianceHashTest::testHash()
{
cv::Mat const hash = rvh->getHash();
uchar const expectResult[] =
{
127, 92, 0, 158, 101,
88, 14, 136, 227, 160,
127, 94, 27, 118, 240,
166, 153, 96, 254, 162,
127, 162, 255, 96, 153,
166, 240, 118, 27, 94,
127, 160, 227, 136, 14,
88, 101, 158, 0, 92
};
for(int i = 0; i != hash.cols; ++i)
{
EXPECT_EQ(hash.at<uchar>(0, i), expectResult[i]);
}
}
#endif
void CV_RadialVarianceHashTest::testPixPerLine()
{
cv::Mat const pixPerLine = rvh->getPixPerLine(input);
uchar const expectResult[] =
{
8,8,8,0,8,15,7,5,8,8,
};
bool const equal =
std::equal(expectResult, expectResult + pixPerLine.total(),
pixPerLine.ptr<int>(0));
if(equal == false)
{
ts->printf(cvtest::TS::LOG, "Wrong pixel per line value \n");
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);
}
}
void CV_RadialVarianceHashTest::testProjection()
{
cv::Mat const proj = rvh->getProjection();
uchar const expectResult[] =
{
32, 33, 34, 35, 36, 37, 38, 39,
16, 17, 18, 27, 36, 37, 46, 47,
0, 9, 18, 19, 36, 45, 46, 55,
0, 0, 0, 0, 0, 0, 0, 0,
2, 10, 18, 27, 36, 44, 53, 61,
4, 59, 51, 44, 36, 29, 22, 14,
0, 58, 51, 43, 36, 30, 22, 15,
0, 0, 58, 43, 36, 21, 6, 0,
56, 49, 42, 43, 36, 21, 22, 15,
40, 41, 42, 35, 36, 29, 22, 23
};
bool const equal =
std::equal(expectResult, expectResult + proj.total(),
proj.ptr<uchar>(0));
if(equal == false)
{
ts->printf(cvtest::TS::LOG, "Wrong projection value \n");
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);
}
}
void CV_RadialVarianceHashTest::run(int)
{
testPixPerLine();
testProjection();
testFeatures();
testComputeHash();
}
TEST(radial_variance_hash_test, accuracy) { CV_RadialVarianceHashTest test; test.safe_run(); }
}} // namespace
|
; A242399: Write n and 3n in ternary representation and add all trits modulo 3.
; Coded manually 2021-04-21 by Simon Strandgaard, https://github.com/neoneye
; 0,4,8,12,16,11,24,19,23,36,40,44,48,52,47,33,28,32,72,76,80,57,61,56,69,64,68,108,112,116,120,124,119,132,127,131,144,148,152,156,160,155,141,136,140,99,103,107,84,88,83,96,91,95,216,220,224,228,232
mul $0,3 ; Now $0 holds n*3.
mov $4,1 ; Inital scale factor
lpb $0
; Add the lowest trit without carry
mov $3,$0
div $0,3 ; Remove the lowest trit from n
add $3,$0
mod $3,3
; Now $3 holds TRIT1($0) ternary xor TRIT0($0)
; Scale up the trit, and add to result
mul $3,$4
add $1,$3
mul $4,3 ; Triple the scale factor. Example: 1,3,9,27,81,243
lpe
mov $0,$1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r14
push %r9
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x1b17e, %rdi
nop
dec %r10
mov $0x6162636465666768, %r14
movq %r14, (%rdi)
nop
inc %r9
lea addresses_WC_ht+0x1c50a, %r12
nop
add $58169, %rsi
mov (%r12), %r9
nop
add $40044, %r14
lea addresses_A_ht+0x9f7e, %rsi
lea addresses_D_ht+0xc95e, %rdi
nop
xor %rax, %rax
mov $54, %rcx
rep movsb
nop
nop
nop
nop
nop
inc %rsi
lea addresses_normal_ht+0x4fa6, %rsi
cmp $21513, %r12
mov (%rsi), %rax
nop
nop
nop
nop
cmp $59797, %rdi
lea addresses_WT_ht+0x497e, %r10
nop
nop
nop
inc %r12
movw $0x6162, (%r10)
nop
nop
nop
nop
nop
dec %rdi
lea addresses_A_ht+0x166be, %r14
nop
nop
nop
nop
inc %rsi
mov $0x6162636465666768, %rcx
movq %rcx, (%r14)
nop
nop
nop
nop
xor $2100, %r14
lea addresses_D_ht+0x1297e, %rax
nop
nop
nop
sub %r14, %r14
mov (%rax), %ecx
nop
nop
nop
nop
sub $4496, %r14
lea addresses_D_ht+0x5a72, %rsi
lea addresses_WC_ht+0x617e, %rdi
nop
nop
nop
add $47964, %r10
mov $103, %rcx
rep movsl
nop
nop
nop
and $7777, %rsi
lea addresses_UC_ht+0x212, %r14
xor %r9, %r9
mov (%r14), %si
nop
add $49596, %r10
lea addresses_WT_ht+0x417e, %rsi
lea addresses_D_ht+0x6fca, %rdi
nop
dec %r14
mov $96, %rcx
rep movsw
inc %rsi
lea addresses_UC_ht+0x1007e, %rsi
lea addresses_WC_ht+0x1b17e, %rdi
nop
add %r10, %r10
mov $6, %rcx
rep movsq
nop
nop
nop
nop
nop
add $39040, %rdi
lea addresses_WC_ht+0x1d92, %rsi
lea addresses_A_ht+0x5406, %rdi
nop
nop
nop
nop
sub $16078, %r9
mov $81, %rcx
rep movsl
nop
nop
xor %rdi, %rdi
lea addresses_normal_ht+0xc77e, %rsi
lea addresses_normal_ht+0x6f1d, %rdi
clflush (%rsi)
nop
nop
nop
nop
add %r9, %r9
mov $15, %rcx
rep movsq
nop
nop
sub $44875, %r9
lea addresses_WC_ht+0x1c0a8, %rsi
lea addresses_normal_ht+0x59d6, %rdi
nop
nop
nop
nop
nop
add %r14, %r14
mov $83, %rcx
rep movsq
nop
nop
nop
nop
add $35651, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r14
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r14
push %r8
push %r9
push %rax
push %rsi
// Load
lea addresses_RW+0x117e, %rax
clflush (%rax)
nop
nop
nop
nop
add $47877, %r13
mov (%rax), %r11d
nop
and $35879, %r13
// Store
mov $0x8f6, %r8
clflush (%r8)
and $10259, %r9
mov $0x5152535455565758, %r11
movq %r11, (%r8)
nop
nop
nop
nop
nop
xor $63265, %r9
// Store
lea addresses_normal+0x154ae, %r13
nop
nop
inc %rax
movl $0x51525354, (%r13)
// Exception!!!
nop
nop
nop
mov (0), %r11
nop
sub %r13, %r13
// Store
lea addresses_WT+0x1257e, %rsi
nop
nop
and %r13, %r13
movb $0x51, (%rsi)
// Exception!!!
nop
nop
nop
mov (0), %r11
nop
add $48522, %r8
// Load
lea addresses_normal+0x217e, %r11
nop
dec %r8
mov (%r11), %r9w
nop
nop
nop
nop
inc %rax
// Store
lea addresses_RW+0x145fe, %r8
nop
nop
nop
add $15370, %rsi
movl $0x51525354, (%r8)
and $49724, %r9
// Faulty Load
lea addresses_WT+0x817e, %rsi
nop
nop
nop
nop
sub %r9, %r9
vmovups (%rsi), %ymm1
vextracti128 $1, %ymm1, %xmm1
vpextrq $0, %xmm1, %r11
lea oracles, %r8
and $0xff, %r11
shlq $12, %r11
mov (%r8,%r11,1), %r11
pop %rsi
pop %rax
pop %r9
pop %r8
pop %r14
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_RW', 'same': False, 'AVXalign': False, 'congruent': 11}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_P', 'same': False, 'AVXalign': False, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 9}}
{'OP': 'LOAD', 'src': {'size': 2, 'NT': True, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_RW', 'same': False, 'AVXalign': False, 'congruent': 6}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_WT', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 11}}
{'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': True, 'congruent': 1}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 9}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 2}}
{'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 6}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 4}}
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 9}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_D_ht', 'congruent': 1}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 11}}
{'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 2}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 10}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 2}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 5}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 10}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 0}, 'dst': {'same': False, 'type': 'addresses_A_ht', 'congruent': 2}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 8}, 'dst': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 0}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 1}, 'dst': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 2}}
{'44': 55, '46': 112, '49': 1543, '00': 10080, '48': 6229}
48 49 48 48 00 00 49 48 00 48 48 48 48 00 00 49 49 00 00 48 00 48 48 00 00 00 48 00 48 00 00 00 00 00 00 48 48 00 49 48 00 00 48 48 00 48 00 00 48 00 00 48 48 00 48 00 00 48 48 48 48 48 48 49 00 48 00 00 48 49 49 00 00 00 00 00 00 00 00 00 00 48 00 49 00 49 48 00 48 00 00 48 48 00 48 00 00 00 00 48 00 00 00 48 00 48 48 48 00 48 00 00 00 00 00 48 00 00 00 00 00 00 48 48 48 00 00 00 00 00 00 00 00 48 00 00 00 48 48 00 00 00 00 00 00 00 48 48 00 48 00 00 00 00 48 48 48 00 49 48 00 00 00 48 00 00 49 49 49 48 00 49 00 48 48 00 00 48 48 48 48 48 00 49 44 00 48 00 00 00 00 00 00 48 00 00 00 48 00 48 48 00 00 00 48 00 48 48 49 00 48 00 00 00 00 00 00 00 48 00 48 00 00 46 49 49 48 49 00 48 00 48 48 49 49 48 00 00 48 48 00 00 00 00 48 00 48 00 49 48 00 00 00 48 48 00 48 00 00 00 48 48 00 48 48 00 00 00 48 48 00 00 48 00 48 00 48 48 48 00 49 48 48 00 00 48 00 00 48 00 00 00 48 00 48 48 00 00 00 00 00 00 00 48 00 48 00 48 00 49 00 00 00 00 00 00 48 48 48 00 00 00 00 00 00 00 00 00 48 00 48 00 00 00 48 00 48 48 48 00 48 00 48 00 48 00 48 00 00 00 00 00 00 48 48 00 48 00 00 48 00 00 48 00 48 00 00 00 00 48 48 00 48 00 00 00 00 00 00 00 00 48 49 48 00 48 00 00 49 48 00 00 48 48 48 48 48 48 48 00 48 48 00 00 48 48 00 48 00 48 00 00 49 00 00 00 48 48 00 00 48 00 00 00 00 48 48 00 48 00 00 48 48 00 48 00 00 48 00 00 00 00 00 48 48 49 00 00 00 48 00 00 00 00 00 00 00 00 00 00 00 00 48 00 00 00 48 49 49 49 49 00 48 48 00 00 48 00 00 00 48 00 00 48 00 00 00 00 00 00 00 00 00 48 00 48 48 00 00 48 00 00 00 00 00 00 00 00 00 00 48 00 00 00 48 00 49 00 48 00 48 00 48 48 00 48 00 00 48 00 48 00 48 00 49 49 49 00 00 00 48 00 00 48 49 48 00 00 48 00 49 00 48 00 00 00 00 48 49 49 48 48 48 48 00 48 00 48 48 00 48 00 00 00 00 00 49 49 49 49 49 00 00 49 48 48 48 48 48 48 48 00 48 00 00 48 48 00 00 48 00 00 00 48 49 46 00 00 00 00 48 48 48 48 00 00 00 48 00 48 48 00 00 00 48 00 48 00 00 00 00 48 00 49 48 49 00 48 49 49 49 00 49 00 00 00 00 00 48 00 00 00 48 00 00 00 00 00 00 00 48 48 48 00 00 00 00 48 00 48 00 00 00 00 00 48 48 48 00 00 00 48 00 46 00 48 48 00 48 48 00 48 00 49 48 48 49 48 48 48 00 00 00 00 00 48 48 00 00 46 48 48 00 00 48 49 49 00 48 48 00 00 00 48 48 00 00 00 00 00 48 00 48 00 48 48 48 00 00 00 00 48 48 48 00 00 48 00 48 00 00 00 00 48 00 00 00 00 49 48 00 00 48 00 48 00 00 00 00 48 00 00 48 00 46 00 48 49 49 00 49 00 00 48 00 00 00 48 48 48 00 00 48 00 00 49 00 48 48 48 00 48 48 00 00 00 00 48 48 48 48 00 48 48 00 00 48 00 00 00 48 48 48 48 48 00 48 00 00 48 00 49 49 00 48 00 49 00 46 48 48 48 49 48 00 48 00 00 48 00 48 49 49 00 00 00 48 48 00 00 00 00 00 49 00 49 49 48 49 49 00 00 48 00 48 00 48 48 00 00 00 48 00 00 48 48 48 49 48 00 48 48 00 48 00 00 00 00 48 00 00 48 48 00 49 49 48 48 00 00 00 48 48 48 48 48 00 48 48 00 00 00 00 48 48 00 00 00 00 00 46 49 48 48 48 48 00 48 48 48 00 00 48 48 48 00 48 00 00 00 00 00 00 00 00 00 00 00 00 00 00 48 00 48 00 00 00 00 00 48 48 48 48 48 00 48 49 00 48 48 48 48 00 00 00 48 48 00 00 00 00 48 00 00 48 00 48 00 49 48
*/
|
// (C) Copyright Gennadiy Rozental 2005-2008.
// Use, modification, and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : generic typed_argument_factory implementation
// ***************************************************************************
#ifndef BOOST_RT_CLA_ARGUMENT_FACTORY_HPP_062604GER
#define BOOST_RT_CLA_ARGUMENT_FACTORY_HPP_062604GER
// Boost.Runtime.Parameter
#include <boost/test/utils/runtime/config.hpp>
#include <boost/test/utils/runtime/fwd.hpp>
#include <boost/test/utils/runtime/validation.hpp>
#include <boost/test/utils/runtime/argument.hpp>
#include <boost/test/utils/runtime/trace.hpp>
#include <boost/test/utils/runtime/interpret_argument_value.hpp>
#include <boost/test/utils/runtime/cla/fwd.hpp>
#include <boost/test/utils/runtime/cla/value_generator.hpp>
#include <boost/test/utils/runtime/cla/value_handler.hpp>
#include <boost/test/utils/runtime/cla/validation.hpp>
#include <boost/test/utils/runtime/cla/argv_traverser.hpp>
#include <boost/test/utils/runtime/cla/detail/argument_value_usage.hpp>
#include <boost/test/utils/runtime/cla/iface/argument_factory.hpp>
// Boost.Test
#include <boost/test/utils/callback.hpp>
// Boost
#include <boost/optional.hpp>
namespace boost {
namespace BOOST_RT_PARAM_NAMESPACE {
namespace cla {
// ************************************************************************** //
// ************** default_value_interpreter ************** //
// ************************************************************************** //
namespace rt_cla_detail {
struct default_value_interpreter {
template<typename T>
void operator()( argv_traverser& tr, boost::optional<T>& value )
{
if( interpret_argument_value( tr.token(), value, 0 ) )
tr.next_token();
}
};
} // namespace rt_cla_detail
// ************************************************************************** //
// ************** typed_argument_factory ************** //
// ************************************************************************** //
template<typename T>
struct typed_argument_factory : public argument_factory {
// Constructor
typed_argument_factory()
: m_value_interpreter( rt_cla_detail::default_value_interpreter() )
{}
BOOST_RT_PARAM_UNNEEDED_VIRTUAL ~typed_argument_factory() {}
// properties modification
template<typename Modifier>
void accept_modifier( Modifier const& m )
{
optionally_assign( m_value_handler, m, handler );
optionally_assign( m_value_interpreter, m, interpreter );
if( m.has( default_value ) ) {
BOOST_RT_PARAM_VALIDATE_LOGIC( !m_value_generator,
BOOST_RT_PARAM_LITERAL( "multiple value generators for parameter" ) );
T const& dv_ref = m[default_value];
m_value_generator = rt_cla_detail::const_generator<T>( dv_ref );
}
if( m.has( default_refer_to ) ) {
BOOST_RT_PARAM_VALIDATE_LOGIC( !m_value_generator,
BOOST_RT_PARAM_LITERAL( "multiple value generators for parameter" ) );
cstring ref_id = m[default_refer_to];
m_value_generator = rt_cla_detail::ref_generator<T>( ref_id );
}
if( m.has( assign_to ) ) {
BOOST_RT_PARAM_VALIDATE_LOGIC( !m_value_handler,
BOOST_RT_PARAM_LITERAL( "multiple value handlers for parameter" ) );
m_value_handler = rt_cla_detail::assigner<T>( m[assign_to] );
}
}
// Argument factory implementation
virtual argument_ptr produce_using( parameter& p, argv_traverser& tr );
virtual argument_ptr produce_using( parameter& p, parser const& );
virtual void argument_usage_info( format_stream& fs );
// !! private?
// Data members
unit_test::callback2<parameter const&,T&> m_value_handler;
unit_test::callback2<parser const&,boost::optional<T>&> m_value_generator;
unit_test::callback2<argv_traverser&,boost::optional<T>&> m_value_interpreter;
};
//____________________________________________________________________________//
template<typename T>
inline argument_ptr
typed_argument_factory<T>::produce_using( parameter& p, argv_traverser& tr )
{
boost::optional<T> value;
try {
m_value_interpreter( tr, value );
}
catch( ... ) { // !! should we do that?
BOOST_RT_PARAM_TRACE( "Fail to parse argument value" );
if( !p.p_optional_value )
throw;
}
argument_ptr arg = p.actual_argument();
BOOST_RT_CLA_VALIDATE_INPUT( !!value || p.p_optional_value, tr,
BOOST_RT_PARAM_LITERAL( "Argument value missing for parameter " ) << p.id_2_report() );
BOOST_RT_CLA_VALIDATE_INPUT( !arg || p.p_multiplicable, tr,
BOOST_RT_PARAM_LITERAL( "Unexpected repetition of the parameter " ) << p.id_2_report() );
if( !!value && !!m_value_handler )
m_value_handler( p, *value );
if( !p.p_multiplicable )
arg.reset( p.p_optional_value && (rtti::type_id<T>() != rtti::type_id<bool>())
? static_cast<argument*>(new typed_argument<boost::optional<T> >( p, value ))
: static_cast<argument*>(new typed_argument<T>( p, *value )) );
else {
typedef std::list<boost::optional<T> > optional_list;
if( !arg )
arg.reset( p.p_optional_value
? static_cast<argument*>(new typed_argument<optional_list>( p ))
: static_cast<argument*>(new typed_argument<std::list<T> >( p )) );
if( p.p_optional_value ) {
optional_list& values = arg_value<optional_list>( *arg );
values.push_back( value );
}
else {
std::list<T>& values = arg_value<std::list<T> >( *arg );
values.push_back( *value );
}
}
return arg;
}
//____________________________________________________________________________//
template<typename T>
inline argument_ptr
typed_argument_factory<T>::produce_using( parameter& p, parser const& pa )
{
argument_ptr arg;
if( !m_value_generator )
return arg;
boost::optional<T> value;
m_value_generator( pa, value );
if( !value )
return arg;
if( !!m_value_handler )
m_value_handler( p, *value );
arg.reset( new typed_argument<T>( p, *value ) );
return arg;
}
//____________________________________________________________________________//
template<typename T>
inline void
typed_argument_factory<T>::argument_usage_info( format_stream& fs )
{
rt_cla_detail::argument_value_usage( fs, 0, reinterpret_cast<T*>(0) );
}
//____________________________________________________________________________//
} // namespace boost
} // namespace BOOST_RT_PARAM_NAMESPACE
} // namespace cla
#endif // BOOST_RT_CLA_ARGUMENT_FACTORY_HPP_062604GER
|
; A018207: Expansion of 1/((1-3x)(1-10x)(1-12x)).
; Submitted by Jon Maiga
; 1,25,439,6685,94471,1276405,16745119,215226205,2725568791,34135388485,423910350799,5229781276525,64185946519111,784517071831765,9557062002788479,116113315455883645,1407645499737869431,17034603139656230245,205843809104280154159,2484411423536578023565,29955794225294584803751,360898102132101963207925,4345062939870924395183839,52283612421308195252272285,628831920484269650557466071,7560268760096949729280188805,90866082264020538519134053519,1091821558596817887532924005805
add $0,2
lpb $0
sub $0,1
div $1,4
max $2,26
mul $2,12
mul $3,10
add $3,$1
mul $1,12
add $1,$2
lpe
mov $0,$3
div $0,78
|
; A066430: a(n) = 8^n mod n^8.
; 0,64,512,4096,32768,262144,2097152,0,5077565,73741824,15579352,352387072,769038655,195124224,1009588832,0,4384458125,2836131328,9009163584,7006846976,33653509289,41376995328,17808619293,26138902528,11605068943,200037316608,161669290688,88607293440,486559764369,544999124224,436466053263,0,52045701659,1404419065600,1164501790782,2066007457792,3252903971284,1367030270464,599980882454,3361080344576,7941364907049,9137365836544,11181800552596,7556609802240,16197197081993,9906838492160,21714199420632
add $0,1
mov $2,8
mov $3,$0
pow $0,8
pow $2,$3
mod $2,$0
mov $0,$2
|
//===- MSP430InstrInfo.cpp - MSP430 Instruction Information ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MSP430 implementation of the TargetInstrInfo class.
//
//===----------------------------------------------------------------------===//
#include "MSP430.h"
#include "MSP430InstrInfo.h"
#include "MSP430MachineFunctionInfo.h"
#include "MSP430TargetMachine.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/PseudoSourceValue.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
#define GET_INSTRINFO_CTOR
#include "MSP430GenInstrInfo.inc"
using namespace llvm;
MSP430InstrInfo::MSP430InstrInfo(MSP430TargetMachine &tm)
: MSP430GenInstrInfo(MSP430::ADJCALLSTACKDOWN, MSP430::ADJCALLSTACKUP),
RI(tm, *this), TM(tm) {}
void MSP430InstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned SrcReg, bool isKill, int FrameIdx,
const TargetRegisterClass *RC,
const TargetRegisterInfo *TRI) const {
DebugLoc DL;
if (MI != MBB.end()) DL = MI->getDebugLoc();
MachineFunction &MF = *MBB.getParent();
MachineFrameInfo &MFI = *MF.getFrameInfo();
MachineMemOperand *MMO =
MF.getMachineMemOperand(
MachinePointerInfo(PseudoSourceValue::getFixedStack(FrameIdx)),
MachineMemOperand::MOStore,
MFI.getObjectSize(FrameIdx),
MFI.getObjectAlignment(FrameIdx));
if (RC == &MSP430::GR16RegClass)
BuildMI(MBB, MI, DL, get(MSP430::MOV16mr))
.addFrameIndex(FrameIdx).addImm(0)
.addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO);
else if (RC == &MSP430::GR8RegClass)
BuildMI(MBB, MI, DL, get(MSP430::MOV8mr))
.addFrameIndex(FrameIdx).addImm(0)
.addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO);
else
llvm_unreachable("Cannot store this register to stack slot!");
}
void MSP430InstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, int FrameIdx,
const TargetRegisterClass *RC,
const TargetRegisterInfo *TRI) const{
DebugLoc DL;
if (MI != MBB.end()) DL = MI->getDebugLoc();
MachineFunction &MF = *MBB.getParent();
MachineFrameInfo &MFI = *MF.getFrameInfo();
MachineMemOperand *MMO =
MF.getMachineMemOperand(
MachinePointerInfo(PseudoSourceValue::getFixedStack(FrameIdx)),
MachineMemOperand::MOLoad,
MFI.getObjectSize(FrameIdx),
MFI.getObjectAlignment(FrameIdx));
if (RC == &MSP430::GR16RegClass)
BuildMI(MBB, MI, DL, get(MSP430::MOV16rm))
.addReg(DestReg).addFrameIndex(FrameIdx).addImm(0).addMemOperand(MMO);
else if (RC == &MSP430::GR8RegClass)
BuildMI(MBB, MI, DL, get(MSP430::MOV8rm))
.addReg(DestReg).addFrameIndex(FrameIdx).addImm(0).addMemOperand(MMO);
else
llvm_unreachable("Cannot store this register to stack slot!");
}
void MSP430InstrInfo::copyPhysReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator I, DebugLoc DL,
unsigned DestReg, unsigned SrcReg,
bool KillSrc) const {
unsigned Opc;
if (MSP430::GR16RegClass.contains(DestReg, SrcReg))
Opc = MSP430::MOV16rr;
else if (MSP430::GR8RegClass.contains(DestReg, SrcReg))
Opc = MSP430::MOV8rr;
else
llvm_unreachable("Impossible reg-to-reg copy");
BuildMI(MBB, I, DL, get(Opc), DestReg)
.addReg(SrcReg, getKillRegState(KillSrc));
}
unsigned MSP430InstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
MachineBasicBlock::iterator I = MBB.end();
unsigned Count = 0;
while (I != MBB.begin()) {
--I;
if (I->isDebugValue())
continue;
if (I->getOpcode() != MSP430::JMP &&
I->getOpcode() != MSP430::JCC &&
I->getOpcode() != MSP430::Br &&
I->getOpcode() != MSP430::Bm)
break;
// Remove the branch.
I->eraseFromParent();
I = MBB.end();
++Count;
}
return Count;
}
bool MSP430InstrInfo::
ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
assert(Cond.size() == 1 && "Invalid Xbranch condition!");
MSP430CC::CondCodes CC = static_cast<MSP430CC::CondCodes>(Cond[0].getImm());
switch (CC) {
default:
assert(0 && "Invalid branch condition!");
break;
case MSP430CC::COND_E:
CC = MSP430CC::COND_NE;
break;
case MSP430CC::COND_NE:
CC = MSP430CC::COND_E;
break;
case MSP430CC::COND_L:
CC = MSP430CC::COND_GE;
break;
case MSP430CC::COND_GE:
CC = MSP430CC::COND_L;
break;
case MSP430CC::COND_HS:
CC = MSP430CC::COND_LO;
break;
case MSP430CC::COND_LO:
CC = MSP430CC::COND_HS;
break;
}
Cond[0].setImm(CC);
return false;
}
bool MSP430InstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
const MCInstrDesc &MCID = MI->getDesc();
if (!MCID.isTerminator()) return false;
// Conditional branch is a special case.
if (MCID.isBranch() && !MCID.isBarrier())
return true;
if (!MCID.isPredicable())
return true;
return !isPredicated(MI);
}
bool MSP430InstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
MachineBasicBlock *&TBB,
MachineBasicBlock *&FBB,
SmallVectorImpl<MachineOperand> &Cond,
bool AllowModify) const {
// Start from the bottom of the block and work up, examining the
// terminator instructions.
MachineBasicBlock::iterator I = MBB.end();
while (I != MBB.begin()) {
--I;
if (I->isDebugValue())
continue;
// Working from the bottom, when we see a non-terminator
// instruction, we're done.
if (!isUnpredicatedTerminator(I))
break;
// A terminator that isn't a branch can't easily be handled
// by this analysis.
if (!I->getDesc().isBranch())
return true;
// Cannot handle indirect branches.
if (I->getOpcode() == MSP430::Br ||
I->getOpcode() == MSP430::Bm)
return true;
// Handle unconditional branches.
if (I->getOpcode() == MSP430::JMP) {
if (!AllowModify) {
TBB = I->getOperand(0).getMBB();
continue;
}
// If the block has any instructions after a JMP, delete them.
while (llvm::next(I) != MBB.end())
llvm::next(I)->eraseFromParent();
Cond.clear();
FBB = 0;
// Delete the JMP if it's equivalent to a fall-through.
if (MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
TBB = 0;
I->eraseFromParent();
I = MBB.end();
continue;
}
// TBB is used to indicate the unconditinal destination.
TBB = I->getOperand(0).getMBB();
continue;
}
// Handle conditional branches.
assert(I->getOpcode() == MSP430::JCC && "Invalid conditional branch");
MSP430CC::CondCodes BranchCode =
static_cast<MSP430CC::CondCodes>(I->getOperand(1).getImm());
if (BranchCode == MSP430CC::COND_INVALID)
return true; // Can't handle weird stuff.
// Working from the bottom, handle the first conditional branch.
if (Cond.empty()) {
FBB = TBB;
TBB = I->getOperand(0).getMBB();
Cond.push_back(MachineOperand::CreateImm(BranchCode));
continue;
}
// Handle subsequent conditional branches. Only handle the case where all
// conditional branches branch to the same destination.
assert(Cond.size() == 1);
assert(TBB);
// Only handle the case where all conditional branches branch to
// the same destination.
if (TBB != I->getOperand(0).getMBB())
return true;
MSP430CC::CondCodes OldBranchCode = (MSP430CC::CondCodes)Cond[0].getImm();
// If the conditions are the same, we can leave them alone.
if (OldBranchCode == BranchCode)
continue;
return true;
}
return false;
}
unsigned
MSP430InstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
MachineBasicBlock *FBB,
const SmallVectorImpl<MachineOperand> &Cond,
DebugLoc DL) const {
// Shouldn't be a fall through.
assert(TBB && "InsertBranch must not be told to insert a fallthrough");
assert((Cond.size() == 1 || Cond.size() == 0) &&
"MSP430 branch conditions have one component!");
if (Cond.empty()) {
// Unconditional branch?
assert(!FBB && "Unconditional branch with multiple successors!");
BuildMI(&MBB, DL, get(MSP430::JMP)).addMBB(TBB);
return 1;
}
// Conditional branch.
unsigned Count = 0;
BuildMI(&MBB, DL, get(MSP430::JCC)).addMBB(TBB).addImm(Cond[0].getImm());
++Count;
if (FBB) {
// Two-way Conditional branch. Insert the second branch.
BuildMI(&MBB, DL, get(MSP430::JMP)).addMBB(FBB);
++Count;
}
return Count;
}
/// GetInstSize - Return the number of bytes of code the specified
/// instruction may be. This returns the maximum number of bytes.
///
unsigned MSP430InstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
const MCInstrDesc &Desc = MI->getDesc();
switch (Desc.TSFlags & MSP430II::SizeMask) {
default:
switch (Desc.getOpcode()) {
default:
assert(0 && "Unknown instruction size!");
case TargetOpcode::PROLOG_LABEL:
case TargetOpcode::EH_LABEL:
case TargetOpcode::IMPLICIT_DEF:
case TargetOpcode::KILL:
case TargetOpcode::DBG_VALUE:
return 0;
case TargetOpcode::INLINEASM: {
const MachineFunction *MF = MI->getParent()->getParent();
const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
return TII.getInlineAsmLength(MI->getOperand(0).getSymbolName(),
*MF->getTarget().getMCAsmInfo());
}
}
case MSP430II::SizeSpecial:
switch (MI->getOpcode()) {
default:
assert(0 && "Unknown instruction size!");
case MSP430::SAR8r1c:
case MSP430::SAR16r1c:
return 4;
}
case MSP430II::Size2Bytes:
return 2;
case MSP430II::Size4Bytes:
return 4;
case MSP430II::Size6Bytes:
return 6;
}
return 6;
}
|
DEVICE ZXSPECTRUMNEXT
DEFINE DOUBLEBUFFER 1
CSPECTMAP testMaths.map
OPT --zxnext=cspect --syntax=a --reversepop
testStartup: ORG $8000
ld ix, TestCase1
.TestLoop: ld a,(testCounter)
ld hl, testTotal
cp (hl)
jr z,.Done
ld a,(ix+testCase.SrcH)
ld h,a
ld a,(ix+testCase.SrcC)
ld c,a
ld a,(ix+testCase.SrcB)
ld b,a
ld a,(ix+testCase.SrcL)
ld l,a
ld a,(ix+testCase.SrcE)
ld e,a
ld a,(ix+testCase.SrcD)
ld d,a
call AddBCHtoDELsigned
ld iyl,'P'
ld a,l
ld (ix+testCase.ActualL),a
cp (ix+testCase.ExpectedL)
jr z,.LOK
ld iyl,'1'
.LOK:
ld a,e
ld (ix+testCase.ActualE),a
cp (ix+testCase.ExpectedE)
jr z,.EOK
ld iyl,'2'
.EOK:
ld a,d
ld (ix+testCase.ActualD),a
cp (ix+testCase.ExpectedD)
jr z,.DOK
ld iyl,'3'
.DOK:
ld a,iyl
ld (ix+testCase.PassFail),a
ld hl,testCounter
inc (hl)
push ix
pop hl
ld a,16
add hl,a
push hl
pop ix
jp .TestLoop
.Done break
jp .Done ; complete tight loop
INCLUDE "../Variables/constant_equates.asm"
INCLUDE "../Hardware/L2ColourDefines.asm"
INCLUDE "../Macros/carryFlagMacros.asm"
INCLUDE "../Macros/jumpMacros.asm"
INCLUDE "../Macros/ldCopyMacros.asm"
INCLUDE "../Macros/ShiftMacros.asm"
INCLUDE "../Macros/NegateMacros.asm"
INCLUDE "../Variables/general_variables_macros.asm"
INCLUDE "../Variables/general_variables.asm"
; DEL = DEL + BCH signed, uses BC, DE, HL, IY, A
AddBCHtoDELsigned: ld a,b ; Are the values both the same sign?
xor d ; .
and SignOnly8Bit ; .
jr nz,.SignDifferent ; .
.SignSame: ld a,b ; if they are then we only need 1 signe
and SignOnly8Bit ; so store it in iyh
ld iyh,a ;
ld a,b ; bch = abs bch
and SignMask8Bit ; .
ld b,a ; .
ld a,d ; del = abs del
and SignMask8Bit ; .
ld d,a ; .
ld a,h ; l = h + l
add l ; .
ld l,a ; .
ld a,c ; e = e + c + carry
adc e ; .
ld e,a ; .
ld a,b ; d = b + d + carry (signed)
adc d ;
or iyh ; d = or back in sign bit
ld d,a ;
ret ; done
.SignDifferent: ld a,b ; bch = abs bch
ld iyh,a ; iyh = b sign
and SignMask8Bit ; .
ld b,a ; .
ld a,d ; del = abs del
ld iyl,a ; iyl = d sign
and SignMask8Bit ; .
ld d,a ; .
push hl ; hl = bc - de
ld hl,bc ; if bc < de then there is a carry
sbc hl,de ;
pop hl ;
jr c,.BCHltDEL
jr nz,.DELltBCH ; if the result was not zero then DEL > BCH
.BCeqDE: ld a,h ; if the result was zero then check lowest bits
JumpIfALTNusng l,.BCHltDEL
jr nz,.DELltBCH
; The same so its just zero
.BCHeqDEL: xor a ; its just zero
ld d,a ; .
ld e,a ; .
ld l,a ; .
ret ; .
;BCH is less than DEL so its DEL - BCH the sort out sign
.BCHltDEL: ld a,l ; l = l - h ; ex
sub h ; . ; 01D70F DEL
ld l,a ; . ; -000028 BCH
ld a,e ; e = e - c - carry ;1.
sbc c ; . ;
ld e,a ; . ;
ld a,d ; d = d - b - carry ;
sbc b ; . ;
ld d,a ; . ;
ld a,iyl ; as d was larger, take d sign
and SignOnly8Bit ;
or d ;
ld d,a ;
ret
.DELltBCH: ld a,h ; l = h - l
sub l ;
ld l,a ;
ld a,c ; e = c - e - carry
sbc e ;
ld e,a ;
ld a,b ; d = b - d - carry
sbc d ;
ld d,a ;
ld a,iyh ; as b was larger, take b sign into d
and SignOnly8Bit ;
or d ;
ld d,a ;
ret
STRUCT testCase
SrcH BYTE 1
SrcC BYTE 2
SrcB BYTE 3
SrcL BYTE 4
SrcE BYTE 5
SrcD BYTE 6
ExpectedL BYTE 7
ExpectedE BYTE 8
ExpectedD BYTE 9
ActualL BYTE 10
ActualE BYTE 11
ActualD BYTE 12
Padding1 BYTE 13
Padding2 BYTE 14
Padding3 BYTE 15
PassFail BYTE 16
ENDS
; 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16
TestCase1 DB $05, $05, $00, $05, $05, $00, $0A, $0A, $00, $00, $00, $00, $00, $00, $01, $00 ; basic
TestCase2 DB $05, $05, $03, $05, $05, $03, $0A, $0A, $06, $00, $00, $00, $00, $00, $02, $00 ; basic 3 byte
TestCase3 DB $05, $05, $83, $05, $05, $03, $00, $00, $00, $00, $00, $00, $00, $00, $03, $00 ; - + = 0
TestCase4 DB $05, $05, $03, $05, $05, $83, $00, $00, $00, $00, $00, $00, $00, $00, $04, $00 ; + - =0
TestCase5 DB $05, $05, $83, $05, $05, $83, $0A, $0A, $86, $00, $00, $00, $00, $00, $05, $00 ; - - add
TestCase6 DB $05, $05, $83, $05, $05, $02, $00, $00, $81, $00, $00, $00, $00, $00, $06, $00 ; - +<1
TestCase7 DB $05, $05, $03, $05, $02, $83, $00, $03, $00, $00, $00, $00, $00, $00, $07, $00 ; + -<1
TestCase8 DB $05, $02, $82, $05, $05, $03, $00, $03, $01, $00, $00, $00, $00, $00, $08, $00 ; - +>1
TestCase9 DB $05, $02, $03, $05, $05, $83, $00, $03, $80, $00, $00, $00, $00, $00, $09, $00 ; + ->1
testTotal DB ($-TestCase1)/16
testCounter DB 0
SAVENEX OPEN "mathssun2.nex", $8000 , $7F00
SAVENEX CFG 0,0,0,1
SAVENEX AUTO
SAVENEX CLOSE
|
; A145825: a(n) is in A145818 such that (4n-1-a(n))/2 is in A145818 as well
; Submitted by Jamie Morken(s2)
; 1,5,1,5,17,21,17,21,1,5,1,5,17,21,17,21,65,69,65,69,81,85,81,85,65,69,65,69
mov $1,$0
seq $1,4451 ; Nimsum n + 10.
add $0,$1
mul $0,2
sub $0,19
|
; A032926: Numbers whose set of base 5 digits is {1,2}.
; 1,2,6,7,11,12,31,32,36,37,56,57,61,62,156,157,161,162,181,182,186,187,281,282,286,287,306,307,311,312,781,782,786,787,806,807,811,812,906,907,911,912,931,932,936,937,1406,1407,1411,1412,1431,1432,1436,1437,1531,1532,1536,1537,1556,1557,1561,1562,3906,3907,3911,3912,3931,3932,3936,3937,4031,4032,4036,4037,4056,4057,4061,4062,4531,4532,4536,4537,4556,4557,4561,4562,4656,4657,4661,4662,4681,4682,4686,4687,7031,7032,7036,7037,7056,7057
seq $0,32925 ; Numbers whose set of base 4 digits is {1,2}.
seq $0,20655 ; Lexicographically earliest increasing sequence of positive numbers that contains no arithmetic progression of length 5.
sub $0,1
|
; A281019: Partial products of A051953; a(1) = 1.
; Submitted by Christian Krause
; 1,1,1,2,2,8,8,32,96,576,576,4608,4608,36864,258048,2064384,2064384,24772608,24772608,297271296,2675441664,32105299968,32105299968,513684799488,2568423997440,35957935964160,323621423677440,5177942778839040,5177942778839040,113914741134458880,113914741134458880,1822635858151342080,23694266155967447040,426496790807414046720,4691464698881554513920,112595152773157308334080,112595152773157308334080,2251903055463146166681600,33778545831947192500224000,810685099966732620005376000
mov $1,1
lpb $0
mov $2,$0
sub $0,1
seq $2,51953 ; Cototient(n) := n - phi(n).
mul $1,$2
lpe
mov $0,$1
|
; A036222: Expansion of 1/(1-3*x)^9; 9-fold convolution of A000244 (powers of 3).
; 1,27,405,4455,40095,312741,2189187,14073345,84440070,478493730,2583866142,13389124554,66945622770,324428787270,1529449997130,7035469986798,31659614940591,139674771796725,605257344452475,2580307626350025,10837292030670105,44897352698490435,183670988312006325,742669648392025575,2970678593568102300,11763887230529685108,46150634519770303116,179474689799106734340,692259517796554546740,2649682981910950161660,10068795331261610614308,38001582379277691673356,142505933922291343775085
mov $1,3
pow $1,$0
mov $2,$0
add $2,8
bin $2,$0
mul $1,$2
mov $0,$1
|
; A266072: Number of ON (black) cells in the n-th iteration of the "Rule 3" elementary cellular automaton starting with a single ON (black) cell.
; 1,1,1,5,1,9,1,13,1,17,1,21,1,25,1,29,1,33,1,37,1,41,1,45,1,49,1,53,1,57,1,61,1,65,1,69,1,73,1,77,1,81,1,85,1,89,1,93,1,97,1,101,1,105,1,109,1,113,1,117,1,121,1,125,1,129,1,133,1,137,1,141,1,145,1,149,1,153,1,157,1,161,1,165,1,169,1,173,1,177,1,181,1,185,1,189,1,193,1,197,1,201,1,205,1,209,1,213,1,217,1,221,1,225,1,229,1,233,1,237,1,241,1,245,1,249,1,253,1,257,1,261,1,265,1,269,1,273,1,277,1,281,1,285,1,289,1,293,1,297,1,301,1,305,1,309,1,313,1,317,1,321,1,325,1,329,1,333,1,337,1,341,1,345,1,349,1,353,1,357,1,361,1,365,1,369,1,373,1,377,1,381,1,385,1,389,1,393,1,397,1,401,1,405,1,409,1,413,1,417,1,421,1,425,1,429,1,433,1,437,1,441,1,445,1,449,1,453,1,457,1,461,1,465,1,469,1,473,1,477,1,481,1,485,1,489,1,493,1,497
mov $1,$0
mod $0,2
pow $1,$0
mul $1,2
sub $1,1
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = {-1, 150, 190, 170, -1, -1, 160, 180};
int n = sizeof(arr)/sizeof(arr[0]);
vector <int> brr;
for(int i = 0; i < n; i++)
{
if(arr[i] != -1)
{
brr.push_back(arr[i]);
}
}
int m = brr.size();
sort(brr.begin(), brr.end());
int crr[n];
int j = 0;
for(int i = 0; i < n; i ++)
{
if(arr[i] == -1) crr[i] = -1;
else
{
crr[i] = brr[j];
j++;
}
}
for(int i = 0; i < n; i++)
{
cout << crr[i] << " ";
}
}
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright(c) 2011-2015 Intel Corporation All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions
; are met:
; * Redistributions of source code must retain the above copyright
; notice, this list of conditions and the following disclaimer.
; * Redistributions in binary form must reproduce the above copyright
; notice, this list of conditions and the following disclaimer in
; the documentation and/or other materials provided with the
; distribution.
; * Neither the name of Intel Corporation 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Optimized pq of N source vectors using SSE3
;;; int pq_gen_sse(int vects, int len, void **array)
;;; Generates P+Q parity vector from N (vects-2) sources in array of pointers
;;; (**array). Last two pointers are the P and Q destinations respectively.
;;; Vectors must be aligned to 16 bytes. Length must be 16 byte aligned.
%include "reg_sizes.asm"
%ifidn __OUTPUT_FORMAT__, elf64
%define arg0 rdi
%define arg1 rsi
%define arg2 rdx
%define arg3 rcx
%define arg4 r8
%define arg5 r9
%define tmp r11
%define return rax
%define PS 8
%define func(x) x:
%define FUNC_SAVE
%define FUNC_RESTORE
%elifidn __OUTPUT_FORMAT__, win64
%define arg0 rcx
%define arg1 rdx
%define arg2 r8
%define arg3 r9
%define return rax
%define PS 8
%define tmp r10
%define stack_size 2*16 + 8 ; must be an odd multiple of 8
%define func(x) proc_frame x
%macro FUNC_SAVE 0
alloc_stack stack_size
save_xmm128 xmm6, 0*16
save_xmm128 xmm7, 1*16
end_prolog
%endmacro
%macro FUNC_RESTORE 0
movdqa xmm6, [rsp + 0*16]
movdqa xmm7, [rsp + 1*16]
add rsp, stack_size
%endmacro
%elifidn __OUTPUT_FORMAT__, elf32
%define arg0 edx
%define arg1 ecx
%define return eax
%define PS 4
%define func(x) x:
%define arg(x) [ebp+8+PS*x]
%define arg2 edi ; must sav/restore
%define arg3 esi
%define tmp ebx
%macro FUNC_SAVE 0
push ebp
mov ebp, esp
push esi
push edi
push ebx
mov arg0, arg(0)
mov arg1, arg(1)
mov arg2, arg(2)
%endmacro
%macro FUNC_RESTORE 0
pop ebx
pop edi
pop esi
mov esp, ebp ;if has frame pointer?
pop ebp
%endmacro
%endif ; output formats
%define vec arg0
%define len arg1
%define ptr arg3
%define pos return
%define xp1 xmm0
%define xq1 xmm1
%define xtmp1 xmm2
%define xs1 xmm3
%define xp2 xmm4
%define xq2 xmm5
%define xtmp2 xmm6
%define xs2 xmm7
%ifidn PS,8 ; 64-bit code
default rel
[bits 64]
%define xpoly xmm15
%elifidn PS,4 ; 32-bit code
%define xpoly [poly]
%endif
;;; Use Non-temporal load/stor
%ifdef NO_NT_LDST
%define XLDR movdqa
%define XSTR movdqa
%else
%define XLDR movntdqa
%define XSTR movntdq
%endif
section .text
align 16
mk_global pq_gen_sse, function
func(pq_gen_sse)
FUNC_SAVE
sub vec, 3 ;Keep as offset to last source
jng return_fail ;Must have at least 2 sources
cmp len, 0
je return_pass
test len, (16-1) ;Check alignment of length
jnz return_fail
mov pos, 0
%ifidn PS,8
movdqa xpoly, [poly] ;For 64-bit, load poly into high xmm reg
%endif
cmp len, 32
jl loop16
len_aligned_32bytes:
sub len, 32 ;Do end of vec first and run backward
loop32:
mov ptr, [arg2+vec*PS] ;Fetch last source pointer
mov tmp, vec ;Set tmp to point back to last vector
XLDR xs1, [ptr+pos] ;Preload last vector (source)
XLDR xs2, [ptr+pos+16] ;Preload last vector (source)
pxor xp1, xp1 ;p1 = 0
pxor xq1, xq1 ;q1 = 0
pxor xp2, xp2 ;p2 = 0
pxor xq2, xq2 ;q2 = 0
next_vect:
sub tmp, 1 ;Inner loop for each source vector
mov ptr, [arg2+tmp*PS] ; get pointer to next vect
pxor xq1, xs1 ; q1 ^= s1
pxor xq2, xs2 ; q2 ^= s2
pxor xp1, xs1 ; p1 ^= s1
pxor xp2, xs2 ; p2 ^= s2
pxor xtmp1, xtmp1 ; xtmp1 = 0 - for compare to 0
pxor xtmp2, xtmp2 ; xtmp2 = 0
pcmpgtb xtmp1, xq1 ; xtmp1 = mask 0xff or 0x00 if bit7 set
pcmpgtb xtmp2, xq2 ; xtmp2 = mask 0xff or 0x00 if bit7 set
pand xtmp1, xpoly ; xtmp1 = poly or 0x00
pand xtmp2, xpoly ; xtmp2 = poly or 0x00
XLDR xs1, [ptr+pos] ; Get next vector (source data1)
XLDR xs2, [ptr+pos+16] ; Get next vector (source data2)
paddb xq1, xq1 ; q1 = q1<<1
paddb xq2, xq2 ; q2 = q2<<1
pxor xq1, xtmp1 ; q1 = q1<<1 ^ poly_masked
pxor xq2, xtmp2 ; q2 = q2<<1 ^ poly_masked
jg next_vect ; Loop for each vect except 0
mov ptr, [arg2+PS+vec*PS] ;Get address of P parity vector
mov tmp, [arg2+(2*PS)+vec*PS] ;Get address of Q parity vector
pxor xp1, xs1 ;p1 ^= s1[0] - last source is already loaded
pxor xq1, xs1 ;q1 ^= 1 * s1[0]
pxor xp2, xs2 ;p2 ^= s2[0]
pxor xq2, xs2 ;q2 ^= 1 * s2[0]
XSTR [ptr+pos], xp1 ;Write parity P1 vector
XSTR [ptr+pos+16], xp2 ;Write parity P2 vector
XSTR [tmp+pos], xq1 ;Write parity Q1 vector
XSTR [tmp+pos+16], xq2 ;Write parity Q2 vector
add pos, 32
cmp pos, len
jle loop32
;; ------------------------------
;; Do last 16 Bytes remaining
add len, 32
cmp pos, len
je return_pass
loop16:
mov ptr, [arg2+vec*PS] ;Fetch last source pointer
mov tmp, vec ;Set tmp to point back to last vector
XLDR xs1, [ptr+pos] ;Preload last vector (source)
pxor xp1, xp1 ;p = 0
pxor xq1, xq1 ;q = 0
next_vect16:
sub tmp, 1 ;Inner loop for each source vector
mov ptr, [arg2+tmp*PS] ; get pointer to next vect
pxor xq1, xs1 ; q1 ^= s1
pxor xtmp1, xtmp1 ; xtmp = 0
pcmpgtb xtmp1, xq1 ; xtmp = mask 0xff or 0x00 if bit7 set
pand xtmp1, xpoly ; xtmp = poly or 0x00
pxor xp1, xs1 ; p ^= s
paddb xq1, xq1 ; q = q<<1
pxor xq1, xtmp1 ; q = q<<1 ^ poly_masked
XLDR xs1, [ptr+pos] ; Get next vector (source data)
jg next_vect16 ; Loop for each vect except 0
mov ptr, [arg2+PS+vec*PS] ;Get address of P parity vector
mov tmp, [arg2+(2*PS)+vec*PS] ;Get address of Q parity vector
pxor xp1, xs1 ;p ^= s[0] - last source is already loaded
pxor xq1, xs1 ;q ^= 1 * s[0]
XSTR [ptr+pos], xp1 ;Write parity P vector
XSTR [tmp+pos], xq1 ;Write parity Q vector
add pos, 16
cmp pos, len
jl loop16
return_pass:
mov return, 0
FUNC_RESTORE
ret
return_fail:
mov return, 1
FUNC_RESTORE
ret
endproc_frame
section .data
align 16
poly:
dq 0x1d1d1d1d1d1d1d1d, 0x1d1d1d1d1d1d1d1d
;;; func core, ver, snum
slversion pq_gen_sse, 00, 08, 0032
|
; ########################################################################################
; # Generated by the active disassembly feature of the Exodus emulation platform
; #
; # Creation Date: 2020-11-26 11:22:26
; # Analysis Region: 0x00003A70 - 0x00003B0A
; # script parser, control code handler
; ########################################################################################
org $00003A70
CurrentChar equr d2 ; data register with current character code
StringROMOffset equr a0 ; address register with start of string in ROM
StringRAMOffset equr a1 ; RAM offset for current character
CharROMOffset equr a2 ; address register with current character position in ROM
ScriptParser:
CLR.w CurrentChar
MOVE.b (CharROMOffset)+, CurrentChar
BEQ.w *+$8A ; should be $88 ; check if code is $00 (end of line marker)
CMPI.b #3, CurrentChar ; check if code is $01,$02 (for kanji, multi-byte variables)
BCC.b CharGTE3 ; skip next two lines if CurrentChar is >= 3
CharLT3:
MOVE.b CurrentChar, (StringRAMOffset)+ ; if it's multibyte, put byte in RAM and grab next byte
MOVE.b (CharROMOffset)+, (StringRAMOffset)+ ; move next byte straight into RAM as well
BRA.B ScriptParser ; return to top
CharGTE3:
BNE.b CharNot3
MOVEA.l (A6)+, StringROMOffset
Unk1:
MOVE.b (StringROMOffset)+, D3
BEQ.b Unk2
CMPI.b #3, D3
BCC.b *+$6 ; add 2 cuz asm68k is the devil
MOVE.b D3, (StringRAMOffset)+
MOVE.b (StringROMOffset)+, D3
MOVE.b D3, (StringRAMOffset)+
BRA.b Unk1
Unk2:
BRA.b ScriptParser
CharNot3:
CMPI.b #4, CurrentChar
BNE.b *+$12 ; add 2 cuz asm68k is the devil
MOVE.l (A6)+, CurrentChar
CLR.w D3
MOVE.b (CharROMOffset)+, D3
MOVEA.l StringRAMOffset, StringROMOffset
MOVEQ #$0000000F, D4
; BSR.w *+$FFFFFCF0
dc.l $6100FCF0
BRA.b ScriptParser
CharNot4:
CMPI.b #5, CurrentChar
BNE.b CharNot5
MOVE.b (CharROMOffset)+, CurrentChar
; adding 2 to all jumps...
BSR.w *+$6722
BSR.w *+$FFFFFA92
Unk3:
TST.b (StringRAMOffset)
BEQ.b *+$6
ADDQ.l #1, StringRAMOffset
BRA.b Unk3
BRA.b ScriptParser
CharNot5:
; added 2 to branches
CMPI.b #6, CurrentChar ; $06 is a variable for player names, item names, etc.
BNE.b CharNot6
MOVEA.l (A6)+, StringROMOffset
BSR.w *+$FFFFFA7C
Unk4:
TST.b (StringRAMOffset)
BEQ.b *+$6
ADDQ.l #1, StringRAMOffset
BRA.b Unk4
BRA.b ScriptParser
CharNot6:
CMPI.b #$0F, CurrentChar
BCC.b PutCharInRam
CharLT0F:
CMPI.b #$0D, CurrentChar
BEQ.b LineBreak
CMPI.b #$0C, CurrentChar
Scroll:
BNE.b Scroll
LineBreak:
TST.w D1
BNE.b PrepForPrint
PutCharInRam:
MOVE.b CurrentChar, (StringRAMOffset)+
BRA.w ScriptParser
PrepForPrint:
CLR.b (A1)
MOVEA.l A2, A0
SUBQ.l #1, A0
MOVEM.l (A7)+, D0/D1/D2/D3/D4/A1/A2
RTS
|
_ls: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
close(fd);
}
int
main(int argc, char *argv[])
{
0: 8d 4c 24 04 lea 0x4(%esp),%ecx
4: 83 e4 f0 and $0xfffffff0,%esp
7: ff 71 fc pushl -0x4(%ecx)
a: 55 push %ebp
b: 89 e5 mov %esp,%ebp
d: 57 push %edi
e: 56 push %esi
f: 53 push %ebx
10: 51 push %ecx
11: bb 01 00 00 00 mov $0x1,%ebx
16: 83 ec 08 sub $0x8,%esp
19: 8b 31 mov (%ecx),%esi
1b: 8b 79 04 mov 0x4(%ecx),%edi
int i;
if(argc < 2){
1e: 83 fe 01 cmp $0x1,%esi
21: 7e 1f jle 42 <main+0x42>
23: 90 nop
24: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
ls(".");
exit();
}
for(i=1; i<argc; i++)
ls(argv[i]);
28: 83 ec 0c sub $0xc,%esp
2b: ff 34 9f pushl (%edi,%ebx,4)
if(argc < 2){
ls(".");
exit();
}
for(i=1; i<argc; i++)
2e: 83 c3 01 add $0x1,%ebx
ls(argv[i]);
31: e8 ca 00 00 00 call 100 <ls>
if(argc < 2){
ls(".");
exit();
}
for(i=1; i<argc; i++)
36: 83 c4 10 add $0x10,%esp
39: 39 de cmp %ebx,%esi
3b: 75 eb jne 28 <main+0x28>
ls(argv[i]);
exit();
3d: e8 40 05 00 00 call 582 <exit>
main(int argc, char *argv[])
{
int i;
if(argc < 2){
ls(".");
42: 83 ec 0c sub $0xc,%esp
45: 68 48 0a 00 00 push $0xa48
4a: e8 b1 00 00 00 call 100 <ls>
exit();
4f: e8 2e 05 00 00 call 582 <exit>
54: 66 90 xchg %ax,%ax
56: 66 90 xchg %ax,%ax
58: 66 90 xchg %ax,%ax
5a: 66 90 xchg %ax,%ax
5c: 66 90 xchg %ax,%ax
5e: 66 90 xchg %ax,%ax
00000060 <fmtname>:
#include "user.h"
#include "fs.h"
char*
fmtname(char *path)
{
60: 55 push %ebp
61: 89 e5 mov %esp,%ebp
63: 56 push %esi
64: 53 push %ebx
65: 8b 5d 08 mov 0x8(%ebp),%ebx
static char buf[DIRSIZ+1];
char *p;
// Find first character after last slash.
for(p=path+strlen(path); p >= path && *p != '/'; p--)
68: 83 ec 0c sub $0xc,%esp
6b: 53 push %ebx
6c: e8 4f 03 00 00 call 3c0 <strlen>
71: 83 c4 10 add $0x10,%esp
74: 01 d8 add %ebx,%eax
76: 73 0f jae 87 <fmtname+0x27>
78: eb 12 jmp 8c <fmtname+0x2c>
7a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
80: 83 e8 01 sub $0x1,%eax
83: 39 c3 cmp %eax,%ebx
85: 77 05 ja 8c <fmtname+0x2c>
87: 80 38 2f cmpb $0x2f,(%eax)
8a: 75 f4 jne 80 <fmtname+0x20>
;
p++;
8c: 8d 58 01 lea 0x1(%eax),%ebx
// Return blank-padded name.
if(strlen(p) >= DIRSIZ)
8f: 83 ec 0c sub $0xc,%esp
92: 53 push %ebx
93: e8 28 03 00 00 call 3c0 <strlen>
98: 83 c4 10 add $0x10,%esp
9b: 83 f8 0d cmp $0xd,%eax
9e: 77 4a ja ea <fmtname+0x8a>
return p;
memmove(buf, p, strlen(p));
a0: 83 ec 0c sub $0xc,%esp
a3: 53 push %ebx
a4: e8 17 03 00 00 call 3c0 <strlen>
a9: 83 c4 0c add $0xc,%esp
ac: 50 push %eax
ad: 53 push %ebx
ae: 68 60 0d 00 00 push $0xd60
b3: e8 98 04 00 00 call 550 <memmove>
memset(buf+strlen(p), ' ', DIRSIZ-strlen(p));
b8: 89 1c 24 mov %ebx,(%esp)
bb: e8 00 03 00 00 call 3c0 <strlen>
c0: 89 1c 24 mov %ebx,(%esp)
c3: 89 c6 mov %eax,%esi
return buf;
c5: bb 60 0d 00 00 mov $0xd60,%ebx
// Return blank-padded name.
if(strlen(p) >= DIRSIZ)
return p;
memmove(buf, p, strlen(p));
memset(buf+strlen(p), ' ', DIRSIZ-strlen(p));
ca: e8 f1 02 00 00 call 3c0 <strlen>
cf: ba 0e 00 00 00 mov $0xe,%edx
d4: 83 c4 0c add $0xc,%esp
d7: 05 60 0d 00 00 add $0xd60,%eax
dc: 29 f2 sub %esi,%edx
de: 52 push %edx
df: 6a 20 push $0x20
e1: 50 push %eax
e2: e8 09 03 00 00 call 3f0 <memset>
return buf;
e7: 83 c4 10 add $0x10,%esp
}
ea: 8d 65 f8 lea -0x8(%ebp),%esp
ed: 89 d8 mov %ebx,%eax
ef: 5b pop %ebx
f0: 5e pop %esi
f1: 5d pop %ebp
f2: c3 ret
f3: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000100 <ls>:
void
ls(char *path)
{
100: 55 push %ebp
101: 89 e5 mov %esp,%ebp
103: 57 push %edi
104: 56 push %esi
105: 53 push %ebx
106: 81 ec 64 02 00 00 sub $0x264,%esp
10c: 8b 7d 08 mov 0x8(%ebp),%edi
char buf[512], *p;
int fd;
struct dirent de;
struct stat st;
if((fd = open(path, 0)) < 0){
10f: 6a 00 push $0x0
111: 57 push %edi
112: e8 ab 04 00 00 call 5c2 <open>
117: 83 c4 10 add $0x10,%esp
11a: 85 c0 test %eax,%eax
11c: 0f 88 9e 01 00 00 js 2c0 <ls+0x1c0>
printf(2, "ls: cannot open %s\n", path);
return;
}
if(fstat(fd, &st) < 0){
122: 8d b5 d4 fd ff ff lea -0x22c(%ebp),%esi
128: 83 ec 08 sub $0x8,%esp
12b: 89 c3 mov %eax,%ebx
12d: 56 push %esi
12e: 50 push %eax
12f: e8 a6 04 00 00 call 5da <fstat>
134: 83 c4 10 add $0x10,%esp
137: 85 c0 test %eax,%eax
139: 0f 88 c1 01 00 00 js 300 <ls+0x200>
printf(2, "ls: cannot stat %s\n", path);
close(fd);
return;
}
switch(st.type){
13f: 0f b7 85 d4 fd ff ff movzwl -0x22c(%ebp),%eax
146: 66 83 f8 01 cmp $0x1,%ax
14a: 74 54 je 1a0 <ls+0xa0>
14c: 66 83 f8 02 cmp $0x2,%ax
150: 75 37 jne 189 <ls+0x89>
case T_FILE:
printf(1, "%s %d %d %d\n", fmtname(path), st.type, st.ino, st.size);
152: 83 ec 0c sub $0xc,%esp
155: 8b 95 e4 fd ff ff mov -0x21c(%ebp),%edx
15b: 8b b5 dc fd ff ff mov -0x224(%ebp),%esi
161: 57 push %edi
162: 89 95 b4 fd ff ff mov %edx,-0x24c(%ebp)
168: e8 f3 fe ff ff call 60 <fmtname>
16d: 8b 95 b4 fd ff ff mov -0x24c(%ebp),%edx
173: 59 pop %ecx
174: 5f pop %edi
175: 52 push %edx
176: 56 push %esi
177: 6a 02 push $0x2
179: 50 push %eax
17a: 68 28 0a 00 00 push $0xa28
17f: 6a 01 push $0x1
181: e8 5a 05 00 00 call 6e0 <printf>
break;
186: 83 c4 20 add $0x20,%esp
}
printf(1, "%s %d %d %d\n", fmtname(buf), st.type, st.ino, st.size);
}
break;
}
close(fd);
189: 83 ec 0c sub $0xc,%esp
18c: 53 push %ebx
18d: e8 18 04 00 00 call 5aa <close>
192: 83 c4 10 add $0x10,%esp
}
195: 8d 65 f4 lea -0xc(%ebp),%esp
198: 5b pop %ebx
199: 5e pop %esi
19a: 5f pop %edi
19b: 5d pop %ebp
19c: c3 ret
19d: 8d 76 00 lea 0x0(%esi),%esi
case T_FILE:
printf(1, "%s %d %d %d\n", fmtname(path), st.type, st.ino, st.size);
break;
case T_DIR:
if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
1a0: 83 ec 0c sub $0xc,%esp
1a3: 57 push %edi
1a4: e8 17 02 00 00 call 3c0 <strlen>
1a9: 83 c0 10 add $0x10,%eax
1ac: 83 c4 10 add $0x10,%esp
1af: 3d 00 02 00 00 cmp $0x200,%eax
1b4: 0f 87 26 01 00 00 ja 2e0 <ls+0x1e0>
printf(1, "ls: path too long\n");
break;
}
strcpy(buf, path);
1ba: 8d 85 e8 fd ff ff lea -0x218(%ebp),%eax
1c0: 83 ec 08 sub $0x8,%esp
1c3: 57 push %edi
1c4: 8d bd c4 fd ff ff lea -0x23c(%ebp),%edi
1ca: 50 push %eax
1cb: e8 70 01 00 00 call 340 <strcpy>
p = buf+strlen(buf);
1d0: 8d 85 e8 fd ff ff lea -0x218(%ebp),%eax
1d6: 89 04 24 mov %eax,(%esp)
1d9: e8 e2 01 00 00 call 3c0 <strlen>
1de: 8d 95 e8 fd ff ff lea -0x218(%ebp),%edx
*p++ = '/';
while(read(fd, &de, sizeof(de)) == sizeof(de)){
1e4: 83 c4 10 add $0x10,%esp
if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
printf(1, "ls: path too long\n");
break;
}
strcpy(buf, path);
p = buf+strlen(buf);
1e7: 8d 0c 02 lea (%edx,%eax,1),%ecx
*p++ = '/';
1ea: 8d 84 05 e9 fd ff ff lea -0x217(%ebp,%eax,1),%eax
if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
printf(1, "ls: path too long\n");
break;
}
strcpy(buf, path);
p = buf+strlen(buf);
1f1: 89 8d a8 fd ff ff mov %ecx,-0x258(%ebp)
*p++ = '/';
1f7: 89 85 a4 fd ff ff mov %eax,-0x25c(%ebp)
1fd: c6 01 2f movb $0x2f,(%ecx)
while(read(fd, &de, sizeof(de)) == sizeof(de)){
200: 83 ec 04 sub $0x4,%esp
203: 6a 10 push $0x10
205: 57 push %edi
206: 53 push %ebx
207: e8 8e 03 00 00 call 59a <read>
20c: 83 c4 10 add $0x10,%esp
20f: 83 f8 10 cmp $0x10,%eax
212: 0f 85 71 ff ff ff jne 189 <ls+0x89>
if(de.inum == 0)
218: 66 83 bd c4 fd ff ff cmpw $0x0,-0x23c(%ebp)
21f: 00
220: 74 de je 200 <ls+0x100>
continue;
memmove(p, de.name, DIRSIZ);
222: 8d 85 c6 fd ff ff lea -0x23a(%ebp),%eax
228: 83 ec 04 sub $0x4,%esp
22b: 6a 0e push $0xe
22d: 50 push %eax
22e: ff b5 a4 fd ff ff pushl -0x25c(%ebp)
234: e8 17 03 00 00 call 550 <memmove>
p[DIRSIZ] = 0;
239: 8b 85 a8 fd ff ff mov -0x258(%ebp),%eax
23f: c6 40 0f 00 movb $0x0,0xf(%eax)
if(stat(buf, &st) < 0){
243: 58 pop %eax
244: 8d 85 e8 fd ff ff lea -0x218(%ebp),%eax
24a: 5a pop %edx
24b: 56 push %esi
24c: 50 push %eax
24d: e8 6e 02 00 00 call 4c0 <stat>
252: 83 c4 10 add $0x10,%esp
255: 85 c0 test %eax,%eax
257: 0f 88 c3 00 00 00 js 320 <ls+0x220>
printf(1, "ls: cannot stat %s\n", buf);
continue;
}
printf(1, "%s %d %d %d\n", fmtname(buf), st.type, st.ino, st.size);
25d: 8b 8d e4 fd ff ff mov -0x21c(%ebp),%ecx
263: 0f bf 85 d4 fd ff ff movswl -0x22c(%ebp),%eax
26a: 83 ec 0c sub $0xc,%esp
26d: 8b 95 dc fd ff ff mov -0x224(%ebp),%edx
273: 89 8d ac fd ff ff mov %ecx,-0x254(%ebp)
279: 8d 8d e8 fd ff ff lea -0x218(%ebp),%ecx
27f: 89 95 b0 fd ff ff mov %edx,-0x250(%ebp)
285: 89 85 b4 fd ff ff mov %eax,-0x24c(%ebp)
28b: 51 push %ecx
28c: e8 cf fd ff ff call 60 <fmtname>
291: 5a pop %edx
292: 8b 95 b0 fd ff ff mov -0x250(%ebp),%edx
298: 59 pop %ecx
299: 8b 8d ac fd ff ff mov -0x254(%ebp),%ecx
29f: 51 push %ecx
2a0: 52 push %edx
2a1: ff b5 b4 fd ff ff pushl -0x24c(%ebp)
2a7: 50 push %eax
2a8: 68 28 0a 00 00 push $0xa28
2ad: 6a 01 push $0x1
2af: e8 2c 04 00 00 call 6e0 <printf>
2b4: 83 c4 20 add $0x20,%esp
2b7: e9 44 ff ff ff jmp 200 <ls+0x100>
2bc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
int fd;
struct dirent de;
struct stat st;
if((fd = open(path, 0)) < 0){
printf(2, "ls: cannot open %s\n", path);
2c0: 83 ec 04 sub $0x4,%esp
2c3: 57 push %edi
2c4: 68 00 0a 00 00 push $0xa00
2c9: 6a 02 push $0x2
2cb: e8 10 04 00 00 call 6e0 <printf>
return;
2d0: 83 c4 10 add $0x10,%esp
printf(1, "%s %d %d %d\n", fmtname(buf), st.type, st.ino, st.size);
}
break;
}
close(fd);
}
2d3: 8d 65 f4 lea -0xc(%ebp),%esp
2d6: 5b pop %ebx
2d7: 5e pop %esi
2d8: 5f pop %edi
2d9: 5d pop %ebp
2da: c3 ret
2db: 90 nop
2dc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
printf(1, "%s %d %d %d\n", fmtname(path), st.type, st.ino, st.size);
break;
case T_DIR:
if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
printf(1, "ls: path too long\n");
2e0: 83 ec 08 sub $0x8,%esp
2e3: 68 35 0a 00 00 push $0xa35
2e8: 6a 01 push $0x1
2ea: e8 f1 03 00 00 call 6e0 <printf>
break;
2ef: 83 c4 10 add $0x10,%esp
2f2: e9 92 fe ff ff jmp 189 <ls+0x89>
2f7: 89 f6 mov %esi,%esi
2f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
printf(2, "ls: cannot open %s\n", path);
return;
}
if(fstat(fd, &st) < 0){
printf(2, "ls: cannot stat %s\n", path);
300: 83 ec 04 sub $0x4,%esp
303: 57 push %edi
304: 68 14 0a 00 00 push $0xa14
309: 6a 02 push $0x2
30b: e8 d0 03 00 00 call 6e0 <printf>
close(fd);
310: 89 1c 24 mov %ebx,(%esp)
313: e8 92 02 00 00 call 5aa <close>
return;
318: 83 c4 10 add $0x10,%esp
31b: e9 75 fe ff ff jmp 195 <ls+0x95>
if(de.inum == 0)
continue;
memmove(p, de.name, DIRSIZ);
p[DIRSIZ] = 0;
if(stat(buf, &st) < 0){
printf(1, "ls: cannot stat %s\n", buf);
320: 8d 85 e8 fd ff ff lea -0x218(%ebp),%eax
326: 83 ec 04 sub $0x4,%esp
329: 50 push %eax
32a: 68 14 0a 00 00 push $0xa14
32f: 6a 01 push $0x1
331: e8 aa 03 00 00 call 6e0 <printf>
continue;
336: 83 c4 10 add $0x10,%esp
339: e9 c2 fe ff ff jmp 200 <ls+0x100>
33e: 66 90 xchg %ax,%ax
00000340 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, const char *t)
{
340: 55 push %ebp
341: 89 e5 mov %esp,%ebp
343: 53 push %ebx
344: 8b 45 08 mov 0x8(%ebp),%eax
347: 8b 4d 0c mov 0xc(%ebp),%ecx
char *os;
os = s;
while((*s++ = *t++) != 0)
34a: 89 c2 mov %eax,%edx
34c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
350: 83 c1 01 add $0x1,%ecx
353: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
357: 83 c2 01 add $0x1,%edx
35a: 84 db test %bl,%bl
35c: 88 5a ff mov %bl,-0x1(%edx)
35f: 75 ef jne 350 <strcpy+0x10>
;
return os;
}
361: 5b pop %ebx
362: 5d pop %ebp
363: c3 ret
364: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
36a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000370 <strcmp>:
int
strcmp(const char *p, const char *q)
{
370: 55 push %ebp
371: 89 e5 mov %esp,%ebp
373: 56 push %esi
374: 53 push %ebx
375: 8b 55 08 mov 0x8(%ebp),%edx
378: 8b 4d 0c mov 0xc(%ebp),%ecx
while(*p && *p == *q)
37b: 0f b6 02 movzbl (%edx),%eax
37e: 0f b6 19 movzbl (%ecx),%ebx
381: 84 c0 test %al,%al
383: 75 1e jne 3a3 <strcmp+0x33>
385: eb 29 jmp 3b0 <strcmp+0x40>
387: 89 f6 mov %esi,%esi
389: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
p++, q++;
390: 83 c2 01 add $0x1,%edx
}
int
strcmp(const char *p, const char *q)
{
while(*p && *p == *q)
393: 0f b6 02 movzbl (%edx),%eax
p++, q++;
396: 8d 71 01 lea 0x1(%ecx),%esi
}
int
strcmp(const char *p, const char *q)
{
while(*p && *p == *q)
399: 0f b6 59 01 movzbl 0x1(%ecx),%ebx
39d: 84 c0 test %al,%al
39f: 74 0f je 3b0 <strcmp+0x40>
3a1: 89 f1 mov %esi,%ecx
3a3: 38 d8 cmp %bl,%al
3a5: 74 e9 je 390 <strcmp+0x20>
p++, q++;
return (uchar)*p - (uchar)*q;
3a7: 29 d8 sub %ebx,%eax
}
3a9: 5b pop %ebx
3aa: 5e pop %esi
3ab: 5d pop %ebp
3ac: c3 ret
3ad: 8d 76 00 lea 0x0(%esi),%esi
}
int
strcmp(const char *p, const char *q)
{
while(*p && *p == *q)
3b0: 31 c0 xor %eax,%eax
p++, q++;
return (uchar)*p - (uchar)*q;
3b2: 29 d8 sub %ebx,%eax
}
3b4: 5b pop %ebx
3b5: 5e pop %esi
3b6: 5d pop %ebp
3b7: c3 ret
3b8: 90 nop
3b9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
000003c0 <strlen>:
uint
strlen(const char *s)
{
3c0: 55 push %ebp
3c1: 89 e5 mov %esp,%ebp
3c3: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
3c6: 80 39 00 cmpb $0x0,(%ecx)
3c9: 74 12 je 3dd <strlen+0x1d>
3cb: 31 d2 xor %edx,%edx
3cd: 8d 76 00 lea 0x0(%esi),%esi
3d0: 83 c2 01 add $0x1,%edx
3d3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
3d7: 89 d0 mov %edx,%eax
3d9: 75 f5 jne 3d0 <strlen+0x10>
;
return n;
}
3db: 5d pop %ebp
3dc: c3 ret
uint
strlen(const char *s)
{
int n;
for(n = 0; s[n]; n++)
3dd: 31 c0 xor %eax,%eax
;
return n;
}
3df: 5d pop %ebp
3e0: c3 ret
3e1: eb 0d jmp 3f0 <memset>
3e3: 90 nop
3e4: 90 nop
3e5: 90 nop
3e6: 90 nop
3e7: 90 nop
3e8: 90 nop
3e9: 90 nop
3ea: 90 nop
3eb: 90 nop
3ec: 90 nop
3ed: 90 nop
3ee: 90 nop
3ef: 90 nop
000003f0 <memset>:
void*
memset(void *dst, int c, uint n)
{
3f0: 55 push %ebp
3f1: 89 e5 mov %esp,%ebp
3f3: 57 push %edi
3f4: 8b 55 08 mov 0x8(%ebp),%edx
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
3f7: 8b 4d 10 mov 0x10(%ebp),%ecx
3fa: 8b 45 0c mov 0xc(%ebp),%eax
3fd: 89 d7 mov %edx,%edi
3ff: fc cld
400: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
402: 89 d0 mov %edx,%eax
404: 5f pop %edi
405: 5d pop %ebp
406: c3 ret
407: 89 f6 mov %esi,%esi
409: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000410 <strchr>:
char*
strchr(const char *s, char c)
{
410: 55 push %ebp
411: 89 e5 mov %esp,%ebp
413: 53 push %ebx
414: 8b 45 08 mov 0x8(%ebp),%eax
417: 8b 5d 0c mov 0xc(%ebp),%ebx
for(; *s; s++)
41a: 0f b6 10 movzbl (%eax),%edx
41d: 84 d2 test %dl,%dl
41f: 74 1d je 43e <strchr+0x2e>
if(*s == c)
421: 38 d3 cmp %dl,%bl
423: 89 d9 mov %ebx,%ecx
425: 75 0d jne 434 <strchr+0x24>
427: eb 17 jmp 440 <strchr+0x30>
429: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
430: 38 ca cmp %cl,%dl
432: 74 0c je 440 <strchr+0x30>
}
char*
strchr(const char *s, char c)
{
for(; *s; s++)
434: 83 c0 01 add $0x1,%eax
437: 0f b6 10 movzbl (%eax),%edx
43a: 84 d2 test %dl,%dl
43c: 75 f2 jne 430 <strchr+0x20>
if(*s == c)
return (char*)s;
return 0;
43e: 31 c0 xor %eax,%eax
}
440: 5b pop %ebx
441: 5d pop %ebp
442: c3 ret
443: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
449: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000450 <gets>:
char*
gets(char *buf, int max)
{
450: 55 push %ebp
451: 89 e5 mov %esp,%ebp
453: 57 push %edi
454: 56 push %esi
455: 53 push %ebx
int i, cc;
char c;
for(i=0; i+1 < max; ){
456: 31 f6 xor %esi,%esi
cc = read(0, &c, 1);
458: 8d 7d e7 lea -0x19(%ebp),%edi
return 0;
}
char*
gets(char *buf, int max)
{
45b: 83 ec 1c sub $0x1c,%esp
int i, cc;
char c;
for(i=0; i+1 < max; ){
45e: eb 29 jmp 489 <gets+0x39>
cc = read(0, &c, 1);
460: 83 ec 04 sub $0x4,%esp
463: 6a 01 push $0x1
465: 57 push %edi
466: 6a 00 push $0x0
468: e8 2d 01 00 00 call 59a <read>
if(cc < 1)
46d: 83 c4 10 add $0x10,%esp
470: 85 c0 test %eax,%eax
472: 7e 1d jle 491 <gets+0x41>
break;
buf[i++] = c;
474: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
478: 8b 55 08 mov 0x8(%ebp),%edx
47b: 89 de mov %ebx,%esi
if(c == '\n' || c == '\r')
47d: 3c 0a cmp $0xa,%al
for(i=0; i+1 < max; ){
cc = read(0, &c, 1);
if(cc < 1)
break;
buf[i++] = c;
47f: 88 44 1a ff mov %al,-0x1(%edx,%ebx,1)
if(c == '\n' || c == '\r')
483: 74 1b je 4a0 <gets+0x50>
485: 3c 0d cmp $0xd,%al
487: 74 17 je 4a0 <gets+0x50>
gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
489: 8d 5e 01 lea 0x1(%esi),%ebx
48c: 3b 5d 0c cmp 0xc(%ebp),%ebx
48f: 7c cf jl 460 <gets+0x10>
break;
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '\0';
491: 8b 45 08 mov 0x8(%ebp),%eax
494: c6 04 30 00 movb $0x0,(%eax,%esi,1)
return buf;
}
498: 8d 65 f4 lea -0xc(%ebp),%esp
49b: 5b pop %ebx
49c: 5e pop %esi
49d: 5f pop %edi
49e: 5d pop %ebp
49f: c3 ret
break;
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '\0';
4a0: 8b 45 08 mov 0x8(%ebp),%eax
gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
4a3: 89 de mov %ebx,%esi
break;
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '\0';
4a5: c6 04 30 00 movb $0x0,(%eax,%esi,1)
return buf;
}
4a9: 8d 65 f4 lea -0xc(%ebp),%esp
4ac: 5b pop %ebx
4ad: 5e pop %esi
4ae: 5f pop %edi
4af: 5d pop %ebp
4b0: c3 ret
4b1: eb 0d jmp 4c0 <stat>
4b3: 90 nop
4b4: 90 nop
4b5: 90 nop
4b6: 90 nop
4b7: 90 nop
4b8: 90 nop
4b9: 90 nop
4ba: 90 nop
4bb: 90 nop
4bc: 90 nop
4bd: 90 nop
4be: 90 nop
4bf: 90 nop
000004c0 <stat>:
int
stat(const char *n, struct stat *st)
{
4c0: 55 push %ebp
4c1: 89 e5 mov %esp,%ebp
4c3: 56 push %esi
4c4: 53 push %ebx
int fd;
int r;
fd = open(n, O_RDONLY);
4c5: 83 ec 08 sub $0x8,%esp
4c8: 6a 00 push $0x0
4ca: ff 75 08 pushl 0x8(%ebp)
4cd: e8 f0 00 00 00 call 5c2 <open>
if(fd < 0)
4d2: 83 c4 10 add $0x10,%esp
4d5: 85 c0 test %eax,%eax
4d7: 78 27 js 500 <stat+0x40>
return -1;
r = fstat(fd, st);
4d9: 83 ec 08 sub $0x8,%esp
4dc: ff 75 0c pushl 0xc(%ebp)
4df: 89 c3 mov %eax,%ebx
4e1: 50 push %eax
4e2: e8 f3 00 00 00 call 5da <fstat>
4e7: 89 c6 mov %eax,%esi
close(fd);
4e9: 89 1c 24 mov %ebx,(%esp)
4ec: e8 b9 00 00 00 call 5aa <close>
return r;
4f1: 83 c4 10 add $0x10,%esp
4f4: 89 f0 mov %esi,%eax
}
4f6: 8d 65 f8 lea -0x8(%ebp),%esp
4f9: 5b pop %ebx
4fa: 5e pop %esi
4fb: 5d pop %ebp
4fc: c3 ret
4fd: 8d 76 00 lea 0x0(%esi),%esi
int fd;
int r;
fd = open(n, O_RDONLY);
if(fd < 0)
return -1;
500: b8 ff ff ff ff mov $0xffffffff,%eax
505: eb ef jmp 4f6 <stat+0x36>
507: 89 f6 mov %esi,%esi
509: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000510 <atoi>:
return r;
}
int
atoi(const char *s)
{
510: 55 push %ebp
511: 89 e5 mov %esp,%ebp
513: 53 push %ebx
514: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
n = 0;
while('0' <= *s && *s <= '9')
517: 0f be 11 movsbl (%ecx),%edx
51a: 8d 42 d0 lea -0x30(%edx),%eax
51d: 3c 09 cmp $0x9,%al
51f: b8 00 00 00 00 mov $0x0,%eax
524: 77 1f ja 545 <atoi+0x35>
526: 8d 76 00 lea 0x0(%esi),%esi
529: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
n = n*10 + *s++ - '0';
530: 8d 04 80 lea (%eax,%eax,4),%eax
533: 83 c1 01 add $0x1,%ecx
536: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
atoi(const char *s)
{
int n;
n = 0;
while('0' <= *s && *s <= '9')
53a: 0f be 11 movsbl (%ecx),%edx
53d: 8d 5a d0 lea -0x30(%edx),%ebx
540: 80 fb 09 cmp $0x9,%bl
543: 76 eb jbe 530 <atoi+0x20>
n = n*10 + *s++ - '0';
return n;
}
545: 5b pop %ebx
546: 5d pop %ebp
547: c3 ret
548: 90 nop
549: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000550 <memmove>:
void*
memmove(void *vdst, const void *vsrc, int n)
{
550: 55 push %ebp
551: 89 e5 mov %esp,%ebp
553: 56 push %esi
554: 53 push %ebx
555: 8b 5d 10 mov 0x10(%ebp),%ebx
558: 8b 45 08 mov 0x8(%ebp),%eax
55b: 8b 75 0c mov 0xc(%ebp),%esi
char *dst;
const char *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
55e: 85 db test %ebx,%ebx
560: 7e 14 jle 576 <memmove+0x26>
562: 31 d2 xor %edx,%edx
564: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
*dst++ = *src++;
568: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
56c: 88 0c 10 mov %cl,(%eax,%edx,1)
56f: 83 c2 01 add $0x1,%edx
char *dst;
const char *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
572: 39 da cmp %ebx,%edx
574: 75 f2 jne 568 <memmove+0x18>
*dst++ = *src++;
return vdst;
}
576: 5b pop %ebx
577: 5e pop %esi
578: 5d pop %ebp
579: c3 ret
0000057a <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
57a: b8 01 00 00 00 mov $0x1,%eax
57f: cd 40 int $0x40
581: c3 ret
00000582 <exit>:
SYSCALL(exit)
582: b8 02 00 00 00 mov $0x2,%eax
587: cd 40 int $0x40
589: c3 ret
0000058a <wait>:
SYSCALL(wait)
58a: b8 03 00 00 00 mov $0x3,%eax
58f: cd 40 int $0x40
591: c3 ret
00000592 <pipe>:
SYSCALL(pipe)
592: b8 04 00 00 00 mov $0x4,%eax
597: cd 40 int $0x40
599: c3 ret
0000059a <read>:
SYSCALL(read)
59a: b8 05 00 00 00 mov $0x5,%eax
59f: cd 40 int $0x40
5a1: c3 ret
000005a2 <write>:
SYSCALL(write)
5a2: b8 10 00 00 00 mov $0x10,%eax
5a7: cd 40 int $0x40
5a9: c3 ret
000005aa <close>:
SYSCALL(close)
5aa: b8 15 00 00 00 mov $0x15,%eax
5af: cd 40 int $0x40
5b1: c3 ret
000005b2 <kill>:
SYSCALL(kill)
5b2: b8 06 00 00 00 mov $0x6,%eax
5b7: cd 40 int $0x40
5b9: c3 ret
000005ba <exec>:
SYSCALL(exec)
5ba: b8 07 00 00 00 mov $0x7,%eax
5bf: cd 40 int $0x40
5c1: c3 ret
000005c2 <open>:
SYSCALL(open)
5c2: b8 0f 00 00 00 mov $0xf,%eax
5c7: cd 40 int $0x40
5c9: c3 ret
000005ca <mknod>:
SYSCALL(mknod)
5ca: b8 11 00 00 00 mov $0x11,%eax
5cf: cd 40 int $0x40
5d1: c3 ret
000005d2 <unlink>:
SYSCALL(unlink)
5d2: b8 12 00 00 00 mov $0x12,%eax
5d7: cd 40 int $0x40
5d9: c3 ret
000005da <fstat>:
SYSCALL(fstat)
5da: b8 08 00 00 00 mov $0x8,%eax
5df: cd 40 int $0x40
5e1: c3 ret
000005e2 <link>:
SYSCALL(link)
5e2: b8 13 00 00 00 mov $0x13,%eax
5e7: cd 40 int $0x40
5e9: c3 ret
000005ea <mkdir>:
SYSCALL(mkdir)
5ea: b8 14 00 00 00 mov $0x14,%eax
5ef: cd 40 int $0x40
5f1: c3 ret
000005f2 <chdir>:
SYSCALL(chdir)
5f2: b8 09 00 00 00 mov $0x9,%eax
5f7: cd 40 int $0x40
5f9: c3 ret
000005fa <dup>:
SYSCALL(dup)
5fa: b8 0a 00 00 00 mov $0xa,%eax
5ff: cd 40 int $0x40
601: c3 ret
00000602 <getpid>:
SYSCALL(getpid)
602: b8 0b 00 00 00 mov $0xb,%eax
607: cd 40 int $0x40
609: c3 ret
0000060a <sbrk>:
SYSCALL(sbrk)
60a: b8 0c 00 00 00 mov $0xc,%eax
60f: cd 40 int $0x40
611: c3 ret
00000612 <sleep>:
SYSCALL(sleep)
612: b8 0d 00 00 00 mov $0xd,%eax
617: cd 40 int $0x40
619: c3 ret
0000061a <uptime>:
SYSCALL(uptime)
61a: b8 0e 00 00 00 mov $0xe,%eax
61f: cd 40 int $0x40
621: c3 ret
00000622 <date>:
SYSCALL(date)
622: b8 16 00 00 00 mov $0x16,%eax
627: cd 40 int $0x40
629: c3 ret
0000062a <alarm>:
SYSCALL(alarm)
62a: b8 17 00 00 00 mov $0x17,%eax
62f: cd 40 int $0x40
631: c3 ret
632: 66 90 xchg %ax,%ax
634: 66 90 xchg %ax,%ax
636: 66 90 xchg %ax,%ax
638: 66 90 xchg %ax,%ax
63a: 66 90 xchg %ax,%ax
63c: 66 90 xchg %ax,%ax
63e: 66 90 xchg %ax,%ax
00000640 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
640: 55 push %ebp
641: 89 e5 mov %esp,%ebp
643: 57 push %edi
644: 56 push %esi
645: 53 push %ebx
646: 89 c6 mov %eax,%esi
648: 83 ec 3c sub $0x3c,%esp
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
64b: 8b 5d 08 mov 0x8(%ebp),%ebx
64e: 85 db test %ebx,%ebx
650: 74 7e je 6d0 <printint+0x90>
652: 89 d0 mov %edx,%eax
654: c1 e8 1f shr $0x1f,%eax
657: 84 c0 test %al,%al
659: 74 75 je 6d0 <printint+0x90>
neg = 1;
x = -xx;
65b: 89 d0 mov %edx,%eax
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
neg = 1;
65d: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
x = -xx;
664: f7 d8 neg %eax
666: 89 75 c0 mov %esi,-0x40(%ebp)
} else {
x = xx;
}
i = 0;
669: 31 ff xor %edi,%edi
66b: 8d 5d d7 lea -0x29(%ebp),%ebx
66e: 89 ce mov %ecx,%esi
670: eb 08 jmp 67a <printint+0x3a>
672: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
do{
buf[i++] = digits[x % base];
678: 89 cf mov %ecx,%edi
67a: 31 d2 xor %edx,%edx
67c: 8d 4f 01 lea 0x1(%edi),%ecx
67f: f7 f6 div %esi
681: 0f b6 92 54 0a 00 00 movzbl 0xa54(%edx),%edx
}while((x /= base) != 0);
688: 85 c0 test %eax,%eax
x = xx;
}
i = 0;
do{
buf[i++] = digits[x % base];
68a: 88 14 0b mov %dl,(%ebx,%ecx,1)
}while((x /= base) != 0);
68d: 75 e9 jne 678 <printint+0x38>
if(neg)
68f: 8b 45 c4 mov -0x3c(%ebp),%eax
692: 8b 75 c0 mov -0x40(%ebp),%esi
695: 85 c0 test %eax,%eax
697: 74 08 je 6a1 <printint+0x61>
buf[i++] = '-';
699: c6 44 0d d8 2d movb $0x2d,-0x28(%ebp,%ecx,1)
69e: 8d 4f 02 lea 0x2(%edi),%ecx
6a1: 8d 7c 0d d7 lea -0x29(%ebp,%ecx,1),%edi
6a5: 8d 76 00 lea 0x0(%esi),%esi
6a8: 0f b6 07 movzbl (%edi),%eax
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
6ab: 83 ec 04 sub $0x4,%esp
6ae: 83 ef 01 sub $0x1,%edi
6b1: 6a 01 push $0x1
6b3: 53 push %ebx
6b4: 56 push %esi
6b5: 88 45 d7 mov %al,-0x29(%ebp)
6b8: e8 e5 fe ff ff call 5a2 <write>
buf[i++] = digits[x % base];
}while((x /= base) != 0);
if(neg)
buf[i++] = '-';
while(--i >= 0)
6bd: 83 c4 10 add $0x10,%esp
6c0: 39 df cmp %ebx,%edi
6c2: 75 e4 jne 6a8 <printint+0x68>
putc(fd, buf[i]);
}
6c4: 8d 65 f4 lea -0xc(%ebp),%esp
6c7: 5b pop %ebx
6c8: 5e pop %esi
6c9: 5f pop %edi
6ca: 5d pop %ebp
6cb: c3 ret
6cc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
neg = 0;
if(sgn && xx < 0){
neg = 1;
x = -xx;
} else {
x = xx;
6d0: 89 d0 mov %edx,%eax
static char digits[] = "0123456789ABCDEF";
char buf[16];
int i, neg;
uint x;
neg = 0;
6d2: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
6d9: eb 8b jmp 666 <printint+0x26>
6db: 90 nop
6dc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
000006e0 <printf>:
}
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
6e0: 55 push %ebp
6e1: 89 e5 mov %esp,%ebp
6e3: 57 push %edi
6e4: 56 push %esi
6e5: 53 push %ebx
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
6e6: 8d 45 10 lea 0x10(%ebp),%eax
}
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
6e9: 83 ec 2c sub $0x2c,%esp
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
6ec: 8b 75 0c mov 0xc(%ebp),%esi
}
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
6ef: 8b 7d 08 mov 0x8(%ebp),%edi
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
6f2: 89 45 d0 mov %eax,-0x30(%ebp)
6f5: 0f b6 1e movzbl (%esi),%ebx
6f8: 83 c6 01 add $0x1,%esi
6fb: 84 db test %bl,%bl
6fd: 0f 84 b0 00 00 00 je 7b3 <printf+0xd3>
703: 31 d2 xor %edx,%edx
705: eb 39 jmp 740 <printf+0x60>
707: 89 f6 mov %esi,%esi
709: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
710: 83 f8 25 cmp $0x25,%eax
713: 89 55 d4 mov %edx,-0x2c(%ebp)
state = '%';
716: ba 25 00 00 00 mov $0x25,%edx
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
71b: 74 18 je 735 <printf+0x55>
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
71d: 8d 45 e2 lea -0x1e(%ebp),%eax
720: 83 ec 04 sub $0x4,%esp
723: 88 5d e2 mov %bl,-0x1e(%ebp)
726: 6a 01 push $0x1
728: 50 push %eax
729: 57 push %edi
72a: e8 73 fe ff ff call 5a2 <write>
72f: 8b 55 d4 mov -0x2c(%ebp),%edx
732: 83 c4 10 add $0x10,%esp
735: 83 c6 01 add $0x1,%esi
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
738: 0f b6 5e ff movzbl -0x1(%esi),%ebx
73c: 84 db test %bl,%bl
73e: 74 73 je 7b3 <printf+0xd3>
c = fmt[i] & 0xff;
if(state == 0){
740: 85 d2 test %edx,%edx
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
c = fmt[i] & 0xff;
742: 0f be cb movsbl %bl,%ecx
745: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
748: 74 c6 je 710 <printf+0x30>
if(c == '%'){
state = '%';
} else {
putc(fd, c);
}
} else if(state == '%'){
74a: 83 fa 25 cmp $0x25,%edx
74d: 75 e6 jne 735 <printf+0x55>
if(c == 'd'){
74f: 83 f8 64 cmp $0x64,%eax
752: 0f 84 f8 00 00 00 je 850 <printf+0x170>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
758: 81 e1 f7 00 00 00 and $0xf7,%ecx
75e: 83 f9 70 cmp $0x70,%ecx
761: 74 5d je 7c0 <printf+0xe0>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
763: 83 f8 73 cmp $0x73,%eax
766: 0f 84 84 00 00 00 je 7f0 <printf+0x110>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
76c: 83 f8 63 cmp $0x63,%eax
76f: 0f 84 ea 00 00 00 je 85f <printf+0x17f>
putc(fd, *ap);
ap++;
} else if(c == '%'){
775: 83 f8 25 cmp $0x25,%eax
778: 0f 84 c2 00 00 00 je 840 <printf+0x160>
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
77e: 8d 45 e7 lea -0x19(%ebp),%eax
781: 83 ec 04 sub $0x4,%esp
784: c6 45 e7 25 movb $0x25,-0x19(%ebp)
788: 6a 01 push $0x1
78a: 50 push %eax
78b: 57 push %edi
78c: e8 11 fe ff ff call 5a2 <write>
791: 83 c4 0c add $0xc,%esp
794: 8d 45 e6 lea -0x1a(%ebp),%eax
797: 88 5d e6 mov %bl,-0x1a(%ebp)
79a: 6a 01 push $0x1
79c: 50 push %eax
79d: 57 push %edi
79e: 83 c6 01 add $0x1,%esi
7a1: e8 fc fd ff ff call 5a2 <write>
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
7a6: 0f b6 5e ff movzbl -0x1(%esi),%ebx
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
7aa: 83 c4 10 add $0x10,%esp
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
7ad: 31 d2 xor %edx,%edx
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
7af: 84 db test %bl,%bl
7b1: 75 8d jne 740 <printf+0x60>
putc(fd, c);
}
state = 0;
}
}
}
7b3: 8d 65 f4 lea -0xc(%ebp),%esp
7b6: 5b pop %ebx
7b7: 5e pop %esi
7b8: 5f pop %edi
7b9: 5d pop %ebp
7ba: c3 ret
7bb: 90 nop
7bc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
} else if(state == '%'){
if(c == 'd'){
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
printint(fd, *ap, 16, 0);
7c0: 83 ec 0c sub $0xc,%esp
7c3: b9 10 00 00 00 mov $0x10,%ecx
7c8: 6a 00 push $0x0
7ca: 8b 5d d0 mov -0x30(%ebp),%ebx
7cd: 89 f8 mov %edi,%eax
7cf: 8b 13 mov (%ebx),%edx
7d1: e8 6a fe ff ff call 640 <printint>
ap++;
7d6: 89 d8 mov %ebx,%eax
7d8: 83 c4 10 add $0x10,%esp
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
7db: 31 d2 xor %edx,%edx
if(c == 'd'){
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
printint(fd, *ap, 16, 0);
ap++;
7dd: 83 c0 04 add $0x4,%eax
7e0: 89 45 d0 mov %eax,-0x30(%ebp)
7e3: e9 4d ff ff ff jmp 735 <printf+0x55>
7e8: 90 nop
7e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
} else if(c == 's'){
s = (char*)*ap;
7f0: 8b 45 d0 mov -0x30(%ebp),%eax
7f3: 8b 18 mov (%eax),%ebx
ap++;
7f5: 83 c0 04 add $0x4,%eax
7f8: 89 45 d0 mov %eax,-0x30(%ebp)
if(s == 0)
s = "(null)";
7fb: b8 4a 0a 00 00 mov $0xa4a,%eax
800: 85 db test %ebx,%ebx
802: 0f 44 d8 cmove %eax,%ebx
while(*s != 0){
805: 0f b6 03 movzbl (%ebx),%eax
808: 84 c0 test %al,%al
80a: 74 23 je 82f <printf+0x14f>
80c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
810: 88 45 e3 mov %al,-0x1d(%ebp)
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
813: 8d 45 e3 lea -0x1d(%ebp),%eax
816: 83 ec 04 sub $0x4,%esp
819: 6a 01 push $0x1
ap++;
if(s == 0)
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
81b: 83 c3 01 add $0x1,%ebx
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
81e: 50 push %eax
81f: 57 push %edi
820: e8 7d fd ff ff call 5a2 <write>
} else if(c == 's'){
s = (char*)*ap;
ap++;
if(s == 0)
s = "(null)";
while(*s != 0){
825: 0f b6 03 movzbl (%ebx),%eax
828: 83 c4 10 add $0x10,%esp
82b: 84 c0 test %al,%al
82d: 75 e1 jne 810 <printf+0x130>
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
82f: 31 d2 xor %edx,%edx
831: e9 ff fe ff ff jmp 735 <printf+0x55>
836: 8d 76 00 lea 0x0(%esi),%esi
839: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
840: 83 ec 04 sub $0x4,%esp
843: 88 5d e5 mov %bl,-0x1b(%ebp)
846: 8d 45 e5 lea -0x1b(%ebp),%eax
849: 6a 01 push $0x1
84b: e9 4c ff ff ff jmp 79c <printf+0xbc>
} else {
putc(fd, c);
}
} else if(state == '%'){
if(c == 'd'){
printint(fd, *ap, 10, 1);
850: 83 ec 0c sub $0xc,%esp
853: b9 0a 00 00 00 mov $0xa,%ecx
858: 6a 01 push $0x1
85a: e9 6b ff ff ff jmp 7ca <printf+0xea>
85f: 8b 5d d0 mov -0x30(%ebp),%ebx
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
862: 83 ec 04 sub $0x4,%esp
865: 8b 03 mov (%ebx),%eax
867: 6a 01 push $0x1
869: 88 45 e4 mov %al,-0x1c(%ebp)
86c: 8d 45 e4 lea -0x1c(%ebp),%eax
86f: 50 push %eax
870: 57 push %edi
871: e8 2c fd ff ff call 5a2 <write>
876: e9 5b ff ff ff jmp 7d6 <printf+0xf6>
87b: 66 90 xchg %ax,%ax
87d: 66 90 xchg %ax,%ax
87f: 90 nop
00000880 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
880: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
881: a1 70 0d 00 00 mov 0xd70,%eax
static Header base;
static Header *freep;
void
free(void *ap)
{
886: 89 e5 mov %esp,%ebp
888: 57 push %edi
889: 56 push %esi
88a: 53 push %ebx
88b: 8b 5d 08 mov 0x8(%ebp),%ebx
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
88e: 8b 10 mov (%eax),%edx
void
free(void *ap)
{
Header *bp, *p;
bp = (Header*)ap - 1;
890: 8d 4b f8 lea -0x8(%ebx),%ecx
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
893: 39 c8 cmp %ecx,%eax
895: 73 19 jae 8b0 <free+0x30>
897: 89 f6 mov %esi,%esi
899: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
8a0: 39 d1 cmp %edx,%ecx
8a2: 72 1c jb 8c0 <free+0x40>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
8a4: 39 d0 cmp %edx,%eax
8a6: 73 18 jae 8c0 <free+0x40>
static Header base;
static Header *freep;
void
free(void *ap)
{
8a8: 89 d0 mov %edx,%eax
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
8aa: 39 c8 cmp %ecx,%eax
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
8ac: 8b 10 mov (%eax),%edx
free(void *ap)
{
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
8ae: 72 f0 jb 8a0 <free+0x20>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
8b0: 39 d0 cmp %edx,%eax
8b2: 72 f4 jb 8a8 <free+0x28>
8b4: 39 d1 cmp %edx,%ecx
8b6: 73 f0 jae 8a8 <free+0x28>
8b8: 90 nop
8b9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
break;
if(bp + bp->s.size == p->s.ptr){
8c0: 8b 73 fc mov -0x4(%ebx),%esi
8c3: 8d 3c f1 lea (%ecx,%esi,8),%edi
8c6: 39 d7 cmp %edx,%edi
8c8: 74 19 je 8e3 <free+0x63>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
8ca: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
8cd: 8b 50 04 mov 0x4(%eax),%edx
8d0: 8d 34 d0 lea (%eax,%edx,8),%esi
8d3: 39 f1 cmp %esi,%ecx
8d5: 74 23 je 8fa <free+0x7a>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
8d7: 89 08 mov %ecx,(%eax)
freep = p;
8d9: a3 70 0d 00 00 mov %eax,0xd70
}
8de: 5b pop %ebx
8df: 5e pop %esi
8e0: 5f pop %edi
8e1: 5d pop %ebp
8e2: c3 ret
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
break;
if(bp + bp->s.size == p->s.ptr){
bp->s.size += p->s.ptr->s.size;
8e3: 03 72 04 add 0x4(%edx),%esi
8e6: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
8e9: 8b 10 mov (%eax),%edx
8eb: 8b 12 mov (%edx),%edx
8ed: 89 53 f8 mov %edx,-0x8(%ebx)
} else
bp->s.ptr = p->s.ptr;
if(p + p->s.size == bp){
8f0: 8b 50 04 mov 0x4(%eax),%edx
8f3: 8d 34 d0 lea (%eax,%edx,8),%esi
8f6: 39 f1 cmp %esi,%ecx
8f8: 75 dd jne 8d7 <free+0x57>
p->s.size += bp->s.size;
8fa: 03 53 fc add -0x4(%ebx),%edx
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
freep = p;
8fd: a3 70 0d 00 00 mov %eax,0xd70
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
if(p + p->s.size == bp){
p->s.size += bp->s.size;
902: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
905: 8b 53 f8 mov -0x8(%ebx),%edx
908: 89 10 mov %edx,(%eax)
} else
p->s.ptr = bp;
freep = p;
}
90a: 5b pop %ebx
90b: 5e pop %esi
90c: 5f pop %edi
90d: 5d pop %ebp
90e: c3 ret
90f: 90 nop
00000910 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
910: 55 push %ebp
911: 89 e5 mov %esp,%ebp
913: 57 push %edi
914: 56 push %esi
915: 53 push %ebx
916: 83 ec 0c sub $0xc,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
919: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
91c: 8b 15 70 0d 00 00 mov 0xd70,%edx
malloc(uint nbytes)
{
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
922: 8d 78 07 lea 0x7(%eax),%edi
925: c1 ef 03 shr $0x3,%edi
928: 83 c7 01 add $0x1,%edi
if((prevp = freep) == 0){
92b: 85 d2 test %edx,%edx
92d: 0f 84 a3 00 00 00 je 9d6 <malloc+0xc6>
933: 8b 02 mov (%edx),%eax
935: 8b 48 04 mov 0x4(%eax),%ecx
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
938: 39 cf cmp %ecx,%edi
93a: 76 74 jbe 9b0 <malloc+0xa0>
93c: 81 ff 00 10 00 00 cmp $0x1000,%edi
942: be 00 10 00 00 mov $0x1000,%esi
947: 8d 1c fd 00 00 00 00 lea 0x0(,%edi,8),%ebx
94e: 0f 43 f7 cmovae %edi,%esi
951: ba 00 80 00 00 mov $0x8000,%edx
956: 81 ff ff 0f 00 00 cmp $0xfff,%edi
95c: 0f 46 da cmovbe %edx,%ebx
95f: eb 10 jmp 971 <malloc+0x61>
961: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
if((prevp = freep) == 0){
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
968: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
96a: 8b 48 04 mov 0x4(%eax),%ecx
96d: 39 cf cmp %ecx,%edi
96f: 76 3f jbe 9b0 <malloc+0xa0>
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
971: 39 05 70 0d 00 00 cmp %eax,0xd70
977: 89 c2 mov %eax,%edx
979: 75 ed jne 968 <malloc+0x58>
char *p;
Header *hp;
if(nu < 4096)
nu = 4096;
p = sbrk(nu * sizeof(Header));
97b: 83 ec 0c sub $0xc,%esp
97e: 53 push %ebx
97f: e8 86 fc ff ff call 60a <sbrk>
if(p == (char*)-1)
984: 83 c4 10 add $0x10,%esp
987: 83 f8 ff cmp $0xffffffff,%eax
98a: 74 1c je 9a8 <malloc+0x98>
return 0;
hp = (Header*)p;
hp->s.size = nu;
98c: 89 70 04 mov %esi,0x4(%eax)
free((void*)(hp + 1));
98f: 83 ec 0c sub $0xc,%esp
992: 83 c0 08 add $0x8,%eax
995: 50 push %eax
996: e8 e5 fe ff ff call 880 <free>
return freep;
99b: 8b 15 70 0d 00 00 mov 0xd70,%edx
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
if((p = morecore(nunits)) == 0)
9a1: 83 c4 10 add $0x10,%esp
9a4: 85 d2 test %edx,%edx
9a6: 75 c0 jne 968 <malloc+0x58>
return 0;
9a8: 31 c0 xor %eax,%eax
9aa: eb 1c jmp 9c8 <malloc+0xb8>
9ac: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
if(p->s.size == nunits)
9b0: 39 cf cmp %ecx,%edi
9b2: 74 1c je 9d0 <malloc+0xc0>
prevp->s.ptr = p->s.ptr;
else {
p->s.size -= nunits;
9b4: 29 f9 sub %edi,%ecx
9b6: 89 48 04 mov %ecx,0x4(%eax)
p += p->s.size;
9b9: 8d 04 c8 lea (%eax,%ecx,8),%eax
p->s.size = nunits;
9bc: 89 78 04 mov %edi,0x4(%eax)
}
freep = prevp;
9bf: 89 15 70 0d 00 00 mov %edx,0xd70
return (void*)(p + 1);
9c5: 83 c0 08 add $0x8,%eax
}
if(p == freep)
if((p = morecore(nunits)) == 0)
return 0;
}
}
9c8: 8d 65 f4 lea -0xc(%ebp),%esp
9cb: 5b pop %ebx
9cc: 5e pop %esi
9cd: 5f pop %edi
9ce: 5d pop %ebp
9cf: c3 ret
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
if(p->s.size == nunits)
prevp->s.ptr = p->s.ptr;
9d0: 8b 08 mov (%eax),%ecx
9d2: 89 0a mov %ecx,(%edx)
9d4: eb e9 jmp 9bf <malloc+0xaf>
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
if((prevp = freep) == 0){
base.s.ptr = freep = prevp = &base;
9d6: c7 05 70 0d 00 00 74 movl $0xd74,0xd70
9dd: 0d 00 00
9e0: c7 05 74 0d 00 00 74 movl $0xd74,0xd74
9e7: 0d 00 00
base.s.size = 0;
9ea: b8 74 0d 00 00 mov $0xd74,%eax
9ef: c7 05 78 0d 00 00 00 movl $0x0,0xd78
9f6: 00 00 00
9f9: e9 3e ff ff ff jmp 93c <malloc+0x2c>
|
;--------------------------------------------------------
; File Created by SDCC : free open source ANSI-C Compiler
; Version 4.0.7 #12017 (Linux)
;--------------------------------------------------------
; Processed by Z88DK
;--------------------------------------------------------
EXTERN __divschar
EXTERN __divschar_callee
EXTERN __divsint
EXTERN __divsint_callee
EXTERN __divslong
EXTERN __divslong_callee
EXTERN __divslonglong
EXTERN __divslonglong_callee
EXTERN __divsuchar
EXTERN __divsuchar_callee
EXTERN __divuchar
EXTERN __divuchar_callee
EXTERN __divuint
EXTERN __divuint_callee
EXTERN __divulong
EXTERN __divulong_callee
EXTERN __divulonglong
EXTERN __divulonglong_callee
EXTERN __divuschar
EXTERN __divuschar_callee
EXTERN __modschar
EXTERN __modschar_callee
EXTERN __modsint
EXTERN __modsint_callee
EXTERN __modslong
EXTERN __modslong_callee
EXTERN __modslonglong
EXTERN __modslonglong_callee
EXTERN __modsuchar
EXTERN __modsuchar_callee
EXTERN __moduchar
EXTERN __moduchar_callee
EXTERN __moduint
EXTERN __moduint_callee
EXTERN __modulong
EXTERN __modulong_callee
EXTERN __modulonglong
EXTERN __modulonglong_callee
EXTERN __moduschar
EXTERN __moduschar_callee
EXTERN __mulint
EXTERN __mulint_callee
EXTERN __mullong
EXTERN __mullong_callee
EXTERN __mullonglong
EXTERN __mullonglong_callee
EXTERN __mulschar
EXTERN __mulschar_callee
EXTERN __mulsuchar
EXTERN __mulsuchar_callee
EXTERN __muluchar
EXTERN __muluchar_callee
EXTERN __muluschar
EXTERN __muluschar_callee
EXTERN __rlslonglong
EXTERN __rlslonglong_callee
EXTERN __rlulonglong
EXTERN __rlulonglong_callee
EXTERN __rrslonglong
EXTERN __rrslonglong_callee
EXTERN __rrulonglong
EXTERN __rrulonglong_callee
EXTERN ___sdcc_call_hl
EXTERN ___sdcc_call_iy
EXTERN ___sdcc_enter_ix
EXTERN banked_call
EXTERN _banked_ret
EXTERN ___fs2schar
EXTERN ___fs2schar_callee
EXTERN ___fs2sint
EXTERN ___fs2sint_callee
EXTERN ___fs2slong
EXTERN ___fs2slong_callee
EXTERN ___fs2slonglong
EXTERN ___fs2slonglong_callee
EXTERN ___fs2uchar
EXTERN ___fs2uchar_callee
EXTERN ___fs2uint
EXTERN ___fs2uint_callee
EXTERN ___fs2ulong
EXTERN ___fs2ulong_callee
EXTERN ___fs2ulonglong
EXTERN ___fs2ulonglong_callee
EXTERN ___fsadd
EXTERN ___fsadd_callee
EXTERN ___fsdiv
EXTERN ___fsdiv_callee
EXTERN ___fseq
EXTERN ___fseq_callee
EXTERN ___fsgt
EXTERN ___fsgt_callee
EXTERN ___fslt
EXTERN ___fslt_callee
EXTERN ___fsmul
EXTERN ___fsmul_callee
EXTERN ___fsneq
EXTERN ___fsneq_callee
EXTERN ___fssub
EXTERN ___fssub_callee
EXTERN ___schar2fs
EXTERN ___schar2fs_callee
EXTERN ___sint2fs
EXTERN ___sint2fs_callee
EXTERN ___slong2fs
EXTERN ___slong2fs_callee
EXTERN ___slonglong2fs
EXTERN ___slonglong2fs_callee
EXTERN ___uchar2fs
EXTERN ___uchar2fs_callee
EXTERN ___uint2fs
EXTERN ___uint2fs_callee
EXTERN ___ulong2fs
EXTERN ___ulong2fs_callee
EXTERN ___ulonglong2fs
EXTERN ___ulonglong2fs_callee
EXTERN ____sdcc_2_copy_src_mhl_dst_deix
EXTERN ____sdcc_2_copy_src_mhl_dst_bcix
EXTERN ____sdcc_4_copy_src_mhl_dst_deix
EXTERN ____sdcc_4_copy_src_mhl_dst_bcix
EXTERN ____sdcc_4_copy_src_mhl_dst_mbc
EXTERN ____sdcc_4_ldi_nosave_bc
EXTERN ____sdcc_4_ldi_save_bc
EXTERN ____sdcc_4_push_hlix
EXTERN ____sdcc_4_push_mhl
EXTERN ____sdcc_lib_setmem_hl
EXTERN ____sdcc_ll_add_de_bc_hl
EXTERN ____sdcc_ll_add_de_bc_hlix
EXTERN ____sdcc_ll_add_de_hlix_bc
EXTERN ____sdcc_ll_add_de_hlix_bcix
EXTERN ____sdcc_ll_add_deix_bc_hl
EXTERN ____sdcc_ll_add_deix_hlix
EXTERN ____sdcc_ll_add_hlix_bc_deix
EXTERN ____sdcc_ll_add_hlix_deix_bc
EXTERN ____sdcc_ll_add_hlix_deix_bcix
EXTERN ____sdcc_ll_asr_hlix_a
EXTERN ____sdcc_ll_asr_mbc_a
EXTERN ____sdcc_ll_copy_src_de_dst_hlix
EXTERN ____sdcc_ll_copy_src_de_dst_hlsp
EXTERN ____sdcc_ll_copy_src_deix_dst_hl
EXTERN ____sdcc_ll_copy_src_deix_dst_hlix
EXTERN ____sdcc_ll_copy_src_deixm_dst_hlsp
EXTERN ____sdcc_ll_copy_src_desp_dst_hlsp
EXTERN ____sdcc_ll_copy_src_hl_dst_de
EXTERN ____sdcc_ll_copy_src_hlsp_dst_de
EXTERN ____sdcc_ll_copy_src_hlsp_dst_deixm
EXTERN ____sdcc_ll_lsl_hlix_a
EXTERN ____sdcc_ll_lsl_mbc_a
EXTERN ____sdcc_ll_lsr_hlix_a
EXTERN ____sdcc_ll_lsr_mbc_a
EXTERN ____sdcc_ll_push_hlix
EXTERN ____sdcc_ll_push_mhl
EXTERN ____sdcc_ll_sub_de_bc_hl
EXTERN ____sdcc_ll_sub_de_bc_hlix
EXTERN ____sdcc_ll_sub_de_hlix_bc
EXTERN ____sdcc_ll_sub_de_hlix_bcix
EXTERN ____sdcc_ll_sub_deix_bc_hl
EXTERN ____sdcc_ll_sub_deix_hlix
EXTERN ____sdcc_ll_sub_hlix_bc_deix
EXTERN ____sdcc_ll_sub_hlix_deix_bc
EXTERN ____sdcc_ll_sub_hlix_deix_bcix
EXTERN ____sdcc_load_debc_deix
EXTERN ____sdcc_load_dehl_deix
EXTERN ____sdcc_load_debc_mhl
EXTERN ____sdcc_load_hlde_mhl
EXTERN ____sdcc_store_dehl_bcix
EXTERN ____sdcc_store_debc_hlix
EXTERN ____sdcc_store_debc_mhl
EXTERN ____sdcc_cpu_pop_ei
EXTERN ____sdcc_cpu_pop_ei_jp
EXTERN ____sdcc_cpu_push_di
EXTERN ____sdcc_outi
EXTERN ____sdcc_outi_128
EXTERN ____sdcc_outi_256
EXTERN ____sdcc_ldi
EXTERN ____sdcc_ldi_128
EXTERN ____sdcc_ldi_256
EXTERN ____sdcc_4_copy_srcd_hlix_dst_deix
EXTERN ____sdcc_4_and_src_mbc_mhl_dst_deix
EXTERN ____sdcc_4_or_src_mbc_mhl_dst_deix
EXTERN ____sdcc_4_xor_src_mbc_mhl_dst_deix
EXTERN ____sdcc_4_or_src_dehl_dst_bcix
EXTERN ____sdcc_4_xor_src_dehl_dst_bcix
EXTERN ____sdcc_4_and_src_dehl_dst_bcix
EXTERN ____sdcc_4_xor_src_mbc_mhl_dst_debc
EXTERN ____sdcc_4_or_src_mbc_mhl_dst_debc
EXTERN ____sdcc_4_and_src_mbc_mhl_dst_debc
EXTERN ____sdcc_4_cpl_src_mhl_dst_debc
EXTERN ____sdcc_4_xor_src_debc_mhl_dst_debc
EXTERN ____sdcc_4_or_src_debc_mhl_dst_debc
EXTERN ____sdcc_4_and_src_debc_mhl_dst_debc
EXTERN ____sdcc_4_and_src_debc_hlix_dst_debc
EXTERN ____sdcc_4_or_src_debc_hlix_dst_debc
EXTERN ____sdcc_4_xor_src_debc_hlix_dst_debc
;--------------------------------------------------------
; Public variables in this module
;--------------------------------------------------------
GLOBAL _m32_atanf
;--------------------------------------------------------
; Externals used
;--------------------------------------------------------
GLOBAL _m32_polyf
GLOBAL _m32_hypotf
GLOBAL _m32_ldexpf
GLOBAL _m32_frexpf
GLOBAL _m32_invsqrtf
GLOBAL _m32_sqrtf
GLOBAL _m32_invf
GLOBAL _m32_sqrf
GLOBAL _m32_div2f
GLOBAL _m32_mul2f
GLOBAL _m32_modff
GLOBAL _m32_fmodf
GLOBAL _m32_roundf
GLOBAL _m32_floorf
GLOBAL _m32_fabsf
GLOBAL _m32_ceilf
GLOBAL _m32_powf
GLOBAL _m32_log10f
GLOBAL _m32_log2f
GLOBAL _m32_logf
GLOBAL _m32_exp10f
GLOBAL _m32_exp2f
GLOBAL _m32_expf
GLOBAL _m32_atanhf
GLOBAL _m32_acoshf
GLOBAL _m32_asinhf
GLOBAL _m32_tanhf
GLOBAL _m32_coshf
GLOBAL _m32_sinhf
GLOBAL _m32_atan2f
GLOBAL _m32_acosf
GLOBAL _m32_asinf
GLOBAL _m32_tanf
GLOBAL _m32_cosf
GLOBAL _m32_sinf
GLOBAL _poly_callee
GLOBAL _poly
GLOBAL _exp10_fastcall
GLOBAL _exp10
GLOBAL _mul10u_fastcall
GLOBAL _mul10u
GLOBAL _mul2_fastcall
GLOBAL _mul2
GLOBAL _div2_fastcall
GLOBAL _div2
GLOBAL _invsqrt_fastcall
GLOBAL _invsqrt
GLOBAL _inv_fastcall
GLOBAL _inv
GLOBAL _sqr_fastcall
GLOBAL _sqr
GLOBAL _isunordered_callee
GLOBAL _isunordered
GLOBAL _islessgreater_callee
GLOBAL _islessgreater
GLOBAL _islessequal_callee
GLOBAL _islessequal
GLOBAL _isless_callee
GLOBAL _isless
GLOBAL _isgreaterequal_callee
GLOBAL _isgreaterequal
GLOBAL _isgreater_callee
GLOBAL _isgreater
GLOBAL _fma_callee
GLOBAL _fma
GLOBAL _fmin_callee
GLOBAL _fmin
GLOBAL _fmax_callee
GLOBAL _fmax
GLOBAL _fdim_callee
GLOBAL _fdim
GLOBAL _nexttoward_callee
GLOBAL _nexttoward
GLOBAL _nextafter_callee
GLOBAL _nextafter
GLOBAL _nan_fastcall
GLOBAL _nan
GLOBAL _copysign_callee
GLOBAL _copysign
GLOBAL _remquo_callee
GLOBAL _remquo
GLOBAL _remainder_callee
GLOBAL _remainder
GLOBAL _fmod_callee
GLOBAL _fmod
GLOBAL _modf_callee
GLOBAL _modf
GLOBAL _trunc_fastcall
GLOBAL _trunc
GLOBAL _lround_fastcall
GLOBAL _lround
GLOBAL _round_fastcall
GLOBAL _round
GLOBAL _lrint_fastcall
GLOBAL _lrint
GLOBAL _rint_fastcall
GLOBAL _rint
GLOBAL _nearbyint_fastcall
GLOBAL _nearbyint
GLOBAL _floor_fastcall
GLOBAL _floor
GLOBAL _ceil_fastcall
GLOBAL _ceil
GLOBAL _tgamma_fastcall
GLOBAL _tgamma
GLOBAL _lgamma_fastcall
GLOBAL _lgamma
GLOBAL _erfc_fastcall
GLOBAL _erfc
GLOBAL _erf_fastcall
GLOBAL _erf
GLOBAL _cbrt_fastcall
GLOBAL _cbrt
GLOBAL _sqrt_fastcall
GLOBAL _sqrt
GLOBAL _pow_callee
GLOBAL _pow
GLOBAL _hypot_callee
GLOBAL _hypot
GLOBAL _fabs_fastcall
GLOBAL _fabs
GLOBAL _logb_fastcall
GLOBAL _logb
GLOBAL _log2_fastcall
GLOBAL _log2
GLOBAL _log1p_fastcall
GLOBAL _log1p
GLOBAL _log10_fastcall
GLOBAL _log10
GLOBAL _log_fastcall
GLOBAL _log
GLOBAL _scalbln_callee
GLOBAL _scalbln
GLOBAL _scalbn_callee
GLOBAL _scalbn
GLOBAL _ldexp_callee
GLOBAL _ldexp
GLOBAL _ilogb_fastcall
GLOBAL _ilogb
GLOBAL _frexp_callee
GLOBAL _frexp
GLOBAL _expm1_fastcall
GLOBAL _expm1
GLOBAL _exp2_fastcall
GLOBAL _exp2
GLOBAL _exp_fastcall
GLOBAL _exp
GLOBAL _tanh_fastcall
GLOBAL _tanh
GLOBAL _sinh_fastcall
GLOBAL _sinh
GLOBAL _cosh_fastcall
GLOBAL _cosh
GLOBAL _atanh_fastcall
GLOBAL _atanh
GLOBAL _asinh_fastcall
GLOBAL _asinh
GLOBAL _acosh_fastcall
GLOBAL _acosh
GLOBAL _tan_fastcall
GLOBAL _tan
GLOBAL _sin_fastcall
GLOBAL _sin
GLOBAL _cos_fastcall
GLOBAL _cos
GLOBAL _atan2_callee
GLOBAL _atan2
GLOBAL _atan_fastcall
GLOBAL _atan
GLOBAL _asin_fastcall
GLOBAL _asin
GLOBAL _acos_fastcall
GLOBAL _acos
GLOBAL _m32_coeff_atan
;--------------------------------------------------------
; special function registers
;--------------------------------------------------------
;--------------------------------------------------------
; ram data
;--------------------------------------------------------
SECTION bss_compiler
;--------------------------------------------------------
; ram data
;--------------------------------------------------------
IF 0
; .area _INITIALIZED removed by z88dk
ENDIF
;--------------------------------------------------------
; absolute external ram data
;--------------------------------------------------------
SECTION IGNORE
;--------------------------------------------------------
; global & static initialisations
;--------------------------------------------------------
SECTION code_crt_init
;--------------------------------------------------------
; Home
;--------------------------------------------------------
SECTION IGNORE
;--------------------------------------------------------
; code
;--------------------------------------------------------
SECTION code_compiler
; ---------------------------------
; Function m32_atanf
; ---------------------------------
_m32_atanf:
push ix
ld ix,0
add ix,sp
ld c, l
ld b, h
ld hl, -9
add hl, sp
ld sp, hl
ld (ix-4),c
ld (ix-3),b
ld (ix-2),e
ld (ix-1),d
ld l,(ix-4)
ld h,(ix-3)
ld e,(ix-2)
ld d,(ix-1)
call _m32_fabsf
ld c,l
ld b,h
ex (sp),hl
ld (ix-7),e
ld (ix-6),d
ld a, d
and a,0x7f
or a, e
or a, b
or a, c
jr NZ,l_m32_atanf_00102
ld hl,0x0000
ld e,l
ld d,h
jp l_m32_atanf_00107
l_m32_atanf_00102:
pop bc
pop hl
push hl
push bc
push hl
push bc
ld hl,0x3f80
push hl
ld hl,0x0000
push hl
call ___fslt_callee
ld (ix-5),l
ld a,l
or a, a
jr Z,l_m32_atanf_00104
ld l,(ix-9)
ld h,(ix-8)
ld e,(ix-7)
ld d,(ix-6)
call _m32_invf
ex (sp),hl
ld (ix-7),e
ld (ix-6),d
l_m32_atanf_00104:
ld hl,0x0007
push hl
ld hl,_m32_coeff_atan
push hl
ld l,(ix-7)
ld h,(ix-6)
push hl
ld l,(ix-9)
ld h,(ix-8)
push hl
call _m32_polyf
ld a,(ix-5)
or a,a
ld c,l
ld b,h
jr Z,l_m32_atanf_00106
push de
push bc
ld hl,0x3fc9
push hl
ld hl,0x0fdb
push hl
call ___fssub_callee
ld c, l
ld b, h
l_m32_atanf_00106:
push bc
push de
ld hl,0x0000
push hl
push hl
ld l,(ix-2)
ld h,(ix-1)
push hl
ld l,(ix-4)
ld h,(ix-3)
push hl
call ___fslt_callee
pop de
pop bc
ld a,l
or a, a
jr Z,l_m32_atanf_00109
ld a, d
xor a,0x80
ld d, a
l_m32_atanf_00109:
ld l, c
ld h, b
l_m32_atanf_00107:
ld sp, ix
pop ix
ret
SECTION IGNORE
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1991 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: Printer/Fax/CCom
FILE: ccomSetup.asm
AUTHOR: Don Reeves, May 2, 1991
ROUTINES:
Name Description
---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
Don 5/02/91 Initial revision
DESCRIPTION:
Miscellaneous routines that are called to initialize and clean up
after print jobd
$Id: ccomremSetup.asm,v 1.1 97/04/18 11:52:50 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrintStartJob
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Do pre-job initialization
CALLED BY: GLOBAL
PASS: BP = segment of locked PState
RETURN: carry = set if some communication problem
DESTROYED: bx
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Jim 03/90 Initial version
Don 04/91 Incorporated CCom calls
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrintStartJob proc far
mov bx, bp ; PState => BX
uses ax, bx, cx, dx, si, di, es, ds
.enter
;
; initialize some info in the PState
;
ForceRef cff
mov ds, bx ; PState => DS:0
clr ax
mov ds:[PS_asciiSpacing], 12 ; set to 1/6th inch
mov ds:[PS_asciiStyle], ax ; set to plain text
mov ds:[PS_cursorPos].P_x, ax ; set to 0,0 text
mov ds:[PS_cursorPos].P_y, ax
;
; Set the paper input/output params from the device info
;
mov bx, ds:[PS_deviceInfo]
call MemLock
mov es, ax
CheckHack <offset PI_paperOutput eq offset PI_paperInput+1>
mov ax, {word} es:[PI_paperInput]
call MemUnlock
push bp
mov bp, ds
call PrintSetPaperPath
pop bp
;
; Store the JobParameters in the status file.
;
call OpenStatusFile ; returns with exclusive access
jc done
call StoreJobParams ; ax <- VM block handle
;
; Copy the spool file (yurg).
;
call CopySpool
call FilePopDir
jc done
;
; Put the thing in the queue.
;
call AddToQueue
;
; Let the remote spooler do its thing.
;
call VMReleaseExclusive
clr al
call VMClose
done:
.leave
ret
PrintStartJob endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
OpenStatusFile
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Open the Queue Status file in the remote spool directory and
return it for exclusive access.
CALLED BY: (INTERNAL) PrintStartJob
PASS: ds = PState
RETURN: carry set on error
ax = FileError/VMStatus
carry clear if ok
bx = handle of VM file
DESTROYED: ax, bx
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 9/28/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
serverDirKeyString char 'serverDir', 0
statusFileName char 'Queue Status', 0
OpenStatusFile proc near
remDir local PathName
category local MAX_INITFILE_CATEGORY_LENGTH dup(char)
uses cx, dx, si, di, es, ds
.enter
;
; Determine the category that holds the server directory.
;
mov al, ({JobParamData}ds:PS_jobParams.JP_printerData).JPD_server
clr ah
segmov ds, cs, cx
.assert @CurSeg eq segment printerCatString
mov si, offset printerCatString
mov dx, offset faxServerKeyString
segmov es, ss
lea di, ss:[category]
push bp
mov bp, (IFCC_INTACT shl offset IFRF_CHAR_CONVERT) or \
(size category shl offset IFRF_SIZE)
call InitFileReadStringSection
pop bp
;
; Fetch the server directory.
;
segmov ds, ss
mov si, di
mov cx, cs
mov dx, offset serverDirKeyString
lea di, ss:[remDir]
push bp
mov bp, (IFCC_INTACT shl offset IFRF_CHAR_CONVERT) or \
(size remDir shl offset IFRF_SIZE)
call InitFileReadString
pop bp
jc done
;
; Push to the server directory.
;
segmov ds, es
mov dx, di
call FilePushDir
clr bx
call FileSetCurrentPath
jc popDirDone
;
; Open the queue file, creating it if necessary.
;
segmov ds, cs
mov dx, offset statusFileName
mov ax, (VMO_CREATE shl 8) or \
mask VMAF_FORCE_READ_WRITE or \
mask VMAF_FORCE_SHARED_MULTIPLE
clr cx
call VMOpen
jc popDirDone
;
; Gain exclusive access to the queue file.
;
mov ax, VMO_WRITE
clr cx
call VMGrabExclusive
done:
.leave
ret
popDirDone:
call FilePopDir
jmp done
OpenStatusFile endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
StoreJobParams
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Copy the JobParameters into a block attached to the VM file
CALLED BY: (INTERNAL) PrintStartJob
PASS: ds = PState
bx = VM handle
RETURN: ax = VM block handle of parameters
DESTROYED:
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 9/28/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
StoreJobParams proc near
uses cx, dx, ds, si, di, es, bp
.enter
;
; Allocate a block to hold the JobParameters
;
mov cx, ds:[PS_jobParams].JP_size
clr ax ; uid == 0 => no next
call VMAlloc
push ax
;
; Copy the existing ones into the block
;
call VMLock
mov es, ax
clr di
mov si, offset PS_jobParams
mov cx, ds:[PS_jobParams].JP_size
rep movsb
; sign-extend coverSheet into server so params all ready for
; ccom
mov al, ({JobParamData}es:[JP_printerData]).JPD_coverSheet
mov ({JobParamData}es:[JP_printerData]).JPD_server, al
;
; Change the JP_fname to the one we're going to use (formed from the
; VM block handle)
;
mov di, offset JP_fname
clr dx
pop ax ; ax <- block handle
push ax
mov cx, mask UHTAF_NULL_TERMINATE
call UtilHex32ToAscii
;
; Dirty the block, unlock it, and we're done.
;
call VMDirty
call VMUnlock
pop ax
.leave
ret
StoreJobParams endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CopySpool
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Copy the spool file to the remote directory.
CALLED BY: (INTERNAL) PrintStartJob
PASS: ds = PState
bx = VM file handle
ax = VM block handle of params
current dir set to remote spool directory
RETURN: carry set if couldn't copy
DESTROYED:
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 9/28/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
CopySpool proc near
uses ax, cx, dx, si, di, es, bp
.enter
mov si, offset PS_jobParams.JP_fname
mov cx, SP_SPOOL
push ax
call VMLock
mov es, ax
mov di, offset JP_fname
clr dx
call FileCopy
call VMUnlock
pop ax
jc nogood
done:
.leave
ret
nogood:
call VMFree
call VMReleaseExclusive
clr ax
call VMClose
stc
jmp done
CopySpool endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
AddToQueue
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Add the allocated JobParameters block to the end of the
current queue within the Queue Status file for the server.
CALLED BY: (INTERNAL) PrintStartJob
PASS: bx = VM file
ax = VM block handle
RETURN: nothing
DESTROYED: ax
SIDE EFFECTS: map block for file may change
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 9/28/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
AddToQueue proc near
uses es, bp, cx, di
.enter
push ax
call VMGetMapBlock
tst ax
jnz addToEnd
;
; No map block => no queue, so make this the head of the queue.
;
pop ax
call VMSetMapBlock
done:
.leave
ret
addToEnd:
;
; Locate the last block in the queue.
;
push ax
call VMInfo
pop ax
tst di
jz hitEnd
mov_tr ax, di
jmp addToEnd
hitEnd:
;
; Set our block as the next block following the last block.
;
pop cx ; cx <- new uid
call VMModifyUserID
jmp done
AddToQueue endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrintEndJob
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Do post-job cleanup
CALLED BY: GLOBAL
PASS: BP - segment of locked PState
RETURN: nothing
DESTROYED: bx
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Jim 03/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrintEndJob proc far
.enter
clc
.leave
ret
PrintEndJob endp
|
setrepeat 4
frame 3, 02
frame 1, 01
frame 2, 01
frame 1, 02
dorepeat 1
frame 0, 25
frame 3, 10
endanim
|
#ifndef _CORE_NEW_INLINE_
#define _CORE_NEW_INLINE_
namespace gsystem { // gsystem
template<typename ClassT> GINLINE
gptr GNewT<ClassT>::operator new(gsize size) GNOEXCEPT
{
gptr ptr = GMalloc(size);
if (GNULL == ptr)
{
throw std::bad_alloc();
}
return ptr;
}
template<typename ClassT>
GINLINE gvoid GNewT<ClassT>::operator delete(gptr ptr) GNOEXCEPT
{
GFree(ptr);
}
template<typename ClassT>
GMemPool<sizeof(ClassT)> GNewInPoolT<ClassT>::pool;
template<typename ClassT>
GINLINE gptr GNewInPoolT<ClassT>::operator new(gsize)
{
gptr ptr = pool.Alloc();
if (!ptr)
{
throw std::bad_alloc();
}
return ptr;
}
template<typename ClassT>
GINLINE gvoid GNewInPoolT<ClassT>::operator delete(gptr free)
{
if (free == GNULL)
{
return;
}
pool.Free(free);
}
//////////////////////////////////////////////////////////////////////////
template<typename ClassT>
std::new_handler GNewWithHandlerT<ClassT>::currentHandler;
template<typename ClassT>
GINLINE std::new_handler GNewWithHandlerT<ClassT>::set_new_handler(std::new_handler p)
{
std::new_handler oldHandler = currentHandler;
currentHandler = p;
return oldHandler;
}
template<typename ClassT>
GINLINE gptr GNewWithHandlerT<ClassT>::operator new(gsize size)
{
GNewHander h(std::set_new_handler(currentHandler));
gptr ptr = GMalloc(size);
if (GNULL == ptr)
{
throw std::bad_alloc();
}
return ptr;
}
template<typename ClassT>
GINLINE gvoid GNewWithHandlerT<ClassT>::operator delete(gptr free)
{
GFree(free);
}
//////////////////////////////////////////////////////////////////////////
template<typename ClassT>
std::new_handler GNewInPoolWithHandlerT<ClassT>::currentHandler;
template<typename ClassT>
GMemPool<sizeof(ClassT)> GNewInPoolWithHandlerT<ClassT>::pool;
template<typename ClassT>
GINLINE gptr GNewInPoolWithHandlerT<ClassT>::operator new(gsize size)
{
GNewHander h(std::set_new_handler(currentHandler));
gptr ptr = pool.Alloc();
if (GNULL == ptr)
{
throw std::bad_alloc();
}
return ptr;
}
template<typename ClassT>
GINLINE gvoid GNewInPoolWithHandlerT<ClassT>::operator delete(gptr free)
{
if (free == GNULL)
{
return;
}
GLockGuard<LockT> autolock(lock);
pool.Free(free);
}
//////////////////////////////////////////////////////////////////////////
template<typename ClassT, typename LockT>
LockT GSafeNewT<ClassT, LockT>::lock;
template<typename ClassT, typename LockT>
GINLINE gptr GSafeNewT<ClassT, LockT>::operator new(gsize size)
{
GLockGuard<LockT> autolock(lock);
gptr ptr = GMalloc(size);
if (nullptr == ptr)
{
throw std::bad_alloc();
}
return ptr;
}
template<typename ClassT, typename LockT>
GINLINE gvoid GSafeNewT<ClassT, LockT>::operator delete(gptr free)
{
GLockGuard<LockT> autolock(lock);
GFree(free);
}
//////////////////////////////////////////////////////////////////////////
template<typename ClassT, typename LockT>
std::new_handler GSafeNewWithHandlerT<ClassT, LockT>::currentHandler;
template<typename ClassT, typename LockT>
LockT GSafeNewWithHandlerT<ClassT, LockT>::lock;
template<typename ClassT, typename LockT>
GINLINE std::new_handler GSafeNewWithHandlerT<ClassT, LockT>::set_new_handler(std::new_handler p)
{
std::new_handler oldHandler = currentHandler;
currentHandler = p;
return oldHandler;
}
template<typename ClassT, typename LockT>
GINLINE gptr GSafeNewWithHandlerT<ClassT, LockT>::operator new(gsize size)
{
GNewHander h(std::set_new_handler(currentHandler));
GLockGuard<LockT> autolock(lock);
gptr ptr = GMalloc(size);
if (nullptr == ptr)
{
throw std::bad_alloc();
}
return ptr;
}
template<typename ClassT, typename LockT>
GINLINE gvoid GSafeNewWithHandlerT<ClassT, LockT>::operator delete(gptr free)
{
GLockGuard<LockT> autolock(lock);
GFree(free);
}
//////////////////////////////////////////////////////////////////////////
template<typename ClassT, typename LockT>
LockT GSafeNewInPoolT<ClassT, LockT>::lock;
template<typename ClassT, typename LockT>
GMemPool<sizeof(ClassT)> GSafeNewInPoolT<ClassT, LockT>::pool;
template<typename ClassT, typename LockT>
GINLINE gptr GSafeNewInPoolT<ClassT, LockT>::operator new(gsize)
{
GLockGuard<LockT> autolock(lock);
gptr ptr = pool.Alloc();
if (!ptr)
{
throw std::bad_alloc();
}
return ptr;
}
template<typename ClassT, typename LockT>
GINLINE gvoid GSafeNewInPoolT<ClassT, LockT>::operator delete(gptr free)
{
if (free == GNULL)
{
return;
}
GLockGuard<LockT> autolock(lock);
pool.Free(free);
}
//////////////////////////////////////////////////////////////////////////
template<typename ClassT, typename LockT>
std::new_handler GSafeNewInPoolWithHandlerT<ClassT, LockT>::currentHandler;
template<typename ClassT, typename LockT>
LockT GSafeNewInPoolWithHandlerT<ClassT, LockT>::lock;
template<typename ClassT, typename LockT>
GMemPool<sizeof(ClassT)> GSafeNewInPoolWithHandlerT<ClassT, LockT>::pool;
template<typename ClassT, typename LockT>
GINLINE std::new_handler GSafeNewInPoolWithHandlerT<ClassT, LockT>::set_new_handler(std::new_handler p)
{
std::new_handler oldHandler = currentHandler;
currentHandler = p;
return oldHandler;
}
template<typename ClassT, typename LockT>
GINLINE gptr GSafeNewInPoolWithHandlerT<ClassT, LockT>::operator new(gsize)
{
GNewHander h(std::set_new_handler(currentHandler));
GLockGuard<LockT> autolock(lock);
gptr ptr = pool.Alloc();
if (!ptr)
{
throw std::bad_alloc();
}
return ptr;
}
template<typename ClassT, typename LockT>
GINLINE gvoid GSafeNewInPoolWithHandlerT<ClassT, LockT>::operator delete(gptr free)
{
if (free == GNULL)
{
return;
}
GLockGuard<LockT> autolock(lock);
pool.Free(free);
}
} // namespace gsystem
#endif // _CORE_NEW_INLINE_ |
; A213585: Principal diagonal of the convolution array A213584.
; 1,7,22,54,116,232,443,821,1490,2664,4710,8256,14373,24883,42878,73594,125880,214664,365087,619425,1048666,1771852,2988362,5031744,8459401,14201887,23811238,39873726,66695420,111440104,186016835,310209101,516859298,860453808,1431331758,2379189504,3951943725,6559959499,10882151822,18041186050,29892661056,49502244872,81932626727,135540990009,224117455786,370408403092,611919655058,1010471811456,1667929015825,2752082129719,4539229997110,7484212280646,12335561282948,20324792722408,33477492169163,55124442213989,90741229869170,149327124891384,245669103054582,404058429048000,664390481498421,1092174061044067,1794952642435742,2949239953870474,4844693946589896,7956548501134472,13064358398681903,21446637451447761,35199842352718330,57761056858385884,94764322767912410,155443380237326016,254929127173074073,418011932189263183,685301908309035718,1123314114223860174,1840977145205155340,3016652655826835944,4942352320102070867,8096088891396806525,13260247646036856386,21715226887439541312,35556171318020254782,58210985340009531264,95287440577123377981,155958296970776236027,255225892520636532398,417624215517793013266,683270289037546708560,1117754711580837129224,1828305388642998407735,2990200695273947513961,4889927066991672468298,7995689340390458505508,13072598968581696043298,21370832448296558141184,34932958117402222845985,57095861405547153240679,93310417063321717001302,152479946849089583409750
mov $2,$0
add $2,1
mov $3,$0
lpb $2
mov $0,$3
sub $2,1
sub $0,$2
add $0,1
seq $0,61705 ; Number of matchings in the wheel graph with n spokes.
sub $0,4
add $1,$0
lpe
mov $0,$1
|
/* Copyright (c) 2020-2021 Arm Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 "utest/utest.h"
#include "unity/unity.h"
#include "greentea-client/test_env.h"
#include "mbed.h"
/*
Requirements specified in docs/design-documents/hal/0005-pin-names-Arduino-Uno-standard.md
*/
#if !(defined (TARGET_FF_ARDUINO_UNO))
#error [NOT_SUPPORTED] Test needs Arduino Uno form factor
#else
using namespace utest::v1;
template <PinName TestedPin>
void GPIO_test()
{
utest_printf("GPIO Pin 0x%x\n", TestedPin);
TEST_SKIP_UNLESS_MESSAGE(TestedPin != CONSOLE_TX, "ARDUINO_UNO pin shared with CONSOLE_TX");
TEST_SKIP_UNLESS_MESSAGE(TestedPin != CONSOLE_RX, "ARDUINO_UNO pin shared with CONSOLE_RX");
const PinMap *maps = gpio_pinmap(); // hal/source/mbed_gpio.c
while (maps->pin != (PinName)NC) { // check each pin from PinMap table till NC pin
if (maps->pin == TestedPin) {
{
DigitalOut TEST1(maps->pin);
TEST1 = !TEST1;
}
{
DigitalIn TEST1(maps->pin);
// Basic API call
TEST1.read();
}
{
DigitalInOut TEST1(maps->pin);
// Basic API call
TEST1.input();
TEST1.output();
}
TEST_ASSERT(true);
return;
}
maps++;
}
// Pin is not part of gpio PinMap
TEST_ASSERT(false);
}
template <PinName TestedPin>
void AnalogIn_test()
{
utest_printf("ADC Pin 0x%x\n", TestedPin);
const PinMap *maps = analogin_pinmap();
while (maps->pin != (PinName)NC) { // check each pin from PinMap table till NC pin
if (maps->pin == TestedPin) {
AnalogIn TEST(TestedPin);
// Basic API call
TEST.read_u16();
TEST_ASSERT(true);
return;
}
maps++;
}
// Pin is not part of analogin PinMap
TEST_ASSERT(false);
}
template <PinName TestedPin>
void PWM_test()
{
utest_printf("PWM Pin 0x%x\n", TestedPin);
const PinMap *maps = pwmout_pinmap();
while (maps->pin != (PinName)NC) { // check each pin from PinMap table till NC pin
if (maps->pin == TestedPin) {
PwmOut pwm(TestedPin);
// Basic API call
pwm.period(1.0f);
pwm.write(0.5f);
TEST_ASSERT(true);
return;
}
maps++;
}
// From docs/design-documents/hal/0005-pin-names-Arduino-Uno-standard.md
// Although this is recomended as per the Arduino Uno standard,
// it's not a mandatory as requirement to be compliant with the Arduino Uno standard for Mbed boards.
TEST_SKIP_UNLESS_MESSAGE(false, "ARDUINO_UNO: this pin doesn’t support PWM");
}
template <PinName TX_pin, PinName RX_pin>
void UART_test()
{
utest_printf("UART TX Pin 0x%x RX Pin 0x%x\n", TX_pin, RX_pin);
TEST_SKIP_UNLESS_MESSAGE(TX_pin != CONSOLE_TX, "ARDUINO_UNO_UART pin shared with CONSOLE_TX");
TEST_SKIP_UNLESS_MESSAGE(RX_pin != CONSOLE_RX, "ARDUINO_UNO_UART pin shared with CONSOLE_RX");
{
const PinMap *maps = serial_tx_pinmap();
while (maps->pin != (PinName)NC) { // check each pin from PinMap table till NC pin
if (maps->pin == TX_pin) {
break;
}
maps++;
}
// Pin is not part of serial_tx PinMap
TEST_ASSERT_NOT_EQUAL(NC, maps->pin);
}
{
const PinMap *maps = serial_rx_pinmap();
while (maps->pin != (PinName)NC) { // check each pin from PinMap table till NC pin
if (maps->pin == RX_pin) {
break;
}
maps++;
}
// Pin is not part of serial_rx PinMap
TEST_ASSERT_NOT_EQUAL(NC, maps->pin);
}
BufferedSerial TEST(TX_pin, RX_pin);
// Basic API call
TEST.set_baud(115200);
}
template <PinName SDA_pin, PinName SCL_pin>
void I2C_test()
{
utest_printf("I2C SDA Pin 0x%x SCL Pin 0x%x\n", SDA_pin, SCL_pin);
{
const PinMap *maps = i2c_master_sda_pinmap();
while (maps->pin != (PinName)NC) { // check each pin from PinMap table till NC pin
if (maps->pin == SDA_pin) {
break;
}
maps++;
}
// Pin is not part of i2c_master_sda PinMap
TEST_ASSERT_NOT_EQUAL(NC, maps->pin);
}
{
const PinMap *maps = i2c_master_scl_pinmap();
while (maps->pin != (PinName)NC) { // check each pin from PinMap table till NC pin
if (maps->pin == SCL_pin) {
break;
}
maps++;
}
// Pin is not part of i2c_master_scl PinMap
TEST_ASSERT_NOT_EQUAL(NC, maps->pin);
}
I2C i2c(SDA_pin, SCL_pin);
}
template <PinName MOSI_pin, PinName MISO_pin, PinName CLK_pin, PinName CS_pin>
void SPI_test()
{
utest_printf("SPI MOSI Pin 0x%x MISO Pin 0x%x CLOCK Pin 0x%x CS Pin0x%x\n", MOSI_pin, MISO_pin, CLK_pin, CS_pin);
{
const PinMap *maps = spi_master_mosi_pinmap();
while (maps->pin != (PinName)NC) { // check each pin from PinMap table till NC pin
if (maps->pin == MOSI_pin) {
break;
}
maps++;
}
// Pin is not part of spi_master_mosi PinMap
TEST_ASSERT_NOT_EQUAL(NC, maps->pin);
}
{
const PinMap *maps = spi_master_miso_pinmap();
while (maps->pin != (PinName)NC) { // check each pin from PinMap table till NC pin
if (maps->pin == MISO_pin) {
break;
}
maps++;
}
// Pin is not part of spi_master_miso PinMap
TEST_ASSERT_NOT_EQUAL(NC, maps->pin);
}
{
const PinMap *maps = spi_master_clk_pinmap();
while (maps->pin != (PinName)NC) { // check each pin from PinMap table till NC pin
if (maps->pin == CLK_pin) {
break;
}
maps++;
}
// Pin is not part of spi_master_clk PinMap
TEST_ASSERT_NOT_EQUAL(NC, maps->pin);
}
{
const PinMap *maps = gpio_pinmap(); // CS pin could be a simple GPIO
while (maps->pin != (PinName)NC) { // check each pin from PinMap table till NC pin
if (maps->pin == CS_pin) {
break;
}
maps++;
}
// Pin is not part of gpio PinMap
TEST_ASSERT_NOT_EQUAL(NC, maps->pin);
}
SPI device(MOSI_pin, MISO_pin, CLK_pin);
DigitalOut cs(CS_pin);
// Basic API call
device.frequency(10000000);
}
Case cases[] = {
Case("GPIO A0", GPIO_test<ARDUINO_UNO_A0>),
Case("GPIO A1", GPIO_test<ARDUINO_UNO_A1>),
Case("GPIO A2", GPIO_test<ARDUINO_UNO_A2>),
Case("GPIO A3", GPIO_test<ARDUINO_UNO_A3>),
Case("GPIO A4", GPIO_test<ARDUINO_UNO_A4>),
Case("GPIO A5", GPIO_test<ARDUINO_UNO_A5>),
Case("GPIO D0", GPIO_test<ARDUINO_UNO_D0>),
Case("GPIO D1", GPIO_test<ARDUINO_UNO_D1>),
Case("GPIO D2", GPIO_test<ARDUINO_UNO_D2>),
Case("GPIO D3", GPIO_test<ARDUINO_UNO_D3>),
Case("GPIO D4", GPIO_test<ARDUINO_UNO_D4>),
Case("GPIO D5", GPIO_test<ARDUINO_UNO_D5>),
Case("GPIO D6", GPIO_test<ARDUINO_UNO_D6>),
Case("GPIO D7", GPIO_test<ARDUINO_UNO_D7>),
Case("GPIO D8", GPIO_test<ARDUINO_UNO_D8>),
Case("GPIO D9", GPIO_test<ARDUINO_UNO_D9>),
Case("GPIO D10", GPIO_test<ARDUINO_UNO_D10>),
Case("GPIO D11", GPIO_test<ARDUINO_UNO_D11>),
Case("GPIO D12", GPIO_test<ARDUINO_UNO_D12>),
Case("GPIO D13", GPIO_test<ARDUINO_UNO_D13>),
Case("GPIO D14", GPIO_test<ARDUINO_UNO_D14>),
Case("GPIO D15", GPIO_test<ARDUINO_UNO_D15>),
Case("ADC A0", AnalogIn_test<ARDUINO_UNO_A0>),
Case("ADC A1", AnalogIn_test<ARDUINO_UNO_A1>),
Case("ADC A2", AnalogIn_test<ARDUINO_UNO_A2>),
Case("ADC A3", AnalogIn_test<ARDUINO_UNO_A3>),
Case("ADC A4", AnalogIn_test<ARDUINO_UNO_A4>),
Case("ADC A5", AnalogIn_test<ARDUINO_UNO_A5>),
Case("PWM D3", PWM_test<ARDUINO_UNO_D3>),
Case("PWM D5", PWM_test<ARDUINO_UNO_D5>),
Case("PWM D6", PWM_test<ARDUINO_UNO_D6>),
Case("PWM D9", PWM_test<ARDUINO_UNO_D9>),
Case("PWM D10", PWM_test<ARDUINO_UNO_D10>),
Case("PWM D11", PWM_test<ARDUINO_UNO_D11>),
Case("UART", UART_test<ARDUINO_UNO_UART_TX, ARDUINO_UNO_UART_RX>),
Case("I2C", I2C_test<ARDUINO_UNO_I2C_SDA, ARDUINO_UNO_I2C_SCL>),
Case("SPI", SPI_test<ARDUINO_UNO_SPI_MOSI, ARDUINO_UNO_SPI_MISO, ARDUINO_UNO_SPI_SCK, ARDUINO_UNO_SPI_CS>),
};
utest::v1::status_t greentea_test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(25, "default_auto");
return greentea_test_setup_handler(number_of_cases);
}
Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler);
int main()
{
Harness::run(specification);
}
#endif
|
; A040319: Continued fraction for sqrt(338).
; Submitted by Jamie Morken(s3)
; 18,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2,36,2,1,1,2
mul $0,2
pow $0,2
mov $2,54
mov $3,$2
mov $1,$3
mov $4,$2
lpb $0
mul $1,2
lpb $$0
div $1,224
add $1,2
add $1,$0
div $0,7
lpe
mod $0,5
lpe
div $1,3
mov $0,$1
|
; A314067: Coordination sequence Gal.3.53.1 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
; 1,5,11,15,22,26,33,37,43,48,53,59,63,70,74,81,85,91,96,101,107,111,118,122,129,133,139,144,149,155,159,166,170,177,181,187,192,197,203,207,214,218,225,229,235,240,245,251,255,262
mov $2,$0
mul $0,2
trn $0,2
add $0,1
mul $0,2
lpb $0,1
add $3,$0
trn $0,4
mov $1,0
add $1,$3
trn $4,2
add $4,$0
trn $0,5
sub $1,$4
sub $3,3
lpe
sub $1,1
lpb $2,1
add $1,4
sub $2,1
lpe
|
/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* reader.cpp
*
* Created on: Feb 13, 2017
* Author: pnorbert
*/
#include <iostream>
#include <vector>
#include <adios2.h>
#ifdef ADIOS2_HAVE_MPI
#include <mpi.h>
#endif
template <class T>
T **Make2DArray(int nRows, int nCols)
{
T **ptr = new T *[nRows];
ptr[0] = new T[nRows * nCols];
for (int i = 1; i < nRows; i++)
{
ptr[i] = ptr[i - 1] + nCols;
}
return ptr;
}
template <class T>
void Delete2DArray(T **ptr)
{
delete[] ptr[0];
delete[] ptr;
}
template <class T>
void Print1DArray(T *ptr, int nElems, std::string name)
{
std::cout << name << " = { ";
for (int i = 0; i < nElems; i++)
{
std::cout << ptr[i] << " ";
}
std::cout << "}\n";
}
template <class T>
void Print2DArray(T **ptr, int nRows, int nCols, std::string name)
{
std::cout << name << " = { \n";
for (int step = 0; step < nRows; step++)
{
std::cout << " { ";
for (int col = 0; col < nCols; col++)
{
std::cout << ptr[step][col] << " ";
}
std::cout << "}\n";
}
std::cout << "}\n";
}
int main(int argc, char *argv[])
{
int rank = 0, nproc = 1;
#ifdef ADIOS2_HAVE_MPI
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &nproc);
#endif
const bool adiosDebug = true;
#ifdef ADIOS2_HAVE_MPI
adios2::ADIOS adios(MPI_COMM_WORLD, adios2::DebugON);
#else
adios2::ADIOS adios(adios2::DebugON);
#endif
// Info variables from the file
int Nwriters;
int Nsteps;
// Data variables from the file
// 1. Global value, constant across processes, constant over time
unsigned int Nx;
// 2. Local value, varying across processes, constant over time
std::vector<int> ProcessID;
// 3. Global array, global dimensions, local dimensions and offsets are
// constant over time
// std::vector<double> GlobalArrayFixedDims;
// 4. Local array, local dimensions are
// constant over time (but different across processors here)
std::vector<float> LocalArrayFixedDims;
// 5. Global value, constant across processes, VARYING value over time
std::vector<unsigned int> Nys;
// 6. Local value, varying across processes, VARYING over time
// Read as a 2D array, time as first dimension
// 7. Global array, dimensions and offsets are VARYING over time
std::vector<double> GlobalArray;
// 8. Local array, dimensions and offsets are VARYING over time
std::vector<float> IrregularArray;
try
{
// Define method for engine creation
// 1. Get method def from config file or define new one
adios2::IO bpReaderSettings = adios.DeclareIO("input");
if (!bpReaderSettings.InConfigFile())
{
// if not defined by user, we can change the default settings
bpReaderSettings.SetEngine(
"ADIOS1"); // BPFile is the default engine
// see only one step at a time
bpReaderSettings.SetParameters({{"OpenAsFile", "yes"}});
}
// Create engine smart pointer due to polymorphism,
// Default behavior
// auto bpReader = adios.Open( "myNumbers.bp", "r" );
// this would just open with a default transport, which is "BP"
auto bpReader =
bpReaderSettings.Open("myNumbers.bp", adios2::Mode::Read);
if (!bpReader)
throw std::ios_base::failure(
"ERROR: failed to open ADIOS bpReader\n");
/* Note: there is no global number of steps. Each variable has its
* own
* number of steps */
adios2::Variable<int> *vNproc = bpReader->InquireVariable<int>("Nproc");
Nwriters = vNproc->m_Data[0];
if (rank == 0)
std::cout << "# of writers = " << Nwriters << std::endl;
/* NX */
/* There is a single value written once.
*/
// read a Global scalar which has a single value in a step
adios2::Variable<unsigned int> *vNX =
bpReader->InquireVariable<unsigned int>("NX");
Nx = vNX->m_Data[0];
// bpReader->Read<unsigned int>("NX", &Nx);
if (rank == 0)
std::cout << "NX = " << Nx << std::endl;
/* NY */
/* We can read all into a 1D array with a step selection.
Steps are not automatically presented as an array dimension
and read does not read it as array by default.
*/
adios2::Variable<unsigned int> *vNY =
bpReader->InquireVariable<unsigned int>("NY");
Nys.resize(vNY->m_AvailableSteps); // number of steps available
// make a StepSelection to select multiple steps. Args: From, #of
// consecutive steps
// ? How do we make a selection for an arbitrary list of steps ?
vNY->SetStepSelection(0, vNY->m_AvailableSteps);
bpReader->Read<unsigned int>(*vNY, Nys.data());
if (rank == 0)
Print1DArray(Nys.data(), Nys.size(), "NY");
/* ProcessID */
adios2::Variable<int> *vProcessID =
bpReader->InquireVariable<int>("ProcessID");
if (vProcessID->m_Shape[0] != Nwriters)
{
std::cout << "ERROR: Unexpected array size of ProcessID = "
<< vProcessID->m_Shape[0] << " != # of writers"
<< std::endl;
}
ProcessID.resize(vProcessID->m_Shape[0]);
bpReader->Read<int>(*vProcessID, ProcessID.data());
if (rank == 0)
Print1DArray(ProcessID.data(), ProcessID.size(), "ProcessID");
/* Nparts */
// Nparts local scalar is presented as a 1D array of Nwriters
// elements.
// We can read all steps into a 2D array of nproc * Nwriters
adios2::Variable<unsigned int> *vNparts =
bpReader->InquireVariable<unsigned int>("Nparts");
unsigned int **Nparts =
Make2DArray<unsigned int>(vNparts->m_AvailableSteps, Nwriters);
vNparts->SetStepSelection(0, vNparts->m_AvailableSteps);
bpReader->Read<unsigned int>(*vNparts, Nparts[0]);
if (rank == 0)
Print2DArray(Nparts, vNparts->m_AvailableSteps, Nwriters, "Nparts");
Delete2DArray(Nparts);
#ifdef ADIOS2_HAVE_MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
/*
* GlobalArrayFixedDims
*/
// inquiry about a variable, whose name we know
adios2::Variable<double> *vGlobalArrayFixedDims =
bpReader->InquireVariable<double>("GlobalArrayFixedDims");
if (vGlobalArrayFixedDims == nullptr)
throw std::ios_base::failure(
"ERROR: failed to find variable "
"'GlobalArrayFixedDims' in input file\n");
// ? how do we know about the type? std::string varNice->m_Type
std::size_t gdim =
vGlobalArrayFixedDims->m_Shape[0]; // ?member var or member func?
std::size_t count = gdim / nproc;
std::size_t start = rank * count;
if (rank == nproc - 1)
{
count = gdim - (count * (nproc - 1));
}
if (rank == 0)
std::cout << "GlobalArrayFixedDims parallel read" << std::endl;
double **GlobalArrayFixedDims =
Make2DArray<double>(vGlobalArrayFixedDims->m_AvailableSteps, count);
// Make a 1D selection to describe the local dimensions of the variable
// we READ and its offsets in the global spaces
vGlobalArrayFixedDims->SetSelection({start}, {count});
vGlobalArrayFixedDims->SetStepSelection(
0, vGlobalArrayFixedDims->m_AvailableSteps);
bpReader->Read<double>(*vGlobalArrayFixedDims, GlobalArrayFixedDims[0]);
#ifdef ADIOS2_HAVE_MPI
MPI_Barrier(MPI_COMM_WORLD);
MPI_Status status;
int token = 0;
if (rank > 0)
MPI_Recv(&token, 1, MPI_INT, rank - 1, 0, MPI_COMM_WORLD, &status);
#endif
std::cout << "Rank " << rank << " read start = " << start
<< " count = " << count << std::endl;
Print2DArray(GlobalArrayFixedDims,
vGlobalArrayFixedDims->m_AvailableSteps, count,
"GlobalArrayFixedDims");
#ifdef ADIOS2_HAVE_MPI
if (rank < nproc - 1)
MPI_Send(&token, 1, MPI_INT, rank + 1, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
#endif
Delete2DArray(GlobalArrayFixedDims);
/*
* LocalArrayFixedDims
*/
// inquiry about a variable, whose name we know
adios2::Variable<float> *vLocalArrayFixedDims =
bpReader->InquireVariable<float>("LocalArrayFixedDims");
if (vLocalArrayFixedDims->m_Shape[0] != adios2::IrregularDim)
{
throw std::ios_base::failure(
"Unexpected condition: LocalArrayFixedDims array's fast "
"dimension is supposed to be adios2::IrregularDim indicating "
"an "
"Irregular array\n");
}
std::cout << "LocalArrayFixedDims is irregular. Cannot read this "
"variable yet...\n";
#ifdef ADIOS2_HAVE_MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
/*
* LocalArrayFixedDimsJoined
*/
// inquiry about a variable, whose name we know
adios2::Variable<float> *vLocalArrayFixedDimsJoined =
bpReader->InquireVariable<float>("LocalArrayFixedDimsJoined");
float **LocalArrayFixedDimsJoined =
Make2DArray<float>(vLocalArrayFixedDimsJoined->m_AvailableSteps,
vLocalArrayFixedDimsJoined->m_Shape[0]);
// Make a 1D selection to describe the local dimensions of the variable
// we READ and its offsets in the global spaces
vLocalArrayFixedDimsJoined->SetSelection(
{0}, {vLocalArrayFixedDimsJoined->m_Shape[0]});
vLocalArrayFixedDimsJoined->SetStepSelection(
0, vLocalArrayFixedDimsJoined->m_AvailableSteps);
bpReader->Read<float>(*vLocalArrayFixedDimsJoined,
LocalArrayFixedDimsJoined[0]);
if (rank == 0)
Print2DArray(LocalArrayFixedDimsJoined,
vLocalArrayFixedDimsJoined->m_AvailableSteps,
vLocalArrayFixedDimsJoined->m_Shape[0],
"LocalArrayFixedDimsJoined");
Delete2DArray(LocalArrayFixedDimsJoined);
#ifdef ADIOS2_HAVE_MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
/*
* GlobalArray which changes size over time
*/
// inquiry about a variable, whose name we know
adios2::Variable<double> *vGlobalArray =
bpReader->InquireVariable<double>("GlobalArray");
std::cout << "GlobalArray [" << vGlobalArray->m_Shape[0] << "]";
std::cout << " = Cannot read this variable yet...\n";
if (vGlobalArray->m_Shape[0] != adios2::IrregularDim)
{
throw std::ios_base::failure(
"Unexpected condition: GlobalArray array's "
"dimension is supposed to be adios2::IrregularDim indicating "
"an "
"Irregular array\n");
}
#ifdef ADIOS2_HAVE_MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
// Close file/stream
bpReader->Close();
}
catch (std::invalid_argument &e)
{
if (rank == 0)
{
std::cout << "Invalid argument exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
}
catch (std::ios_base::failure &e)
{
if (rank == 0)
{
std::cout << "System exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
}
catch (std::exception &e)
{
if (rank == 0)
{
std::cout << "Exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
}
#ifdef ADIOS2_HAVE_MPI
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
#endif
return 0;
}
|
Animation_Circle_Q3:
push bp
mov bp, sp
sub sp, 6
push es
push di
push si
push ax
push cx
push dx
mov si, word [bp + circ_r] ; x = -r
neg si
mov [bp - x], si
mov [bp - y], word 0d ; y = 0
neg si ; err = 2 - 2*r
add si, word [bp + circ_r]
mov [bp - err], word 2d
sub [bp - err], si
mov si, 0A000h ; Segment of display memory
mov es, si
Animation_Circle_Q3_Repeat:
xor cx, cx ; Delay
mov dx, 0750h
mov ah, 86h
int 15h
mov si, word [bp + circ_ym] ; 2nd quadrant
sub si, word [bp - x]
mov di, si
shl di, 8
shl si, 6
add di, si
mov si, word [bp + circ_xm]
sub si, word [bp - y]
add di, si
mov al, 00h ; Colour: black
mov byte [es:di], al
mov si, word [bp + circ_ym] ; 3rd quadrant
sub si, word [bp - y]
mov di, si
shl di, 8
shl si, 6
add di, si
mov si, word [bp + circ_xm]
add si, word [bp - x]
add di, si
mov al, 0Ch ; Colour: light red
mov byte [es:di], al
;____________________
mov si, word [bp - err] ; r = err
mov [bp + circ_r], si
mov si, word [bp + circ_r] ; if (r <= y) err += ++y*2+1;
cmp si, word [bp - y]
jg anim_circle_q3_test2
inc word [bp - y]
mov si, word [bp - y]
add si, si
inc si
add [bp - err], si
anim_circle_q3_test2:
mov si, word [bp + circ_r] ; if (r > x || err > y) err += ++x*2+1;
cmp si, word [bp - x]
jg anim_circle_q3_test2_execute
mov si, word [bp - err]
cmp si, word [bp - y]
jg anim_circle_q3_test2_execute
jmp anim_circle_q3_test_exit
anim_circle_q3_test2_execute:
inc word [bp - x] ; err += ++x*2+1
mov si, word [bp - x]
add si, si
inc si
add [bp - err], si
;____________________
anim_circle_q3_test_exit:
cmp [bp - x], word 0 ; if (x < 0) break;
jl Animation_Circle_Q3_Repeat
pop dx
pop cx
pop ax
pop si
pop di
pop es
leave
ret 6 |
[bits 16]
disk_read:
pusha
push dx
mov ah, 0x02
mov al, dh
mov ch, 0x00
mov dh, 0x00
mov cl, 0x02
int 0x13
jc disk_read_error
pop dx
cmp dh, al
jne disk_read_error
popa
jmp after_disk_read
ret
disk_read_error:
mov bx, DISK_READ_ERROR_MSG
call print_string
hlt |
/*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2019 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEDeformableSpringDomain.h"
#include <FECore/FEModel.h>
#include <FECore/FEGlobalMatrix.h>
BEGIN_PARAMETER_LIST(FEDeformableSpringDomain, FEDiscreteDomain)
ADD_PARAMETER(m_kbend, FE_PARAM_DOUBLE, "k_bend");
ADD_PARAMETER(m_kstab, FE_PARAM_DOUBLE, "k_stab");
END_PARAMETER_LIST();
//-----------------------------------------------------------------------------
FEDeformableSpringDomain::FEDeformableSpringDomain(FEModel* pfem) : FEDiscreteDomain(&pfem->GetMesh()), FEElasticDomain(pfem)
{
m_pMat = 0;
m_kbend = 0.0;
m_kstab = 0.0;
}
//-----------------------------------------------------------------------------
void FEDeformableSpringDomain::SetMaterial(FEMaterial* pmat)
{
m_pMat = dynamic_cast<FESpringMaterial*>(pmat);
assert(m_pMat);
}
//-----------------------------------------------------------------------------
void FEDeformableSpringDomain::BuildMatrixProfile(FEGlobalMatrix& K)
{
// we connect each node to its two neighbors
int NN = Nodes();
for (int i=1; i<NN-1; ++i)
{
vector<int> lm(3*6, -1);
for (int j=0; j<3; ++j)
{
int n = i-1+j;
vector<int>& id = Node(n).m_ID;
// first the displacement dofs
lm[6 * j ] = id[m_dofX];
lm[6 * j + 1] = id[m_dofY];
lm[6 * j + 2] = id[m_dofZ];
// rigid rotational dofs
lm[6 * j + 3] = id[m_dofRU];
lm[6 * j + 4] = id[m_dofRV];
lm[6 * j + 5] = id[m_dofRW];
}
K.build_add(lm);
}
}
//-----------------------------------------------------------------------------
void FEDeformableSpringDomain::UnpackLM(FEElement &el, vector<int>& lm)
{
int N = el.Nodes();
lm.resize(N * 6);
for (int i = 0; i<N; ++i)
{
FENode& node = m_pMesh->Node(el.m_node[i]);
vector<int>& id = node.m_ID;
// first the displacement dofs
lm[3 * i] = id[m_dofX];
lm[3 * i + 1] = id[m_dofY];
lm[3 * i + 2] = id[m_dofZ];
// rigid rotational dofs
lm[3 * N + 3 * i] = id[m_dofRU];
lm[3 * N + 3 * i + 1] = id[m_dofRV];
lm[3 * N + 3 * i + 2] = id[m_dofRW];
}
}
//-----------------------------------------------------------------------------
void FEDeformableSpringDomain::Activate()
{
for (int i = 0; i<Nodes(); ++i)
{
FENode& node = Node(i);
if (node.HasFlags(FENode::EXCLUDE) == false)
{
if (node.m_rid < 0)
{
node.m_ID[m_dofX] = DOF_ACTIVE;
node.m_ID[m_dofY] = DOF_ACTIVE;
node.m_ID[m_dofZ] = DOF_ACTIVE;
}
}
}
// calculate the intitial spring length
m_L0 = InitialLength();
}
//-----------------------------------------------------------------------------
double FEDeformableSpringDomain::InitialLength()
{
FEMesh& mesh = *m_pMesh;
double L = 0.0;
for (size_t i = 0; i<m_Elem.size(); ++i)
{
// get the discrete element
FEDiscreteElement& el = m_Elem[i];
// get the nodes
FENode& n1 = mesh.Node(el.m_node[0]);
FENode& n2 = mesh.Node(el.m_node[1]);
// get the nodal positions
vec3d& r1 = n1.m_r0;
vec3d& r2 = n2.m_r0;
L += (r2 - r1).norm();
}
return L;
}
//-----------------------------------------------------------------------------
double FEDeformableSpringDomain::CurrentLength()
{
FEMesh& mesh = *m_pMesh;
double L = 0.0;
for (size_t i = 0; i<m_Elem.size(); ++i)
{
// get the discrete element
FEDiscreteElement& el = m_Elem[i];
// get the nodes
FENode& n1 = mesh.Node(el.m_node[0]);
FENode& n2 = mesh.Node(el.m_node[1]);
// get the nodal positions
vec3d& r1 = n1.m_rt;
vec3d& r2 = n2.m_rt;
L += (r2 - r1).norm();
}
return L;
}
//-----------------------------------------------------------------------------
//! Calculates the forces due to discrete elements (i.e. springs)
void FEDeformableSpringDomain::InternalForces(FEGlobalVector& R)
{
FEMesh& mesh = *m_pMesh;
vector<double> fe(6);
vec3d u1, u2;
vector<int> en(2), lm(6);
// calculate current length
double L = CurrentLength();
double DL = L - m_L0;
// calculate force
double F = m_pMat->force(DL);
for (size_t i = 0; i<m_Elem.size(); ++i)
{
// get the discrete element
FEDiscreteElement& el = m_Elem[i];
// get the nodes
FENode& n1 = mesh.Node(el.m_node[0]);
FENode& n2 = mesh.Node(el.m_node[1]);
// get the nodal positions
vec3d& r01 = n1.m_r0;
vec3d& r02 = n2.m_r0;
vec3d& rt1 = n1.m_rt;
vec3d& rt2 = n2.m_rt;
vec3d e = rt2 - rt1; e.unit();
// calculate spring lengths
double L0 = (r02 - r01).norm();
double Lt = (rt2 - rt1).norm();
double DL = Lt - L0;
// set up the force vector
fe[0] = F*e.x;
fe[1] = F*e.y;
fe[2] = F*e.z;
fe[3] = -F*e.x;
fe[4] = -F*e.y;
fe[5] = -F*e.z;
// setup the node vector
en[0] = el.m_node[0];
en[1] = el.m_node[1];
// set up the LM vector
UnpackLM(el, lm);
// assemble element
R.Assemble(en, lm, fe);
}
if (m_kbend > 0)
{
/* double eps = m_kbend;
lm.resize(3);
en.resize(1);
fe.resize(3);
int NN = Nodes();
for (int i = 1; i<NN - 1; ++i)
{
int i0 = i - 1;
int i1 = i + 1;
vec3d xi = Node(i).m_rt;
vec3d x0 = Node(i0).m_rt;
vec3d x1 = Node(i1).m_rt;
vec3d r = xi - x0;
vec3d s = x1 - x0; s.unit();
vec3d d = r - s*(r*s);
fe[0] = -eps*d.x;
fe[1] = -eps*d.y;
fe[2] = -eps*d.z;
en[0] = m_Node[i];
lm[0] = Node(i).m_ID[m_dofX];
lm[1] = Node(i).m_ID[m_dofY];
lm[2] = Node(i).m_ID[m_dofZ];
R.Assemble(en, lm, fe);
}
*/
double eps = m_kbend;
lm.resize(3);
en.resize(1);
fe.resize(3);
int NN = Nodes();
for (int i = 1; i<NN - 1; ++i)
{
int i0 = i - 1;
int i1 = i + 1;
vec3d xi = Node(i).m_rt;
vec3d x0 = Node(i0).m_rt;
vec3d x1 = Node(i1).m_rt;
vec3d d = xi - (x0 + x1)*0.5;
fe[0] = -eps*d.x;
fe[1] = -eps*d.y;
fe[2] = -eps*d.z;
en[0] = m_Node[i];
lm[0] = Node(i).m_ID[m_dofX];
lm[1] = Node(i).m_ID[m_dofY];
lm[2] = Node(i).m_ID[m_dofZ];
R.Assemble(en, lm, fe);
}
}
if (m_kstab > 0)
{
double eps = m_kstab;
lm.resize(6);
en.resize(2);
fe.resize(6);
int NE = Elements();
for (int i=0; i<NE; ++i)
{
FEDiscreteElement& el = Element(i);
en[0] = el.m_node[0];
en[1] = el.m_node[1];
// get the nodes
FENode& n0 = mesh.Node(en[0]);
FENode& n1 = mesh.Node(en[1]);
lm[0] = n0.m_ID[m_dofX];
lm[1] = n0.m_ID[m_dofY];
lm[2] = n0.m_ID[m_dofZ];
lm[3] = n1.m_ID[m_dofX];
lm[4] = n1.m_ID[m_dofY];
lm[5] = n1.m_ID[m_dofZ];
vec3d ei = n1.m_rt - n0.m_rt;
fe[0] = eps*ei.x;
fe[1] = eps*ei.y;
fe[2] = eps*ei.z;
fe[3] = -eps*ei.x;
fe[4] = -eps*ei.y;
fe[5] = -eps*ei.z;
R.Assemble(en, lm, fe);
}
}
}
//-----------------------------------------------------------------------------
//! Calculates the discrete element stiffness
void FEDeformableSpringDomain::StiffnessMatrix(FESolver* psolver)
{
FEMesh& mesh = *m_pMesh;
// calculate current length
double L = CurrentLength();
double DL = L - m_L0;
// evaluate the stiffness
double F = m_pMat->force(DL);
double E = m_pMat->stiffness(DL);
matrix ke(6, 6);
ke.zero();
vector<int> en(2), lm(6);
// loop over all discrete elements
for (size_t i = 0; i<m_Elem.size(); ++i)
{
// get the discrete element
FEDiscreteElement& el = m_Elem[i];
// get the nodes of the element
FENode& n1 = mesh.Node(el.m_node[0]);
FENode& n2 = mesh.Node(el.m_node[1]);
// get the nodal positions
vec3d& r01 = n1.m_r0;
vec3d& r02 = n2.m_r0;
vec3d& rt1 = n1.m_rt;
vec3d& rt2 = n2.m_rt;
vec3d e = rt2 - rt1; e.unit();
// calculate nodal displacements
vec3d u1 = rt1 - r01;
vec3d u2 = rt2 - r02;
// calculate spring lengths
double L0 = (r02 - r01).norm();
double Lt = (rt2 - rt1).norm();
double DL = Lt - L0;
if (Lt == 0) { F = 0; Lt = 1; e = vec3d(1, 1, 1); }
double A[3][3] = { 0 };
A[0][0] = ((E - F / Lt)*e.x*e.x + F / Lt);
A[1][1] = ((E - F / Lt)*e.y*e.y + F / Lt);
A[2][2] = ((E - F / Lt)*e.z*e.z + F / Lt);
A[0][1] = A[1][0] = (E - F / Lt)*e.x*e.y;
A[1][2] = A[2][1] = (E - F / Lt)*e.y*e.z;
A[0][2] = A[2][0] = (E - F / Lt)*e.x*e.z;
ke[0][0] = A[0][0]; ke[0][1] = A[0][1]; ke[0][2] = A[0][2];
ke[1][0] = A[1][0]; ke[1][1] = A[1][1]; ke[1][2] = A[1][2];
ke[2][0] = A[2][0]; ke[2][1] = A[2][1]; ke[2][2] = A[2][2];
ke[0][3] = -A[0][0]; ke[0][4] = -A[0][1]; ke[0][5] = -A[0][2];
ke[1][3] = -A[1][0]; ke[1][4] = -A[1][1]; ke[1][5] = -A[1][2];
ke[2][3] = -A[2][0]; ke[2][4] = -A[2][1]; ke[2][5] = -A[2][2];
ke[3][0] = -A[0][0]; ke[3][1] = -A[0][1]; ke[3][2] = -A[0][2];
ke[4][0] = -A[1][0]; ke[4][1] = -A[1][1]; ke[4][2] = -A[1][2];
ke[5][0] = -A[2][0]; ke[5][1] = -A[2][1]; ke[5][2] = -A[2][2];
ke[3][3] = A[0][0]; ke[3][4] = A[0][1]; ke[3][5] = A[0][2];
ke[4][3] = A[1][0]; ke[4][4] = A[1][1]; ke[4][5] = A[1][2];
ke[5][3] = A[2][0]; ke[5][4] = A[2][1]; ke[5][5] = A[2][2];
// setup the node vector
en[0] = el.m_node[0];
en[1] = el.m_node[1];
// set up the LM vector
UnpackLM(el, lm);
// assemble the element into the global system
psolver->AssembleStiffness(en, lm, ke);
}
// Add Bending stiffness
if (m_kbend > 0)
{
double eps = m_kbend;
vector<int> lmi(3);
vector<int> lmj(9);
en.resize(3);
int NN = Nodes();
for (int i = 1; i<NN - 1; ++i)
{
int i0 = i - 1;
int i1 = i + 1;
ke.resize(3, 9);
ke.zero();
ke[0][0] = -eps; ke[0][3] = 0.5*eps; ke[0][6] = 0.5*eps;
ke[1][1] = -eps; ke[1][4] = 0.5*eps; ke[1][7] = 0.5*eps;
ke[2][2] = -eps; ke[2][5] = 0.5*eps; ke[2][8] = 0.5*eps;
vector<int>& IDi = Node(i).m_ID;
vector<int>& ID0 = Node(i0).m_ID;
vector<int>& ID1 = Node(i1).m_ID;
lmi[0] = IDi[m_dofX];
lmi[1] = IDi[m_dofY];
lmi[2] = IDi[m_dofZ];
lmj[0] = IDi[m_dofX];
lmj[1] = IDi[m_dofY];
lmj[2] = IDi[m_dofZ];
lmj[3] = ID0[m_dofX];
lmj[4] = ID0[m_dofY];
lmj[5] = ID0[m_dofZ];
lmj[6] = ID1[m_dofX];
lmj[7] = ID1[m_dofY];
lmj[8] = ID1[m_dofZ];
psolver->AssembleStiffness2(lmi, lmj, ke);
}
}
if (m_kstab > 0)
{
double eps = m_kstab;
lm.resize(6);
en.resize(2);
ke.resize(6,6); ke.zero();
ke[0][0] = ke[1][1] = ke[2][2] = eps;
ke[3][0] = ke[4][1] = ke[5][2] = -eps;
ke[0][3] = ke[1][4] = ke[2][5] = -eps;
ke[3][3] = ke[4][4] = ke[5][5] = eps;
int NE = Elements();
for (int i = 0; i<NE; ++i)
{
FEDiscreteElement& el = Element(i);
en[0] = el.m_node[0];
en[1] = el.m_node[1];
// get the nodes
FENode& n0 = mesh.Node(en[0]);
FENode& n1 = mesh.Node(en[1]);
lm[0] = n0.m_ID[m_dofX];
lm[1] = n0.m_ID[m_dofY];
lm[2] = n0.m_ID[m_dofZ];
lm[3] = n1.m_ID[m_dofX];
lm[4] = n1.m_ID[m_dofY];
lm[5] = n1.m_ID[m_dofZ];
// assemble the element into the global system
psolver->AssembleStiffness(en, lm, ke);
}
}
}
//=============================================================================
//-----------------------------------------------------------------------------
FEDeformableSpringDomain2::FEDeformableSpringDomain2(FEModel* pfem) : FEDiscreteDomain(&pfem->GetMesh()), FEElasticDomain(pfem)
{
m_pMat = 0;
}
//-----------------------------------------------------------------------------
void FEDeformableSpringDomain2::SetMaterial(FEMaterial* pmat)
{
m_pMat = dynamic_cast<FESpringMaterial*>(pmat);
assert(m_pMat);
}
//-----------------------------------------------------------------------------
// Only two nodes contribute to this spring
void FEDeformableSpringDomain2::UnpackLM(FEElement &el, vector<int>& lm)
{
int N = Nodes();
lm.resize(2 * 6);
for (int i = 0; i<2; ++i)
{
int n = (i==0? 0 : N-1);
FENode& node = Node(n);
vector<int>& id = node.m_ID;
// first the displacement dofs
lm[3 * i ] = id[m_dofX];
lm[3 * i + 1] = id[m_dofY];
lm[3 * i + 2] = id[m_dofZ];
// rigid rotational dofs
lm[3 + 3 * i ] = id[m_dofRU];
lm[3 + 3 * i + 1] = id[m_dofRV];
lm[3 + 3 * i + 2] = id[m_dofRW];
}
}
//-----------------------------------------------------------------------------
bool FEDeformableSpringDomain2::Init()
{
if (FEDiscreteDomain::Init() == false) return false;
// initialize node data
int NN = Nodes();
m_nodeData.resize(NN);
for (int i=0; i<NN; ++i) m_nodeData[i].banchor = false;
// anchor first and last
m_nodeData[0].banchor = true;
m_nodeData[NN-1].banchor = true;
return true;
}
//-----------------------------------------------------------------------------
void FEDeformableSpringDomain2::Activate()
{
int N = Nodes();
for (int i = 0; i<2; ++i)
{
int n = (i == 0 ? 0 : N - 1);
FENode& node = Node(n);
if (node.HasFlags(FENode::EXCLUDE) == false)
{
if (node.m_rid < 0)
{
node.m_ID[m_dofX] = DOF_ACTIVE;
node.m_ID[m_dofY] = DOF_ACTIVE;
node.m_ID[m_dofZ] = DOF_ACTIVE;
}
}
}
// Not sure if this necessary, but let's just do it to be sure
UpdateNodes();
// calculate the spring lengths
m_L0 = InitialLength();
m_Lt = CurrentLength();
}
//-----------------------------------------------------------------------------
double FEDeformableSpringDomain2::InitialLength()
{
FEMesh& mesh = *m_pMesh;
double L = 0.0;
for (size_t i = 0; i<m_Elem.size(); ++i)
{
// get the discrete element
FEDiscreteElement& el = m_Elem[i];
// get the nodes
FENode& n1 = mesh.Node(el.m_node[0]);
FENode& n2 = mesh.Node(el.m_node[1]);
// get the nodal positions
vec3d& r1 = n1.m_r0;
vec3d& r2 = n2.m_r0;
double DL = (r2 - r1).norm();
L += DL;
}
return L;
}
//-----------------------------------------------------------------------------
double FEDeformableSpringDomain2::CurrentLength()
{
FEMesh& mesh = *m_pMesh;
double L = 0.0;
for (size_t i = 0; i<m_Elem.size(); ++i)
{
// get the discrete element
FEDiscreteElement& el = m_Elem[i];
// get the nodes
FENode& n1 = mesh.Node(el.m_node[0]);
FENode& n2 = mesh.Node(el.m_node[1]);
// get the nodal positions
vec3d& r1 = n1.m_rt;
vec3d& r2 = n2.m_rt;
double DL = (r2 - r1).norm();
L += DL;
}
return L;
}
//-----------------------------------------------------------------------------
//! Calculates the forces due to discrete elements (i.e. springs)
void FEDeformableSpringDomain2::InternalForces(FEGlobalVector& R)
{
FEMesh& mesh = *m_pMesh;
vector<double> fe(6);
vec3d u1, u2;
vector<int> en(2), lm(6);
// calculate length increment
double DL = m_Lt - m_L0;
// calculate force
double F = m_pMat->force(DL);
int N = Elements();
for (size_t i = 0; i<2; ++i)
{
int n = (i==0? 0 : N-1);
double sign = (i == 0 ? 1 : -1);
// get the discrete element
FEDiscreteElement& el = Element(n);
// get the nodes
FENode& n1 = mesh.Node(el.m_node[0]);
FENode& n2 = mesh.Node(el.m_node[1]);
// get the nodal positions
vec3d& r01 = n1.m_r0;
vec3d& r02 = n2.m_r0;
vec3d& rt1 = n1.m_rt;
vec3d& rt2 = n2.m_rt;
vec3d e = rt2 - rt1; e.unit();
// set up the force vector
fe[i*3 ] = sign*F*e.x;
fe[i*3 + 1] = sign*F*e.y;
fe[i*3 + 2] = sign*F*e.z;
// setup the node vector
en[i] = el.m_node[i];
// set up the LM vector
if (i==0) UnpackLM(el, lm);
}
// assemble element
R.Assemble(en, lm, fe);
}
//-----------------------------------------------------------------------------
//! Calculates the discrete element stiffness
void FEDeformableSpringDomain2::StiffnessMatrix(FESolver* psolver)
{
FEMesh& mesh = *m_pMesh;
matrix ke(6, 6);
ke.zero();
vector<int> en(2), lm(6);
// get the nodes of the element
int NN = Nodes();
FENode& n1 = Node(0);
FENode& n2 = Node(NN-1);
// get the nodal positions
vec3d& r01 = n1.m_r0;
vec3d& r02 = n2.m_r0;
vec3d& rt1 = n1.m_rt;
vec3d& rt2 = n2.m_rt;
vec3d e = rt2 - rt1; e.unit();
// calculate spring lengths
double L0 = (r02 - r01).norm();
double Lt = (rt2 - rt1).norm();
double DL = Lt - L0;
// evaluate the stiffness
double F = m_pMat->force(DL);
double E = m_pMat->stiffness(DL);
if (Lt == 0) { F = 0; Lt = 1; e = vec3d(1, 1, 1); }
double A[3][3] = { 0 };
A[0][0] = ((E - F / Lt)*e.x*e.x + F / Lt);
A[1][1] = ((E - F / Lt)*e.y*e.y + F / Lt);
A[2][2] = ((E - F / Lt)*e.z*e.z + F / Lt);
A[0][1] = A[1][0] = (E - F / Lt)*e.x*e.y;
A[1][2] = A[2][1] = (E - F / Lt)*e.y*e.z;
A[0][2] = A[2][0] = (E - F / Lt)*e.x*e.z;
ke[0][0] = A[0][0]; ke[0][1] = A[0][1]; ke[0][2] = A[0][2];
ke[1][0] = A[1][0]; ke[1][1] = A[1][1]; ke[1][2] = A[1][2];
ke[2][0] = A[2][0]; ke[2][1] = A[2][1]; ke[2][2] = A[2][2];
ke[0][3] = -A[0][0]; ke[0][4] = -A[0][1]; ke[0][5] = -A[0][2];
ke[1][3] = -A[1][0]; ke[1][4] = -A[1][1]; ke[1][5] = -A[1][2];
ke[2][3] = -A[2][0]; ke[2][4] = -A[2][1]; ke[2][5] = -A[2][2];
ke[3][0] = -A[0][0]; ke[3][1] = -A[0][1]; ke[3][2] = -A[0][2];
ke[4][0] = -A[1][0]; ke[4][1] = -A[1][1]; ke[4][2] = -A[1][2];
ke[5][0] = -A[2][0]; ke[5][1] = -A[2][1]; ke[5][2] = -A[2][2];
ke[3][3] = A[0][0]; ke[3][4] = A[0][1]; ke[3][5] = A[0][2];
ke[4][3] = A[1][0]; ke[4][4] = A[1][1]; ke[4][5] = A[1][2];
ke[5][3] = A[2][0]; ke[5][4] = A[2][1]; ke[5][5] = A[2][2];
// setup the node vector
en[0] = m_Node[0];
en[1] = m_Node[NN-1];
// set up the LM vector
UnpackLM(Element(0), lm);
// assemble the element into the global system
psolver->AssembleStiffness(en, lm, ke);
}
//-----------------------------------------------------------------------------
void FEDeformableSpringDomain2::Update(const FETimeInfo& tp)
{
// update wire partition and nodal positions
UpdateNodes();
}
//-----------------------------------------------------------------------------
void FEDeformableSpringDomain2::SetNodePosition(int node, const vec3d& r)
{
FENode& nd = Node(node);
nd.m_rt = r;
vec3d u = nd.m_rt - nd.m_r0;
nd.set_vec3d(m_dofX, m_dofY, m_dofZ, u);
}
//-----------------------------------------------------------------------------
// This functions distributes the nodes that are not anchored evenly between anchor
// points.
void FEDeformableSpringDomain2::UpdateNodes()
{
// make sure we have enough nodes
// We need more than 2 nodes since the outer nodes are always anchored.
int NN = Nodes();
if (NN <= 2) return;
// find wire segments
int n0 = 0, n1 = 1;
while (n0 < NN-1)
{
if (m_nodeData[n1].banchor)
{
vec3d r0 = Node(n0).m_rt;
vec3d r1 = Node(n1).m_rt;
for (int n = n0+1; n<=n1-1; ++n)
{
assert(m_nodeData[n].banchor == false);
double w = (double) (n - n0) / (double)(n1 - n0);
FENode& nd = Node(n);
nd.m_rt = r0 + (r1 - r0)*w;
vec3d u = nd.m_rt - nd.m_r0;
nd.set_vec3d(m_dofX, m_dofY, m_dofZ, u);
}
n0 = n1;
}
n1++;
}
// re-calculate current length
m_Lt = CurrentLength();
}
//-----------------------------------------------------------------------------
//! Anchor (or release) a node
void FEDeformableSpringDomain2::AnchorNode(int node, bool banchor)
{
m_nodeData[node].banchor = banchor;
}
//-----------------------------------------------------------------------------
vec3d FEDeformableSpringDomain2::NodalForce(int node)
{
int NN = Nodes();
if ((node <= 0) || (node >= NN -1)) return vec3d(0,0,0);
vec3d r = Node(node).m_rt;
vec3d rm = Node(node-1).m_rt;
vec3d rp = Node(node+1).m_rt;
double F = SpringForce();
vec3d A = rm - r; A.unit(); A *= F;
vec3d B = rp - r; B.unit(); B *= F;
vec3d D = A + B;
return D;
}
//-----------------------------------------------------------------------------
//! get net spring force
double FEDeformableSpringDomain2::SpringForce()
{
return m_pMat->force(m_Lt - m_L0);
}
//-----------------------------------------------------------------------------
//! tangent
vec3d FEDeformableSpringDomain2::Tangent(int node)
{
int NN = Nodes();
if (NN < 2) return vec3d(0,0,0);
if (node == 0)
{
vec3d t = Node(node+1).m_rt - Node(node).m_rt;
t.unit();
return t;
}
else if (node == NN-1)
{
vec3d t = Node(node).m_rt - Node(node - 1).m_rt;
t.unit();
return t;
}
else
{
vec3d t = Node(node + 1).m_rt - Node(node - 1).m_rt;
t.unit();
return t;
}
}
|
SECTION code_clib
PUBLIC plotpixel
EXTERN __gfx_coords
;
; $Id: plotpixl.asm,v 1.14 2016/07/02 09:01:36 dom Exp $
;
; ******************************************************************
;
; Plot pixel at (x,y) coordinate.
;
; ZX 81 version.
; 64x48 dots.
;
;
.plotpixel
ld a,h
cp 64
ret nc
ld a,l
;cp maxy
cp 48
ret nc ; y0 out of range
ld (__gfx_coords),hl
push bc
ld c,l
ld b,h
push bc
srl b
srl c
IF FORlambda
ld hl,16510
ELSE
ld hl,(16396) ; D_FILE
inc hl
ENDIF
ld a,c
ld c,b ; !!
ld de,33 ; 32+1. Every text line ends with an HALT
and a
jr z,r_zero
ld b,a
.r_loop
add hl,de
djnz r_loop
.r_zero ; hl = char address
ld e,c
add hl,de
ld a,(hl) ; get current symbol
cp 8
jr c,islow ; recode graph symbol to binary -> 0..F
ld a,143
sub (hl)
.islow ex (sp),hl ; save char address <=> restore x,y
cp 16 ; Just to be sure:
jr c,issym ; if it isn't a symbol...
xor a ; .. force to blank sym
.issym
ld b,a
ld a,1 ; the bit we want to draw
bit 0,h
jr z,iseven
add a,a ; move right the bit
.iseven
bit 0,l
jr z,evenrow
add a,a
add a,a ; move down the bit
.evenrow
or b
cp 8 ; Now back from binary to
jr c,hisym ; graph symbols.
ld b,a
ld a,15
sub b
add a,128
.hisym
pop hl
ld (hl),a
pop bc
ret
|
;/**; HOT- ;; sart ;*/;NOTE: T=85;..\headers\hot.incmObject_var _v2_HOThome_data res 0;// PUP DSFLAG res 1 ; DSFLAG,0 - H-Init is successful ; DSFLAG,1 - H-Last cicle is start( ; DSFLAG,2 - H-Normal Work,L-first mal ; DSFLAG,3 - ; DSFLAG,4 - H- DS- DS (=85, CRC=CRC_DS) ; DSFLAG,5 - H- DS- 3-\) ; DSFLAG,6 - H- DS ;+060910 DSFLAG,7 - DSTEMP res 1 ; ->L avaData(_HOT)->M assiveUp+20(_BUM)->Resp_UM1+20(_INFO)->Mass2(_INFO)-> to PC;/// DSLoop res 1CTDS res 1;// ;// LavaData res 1 ;// movff DSTEMP,LavaData ; + 12 ;+310110 ;_HOT_GET_DS1821: mObject_sel THIS movf LavaData,wDSbyte res 9ctERR_DS res 1 ; ERROR DS - 4 ; 0 ByteCount res 1 ; itCount res 1 ; DataByte res 1 ; CRC res 1 ; RC;xxxx idata waveFormTemper res 1 ; 0000_00ss hot_readOnly_zero res 1; ;/// /// ///;///;/// Obj_HOT code;// _HOT_SET_Ini: mObject_sel THIS movlw b'10001110' ; (,bit<0>) (bit<1>) movwf DSFLAG ;DS1820PAR clrf ctERR_DS ; +040310 RROR DS ; !! banksel waveFormTemper clrf hot_readOnly_zero mObject_sel THIS return;/// /// ///;///;/// DS1820PAR;// , ;_B UM_SETdw_Temper; _v#v(HERE)_T ASK_HLTuw_DataRefreshWait;(void/void)<<<DataRefreshWait; _C LK_HLTuw_Tick; _HOT_SET_DS1821:_DSread_DSini_status mObject_sel THIS btfsc DSFLAG,0 ;INI flag resetting ;S (2-10- 5 bra out_DSini_status clrf DSTEMP ;T=0 C incf ctERR_DS,f ;+040310 movlw 4 ;+040310 cpfslt ctERR_DS ;+040310 ? movff DSTEMP, LavaData ; + 12 ;+310110out_DSini_status: btfsc DSFLAG,3 ; ++060910 bra _Testo btfsc DSFLAG,1 ;0- bra _Tstart return_Testo btfsc DSFLAG,1 ;0- bra _Tstart btfsc DSFLAG,5 bra _DSyes ;DS- 3-\) call _DSini btfss DSFLAG,0 return bsf DSFLAG,5 ;1-DS return_DSyes DelayUs 30;25 movlw 0xCC ;command S1820 call _DSWbyte DelayUs 30;25 movlw 0xBE ;command t DS1820 call _DSWbyte DelayUs 13; 10 ;~20mKs- call _DS_R9byte ;DS cpfseq DSbyte+8 ; bra lbl_DSfalse_crc ;CRC NOT=DSbyte+8 movff DSbyte,DSTEMP nop ; t, rrncf DSTEMP ;2 t=1 bcf DSTEMP,7lbl_85: ; T=85, DS: movlw 85 cpfseq DSTEMP bra lbl_85OUT bsf DSFLAG,4 ;H- S incf ctERR_DS ;+040310 clrf DSTEMP ;T=0 C bra lbl_out_DSyes2 ;+040310lbl_85OUT: bcf DSFLAG,4 bra lbl_out_DSyeslbl_DSfalse_crc: incf ctERR_DS ;+040310 clrf DSTEMP ;T=0 C bsf DSFLAG,6 ; DS bra lbl_DS_in_Lavalbl_out_DSyes: clrf ctERR_DS ;+040310lbl_out_DSyes2: bcf DSFLAG,6 ;not DSlbl_DS_in_Lava: ; /=0 (40310) btfsc DSFLAG,4 ;H- S ? bra lbl_ctERR btfss DSFLAG,6 ;H- DS? movff DSTEMP, LavaData ;+ 12 ; lbl_ctERR: movlw 4 ;+040310 cpfslt ctERR_DS ;+040310 ? movff DSTEMP,LavaData ;+ 12 ;+310110 =0 4- bsf DSFLAG,1 bcf DSFLAG,5 ;0-DS _DSini) return_Tstart ;t S1820par mObject_sel THIS call _DSini btfss DSFLAG,0 return DelayUs 30;25 movlw 0xCC ;command call _DSWbyte DelayUs 30;25 ; movlw 0x44 ;command S1820 call _DSWbyte bsf TTX_port bcf TTX_tris bcf DSFLAG,1 ; - bcf DSFLAG,7 ; bcf DSFLAG,3 ;++ 060910 return_DSRbyte ;DS1821 BYTE Read Sub-Programm clrf DSTEMP movlw 0x08 movwf DSLoop_DSLoopr bcf TTX_tris bcf TTX_port DelayUs 3;2 ;Really x2 bcf INTCON,GIEH bsf TTX_tris DelayUs 12; 8 btfsc TTX_port bsf DSTEMP,7 bsf INTCON,GIEH dcfsnz DSLoop,f return ;Byte Reading is finished nop nop DelayUs 25 ;20 ;10 ;20 rrncf DSTEMP,f bra _DSLoopr_DSWbyte ;DS1821 BYTE Write Sub-Programm movwf DSTEMP movlw 0x09 ; 9 movwf DSLoop_DSLoopw dcfsnz DSLoop,f return bcf INTCON,GIEH bcf TTX_tris bcf TTX_port DelayUs 3; 2 btfsc DSTEMP,0 ;Sending H? bsf TTX_tris ;Yes, H DelayUs 75 ;60 ;Send Slot Time bsf TTX_tris bsf INTCON,GIEH DelayUs 3; 2 ;Pause rrncf DSTEMP,f bra _DSLoopw_DSini ;DS1821 INI Sub-Programm bcf DSFLAG,0 ;INI flag resetting bcf TTX_tris bcf TTX_port DelayUs 250; 200 ;Really ~500mkS DelayUs 250; 200 bsf TTX_tris DelayUs 21; 15 movlw 50 movwf CTDS_DSW DelayUs 2;1 dcfsnz CTDS,f return btfsc TTX_port bra _DSW movlw 200 movwf CTDS_DSW2 DelayUs 2;1 dcfsnz CTDS,f return btfss TTX_port bra _DSW2 bsf DSFLAG,0 ;INI is successful return_DS_R9byte ; DS, RC call _DSRbyte MOVFF DSTEMP,DSbyte DelayUs 25 ; 20 call _DSRbyte MOVFF DSTEMP,DSbyte+1 DelayUs 25 ; 20 call _DSRbyte MOVFF DSTEMP,DSbyte+2 DelayUs 25 ; 20 call _DSRbyte MOVFF DSTEMP,DSbyte+3 DelayUs 25 ; 20 call _DSRbyte MOVFF DSTEMP,DSbyte+4 DelayUs 25 ; 20 call _DSRbyte MOVFF DSTEMP,DSbyte+5 DelayUs 25 ; 20 call _DSRbyte MOVFF DSTEMP,DSbyte+6 DelayUs 25 ; 20 call _DSRbyte MOVFF DSTEMP,DSbyte+7 DelayUs 25 ; 20 call _DSRbyte MOVFF DSTEMP, DSbyte+8 lfsr 0, DSbyte ;0x50 ;_DSRbyte movlw 0x08 ; CRC; call CalcCRC8 ;RC, return CRC in W; *********************************************************************; * *; * CalcCRC8 *; * *; * : PIC16. *; * W = . *; * FSR = . *; * IRB = . *; * W = CRC8. *; * : RC8 *; * 8+X5+X4+X1 ( LLAS AN27). CRC8 *; * , *; * ; * , FSR *; * IRB. . *; * *; * . *; * *; * *; * : 26.11.2006 - CRC *; * "#d efine CRC_POLY 0x18". *; * *; *********************************************************************CalcCRC8: movwf ByteCount ; movlw 0x00 ; CRC F !!! - movwf CRCCalcNextByte ; movlw 8 ; 8 movwf BitCount ; movf POSTINC0,w ; SLAVA 051010 movwf DataByte ; CalcNextBit ; movf CRC,w ; RC andlw 0x01 xorwf DataByte, F ; DataByte.0 = CRC.0 btfss DataByte, 0 ; 4 RC goto ShftCRC ; 4 RC movlw CRC_POLY ; 4 RC xorwf CRC, FShftCRC rrcf DataByte, F ; RC rrcf CRC, F decfsz BitCount, F ; goto CalcNextBit ; decfsz ByteCount, F ; goto CalcNextByte ; movf CRC,w ; return;/// /// ///;///;/// -_HOT_GET_DS1821: mObject_sel THIS movf LavaData,w return;_HOT_ASK_DS1821NeedTime: mObject_sel THIS btfss DSFLAG,7 retlw TRUE retlw FALSE;_HOT_CLR_DS1821NeedTime: mObject_sel THIS bsf DSFLAG,7 return;_HOT_SET_DS1821TimeOver: mObject_sel THIS bsf DSFLAG,3 return; igor; _v0_hot_getTermAlrmMask;(void/w) ; banksel waveFormTemper rlncf waveFormTemper, f ; movlw 0x03 ; 0000_0011 - andwf waveFormTemper, f ; ; - mObject_sel THIS ; movlw TERM_THRESHOLD cpfsgt LavaData ; f > w bra temperAlrmNoAdded ; , ; ; banksel waveFormTemper bsf waveFormTemper, 0 ; 0000_00x1 ; movlw b'00010000' bra temperAlrmWasAddedtemperAlrmNoAdded: movlw 0temperAlrmWasAdded: mRETURN; ; waveFormTemper = 0,1,2,3;mEXTENDS _v2_HOT, _v?, hot_public_testTempFront;(void/w)hot_public_testTempFront;(void/w) banksel waveFormTemper ; switch (waveFormTemper) { ; ; 000_0000 movlw 0x00 cpfseq waveFormTemper TSTFSZ hot_readOnly_zero ; retlw NO_EVENT ; 0000_0011 movlw 0x03 cpfseq waveFormTemper TSTFSZ hot_readOnly_zero retlw NO_EVENT; Event occure ; 000_0001 movlw 0x01 cpfseq waveFormTemper TSTFSZ hot_readOnly_zero retlw EVENT_UP ; 000_0010 movlw 0x02 cpfseq waveFormTemper TSTFSZ hot_readOnly_zero mSlideTo hot_prv_tAlrFalled;() ;} retlw NO_EVENT; hot_prv_tAlrFalled;() ;bcf INTCON, GIE ;disable irq . .#ifdef Z_T_ALR_FALL ;movlw 0x13 ;mCall setZ1#endif mCall onDisappearTemperAlrm;(void/void) retlw EVENT_DOWNend
|
#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include <QApplication>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#if QT_VERSION >= 0x050000
#include <QUrlQuery>
#else
#include <QUrl>
#endif
#include <QTextDocument> // for Qt::mightBeRichText
#include <QAbstractItemView>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <QSettings>
#include <QDesktopWidget>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
// return if URI is not valid or is no bitcoin URI
if(!uri.isValid() || uri.scheme() != QString("bitcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
#if QT_VERSION < 0x050000
QList<QPair<QString, QString> > items = uri.queryItems();
#else
QUrlQuery uriQuery(uri);
QList<QPair<QString, QString> > items = uriQuery.queryItems();
#endif
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("bitcoin://"))
{
uri.replace(0, 10, "bitcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
#if QT_VERSION < 0x050000
QString escaped = Qt::escape(str);
#else
QString escaped = str.toHtmlEscaped();
#endif
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item (global clipboard)
QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard);
// Copy first item (global mouse selection for e.g. X11 - NOP on Windows)
QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection);
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != qApp->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "XavierCoin.lnk";
}
bool GetStartOnSystemStartup()
{
// check for XavierCoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "bitcoin.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=XavierCoin\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#elif defined(Q_OS_MAC)
// based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)
{
// loop through the list of startup items and try to find the bitcoin app
CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL);
for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
CFURLRef currentItemURL = NULL;
LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, NULL);
if(currentItemURL && CFEqual(currentItemURL, findUrl)) {
// found
CFRelease(currentItemURL);
return item;
}
if(currentItemURL) {
CFRelease(currentItemURL);
}
}
return NULL;
}
bool GetStartOnSystemStartup()
{
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
return !!foundItem; // return boolified object
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
if(fAutoStart && !foundItem) {
// add bitcoin app to startup item list
LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL);
}
else if(!fAutoStart && foundItem) {
// remove item
LSSharedFileListItemRemove(loginItems, foundItem);
}
return true;
}
#else
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
void saveWindowGeometry(const QString& strSetting, QWidget *parent)
{
QSettings settings;
settings.setValue(strSetting + "Pos", parent->pos());
settings.setValue(strSetting + "Size", parent->size());
}
void restoreWindowGeometry(const QString& strSetting, const QSize& defaultSize, QWidget *parent)
{
QSettings settings;
QPoint pos = settings.value(strSetting + "Pos").toPoint();
QSize size = settings.value(strSetting + "Size", defaultSize).toSize();
if (!pos.x() && !pos.y()) {
QRect screen = QApplication::desktop()->screenGeometry();
pos.setX((screen.width() - size.width()) / 2);
pos.setY((screen.height() - size.height()) / 2);
}
parent->resize(size);
parent->move(pos);
}
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("XavierCoin-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" xaviercoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n" +
" -choosedatadir " + tr("Choose data directory on startup (default: 0)") + "\n";
setWindowTitle(tr("XavierCoin-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
|
;NeoGeo memory editor system ROM v1
;furrtek CC BY-NC 2017
cpu 68000
supmode on
INCLUDE "regdefs.asm"
INCLUDE "ram.asm"
INCLUDE "header.asm"
PHASE $C00000
INCLUDE "irq.asm"
ORG $500
Err:
rts
ORG $600
ErrG:
rte
ORG $1000
Start:
lea $10F300,a7
move.w #$0000,REG_LSPCMODE
move.b d0,REG_SWPBIOS
move.b d0,REG_PALBANK0
move.l #($F300/32)-1,d7 ; Clear work RAM
lea RAMSTART,a0
moveq.l #0,d0
.clear_ram:
move.b d0,REG_DIPSW ; Watchdoge
move.l d0,(a0)+
move.l d0,(a0)+
move.l d0,(a0)+
move.l d0,(a0)+
move.l d0,(a0)+
move.l d0,(a0)+
move.l d0,(a0)+
move.l d0,(a0)+
dbra d7,.clear_ram
move.w #7,REG_IRQACK
move.w #$2000,sr ; Allow IRQs
move.w #BLACK,PALETTES ; Palette 0 color 0
move.w #WHITE,PALETTES+2 ; Palette 0 color 1: Text
move.w #BLACK,PALETTES+4 ; Palette 0 color 2
move.w #BLACK,PALETTES+32 ; Palette 1 color 0
move.w #RED,PALETTES+34 ; Palette 1 color 1: Text
move.w #BLACK,PALETTES+36 ; Palette 1 color 2
move.w #BLACK,BACKDROPCOLOR
lea VRAM_ADDR,a2 ; Clear VRAM
; Fix
move.w #$7000,0(a2) ; VRAM address
move.l #$1000-1,d7
move.w #$00FF,d0 ; Tile $FF, palette 0
nop
move.w #$1,4(a2) ; VRAM mod
.clear_fix:
move.w d0,2(a2) ; VRAM data
nop
nop
dbra d7,.clear_fix
; Sprite heights
move.w #$8200,0(a2) ; VRAM address
move.l #$200-1,d7
move.w #$7800,d0 ; Y=256, height=0
nop
move.w #$1,4(a2) ; VRAM mod
.clear_spr:
move.w d0,2(a2) ; VRAM data
nop
nop
dbra d7,.clear_spr
move.b d0,REG_BRDFIX
move.b #6,CUR_X
move.b #0,CUR_Y
move.l #$300000,BASE_ADDR
clr.b FLAG_VBI
MainLoop:
tst.b FLAG_VBI ; Wait for VBI
beq MainLoop
clr.b FLAG_VBI
; Read inputs
; Update values
movea.l BASE_ADDR,a0
lea $C02000,a1
move.w #$7064,d4 ; VRAM start address
move.l #16-1,d6
.write_lines:
move.w #-$20,4(a2) ; VRAM mod
; Is cursor on this line ?
move.b CUR_X,d2
move.b CUR_Y,d0
neg.b d0
addi.b #15,d0
cmp.b d6,d0
beq .no_hl_l
st.b d2 ; Cursor isn't on line, trash X position to make it invisible
.no_hl_l:
; Write address
addi.w #$C0,d4
move.w d4,0(a2) ; VRAM address
movea.l a0,d0
move.l #6-1,d7
.write_addr:
move.b d0,d1
andi.w #$0F,d1
move.b (a1,d1),d1
cmp.b d7,d2 ; Cursor check
bne .no_hl_a
ori.w #$1000,d1 ; Highlight
.no_hl_a:
move.w d1,2(a2) ; VRAM data
lsr.l #4,d0
dbra d7,.write_addr
addi.w #$40,d4
move.w #$20,4(a2) ; VRAM mod
move.l #6,d3
move.l #8-1,d7
.write_bytes:
move.b (a0)+,d0
move.b d0,d1
move.w d4,0(a2) ; VRAM address
lsr.b #4,d1
andi.w #$0F,d1
move.b (a1,d1),d1
cmp.b d3,d2 ; Cursor check
bne .no_hl_va
ori.w #$1000,d1 ; Highlight
.no_hl_va:
move.w d1,2(a2) ; VRAM data
addq.b #1,d3
andi.w #$0F,d0
move.b (a1,d0),d0
cmp.b d3,d2 ; Cursor check
bne .no_hl_vb
ori.w #$1000,d0 ; Highlight
.no_hl_vb:
move.w d0,2(a2) ; VRAM data
addq.b #1,d3
addi.w #$60,d4
dbra d7,.write_bytes
subi.w #$3FF,d4
dbra d6,.write_lines
bra MainLoop
INCLUDE "video.asm"
ORG $2000
dc.b $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $41, $42, $43, $44, $45, $46
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1992 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: Video Drivers
FILE: vga8Chars.asm
AUTHOR: Jim DeFrisco, Oct 8, 1992
ROUTINES:
Name Description
---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
Jim 10/ 8/92 Initial revision
DESCRIPTION:
$Id: vga8Chars.asm,v 1.2 96/08/05 03:51:45 canavese Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Char1In1Out
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Draw a character, 1 byte of picture data
CALLED BY: INTERNAL
FastCharCommon
PASS: ds:si - character data
es:di - screen position
ch - number of lines to draw
on stack - ax
RETURN: ax - popped off stack
DESTROYED: ch, dx, bp, si, di
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jim 10/19/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Char1In1Out proc near
uses bx
.enter
NMEM < mov bp, cs:[modeInfo].VMI_scanSize >
push ax, dx
mov ax, 8
mul cs:[pixelBytes]
sub bp, ax
pop ax, dx
mov bl, cs:[currentColor].RGB_blue ; get current draw color
mov ax, {word} cs:[currentColor].RGB_red
; do next scan. Load data byte and go for it.
scanLoop:
call DrawOneDataByte
dec ch ; one less scan to do
jz done
NMEM < NextScan di,bp >
MEM < NextScan di ; onto next scan line >
MEM < tst cs:[bm_scansNext] ; if zero, done >
MEM < jns scanLoop >
NMEM < jmp scanLoop >
done:
.leave
pop ax
jmp PSL_afterDraw
Char1In1Out endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DrawOneDataByte
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Draw one data byte, part of a series
CALLED BY:
PASS: ds:si - points to byte to draw
es:di - points into frame buffer
al - color to draw with
RETURN: nothing
DESTROYED: ah
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jim 10/19/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
DrawOneDataByte proc near
mov bh, ds:[si] ; save data byte in al
inc si
xchg al, bl
NextScan di, 0
jc pageDCB
nopageDCB:
shl bh,1
jnc pix2
mov [es:di],ax
mov [es:di+2], bl
pix2:
add di, cs:[pixelBytes]
shl bh,1
jnc pix3
mov [es:di],ax
mov [es:di+2], bl
pix3:
add di, cs:[pixelBytes]
shl bh,1
jnc pix4
mov [es:di],ax
mov [es:di+2], bl
pix4:
add di, cs:[pixelBytes]
shl bh,1
jnc pix5
mov [es:di],ax
mov [es:di+2], bl
pix5:
add di, cs:[pixelBytes]
shl bh,1
jnc pix6
mov [es:di],ax
mov [es:di+2], bl
pix6:
add di, cs:[pixelBytes]
shl bh,1
jnc pix7
mov [es:di],ax
mov [es:di+2], bl
pix7:
add di, cs:[pixelBytes]
shl bh,1
jnc pix8
mov [es:di],ax
mov [es:di+2], bl
pix8:
add di, cs:[pixelBytes]
shl bh,1
jnc done
mov [es:di],ax
mov [es:di+2], bl
done:
add di, cs:[pixelBytes]
xchg al, bl
ret
pageDCB:
mov dx, cs:[pixelsLeft]
cmp dx, 8
ja nopageDCB
cmp cs:[pixelsLeft], 0
jnz nosplit
push cx
xchg al, bl
test bh, 0x80
call PutSplitedPixelMask
xchg al, bl
pop cx
shl bh, 1
dec dx
jmp DCB_1
nosplit:
shl bh, 1
jnc loop1
mov [es:di],ax
mov [es:di+2], bl
loop1:
add di, cs:[pixelBytes]
dec dx
jnz DCB_1
push cx
xchg al, bl
test bh, 0x80
call PutSplitedPixelMask
xchg al, bl
pop cx
shl bh, 1
dec dx
jmp DCB_2
DCB_1:
shl bh, 1
jnc loop2
mov [es:di],ax
mov [es:di+2], bl
loop2:
add di, cs:[pixelBytes]
dec dx
jnz DCB_2
push cx
xchg al, bl
test bh, 0x80
call PutSplitedPixelMask
xchg al, bl
pop cx
shl bh, 1
dec dx
jmp DCB_3
DCB_2:
shl bh, 1
jnc loop3
mov [es:di],ax
mov [es:di+2], bl
loop3:
add di, cs:[pixelBytes]
dec dx
jnz DCB_3
push cx
xchg al, bl
test bh, 0x80
call PutSplitedPixelMask
xchg al, bl
pop cx
shl bh, 1
dec dx
jmp DCB_4
DCB_3:
shl bh,1
jnc loop4
mov [es:di],ax
mov [es:di+2], bl
loop4:
add di, cs:[pixelBytes]
dec dx
jnz DCB_4
push cx
xchg al, bl
test bh, 0x80
call PutSplitedPixelMask
xchg al, bl
pop cx
shl bh, 1
dec dx
jmp DCB_5
DCB_4:
shl bh,1
jnc loop5
mov [es:di],ax
mov [es:di+2], bl
loop5:
add di, cs:[pixelBytes]
dec dx
jnz DCB_5
push cx
xchg al, bl
test bh, 0x80
call PutSplitedPixelMask
xchg al, bl
pop cx
shl bh, 1
dec dx
jmp DCB_6
DCB_5:
shl bh,1
jnc loop6
mov [es:di],ax
mov [es:di+2], bl
loop6:
add di, cs:[pixelBytes]
dec dx
jnz DCB_6
push cx
xchg al, bl
test bh, 0x80
call PutSplitedPixelMask
xchg al, bl
pop cx
shl bh, 1
dec dx
jmp DCB_7
DCB_6:
shl bh,1
jnc loop7
mov [es:di],ax
mov [es:di+2], bl
loop7:
add di, cs:[pixelBytes]
dec dx
tst dx
jnz DCB_7
push cx
xchg al, bl
test bh, 0x80
call PutSplitedPixelMask
xchg al, bl
pop cx
shl bh, 1
dec dx
jmp DCB_8
DCB_7:
shl bh,1
jnc loop8
mov [es:di],ax
mov [es:di+2], bl
loop8:
add di, cs:[pixelBytes]
cmp di, 0
jnz DCB_8
; dec dx
; jnz DCB_8
; cmp cs:[restBytes], 0
; jnz DCB_8
call MidScanNextWin
DCB_8:
xchg al, bl
ret
DrawOneDataByte endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Char2In2Out
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Draw a character, 2 bytes of picture data
CALLED BY: INTERNAL
FastCharCommon
PASS: ds:si - character data
es:di - screen position
ch - number of lines to draw
on stack - ax
RETURN: ax - popped off stack
DESTROYED: ch, dx, bp, si, di
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jim 10/19/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Char2In2Out proc near
uses bx
.enter
NMEM < mov bp, cs:[modeInfo].VMI_scanSize >
push ax, dx
mov ax, 16
mul cs:[pixelBytes]
sub bp, ax
pop ax, dx
mov bl, cs:[currentColor].RGB_blue ; get current draw color
mov ax, {word} cs:[currentColor].RGB_red
; do next scan. Load data byte and go for it.
scanLoop:
call DrawOneDataByte
call DrawOneDataByte
dec ch ; one less scan to do
jz done
NMEM < NextScan di,bp ; onto next scan line >
MEM < NextScan di ; onto next scan line >
MEM < tst cs:[bm_scansNext] ; if zero, done >
MEM < jns scanLoop >
NMEM < jmp scanLoop >
done:
.leave
pop ax
jmp PSL_afterDraw
Char2In2Out endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Char3In3Out
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Draw a character, 3 bytes of picture data
CALLED BY: INTERNAL
FastCharCommon
PASS: ds:si - character data
es:di - screen position
ch - number of lines to draw
on stack - ax
RETURN: ax - popped off stack
DESTROYED: ch, dx, bp, si, di
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jim 10/19/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Char3In3Out proc near
uses bx
.enter
NMEM < mov bp, cs:[modeInfo].VMI_scanSize >
push ax, dx
mov ax, 24
mul cs:[pixelBytes]
sub bp, ax
pop ax, dx
mov bl, cs:[currentColor].RGB_blue ; get current draw color
mov ax, {word} cs:[currentColor].RGB_red
; do next scan. Load data byte and go for it.
scanLoop:
call DrawOneDataByte
call DrawOneDataByte
call DrawOneDataByte
dec ch ; one less scan to do
jz done
NMEM < NextScan di,bp ; onto next scan line >
MEM < NextScan di ; onto next scan line >
MEM < tst cs:[bm_scansNext] ; if zero, done >
MEM < jns scanLoop >
NMEM < jmp scanLoop >
done:
.leave
pop ax
jmp PSL_afterDraw
Char3In3Out endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Char4In4Out
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Draw a character,4 bytes of picture data
CALLED BY: INTERNAL
FastCharCommon
PASS: ds:si - character data
es:di - screen position
ch - number of lines to draw
on stack - ax
RETURN: ax - popped off stack
DESTROYED: ch, dx, bp, si, di
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jim 10/19/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Char4In4Out proc near
uses bx
.enter
NMEM < mov bp, cs:[modeInfo].VMI_scanSize >
push ax, dx
mov ax, 32
mul cs:[pixelBytes]
sub bp, ax
pop ax, dx
mov bl, cs:[currentColor].RGB_blue ; get current draw color
mov ax, {word} cs:[currentColor].RGB_red
; do next scan. Load data byte and go for it.
scanLoop:
call DrawOneDataByte
call DrawOneDataByte
call DrawOneDataByte
call DrawOneDataByte
dec ch ; one less scan to do
jz done
NMEM < NextScan di,bp ; onto next scan line >
MEM < NextScan di ; onto next scan line >
MEM < tst cs:[bm_scansNext] ; if zero, done >
MEM < jns scanLoop >
NMEM < jmp scanLoop >
done:
.leave
pop ax
jmp PSL_afterDraw
Char4In4Out endp
|
; A140236: Double tetrahedral numbers (or double pyramidal numbers): a(n) = k(k+1)(k+2)/6 where k = n(n+1)(n+2)/6.
; 0,1,20,220,1540,7770,30856,102340,295240,762355,1798940,3939936,8104460,15803060,29426320,52636760,90889616,152112005,247574180,392991060,609896980,927341646,1383960600,2030479100,2932714200,4175145975,5865135276,8137872120,11162145820,15147035240,20349625120,27083862256,35730673440,46749475465,60691216180,78213094540,100095116836,127258655810,160787189160,201949404020,252224864360,313332448891,387261777980,476307859280,583109193260,710689591580,862503973296,1042488416200,1255114753200,1505450016525,1799221045700,2142884588676,2543703239220,3009827567670,3550384816440,4175574546220,4896771633656,5726637036415,6679236756940,7770169451880,9016703150140,10437921558736,12054880452160,13890774657760,15971116166720,18323923917585,20979925816916,23972773579580,27339270989380,31119616199210,35357658708680,40101171676196,45402140241800,51317066556675,57907292235100,65239338964800,73385268032076,82423059538820,92437012109520,103518163907640,115764735802320,129282597548181,144185757863140,160596879311540,178647818922580,198480195496990,220245984578136,244108142087260,270241257646360,298832238636295,330081026062060,364201343321816,401421479001180,441985104839480,486152130040160,534199593123280,586422592544096,643135257328025,704671758998900,771387366104300
sub $2,$0
bin $2,3
bin $2,3
sub $1,$2
mov $0,$1
|
MailItems:
db FLOWER_MAIL
db SURF_MAIL
db LITEBLUEMAIL
db PORTRAITMAIL
db LOVELY_MAIL
db EON_MAIL
db MORPH_MAIL
db BLUESKY_MAIL
db MUSIC_MAIL
db MIRAGE_MAIL
db -1
|
/* $Id: Class1.c++ 1024 2010-11-04 19:44:29Z faxguy $ */
/*
* Copyright (c) 1990-1996 Sam Leffler
* Copyright (c) 1991-1996 Silicon Graphics, Inc.
* HylaFAX is a trademark of Silicon Graphics
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
/*
* EIA/TIA-578 (Class 1) Modem Driver.
*/
#include "Sys.h"
#include "Class1.h"
#include "ModemConfig.h"
#include "HDLCFrame.h"
#include "t.30.h"
#include "tiffio.h"
#include "config.h"
#if defined(HAVE_SSL)
#include "sslfax.h"
#endif
#include <stdlib.h>
#include <ctype.h>
#include <arpa/inet.h>
const char* Class1Modem::modulationNames[6] = {
"v.21, chan 2",
"v.27ter fallback mode",
"v.27ter",
"v.29",
"v.17",
"v.33",
};
/*
* Modem capabilities are queried at startup and a
* table based on this is created for each modem.
* This information is used to negotiate T.30 session
* parameters (e.g. signalling rate).
*
* NB: v.17 w/ long training is the same as v.33, at
* least at 12000 and 14400.
*/
const Class1Cap Class1Modem::basicCaps[15] = {
{ 3, 0, 0, V21, false, 0 }, // v.21
{ 24, BR_2400, DCSSIGRATE_2400V27, V27FB, false, 1 }, // v.27 ter
{ 48, BR_4800, DCSSIGRATE_4800V27, V27, false, 2 }, // v.27 ter
{ 72, BR_7200, DCSSIGRATE_7200V29, V29, false, 3 }, // v.29
{ 73, BR_7200, DCSSIGRATE_7200V17, V17, false, 4 }, // v.17
{ 74, BR_7200, DCSSIGRATE_7200V17, V17, false, 5 }, // v.17 w/st
{ 96, BR_9600, DCSSIGRATE_9600V29, V29, false, 6 }, // v.29
{ 97, BR_9600, DCSSIGRATE_9600V17, V17, false, 7 }, // v.17
{ 98, BR_9600, DCSSIGRATE_9600V17, V17, false, 8 }, // v.17 w/st
{ 121, BR_12000, DCSSIGRATE_12000V33, V33, false, 9 }, // v.33
{ 121, BR_12000, DCSSIGRATE_12000V17, V17, false, 10 }, // v.17
{ 122, BR_12000, DCSSIGRATE_12000V17, V17, false, 11 }, // v.17 w/st
{ 145, BR_14400, DCSSIGRATE_14400V33, V33, false, 12 }, // v.33
{ 145, BR_14400, DCSSIGRATE_14400V17, V17, false, 13 }, // v.17
{ 146, BR_14400, DCSSIGRATE_14400V17, V17, false, 14 }, // v.17 w/st
};
#define NCAPS (sizeof (basicCaps) / sizeof (basicCaps[0]))
const char* Class1Modem::tmCmdFmt = "AT+FTM=%u";
const char* Class1Modem::rmCmdFmt = "AT+FRM=%u";
Class1Modem::Class1Modem(FaxServer& s, const ModemConfig& c)
: FaxModem(s,c)
, thCmd("AT+FTH=3")
, rhCmd("AT+FRH=3")
{
messageReceived = false;
memcpy(xmitCaps, basicCaps, sizeof (basicCaps));
memcpy(recvCaps, basicCaps, sizeof (basicCaps));
/*
* Because the sending routines deliver data to the transmit functions
* in segments, these must be globally available to spool outgoing data
* until a complete ECM block can be assembled.
*
* Besides the contents of ecmBlock, ecmStuffedBlock must be able to
* hold all sync flag bytes, stuffed bits, and RCP frames.
*/
u_int fs = 256;
if (conf.class1ECMFrameSize == 64) fs = 64;
ecmFrame = (u_char*) malloc(fs + 4);
fxAssert(ecmFrame != NULL, "ECM procedure error (frame).");
ecmBlock = (u_char*) malloc((fs + 4) * 256);
fxAssert(ecmBlock != NULL, "ECM procedure error (block).");
ecmStuffedBlock = (u_char*) malloc(fs == 256 ? 83000 : 33000);
fxAssert(ecmStuffedBlock != NULL, "ECM procedure error (stuffed block).");
gotCTRL = false;
repeatPhaseB = false;
silenceHeard = false;
imagefd = 0;
}
Class1Modem::~Class1Modem()
{
free(ecmFrame);
free(ecmBlock);
free(ecmStuffedBlock);
}
bool
Class1Modem::atCmd(const fxStr& cmd, ATResponse r, long ms)
{
silenceHeard = false;
return (ClassModem::atCmd(cmd, r, ms));
}
/*
* Check if the modem is a Class 1 modem and,
* if so, configure it for use.
*/
bool
Class1Modem::setupModem(bool isSend)
{
if (!selectBaudRate(conf.maxRate, conf.flowControl, conf.flowControl))
return (false);
// Query service support information
fxStr s;
if (doQuery(conf.classQueryCmd, s, 5000) && FaxModem::parseRange(s, modemServices))
traceBits(modemServices & SERVICE_ALL, serviceNames);
if ((modemServices & serviceType) == 0)
return (false);
atCmd(classCmd);
/*
* Query manufacturer, model, and firmware revision.
* We use the manufacturer especially as a key to
* working around firmware bugs (yech!).
*/
if (setupManufacturer(modemMfr)) {
modemCapability("Mfr " | modemMfr);
modemMfr.raisecase();
}
(void) setupModel(modemModel);
(void) setupRevision(modemRevision);
if (modemModel != "")
modemCapability("Model " | modemModel);
if (modemRevision != "")
modemCapability("Revision " | modemRevision);
/*
* Get modem capabilities and calculate best signalling
* rate, data formatting capabilities, etc. for use in
* T.30 negotiations.
*/
if (!class1Query(conf.class1TMQueryCmd, xmitCaps)) {
serverTrace("Error parsing \"+FTM\" query response: \"%s\"", rbuf);
return (false);
}
modemParams.br = 0;
u_int i;
for (i = 1; i < NCAPS; i++)
if (xmitCaps[i].ok)
modemParams.br |= BIT(xmitCaps[i].br);
nonV34br = modemParams.br;
if (conf.class1EnableV34Cmd != "" && conf.class1ECMSupport) {
// This is cosmetic, mostly, to state the modem supports V.34.
// We could query the modem but that would require another
// config option, so we just trust the enable command.
primaryV34Rate = 0;
u_short pos = conf.class1EnableV34Cmd.findR(conf.class1EnableV34Cmd.length(), "+F34=", 5) + 4;
if (pos == 4) // Unknown class1EnableV34Cmd
modemCapability("Unable to determinate V.34 speed from class1EnableV34Cmd, V.34 faxing will be disabled!");
else
primaryV34Rate = atoi(conf.class1EnableV34Cmd.extract(pos, conf.class1EnableV34Cmd.next(pos, ',') - pos));
modemParams.br |= BIT(primaryV34Rate) - 1;
}
modemParams.wd = conf.class1PageWidthSupport;
modemParams.ln = conf.class1PageLengthSupport;
modemParams.df = BIT(DF_1DMH) | (conf.class1MRSupport ? BIT(DF_2DMR) : 0);
modemParams.bf = BF_DISABLE;
modemParams.st = ST_ALL;
modemParams.jp = 0;
pokeConfig(isSend);
traceModemParams();
/*
* Receive capabilities are maintained separately from
* transmit capabilities because we need to know more
* than the signalling rate to formulate the DIS.
*/
if (!class1Query(conf.class1RMQueryCmd, recvCaps)) {
serverTrace("Error parsing \"+FRM\" query response: \"%s\"", rbuf);
return (false);
}
u_int mods = 0;
for (i = 1; i < NCAPS; i++)
if (recvCaps[i].ok)
mods |= BIT(recvCaps[i].mod);
switch (mods) {
case BIT(V27FB):
discap = DISSIGRATE_V27FB;
break;
case BIT(V27FB)|BIT(V27):
discap = DISSIGRATE_V27;
break;
case BIT(V29):
discap = DISSIGRATE_V29;
break;
case BIT(V27FB)|BIT(V27)|BIT(V29):
discap = DISSIGRATE_V2729;
break;
case BIT(V27FB)|BIT(V27)|BIT(V29)|BIT(V33):
discap = DISSIGRATE_V33;
break;
case BIT(V27FB)|BIT(V27)|BIT(V29)|BIT(V17):
case BIT(V27FB)|BIT(V27)|BIT(V29)|BIT(V33)|BIT(V17):
discap = DISSIGRATE_V17;
break;
}
/*
* T.30 specifies that HDLC frame data are in MSB bit
* order except for CIG/TSI data which have LSB bit order.
* We compose and interpret frame data in MSB bit order
* and pass the frames through frameRev immediately before
* transmitting and upon receiving to handle modem characteristics.
*
* Class1Modem::encodeTSI and Class1Modem::decodeTSI (below)
* assume this work and process CIG/TSI data accordingly.
*/
frameRev = TIFFGetBitRevTable(conf.frameFillOrder == FILLORDER_LSB2MSB);
setupClass1Parameters();
return (true);
}
/*
* These are potentially dynamic modem settings that can be altered on-the-fly.
*/
void
Class1Modem::pokeConfig(bool isSend)
{
modemParams.vr = conf.class1Resolutions; // bitmapped by configuration
if (conf.class1ECMSupport) {
modemParams.ec = BIT(EC_DISABLE) | BIT(EC_ENABLE64) | BIT(EC_ENABLE256);
if (conf.class1MMRSupport) modemParams.df |= BIT(DF_2DMMR);
else modemParams.df &= ~BIT(DF_2DMMR);
switch (conf.class1JBIGSupport) {
case FaxModem::JBIG_FULL:
jbigSupported = true;
break;
case FaxModem::JBIG_SEND:
jbigSupported = isSend;
break;
case FaxModem::JBIG_RECV:
jbigSupported = !isSend;
break;
default:
jbigSupported = false;
break;
}
if (jbigSupported) modemParams.df |= BIT(DF_JBIG);
else modemParams.df &= ~BIT(DF_JBIG);
modemParams.jp = 0;
if (conf.class1GreyJPEGSupport || conf.class1ColorJPEGSupport)
modemParams.jp |= BIT(JP_GREY);
if (conf.class1ColorJPEGSupport)
modemParams.jp |= BIT(JP_COLOR);
} else {
modemParams.ec = BIT(EC_DISABLE);
modemParams.df &= ~BIT(DF_2DMMR);
modemParams.jp = 0;
}
}
/*
* Send the modem the Class 1 configuration commands.
*/
bool
Class1Modem::setupClass1Parameters()
{
if (modemServices & serviceType) {
setupFlowControl(flowControl);
atCmd(conf.setupAACmd);
}
return (true);
}
void
Class1Modem::hangup()
{
#if defined(HAVE_SSL)
if (isSSLFax) {
// terminate SSL Fax connection
SSLFax sslfax;
sslfax.cleanup(sslFaxProcess);
useSSLFax = false;
isSSLFax = false;
setSSLFaxFd(0);
if (sslWatchModem) abortReceive();
sslWatchModem = false;
wasSSLFax = true;
}
#endif
if (useV34) {
// terminate V.34 channel
u_char buf[2];
buf[0] = DLE; buf[1] = EOT; // <DLE><EOT>
putModemData(buf, 2);
// T.31-A1 states that OK is expected. If we don't wait for it, then ATH0 may get missed later.
waitFor(AT_OK);
}
atCmd(conf.onHookCmd, AT_OK, 5000);
}
/*
* Setup receive-specific parameters.
*/
bool
Class1Modem::setupReceive()
{
return (true); // nothing to do
}
/*
* Send the modem any commands needed to force use of
* the specified flow control scheme.
*/
bool
Class1Modem::setupFlowControl(FlowControl fc)
{
switch (fc) {
case FLOW_NONE: return atCmd(conf.class1NFLOCmd);
case FLOW_XONXOFF: return atCmd(conf.class1SFLOCmd);
case FLOW_RTSCTS: return atCmd(conf.class1HFLOCmd);
}
return (true);
}
/*
* Place the modem into the appropriate state
* for sending facsimile.
*/
bool
Class1Modem::faxService(bool enableV34, bool enableV17)
{
if (!atCmd(classCmd)) return (false);
if (conf.class1EnableV34Cmd != "" && enableV34)
atCmd(conf.class1EnableV34Cmd);
useV34 = false; // only when V.8 handshaking is used
#if defined(HAVE_SSL)
SSLFax sslfax;
sslFaxProcess = sslfax.null();
#endif
useSSLFax = false;
isSSLFax = false;
wasSSLFax = false;
remoteCSAinfo = "";
sslFaxPasscode = "";
remoteCSAType = 0x00;
sslRcvCC = sslRcvNext = sslRcvBit = sslGotByte = 0;
sslSawBlockEnd = false;
sslWatchModem = false;
gotEOT = false;
gotRTNC = false;
return (setupFlowControl(flowControl));
}
/*
* The modem is initialized. Now set it to ready for answer.
*/
bool
Class1Modem::ready(long ms)
{
gotEOT = false;
gotRTNC = false;
useV34 = false; // only when V.8 handshaking is used
#if defined(HAVE_SSL)
SSLFax sslfax;
sslFaxProcess = sslfax.null();
#endif
useSSLFax = false;
isSSLFax = false;
wasSSLFax = false;
sslRcvCC = sslRcvNext = sslRcvBit = sslGotByte = 0;
sslSawBlockEnd = false;
sslWatchModem = false;
remoteCSAinfo = "";
sslFaxPasscode = "";
remoteCSAType = 0x00;
if (conf.class1EnableV34Cmd != "" && conf.class1ECMSupport)
if (!atCmd(conf.class1EnableV34Cmd))
return (false);
if (conf.class1AdaptRecvCmd != "")
if (!atCmd(conf.class1AdaptRecvCmd))
return (false);
return (FaxModem::ready(ms));
}
/*
* Set the local subscriber identification.
*/
void
Class1Modem::setLID(const fxStr& number)
{
encodeTSI(lid, number);
}
bool
Class1Modem::supportsPolling() const
{
return (true);
}
/*
* Construct a binary TSI/CIG string for transmission. Note
* that we do not enforce the specification that restricts
* the alphabet to that of Table 3/T.30 (numeric digits,
* hyphen, period, and space), but instead permit any
* printable ASCII string of at most 20 characters to be
* used. Note also that the bit reversal is done with the
* understanding that the encoded string is processed again
* using frameRev (see above) when forming the transmitted
* HDLC frame.
*/
void
Class1Modem::encodeTSI(fxStr& binary, const fxStr& ascii)
{
u_int i, j;
u_char buf[20];
u_int n = fxmin(ascii.length(),(u_int) 20);
for (i = 0, j = 0; i < n; i++) {
int c = ascii[i];
if (isprint(c) || c == ' ')
buf[j++] = frameRev[c];
}
/*
* Now ``reverse copy'' the string.
*/
binary.resize(20);
for (i = 0; j > 0; i++, j--)
binary[i] = buf[j-1];
for (; i < 20; i++)
binary[i] = frameRev[' ']; // blank pad remainder
}
/*
* Encode an NSF string for transmission.
*/
void
Class1Modem::encodeNSF(fxStr& binary, const fxStr& ascii)
{
u_int i, j;
u_int n = ascii.length();
binary.resize(n);
for (i = 0, j = 0; i < n; i++) {
int c = ascii[i];
if (isprint(c) || c == ' ')
binary[j++] = frameRev[c];
}
}
char*
randomString(int len)
{
static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int cs = sizeof(charset) - 1;
char* rstr = (char*) malloc((len + 1) * sizeof(char));
for (int i = 0; i < len; i++) rstr[i] = charset[rand() % cs];
rstr[len] = '\0';
return rstr;
}
/*
* Encode a CSA, TSA, CIA, IRA, or ISP string for transmission.
*
* The format is defined in T.30 5.3.6.2.12. The format provides
* for multiple frames and long addresses (>77 bytes, >80 byte FIF),
* but because we're only currently dealing with what is likely just
* a short string, we don't get that complicated yet.
*
* T.30 doesn't specify how the address is to be formatted in the FIF,
* whether that's IPv4, IPv6, email, or URL. T.30 does suggest that
* these features are intended for T.37 and T.38 uses (because to use
* them bits 1 and/or 3 of the DIS/DCS must be set). However, neither
* T.37 nor T.38 mention these signals at all except for one reference
* in T.38 to IRA/ISP, which only refers the reader back to T.30.
*
* So, it seems that manufacturers are left to their own methods in
* formatting the FIF, and manufacturers are expected to collaborate
* between themselves about how to interact with each other via these
* signals. Therefore, the net effect of DIS/DCS bits 1 and 3 is just
* to enable use of CIA, TSA, and CSA. (IRA/ISP is enabled by yet
* other bits.) There is an expectation that use of those bits would
* suggest T.37 support and T.38 support, but because the FIF of CIA,
* TSA, and CSA is not specified it is left to the DTE to encode or
* decode the meaning and use of these signals so that others may
* be able to interact with it. This enables us to use bits 1 and 3
* and, consequently, TSA and CSA, for SSL Fax.
*
* So, until we see how other manufacturers have implemented these,
* we'll just format the address in a way that will be as transparent
* as possible. (So, we use URLs in a human-readable format.)
*
* The administrator is expected to configure the modem with
* Class1SSLFaxInfo using a hostname and port number, in that order,
* separated by a colon, like this: "hostname:port". If the
* hostname is an IPv6 address it should be enclosed by square
* [brackets]. encodeCSA will prepend Class1SSLFaxInfo with the
* protocol (ssl) and a passcode with formatting. The end-result
* will be a URL in this format:
*
* ssl://passcode@hostname:port
*
* We'll use a passcode of 10 characters (bytes) which will leave
* 60 bytes for the Class1SSLFaxInfo. Although, I suppose that
* a hostname could be longer than this (perhaps just contrived),
* it seems a reasonable limit. If the limit should be expanded
* we'll need to add support for multiple frames as indicated in
* T.30 5.3.6.2.12.
*/
void
Class1Modem::encodeCSA(fxStr& binary, const fxStr& ascii)
{
u_int n = ascii.length();
if (n > 60) {
// We can't support the length of the string.
binary = "";
return;
}
fxStr url = ascii;
url.insert('@');
sslFaxPasscode = randomString(10);
url.insert(sslFaxPasscode);
url.insert("ssl://");
n = url.length();
u_int i, j = 0;
binary.resize(n+3);
binary[j++] = 0x00; // no continuation
binary[j++] = 0x40; // URL address
binary[j++] = frameRev[n]; // address length
for (i = 0; i < n; i++) {
int c = url[i];
binary[j++] = frameRev[c]; // T.30 says LSB2MSB for this
}
}
const fxStr&
Class1Modem::decodeCSA(fxStr& ascii, const HDLCFrame& binary)
{
remoteCSAinfo = "";
remoteCSAType = 0x00;
int n = binary.getFrameDataLength();
ascii = "";
if (n > 3) { // FCF+sequence+type+length
n -= 4;
remoteCSAType = binary[4];
u_int len = binary[5]; len = frameRev[len];
if (n != len) protoTrace("CSA/TSA address length mismatch. Expected %d, got %d.", len, n);
ascii.resize(n);
u_int d = 0;
for (; n > 0; n--) {
u_char b = binary[6+d];
ascii[d++] = frameRev[b];
}
}
return ascii;
}
/*
* Do the inverse of encodeTSI; i.e. convert a binary
* string of encoded digits into the equivalent ascii.
* Note that as above (and per the spec) bytes are
* presumed to be transmitted in LSB2MSB bit order and
* then reversed on receipt according to the host bit
* order.
*/
const fxStr&
Class1Modem::decodeTSI(fxStr& ascii, const HDLCFrame& binary)
{
int n = binary.getFrameDataLength();
if (n > 20) // spec says no more than 20 digits
n = 20;
else n--; // trim FCF
ascii.resize(n);
u_int d = 0;
bool seenDigit = false;
for (const u_char* cp = binary.getFrameData() + n-1; n > 0; cp--, n--) {
/*
* Accept any printable ascii.
*/
u_char c = frameRev[*cp];
if (isprint(c) || c == ' ') {
if (c != ' ')
seenDigit = true;
if (seenDigit)
ascii[d++] = c;
}
}
ascii.resize(d);
return ascii;
}
/*
* Construct a binary PWD/SUB/SEP string for transmission.
*/
void
Class1Modem::encodePWD(fxStr& binary, const fxStr& ascii)
{
encodeTSI(binary, ascii);
}
/*
* Do the inverse of encodePWD; i.e. convert a binary
* string of encoded digits into the equivalent ascii.
*/
const fxStr&
Class1Modem::decodePWD(fxStr& ascii, const HDLCFrame& binary)
{
return decodeTSI(ascii, binary);
}
bool
Class1Modem::switchingPause(fxStr& emsg, u_int times)
{
if (isSSLFax) return (true); // SSL is full-duplex, so no need to pause
if (useV34) return (true); // V.34 is also full-duplex.
/*
* If class1SwitchingCmd is of the AT+FRS=n form we honor
* the caller's indicattion for a multiplication of the
* configured silence detection. This is primarily used
* to avoid sending CRP as a receiver during a sender's TCF,
* but it could also be used in places where we find a
* longer wait often necessary.
*/
fxStr scmd = fxStr(conf.class1SwitchingCmd);
if (times != 1) {
fxStr ncmd = fxStr(scmd);
ncmd.raiseatcmd();
if (ncmd.length() > 7 && ncmd.head(7) == "AT+FRS=") {
int dur = atoi(ncmd.tail(ncmd.length()-7)) * times;
scmd = scmd.head(7) | fxStr(dur, "%d");
}
}
if (!silenceHeard && !atCmd(scmd, AT_OK, 60*1000)) {
emsg = "Failure to receive silence (synchronization failure). {E100}";
protoTrace(emsg);
if (wasTimeout()) abortReceive();
return (false);
}
/*
* We necessarily use class1SwitchingCmd rather frequently...
* sometimes this is programmed to be immediately before our signalling,
* and sometimes this is programmed to be immediately after the remote
* signalling. That doesn't therefore give us very good control on
* ensuring that class1SwitchingCmd is not issued in duplicate in some
* kinds of program flow.
*
* Ideally we'd be able to standardize on issuing class1SwitchingCmd
* only in one case or another (but not both), but that's not particularly
* an easy ideal to realize given the number of exceptions to that rule
* that would neccesarily be required.
*
* So for now we just set this flag here, and we unset it in atCmd, and
* if the flag is set when we come back here, then we can avoid duplication.
*/
silenceHeard = true;
return (true);
}
/*
* Pass data to modem, filtering DLE's and
* optionally including the end-of-data
* marker <DLE><ETX>.
*
* If the data transfer is aborted by the user
* then we must take care to send <DLE><ETX>
* in order to exit gracefully.
*/
bool
Class1Modem::sendClass1Data(const u_char* data, u_int cc,
const u_char* bitrev, bool eod, long ms)
{
#if defined(HAVE_SSL)
if (isSSLFax) {
SSLFax sfp;
int cs = sfp.write(sslFaxProcess, data, cc, bitrev, (sslWatchModem ? getModemFd() : 0), (ms ? ms : 60000), true);
if (cs > 0) { // SSLFax::write returns "1" on success.
if (eod) {
u_char buf[2];
buf[0] = bitrev[DLE]; // counteract later reversal
buf[1] = bitrev[ETX];
cs = sfp.write(sslFaxProcess, buf, 2, bitrev, getModemFd(), (ms ? ms : 60000), false);
}
if (cs > 0) {
protoTrace("SSL Fax successfully wrote %d bytes", cc);
return (true);
}
}
protoTrace("SSL FAX WRITE ERROR: %s", (const char*) sslFaxProcess.emsg);
useSSLFax = false;
isSSLFax = false;
setSSLFaxFd(0);
if (sslWatchModem) abortReceive();
sslWatchModem = false;
wasSSLFax = true;
return (false);
}
#endif
bool ok = putModemDLEData(data, cc, bitrev, ms, conf.doPhaseCDebug);
if (!wasTimeout() && (eod || abortRequested())) {
u_char buf[2];
buf[0] = DLE;
buf[1] = ETX;
ok = putModemData(buf, 2, ms);
return (ok && !abortRequested());
} else
return (ok);
}
/*
* Receive timed out, abort the operation
* and resynchronize before returning.
*/
void
Class1Modem::abortReceive()
{
if (isSSLFax || useV34) return; // nothing to do in V.34 or SSL Fax
if (wasSSLFax) {
// the abort already happened
wasSSLFax = false;
return;
}
bool b = wasTimeout();
char c = CAN; // anything other than DC1/DC3
putModem(&c, 1, 1);
/*
* If the modem handles abort properly, then just
* wait for an OK result. Otherwise, wait a short
* period of time, flush any input, and then send
* "AT" and wait for the return "OK".
*/
if (conf.class1RecvAbortOK == 0) { // modem doesn't send OK response
pause(200);
flushModemInput();
(void) atCmd("AT", AT_OK, 100);
} else
while (!waitFor(AT_OK, conf.class1RecvAbortOK) && lastResponse == AT_OTHER && !wasTimeout());
setTimeout(b); // XXX putModem clobbers timeout state
}
/*
* Request a primary rate renegotiation.
*/
bool
Class1Modem::renegotiatePrimary(bool constrain)
{
u_char buf[4];
u_short size = 0;
buf[size++] = DLE;
if (constrain) {
// don't neotiate a faster rate
if (primaryV34Rate == 1) buf[size++] = 0x70; // 2400 bit/s
else if (primaryV34Rate == 2 || primaryV34Rate == 3) {
/*
* V.34 bitspeed 2400 is only possible with symbolrate 2400, and
* as we have no way of determining the symbolrate, we cannot
* wisely instruct the modem to use 2400 bps unless the modem
* negotiates it independently.
*/
buf[size++] = 0x71; // 4800 bit/s
} else buf[size++] = primaryV34Rate + 0x6D; // drop 4800 bit/s
buf[size++] = DLE;
}
buf[size++] = 0x6C; // <DLE><pph>
if (!putModemData(buf, size)) return (false);
if (constrain)
protoTrace("Request primary rate renegotiation (limit %u bit/s).",
primaryV34Rate == 1 ? 2400 : primaryV34Rate > 3 ? (primaryV34Rate-2)*2400 : 4800);
else
protoTrace("Request primary rate renegotiation.");
return (true);
}
/*
* We need to be ambidextrous in reading data from either
* the modem or the SSL Fax socket.
*/
int
Class1Modem::getModemChar(long ms, bool isquery)
{
if (!isSSLFax) return (ClassModem::getModemChar(ms, isquery));
#if defined(HAVE_SSL)
// We can ignore isquery for SSL Fax because there is no DCE debug needed for it.
int buf[1];
SSLFax sfp;
int r = sfp.read(sslFaxProcess, buf, 1, (sslWatchModem ? getModemFd() : 0), (ms ? ms : 60000));
if (r > 0) {
return (buf[0] & 0xFF);
}
protoTrace("SSL FAX READ ERROR: %s", (const char*) sslFaxProcess.emsg);
useSSLFax = false;
isSSLFax = false;
setSSLFaxFd(0);
if (sslWatchModem) abortReceive();
sslWatchModem = false;
wasSSLFax = true;
#endif
return (EOF);
}
int
Class1Modem::getModemBit(long ms)
{
if (!isSSLFax) return (ClassModem::getModemBit(ms));
/*
* Return bytes bit-by-bit in MSB2LSB order.
* getModemChar() returns them in LSB2MSB.
*/
if (sslRcvBit < 1) {
sslRcvBit = 8;
sslGotByte = getModemChar(ms);
if (sslGotByte == 0x10) { // strip stuffed DLE
sslGotByte = getModemChar(ms);
if (sslGotByte == 0x03) {
sslSawBlockEnd = true; // DLE+ETX
sawBlockEnd();
}
}
}
// enable this to simulate a VERY noisy connection
// if (((int) Sys::now() & 1) && ((random() % 10000)/10000.0) > 0.95) return (1);
if (sslGotByte == EOF) return (EOF);
else if (sslGotByte & (0x80 >> --sslRcvBit)) return (1);
else return (0);
}
int
Class1Modem::getModemDataChar()
{
if (!isSSLFax) return (ClassModem::getModemChar(getDataTimeout()));
return (getModemChar(getDataTimeout()));
}
/*
* Wait for a <DLE><ctrl> response per T.31-A1 B.8.4.
*/
bool
Class1Modem::waitForDCEChannel(bool awaitctrl)
{
time_t start = Sys::now();
int c;
fxStr garbage;
bool gotresponse = false;
gotRTNC = false;
ctrlFrameRcvd = fxStr::null;
do {
c = getModemChar(60000);
if (c == EOF) {
// possible SSL Fax connection
return (false);
}
if (c == DLE) {
/*
* With V.34-faxing we expect <DLE><command>
* Refer to T.31-A1 Table B.1. Except for EOT
* these are merely indicators and do not require
* action.
*/
c = getModemChar(60000);
switch (c) {
case EOT:
protoTrace("EOT received (end of transmission)");
gotEOT = true;
recvdDCN = true;
return (false);
case 0x69:
protoTrace("Control channel retrain");
// wait for the control channel to reappear
// should we reset the timeout setting?
gotresponse = waitForDCEChannel(true);
gotRTNC = true;
return ((awaitctrl ? gotresponse : false));
case 0x6B:
protoTrace("Primary channel selected");
gotCTRL = false;
continue;
case 0x6D:
protoTrace("Control channel selected");
gotCTRL = true;
continue;
case 0x6E: // 1200 bit/s
case 0x6F: // 2400 bit/s
// control rate indication
if (controlV34Rate != (c - 0x6D)) {
controlV34Rate = (c - 0x6D);
protoTrace("Control channel rate now %u bit/s", controlV34Rate*1200);
}
if (awaitctrl) gotresponse = true;
continue;
case 0x70: // 2400 bit/s
case 0x71: // 4800 bit/s
case 0x72: // 7200 bit/s
case 0x73: // 9600 bit/s
case 0x74: // 12000 bit/s
case 0x75: // 14400 bit/s
case 0x76: // 16800 bit/s
case 0x77: // 19200 bit/s
case 0x78: // 21600 bit/s
case 0x79: // 24000 bit/s
case 0x7A: // 26400 bit/s
case 0x7B: // 28800 bit/s
case 0x7C: // 31200 bit/s
case 0x7D: // 33600 bit/s
// primary rate indication
if (primaryV34Rate != (c - 0x6F)) {
primaryV34Rate = (c - 0x6F);
protoTrace("Primary channel rate now %u bit/s", primaryV34Rate*2400);
}
if (!awaitctrl) gotresponse = true;
continue;
default:
// unexpected <DLE><command>, deem as garbage
garbage.append(DLE);
garbage.append(c);
break;
}
} else garbage.append(c);
if (gotCTRL && garbage.length() > 2 && (garbage[0] & 0xFF) == 0xFF &&
(garbage[garbage.length()-2] & 0xFF) == 0x10 &&
(garbage[garbage.length()-1] & 0xFF) == 0x03) {
// We got a control frame and won't get the channel change...
for (u_int i = 0; i < garbage.length()-2; i++) {
if ((garbage[i] & 0xFF) == DLE && ++i < garbage.length()) {
/*
* We've got a frame and must apply T.31-A1 Table B.1.
*/
if ((garbage[i] & 0xFF) == 0x07) { // end of HDLC frame w/FCS error
// what to do? send CRP? discard frame?
continue;
}
switch (garbage[i] & 0xFF) {
case DLE: // <DLE><DLE> => <DLE>
ctrlFrameRcvd.append(DLE);
break;
case SUB: // <DLE><SUB> => <DLE><DLE>
ctrlFrameRcvd.append(DLE);
ctrlFrameRcvd.append(DLE);
break;
case 0x51: // <DLE><0x51> => <DC1>
ctrlFrameRcvd.append(DC1);
break;
case 0x53: // <DLE><0x53> => <DC3>
ctrlFrameRcvd.append(0x13);
break;
}
} else
ctrlFrameRcvd.append(garbage[i] & 0xFF);
}
return (false);
}
fxStr rcpsignal;
rcpsignal.append(0xFF); rcpsignal.append(0x03); rcpsignal.append(0x86); rcpsignal.append(0x69);
rcpsignal.append(0xCB); rcpsignal.append(0x10); rcpsignal.append(0x03);
if (!gotCTRL && garbage == rcpsignal) {
// We anticipate getting "extra" RCP frames since we
// only look for one but usually we will see three.
garbage.cut(0, 7);
}
} while (!gotresponse && Sys::now()-start < 60);
if (getHDLCTracing() && garbage.length()) {
fxStr buf;
u_int j = 0;
for (u_int i = 0; i < garbage.length(); i++) {
if (j > 0)
buf.append(' ');
buf.append(fxStr(garbage[i] & 0xFF, "%2.2X"));
j++;
if (j > 19) {
protoTrace("--> [%u:%.*s]",
j, buf.length(), (const char*) buf);
buf = "";
j = 0;
}
}
if (j)
protoTrace("--> [%u:%.*s]",
j, buf.length(), (const char*) buf);
}
return (gotresponse);
}
/*
* Receive an HDLC frame. The frame itself must
* be received within 3 seconds (per the spec).
* If a carrier is received, but the complete frame
* is not received before the timeout, the receive
* is aborted.
*/
bool
Class1Modem::recvRawFrame(HDLCFrame& frame)
{
/*
* We need to be generous here ... given that
* some frames can be long and some devices
* can add lots of flags to the signalling.
* Adhering to the spec too closely, 5 sec,
* appears to be too conservative; if the modem
* has said CONNECT, then it should be
* responsible enough to carry-through with
* things. A timeout here is only needed to
* reign-in modems that don't carry-through.
*/
startTimeout(10000);
/*
* Strip HDLC frame flags. This is not needed,
* (according to the standard DCE does the job),
* be we leave this legacy code unchanged
* for sure - D.B.
*/
int c;
fxStr garbage;
for (;;) {
c = getModemChar(0);
if (c == 0xff || c == EOF)
break;
if (!isSSLFax && useV34 && c == DLE) {
c = getModemChar(0);
switch (c) {
case EOT:
protoTrace("EOT received (end of transmission)");
gotEOT = true;
recvdDCN = true;
return (false);
case 0x69:
protoTrace("Control channel retrain");
// wait for the control channel to reappear
// should we reset the timeout setting?
waitForDCEChannel(true);
gotRTNC = true;
return (false);
default:
// unexpected <DLE><command>, deem as garbage
garbage.append(DLE);
break;
}
}
garbage.append(c);
if ( garbage.length() >= 2 && garbage.tail(2) == "\r\n") {
/*
* CR+LF received before address field.
* We expect result code (though it's possible
* that CR+LF is a part of garbage frame)
*/
garbage = garbage.head(garbage.length() - 2);
break;
}
}
if (getHDLCTracing() && garbage.length()) {
fxStr buf;
u_int j = 0;
for (u_int i = 0; i < garbage.length(); i++) {
if (j > 0)
buf.append(' ');
buf.append(fxStr(garbage[i] & 0xFF, "%2.2X"));
j++;
if (j > 19) {
protoTrace("--> [%u:%.*s]",
j, buf.length(), (const char*) buf);
buf = "";
j = 0;
}
}
if (j)
protoTrace("--> [%u:%.*s]",
j, buf.length(), (const char*) buf);
}
if (c == 0xff) { // address field received
do {
if (c == DLE) {
c = getModemChar(0);
if (c == ETX || c == EOF)
break;
if (!isSSLFax && useV34) {
/*
* T.31-A1 Table B.1
* These indicate transparancy, shielding, or delimiting.
*/
if (c == 0x07) { // end of HDLC frame w/FCS error
break;
}
switch (c) {
case EOT:
protoTrace("EOT received (end of transmission)");
gotEOT = true;
recvdDCN = true;
return (false);
case DLE: // <DLE><DLE> => <DLE>
break;
case SUB: // <DLE><SUB> => <DLE><DLE>
frame.put(frameRev[DLE]);
break;
case 0x51: // <DLE><0x51> => <DC1>
c = DC1;
break;
case 0x53: // <DLE><0x53> => <DC3>
c = 0x13;
break;
}
} else {
/*
* Some modems may not double-up the in-data DLEs like they should.
*/
if (conf.class1ModemHasDLEBug) frame.put(frameRev[DLE]);
else if (c != DLE) {
protoTrace("Odd. Modem reported meaningless <DLE><0x%X>. Possible DLE bug indication.", c);
}
}
}
frame.put(frameRev[c]);
} while ((c = getModemChar(0)) != EOF);
}
stopTimeout("receiving HDLC frame data");
if (wasSSLFax) setTimeout(true);
if (frame.getLength() > 0)
traceHDLCFrame("-->", frame);
if (wasTimeout()) {
abortReceive();
return (false);
}
/*
* Now collect the "OK", "ERROR", or "FCERROR"
* response telling whether or not the FCS was
* legitimate.
*/
if (!isSSLFax && !useV34 && !waitFor(AT_OK)) {
if (lastResponse == AT_ERROR)
protoTrace("FCS error");
return (false);
}
if (!isSSLFax && useV34 && c == 0x07) {
protoTrace("FCS error");
return (false);
}
if (frame.getFrameDataLength() < 1) {
protoTrace("HDLC frame too short (%u bytes)", frame.getLength());
return (false);
}
if ((frame[1]&0xf7) != 0xc0) {
protoTrace("HDLC frame with bad control field %#x", frame[1]);
return (false);
}
if ((isSSLFax || conf.class1ValidateV21Frames) && !frame.checkCRC()) {
protoTrace("FCS error (calculated)");
return (false);
}
frameRcvd = "";
for (u_int i = 0; i < frame.getLength(); i++) frameRcvd.append(frame[i]);
frame.setOK(true);
return (true);
}
bool
Class1Modem::syncECMFrame()
{
/*
* We explicitly look for the first sync flag so as to
* not get confused by any initial garbage or training.
*/
int bit = 0;
u_short ones = 0;
// look for the first sync flag
time_t start = Sys::now();
startTimeout(60000); // despite indications by T.4 A.3.1
do {
if ((unsigned) Sys::now()-start >= 60) {
protoTrace("Timeout awaiting synchronization sequence");
setTimeout(true);
return (false);
}
bit = getModemBit(0);
} while (bit != EOF && bit != 0 && !didBlockEnd());
if (bit != EOF && !didBlockEnd()) {
do {
if ((unsigned) Sys::now()-start >= 60) {
protoTrace("Timeout awaiting synchronization sequence");
setTimeout(true);
return (false);
}
if (bit == 0 || ones > 0xFF) ones = 0;
bit = getModemBit(0);
if (bit == EOF) break;
if (bit == 1) ones++;
} while (!(ones == 6 && bit == 0) && !didBlockEnd());
}
stopTimeout("awaiting synchronization sequence");
if (bit == EOF || didBlockEnd()) setTimeout(true);
if (wasTimeout()) {
return (false);
}
return (true);
}
/*
* Receive an HDLC frame with ECM. We must always be cautious
* of "stuffed" zero-bits after five sequential one-bits between
* flag sequences. We assume this is called only after a
* successfuly received complete flag sequence.
*
* Things are significantly more simple with V.34-fax ECM since
* there is no synchronization or RCP frames. In this case we
* simply have to handle byte transparancy and shielding, looking
* for byte-aligned frame delimiters.
*/
bool
Class1Modem::recvECMFrame(HDLCFrame& frame)
{
if (!isSSLFax && useV34) {
int c;
for (;;) {
c = getModemChar(60000);
if (wasTimeout()) {
return (false);
}
if (c == DLE) {
c = getModemChar(60000);
if (wasTimeout()) {
return (false);
}
switch (c) {
case DLE:
break;
case SUB:
frame.put(frameRev[DLE]);
break;
case 0x51:
c = 0x11;
break;
case 0x53:
c = 0x13;
break;
case ETX:
if (frame.getLength() > 0)
traceHDLCFrame("-->", frame, true);
if (frame.getLength() < 5) { // RCP frame size
protoTrace("HDLC frame too short (%u bytes)", frame.getLength());
return (false);
}
if (frame[0] != 0xff) {
protoTrace("HDLC frame with bad address field %#x", frame[0]);
return (false);
}
if ((frame[1]&0xf7) != 0xc0) {
protoTrace("HDLC frame with bad control field %#x", frame[1]);
return (false);
}
return (true);
case 0x07:
protoTrace("FCS error");
return (false);
case 0x04:
protoTrace("EOT received (end of transmission)");
gotEOT = true;
recvdDCN = true;
return (false);
case 0x6D:
protoTrace("Control channel selected");
gotCTRL = true;
return (false);
default:
protoTrace("got <DLE><%X>", c);
break;
}
}
frame.put(frameRev[c]);
}
}
int bit = getModemBit(60000);
u_short ones = 0;
// look for the last sync flag (possibly the previous one)
// some senders use this as the time to do framing so we must wait longer than T.4 A.3.1 implies
time_t start = Sys::now();
while (bit != 1 && bit != EOF && !didBlockEnd()) { // flag begins with zero, address begins with one
do {
if ((unsigned) Sys::now()-start >= 300) { // 5 minutes of synchronization is too much
protoTrace("Timeout waiting for the last synchronization flag");
return false;
}
if (bit == 0 || ones > 6) ones = 0;
bit = getModemBit(60000);
if (bit == 1) ones++;
} while (!(ones == 6 && bit == 0 && bit != EOF) && !didBlockEnd());
ones = 0;
bit = getModemBit(60000);
}
// receive the frame, strip stuffed zero-bits, and look for end flag
ones = 1;
u_short bitpos = 7;
u_int byte = (bit << bitpos);
bool rcpframe = false;
start = Sys::now();
do {
if ((unsigned) Sys::now()-start >= 3) {
protoTrace("Timeout receiving HDLC frame");
return (false);
}
bit = getModemBit(60000);
if (bit == 1) {
ones++;
}
if (!(ones == 5 && bit == 0 && bit != EOF)) { // not transparent stuffed zero-bits
bitpos--;
byte |= (bit << bitpos);
if (bitpos == 0) { // fully populated byte
frame.put(byte);
bitpos = 8;
byte = 0;
}
}
if (bit == 0) ones = 0;
// don't wait for the terminating flag on an RCP frame
if (frame[0] == 0xff && frame[1] == 0xc0 && frame[2] == 0x61 && frame.getLength() == 5 && frame.checkCRC()) {
protoTrace("RECV received RCP frame");
rcpframe = true;
} else if (didBlockEnd()) {
// sometimes RCP frames are truncated by or are missing due to premature DLE+ETX characters, sadly
protoTrace("RECV assumed RCP frame with block end");
// force-feed a valid RCP frame with FCS
frame.reset();
frame.put(0xff); frame.put(0xc0); frame.put(0x61); frame.put(0x96); frame.put(0xd3);
rcpframe = true;
}
} while (ones != 6 && bit != EOF && !rcpframe && frame.getLength() < frameSize+6);
if (ones == 6) bit = getModemBit(60000); // trailing bit on flag
if (!rcpframe && frame.getLength() < frameSize+6) {
/*
* The HDLC frame was terminated early by a flag. T.30 A.3.5 states that
* frame size cannot change during one page, and T.4 A.3.6.2 seems to provide
* for padding in order to get that last frame on a block to always line up
* on a byte and frame boundary. However, the NOTE 2 there seemse to give
* leniency to that requirement, and in fact many senders will send short
* frames on the last frame of a block. So we run a couple of additional
* checks here (in addition to FCS checking) to limit the remote chance
* of FCS actually checking out on corrupt data (although that may be very
* remote indeed). We don't do these "trailing flag" tests on normal-sized
* frames because we deliberately don't look for a trailing flag when we
* get enough data.
*/
if (bit) { // should have been zero
protoTrace("Bad HDLC terminating flag received.");
return (false);
}
if (byte != 0x7e) { // trailing byte should be flag
protoTrace("HDLC frame not byte-oriented. Trailing byte: %#x", byte);
return (false);
}
}
traceHDLCFrame("-->", frame, true);
if (bit == EOF) {
protoTrace("EOF received.");
return (false);
}
if (frame.getLength() < 5) { // RCP frame size
protoTrace("HDLC frame too short (%u bytes)", frame.getLength());
return (false);
}
if (frame[0] != 0xff) {
protoTrace("HDLC frame with bad address field %#x", frame[0]);
return (false);
}
if ((frame[1]&0xf7) != 0xc0) {
protoTrace("HDLC frame with bad control field %#x", frame[1]);
return (false);
}
return (true);
}
bool
Class1Modem::endECMBlock()
{
if (didBlockEnd()) return (true); // some erroniously re-use bytes
int c = getLastByte(); // some erroniously re-use bits
time_t start = Sys::now();
setTimeout(false);
do {
if ((unsigned) Sys::now()-start >= 60) { // 60 seconds of garbage after RCP is too much
protoTrace("Timeout waiting for DLE+ETX");
setTimeout(true);
return false;
}
if (c == DLE) {
c = getModemChar(30*1000);
if (c == ETX || c == EOF)
break;
}
} while ((c = getModemChar(30*1000)) != EOF);
if (c == EOF) return (false);
else return (true);
}
#include "StackBuffer.h"
/*
* Log an HLDC frame along with a time stamp (secs.10ms).
*/
void
Class1Modem::traceHDLCFrame(const char* direction, const HDLCFrame& frame, bool isecm)
{
if (!isecm) {
if (!getHDLCTracing()) return;
} else {
if (!getECMTracing()) return;
}
const char* hexdigits = "0123456789ABCDEF";
fxStackBuffer buf;
for (u_int i = 0; i < frame.getLength(); i++) {
u_char b = frame[i];
if (i > 0)
buf.put(' ');
buf.put(hexdigits[b>>4]);
buf.put(hexdigits[b&0xf]);
}
protoTrace("%s HDLC<%u:%.*s>", direction,
frame.getLength(), buf.getLength(), (const char*) buf);
}
/*
* Send a raw HDLC frame and wait for the modem response.
* The modem is expected to be an HDLC frame sending mode
* (i.e. +FTH=3 or similar has already be sent to the modem).
* The T.30 max frame length is enforced with a 3 second
* timeout on the send.
*/
bool
Class1Modem::sendRawFrame(HDLCFrame& frame)
{
if (isSSLFax) {
// We must generate FCS for SSL Fax; the modem firmware does it for us using modems.
int fcs1 = (frame.getCRC() >> 8) & 0xff; // 1st byte FCS
int fcs2 = frame.getCRC() & 0xff; // 2nd byte FCS
frame.put(fcs1); frame.put(fcs2);
}
traceHDLCFrame("<--", frame);
if (frame.getLength() < 3) {
protoTrace("HDLC frame too short (%u bytes)", frame.getLength());
return (false);
}
if (frame[0] != 0xff) {
protoTrace("HDLC frame with bad address field %#x", frame[0]);
return (false);
}
if ((frame[1]&0xf7) != 0xc0) {
protoTrace("HDLC frame with bad control field %#x", frame[1]);
return (false);
}
signalSent = "";
for (u_int i = 0; i < frame.getLength(); i++) signalSent.append(frame[i]);
/*
* sendFrame() is always called with a timeout set.
* Let's keep it that way
*/
return (sendClass1Data(frame, frame.getLength(), frameRev, true, 0) &&
((useV34 || isSSLFax) ? true : waitFor(frame.moreFrames() ? AT_CONNECT : AT_OK, 0)));
}
/*
* Send a single byte frame.
*/
bool
Class1Modem::sendFrame(u_char fcf, bool lastFrame)
{
HDLCFrame frame(conf.class1FrameOverhead);
frame.put(0xff);
frame.put(lastFrame ? 0xc8 : 0xc0);
frame.put(fcf);
return (sendRawFrame(frame));
}
/*
* Send a frame with DCS/DIS.
*/
bool
Class1Modem::sendFrame(u_char fcf, FaxParams& dcs_caps, bool lastFrame)
{
HDLCFrame frame(conf.class1FrameOverhead);
frame.put(0xff);
frame.put(lastFrame ? 0xc8 : 0xc0);
frame.put(fcf);
int curByte = 0;
//add dcs bytes an any optional bytes
frame.put(dcs_caps.getByte(curByte));
while (dcs_caps.hasNextByte(curByte)) {
curByte += 1;
frame.put(dcs_caps.getByte(curByte));
}
return (sendRawFrame(frame));
}
/*
* Send a frame with TSI/CSI/PWD/SUB/SEP/PPR.
*/
bool
Class1Modem::sendFrame(u_char fcf, const fxStr& tsi, bool lastFrame)
{
HDLCFrame frame(conf.class1FrameOverhead);
frame.put(0xff);
frame.put(lastFrame ? 0xc8 : 0xc0);
frame.put(fcf);
frame.put((const u_char*)(const char*)tsi, tsi.length());
return (sendRawFrame(frame));
}
/*
* Send a frame with NSF.
*/
bool
Class1Modem::sendFrame(u_char fcf, const u_char* code, const u_char* features, const fxStr& nsf, bool lastFrame)
{
HDLCFrame frame(conf.class1FrameOverhead);
frame.put(0xff);
frame.put(lastFrame ? 0xc8 : 0xc0);
frame.put(fcf);
frame.put(code, 3); // should be in LSBMSB already
frame.put(features, 1);
frame.put((const u_char*)(const char*)nsf, nsf.length());
return (sendRawFrame(frame));
}
bool
Class1Modem::transmitFrame(fxStr& signal)
{
HDLCFrame frame(conf.class1FrameOverhead);
for (u_int i = 0; i < signal.length(); i++) frame.put(signal[i]);
startTimeout(7550);
bool frameSent = (useV34 || isSSLFax) ? true : atCmd(thCmd, AT_NOTHING, 0);
if (frameSent) frameSent = (useV34 || isSSLFax) ? true : atResponse(rbuf, 0) == AT_CONNECT;
if (frameSent) frameSent = sendRawFrame(frame);
else if (lastResponse == AT_ERROR) gotEOT = true; // on hook
stopTimeout("sending HDLC frame");
return (frameSent);
}
bool
Class1Modem::transmitFrame(u_char fcf, bool lastFrame)
{
startTimeout(7550);
bool frameSent = (useV34 || isSSLFax) ? true : atCmd(thCmd, AT_NOTHING, 0);
if (frameSent) frameSent = (useV34 || isSSLFax) ? true : atResponse(rbuf, 0) == AT_CONNECT;
if (frameSent) frameSent = sendFrame(fcf, lastFrame);
else if (lastResponse == AT_ERROR) gotEOT = true; // on hook
stopTimeout("sending HDLC frame");
return (frameSent);
}
bool
Class1Modem::transmitFrame(u_char fcf, FaxParams& dcs_caps, bool lastFrame)
{
/*
* The T.30 spec says no frame can take more than 3 seconds
* (+/- 15%) to transmit. But the DCE can take as much as 5
* seconds to respond CONNECT or result OK, per T.31.
*/
startTimeout(7550);
bool frameSent = (useV34 || isSSLFax) ? true : atCmd(thCmd, AT_NOTHING, 0);
if (frameSent) frameSent = (useV34 || isSSLFax) ? true : atResponse(rbuf, 0) == AT_CONNECT;
if (frameSent) frameSent = sendFrame(fcf, dcs_caps, lastFrame);
else if (lastResponse == AT_ERROR) gotEOT = true; // on hook
stopTimeout("sending HDLC frame");
return (frameSent);
}
bool
Class1Modem::transmitFrame(u_char fcf, const fxStr& tsi, bool lastFrame)
{
startTimeout(7550);
bool frameSent = (useV34 || isSSLFax) ? true : atCmd(thCmd, AT_NOTHING, 0);
if (frameSent) frameSent = (useV34 || isSSLFax) ? true : atResponse(rbuf, 0) == AT_CONNECT;
if (frameSent) frameSent = sendFrame(fcf, tsi, lastFrame);
else if (lastResponse == AT_ERROR) gotEOT = true; // on hook
stopTimeout("sending HDLC frame");
return (frameSent);
}
bool
Class1Modem::transmitFrame(u_char fcf, const u_char* code, const u_char* features, const fxStr& nsf, bool lastFrame)
{
startTimeout(7550);
bool frameSent = (useV34 || isSSLFax) ? true : atCmd(thCmd, AT_NOTHING, 0);
if (frameSent) frameSent = (useV34 || isSSLFax) ? true : atResponse(rbuf, 0) == AT_CONNECT;
if (frameSent) frameSent = sendFrame(fcf, code, features, nsf, lastFrame);
else if (lastResponse == AT_ERROR) gotEOT = true; // on hook
stopTimeout("sending HDLC frame");
return (frameSent);
}
/*
* Send data using the specified signalling rate.
*/
bool
Class1Modem::transmitData(int br, u_char* data, u_int cc,
const u_char* bitrev, bool eod)
{
if (flowControl == FLOW_XONXOFF)
setXONXOFF(FLOW_XONXOFF, FLOW_NONE, ACT_FLUSH);
fxStr tmCmd(br, tmCmdFmt);
bool ok = atCmd(tmCmd, AT_CONNECT);
if (ok) {
// T.31 8.3.3 requires the DCE to report CONNECT at the beginning
// of transmission of the training pattern rather than at the end.
// We pause here to allow the remote's +FRM to result in CONNECT.
// This delay will vary depending on the modem's adherence to T.31.
pause(conf.class1TMConnectDelay);
ok = sendClass1Data(data, cc, bitrev, eod, getDataTimeout());
if (ok && eod) {
ok = false;
u_short attempts = 0;
lastResponse = AT_NOTHING;
while (!isSSLFax && !ok && lastResponse != AT_NOCARRIER && attempts++ < 3) {
ok = waitFor(AT_OK, 60*1000); // wait up to 60 seconds for "OK"
}
}
} else if (lastResponse == AT_ERROR) gotEOT = true; // on hook
if (flowControl == FLOW_XONXOFF)
setXONXOFF(FLOW_NONE, FLOW_NONE, ACT_DRAIN);
return (ok);
}
/*
* Receive an HDLC frame. The timeout is against
* the receipt of the HDLC flags; the frame itself must
* be received within 3 seconds (per the spec).
* If a carrier is received, but the complete frame
* is not received before the timeout, the receive
* is aborted.
*
* If the frame is received in error, then in instances
* where the other end is likely to be able to receive
* it, we can transmit CRP to get the other end to
* retransmit the frame.
*/
bool
Class1Modem::recvFrame(HDLCFrame& frame, u_char dir, long ms, bool readPending, bool docrp, bool usehooksensitivity)
{
bool gotframe;
u_short crpcnt = 0, rhcnt = 0;
u_int onhooks = 0;
gotCONNECT = true;
time_t start = Sys::now();
if (isSSLFax || useV34) {
do {
if (crpcnt) traceFCF(dir == FCF_SNDR ? "SEND send" : "RECV send", FCF_CRP);
frame.reset();
gotframe = recvRawFrame(frame);
} while (!gotframe && !gotRTNC && !gotEOT && docrp && crpcnt++ < 3 && !wasTimeout() && frame.getLength() && transmitFrame(dir|FCF_CRP));
return (gotframe);
}
startTimeout(ms);
if (!readPending) {
/*
* Hopefully the modem is smart enough to *not* do +FCERROR after +FRH=3,
* as it is only a stumbling-block for us and cannot be beneficial. But,
* in case it adheres blindly to the spec, we'll repeat ourselves here
* until we timeout or we do get the V.21 carrier. We do slow the looping
* with a pause to prevent unwanted massive amounts of tracing. The pause
* needs to be short enough, though, that the modem will still pick up
* any V.21 signalling if it misses that much of the startup.
*
* T.31 8.3.6 states that the NO CARRIER result to AT+FRH=3 indicates
* carrier loss. Getting this result without first getting a CONNECT
* response (indicating carrier detection) seems a bit undefined. However,
* sample sessions T.31 I.1 and I.2 seem to give its use as a means to
* deliberately detect carrier loss since the OK result to AT+FRH=3 does
* not necessarily indicate carrier loss (even on final frames - although
* smart modem developers would make it thus). Thus could serve a purpose
* similar to AT+FRS=1 as we haved used in Class1TCFRecvHackCmd (which is
* generally a bad idea). In any case, if we're trying to detect a V.21
* HDLC frame and we get a NO CARRIER result immediately following AT+FRH=3
* it probably means that the previous carrier was still up, that we just
* saw its loss, and so we just need to re-issue AT+FRH=3. See more below...
*/
do {
readPending = atCmd(rhCmd, AT_NOTHING, 0) && waitFor(AT_CONNECT, 0);
if (lastResponse == AT_FCERROR) pause(200);
if (lastResponse == AT_ERROR && !wasTimeout() && ++onhooks <= conf.class1HookSensitivity) {
if (!usehooksensitivity) {
/*
* Class1HookSensitivity is used by the calling function, not us.
*/
break;
} else {
stopTimeout("");
startTimeout(ms);
}
}
} while (((u_int) Sys::now()-start < conf.t1Timer) && !wasTimeout() &&
(lastResponse == AT_FCERROR || lastResponse == AT_NOCARRIER || (lastResponse == AT_ERROR && onhooks <= conf.class1HookSensitivity)));
}
if (readPending) {
stopTimeout("waiting for HDLC flags");
if (wasTimeout()){
abortReceive();
return (false);
}
fxStr emsg;
do {
if (crpcnt || rhcnt) {
if (rhcnt) crpcnt = 0;
if (crpcnt) {
rhcnt = 0;
traceFCF(dir == FCF_SNDR ? "SEND send" : "RECV send", FCF_CRP);
}
do {
lastResponse = AT_NOTHING;
startTimeout(ms);
if (!(atCmd(rhCmd, AT_NOTHING, 0) && waitFor(AT_CONNECT,0))) {
stopTimeout("waiting for v.21 carrier");
if (wasTimeout()) {
abortReceive();
setTimeout(false);
}
if (lastResponse != AT_NOCARRIER || rhcnt++ > 30) return (false);
}
stopTimeout("waiting for v.21 carrier");
/*
* The meaning of a direct NO CARRIER response/result to the AT+FRH=3
* command can be interpreted two ways due to wording in ITU T.31.
* The more traditional interpretation is that it is out-of-spec: that
* a NO CARRIER response should only come after a CONNECT message.
* However, T.31 gives sample sessions that illustrate precisely this
* kind of out-of-spec sequence:
*
* <-- AT+FRH=3
* --> NO CARRIER
*
* And the interpretation is clear to indicate that in this case the
* modem detected a carrier, but it apparently was not V.21 HDLC, and
* the NO CARRIER response indicates that the indeterminate carrier
* has dropped. This functionality is more cumbersome than it is
* helpful (its value is not much different than that of an AT+FRS=1
* command), and what it really means is that we just need to re-issue
* the AT+FRH=3 command until we get something useful as this scenario
* will most likely occur on incidence of Phase C premature carrier loss.
*/
} while (lastResponse == AT_NOCARRIER);
}
frame.reset();
gotframe = recvRawFrame(frame);
/*
* Some modems aren't very particular about reporting CONNECT after AT+FRH=3.
* So, for such modems CONNECT may come with V.17 modulated audio or any noise
* whatsoever. Those modems tend to report NO CARRIER after CONNECT, perhaps
* after <DLE><ETX> or some other garbage possibly. NO CARRIER is an invalid
* modem response at that point, anyway. So it is a good indicator for us.
* So we simply repeat AT+FRH=3 in that case.
*/
} while (((u_int) Sys::now()-start < howmany(conf.t1Timer, 1000)) && !gotframe && !wasTimeout() &&
((conf.class1HasRHConnectBug && !frame.getLength() && lastResponse == AT_NOCARRIER && rhcnt++ < 30) ||
(docrp && crpcnt++ < 3 && switchingPause(emsg, 3) && transmitFrame(dir|FCF_CRP)))); /* triple switchingPause to avoid sending CRP during TCF */
return (gotframe);
} else {
gotCONNECT = false;
if (lastResponse == AT_ERROR) gotEOT = true; // on hook
}
stopTimeout("waiting for v.21 carrier");
if (wasTimeout()) {
abortReceive();
setTimeout(false);
}
return (false);
}
/*
* Receive TCF data using the specified signalling rate.
*/
bool
Class1Modem::recvTCF(int br, HDLCFrame& buf, const u_char* bitrev, long ms)
{
buf.reset();
if (flowControl == FLOW_XONXOFF)
setXONXOFF(FLOW_NONE, FLOW_XONXOFF, ACT_DRAIN);
/*
* Loop waiting for carrier or timeout.
*/
bool readPending, gotCarrier;
fxStr rmCmd(br, rmCmdFmt);
startTimeout(ms);
u_short attempts = 0;
do {
readPending = atCmd(rmCmd, AT_NOTHING, 0);
gotCarrier = readPending && waitFor(AT_CONNECT, 0);
} while (readPending && !gotCarrier && lastResponse == AT_FCERROR && ++attempts < conf.class1RMPersistence);
/*
* If carrier was recognized, collect the data.
*/
bool gotData = false;
if (gotCarrier) {
int c = getModemChar(0); // NB: timeout is to first byte
stopTimeout("receiving TCF");
if (c != EOF) {
buf.reset();
/*
* Use a timer to receive the 1.5
* second TCF--perhaps if it is too long it
* won't permit us to send the nak in time?
*
* The initial timer needs to be longer than 1.5 seconds
* to support senders that may not start the zeros
* until a second or two after CONNECT. This is
* also why we restart our timeout after the zeros
* start.
*/
bool zerosstarted = false;
startTimeout(ms);
do {
if (c == 0x00 && !zerosstarted) {
zerosstarted = true;
startTimeout(ms);
}
if (c == DLE) {
c = getModemChar(0);
if (c == ETX) {
gotData = true;
break;
}
if (c == EOF) {
break;
}
}
buf.put(bitrev[c]);
if (buf.getLength() > 10000) {
setTimeout(true);
break;
}
} while ((c = getModemChar(0)) != EOF);
}
}
stopTimeout("receiving TCF");
/*
* If the +FRM is still pending, abort it.
*/
if (readPending && wasTimeout())
abortReceive();
if (flowControl == FLOW_XONXOFF)
setXONXOFF(FLOW_NONE, FLOW_NONE, ACT_DRAIN);
return (gotData);
}
/*
* Modem manipulation support.
*/
/*
* Reset a Class 1 modem.
*/
bool
Class1Modem::reset(long ms)
{
return (FaxModem::reset(ms) && setupClass1Parameters());
}
ATResponse
Class1Modem::atResponse(char* buf, long ms)
{
if (FaxModem::atResponse(buf, ms) == AT_OTHER && strneq(buf, "+FCERROR", 8))
lastResponse = AT_FCERROR;
if (lastResponse == AT_OTHER && strneq(buf, "+FRH:3", 6))
lastResponse = AT_FRH3;
if (lastResponse == AT_OTHER && strneq(buf, "+F34:", 5)) {
/*
* V.8 handshaking was successful. The rest of the
* session is governed by T.31 Amendment 1 Annex B.
* (This should only happen after ATA or ATD.)
*
* The +F34: response is interpreted according to T.31-A1 B.6.2.
*/
buf += 5; // skip "+F34:" prefix
primaryV34Rate = 0;
while (!isdigit(buf[0])) buf++; // move to digits
do {
primaryV34Rate = primaryV34Rate*10 + (buf[0] - '0');
} while (isdigit((++buf)[0]));
controlV34Rate = 0;
while (!isdigit(buf[0])) buf++; // move to digits
do {
controlV34Rate = controlV34Rate*10 + (buf[0] - '0');
} while (isdigit((++buf)[0]));
useV34 = true;
protoTrace("V.8 handshaking succeeded, V.34-Fax (SuperG3) capability enabled.");
protoTrace("Primary channel rate: %u bit/s, Control channel rate: %u bit/s.", primaryV34Rate*2400, controlV34Rate*1200);
modemParams.br |= BIT(primaryV34Rate) - 1;
}
return (lastResponse);
}
/*
* Wait (carefully) for some response from the modem.
*/
bool
Class1Modem::waitFor(ATResponse wanted, long ms)
{
for (;;) {
ATResponse response = atResponse(rbuf, ms);
if (response == wanted)
return (true);
switch (response) {
case AT_TIMEOUT:
case AT_EMPTYLINE:
case AT_ERROR:
case AT_NOCARRIER:
case AT_NODIALTONE:
case AT_NOANSWER:
case AT_OFFHOOK:
case AT_RING:
modemTrace("MODEM %s", ATresponses[response]);
/* fall thru... */
case AT_OTHER:
case AT_FCERROR:
case AT_FRH3:
case AT_OK:
case AT_CONNECT:
return (false);
}
}
}
/*
* Send queryCmd and get a range response.
*/
bool
Class1Modem::class1Query(const fxStr& queryCmd, Class1Cap caps[])
{
char response[1024];
if (queryCmd[0] == '!') {
return (parseQuery(queryCmd.tail(queryCmd.length()-1), caps));
}
if (atCmd(queryCmd, AT_NOTHING) && atResponse(response) == AT_OTHER) {
sync(5000);
return (parseQuery(response, caps));
}
return (false);
}
/*
* Map the DCS signalling rate to the appropriate
* Class 1 capability entry.
*/
const Class1Cap*
Class1Modem::findSRCapability(u_short sr, const Class1Cap caps[])
{
for (u_int i = NCAPS-1; i > 0; i--) {
const Class1Cap* cap = &caps[i];
if (cap->sr == sr) {
if (cap->mod == V17 && HasShortTraining(cap-1))
cap--;
return (cap);
}
}
// XXX should not happen...
protoTrace("MODEM: unknown signalling rate %#x, using 9600 v.29", sr);
return findSRCapability(DCSSIGRATE_9600V29, caps);
}
/*
* Map the Class 2 bit rate to the best
* signalling rate capability of the modem.
*/
const Class1Cap*
Class1Modem::findBRCapability(u_short br, const Class1Cap caps[])
{
for (u_int i = NCAPS-1; i > 0; i--) {
const Class1Cap* cap = &caps[i];
if (cap->br == br && cap->ok) {
if (cap->mod == V17 && HasShortTraining(cap-1))
cap--;
return (cap);
}
}
protoTrace("MODEM: unsupported baud rate %#x", br);
return NULL;
}
/*
* Build upon the result from Class2Params.
*/
FaxParams
Class1Modem::modemDIS() const
{
FaxParams dis_caps = FaxModem::modemDIS();
// signalling rates
for (u_short i = 0; i < 4; i++) dis_caps.setBit(11+i, (discap & (0x08>>i)));
if (useV34) dis_caps.setBit(FaxParams::BITNUM_V8_CAPABLE, true);
// internet fax (support for CIA, CSA, and TSA frames)
if (conf.class1SSLFaxSupport) {
dis_caps.setBit(FaxParams::BITNUM_T37, true);
dis_caps.setBit(FaxParams::BITNUM_T38, true);
}
// preferred ECM frame size
if (conf.class1ECMFrameSize == 64) dis_caps.setBit(FaxParams::BITNUM_FRAMESIZE_DIS, true);
// we set both units preferences to allow the sender to choose
dis_caps.setBit(FaxParams::BITNUM_METRIC_RES, true);
dis_caps.setBit(FaxParams::BITNUM_INCH_RES, true);
// we indicate both letter and legal page size support
dis_caps.setBit(FaxParams::BITNUM_LETTER_SIZE, true);
dis_caps.setBit(FaxParams::BITNUM_LEGAL_SIZE, true);
// selective polling, subaddressing, password
dis_caps.setBit(FaxParams::BITNUM_SEP, true);
dis_caps.setBit(FaxParams::BITNUM_SUB, true);
dis_caps.setBit(FaxParams::BITNUM_PWD, true);
if (conf.class1ECMSupport) {
// JBIG
if (jbigSupported) {
dis_caps.setBit(FaxParams::BITNUM_JBIG_BASIC, true);
dis_caps.setBit(FaxParams::BITNUM_JBIG_L0, true); // JBIG library can handle L0 = 1-Yd
}
/* - disabled for now
// JBIG grey/color requires JPEG grey/color
if (conf.class1GreyJBIGSupport || conf.class1ColorJBIGSupport) {
dis_caps.setBit(FaxParams::BITNUM_JPEG, true);
dis_caps.setBit(FaxParams::BITNUM_JBIG, true);
}
if (conf.class1ColorJBIGSupport)
dis_caps.setBit(FaxParams::BITNUM_FULLCOLOR, true);
*/
// JPEG
if (conf.class1GreyJPEGSupport || conf.class1ColorJPEGSupport)
dis_caps.setBit(FaxParams::BITNUM_JPEG, true);
if (conf.class1ColorJPEGSupport)
dis_caps.setBit(FaxParams::BITNUM_FULLCOLOR, true);
}
return dis_caps;
}
const char COMMA = ',';
const char SPACE = ' ';
/*
* Parse a Class 1 parameter string.
*/
bool
Class1Modem::parseQuery(const char* cp, Class1Cap caps[])
{
bool bracket = false, first = true;
while (cp[0]) {
if (cp[0] == SPACE) { // ignore white space
cp++;
continue;
}
/* by a.pogoda@web.de, jan 21st 2002
* workaround for modems sending (<item>,<item>,...), i.e.
* enclosed in brackets rather than just <item>,<item>,...
* e.g. elsa microlink 56k internet II and maybo others
*/
if (cp[0]=='(' && first && !bracket) {
/* check whether the first non-space char is an
* opening bracket and skip it if true
*/
bracket = true;
cp++;
continue;
}
else if (cp[0]==')' && !first && bracket) {
/* if an opening bracket was scanned before and
* the current char is a closing one, skip it
*/
bracket = false;
cp++;
continue;
}
else if (!isdigit(cp[0]))
return (false);
/* state that we already scanned past the first char */
first = false;
int v = 0;
do {
v = v*10 + (cp[0] - '0');
} while (isdigit((++cp)[0]));
int r = v;
if (cp[0] == '-') { // <low>-<high>
cp++;
if (!isdigit(cp[0])) {
return (false);
}
r = 0;
do {
r = r*10 + (cp[0] - '0');
} while (isdigit((++cp)[0]));
}
for (u_int i = 0; i < NCAPS; i++)
if (caps[i].value >= v && caps[i].value <= r) {
caps[i].ok = true;
break;
}
if (cp[0] == COMMA) // <item>,<item>...
cp++;
}
return (true);
}
|
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Southwest Research Institute
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Southwest Research Institute, nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "industrial_robot_client/robot_status_relay_handler.h"
#include "industrial_msgs/RobotStatus.h"
#include "simple_message/log_wrapper.h"
using namespace industrial::shared_types;
using namespace industrial::smpl_msg_connection;
using namespace industrial::simple_message;
using namespace industrial::robot_status;
using namespace industrial::robot_status_message;
namespace industrial_robot_client
{
namespace robot_status_relay_handler
{
bool RobotStatusRelayHandler::init(SmplMsgConnection* connection)
{
this->pub_robot_status_ = this->node_.advertise<industrial_msgs::RobotStatus>("robot_status", 1);
return init((int)StandardMsgTypes::STATUS, connection);
}
bool RobotStatusRelayHandler::internalCB(SimpleMessage& in)
{
RobotStatusMessage status_msg;
if (!status_msg.init(in))
{
LOG_ERROR("Failed to initialize status message");
return false;
}
return internalCB(status_msg);
}
bool RobotStatusRelayHandler::internalCB(RobotStatusMessage & in)
{
industrial_msgs::RobotStatus status;
bool rtn = true;
status.drives_powered.val = TriStates::toROSMsgEnum(in.status_.getDrivesPowered());
status.e_stopped.val = TriStates::toROSMsgEnum(in.status_.getEStopped());
status.error_code = in.status_.getErrorCode();
status.in_error.val = TriStates::toROSMsgEnum(in.status_.getInError());
status.in_motion.val = TriStates::toROSMsgEnum(in.status_.getInMotion());
status.mode.val = RobotModes::toROSMsgEnum(in.status_.getMode());
status.motion_possible.val = TriStates::toROSMsgEnum(in.status_.getMotionPossible());
this->pub_robot_status_.publish(status);
// Reply back to the controller if the sender requested it.
if (CommTypes::SERVICE_REQUEST == in.getMessageType())
{
SimpleMessage reply;
in.toReply(reply, rtn ? ReplyTypes::SUCCESS : ReplyTypes::FAILURE);
this->getConnection()->sendMsg(reply);
}
return rtn;
}
}
}
|
// Copyright (c) 2012 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.
// Create a service process that uses a Mock to respond to the browser in order
// to test launching the browser using the cloud print policy check command
// line switch.
#include "base/bind.h"
#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/process/kill.h"
#include "base/process/process.h"
#include "base/rand_util.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/multiprocess_test.h"
#include "base/test/test_timeouts.h"
#include "base/time/default_tick_clock.h"
#include "base/time/time.h"
#include "chrome/browser/chrome_content_browser_client.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
#include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
#include "chrome/browser/service_process/service_process_control.h"
#include "chrome/browser/ui/startup/startup_browser_creator.h"
#include "chrome/common/chrome_content_client.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/service_messages.h"
#include "chrome/common/service_process_util.h"
#include "chrome/service/service_ipc_server.h"
#include "chrome/service/service_process.h"
#include "chrome/test/base/chrome_unit_test_suite.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_io_thread_state.h"
#include "chrome/test/base/testing_pref_service_syncable.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/keyed_service/core/keyed_service.h"
#include "content/public/browser/notification_service.h"
#include "content/public/common/content_paths.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_utils.h"
#include "ipc/ipc_descriptors.h"
#include "ipc/ipc_multiprocess_test.h"
#include "ipc/ipc_switches.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"
#if defined(OS_MACOSX)
#include "chrome/common/mac/mock_launchd.h"
#endif
#if defined(OS_POSIX)
#include "base/posix/global_descriptors.h"
#endif
using ::testing::AnyNumber;
using ::testing::Assign;
using ::testing::AtLeast;
using ::testing::DoAll;
using ::testing::Invoke;
using ::testing::Mock;
using ::testing::Property;
using ::testing::Return;
using ::testing::WithoutArgs;
using ::testing::_;
using content::BrowserThread;
namespace {
enum MockServiceProcessExitCodes {
kMissingSwitch = 1,
kInitializationFailure,
kExpectationsNotMet,
kShutdownNotGood
};
#if defined(OS_MACOSX)
const char kTestExecutablePath[] = "test-executable-path";
#endif
bool g_good_shutdown = false;
void ShutdownTask() {
g_good_shutdown = true;
g_service_process->Shutdown();
}
class TestStartupClientChannelListener : public IPC::Listener {
public:
bool OnMessageReceived(const IPC::Message& message) override { return false; }
};
} // namespace
class TestServiceProcess : public ServiceProcess {
public:
TestServiceProcess() { }
~TestServiceProcess() override {}
bool Initialize(base::MessageLoopForUI* message_loop,
ServiceProcessState* state);
base::MessageLoopProxy* IOMessageLoopProxy() {
return io_thread_->message_loop_proxy().get();
}
};
bool TestServiceProcess::Initialize(base::MessageLoopForUI* message_loop,
ServiceProcessState* state) {
main_message_loop_ = message_loop;
service_process_state_.reset(state);
base::Thread::Options options(base::MessageLoop::TYPE_IO, 0);
io_thread_.reset(new base::Thread("TestServiceProcess_IO"));
return io_thread_->StartWithOptions(options);
}
// This mocks the service side IPC message handler, allowing us to have a
// minimal service process.
class MockServiceIPCServer : public ServiceIPCServer {
public:
static std::string EnabledUserId();
explicit MockServiceIPCServer(const IPC::ChannelHandle& handle)
: ServiceIPCServer(handle),
enabled_(true) { }
MOCK_METHOD1(OnMessageReceived, bool(const IPC::Message& message));
MOCK_METHOD1(OnChannelConnected, void(int32 peer_pid));
MOCK_METHOD0(OnChannelError, void());
void SetServiceEnabledExpectations();
void SetWillBeDisabledExpectations();
void CallServiceOnChannelConnected(int32 peer_pid) {
ServiceIPCServer::OnChannelConnected(peer_pid);
}
bool SendInfo();
private:
cloud_print::CloudPrintProxyInfo info_;
bool enabled_;
};
// static
std::string MockServiceIPCServer::EnabledUserId() {
return std::string("kitteh@canhazcheezburger.cat");
}
void MockServiceIPCServer::SetServiceEnabledExpectations() {
EXPECT_CALL(*this, OnChannelConnected(_)).Times(1)
.WillRepeatedly(
Invoke(this, &MockServiceIPCServer::CallServiceOnChannelConnected));
EXPECT_CALL(*this, OnChannelError()).Times(0);
EXPECT_CALL(*this, OnMessageReceived(_)).Times(0);
EXPECT_CALL(*this,
OnMessageReceived(
Property(&IPC::Message::type,
static_cast<int32>(ServiceMsg_GetCloudPrintProxyInfo::ID))))
.Times(AnyNumber()).WillRepeatedly(
WithoutArgs(Invoke(this, &MockServiceIPCServer::SendInfo)));
EXPECT_CALL(*this,
OnMessageReceived(
Property(&IPC::Message::type,
static_cast<int32>(ServiceMsg_Shutdown::ID))))
.Times(1)
.WillOnce(
DoAll(Assign(&g_good_shutdown, true),
WithoutArgs(
Invoke(g_service_process, &ServiceProcess::Shutdown)),
Return(true)));
}
void MockServiceIPCServer::SetWillBeDisabledExpectations() {
SetServiceEnabledExpectations();
EXPECT_CALL(*this,
OnMessageReceived(
Property(&IPC::Message::type,
static_cast<int32>(
ServiceMsg_DisableCloudPrintProxy::ID))))
.Times(AtLeast(1))
.WillRepeatedly(DoAll(Assign(&enabled_, false), Return(true)));
}
bool MockServiceIPCServer::SendInfo() {
if (enabled_) {
info_.enabled = true;
info_.email = EnabledUserId();
EXPECT_TRUE(Send(new ServiceHostMsg_CloudPrintProxy_Info(info_)));
} else {
info_.enabled = false;
info_.email = std::string();
EXPECT_TRUE(Send(new ServiceHostMsg_CloudPrintProxy_Info(info_)));
}
return true;
}
typedef base::Callback<void(MockServiceIPCServer* server)>
SetExpectationsCallback;
// The return value from this routine is used as the exit code for the mock
// service process. Any non-zero return value will be printed out and can help
// determine the failure.
int CloudPrintMockService_Main(SetExpectationsCallback set_expectations) {
base::MessageLoopForUI main_message_loop;
main_message_loop.set_thread_name("Main Thread");
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
content::RegisterPathProvider();
#if defined(OS_MACOSX)
if (!command_line->HasSwitch(kTestExecutablePath))
return kMissingSwitch;
base::FilePath executable_path =
command_line->GetSwitchValuePath(kTestExecutablePath);
EXPECT_FALSE(executable_path.empty());
MockLaunchd mock_launchd(executable_path, &main_message_loop, true, true);
Launchd::ScopedInstance use_mock(&mock_launchd);
#endif
base::FilePath user_data_dir =
command_line->GetSwitchValuePath(switches::kUserDataDir);
CHECK(!user_data_dir.empty());
CHECK(test_launcher_utils::OverrideUserDataDir(user_data_dir));
ServiceProcessState* state(new ServiceProcessState);
bool service_process_state_initialized = state->Initialize();
EXPECT_TRUE(service_process_state_initialized);
if (!service_process_state_initialized)
return kInitializationFailure;
TestServiceProcess service_process;
EXPECT_EQ(&service_process, g_service_process);
// Takes ownership of the pointer, but we can use it since we have the same
// lifetime.
EXPECT_TRUE(service_process.Initialize(&main_message_loop, state));
MockServiceIPCServer server(state->GetServiceProcessChannel());
// Here is where the expectations/mock responses need to be set up.
set_expectations.Run(&server);
EXPECT_TRUE(server.Init());
EXPECT_TRUE(state->SignalReady(service_process.IOMessageLoopProxy(),
base::Bind(&ShutdownTask)));
#if defined(OS_MACOSX)
mock_launchd.SignalReady();
#endif
// Connect up the parent/child IPC channel to signal that the test can
// continue.
TestStartupClientChannelListener listener;
EXPECT_TRUE(base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kProcessChannelID));
std::string startup_channel_name =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kProcessChannelID);
scoped_ptr<IPC::ChannelProxy> startup_channel;
startup_channel =
IPC::ChannelProxy::Create(startup_channel_name,
IPC::Channel::MODE_CLIENT,
&listener,
service_process.IOMessageLoopProxy());
main_message_loop.Run();
if (!Mock::VerifyAndClearExpectations(&server))
return kExpectationsNotMet;
if (!g_good_shutdown)
return kShutdownNotGood;
return 0;
}
void SetServiceEnabledExpectations(MockServiceIPCServer* server) {
server->SetServiceEnabledExpectations();
}
MULTIPROCESS_IPC_TEST_MAIN(CloudPrintMockService_StartEnabledWaitForQuit) {
return CloudPrintMockService_Main(
base::Bind(&SetServiceEnabledExpectations));
}
void SetServiceWillBeDisabledExpectations(MockServiceIPCServer* server) {
server->SetWillBeDisabledExpectations();
}
MULTIPROCESS_IPC_TEST_MAIN(CloudPrintMockService_StartEnabledExpectDisabled) {
return CloudPrintMockService_Main(
base::Bind(&SetServiceWillBeDisabledExpectations));
}
class CloudPrintProxyPolicyStartupTest : public base::MultiProcessTest,
public IPC::Listener {
public:
CloudPrintProxyPolicyStartupTest();
~CloudPrintProxyPolicyStartupTest() override;
void SetUp() override;
void TearDown() override;
scoped_refptr<base::MessageLoopProxy> IOMessageLoopProxy() {
return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
}
base::Process Launch(const std::string& name);
void WaitForConnect();
bool Send(IPC::Message* message);
void ShutdownAndWaitForExitWithTimeout(base::Process process);
// IPC::Listener implementation
bool OnMessageReceived(const IPC::Message& message) override { return false; }
void OnChannelConnected(int32 peer_pid) override;
// MultiProcessTest implementation.
base::CommandLine MakeCmdLine(const std::string& procname) override;
bool LaunchBrowser(const base::CommandLine& command_line, Profile* profile) {
StartupBrowserCreator browser_creator;
return StartupBrowserCreator::ProcessCmdLineImpl(
command_line, base::FilePath(), false, profile,
StartupBrowserCreator::Profiles(), &browser_creator);
}
protected:
content::TestBrowserThreadBundle thread_bundle_;
base::ScopedTempDir temp_user_data_dir_;
std::string startup_channel_id_;
scoped_ptr<IPC::ChannelProxy> startup_channel_;
scoped_ptr<ChromeContentClient> content_client_;
scoped_ptr<chrome::ChromeContentBrowserClient> browser_content_client_;
#if defined(OS_MACOSX)
base::ScopedTempDir temp_dir_;
base::FilePath executable_path_, bundle_path_;
scoped_ptr<MockLaunchd> mock_launchd_;
scoped_ptr<Launchd::ScopedInstance> scoped_launchd_instance_;
#endif
private:
class WindowedChannelConnectionObserver {
public:
WindowedChannelConnectionObserver()
: seen_(false),
running_(false) { }
void Wait() {
if (seen_)
return;
running_ = true;
content::RunMessageLoop();
}
void Notify() {
seen_ = true;
if (running_)
base::MessageLoopForUI::current()->Quit();
}
private:
bool seen_;
bool running_;
};
WindowedChannelConnectionObserver observer_;
};
CloudPrintProxyPolicyStartupTest::CloudPrintProxyPolicyStartupTest()
: thread_bundle_(content::TestBrowserThreadBundle::REAL_IO_THREAD) {
// Although is really a unit test which runs in the browser_tests binary, it
// doesn't get the unit setup which normally happens in the unit test binary.
ChromeUnitTestSuite::InitializeProviders();
ChromeUnitTestSuite::InitializeResourceBundle();
}
CloudPrintProxyPolicyStartupTest::~CloudPrintProxyPolicyStartupTest() {
}
void CloudPrintProxyPolicyStartupTest::SetUp() {
content_client_.reset(new ChromeContentClient);
content::SetContentClient(content_client_.get());
browser_content_client_.reset(new chrome::ChromeContentBrowserClient());
content::SetBrowserClientForTesting(browser_content_client_.get());
TestingBrowserProcess::CreateInstance();
#if defined(OS_MACOSX)
EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
EXPECT_TRUE(MockLaunchd::MakeABundle(temp_dir_.path(),
"CloudPrintProxyTest",
&bundle_path_,
&executable_path_));
mock_launchd_.reset(new MockLaunchd(executable_path_,
base::MessageLoopForUI::current(),
true, false));
scoped_launchd_instance_.reset(
new Launchd::ScopedInstance(mock_launchd_.get()));
#endif
// Ensure test does not use the standard profile directory. This is copied
// from InProcessBrowserTest::SetUp(). These tests require a more complex
// process startup so they are unable to just inherit from
// InProcessBrowserTest.
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
base::FilePath user_data_dir =
command_line->GetSwitchValuePath(switches::kUserDataDir);
if (user_data_dir.empty()) {
ASSERT_TRUE(temp_user_data_dir_.CreateUniqueTempDir() &&
temp_user_data_dir_.IsValid())
<< "Could not create temporary user data directory \""
<< temp_user_data_dir_.path().value() << "\".";
user_data_dir = temp_user_data_dir_.path();
command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
}
ASSERT_TRUE(test_launcher_utils::OverrideUserDataDir(user_data_dir));
}
void CloudPrintProxyPolicyStartupTest::TearDown() {
browser_content_client_.reset();
content_client_.reset();
content::SetContentClient(NULL);
TestingBrowserProcess::DeleteInstance();
}
base::Process CloudPrintProxyPolicyStartupTest::Launch(
const std::string& name) {
EXPECT_FALSE(CheckServiceProcessReady());
startup_channel_id_ =
base::StringPrintf("%d.%p.%d",
base::GetCurrentProcId(), this,
base::RandInt(0, std::numeric_limits<int>::max()));
startup_channel_ = IPC::ChannelProxy::Create(startup_channel_id_,
IPC::Channel::MODE_SERVER,
this,
IOMessageLoopProxy());
#if defined(OS_POSIX)
base::FileHandleMappingVector ipc_file_list;
ipc_file_list.push_back(std::make_pair(
startup_channel_->TakeClientFileDescriptor().release(),
kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor));
base::LaunchOptions options;
options.fds_to_remap = &ipc_file_list;
base::Process process = SpawnChildWithOptions(name, options);
#else
base::Process process = SpawnChild(name);
#endif
EXPECT_TRUE(process.IsValid());
return process.Pass();
}
void CloudPrintProxyPolicyStartupTest::WaitForConnect() {
observer_.Wait();
EXPECT_TRUE(CheckServiceProcessReady());
EXPECT_TRUE(base::MessageLoopProxy::current().get());
ServiceProcessControl::GetInstance()->SetChannel(
IPC::ChannelProxy::Create(GetServiceProcessChannel(),
IPC::Channel::MODE_NAMED_CLIENT,
ServiceProcessControl::GetInstance(),
IOMessageLoopProxy()));
}
bool CloudPrintProxyPolicyStartupTest::Send(IPC::Message* message) {
return ServiceProcessControl::GetInstance()->Send(message);
}
void CloudPrintProxyPolicyStartupTest::ShutdownAndWaitForExitWithTimeout(
base::Process process) {
ASSERT_TRUE(Send(new ServiceMsg_Shutdown()));
int exit_code = -100;
bool exited = process.WaitForExitWithTimeout(TestTimeouts::action_timeout(),
&exit_code);
EXPECT_TRUE(exited);
EXPECT_EQ(exit_code, 0);
}
void CloudPrintProxyPolicyStartupTest::OnChannelConnected(int32 peer_pid) {
observer_.Notify();
}
base::CommandLine CloudPrintProxyPolicyStartupTest::MakeCmdLine(
const std::string& procname) {
base::CommandLine cl = MultiProcessTest::MakeCmdLine(procname);
cl.AppendSwitchASCII(switches::kProcessChannelID, startup_channel_id_);
#if defined(OS_MACOSX)
cl.AppendSwitchASCII(kTestExecutablePath, executable_path_.value());
#endif
return cl;
}
TEST_F(CloudPrintProxyPolicyStartupTest, StartAndShutdown) {
TestingBrowserProcess* browser_process =
TestingBrowserProcess::GetGlobal();
TestingProfileManager profile_manager(browser_process);
ASSERT_TRUE(profile_manager.SetUp());
// Must be created after the TestingProfileManager since that creates the
// LocalState for the BrowserProcess. Must be created before profiles are
// constructed.
chrome::TestingIOThreadState testing_io_thread_state;
base::Process process =
Launch("CloudPrintMockService_StartEnabledWaitForQuit");
WaitForConnect();
ShutdownAndWaitForExitWithTimeout(process.Pass());
content::RunAllPendingInMessageLoop();
}
KeyedService* CloudPrintProxyServiceFactoryForPolicyTest(
content::BrowserContext* profile) {
CloudPrintProxyService* service =
new CloudPrintProxyService(static_cast<Profile*>(profile));
service->Initialize();
return service;
}
TEST_F(CloudPrintProxyPolicyStartupTest, StartBrowserWithoutPolicy) {
base::Process process =
Launch("CloudPrintMockService_StartEnabledWaitForQuit");
// Setup the Browser Process with a full IOThread::Globals.
TestingBrowserProcess* browser_process =
TestingBrowserProcess::GetGlobal();
TestingProfileManager profile_manager(browser_process);
ASSERT_TRUE(profile_manager.SetUp());
// Must be created after the TestingProfileManager since that creates the
// LocalState for the BrowserProcess. Must be created before profiles are
// constructed.
chrome::TestingIOThreadState testing_io_thread_state;
TestingProfile* profile =
profile_manager.CreateTestingProfile("StartBrowserWithoutPolicy");
CloudPrintProxyServiceFactory::GetInstance()->
SetTestingFactory(profile, CloudPrintProxyServiceFactoryForPolicyTest);
TestingPrefServiceSyncable* prefs = profile->GetTestingPrefService();
prefs->SetUserPref(
prefs::kCloudPrintEmail,
new base::StringValue(MockServiceIPCServer::EnabledUserId()));
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitch(switches::kCheckCloudPrintConnectorPolicy);
test_launcher_utils::PrepareBrowserCommandLineForTests(&command_line);
WaitForConnect();
base::RunLoop run_loop;
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
run_loop.QuitClosure(),
TestTimeouts::action_timeout());
bool should_run_loop = LaunchBrowser(command_line, profile);
EXPECT_FALSE(should_run_loop);
if (should_run_loop)
run_loop.Run();
EXPECT_EQ(MockServiceIPCServer::EnabledUserId(),
prefs->GetString(prefs::kCloudPrintEmail));
ShutdownAndWaitForExitWithTimeout(process.Pass());
content::RunAllPendingInMessageLoop();
profile_manager.DeleteTestingProfile("StartBrowserWithoutPolicy");
}
TEST_F(CloudPrintProxyPolicyStartupTest, StartBrowserWithPolicy) {
base::Process process =
Launch("CloudPrintMockService_StartEnabledExpectDisabled");
TestingBrowserProcess* browser_process =
TestingBrowserProcess::GetGlobal();
TestingProfileManager profile_manager(browser_process);
ASSERT_TRUE(profile_manager.SetUp());
// Must be created after the TestingProfileManager since that creates the
// LocalState for the BrowserProcess. Must be created before profiles are
// constructed.
chrome::TestingIOThreadState testing_io_thread_state;
TestingProfile* profile =
profile_manager.CreateTestingProfile("StartBrowserWithPolicy");
CloudPrintProxyServiceFactory::GetInstance()->
SetTestingFactory(profile, CloudPrintProxyServiceFactoryForPolicyTest);
TestingPrefServiceSyncable* prefs = profile->GetTestingPrefService();
prefs->SetUserPref(
prefs::kCloudPrintEmail,
new base::StringValue(MockServiceIPCServer::EnabledUserId()));
prefs->SetManagedPref(prefs::kCloudPrintProxyEnabled,
new base::FundamentalValue(false));
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitch(switches::kCheckCloudPrintConnectorPolicy);
test_launcher_utils::PrepareBrowserCommandLineForTests(&command_line);
WaitForConnect();
base::RunLoop run_loop;
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
run_loop.QuitClosure(),
TestTimeouts::action_timeout());
bool should_run_loop = LaunchBrowser(command_line, profile);
// No expectations on run_loop being true here; that would be a race
// condition.
if (should_run_loop)
run_loop.Run();
EXPECT_EQ("", prefs->GetString(prefs::kCloudPrintEmail));
ShutdownAndWaitForExitWithTimeout(process.Pass());
content::RunAllPendingInMessageLoop();
profile_manager.DeleteTestingProfile("StartBrowserWithPolicy");
}
|
//
// Page2.xaml.cpp
// Implementation of the Page2 class
//
#include "pch.h"
#include "Page2.xaml.h"
using namespace SDKSample::PersonalityAnimations;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
Page2::Page2()
{
InitializeComponent();
messageData = ref new MessageData;
GridView1->ItemsSource = messageData->Items;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void Page2::OnNavigatedTo(NavigationEventArgs^ e)
{
VisualStateManager::GoToState(this, "NavigatedTo", true);
//(void) e; // Unused parameter
}
|
;
; Sharp OZ family functions
;
; ported from the OZ-7xx SDK by by Alexander R. Pruss
; by Stefano Bodrato - Oct. 2003
;
;
; Keyboard routines
;
; ------
; $Id: ozkeyhit.asm,v 1.2 2003/10/27 16:56:57 stefano Exp $
;
XLIB ozkeyhit2 ; renamed (will be redefined if used)
XREF KeyBufGetPos
XREF EnableKeyboard
ozkeyhit2:
ld de,EnableKeyboard
ld a,(de)
and 0ffh-7
ld (de),a
ld hl,KeyBufGetPos
ld a,(hl)
inc hl ;; KeyBufPutPos
cp (hl)
ld hl,1
ret nz
dec hl
ret
|
; Mugwump for the HP-35s
; This program is from Bob Albrecht and is used here by permission.
; http://www.vintage-basic.net/bcg/mugwump.bas
MODEL P35S
SEGMENT MUGWUMP CODE
LBL M
;1 PRINT TAB(33);"MUGWUMP"
SF 10
eqn 'MUGWUMP'
PSE
CF 10
;------------------------------------------------------
; CREATIVE COMPUTING MORRISTOWN, NEW JERSEY
;
; COURTESY PEOPLE'S COMPUTER COMPANY
;------------------------------------------------------
;10 DIM P(4,2)
4
STO P
STO I
SGN
STO+ I
+/-
STO (I)
;------------------------------------------------------
; THE OBJECT OF THIS GAME IS TO FIND FOUR MUGWUMPS
; HIDDEN ON A 10 BY 10 GRID. HOMEBASE IS POSITION 0,0.
; ANY GUESS YOU MAKE MUST BE TWO NUMBERS WITH EACH
; NUMBER BETWEEN 0 AND 9, INCLUSIVE. FIRST NUMBER
; IS DISTANCE TO RIGHT OF HOMEBASE AND SECOND NUMBER
; IS DISTANCE ABOVE HOMEBASE.
;
; YOU GET 10 TRIES. AFTER EACH TRY, I WILL TELL
; YOU HOW FAR YOU ARE FROM EACH MUGWUMP.
;------------------------------------------------------
@240:
;240 GOSUB 1000
XEQ @1000
;250 T=0
CLx
STO T
@260:
;260 T=T+1
1
STO+ T
;270 PRINT
;275 PRINT
;290 PRINT "TURN NO.";T;"-- WHAT IS YOUR GUESS";
SF 10
eqn 'TURN NUM'
PSE
ALL
ALG
RCL T
PSE
RPN
eqn 'YOUR GUESS'
PSE
CF 10
;300 INPUT M,N
INPUT X
INPUT Y
FIX 4
;310 FOR I=1 TO 4
1.004
STO I
@320:
;320 IF P(I,1)=-1 THEN 400
eqn '(I)*[1,0]'
x<0?
GTO @400
;330 IF P(I,1)<>M THEN 380
RCL X
x!=y?
GTO @380
;340 IF P(I,2)<>N THEN 380
eqn '(I)*[0,1]'
RCL Y
x!=y?
GTO @380
;350 P(I,1)=-1
[-1,0]
STO (I)
;360 PRINT "YOU HAVE FOUND MUGWUMP";I
SF 10
eqn 'FOUND MUGWUMP'
PSE
CF 10
ALL
ALG
RCL I
IP
PSE
RPN
FIX 4
;370 GOTO 400
GTO @400
@380:
;380 D=SQR((P(I,1)-M)^2+(P(I,2)-N)^2)
eqn 'ABS((I)-[X,Y])'
;390 PRINT "YOU ARE";(INT(D*10))/10;"UNITS FROM MUGWUMP";I
x<> (I)
SF 10
eqn 'UNITS'
PSE
eqn 'FROM MUGWUMP'
PSE
CF 10
FIX 1
VIEW (I)
PSE
FIX 4
x<> (I)
@400:
;400 NEXT I
ISG I
GTO @320
;410 FOR J=1 TO 4
1.004
STO J
@420:
;420 IF P(J,1)<>-1 THEN 470
eqn '(J)*[1,0]'
x>=0?
GTO @470
;430 NEXT J
ISG J
GTO @420
;440 PRINT
;450 PRINT "YOU GOT THEM ALL IN";T;"TURNS!"
SF 10
eqn 'YOU GOT IT!'
PSE
eqn 'NUM ATTEMPTS'
PSE
CF 10
ALL
VIEW T
PSE
FIX 4
;460 GOTO 580
GTO @580
@470:
;470 IF T<10 THEN 260
10
RCL T
x<y?
GTO @260
;480 PRINT
;490 PRINT "SORRY, THAT'S 10 TRIES. HERE IS WHERE THEY'RE HIDING:"
SF 10
eqn 'SORRY,10 TRIES'
PSE
eqn 'HERE THEY ARE'
PSE
CF 10
;540 FOR I=1 TO 4
1.004
STO I
@550:
;550 IF P(I,1)=-1 THEN 570
eqn '(I)*[1,0]'
x<0?
GTO @570
;560 PRINT "MUGWUMP";I;"IS AT (";P(I,1);",";P(I,2);")"
SF 10
eqn 'MUGWUMP AT'
PSE
CF 10
ALL
VIEW (I)
PSE
FIX 4
@570:
;570 NEXT I
ISG I
GTO @550
@580:
;580 PRINT
;600 PRINT "THAT WAS FUN! LET'S PLAY AGAIN......."
;610 PRINT "FOUR MORE MUGWUMPS ARE NOW IN HIDING."
SF 10
eqn 'PLAY AGAIN'
PSE
CF 10
;630 GOTO 240
GTO @240
@1000:
;1000 FOR J=1 TO 2
;1010 FOR I=1 TO 4
1.004
STO I
@1020:
; 1020 P(I,J)=INT(10*RND(1))
eqn 'IP(10*RAND)'
eqn 'IP(10*RAND)'
eqn '[REGX,REGY]'
STO (I)
;1030 NEXT I
;1040 NEXT J
ISG I
GTO @1020
RTN
ENDS MUGWUMP
END
|
global idt_init_asm
global idt_load
extern interrupts_register_isr
extern idtr
extern panic
extern sched_switch
%macro register_isr 1
push isr_%1
push %1
call interrupts_register_isr
add esp, 8
%endmacro
%macro ack_irq 0
push ax
mov al, 0x20
out 0xa0, al
out 0x20, al
pop ax
%endmacro
%macro begin_isr 1
jmp isr_%1.end
isr_%1:
%endmacro
%macro end_isr 1
.end:
register_isr %1
%endmacro
%macro generic_exception 2
begin_isr %1
push .msg
call panic
.msg db %2, 0
end_isr %1
%endmacro
section .text
idt_load:
lidt [idtr]
ret
idt_init_asm:
generic_exception 0, "divide by zero"
generic_exception 1, "debug"
generic_exception 2, "non-maskable interrupt"
generic_exception 3, "breakpoint"
generic_exception 4, "overflow"
generic_exception 5, "bound range exceeded"
generic_exception 6, "invalid opcode"
generic_exception 7, "device not available"
generic_exception 8, "double fault"
generic_exception 10, "invalid tss"
generic_exception 11, "segment not present"
generic_exception 12, "stack segment fault"
generic_exception 13, "general protection fault"
; page fault
begin_isr 14
mov eax, cr2
push eax
push .msg
call panic
iret
.msg db "page fault at 0x%x, error code: %x", 0
end_isr 14
; PIT irq
begin_isr 32
ack_irq
push ebp
push dword 0
push dword 0
mov ebp, esp
call sched_switch
add esp, 8 ; fix up the fake stack frame we created
pop ebp
iret
end_isr 32
; keyboard irq
begin_isr 33
ack_irq
iret
end_isr 33
; spurious irq
begin_isr 39
iret
end_isr 39
ret
|
//
// _ _ ______ _ _ _ _ _ _ _
// | \ | | | ____| | (_) | (_) | | | |
// | \| | ___ | |__ __| |_| |_ _ _ __ __ _| | | |
// | . ` |/ _ \ | __| / _` | | __| | '_ \ / _` | | | |
// | |\ | (_) | | |___| (_| | | |_| | | | | (_| |_|_|_|
// |_| \_|\___/ |______\__,_|_|\__|_|_| |_|\__, (_|_|_)
// __/ |
// |___/
//
// This file is auto-generated. Do not edit manually
//
// Copyright 2013-2022 Step Function I/O, LLC
//
// Licensed to Green Energy Corp (www.greenenergycorp.com) and Step Function I/O
// LLC (https://stepfunc.io) under one or more contributor license agreements.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. Green Energy Corp and Step Function I/O LLC license
// this file to you under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You may obtain
// a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "opendnp3/gen/RestartMode.h"
#include <stdexcept>
namespace opendnp3 {
uint8_t RestartModeSpec::to_type(RestartMode arg)
{
return static_cast<uint8_t>(arg);
}
RestartMode RestartModeSpec::from_type(uint8_t arg)
{
switch(arg)
{
case(0):
return RestartMode::UNSUPPORTED;
case(1):
return RestartMode::SUPPORTED_DELAY_FINE;
case(2):
return RestartMode::SUPPORTED_DELAY_COARSE;
default:
throw new std::invalid_argument("Unknown value");
}
}
char const* RestartModeSpec::to_string(RestartMode arg)
{
switch(arg)
{
case(RestartMode::UNSUPPORTED):
return "UNSUPPORTED";
case(RestartMode::SUPPORTED_DELAY_FINE):
return "SUPPORTED_DELAY_FINE";
case(RestartMode::SUPPORTED_DELAY_COARSE):
return "SUPPORTED_DELAY_COARSE";
default:
return "UNDEFINED";
}
}
char const* RestartModeSpec::to_human_string(RestartMode arg)
{
switch(arg)
{
case(RestartMode::UNSUPPORTED):
return "UNSUPPORTED";
case(RestartMode::SUPPORTED_DELAY_FINE):
return "SUPPORTED_DELAY_FINE";
case(RestartMode::SUPPORTED_DELAY_COARSE):
return "SUPPORTED_DELAY_COARSE";
default:
return "UNDEFINED";
}
}
RestartMode RestartModeSpec::from_string(const std::string& arg)
{
if(arg == "UNSUPPORTED") return RestartMode::UNSUPPORTED;
if(arg == "SUPPORTED_DELAY_FINE") return RestartMode::SUPPORTED_DELAY_FINE;
if(arg == "SUPPORTED_DELAY_COARSE") return RestartMode::SUPPORTED_DELAY_COARSE;
else throw std::invalid_argument(std::string("Unknown value: ") + arg);
}
}
|
; A047308: Numbers that are congruent to {0, 3, 4, 5, 6} mod 7.
; 0,3,4,5,6,7,10,11,12,13,14,17,18,19,20,21,24,25,26,27,28,31,32,33,34,35,38,39,40,41,42,45,46,47,48,49,52,53,54,55,56,59,60,61,62,63,66,67,68,69,70,73,74,75,76,77
mov $1,$0
add $0,4
div $0,5
mul $0,2
add $0,$1
|
; A077840: Expansion of (1-x)/(1-2*x-3*x^2-3*x^3).
; Submitted by Jamie Morken(s4)
; 1,1,5,16,50,163,524,1687,5435,17503,56372,181558,584741,1883272,6065441,19534921,62915981,202633048,652618802,2101884691,6769524932,21802560343,70219349555,226154954935,728375639564,2345874192598,7555340168693,24333429833872
mov $2,1
mov $4,1
lpb $0
sub $0,1
mul $1,2
add $1,$4
add $1,$3
mul $2,3
mov $4,$3
mov $3,$2
mov $2,$1
lpe
mov $0,$2
|
; Copyright (c) 2004, 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:
;
; WriteDr4.Asm
;
; Abstract:
;
; AsmWriteDr4 function
;
; Notes:
;
;------------------------------------------------------------------------------
.code
;------------------------------------------------------------------------------
; UINTN
; EFIAPI
; AsmWriteDr4 (
; IN UINTN Value
; );
;------------------------------------------------------------------------------
AsmWriteDr4 PROC
;
; There's no obvious reason to access this register, since it's aliased to
; DR6 when DE=0 or an exception generated when DE=1
;
DB 0fh, 23h, 0e1h
mov rax, rcx
ret
AsmWriteDr4 ENDP
END
|
; A330025: a(n) = (-1)^floor(n/5) * sign(mod(n, 5)).
; 0,1,1,1,1,0,-1,-1,-1,-1,0,1,1,1,1,0,-1,-1,-1,-1,0,1,1,1,1,0,-1,-1,-1,-1,0,1,1,1,1,0,-1,-1,-1,-1,0,1,1,1,1,0,-1,-1,-1,-1,0,1,1,1,1,0,-1,-1,-1,-1,0,1,1,1,1,0,-1,-1,-1,-1,0,1,1,1,1,0,-1
add $0,10
seq $0,163812 ; Expansion of (1 - x^5) * (1 - x^6) / ((1 - x) * (1 - x^10)) in powers of x.
|
.MODEL small
.STACK
.DATA
n1 db 10
n2 db 10h
n3 db 10b
res db 0
.CODE
.STARTUP
mov al, n1
add al, n2
sub al, n3
mov res ,al
.EXIT
END |
; $Id: bs3-cmn-SelProtModeCodeToRealMode.asm 69111 2017-10-17 14:26:02Z vboxsync $
;; @file
; BS3Kit - Bs3SelProtModeCodeToRealMode.
;
;
; Copyright (C) 2007-2017 Oracle Corporation
;
; This file is part of VirtualBox Open Source Edition (OSE), as
; available from http://www.virtualbox.org. This file is free software;
; you can redistribute it and/or modify it under the terms of the GNU
; General Public License (GPL) as published by the Free Software
; Foundation, in version 2 as it comes in the "COPYING" file of the
; VirtualBox OSE distribution. VirtualBox OSE is distributed in the
; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
;
; The contents of this file may alternatively be used under the terms
; of the Common Development and Distribution License Version 1.0
; (CDDL) only, as it comes in the "COPYING.CDDL" file of the
; VirtualBox OSE distribution, in which case the provisions of the
; CDDL are applicable instead of those of the GPL.
;
; You may elect to license modified versions of this file under the
; terms and conditions of either the GPL or the CDDL or both.
;
%include "bs3kit-template-header.mac"
;
; Make sure we can get at all the segments.
;
BS3_BEGIN_TEXT16
BS3_BEGIN_RMTEXT16
BS3_BEGIN_X0TEXT16
BS3_BEGIN_X1TEXT16
TMPL_BEGIN_TEXT
;;
; @cproto BS3_CMN_PROTO(uint16_t, Bs3SelProtModeCodeToRealMode,(uint16_t uRealSel), false);
; @uses ax (return register)
;
BS3_PROC_BEGIN_CMN Bs3SelProtModeCodeToRealMode, BS3_PBC_NEAR
BS3_CALL_CONV_PROLOG 1
push xBP
mov xBP, xSP
; Load it and mask off the RPL.
mov ax, [xBP + xCB + cbCurRetAddr]
and ax, X86_SEL_MASK_OFF_RPL
; We're allowed to use the real-mode segment value.
cmp ax, CGROUP16
je .bs3text16
; Check for typical code segments.
cmp ax, BS3_SEL_R0_CS16
je .bs3text16
cmp ax, BS3_SEL_RMTEXT16_CS
je .bs3rmtext16
cmp ax, BS3_SEL_X0TEXT16_CS
je .bs3x0text16
cmp ax, BS3_SEL_X1TEXT16_CS
je .bs3x1text16
; Check for less common BS3_SEL_R*_CS16_* values.
cmp ax, BS3_SEL_R0_FIRST
jb .panic
cmp ax, BS3_SEL_R3_FIRST + (1 << BS3_SEL_RING_SHIFT)
jae .panic
; Since the relevant bits now are the lower 8 ones, we skip the
; AND AX, BS3_SEL_RING_SHIFT
; ADD AX, BS3_SEL_R0_FIRST
; bits and compare AL with lower 8-bit of the BS3_SEL_R0_CS16* values.
AssertCompile(BS3_SEL_RING_SHIFT == 8)
cmp al, BS3_SEL_R0_CS16 & 0xff
je .bs3text16
cmp al, BS3_SEL_R0_CS16_EO & 0xff
je .bs3text16
cmp ax, BS3_SEL_R0_CS16_CNF & 0xff
je .bs3text16
cmp ax, BS3_SEL_R0_CS16_CNF_EO & 0xff
je .bs3text16
.panic:
extern BS3_CMN_NM(Bs3Panic)
call BS3_CMN_NM(Bs3Panic)
jmp .return
.bs3x1text16:
mov ax, BS3GROUPX1TEXT16
jmp .return
.bs3x0text16:
mov ax, BS3GROUPX0TEXT16
jmp .return
.bs3rmtext16:
mov ax, BS3GROUPRMTEXT16
jmp .return
.bs3text16:
mov ax, CGROUP16
.return:
pop xBP
BS3_CALL_CONV_EPILOG 1
BS3_HYBRID_RET
BS3_PROC_END_CMN Bs3SelProtModeCodeToRealMode
;
; We may be using the near code in some critical code paths, so don't
; penalize it.
;
BS3_CMN_FAR_STUB Bs3SelProtModeCodeToRealMode, 2
|
; A053143: Smallest square divisible by n.
; 1,4,9,4,25,36,49,16,9,100,121,36,169,196,225,16,289,36,361,100,441,484,529,144,25,676,81,196,841,900,961,64,1089,1156,1225,36,1369,1444,1521,400,1681,1764,1849,484,225,2116,2209,144,49,100,2601,676,2809,324,3025,784,3249,3364,3481,900,3721,3844,441,64,4225,4356,4489,1156,4761,4900,5041,144,5329,5476,225,1444,5929,6084,6241,400,81,6724,6889,1764,7225,7396,7569,1936,7921,900,8281,2116,8649,8836,9025,576,9409,196,1089,100
mov $1,$0
add $0,1
seq $1,7913 ; Squarefree part of n: a(n) is the smallest positive number m such that n/m is a square.
mul $0,$1
|
;
; jdcolss2-64.asm - colorspace conversion (64-bit SSE2)
;
; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
; Copyright 2009 D. R. Commander
;
; Based on
; x86 SIMD extension for IJG JPEG library
; Copyright (C) 1999-2006, MIYASAKA Masaru.
; For conditions of distribution and use, see copyright notice in jsimdext.inc
;
; This file should be assembled with NASM (Netwide Assembler),
; can *not* be assembled with Microsoft's MASM or any compatible
; assembler (including Borland's Turbo Assembler).
; NASM is available from http://nasm.sourceforge.net/ or
; http://sourceforge.net/project/showfiles.php?group_id=6208
;
; [TAB8]
%include "jsimdext.inc"
; --------------------------------------------------------------------------
%define SCALEBITS 16
F_0_344 equ 22554 ; FIX(0.34414)
F_0_714 equ 46802 ; FIX(0.71414)
F_1_402 equ 91881 ; FIX(1.40200)
F_1_772 equ 116130 ; FIX(1.77200)
F_0_402 equ (F_1_402 - 65536) ; FIX(1.40200) - FIX(1)
F_0_285 equ ( 65536 - F_0_714) ; FIX(1) - FIX(0.71414)
F_0_228 equ (131072 - F_1_772) ; FIX(2) - FIX(1.77200)
; --------------------------------------------------------------------------
SECTION SEG_CONST
alignz 16
global EXTN(jconst_ycc_rgb_convert_sse2) PRIVATE
EXTN(jconst_ycc_rgb_convert_sse2):
PW_F0402 times 8 dw F_0_402
PW_MF0228 times 8 dw -F_0_228
PW_MF0344_F0285 times 4 dw -F_0_344, F_0_285
PW_ONE times 8 dw 1
PD_ONEHALF times 4 dd 1 << (SCALEBITS-1)
alignz 16
; --------------------------------------------------------------------------
%include "jdclrss2-64.asm"
%undef RGB_RED
%undef RGB_GREEN
%undef RGB_BLUE
%undef RGB_PIXELSIZE
%define RGB_RED 0
%define RGB_GREEN 1
%define RGB_BLUE 2
%define RGB_PIXELSIZE 3
%define jsimd_ycc_rgb_convert_sse2 jsimd_ycc_extrgb_convert_sse2
%include "jdclrss2-64.asm"
%undef RGB_RED
%undef RGB_GREEN
%undef RGB_BLUE
%undef RGB_PIXELSIZE
%define RGB_RED 0
%define RGB_GREEN 1
%define RGB_BLUE 2
%define RGB_PIXELSIZE 4
%define jsimd_ycc_rgb_convert_sse2 jsimd_ycc_extrgbx_convert_sse2
%include "jdclrss2-64.asm"
%undef RGB_RED
%undef RGB_GREEN
%undef RGB_BLUE
%undef RGB_PIXELSIZE
%define RGB_RED 2
%define RGB_GREEN 1
%define RGB_BLUE 0
%define RGB_PIXELSIZE 3
%define jsimd_ycc_rgb_convert_sse2 jsimd_ycc_extbgr_convert_sse2
%include "jdclrss2-64.asm"
%undef RGB_RED
%undef RGB_GREEN
%undef RGB_BLUE
%undef RGB_PIXELSIZE
%define RGB_RED 2
%define RGB_GREEN 1
%define RGB_BLUE 0
%define RGB_PIXELSIZE 4
%define jsimd_ycc_rgb_convert_sse2 jsimd_ycc_extbgrx_convert_sse2
%include "jdclrss2-64.asm"
%undef RGB_RED
%undef RGB_GREEN
%undef RGB_BLUE
%undef RGB_PIXELSIZE
%define RGB_RED 3
%define RGB_GREEN 2
%define RGB_BLUE 1
%define RGB_PIXELSIZE 4
%define jsimd_ycc_rgb_convert_sse2 jsimd_ycc_extxbgr_convert_sse2
%include "jdclrss2-64.asm"
%undef RGB_RED
%undef RGB_GREEN
%undef RGB_BLUE
%undef RGB_PIXELSIZE
%define RGB_RED 1
%define RGB_GREEN 2
%define RGB_BLUE 3
%define RGB_PIXELSIZE 4
%define jsimd_ycc_rgb_convert_sse2 jsimd_ycc_extxrgb_convert_sse2
%include "jdclrss2-64.asm"
|
#include "ModuleMSTimer.h"
#include "ModuleUI.h"
#include "SDL.h"
ModuleMSTimer::ModuleMSTimer(){}
ModuleMSTimer::~ModuleMSTimer(){}
bool ModuleMSTimer::Start() {
App->ui->my_log.AddLog("Init Timer\n");
currentTime = 0;
counting = true;
return true;
}
void ModuleMSTimer::Read() {
//In milliseconds
if(counting)
currentTime = SDL_GetTicks();
}
float ModuleMSTimer::Stop() {
counting = false;
return currentTime;
} |
%include "x86-helpers.asm"
nasm_util_assert_boilerplate
thunk_boilerplate
; branch notes
;
; The BTB seems to have a 32-byte granularity and only the first taken
; branch in a 32-byte region gets a "fast" back-to-back prediction, of
; 1 cycle
; the second branch in a 32-byte region appears to take at least 2 cycles
; sometimes longer, exhibiting patterns such as 5.0, 5.67 or 6.33 cycles for
; two such branches for the *same* benchmark, from run to run
; an lfence inside the loop appears to remove the variance (only the
; fastest timing shows).
; The "second" determination is based on the IP, not frequency: even if the
; second branch is jumped to 2x as often, the first branch retains the fast
; behavior.
; an lfence before the benchmark but outside the loop seems to reduce
; the variance
;
;
; indirect branches
;
; indirect seem to have a best-case throughput of 1 per 2 cycles,
; regardless of spacing
; fill the given number of bytes with nop3, using
; plain nop for the 0-2 odd bytes at the end
%macro fillnop3 1-2 2
times ((%1 - %2) / 3) nop3
times ((%1 - %2) % 3) nop
%endmacro
%macro jmp_forward 1
%assign jump_bytes %1
%if %1 < 2
%error jump should be at least two bytes
%assign jump_bytes 2
%endif
jmp %%target
fillnop3 jump_bytes
%%target:
%undef jump_bytes
%endmacro
; make a benchmark that jumps forward by %1 bytes
; then by %2 bytes, repeated 10 times
;
; shows the important of jump spacing on BTB access
; and or prediction latency
;
; %1 first jump distance
; %2 second jump distance
%macro define_jmp_forward 2
define_bench jmp_forward_%1_%2
xor eax, eax
clc
jmp .top
align 64
.top:
%rep 10
jmp_forward %1
jmp_forward %2
%endrep
dec rdi
jnz .top
nop2
ret
%endmacro
define_jmp_forward 8, 8
define_jmp_forward 16, 16
define_jmp_forward 32, 32
define_jmp_forward 64, 64
define_jmp_forward 96, 96
define_jmp_forward 128, 128
; This test consists of a series of forward jumps, two per "block", organized
; into two chains: a first chain whose jmp is always first in the block and
; targets the first jmp in the second block, and a second chain that is similar
; except using the second jump.
;
; We go though three chains every iteration, either 2 first and 1 second, or
; 2 second and 1 first chains. This test shows that the first jump in a block
; is resolved faster (1 cycle) by the BTB, since the variant with 2:1
; first:second jumps is faster by 1 cycle per jmp tham the 1:2 variant.
;
; %1 total gap (between first/second jump in one block and first/second
; %2 first gap (between first and second jump targets)
; jump in the next)
; %3: 0 means the second jump occurs in a 2:1 ratio with the first
; 1 means the second jump occurs in a 1:2 ratio with the first
; %4 offset of the first jump after the start of the block
%macro define_jmp_forward_dual 4
define_bench jmp_forward_dual_%1_%2_%3
xor eax, eax
jmp .first_1
align 64
%assign reps 10
%assign fill1 %2
%assign fill2 (%1 - %2 - %4)
%assign i 1
%rep (reps-1)
%assign next (i+1)
fillnop3 %4, 0
.first_%+i:
jmp .first_%+next
fillnop3 fill1
.second_%+i:
jmp .second_%+next
fillnop3 fill2
%assign i (i+1)
%endrep
%if %3
%define target1 first
%define target2 second
%else
%define target1 second
%define target2 first
%endif
; the final iteration of the first pass jumps to
; the first target of the second pass, unconditionally
. %+ target1 %+ _ %+ reps:
jmp . %+ target2 %+ _1
; while the second iteration alternates between jumping again
; to the second pass and the first pass (in the latter case
; also checking for termination). So the first:second passes are
; executed in a 1:2 ratio
. %+ target2 %+ _ %+ reps:
xor eax, 1
jnz . %+ target2 %+ _1
dec rdi
jnz . %+ target1 %+ _1
ret
%endmacro
define_jmp_forward_dual 32, 16, 0, 3
define_jmp_forward_dual 32, 6, 0, 3
define_jmp_forward_dual 64, 16, 0, 3
define_jmp_forward_dual 64, 48, 0, 3
define_jmp_forward_dual 32, 16, 1, 3
define_jmp_forward_dual 32, 6, 1, 3
define_jmp_forward_dual 64, 16, 1, 3
define_jmp_forward_dual 64, 48, 1, 3
struc jmp_loop_args
.total : resd 1
.first : resd 1
endstruc
; this is similar to the jmp_forward_dual test
; except that we execute the forward jump region
; 100x times in a loop, split in a configurable way
; between the first and second regions
;
; %1 total gap (between first/second jump in one block and first/second
; %2 first gap (between first and second jump targets)
%macro define_jmp_loop_generic 2
define_bench jmp_loop_generic_%1_%2
%define block_size %1
%define gap %2
mov edx, [rsi + jmp_loop_args.total]
mov ecx, [rsi + jmp_loop_args.first]
%define total_iters edx
%define first_iters ecx
xor eax, eax
jmp .bottom
ud2
align 64
%assign reps 10
%assign fill1 gap
%assign fill2 (block_size - gap)
%assign i 1
%rep (reps-1)
%assign next (i+1)
.first_%+i:
jmp .first_%+next
fillnop3 fill1
.second_%+i:
jmp .second_%+next
fillnop3 fill2
%assign i (i+1)
%endrep
.first_%+i:
nop
nop
.second_%+i:
.bottom:
inc eax
cmp eax, first_iters
jle .first_1
cmp eax, total_iters
jle .second_1
xor eax, eax
dec rdi
jnz .bottom
.done:
ret
%endmacro
define_jmp_loop_generic 32, 16
%macro indirect_forward 1
%%before:
add rax, %%target - %%before
jmp rax
%%after:
%assign rem (%1 - (%%after - %%before))
%if rem < 0
%error indirect jump bytes too small: smaller than lea/jmp pair
%endif
times (rem / 3) nop3
times (rem % 3) nop
%%target:
%undef rem
%endmacro
%macro define_indirect_forward 1
define_bench indirect_forward_%1
xor eax, eax
clc
jmp .top
align 64
.top:
lea rax, [.before]
.before:
%rep 20
indirect_forward %1
%endrep
dec rdi
jnz .top
nop2
ret
%endmacro
define_indirect_forward 8
define_indirect_forward 16
define_indirect_forward 32
define_indirect_forward 64
%macro define_indirect_variable 1
define_bench define_indirect_variable
xor eax, eax
clc
lea rax, [.nops]
jmp .top
align 64
.top:
.before:
mov rdx, rdi
and rdx, 127
lea rdx, [rax + rdx * 2]
jmp rdx
.nops:
times 128 nop2
dec rdi
jnz .top
nop2
ret
%endmacro
define_indirect_variable 0
; ALIGNMODE p6,nojmp
%define LAT_BODY_SIZE 64
%define LAT_BODY_COUNT_LG2 3
%define LAT_BODY_COUNT (1 << LAT_BODY_COUNT_LG2)
; %1 1st instruction
; %2 2nd instruction
%macro lat_body 2
; chaining instructions
%1
%2
; do the LCG
imul rdx, rax ; x*a
add rdx, rcx ; + c
mov r8, rdx
shr r8, 45 ; high bits have much longer cycles
and r8d, (LAT_BODY_COUNT - 1)
imul r8, LAT_BODY_SIZE
lea r8, [r8 + .top]
dec rdi
cmovz r8, r11 ; jump to end when rdi == 0
jmp r8
%endmacro
; %1 name suffix
; %2 fist payload instruction
; %3 fist payload instruction
%macro define_load_alloc 3
define_bench la_%1
push 0
xor r10d, r10d
lea r11, [rel .end]
mov rax, 6364136223846793005
mov ecx, 1
mov rdx, rax
jmp .top
align 64
.top:
%rep LAT_BODY_COUNT
lat_body {%2},{%3}
ALIGN 64
%endrep
.end:
pop rax
ret
%assign GAP (.end - .top)
%assign GAPPER (GAP / LAT_BODY_COUNT)
%if GAP != LAT_BODY_SIZE * LAT_BODY_COUNT
%error wrong LAT BODY SIZE (LAT_BODY_SIZE) vs GAPPER
%endif
%undef GAP
%undef GAPPER
%endmacro
; See this tweet from Rivet Amber
; https://twitter.com/rivet_amber/status/1312141314629148673
;
; The idea is that IACA shows that load instructions take an extra 3 cycles (4 total)
; from allocation until when they can be dispatched.
;
; We test this by setting up a test that jumps around randomly using indirect branches
; between 8 identical blocks. This will mispredict with a rate of 87.5% (7/8) and we
; use the misprediction to ensure that allocation starts fresh every time, and we put
; two 'payload' instrucitons as the first two in each block, and include them in the dep
; chain leading to the next branch mispredict. In particular, they modify (but don't
; actually change the value) of rdx which is contains the state of the rng and is used
; to calculate the next jump address.
;
; We have two variants of this test with differnet payload: one with a load+add and a nop,
; and one with two lea instructions. Nominally, both add 6 cycles to the latency chain (5
; cycles for the load + 1 for the add, and 3 + 3 for the two LEAs), so if the measured
; performacne is the same, we conclude that load don't have this additional allocation time.
;
; On Skylake, I find that both run in the same time, indicating no additional allocation time.
define_load_alloc load,{add rdx, [rsp + r10]},{nop5}
define_load_alloc lea,{lea rdx, [rdx + r10 - 1]},{lea rdx, [rdx + r10 + 1]}
|
#include "Window.h"
#include "Platform/Windows/WinWindow.h"
namespace Tiger {
Scope<Window> Window::createWindow(const char* title, int width, int height)
{
#ifdef TG_PLATFORM_WINDOWS
return MakeScope<WinWindow>(title, width, height);
#endif
TG_ERROR("Tiger only supports Windows");
return nullptr;
}
} |
; A004197: Table of min(x,y), where (x,y) = (0,0),(0,1),(1,0),(0,2),(1,1),(2,0),...
; 0,0,0,0,1,0,0,1,1,0,0,1,2,1,0,0,1,2,2,1,0,0,1,2,3,2,1,0,0,1,2,3,3,2,1,0,0,1,2,3,4,3,2,1,0,0,1,2,3,4,4,3,2,1,0,0,1,2,3,4,5,4,3,2,1,0,0,1,2,3,4,5,5,4,3,2,1,0,0,1,2,3,4,5,6,5,4,3,2,1,0,0,1,2,3,4,5,6,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,7,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,8,7,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,8,8,7,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,8,9,9,8,7,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,8,9,10,10,9,8,7,6,5,4,3
lpb $0
sub $0,$2
trn $0,1
add $2,1
trn $3,$1
add $0,$3
mov $1,$0
add $3,$2
lpe
|
; A288835: a(n) = (1/2!)*3^n*(n+3)*(n).
; 6,45,243,1134,4860,19683,76545,288684,1062882,3838185,13640319,47829690,165809592,569173311,1937102445,6543101592,21953827710,73222472421,242912646603,801960412230,2636009007156,8629791392475,28148810469273,91507169819844
mov $2,$0
add $0,4
mov $1,1
add $2,1
mov $3,3
lpb $0,1
sub $0,1
add $1,$3
mul $2,3
mov $3,2
lpe
sub $1,2
mul $1,$2
add $1,11
mul $1,2
sub $1,1318
div $1,648
mul $1,3
add $1,6
|
#include <QtWidgets>
#include "vdeletenotebookdialog.h"
#include "vconfigmanager.h"
extern VConfigManager *g_config;
VDeleteNotebookDialog::VDeleteNotebookDialog(const QString &p_title,
const VNotebook *p_notebook,
QWidget *p_parent)
: QDialog(p_parent), m_notebook(p_notebook)
{
setupUI(p_title, m_notebook->getName());
}
void VDeleteNotebookDialog::setupUI(const QString &p_title, const QString &p_name)
{
QLabel *infoLabel = new QLabel(tr("Are you sure to delete notebook <span style=\"%1\">%2</span>?")
.arg(g_config->c_dataTextStyle).arg(p_name));
m_warningLabel = new QLabel();
m_warningLabel->setWordWrap(true);
m_deleteCheck = new QCheckBox(tr("Delete files from disk"), this);
m_deleteCheck->setChecked(false);
m_deleteCheck->setToolTip(tr("When checked, VNote will delete all files (including Recycle Bin) of this notebook from disk"));
connect(m_deleteCheck, &QCheckBox::stateChanged,
this, &VDeleteNotebookDialog::deleteCheckChanged);
deleteCheckChanged(false);
// Ok is the default button.
m_btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(m_btnBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(m_btnBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
QPushButton *okBtn = m_btnBox->button(QDialogButtonBox::Ok);
okBtn->setProperty("DangerBtn", true);
// Standard Warning icon.
QLabel *iconLabel = new QLabel();
QPixmap pixmap = standardIcon(QMessageBox::Warning);
if (pixmap.isNull()) {
iconLabel->hide();
} else {
iconLabel->setPixmap(pixmap);
}
QVBoxLayout *iconLayout = new QVBoxLayout();
iconLayout->addStretch();
iconLayout->addWidget(iconLabel);
iconLayout->addStretch();
QVBoxLayout *infoLayout = new QVBoxLayout();
infoLayout->addWidget(infoLabel);
infoLayout->addWidget(m_deleteCheck);
infoLayout->addWidget(m_warningLabel);
QHBoxLayout *topLayout = new QHBoxLayout();
topLayout->addLayout(iconLayout);
topLayout->addLayout(infoLayout);
QVBoxLayout *mainLayout = new QVBoxLayout();
mainLayout->addLayout(topLayout);
mainLayout->addWidget(m_btnBox);
setLayout(mainLayout);
mainLayout->setSizeConstraint(QLayout::SetFixedSize);
setWindowTitle(p_title);
}
bool VDeleteNotebookDialog::getDeleteFiles() const
{
return m_deleteCheck->isChecked();
}
QPixmap VDeleteNotebookDialog::standardIcon(QMessageBox::Icon p_icon)
{
QStyle *style = this->style();
int iconSize = style->pixelMetric(QStyle::PM_MessageBoxIconSize, 0, this);
QIcon tmpIcon;
switch (p_icon) {
case QMessageBox::Information:
tmpIcon = style->standardIcon(QStyle::SP_MessageBoxInformation, 0, this);
break;
case QMessageBox::Warning:
tmpIcon = style->standardIcon(QStyle::SP_MessageBoxWarning, 0, this);
break;
case QMessageBox::Critical:
tmpIcon = style->standardIcon(QStyle::SP_MessageBoxCritical, 0, this);
break;
case QMessageBox::Question:
tmpIcon = style->standardIcon(QStyle::SP_MessageBoxQuestion, 0, this);
break;
default:
break;
}
if (!tmpIcon.isNull()) {
QWindow *window = this->windowHandle();
if (!window) {
if (const QWidget *nativeParent = this->nativeParentWidget()) {
window = nativeParent->windowHandle();
}
}
return tmpIcon.pixmap(window, QSize(iconSize, iconSize));
}
return QPixmap();
}
void VDeleteNotebookDialog::deleteCheckChanged(int p_state)
{
if (!p_state) {
m_warningLabel->setText(tr("VNote won't delete files in directory <span style=\"%1\">%2</span>.")
.arg(g_config->c_dataTextStyle).arg(m_notebook->getPath()));
} else {
m_warningLabel->setText(tr("<span style=\"%1\">WARNING</span>: "
"VNote may delete <b>ANY</b> files in directory <span style=\"%2\">%3</span> "
"and directory <span style=\"%2\">%4</span>!<br>"
"VNote will try to delete all the root folders within this notebook one by one.<br>"
"It may be UNRECOVERABLE!")
.arg(g_config->c_warningTextStyle)
.arg(g_config->c_dataTextStyle)
.arg(m_notebook->getPath())
.arg(m_notebook->getRecycleBinFolderPath()));
}
}
|
%ifdef CONFIG
{
"Match": "All",
"RegData": {
"RAX": "0x20"
}
}
%endif
mov rax, 32
; patch mov rax,... to nops
mov byte [rel patched_op + 0], 0x90
mov byte [rel patched_op + 1], 0x90
mov byte [rel patched_op + 2], 0x90
mov byte [rel patched_op + 3], 0x90
mov byte [rel patched_op + 4], 0x90
mov byte [rel patched_op + 5], 0x90
mov byte [rel patched_op + 6], 0x90
mov byte [rel patched_op + 7], 0x90
mov byte [rel patched_op + 8], 0x90
mov byte [rel patched_op + 9], 0x90
patched_op:
mov rax,0xFABCFABCFABC0123 ; 10 bytes long
hlt |
db DEX_ELECTRODE ; pokedex id
db 60 ; base hp
db 50 ; base attack
db 70 ; base defense
db 150 ; base speed
db 80 ; base special
db ELECTRIC ; species type 1
db ELECTRIC ; species type 2
db 58 ; catch rate
db 150 ; base exp yield
INCBIN "pic/ymon/electrode.pic",0,1 ; 55, sprite dimensions
dw ElectrodePicFront
dw ElectrodePicBack
; attacks known at lvl 0
db TACKLE
db SCREECH
db SONICBOOM
db 0
db 0 ; growth rate
; learnset
tmlearn 6
tmlearn 9,15
tmlearn 20,24
tmlearn 25,30,31,32
tmlearn 33,34,36,39,40
tmlearn 44,45,47
tmlearn 50,55
db BANK(ElectrodePicFront)
|
// Copyright 2017-2018 Chabloom LC
//
// 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 "_vulkan.h"
VKAPI_ATTR void VKAPI_CALL vkDestroyShaderModule(
VkDevice device,
VkShaderModule shaderModule,
const VkAllocationCallbacks* pAllocator)
{
if (pAllocator)
{
pAllocator->pfnFree(nullptr, shaderModule);
}
else
{
delete shaderModule;
}
shaderModule = nullptr;
}
|
; A205136: Ordered differences of distinct pentagonal numbers.
; Submitted by Jon Maiga
; 4,11,7,21,17,10,34,30,23,13,50,46,39,29,16,69,65,58,48,35,19,91,87,80,70,57,41,22,116,112,105,95,82,66,47,25,144,140,133,123,110,94,75,53,28,175,171,164,154,141,125,106,84,59,31,209,205,198,188,175
lpb $0
add $1,1
sub $0,$1
lpe
sub $1,$0
mul $0,6
add $0,$1
add $0,8
add $0,$1
add $0,$1
mul $1,$0
add $0,$1
div $0,2
|
; *******************************************************************************************
; *******************************************************************************************
;
; Name : inttostr.asm
; Purpose : Convert integer to string.
; Date : 13th August 2019
; Author : Paul Robson (paul@robsons.org.uk)
;
; *******************************************************************************************
; *******************************************************************************************
; *******************************************************************************************
;
; Convert integer in A_Mantissa to ASCII String at Num_Buffer[NumBufX]
;
; *******************************************************************************************
INTToString:
pha
phx
phy
lda A_Mantissa+3 ; check -ve
bpl _ITSNotMinus
lda #"-" ; output a minus
jsr ITSOutputCharacter
ldx #0
jsr FPUIntegerNegateX
_ITSNotMinus:
ldx #0 ; X is offset in table.
stx NumSuppress ; clear the suppression flag.
_ITSNextSubtractor:
ldy #0 ; Y is count.
_ITSSubtract:
sec
lda A_Mantissa ; subtract number and push on stack
sbc _ITSSubtractors+0,x
pha
lda A_Mantissa+1
sbc _ITSSubtractors+1,x
pha
lda A_Mantissa+2
sbc _ITSSubtractors+2,x
pha
lda A_Mantissa+3
sbc _ITSSubtractors+3,x
bcc _ITSCantSubtract ; if CC, then gone too far.
;
sta A_Mantissa+3 ; save subtract off stack
pla
sta A_Mantissa+2
pla
sta A_Mantissa+1
pla
sta A_Mantissa+0
;
iny ; bump count.
bra _ITSSubtract ; go round again.
;
_ITSCantSubtract:
pla ; throw away interim answers
pla
pla
cpy #0 ; if not zero then no suppression check
bne _ITSOutputDigit
bit NumSuppress ; if suppression check +ve (e.g. zero)
bpl _ITSGoNextSubtractor
_ITSOutputDigit:
dec NumSuppress ; suppression check will be -ve.
tya ; count of subtractions
ora #"0" ; make ASCII
jsr ITSOutputCharacter ; output it.
;
_ITSGoNextSubtractor:
inx ; next dword
inx
inx
inx
cpx #_ITSSubtractorsEnd-_ITSSubtractors
bne _ITSNextSubtractor ; do all the subtractors.
lda A_Mantissa ; and the last digit is left.
ora #"0"
jsr ITSOutputCharacter
ply ; and exit
plx
pla
rts
;
; Powers of 10 table.
;
_ITSSubtractors:
.dword 1000000000
.dword 100000000
.dword 10000000
.dword 1000000
.dword 100000
.dword 10000
.dword 1000
.dword 100
.dword 10
_ITSSubtractorsEnd:
; *******************************************************************************************
;
; Output A to Number output buffer
;
; *******************************************************************************************
ITSOutputCharacter:
pha
phx
ldx NumBufX ; save digit
sta Num_Buffer,x
lda #0 ; follow by trailing NULL
sta Num_Buffer+1,x
inc NumBufX ; bump pointer.
plx
pla
rts
|
; A034326: Hours struck by a clock.
; 1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9
mov $1,$0
mod $1,12
add $1,1
|
; A006368: The "amusical permutation" of the nonnegative numbers: a(2n)=3n, a(4n+1)=3n+1, a(4n-1)=3n-1.
; 0,1,3,2,6,4,9,5,12,7,15,8,18,10,21,11,24,13,27,14,30,16,33,17,36,19,39,20,42,22,45,23,48,25,51,26,54,28,57,29,60,31,63,32,66,34,69,35,72,37,75,38,78,40,81,41,84,43,87,44,90,46,93,47,96,49,99,50,102,52,105,53,108,55,111,56,114,58,117,59,120,61,123,62,126,64,129,65,132,67,135,68,138,70,141,71,144,73,147,74,150,76,153,77,156,79,159,80,162,82,165,83,168,85,171,86,174,88,177,89,180,91,183,92,186,94,189,95,192,97,195,98,198,100,201,101,204,103,207,104,210,106,213,107,216,109,219,110,222,112,225,113,228,115,231,116,234,118,237,119,240,121,243,122,246,124,249,125,252,127,255,128,258,130,261,131,264,133,267,134,270,136,273,137,276,139,279,140,282,142,285,143,288,145,291,146,294,148,297,149,300,151,303,152,306,154,309,155,312,157,315,158,318,160,321,161,324,163,327,164,330,166,333,167,336,169,339,170,342,172,345,173,348,175,351,176,354,178,357,179,360,181,363,182,366,184,369,185,372,187
mov $1,$0
gcd $1,2
mul $1,$0
mul $1,6
add $1,10
div $1,8
sub $1,1
|
; A175887: Numbers that are congruent to {1, 14} mod 15.
; 1,14,16,29,31,44,46,59,61,74,76,89,91,104,106,119,121,134,136,149,151,164,166,179,181,194,196,209,211,224,226,239,241,254,256,269,271,284,286,299,301,314,316,329,331,344,346,359,361,374,376,389,391,404,406,419,421,434,436,449,451,464,466,479,481,494,496,509,511,524,526,539,541,554,556,569,571,584,586,599,601,614,616,629,631,644,646,659,661,674,676,689,691,704,706,719,721,734,736,749
mov $1,13
mul $1,$0
div $0,2
mul $0,11
add $1,1
sub $1,$0
mov $0,$1
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php.
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
; SetMem32.asm
;
; Abstract:
;
; SetMem32 function
;
; Notes:
;
;------------------------------------------------------------------------------
.686
.model flat,C
.mmx
.code
;------------------------------------------------------------------------------
; VOID *
; EFIAPI
; InternalMemSetMem32 (
; IN VOID *Buffer,
; IN UINTN Count,
; IN UINT32 Value
; );
;------------------------------------------------------------------------------
InternalMemSetMem32 PROC
mov eax, [esp + 4] ; eax <- Buffer as return value
mov ecx, [esp + 8] ; ecx <- Count
movd mm0, dword ptr [esp + 12] ; mm0 <- Value
shr ecx, 1 ; ecx <- number of qwords to set
mov edx, eax ; edx <- Buffer
jz @SetDwords
movq mm1, mm0
psllq mm1, 32
por mm0, mm1
@@:
movq qword ptr [edx], mm0
lea edx, [edx + 8] ; use "lea" to avoid change in flags
loop @B
@SetDwords:
jnc @F
movd dword ptr [edx], mm0
@@:
ret
InternalMemSetMem32 ENDP
END
|
#define BOOST_TEST_MODULE Amerios Test Suite
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include "db.h"
#include "txdb.h"
#include "main.h"
#include "wallet.h"
#include "util.h"
CWallet* pwalletMain;
CClientUIInterface uiInterface;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
CCoinsViewDB *pcoinsdbview;
boost::filesystem::path pathTemp;
boost::thread_group threadGroup;
TestingSetup() {
fPrintToDebugger = true; // don't want to write to debug.log file
noui_connect();
bitdb.MakeMock();
pathTemp = GetTempPath() / strprintf("test_amerios_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
boost::filesystem::create_directories(pathTemp);
mapArgs["-datadir"] = pathTemp.string();
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
InitBlockIndex();
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterWallet(pwalletMain);
nScriptCheckThreads = 3;
for (int i=0; i < nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
}
~TestingSetup()
{
threadGroup.interrupt_all();
threadGroup.join_all();
delete pwalletMain;
pwalletMain = NULL;
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
bitdb.Flush(true);
boost::filesystem::remove_all(pathTemp);
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
|
; A011853: [ binomial(n,7)/7 ].
; 0,0,0,0,0,0,0,0,1,5,17,47,113,245,490,919,1634,2778,4546,7198,11074,16611,24363,35022,49443,68671,93971,126861,169148,222968,290828,375653,480836,610292,768516,960645
bin $0,7
div $0,7
|
SECTION data_clib
PUBLIC __mc1000_mode
__mc1000_mode: defb 0x00 ; lores mode 0x9e ;hires mode
|
; New gets library function for the monitor: development testbed
; Works together with c/test_programs/gets_test.c and therefore
; starts at 0xE000. Load this program first, before executing gets_test.c
;
; gets_test.c expects the following 4 words as a "magic" at 0xE000:
; 0xFF90, 0x0016, 0x2309, 0x1976
; It further expects the entry point of GETS to be 0xE004
;
; done by sy2002 in October 2016
; enhanced by sy2002 to support gets_s and gets_slf in December 2016
#include "../dist_kit/sysdef.asm"
#include "../dist_kit/monitor.def"
.ORG 0xE000
SYSCALL(exit, 1) ; 0xE000: 0xFF90 0x0016
.DW 0x2309, 0x1976 ; 0xE002: 0x2309 0x1976
; 0xE004: GETS entry for gets_test.c
;===================== REUSABLE CODE FOR MONITOR STARTS HERE =================
;
;***************************************************************************************
;* IO$GETS reads a zero terminated string from STDIN and echos typing on STDOUT
;*
;* ALWAYS PREFER IO$GETS_S OVER THIS FUNCTION!
;*
;* It accepts CR, LF and CR/LF as input terminator, so it directly works with various
;* terminal settings on UART and also with keyboards on PS/2 ("USB"). Furtheron, it
;* accepts BACKSPACE for editing the string.
;*
;* R8 has to point to a preallocated memory area to store the input line
;***************************************************************************************
;
IO$GETS MOVE R9, @--SP ; save original R9
MOVE R10, @--SP ; save original R10
XOR R9, R9 ; R9 = 0: unlimited chars
XOR R10, R10 ; R10 = 0: no LF at end of str.
RSUB IO$GETS_CORE, 1 ; get the unlimited string
MOVE @SP++, R10 ; restore original R10
MOVE @SP++, R9 ; restore original R9
RET
;
;***************************************************************************************
;* IO$GETS_S reads a zero terminated string from STDIN into a buffer with a
;* specified maximum size and echos typing on STDOUT
;*
;* It accepts CR, LF and CR/LF as input terminator, so it directly works with various
;* terminal settings on UART and also with keyboards on PS/2 ("USB"). Furtheron, it
;* accepts BACKSPACE for editing the string.
;*
;* A maximum amount of (R9 - 1) characters will be read, because the function will
;* add the zero terminator to the string, which then results in R9 words.
;*
;* R8 has to point to a preallocated memory area to store the input line
;* R9 specifies the size of the buffer, so (R9 - 1) characters can be read;
;* if R9 == 0, then an unlimited amount of characters is being read
;***************************************************************************************
;
IO$GETS_S MOVE R10, @--SP ; save original R10
XOR R10, R10 ; R10 = 0: no LF at end of str.
RSUB IO$GETS_CORE, 1 ; get string
MOVE @SP++, R10 ; restore original R10
RET
;
;***************************************************************************************
;* IO$GETS_SLF reads a zero terminated string from STDIN into a buffer with a specified
;* maximum size and echos typing on STDOUT. A line feed character is added
;* to the string in case the function is ended not "prematurely" by
;* reaching the buffer size, but by pressing CR or LF or CR/LF.
;*
;* It accepts CR, LF and CR/LF as input terminator, so it directly works with various
;* terminal settings on UART and also with keyboards on PS/2 ("USB"). Furtheron, it
;* accepts BACKSPACE for editing the string.
;*
;* A maximum amount of (R9 - 1) characters will be read, because the function will
;* add the zero terminator to the string, which then results in R9 words.
;*
;* R8 has to point to a preallocated memory area to store the input line
;* R9 specifies the size of the buffer, so (R9 - 1) characters can be read;
;* if R9 == 0, then an unlimited amount of characters is being read
;***************************************************************************************
;
IO$GETS_SLF MOVE R10, @--SP ; save original R10
MOVE 1, R10 ; R10 = 1: add LF, if the function
; ends regularly, i.e. by a key
; stroke (LF, CR or CR/LF)
RSUB IO$GETS_CORE, 1 ; get string
MOVE @SP++, R10 ; restore original R10
RET
;
;***************************************************************************************
;* IO$GETS_CORE implements the various gets variants.
;*
;* Refer to the comments for IO$GETS, IO$GET_S and IO$GET_SLF
;*
;* R8 has to point to a preallocated memory area to store the input line
;* R9 specifies the size of the buffer, so (R9 - 1) characters can be read;
;* if R9 == 0, then an unlimited amount of characters is being read
;* R10 specifies the LF behaviour: R10 = 0 means never add LF, R10 = 1 means: add a
;* LF when the input is ended by a key stroke (LF, CR or CR/LF) in contrast to
;* automatically ending due to a full buffer
;***************************************************************************************
;
IO$GETS_CORE INCRB
MOVE R10, @--SP ; save original R10
MOVE R11, @--SP ; save original R11
MOVE R12, @--SP ; save original R12
MOVE R10, R12 ; R12 = add LF flag
XOR R11, R11 ; R11 = character counter = 0
MOVE R9, R10 ; R10 = max characters
SUB 1, R10 ; R10 = R9 - 1 characters
MOVE R8, R0 ; save original R8
MOVE R8, R1 ; R1 = working pointer
_IO$GETS_LOOP CMP R9, 0 ; unlimited characters?
RBRA _IO$GETS_GETC, Z ; yes
CMP R11, R10 ; buffer size - 1 reached?
RBRA _IO$GETS_ZT, Z ; yes: add zero terminator
ADD 1, R11 ; no: next character
_IO$GETS_GETC SYSCALL(getc, 1) ; get char from STDIN
CMP R8, 0x000D ; accept CR as line end
RBRA _IO$GETS_CR, Z
CMP R8, 0x000A ; accept LF as line end
RBRA _IO$GETS_LF, Z
CMP R8, 0x0008 ; use BACKSPACE for editing
RBRA _IO$GETS_BS, Z
CMP R8, 0x007F ; treat DEL key as BS, e.g. for ..
RBRA _IO$GETS_DEL, Z ; .. MAC compatibility in EMU
_IO$GETS_ADDBUF MOVE R8, @R1++ ; store char to buffer
_IO$GETS_ECHO SYSCALL(putc, 1) ; echo char on STDOUT
RBRA _IO$GETS_LOOP, 1 ; next character
_IO$GETS_LF CMP R12, 0 ; evaluate LF flag
RBRA _IO$GETS_ZT, Z ; 0 = do not add LF flag
MOVE 0x000A, @R1++ ; add LF
_IO$GETS_ZT MOVE 0, @R1 ; add zero terminator
MOVE R0, R8 ; restore original R8
MOVE @SP++, R12 ; restore original R12
MOVE @SP++, R11 ; restore original R11
MOVE @SP++, R10 ; restore original R10
DECRB
RET
; For also accepting CR/LF, we need to do a non-blocking
; check on STDIN, if there is another character waiting.
; IO$GETCHAR is a blocking call, so we cannot use it here.
; STDIN = UART, if bit #0 of IO$SWITCH_REG = 0, otherwise
; STDIN = PS/2 ("USB") keyboard
;
; At a terminal speed of 115200 baud = 14.400 chars/sec
; (for being save, let us assume only 5.000 chars/sec)
; and a CPU frequency of 50 MHz we need to wait about
; 10.000 CPU cycles until we check, if the terminal program
; did send one other character. The loop at GETS_CR_WAIT
; costs about 7 cycles per iteration, so we loop (rounded up)
; 2.000 times.
; As a simplification, we assume the same waiting time
; for a PS/2 ("USB") keyboard
_IO$GETS_CR MOVE 2000, R3 ; CPU speed vs. transmit speed
_IO$GETS_CRWAIT SUB 1, R3
RBRA _IO$GETS_CRWAIT, !Z
MOVE IO$SWITCH_REG, R2 ; read the switch register
MOVE @R2, R2
AND 0x0001, R2 ; lowest bit set?
RBRA _IO$GETS_CRUART, Z ; no: read from UART
MOVE IO$KBD_STATE, R2 ; read the keyboard status reg.
MOVE @R2, R2
AND 0x0001, R2 ; char waiting/lowest bit set?
RBRA _IO$GETS_LF, Z ; no: then add zero term. and ret.
MOVE IO$KBD_DATA, R2 ; yes: read waiting character
MOVE @R2, R2
RBRA _IO$GETS_CR_LF, 1 ; check for LF
_IO$GETS_CRUART MOVE IO$UART_SRA, R2 ; read UART status register
MOVE @R2, R2
AND 0x0001, R2 ; is there a character waiting?
RBRA _IO$GETS_LF, Z ; no: then add zero term. and ret.
MOVE IO$UART_RHRA, R2 ; yes: read waiting character
MOVE @R2, R2
_IO$GETS_CR_LF CMP R2, 0x000A ; is it a LF (so we have CR/LF)?
RBRA _IO$GETS_LF, Z ; yes: then add zero trm. and ret.
; it is CR/SOMETHING, so add both: CR and "something" to
; the string and go on waiting for input, but only of the
; buffer is large enough. Otherwise only add CR.
MOVE 0x000D, @R1++ ; add CR
CMP R9, 0 ; unlimited characters?
RBRA _IO$GETS_CRSS, Z ; yes: go on and add SOMETHING
CMP R11, R10 ; buffer size - 1 reached?
RBRA _IO$GETS_ZT, Z ; yes: add zero terminator and end
ADD 1, R11 ; increase amount of stored chars
_IO$GETS_CRSS MOVE R2, R8 ; no: prepare to add SOMETHING
RBRA _IO$GETS_ADDBUF, 1 ; add it to buffer and go on
; handle BACKSPACE for editing and accept DEL as alias for BS
;
; For STDOUT = UART it is kind of trivial, because you "just"
; need to rely on the fact, that the terminal settings are
; correct and then the terminal program takes care of the
; nitty gritty details like moving the cursor and scrolling.
;
; For STDOUT = VGA, this needs to be done manually by this
; routine.
_IO$GETS_DEL MOVE 0x0008, R8 ; treat DEL as BS
_IO$GETS_BS SUB 1, R11 ; do not count DEL/BS character
CMP R0, R1 ; beginning of string?
RBRA _IO$GETS_LOOP, Z ; yes: ignore BACKSPACE key
SUB 1, R1 ; delete last char in memory
SUB 1, R11 ; do not count last char in mem.
MOVE IO$SWITCH_REG, R2 ; read the switch register
MOVE @R2, R2
AND 0x0002, R2 ; bit #1 set?
RBRA _IO$GETS_ECHO, Z ; no: STDOUT = UART: just echo
MOVE VGA$CR_X, R2 ; R2: HW X-register
MOVE VGA$CR_Y, R3 ; R3: HW Y-register
MOVE VGA$CHAR, R4 ; R4: HW put/get character reg.
MOVE _VGA$X, R5 ; R5: SW X-register
MOVE _VGA$Y, R6 ; R6: SW Y-register
CMP @R2, 0 ; cursor already at leftmost pos.?
RBRA _IO$GETS_BSLUP, Z ; yes: scroll one line up
SUB 1, @R2 ; cursor one position to the left
SUB 1, @R5
_IO$GETS_BSX MOVE 0x0020, @R4 ; delete char on the screen
RBRA _IO$GETS_LOOP, 1 ; next char/key
_IO$GETS_BSLUP CMP @R3, VGA$MAX_Y ; cursor already bottom line?
RBRA _IO$GETS_BSSUP, Z ; yes: scroll screen up
SUB 1, @R3 ; cursor one line up
SUB 1, @R6
_IO$GETS_BSXLU MOVE VGA$MAX_X, @R2 ; cursor to the rightpost pos.
MOVE VGA$MAX_X, @R5
RBRA _IO$GETS_BSX, 1 ; delete char on screen and go on
_IO$GETS_BSSUP MOVE VGA$OFFS_DISPLAY, R7 ; if RW > DISP then do not
MOVE VGA$OFFS_RW, R8 ; scroll up the screen
CMP @R8, @R7 ; see VGA$SCROLL_UP_1 for
RBRA _IO$GETS_BSUPSP, N ; an explanation
SUB VGA$CHARS_PER_LINE, @R7 ; do the visual scrolling
_IO$GETS_BSUPSP SUB VGA$CHARS_PER_LINE, @R8 ; scroll the RW window
CMP @R7, @R8 ; if after the scrolling
RBRA _IO$GETS_NOCRS, !Z ; RW = DISP then show
MOVE VGA$STATE, R8 ; the cursor
OR VGA$EN_HW_CURSOR, @R8
_IO$GETS_NOCRS MOVE VGA$MAX_Y, @R3 ; cursor to bottom
MOVE VGA$MAX_Y, @R6
RBRA _IO$GETS_BSXLU, 1 ; cursor to rightmost pos.
;===================== REUSABLE CODE FOR MONITOR ENDS HERE ===================
#include "../monitor/variables.asm"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.