text stringlengths 1 1.05M |
|---|
; A126587: a(n) is the number of integer lattice points inside the right triangle with legs 3n and 4n (and hypotenuse 5n).
; 3,17,43,81,131,193,267,353,451,561,683,817,963,1121,1291,1473,1667,1873,2091,2321,2563,2817,3083,3361,3651,3953,4267,4593,4931,5281,5643,6017,6403,6801,7211,7633,8067,8513,8971,9441,9923,10417,10923,11441,11971,12513,13067,13633,14211,14801,15403,16017,16643,17281,17931,18593,19267,19953,20651,21361,22083,22817,23563,24321,25091,25873,26667,27473,28291,29121,29963,30817,31683,32561,33451,34353,35267,36193,37131,38081,39043,40017,41003,42001,43011,44033,45067,46113,47171,48241,49323,50417,51523,52641,53771,54913,56067,57233,58411,59601,60803,62017,63243,64481,65731,66993,68267,69553,70851,72161,73483,74817,76163,77521,78891,80273,81667,83073,84491,85921,87363,88817,90283,91761,93251,94753,96267,97793,99331,100881,102443,104017,105603,107201,108811,110433,112067,113713,115371,117041,118723,120417,122123,123841,125571,127313,129067,130833,132611,134401,136203,138017,139843,141681,143531,145393,147267,149153,151051,152961,154883,156817,158763,160721,162691,164673,166667,168673,170691,172721,174763,176817,178883,180961,183051,185153,187267,189393,191531,193681,195843,198017,200203,202401,204611,206833,209067,211313,213571,215841,218123,220417,222723,225041,227371,229713,232067,234433,236811,239201,241603,244017,246443,248881,251331,253793,256267,258753,261251,263761,266283,268817,271363,273921,276491,279073,281667,284273,286891,289521,292163,294817,297483,300161,302851,305553,308267,310993,313731,316481,319243,322017,324803,327601,330411,333233,336067,338913,341771,344641,347523,350417,353323,356241,359171,362113,365067,368033,371011,374001
mov $1,6
mul $1,$0
add $1,8
mul $1,$0
add $1,3
|
%include "include/u7bg-all-includes.asm"
defineAddress seg_dseg, 0x0B00, cheatMenuTimeFormat
defineAddress seg_dseg, 0x0B0E, cheatMenuTimeFormat_end
[bits 16]
startPatch EXE_LENGTH, itemLabels
startBlockAt addr_cheatMenuTimeFormat
db '%s %d:%02d %s', 0
endBlockAt off_cheatMenuTimeFormat_end
endPatch
|
/*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "oneflow/core/framework/framework.h"
#include "oneflow/user/kernels/copy_data_content_kernel.h"
namespace oneflow {
#define REGISTER_EXPAND_DIMS_KERNEL(D) \
REGISTER_USER_KERNEL("expand_dims") \
.SetCreateFn<CopyDataContentKernel<DeviceType::D>>() \
.SetIsMatchedHob(user_op::HobDeviceType() == DeviceType::D) \
.SetInplaceProposalFn([](const user_op::InferContext&, \
user_op::AddInplaceArgPair AddInplaceArgPairFn) -> Maybe<void> { \
OF_RETURN_IF_ERROR(AddInplaceArgPairFn("out", 0, "in", 0, false)); \
return Maybe<void>::Ok(); \
});
REGISTER_EXPAND_DIMS_KERNEL(kCPU)
#ifdef WITH_CUDA
REGISTER_EXPAND_DIMS_KERNEL(kGPU)
#endif
} // namespace oneflow
|
dnl Alpha EV5 mpn_lshift -- Shift a number left.
dnl Copyright 1994, 1995, 2000, 2003 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of the GNU Lesser General Public License as published
dnl by the Free Software Foundation; either version 3 of the License, or (at
dnl your option) any later version.
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
dnl License for more details.
dnl You should have received a copy of the GNU Lesser General Public License
dnl along with the GNU MP Library. If not, see http://www.gnu.org/licenses/.
include(`../config.m4')
C cycles/limb
C EV4: ?
C EV5: 3.25
C EV6: 1.75
C INPUT PARAMETERS
C rp r16
C up r17
C n r18
C cnt r19
ASM_START()
PROLOGUE(mpn_lshift)
s8addq r18,r17,r17 C make r17 point at end of s1
ldq r4,-8(r17) C load first limb
subq r31,r19,r20
s8addq r18,r16,r16 C make r16 point at end of RES
subq r18,1,r18
and r18,4-1,r28 C number of limbs in first loop
srl r4,r20,r0 C compute function result
beq r28,$L0
subq r18,r28,r18
ALIGN(8)
$Loop0: ldq r3,-16(r17)
subq r16,8,r16
sll r4,r19,r5
subq r17,8,r17
subq r28,1,r28
srl r3,r20,r6
bis r3,r3,r4
bis r5,r6,r8
stq r8,0(r16)
bne r28,$Loop0
$L0: sll r4,r19,r24
beq r18,$Lend
C warm up phase 1
ldq r1,-16(r17)
subq r18,4,r18
ldq r2,-24(r17)
ldq r3,-32(r17)
ldq r4,-40(r17)
beq r18,$Lend1
C warm up phase 2
srl r1,r20,r7
sll r1,r19,r21
srl r2,r20,r8
ldq r1,-48(r17)
sll r2,r19,r22
ldq r2,-56(r17)
srl r3,r20,r5
bis r7,r24,r7
sll r3,r19,r23
bis r8,r21,r8
srl r4,r20,r6
ldq r3,-64(r17)
sll r4,r19,r24
ldq r4,-72(r17)
subq r18,4,r18
beq r18,$Lend2
ALIGN(16)
C main loop
$Loop: stq r7,-8(r16)
bis r5,r22,r5
stq r8,-16(r16)
bis r6,r23,r6
srl r1,r20,r7
subq r18,4,r18
sll r1,r19,r21
unop C ldq r31,-96(r17)
srl r2,r20,r8
ldq r1,-80(r17)
sll r2,r19,r22
ldq r2,-88(r17)
stq r5,-24(r16)
bis r7,r24,r7
stq r6,-32(r16)
bis r8,r21,r8
srl r3,r20,r5
unop C ldq r31,-96(r17)
sll r3,r19,r23
subq r16,32,r16
srl r4,r20,r6
ldq r3,-96(r17)
sll r4,r19,r24
ldq r4,-104(r17)
subq r17,32,r17
bne r18,$Loop
C cool down phase 2/1
$Lend2: stq r7,-8(r16)
bis r5,r22,r5
stq r8,-16(r16)
bis r6,r23,r6
srl r1,r20,r7
sll r1,r19,r21
srl r2,r20,r8
sll r2,r19,r22
stq r5,-24(r16)
bis r7,r24,r7
stq r6,-32(r16)
bis r8,r21,r8
srl r3,r20,r5
sll r3,r19,r23
srl r4,r20,r6
sll r4,r19,r24
C cool down phase 2/2
stq r7,-40(r16)
bis r5,r22,r5
stq r8,-48(r16)
bis r6,r23,r6
stq r5,-56(r16)
stq r6,-64(r16)
C cool down phase 2/3
stq r24,-72(r16)
ret r31,(r26),1
C cool down phase 1/1
$Lend1: srl r1,r20,r7
sll r1,r19,r21
srl r2,r20,r8
sll r2,r19,r22
srl r3,r20,r5
bis r7,r24,r7
sll r3,r19,r23
bis r8,r21,r8
srl r4,r20,r6
sll r4,r19,r24
C cool down phase 1/2
stq r7,-8(r16)
bis r5,r22,r5
stq r8,-16(r16)
bis r6,r23,r6
stq r5,-24(r16)
stq r6,-32(r16)
stq r24,-40(r16)
ret r31,(r26),1
$Lend: stq r24,-8(r16)
ret r31,(r26),1
EPILOGUE(mpn_lshift)
ASM_END()
|
; A157999: 338n - 1.
; 337,675,1013,1351,1689,2027,2365,2703,3041,3379,3717,4055,4393,4731,5069,5407,5745,6083,6421,6759,7097,7435,7773,8111,8449,8787,9125,9463,9801,10139,10477,10815,11153,11491,11829,12167,12505,12843,13181,13519,13857,14195,14533,14871,15209,15547,15885,16223,16561,16899,17237,17575,17913,18251,18589,18927,19265,19603,19941,20279,20617,20955,21293,21631,21969,22307,22645,22983,23321,23659,23997,24335,24673,25011,25349,25687,26025,26363,26701,27039,27377,27715,28053,28391,28729,29067,29405,29743,30081,30419,30757,31095,31433,31771,32109,32447,32785,33123,33461,33799,34137,34475,34813,35151,35489,35827,36165,36503,36841,37179,37517,37855,38193,38531,38869,39207,39545,39883,40221,40559,40897,41235,41573,41911,42249,42587,42925,43263,43601,43939,44277,44615,44953,45291,45629,45967,46305,46643,46981,47319,47657,47995,48333,48671,49009,49347,49685,50023,50361,50699,51037,51375,51713,52051,52389,52727,53065,53403,53741,54079,54417,54755,55093,55431,55769,56107,56445,56783,57121,57459,57797,58135,58473,58811,59149,59487,59825,60163,60501,60839,61177,61515,61853,62191,62529,62867,63205,63543,63881,64219,64557,64895,65233,65571,65909,66247,66585,66923,67261,67599,67937,68275,68613,68951,69289,69627,69965,70303,70641,70979,71317,71655,71993,72331,72669,73007,73345,73683,74021,74359,74697,75035,75373,75711,76049,76387,76725,77063,77401,77739,78077,78415,78753,79091,79429,79767,80105,80443,80781,81119,81457,81795,82133,82471,82809,83147,83485,83823,84161,84499
mov $1,$0
mul $1,338
add $1,337
|
.model flat,c
; There are difined in IntegerAddition.h
extern GlChar:byte
extern GlShort:word
extern GlInt:dword
extern GlLongLong:qword
; extern "C" void IntegerAdd_(char a, short b, int c, long long d);
;
; Description: Addition using various-sized integers
;
; Return: None.
.code
IntegerAdd_ proc
; Function prolog
push ebp
mov ebp,esp
; Compute GlChar += a
mov al,[ebp+8]
add [GlChar],al
; Compute GlShort += b, note offset of 'b' on starck
mov ax,[ebp+12]
add [GlShort],ax
; Compute GlInt += c, note offset of 'c' on stack
mov eax,[ebp+16]
add [GlInt],eax
; Compute GlLongLong += d, note use of dword ptr operator and adc
mov eax, [ebp+20]
mov edx,[ebp+14]
add dword ptr [GlLongLong],eax
adc dword ptr [GlLongLong],edx
; Function epilog
pop ebp
ret
IntegerAdd_ endp
end
|
; A313276: Coordination sequence Gal.6.265.2 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.
; Submitted by Jamie Morken(s2)
; 1,4,9,15,21,25,29,33,39,45,50,54,58,63,69,75,79,83,87,93,99,104,108,112,117,123,129,133,137,141,147,153,158,162,166,171,177,183,187,191,195,201,207,212,216,220,225,231,237,241
mov $1,$0
add $0,1
add $0,$1
add $0,1
mov $2,$1
mov $3,$1
mul $1,2
sub $1,3
trn $3,1
add $0,$3
add $0,4
lpb $1
add $0,$1
sub $0,1
trn $1,5
sub $0,$1
add $0,1
trn $1,6
lpe
lpb $2
add $0,1
sub $2,1
lpe
sub $0,5
|
/*
* Copyright 2007-2009 TIM/ETI University of Geneva.
* All Rights Reserved. Use is subject to license terms.
*
* File: RtpTransceiver.cpp
* Author: Nikos Tsourakis <Nikolaos.Tsourakis@unige.ch>
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*/
#include <limits.h>
#include <string.h>
#include <iostream>
#include "RtpTransceiver.hpp"
#include "ace/Log_Msg.h"
//#include "core-rand-gen.hpp"
#include <vector>
using namespace std;
vector<RTPPacket> Packets;
//vector<RTPPacket> Packets2;
int counter = 0;
// Helper classes and functions.
class RTPPacketEx : public RTPPacket
{
public:
RTPPacketEx (const Uint8* data, Uint32 size)
{
m_data.Replace(0, data, size);
return;
}
};
// Public variables.
static const RTPPayloadFormat s_payload_format = { 1, 20, 1, 0.0 };
// Helper functions
static long AbsInt(long value)
{
return (value < 0) ? -value : value;
}
static int CmpSeq(RTPSeqNumber s1,
RTPSeqNumber s2,
unsigned short thresh)
{
const int bnd(USHRT_MAX - thresh);
const int adj(USHRT_MAX + 1);
int diff(s1 - s2);
if (diff > bnd)
{
return diff - adj;
}
else if (diff < -bnd)
{
return diff + adj;
}
else
{
return diff;
}
}
static Uint32 GenerateRandom(void)
{
// NOTE: Should be seeded elsewhere..
Uint32 rnd = 0;
while (rnd == 0)
{
rnd = rand();
}
return rnd;
}
// Implementation of the 'RtpTransceiver' class.
RtpTransceiver::RtpTransceiver(RtpTransceiverObserver& observer)
: m_observer(observer),
m_ssrc(0),
m_payload_type(RTP_PAYLOAD_UNDEFINED),
m_payload_format(s_payload_format),
m_rx_limit(RTP_IN_BUFFER_SIZE),
m_tx_limit(RTP_OUT_BUFFER_SIZE)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::RtpTransceiver()]"));
ClearRxStats();
ClearTxStats();
CloneState();
m_server = "";
m_remote_port = 0;
m_local_port = 0;
m_socket_engine = NULL;
m_socket_engine = new SocketsEngine(*this);
// m_audiostream_engine = NULL;
// m_audiostream_engine = new AudioStreamEngine(*this);
return;
}
RtpTransceiver::~RtpTransceiver(void)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::~RtpTransceiver()]"));
Close();
if (m_socket_engine != NULL)
{
delete m_socket_engine;
}
/* if (m_audiostream_engine != NULL)
{
delete m_audiostream_engine;
}*/
return;
}
void RtpTransceiver::SetServerName(const string name)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::SetServerName()]"));
m_server = name;
return;
}
const string RtpTransceiver::GetServerName()
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetServerName()]"));
return m_server;
}
void RtpTransceiver::SetServerPort(int port)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::SetServerPort()]"));
m_remote_port = port;
return;
}
int RtpTransceiver::GetServerPort()
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetServerPort()]"));
return m_remote_port;
}
void RtpTransceiver::SetLocalRtpPort(int port)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::SetLocalRtpPort()]"));
m_local_port = port;
return;
}
int RtpTransceiver::GetLocalRtpPort()
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetLocalRtpPort()]"));
return m_local_port;
}
void RtpTransceiver::Close(void)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::Close()]"));
//! clearState(IOStream::STATE_FAIL);
m_rx_data.Clear();
m_tx_data.Clear();
return;
}
Uint32 RtpTransceiver::Flush(bool force)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::Flush()]"));
if (m_tx_data.Size() == 0)
{
return 0;
}
/*! if (eos() == true)
{
throw IOStream::EndOfStream();
}
if (fail() == true)
{
throw IOStream::InvalidStream();
}
if (IsConnected() == false)
{
throw IOStream::InvalidStream();
}
*/
// Initialize the transmission statistics, if not
// already inititalized.
if (HasTxStats() == false)
{
ResetTxStats();
}
Uint32 writen(0);
Uint32 needed(m_payload_format.blocksPerPacket
* m_payload_format.bytesPerBlock);
RTPPayloadInfo info;
RTPPacket packet(m_ssrc, m_csrcs.Data(), m_csrcs.Size());
packet.SetPayloadType(m_payload_type);
while (m_tx_data.Size() != 0)
{
packet.ClearPayloadData();
if (m_tx_data.Size() < needed)
{
if (force == true)
{
needed = m_tx_data.Size();
}
else
{
break;
}
}
for (Uint32 remain = needed; remain != 0; )
{
const Uint8* buffer;
Uint32 length(m_tx_data.Access(
buffer, needed - remain));
if (remain < length)
{
length = remain;
}
packet.AddPayloadData(buffer, length);
remain -= length;
}
packet.SetSequence(m_tx_next.sequence);
packet.SetTimestamp(m_tx_next.timestamp);
// Step 3: Failing to transmit the packet indicates a
// fatal error. However, in the case of success, adjust
// the outgoing data buffer and loop over.
EvalPayloadInfo(packet.GetPayloadType(),
packet.GetPayloadSize(), info);
if (SendPacket(packet, info) != packet.GetPacketSize())
{
break;
}
m_tx_data.Discard(packet.GetPayloadSize());
writen += packet.GetPayloadSize();
}
return writen;
}
void RtpTransceiver::SetLocalPort(Uint32 port)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::SetLocalPort()]"));
m_socket_engine->SetLocalPort(port);
return;
}
Uint32 RtpTransceiver::GetLocalPort(void) const
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetLocalPort()]"));
return m_socket_engine->GetLocalPort();
}
bool RtpTransceiver::GetPacket(void)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetPacket()]"));
/*! if (eos() == true)
{
throw IOStream::EndOfStream();
}
if (fail() == true)
{
throw IOStream::InvalidStream();
}
if (IsListening() == false)
{
throw IOStream::InvalidStream();
}
*/
return (RecvPacket("") != 0);
}
bool RtpTransceiver::PutPacket(const RTPPacket& packet)
{
#if _DEBUG_2
ACE_TRACE(ACE_TEXT("[RtpTransceiver::PutPacket()]"));
#endif
/*! if (eos() == true)
{
throw IOStream::EndOfStream();
}
if (fail() == true)
{
throw IOStream::InvalidStream();
}
if (IsConnected() == false)
{
throw IOStream::InvalidStream();
}
*/
/* cout << "---" << packet.IsValid()
<< "---" << packet.GetSequence()
<< "---" << m_tx_next.sequence
<< "---" << packet.GetTimestamp()
<< "---" << m_tx_next.timestamp
<< "---" << packet.GetSyncSource()
<< "---" << m_ssrc << endl;
*/
if ((packet.IsValid() == false)
|| (packet.GetSequence() != m_tx_next.sequence)
|| (packet.GetTimestamp() < m_tx_next.timestamp)
|| (packet.GetSyncSource() != m_ssrc))
{
// TODO: Recheck
// return false;
}
// Initialize the transmission statistics, if not
// already inititalized.
if (HasTxStats() == false)
{
ResetTxStats();
}
// Evaluate the time metrics of the supplied packet
// and proceed by transmitting it over the network.
RTPPayloadInfo info;
EvalPayloadInfo(packet.GetPayloadType(),
packet.GetPayloadSize(), info);
if (SendPacket(packet, info) != packet.GetPacketSize())
{
DropPayload(packet.GetPayloadSize(), info);
return false;
}
return true;
}
void RtpTransceiver::Connect(void)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::Connect()]"));
/*! try
{
m_udp_peer.connect();
}
catch (...)
{
cloneState(); throw;
}
*/
ClearTxStats();
CloneState();
return;
}
void RtpTransceiver::Listen(Uint32 port)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::Listen()]"));
/*! try
{
m_udp_peer.listen(port);
}
catch (...)
{
CloneState(); throw;
}
*/
ClearRxStats();
CloneState();
return;
}
/*
void RtpTransceiver::SetHostname(const String& addr)
{
m_udp_peer.SetHostname(addr);
return;
}
String RtpTransceiver::GetHostname(void) const
{
return m_udp_peer.getHostname();
}
void RtpTransceiver::SetRemotePort(Uint32 port)
{
m_udp_peer.setRemotePort(port);
return;
}
Uint32 RtpTransceiver::GetRemotePort(void) const
{
return m_udp_peer.getRemotePort();
}
void RtpTransceiver::SetAddress(const IPAddress& addr)
{
m_udp_peer.setAddress(addr);
return;
}
IPAddress RtpTransceiver::GetAddress(void) const
{
return m_udp_peer.getAddress();
}
bool RtpTransceiver::IsConnected(void) const
{
return m_udp_peer.isConnected();
}
bool RtpTransceiver::IsListening(void) const
{
return m_udp_peer.isListening();
}
void RtpTransceiver::SetTimeout(Uint32 msecs)
{
m_udp_peer.setTimeout(msecs);
return;
}
Uint32 RtpTransceiver::GetTimeout(void) const
{
return m_udp_peer.getTimeout();
}
*//*
void RtpTransceiver::SetFilter(RTPPacketFilter* filter)
{
m_filter = filter;
return;
}
RTPPacketFilter* RtpTransceiver::GetFilter(void) const
{
return m_filter;
}
*/
void RtpTransceiver::SetRxBufferSize(Uint32 value)
{
#if _DEBUG_2
ACE_TRACE(ACE_TEXT("[RtpTransceiver::SetRxBufferSize()]"));
#endif
Uint32 min_size(m_payload_format.blocksPerPacket
* m_payload_format.bytesPerBlock);
if (value == 0)
{
value = RTP_IN_BUFFER_SIZE;
}
if (value < min_size)
{
value = min_size;
}
m_rx_limit = value;
while (m_rx_data.Size() > m_rx_limit)
{
m_rx_data.Discard(min_size);
}
return;
}
Uint32 RtpTransceiver::GetRxBufferSize(void) const
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetRxBufferSize()]"));
return m_rx_limit;
}
Uint32 RtpTransceiver::GetRxOctets(void) const
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetRxOctets()]"));
return m_rx_data.Size();
}
RTPStats RtpTransceiver::GetRxStats(void) const
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetRxStats()]"));
return m_rx_stats;
}
void RtpTransceiver::ClearRxStats(void)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::ClearRxStats()]"));
memset(&m_rx_stats, 0, sizeof(RTPStats));
m_rx_transit = 0;
return;
}
void RtpTransceiver::SetTxBufferSize(Uint32 value)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::SetTxBufferSize()]"));
Uint32 min_size(m_payload_format.blocksPerPacket
* m_payload_format.bytesPerBlock);
if (value == 0)
{
value = RTP_OUT_BUFFER_SIZE;
}
if (value < min_size)
{
value = min_size;
}
m_tx_limit = value;
while (m_tx_data.Size() > m_tx_limit)
{
m_tx_data.Discard(min_size);
}
return;
}
Uint32 RtpTransceiver::GetTxBufferSize(void) const
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetTxBufferSize()]"));
return m_tx_limit;
}
Uint32 RtpTransceiver::GetTxOctets(void) const
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetTxOctets()]"));
return m_tx_data.Size();
}
RTPStats RtpTransceiver::GetTxStats(void) const
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetTxStats()]"));
return m_tx_stats;
}
void RtpTransceiver::ClearTxStats(void)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::ClearTxStats()]"));
memset(&m_tx_stats, 0, sizeof(RTPStats));
memset(&m_tx_next, 0, sizeof(RTPTimeMetrics));
m_tx_transit = 0;
return;
}
void RtpTransceiver::SetSyncSource(RTPSrc ssrc)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::SetSyncSource()]"));
if (ssrc == 0)
{
ssrc = GenerateRandom();
}
m_ssrc = ssrc;
ClearTxStats();
m_tx_data.Clear();
return;
}
RTPSrc RtpTransceiver::GetSyncSource(void) const
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetSyncSource()]"));
return m_ssrc;
}
void RtpTransceiver::SetCntrSources(const RTPSrc* csrc_tab,
Uint32 csrc_num)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::SetCntrSources()]"));
if (csrc_num > 15)
{
csrc_num = 15;
}
m_csrcs.Clear();
m_csrcs.Append(csrc_tab, csrc_num);
m_tx_data.Clear();
return;
}
Uint32 RtpTransceiver::GetCntrSources(RTPSrc* csrc_tab,
Uint32 csrc_num) const
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetCntrSources()]"));
if (m_csrcs.Size() < csrc_num)
{
csrc_num = m_csrcs.Size();
}
memcpy(csrc_tab, m_csrcs.Data(), csrc_num * sizeof(RTPSrc));
return csrc_num;
}
void RtpTransceiver::SetPayloadType(RTPPayloadType type)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::SetPayloadType()]"));
m_payload_type = type;
m_tx_data.Clear();
return;
}
RTPPayloadType RtpTransceiver::GetPayloadType(void) const
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetPayloadType()]"));
return m_payload_type;
}
void RtpTransceiver::SetPayloadFormat(RTPPayloadFormat format)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::SetPayloadFormat()]"));
m_payload_format = format;
if (m_payload_format.bytesPerBlock == 0)
{
m_payload_format.bytesPerBlock = 1;
}
if (m_payload_format.blocksPerPacket == 0)
{
m_payload_format.blocksPerPacket = 20;
}
if (m_payload_format.blockDuration == 0)
{
m_payload_format.blockDuration = 1;
}
if (m_payload_format.blocksPerSecond == 0.0)
{
m_payload_format.blocksPerSecond = 1.0;
}
return;
}
RTPPayloadFormat RtpTransceiver::GetPayloadFormat(void) const
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::GetPayloadFormat()]"));
return m_payload_format;
}
void RtpTransceiver::CloneState(void)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::CloneState()]"));
/*! ClearState();
if (m_udp_peer.eos() == true)
{
setState(IOStream::STATE_EOS);
}
if (m_udp_peer.fail() == true)
{
setState(IOStream::STATE_FAIL);
}
*/
return;
}
bool RtpTransceiver::HasRxStats(void) const
{
#if _DEBUG_2
ACE_TRACE(ACE_TEXT("[RtpTransceiver::HasRxStats()]"));
#endif
return (m_rx_stats.seed.wallclock != NTPTime());
}
bool RtpTransceiver::HasTxStats(void) const
{
#if _DEBUG_2
ACE_TRACE(ACE_TEXT("[RtpTransceiver::HasTxStats()]"));
#endif
return (m_tx_stats.seed.wallclock != NTPTime());
}
void RtpTransceiver::ResetTxStats(void)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::ResetTxStats()]"));
ClearTxStats();
if (GetSyncSource() == 0)
{
SetSyncSource(0);
}
m_tx_stats.ssrc = GetSyncSource();
m_tx_stats.seed.sequence = GenerateRandom();
m_tx_stats.seed.timestamp = GenerateRandom();
m_tx_stats.seed.wallclock = NTPTime::Now();
m_tx_next = m_tx_stats.seed;
m_tx_transit = 0;
return;
}
void RtpTransceiver::EvalPayloadInfo(RTPPayloadType type,
Uint32 octets,
RTPPayloadInfo& info)
{
#if _DEBUG_2
ACE_TRACE(ACE_TEXT("[RtpTransceiver::EvalPayloadInfo()]"));
#endif
// Set the default packet time info values.
info.sequence = 1;
info.timestamp = 0;
// NOTE: The RTP time offset is not affected by
// transmitted payload data that is not of the
// configured type.
if (type != m_payload_type)
{
return;
}
// Evaluate the RTP duration of the indicated payload
// size. If the bytes-per-block and block-duration
// values have not been defined, the default value
// one (1) is assumed.
Uint32 blocks(octets / m_payload_format.bytesPerBlock);
Uint32 duration(blocks * m_payload_format.blockDuration);
info.timestamp = duration;
return;
}
Uint32 RtpTransceiver::SendPacket(const RTPPacket& packet,
const RTPPayloadInfo& info)
{
#if _DEBUG_2
ACE_TRACE(ACE_TEXT("[RtpTransceiver::SendPacket()]"));
#endif
//packet.PrintSelf();
const Uint8* buffer(packet.GetPacketData());
Uint32 length(packet.GetPacketSize());
//cout << "---[DEBUG] [GetPacketSize]" << length << endl;
Uint32 writen(0);
/*
try
{
writen = m_udp_peer.put(buffer, length);
}
catch (...)
{
writen = 0;
CloneState();
}
*/
writen = m_socket_engine->WriteData(buffer, length);
//cout << "---[DEBUG] [writen]" << writen << endl;
if (writen != length)
{
return writen;
}
// Update transmission statistics.
Uint32 sequence(packet.GetSequence());
Uint32 timestamp(packet.GetTimestamp());
const NTPTime wallclock(NTPTime::Now());
Uint32 last_seq(m_tx_stats.last.sequence);
m_tx_stats.last.sequence = sequence;
m_tx_stats.last.timestamp = timestamp;
m_tx_stats.last.wallclock = wallclock;
if ((sequence < last_seq)
&& (CmpSeq(last_seq, sequence, 128) < 0))
{
m_tx_stats.last.cycles += 1;
}
m_tx_next.sequence = sequence + info.sequence;
m_tx_next.timestamp = timestamp + info.timestamp;
if (m_tx_next.sequence > USHRT_MAX)
{
m_tx_next.cycles += 1;
m_tx_next.sequence &= USHRT_MAX;
}
Uint32 rtp_offset(timestamp - m_tx_stats.seed.timestamp);
Uint32 rtp_blocks(rtp_offset / m_payload_format.blockDuration);
double ntp_offset((double)rtp_blocks / m_payload_format.blocksPerSecond);
const NTPTime ntp_expect(m_tx_stats.seed.wallclock
+ (Uint32)(1000.0 * ntp_offset));
long trans(NTPTime::Diff(wallclock, ntp_expect));
long delay(trans - m_tx_transit);
m_tx_transit = trans;
m_tx_stats.jitter -= (m_tx_stats.jitter + 8) / 16;
m_tx_stats.jitter += AbsInt(delay);
m_tx_stats.handled.packetCount += 1;
m_tx_stats.handled.octetCount +=
packet.GetPayloadSize();
return writen;
}
Uint32 RtpTransceiver::RecvPacket(string buffer)
{
#if _DEBUG_2
ACE_TRACE(ACE_TEXT("[RtpTransceiver::RecvPacket()]"));
#endif
/* Uint8 rtp_data[RTP_MTU];
Uint32 rtp_size(sizeof(rtp_data));
//! IPAddress rtp_addr;
Uint32 readn(0);*/
/* try
{
readn = m_udp_peer.getFrom(rtp_data,
rtp_size, rtp_addr);
}
catch (...)
{
readn = 0;
CloneState();
}
if (readn == 0)
{
return readn;
}*/
Uint32 readn(0);
// readn = m_socket_buf.size();
readn = buffer.size();
// const RTPPacketEx packet((Uint8*)m_socket_buf.c_str(), readn);
const RTPPacketEx packet((Uint8*)buffer.c_str(), readn);
//const RTPPacketEx packet(rtp_data, readn);
if (packet.IsValid() == false)
{
//return readn;
}
// Apply packet filtering and bypass standard processing
// if the user-defined filter indicates that the packet
// should be dropped.
/*! if ((m_filter != 0)
&& (m_filter->FilterPacket(packet, rtp_addr) == true))
{
return readn;
}
*/
// Apply standard packet processing.
Uint32 sequence(packet.GetSequence());
Uint32 timestamp(packet.GetTimestamp());
const NTPTime wallclock(NTPTime::Now());
Uint32 last_seq(m_rx_stats.last.sequence);
int diff_seq(CmpSeq(sequence, last_seq, 128));
if (HasRxStats() == false)
{
ClearRxStats(); // clears 'm_rx_transit' too.
m_rx_stats.ssrc = packet.GetSyncSource();
m_rx_stats.seed.sequence = sequence;
m_rx_stats.seed.timestamp = timestamp;
m_rx_stats.seed.wallclock = wallclock;
m_rx_stats.last = m_rx_stats.seed;
diff_seq = 1;
}
else if (diff_seq > 0)
{
m_rx_stats.last.sequence = sequence;
m_rx_stats.last.timestamp = timestamp;
m_rx_stats.last.wallclock = wallclock;
if (sequence < last_seq)
{
m_rx_stats.last.cycles += 1;
}
}
if (diff_seq == 0)
{
// Duplicate packet. Discard and update statistics.
m_rx_stats.dropped.packetCount += 1;
m_rx_stats.dropped.octetCount +=
packet.GetPayloadSize();
}
else if (diff_seq > 0)
{
// If the sequence numbers differ by more than one,
// assume that all intermediate packets were lost.
m_rx_stats.dropped.packetCount += diff_seq - 1;
// Process the received packet, if and only if the
// payload is of the expected type.
if (packet.GetPayloadType() == m_payload_type)
{
// Packet seems to be valid and the payload of the
// expected type. Enqueue the payload data, discard
// data if necessary to prevent incoming data buffer
// overflow, and then update the reception statistics.
m_rx_data.Enqueue(packet.GetPayloadData(),
packet.GetPayloadSize());
SetRxBufferSize(m_rx_limit);
// NOTE: If this is the very first RTP packet to
// be received, the 'ntp_expect' timestamp will
// be equal to the wallclock time and the delay
// equal to zero (0).
Uint32 rtp_offset(timestamp
- m_rx_stats.seed.timestamp);
Uint32 rtp_blocks(rtp_offset
/ m_payload_format.blockDuration);
double ntp_offset((double)rtp_blocks
/ m_payload_format.blocksPerSecond);
const NTPTime ntp_expect(m_rx_stats.seed.wallclock
+ (Uint32)(1000.0 * ntp_offset));
long trans(NTPTime::Diff(wallclock, ntp_expect));
long delay(trans - m_rx_transit);
m_rx_transit = trans;
m_rx_stats.jitter -= (m_rx_stats.jitter + 8) / 16;
m_rx_stats.jitter += AbsInt(delay);
m_rx_stats.handled.packetCount += 1;
m_rx_stats.handled.octetCount +=
packet.GetPayloadSize();
}
else
{
m_rx_stats.dropped.packetCount += 1;
m_rx_stats.dropped.octetCount +=
packet.GetPayloadSize();
}
}
// Packets.push_back(packet);
m_observer.TTSDataReceived(packet.GetPayloadData());
// m_audiostream_engine->PlayData(packet.GetPayloadData());
return readn;
}
void RtpTransceiver::DropPayload(Uint32 octets,
const RTPPayloadInfo& info)
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::DropPayload()]"));
m_tx_next.sequence += info.sequence;
m_tx_next.timestamp += info.timestamp;
if (m_tx_next.sequence > USHRT_MAX)
{
m_tx_next.cycles += 1;
m_tx_next.sequence &= USHRT_MAX;
}
m_tx_stats.dropped.packetCount += 1;
m_tx_stats.dropped.octetCount += octets;
return;
}
void RtpTransceiver::StartComms()
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::StartComms()]"));
m_socket_engine->SetServerName(m_server);
m_socket_engine->SetServerPort(m_remote_port);
m_socket_engine->SetLocalPort(m_local_port);
m_socket_engine->SetBufferSize(RTP_MTU);
m_socket_engine->ConnectServer("UDP");
return;
}
void RtpTransceiver::StopComms()
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::StopComms()]"));
// TODO: Recheck if stop listening to port must be implemented
if (m_socket_engine != NULL)
{
m_socket_engine->DisconnectServer();
}
return;
}
void RtpTransceiver::MessageReceived(ostringstream& buffer)
{
#if _DEBUG_2
ACE_TRACE(ACE_TEXT("[RtpTransceiver::MessageReceived()]"));
#endif
// m_socket_buf = buffer;
m_socket_buf = buffer.str();
// string m_socket_buf = buffer.str();
#if _DEBUG_2
ACE_DEBUG((LM_DEBUG, ACE_TEXT("%I[DEBUG] [RtpTransceiver::MessageReceived()] "
"[Received Message: %d]\n"), m_socket_buf.size()));
#endif
// cout << buffer.str() << endl;
// m_socket_engine->WriteData((Uint8*)m_socket_buf.c_str(), m_socket_buf.size());
while (m_socket_buf.size() >= RTP_MTU)
{
counter++;
// cout << "---[DEBUG] [Packet: " << counter << "]" << endl;
string buffer;
buffer.assign(m_socket_buf, 0, RTP_MTU);
m_socket_buf.erase(0, RTP_MTU);
RecvPacket(buffer);
}
return;
}
void RtpTransceiver::SendPackets()
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::SendPackets()]"));
counter = 0;
int data[172] = {0};
//RTPPayloadInfo info;
//Uint32 needed(m_payload_format.blocksPerPacket
// * m_payload_format.bytesPerBlock);
RTPPacket pack(m_ssrc, (RTPSrc*)data, 0);
pack.SetPayloadType(m_payload_type);
//cout << "---[DEBUG] [RtpTransceiver::SendPackets()] >>" << endl;
//cout << "---[DEBUG] [Packets.size()] " << Packets.size() << endl;
for (int i = 0; i < (int)Packets.size(); ++i)
{
pack.ClearPayloadData();
if (Packets[i].GetPacketData() == NULL)
{
ACE_DEBUG((LM_DEBUG, ACE_TEXT("%I[DEBUG] [RtpTransceiver::SendPackets()] "
"[Packets.size()] [NULL PACKET!!!]\n")));
}
pack.AddPayloadData(Packets[i].GetPayloadData(), Packets[i].GetPayloadSize());
pack.SetSequence(m_tx_next.sequence);
pack.SetTimestamp(m_tx_next.timestamp);
++counter;
if (PutPacket(pack) == false)
{
ACE_DEBUG((LM_DEBUG, ACE_TEXT("%I[DEBUG] [RtpTransceiver::SendPackets()] "
"[PutPacket returned false]\n")));
}
}
// cout << "---[DEBUG] [RtpTransceiver::SendPackets()] <<" << endl;
#if 0
// ?
//ACE_Time_Value tv;
//tv.msec(300);
counter = 0;
int data[172] = {0};
RTPPayloadInfo info;
Uint32 needed(m_payload_format.blocksPerPacket
* m_payload_format.bytesPerBlock);
RTPPacket pack(m_ssrc, (RTPSrc*)data, 0);
pack.SetPayloadType(m_payload_type);
#if 0
//for (int i = 0; i < Packets.size(); ++i)
for (int i = 0; i < Packets2.size(); ++i)
{
pack.ClearPayloadData();
pack.AddPayloadData(Packets2[i].GetPayloadData(), Packets2[i].GetPayloadSize());
//pack.AddPayloadData(Packets[i].GetPayloadData(), Packets[i].GetPayloadSize());
/*if ((i > 5) && (i < 350))
{
pack.AddPayloadData(Packets2[i].GetPayloadData(), Packets2[i].GetPayloadSize());
}
else
{
pack.AddPayloadData(Packets[i].GetPayloadData(), Packets[i].GetPayloadSize());
}*/
pack.SetSequence(m_tx_next.sequence);
pack.SetTimestamp(m_tx_next.timestamp);
//const Uint8* tmp(pack.GetPayloadData());
//cout << "---tmp[0]" << tmp[0] << endl;
//Packets[i].SetSequence(m_tx_next.sequence);
//Packets[i].SetTimestamp(m_tx_next.timestamp);
counter++;
if (PutPacket(pack) == false)
//if (PutPacket(Packets[i]) == false)
//if (PutPacket(Packets2[i]) == false)
{
ACE_DEBUG((LM_DEBUG, ACE_TEXT("%I[DEBUG] [RtpTransceiver::SendPackets()] "
"[PutPacket returned false]\n")));
}
//m_audiostream_engine->PlayData(Packets2[i].GetPayloadData());
//m_audiostream_engine->PlayData(Packets2[i].GetPayloadData());
//const Uint8* buf(Packets[i].GetPacketData());
//m_audiostream_engine->PlayData(Packets[i].GetPayloadData());
//m_audiostream_engine->PlayData(pack.GetPayloadData());
//PutPacket(Packets[i]);
//Packets[i].PrintSelf();
//pack.PrintSelf();
//PutPacket(pack);
}
#endif
#endif
// TODO: Recheck
for (int i = 0; i < 50; ++i)
{
counter++;
PutPacket(Packets[Packets.size()-1]);
}
#if _DEBUG_0
ACE_DEBUG((LM_DEBUG, ACE_TEXT("%I[DEBUG] [RtpTransceiver::SendPackets()] "
"[Send %d packets]\n"), counter));
#endif
return;
}
void RtpTransceiver::ClearPacketsBuffer()
{
ACE_TRACE(ACE_TEXT("[RtpTransceiver::ClearPacketsBuffer()]"));
Packets.clear();
return;
}
void RtpTransceiver::CreateAndSendPacket(const Uint8* buffer)
{
#if _DEBUG_1
ACE_TRACE(ACE_TEXT("[RtpTransceiver::CreateAndSendPacket()]"));
#endif
int data[172] = {0};
//RTPPayloadInfo info;
//Uint32 needed(m_payload_format.blocksPerPacket
// * m_payload_format.bytesPerBlock);
RTPPacket pack(m_ssrc, (RTPSrc*)data, 0);
pack.SetPayloadType(m_payload_type);
// TODO: recheck size
pack.AddPayloadData(buffer, 160);
pack.SetSequence(m_tx_next.sequence);
pack.SetTimestamp(m_tx_next.timestamp);
if (PutPacket(pack) == false)
{
ACE_DEBUG((LM_DEBUG, ACE_TEXT("%I[DEBUG] [RtpTransceiver::CreateAndSendPacket()] "
"[PutPacket returned false]\n")));
}
Packets.push_back(pack);
return;
}
/*
//void RtpTransceiver::AudioDataReceived(const Uint8* buffer)
void RtpTransceiver::AudioDataReceived(ostringstream& buffer)
{
#if _DEBUG
cout << endl << "---[DEBUG] [RtpTransceiver::AudioDataReceived()]" << endl;
#endif
int data[172] = {0};
RTPPayloadInfo info;
Uint32 needed(m_payload_format.blocksPerPacket
* m_payload_format.bytesPerBlock);
RTPPacket packet(m_ssrc, (RTPSrc*)data, 0);
packet.SetPayloadType(m_payload_type);
packet.ClearPayloadData();
string str = buffer.str();
const Uint8* buf((Uint8*)str.c_str());
// TODO: Recheck
//packet.AddPayloadData(buf, 160);
//Uint8* buff= const_cast<Uint8 *>(buffer);
//packet.AddPayloadData(buffer, 160);
//for (int i = 0; i <160; ++i)
//{
// buf[i]=2*buf[i];
//}
packet.AddPayloadData(buf, 160);
packet.SetSequence(m_tx_next.sequence);
packet.SetTimestamp(m_tx_next.timestamp);
Packets2.push_back(packet);
return;
}
void RtpTransceiver::CloseAudio()
{
#if _DEBUG
cout << endl << "---[DEBUG] [RtpTransceiver::CloseAudio()]" << endl;
#endif
if (m_audiostream_engine != NULL)
{
m_audiostream_engine->CloseAudio();
}
return;
}
void RtpTransceiver::CaptureAudio()
{
#if _DEBUG
cout << endl << "---[DEBUG] [RtpTransceiver::CaptureAudio()]" << endl;
#endif
Packets2.clear();
if (m_audiostream_engine != NULL)
{
m_audiostream_engine->RecordData();
}
return;
}
*/
|
// 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.
#include "net/http/proxy_client_socket.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/stringprintf.h"
#include "net/base/host_port_pair.h"
#include "net/base/net_errors.h"
#include "net/http/http_auth_controller.h"
#include "net/http/http_request_info.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "url/gurl.h"
namespace net {
namespace {
void CopyHeaderValues(scoped_refptr<HttpResponseHeaders> source,
scoped_refptr<HttpResponseHeaders> dest,
const std::string& header_name) {
size_t iter = 0;
std::string header_value;
while (source->EnumerateHeader(&iter, header_name, &header_value))
dest->AddHeader(header_name + ": " + header_value);
}
} // namespace
// static
void ProxyClientSocket::BuildTunnelRequest(
const HostPortPair& endpoint,
const HttpRequestHeaders& auth_headers,
const std::string& user_agent,
std::string* request_line,
HttpRequestHeaders* request_headers) {
// RFC 7230 Section 5.4 says a client MUST send a Host header field in all
// HTTP/1.1 request messages, and Host SHOULD be the first header field
// following the request-line. Add "Proxy-Connection: keep-alive" for compat
// with HTTP/1.0 proxies such as Squid (required for NTLM authentication).
std::string host_and_port = endpoint.ToString();
*request_line =
base::StringPrintf("CONNECT %s HTTP/1.1\r\n", host_and_port.c_str());
request_headers->SetHeader(HttpRequestHeaders::kHost, host_and_port);
request_headers->SetHeader(HttpRequestHeaders::kProxyConnection,
"keep-alive");
if (!user_agent.empty())
request_headers->SetHeader(HttpRequestHeaders::kUserAgent, user_agent);
request_headers->MergeFrom(auth_headers);
}
// static
int ProxyClientSocket::HandleProxyAuthChallenge(HttpAuthController* auth,
HttpResponseInfo* response,
const BoundNetLog& net_log) {
DCHECK(response->headers.get());
int rv = auth->HandleAuthChallenge(response->headers, response->ssl_info,
false, true, net_log);
response->auth_challenge = auth->auth_info();
if (rv == OK)
return ERR_PROXY_AUTH_REQUESTED;
return rv;
}
// static
void ProxyClientSocket::LogBlockedTunnelResponse(int http_status_code,
bool is_https_proxy) {
if (is_https_proxy) {
UMA_HISTOGRAM_CUSTOM_ENUMERATION(
"Net.BlockedTunnelResponse.HttpsProxy",
HttpUtil::MapStatusCodeForHistogram(http_status_code),
HttpUtil::GetStatusCodesForHistogram());
} else {
UMA_HISTOGRAM_CUSTOM_ENUMERATION(
"Net.BlockedTunnelResponse.HttpProxy",
HttpUtil::MapStatusCodeForHistogram(http_status_code),
HttpUtil::GetStatusCodesForHistogram());
}
}
// static
bool ProxyClientSocket::SanitizeProxyAuth(HttpResponseInfo* response) {
DCHECK(response && response->headers.get());
scoped_refptr<HttpResponseHeaders> old_headers = response->headers;
const char kHeaders[] = "HTTP/1.1 407 Proxy Authentication Required\n\n";
scoped_refptr<HttpResponseHeaders> new_headers = new HttpResponseHeaders(
HttpUtil::AssembleRawHeaders(kHeaders, arraysize(kHeaders)));
// Copy status line and all hop-by-hop headers to preserve keep-alive
// behavior.
new_headers->ReplaceStatusLine(old_headers->GetStatusLine());
CopyHeaderValues(old_headers, new_headers, "connection");
CopyHeaderValues(old_headers, new_headers, "proxy-connection");
CopyHeaderValues(old_headers, new_headers, "keep-alive");
CopyHeaderValues(old_headers, new_headers, "trailer");
CopyHeaderValues(old_headers, new_headers, "transfer-encoding");
CopyHeaderValues(old_headers, new_headers, "upgrade");
CopyHeaderValues(old_headers, new_headers, "content-length");
CopyHeaderValues(old_headers, new_headers, "proxy-authenticate");
response->headers = new_headers;
return true;
}
// static
bool ProxyClientSocket::SanitizeProxyRedirect(HttpResponseInfo* response) {
DCHECK(response && response->headers.get());
std::string location;
if (!response->headers->IsRedirect(&location))
return false;
// Return minimal headers; set "Content-Length: 0" to ignore response body.
std::string fake_response_headers = base::StringPrintf(
"HTTP/1.0 302 Found\n"
"Location: %s\n"
"Content-Length: 0\n"
"Connection: close\n"
"\n",
location.c_str());
std::string raw_headers =
HttpUtil::AssembleRawHeaders(fake_response_headers.data(),
fake_response_headers.length());
response->headers = new HttpResponseHeaders(raw_headers);
return true;
}
} // namespace net
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r8
push %r9
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0x879a, %rsi
lea addresses_WC_ht+0xc19a, %rdi
inc %r9
mov $105, %rcx
rep movsl
add %r12, %r12
lea addresses_D_ht+0x11d1a, %r8
xor %r12, %r12
mov (%r8), %r9d
nop
nop
nop
cmp $49501, %rsi
lea addresses_WC_ht+0xa57a, %rsi
nop
nop
nop
nop
nop
cmp $45880, %r13
movups (%rsi), %xmm2
vpextrq $0, %xmm2, %rdi
nop
nop
nop
nop
add %rdi, %rdi
lea addresses_WT_ht+0xb01a, %r9
nop
nop
nop
nop
nop
xor %r8, %r8
mov (%r9), %r13w
nop
nop
nop
nop
add $60830, %r9
lea addresses_UC_ht+0xfbca, %r13
nop
nop
nop
nop
nop
xor %r9, %r9
mov $0x6162636465666768, %rcx
movq %rcx, (%r13)
nop
nop
inc %r13
lea addresses_WT_ht+0x3d05, %rdi
nop
nop
nop
nop
nop
add $19153, %r13
mov $0x6162636465666768, %r12
movq %r12, %xmm6
vmovups %ymm6, (%rdi)
sub %r12, %r12
lea addresses_A_ht+0x19a9a, %rsi
lea addresses_A_ht+0x19e9a, %rdi
nop
nop
nop
dec %r13
mov $76, %rcx
rep movsq
nop
nop
nop
nop
and %rsi, %rsi
lea addresses_D_ht+0x1111a, %rsi
lea addresses_D_ht+0x599a, %rdi
nop
sub $49239, %rax
mov $26, %rcx
rep movsl
nop
nop
nop
nop
nop
add $54993, %r8
lea addresses_UC_ht+0x2002, %rsi
lea addresses_A_ht+0x1a142, %rdi
clflush (%rsi)
clflush (%rdi)
nop
nop
nop
nop
nop
cmp %r13, %r13
mov $31, %rcx
rep movsw
nop
xor $19558, %r13
lea addresses_UC_ht+0x5d9a, %rax
cmp %r12, %r12
movb (%rax), %cl
nop
nop
cmp $30674, %r8
lea addresses_UC_ht+0x1c8e2, %r9
nop
nop
add $13807, %rsi
movb (%r9), %al
add $15311, %r13
lea addresses_D_ht+0x578a, %r9
nop
nop
nop
nop
nop
and $59207, %rax
and $0xffffffffffffffc0, %r9
movntdqa (%r9), %xmm1
vpextrq $0, %xmm1, %rcx
nop
nop
inc %rsi
lea addresses_A_ht+0x779a, %rsi
lea addresses_D_ht+0x7f9a, %rdi
nop
nop
nop
nop
dec %r12
mov $85, %rcx
rep movsq
nop
cmp %rdi, %rdi
lea addresses_D_ht+0x4b1a, %rsi
lea addresses_WC_ht+0x439a, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
cmp %r9, %r9
mov $86, %rcx
rep movsq
dec %r13
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r8
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r14
push %r9
push %rbp
push %rbx
push %rdx
// Faulty Load
mov $0x17245d000000079a, %r14
nop
nop
add %rbx, %rbx
movups (%r14), %xmm5
vpextrq $1, %xmm5, %rdx
lea oracles, %rbp
and $0xff, %rdx
shlq $12, %rdx
mov (%rbp,%rdx,1), %rdx
pop %rdx
pop %rbx
pop %rbp
pop %r9
pop %r14
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_NC', 'same': False, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_NC', 'same': True, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'same': False, 'size': 4, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC_ht', 'same': True, 'size': 16, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 2, 'congruent': 7, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 8, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 1, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'same': True, 'size': 1, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D_ht', 'same': False, 'size': 16, 'congruent': 3, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'}
{'7a': 1, '46': 1313, '00': 19658, '48': 4, '45': 853}
00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 46 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 46 00 45 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 46 00 00 00 00 00 46 00 00 45 00 00 00 46 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 45 00 00 00 00 00 46 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 46 45 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 45 46 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 46 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 45 45 00 00 00 00 00 00 00 00 46 46 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 46 00 45 00 00 00 00 00 00 00 00 00 46 00 45 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 46 45 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 45 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 46 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 45 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 46 00 46 00 00 00 00 00 00 00 00 46 00 45 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 46 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 45 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 45 00 46 00 00 00 00 00 00 00 00 00 00 00 00 45 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; A110426: The r-th term of the n-th row of the following array contains the sum of r successively decreasing integers beginning from n. 0<r<=n. e.g. the row corresponding to 4 contains 4, (3+2),{(1) +(0)+(-1)}, {(-2)+(-3)+(-4)+(-5)} ----> 4,5,0,-14 1 2 1 3 3 -3 4 5 0 -14 5 7 3 -10 -35 6 9 6 -6 -30 -69 ... Sequence contains the row sums.
; 1,3,3,-5,-30,-84,-182,-342,-585,-935,-1419,-2067,-2912,-3990,-5340,-7004,-9027,-11457,-14345,-17745,-21714,-26312,-31602,-37650,-44525,-52299,-61047,-70847,-81780,-93930,-107384,-122232,-138567,-156485,-176085,-197469,-220742,-246012,-273390,-302990,-334929,-369327,-406307,-445995,-488520,-534014,-582612,-634452,-689675,-748425,-810849,-877097,-947322,-1021680,-1100330,-1183434,-1271157,-1363667,-1461135,-1563735,-1671644,-1785042,-1904112,-2029040,-2160015,-2297229,-2440877,-2591157,-2748270,-2912420,-3083814,-3262662,-3449177,-3643575,-3846075,-4056899,-4276272,-4504422,-4741580,-4987980,-5243859,-5509457,-5785017,-6070785,-6367010,-6673944,-6991842,-7320962,-7661565,-8013915,-8378279,-8754927,-9144132,-9546170,-9961320,-10389864,-10832087,-11288277,-11758725,-12243725,-12743574,-13258572,-13789022,-14335230,-14897505,-15476159,-16071507,-16683867,-17313560,-17960910,-18626244,-19309892,-20012187,-20733465,-21474065,-22234329,-23014602,-23815232,-24636570,-25478970,-26342789,-27228387,-28136127,-29066375,-30019500,-30995874,-31995872,-33019872,-34068255,-35141405,-36239709,-37363557,-38513342,-39689460,-40892310,-42122294,-43379817,-44665287,-45979115,-47321715,-48693504,-50094902,-51526332,-52988220,-54480995,-56005089,-57560937,-59148977,-60769650,-62423400,-64110674,-65831922,-67587597,-69378155,-71204055,-73065759,-74963732,-76898442,-78870360,-80879960,-82927719,-85014117,-87139637,-89304765,-91509990,-93755804,-96042702,-98371182,-100741745,-103154895,-105611139,-108110987,-110654952,-113243550,-115877300,-118556724,-121282347,-124054697,-126874305,-129741705,-132657434,-135622032,-138636042,-141700010,-144814485,-147980019,-151197167,-154466487,-157788540,-161163890,-164593104,-168076752,-171615407,-175209645,-178860045,-182567189,-186331662,-190154052,-194034950,-197974950,-201974649,-206034647,-210155547,-214337955,-218582480,-222889734,-227260332,-231694892,-236194035,-240758385,-245388569,-250085217,-254848962,-259680440,-264580290,-269549154,-274587677,-279696507,-284876295,-290127695,-295451364,-300847962,-306318152,-311862600,-317481975,-323176949,-328948197,-334796397,-340722230,-346726380,-352809534,-358972382,-365215617,-371539935,-377946035,-384434619,-391006392,-397662062,-404402340,-411227940,-418139579,-425137977,-432223857,-439397945,-446660970,-454013664,-461456762,-468991002,-476617125,-484335875
add $0,2
mov $1,4
mov $2,4
mov $3,3
sub $3,$0
bin $0,2
sub $2,$0
add $3,2
sub $2,$3
mov $4,$2
lpb $0,1
sub $0,1
add $4,1
add $1,$4
lpe
sub $1,4
|
/*
* Copyright (c) 2014-2022 The Voxie Authors
*
* 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 "ArrayInfo.hpp"
vx::Array1Info::Array1Info(const vx::Array1InfoDBus& info) {
handle = std::get<0>(info);
offset = std::get<1>(info);
dataType = std::get<0>(std::get<2>(info));
dataTypeSize = std::get<1>(std::get<2>(info));
byteorder = std::get<2>(std::get<2>(info));
size = std::get<0>(std::get<3>(info));
stride = std::get<0>(std::get<4>(info));
metadata = std::get<5>(info);
}
vx::Array1InfoDBus vx::Array1Info::toDBus() const {
return std::make_tuple(
handle, offset, std::make_tuple(dataType, dataTypeSize, byteorder),
std::make_tuple(size), std::make_tuple(stride), metadata);
}
vx::Array2Info::Array2Info(const vx::Array2InfoDBus& info) {
handle = std::get<0>(info);
offset = std::get<1>(info);
dataType = std::get<0>(std::get<2>(info));
dataTypeSize = std::get<1>(std::get<2>(info));
byteorder = std::get<2>(std::get<2>(info));
sizeX = std::get<0>(std::get<3>(info));
sizeY = std::get<1>(std::get<3>(info));
strideX = std::get<0>(std::get<4>(info));
strideY = std::get<1>(std::get<4>(info));
metadata = std::get<5>(info);
}
vx::Array2InfoDBus vx::Array2Info::toDBus() const {
return std::make_tuple(handle, offset,
std::make_tuple(dataType, dataTypeSize, byteorder),
std::make_tuple(sizeX, sizeY),
std::make_tuple(strideX, strideY), metadata);
}
vx::Array3Info::Array3Info(const vx::Array3InfoDBus& info) {
handle = std::get<0>(info);
offset = std::get<1>(info);
dataType = std::get<0>(std::get<2>(info));
dataTypeSize = std::get<1>(std::get<2>(info));
byteorder = std::get<2>(std::get<2>(info));
sizeX = std::get<0>(std::get<3>(info));
sizeY = std::get<1>(std::get<3>(info));
sizeZ = std::get<2>(std::get<3>(info));
strideX = std::get<0>(std::get<4>(info));
strideY = std::get<1>(std::get<4>(info));
strideZ = std::get<2>(std::get<4>(info));
metadata = std::get<5>(info);
}
vx::Array3InfoDBus vx::Array3Info::toDBus() const {
return std::make_tuple(handle, offset,
std::make_tuple(dataType, dataTypeSize, byteorder),
std::make_tuple(sizeX, sizeY, sizeZ),
std::make_tuple(strideX, strideY, strideZ), metadata);
}
|
// Commodore 64 PRG executable file
.file [name="arrays-init.prg", type="prg", segments="Program"]
.segmentdef Program [segments="Basic, Code, Data"]
.segmentdef Basic [start=$0801]
.segmentdef Code [start=$80d]
.segmentdef Data [startAfter="Code"]
.segment Basic
:BasicUpstart(main)
.label SCREEN = $400
.segment Code
main: {
// b[0] = 'c'
lda #'c'
sta b
// *SCREEN = b[0]
sta SCREEN
// *(SCREEN+1) = c[1]
lda c+1
sta SCREEN+1
// *(SCREEN+2) = d[2]
lda d+2
sta SCREEN+2
// }
rts
}
.segment Data
b: .fill 3, 0
c: .byte 'c', 'm', 'l'
d: .text "cml"
|
; char __fseq (float left, float right)
SECTION code_clib
SECTION code_fp_math48
PUBLIC cm48_sdccixp_dseq
EXTERN cm48_sdccixp_dread2, am48_deq
cm48_sdccixp_dseq:
; (left == right)
;
; enter : sdcc_float right, sdcc_float left, ret
;
; exit : HL = 0 and carry reset if false
; HL = 1 and carry set if true
;
; uses : af, bc, de, hl, bc', de', hl'
call cm48_sdccixp_dread2
; AC = right
; AC'= left
jp am48_deq
|
//
// Created by Jason Mohoney on 2/1/22.
//
#include "nn/layers/embedding/embedding.h"
#include "nn/initialization.h"
EmbeddingLayer::EmbeddingLayer(shared_ptr<LayerConfig> layer_config, torch::Device device, int offset) {
config_ = layer_config;
offset_ = offset;
device_ = device;
reset();
}
torch::Tensor EmbeddingLayer::forward(torch::Tensor input) {
return input.narrow(1, offset_, config_->output_dim);
}
torch::Tensor EmbeddingLayer::init_embeddings(int64_t num_nodes) {
auto options = torch::TensorOptions().device(device_).dtype(torch::kFloat32);
torch::Tensor embs = initialize_tensor(config_->init, {num_nodes, config_->output_dim}, options);
return embs;
}
void EmbeddingLayer::reset() {
if (config_->bias) {
init_bias();
}
} |
; int fflush_unlocked_fastcall(FILE *stream)
SECTION code_stdio
PUBLIC _fflush_unlocked_fastcall
EXTERN asm_fflush_unlocked
_fflush_unlocked_fastcall:
push hl
ex (sp),ix
call asm_fflush_unlocked
pop ix
ret
|
/*
* Copyright (c) 2019, The OpenThread Commissioner Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* The file implements CLI interpreter.
*/
#include "app/cli/interpreter.hpp"
#include <string.h>
#include "app/file_util.hpp"
#include "app/json.hpp"
#include "common/error_macros.hpp"
#include "common/utils.hpp"
namespace ot {
namespace commissioner {
const std::map<std::string, Interpreter::Evaluator> &Interpreter::mEvaluatorMap = *new std::map<std::string, Evaluator>{
{"start", &Interpreter::ProcessStart},
{"stop", &Interpreter::ProcessStop},
{"active", &Interpreter::ProcessActive},
{"token", &Interpreter::ProcessToken},
{"network", &Interpreter::ProcessNetwork},
{"sessionid", &Interpreter::ProcessSessionId},
{"borderagent", &Interpreter::ProcessBorderAgent},
{"joiner", &Interpreter::ProcessJoiner},
{"commdataset", &Interpreter::ProcessCommDataset},
{"opdataset", &Interpreter::ProcessOpDataset},
{"bbrdataset", &Interpreter::ProcessBbrDataset},
{"reenroll", &Interpreter::ProcessReenroll},
{"domainreset", &Interpreter::ProcessDomainReset},
{"migrate", &Interpreter::ProcessMigrate},
{"mlr", &Interpreter::ProcessMlr},
{"announce", &Interpreter::ProcessAnnounce},
{"panid", &Interpreter::ProcessPanId},
{"energy", &Interpreter::ProcessEnergy},
{"exit", &Interpreter::ProcessExit},
{"help", &Interpreter::ProcessHelp},
};
const std::map<std::string, std::string> &Interpreter::mUsageMap = *new std::map<std::string, std::string>{
{"start", "start <border-agent-addr> <border-agent-port>"},
{"stop", "stop"},
{"active", "active"},
{"token", "token request <registrar-addr> <registrar-port>\n"
"token print\n"
"token set <signed-token-hex-string-file> <signer-cert-pem-file>"},
{"network", "network save <network-data-file>\n"
"network sync"},
{"sessionid", "sessionid"},
{"borderagent", "borderagent discover [<timeout-in-milliseconds>]\n"
"borderagent get locator\n"
"borderagent get meshlocaladdr"},
{"joiner", "joiner enable (meshcop|ae|nmkp) <joiner-eui64> [<joiner-password>] [<provisioning-url>]\n"
"joiner enableall (meshcop|ae|nmkp) [<joiner-password>] [<provisioning-url>]\n"
"joiner disable (meshcop|ae|nmkp) <joiner-eui64>\n"
"joiner disableall (meshcop|ae|nmkp)\n"
"joiner getport (meshcop|ae|nmkp)\n"
"joiner setport (meshcop|ae|nmkp) <joiner-udp-port>"},
{"commdataset", "commdataset get\n"
"commdataset set '<commissioner-dataset-in-json-string>'"},
{"opdataset", "opdataset get activetimestamp\n"
"opdataset get channel\n"
"opdataset set channel <page> <channel> <delay-in-milliseconds>\n"
"opdataset get channelmask\n"
"opdataset set channelmask (<page> <channel-mask>)...\n"
"opdataset get xpanid\n"
"opdataset set xpanid <extended-pan-id>\n"
"opdataset get meshlocalprefix\n"
"opdataset set meshlocalprefix <prefix> <delay-in-milliseconds>\n"
"opdataset get networkmasterkey\n"
"opdataset set networkmasterkey <network-master-key> <delay-in-milliseconds>\n"
"opdataset get networkname\n"
"opdataset set networkname <network-name>\n"
"opdataset get panid\n"
"opdataset set panid <panid> <delay-in-milliseconds>\n"
"opdataset get pskc\n"
"opdataset set pskc <PSKc>\n"
"opdataset get securitypolicy\n"
"opdataset set securitypolicy <rotation-timer> <flags-hex>\n"
"opdataset get active\n"
"opdataset set active '<active-dataset-in-json-string>'\n"
"opdataset get pending\n"
"opdataset set pending '<pending-dataset-in-json-string>'"},
{"bbrdataset", "bbrdataset get trihostname\n"
"bbrdataset set trihostname <TRI-hostname>\n"
"bbrdataset get reghostname\n"
"bbrdataset set reghostname <registrar-hostname>\n"
"bbrdataset get regaddr\n"
"bbrdataset get\n"
"bbrdataset set '<bbr-dataset-in-json-string>'"},
{"reenroll", "reenroll <device-addr>"},
{"domainreset", "domainreset <device-addr>"},
{"migrate", "migrate <device-addr> <designated-network-name>"},
{"mlr", "mlr (<multicast-addr>)+ <timeout-in-seconds>"},
{"announce", "announce <channel-mask> <count> <period> <dst-addr>"},
{"panid", "panid query <channel-mask> <panid> <dst-addr>\n"
"panid conflict <panid>"},
{"energy", "energy scan <channel-mask> <count> <period> <scan-duration> <dst-addr>\n"
"energy report [<dst-addr>]"},
{"help", "help [<command>]"},
};
template <typename T> static std::string ToHex(T aInteger)
{
return "0x" + utils::Hex(utils::Encode(aInteger));
};
template <typename T> static Error ParseInteger(T &aInteger, const std::string &aStr)
{
Error error;
uint64_t integer;
char * endPtr = nullptr;
integer = strtoull(aStr.c_str(), &endPtr, 0);
VerifyOrExit(endPtr != nullptr && endPtr > aStr.c_str(),
error = ERROR_INVALID_ARGS("{} is not a valid integer", aStr));
aInteger = integer;
exit:
return error;
}
std::string ToLower(const std::string &aStr)
{
std::string ret = aStr;
for (auto &c : ret)
{
c = tolower(c);
}
return ret;
}
static inline bool CaseInsensitiveEqual(const std::string &aLhs, const std::string &aRhs)
{
return ToLower(aLhs) == ToLower(aRhs);
}
Error Interpreter::Init(const std::string &aConfigFile)
{
Error error;
std::string configJson;
Config config;
SuccessOrExit(error = ReadFile(configJson, aConfigFile));
SuccessOrExit(error = ConfigFromJson(config, configJson));
SuccessOrExit(error = CommissionerApp::Create(mCommissioner, config));
exit:
return error;
}
void Interpreter::Run()
{
Expression expr;
VerifyOrExit(mCommissioner != nullptr);
while (!mShouldExit)
{
Print(Eval(Read()));
}
exit:
return;
}
void Interpreter::AbortCommand()
{
if (mCommissioner->IsActive())
{
mCommissioner->AbortRequests();
}
else
{
mCommissioner->Stop();
}
}
Interpreter::Expression Interpreter::Read()
{
return ParseExpression(mConsole.Read());
}
Interpreter::Value Interpreter::Eval(const Expression &aExpr)
{
Value value;
std::map<std::string, Evaluator>::const_iterator evaluator;
VerifyOrExit(!aExpr.empty(), value = ERROR_NONE);
evaluator = mEvaluatorMap.find(ToLower(aExpr.front()));
if (evaluator == mEvaluatorMap.end())
{
ExitNow(value = ERROR_INVALID_COMMAND("'{}' is not a valid command, type 'help' to list all commands",
aExpr.front()));
}
value = evaluator->second(this, aExpr);
exit:
return value;
}
void Interpreter::Print(const Value &aValue)
{
std::string output = aValue.ToString();
if (!output.empty())
{
output += "\n";
}
output += aValue.HasNoError() ? "[done]" : "[failed]";
auto color = aValue.HasNoError() ? Console::Color::kGreen : Console::Color::kRed;
mConsole.Write(output, color);
}
std::string Interpreter::Value::ToString() const
{
return HasNoError() ? mData : mError.ToString();
}
bool Interpreter::Value::HasNoError() const
{
return mError == ErrorCode::kNone;
}
Interpreter::Expression Interpreter::ParseExpression(const std::string &aLiteral)
{
Expression expr;
bool inSingleQuotes = false;
auto begin = aLiteral.end();
for (auto c = aLiteral.begin(); c != aLiteral.end(); ++c)
{
if (inSingleQuotes)
{
if (*c == '\'')
{
VerifyOrDie(begin != aLiteral.end());
expr.emplace_back(begin, c);
begin = aLiteral.end();
inSingleQuotes = false;
}
}
else
{
if (isspace(*c))
{
if (begin != aLiteral.end())
{
expr.emplace_back(begin, c);
begin = aLiteral.end();
}
}
else if (*c == '\'')
{
inSingleQuotes = true;
begin = c + 1;
}
else if (begin == aLiteral.end())
{
begin = c;
}
}
}
if (begin != aLiteral.end())
{
expr.emplace_back(begin, aLiteral.end());
}
return expr;
}
Interpreter::Value Interpreter::ProcessStart(const Expression &aExpr)
{
Error error;
uint16_t port;
std::string existingCommissionerId;
VerifyOrExit(aExpr.size() >= 3, error = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(error = ParseInteger(port, aExpr[2]));
SuccessOrExit(error = mCommissioner->Start(existingCommissionerId, aExpr[1], port));
exit:
if (!existingCommissionerId.empty())
{
ASSERT(error != ErrorCode::kNone);
error = Error{error.GetCode(), "there is an existing active commissioner: " + existingCommissionerId};
}
return error;
}
Interpreter::Value Interpreter::ProcessStop(const Expression &)
{
mCommissioner->Stop();
return ERROR_NONE;
}
Interpreter::Value Interpreter::ProcessActive(const Expression &)
{
return std::string{mCommissioner->IsActive() ? "true" : "false"};
}
Interpreter::Value Interpreter::ProcessToken(const Expression &aExpr)
{
Value value;
VerifyOrExit(aExpr.size() >= 2, value = ERROR_INVALID_ARGS("too few arguments"));
if (CaseInsensitiveEqual(aExpr[1], "request"))
{
uint16_t port;
VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(port, aExpr[3]));
SuccessOrExit(value = mCommissioner->RequestToken(aExpr[2], port));
}
else if (CaseInsensitiveEqual(aExpr[1], "print"))
{
auto signedToken = mCommissioner->GetToken();
VerifyOrExit(!signedToken.empty(), value = ERROR_NOT_FOUND("no valid Commissioner Token found"));
value = utils::Hex(signedToken);
}
else if (CaseInsensitiveEqual(aExpr[1], "set"))
{
ByteArray signedToken, signerCert;
VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ReadHexStringFile(signedToken, aExpr[2]));
SuccessOrExit(value = ReadPemFile(signerCert, aExpr[3]));
SuccessOrExit(value = mCommissioner->SetToken(signedToken, signerCert));
}
else
{
ExitNow(value = ERROR_INVALID_COMMAND("{} is not a valid sub-command", aExpr[1]));
}
exit:
return value;
}
Interpreter::Value Interpreter::ProcessNetwork(const Expression &aExpr)
{
Value value;
VerifyOrExit(aExpr.size() >= 2, value = ERROR_INVALID_ARGS("too few arguments"));
if (CaseInsensitiveEqual(aExpr[1], "save"))
{
VerifyOrExit(aExpr.size() >= 3, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = mCommissioner->SaveNetworkData(aExpr[2]));
}
else if (CaseInsensitiveEqual(aExpr[1], "sync"))
{
SuccessOrExit(value = mCommissioner->SyncNetworkData());
}
else
{
ExitNow(value = ERROR_INVALID_COMMAND("{} is not a valid sub-command", aExpr[1]));
}
exit:
return value;
}
Interpreter::Value Interpreter::ProcessSessionId(const Expression &)
{
Value value;
uint16_t sessionId;
SuccessOrExit(value = mCommissioner->GetSessionId(sessionId));
value = std::to_string(sessionId);
exit:
return value;
}
Interpreter::Value Interpreter::ProcessBorderAgent(const Expression &aExpr)
{
Value value;
VerifyOrExit(aExpr.size() >= 2, value = ERROR_INVALID_ARGS("too few arguments"));
if (CaseInsensitiveEqual(aExpr[1], "discover"))
{
uint64_t timeout = 4000;
if (aExpr.size() >= 3)
{
SuccessOrExit(value = ParseInteger(timeout, aExpr[2]));
}
SuccessOrExit(value = DiscoverBorderAgent(BorderAgentHandler, static_cast<size_t>(timeout)));
}
else if (CaseInsensitiveEqual(aExpr[1], "get"))
{
VerifyOrExit(aExpr.size() >= 3, value = ERROR_INVALID_ARGS("too few arguments"));
if (CaseInsensitiveEqual(aExpr[2], "locator"))
{
uint16_t locator;
SuccessOrExit(value = mCommissioner->GetBorderAgentLocator(locator));
value = ToHex(locator);
}
else if (CaseInsensitiveEqual(aExpr[2], "meshlocaladdr"))
{
uint16_t locator;
std::string meshLocalPrefix;
std::string meshLocalAddr;
SuccessOrExit(value = mCommissioner->GetBorderAgentLocator(locator));
SuccessOrExit(value = mCommissioner->GetMeshLocalPrefix(meshLocalPrefix));
SuccessOrExit(value = Commissioner::GetMeshLocalAddr(meshLocalAddr, meshLocalPrefix, locator));
value = meshLocalAddr;
}
else
{
value = ERROR_INVALID_ARGS("{} is not a valid border agent field", aExpr[2]);
}
}
else
{
value = ERROR_INVALID_COMMAND("{} is not a valid sub-command", aExpr[1]);
}
exit:
return value;
}
Interpreter::Value Interpreter::ProcessJoiner(const Expression &aExpr)
{
Value value;
JoinerType type;
VerifyOrExit(aExpr.size() >= 3, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = GetJoinerType(type, aExpr[2]));
if (CaseInsensitiveEqual(aExpr[1], "enable"))
{
uint64_t eui64;
std::string pskd;
std::string provisioningUrl;
VerifyOrExit(aExpr.size() >= (type == JoinerType::kMeshCoP ? 5 : 4),
value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(eui64, aExpr[3]));
if (type == JoinerType::kMeshCoP)
{
pskd = aExpr[4];
if (aExpr.size() >= 6)
{
provisioningUrl = aExpr[5];
}
}
SuccessOrExit(value = mCommissioner->EnableJoiner(type, eui64, pskd, provisioningUrl));
}
else if (CaseInsensitiveEqual(aExpr[1], "enableall"))
{
std::string pskd;
std::string provisioningUrl;
if (type == JoinerType::kMeshCoP)
{
VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("too few arguments"));
pskd = aExpr[3];
if (aExpr.size() >= 5)
{
provisioningUrl = aExpr[4];
}
}
SuccessOrExit(value = mCommissioner->EnableAllJoiners(type, pskd, provisioningUrl));
}
else if (CaseInsensitiveEqual(aExpr[1], "disable"))
{
uint64_t eui64;
VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(eui64, aExpr[3]));
SuccessOrExit(value = mCommissioner->DisableJoiner(type, eui64));
}
else if (CaseInsensitiveEqual(aExpr[1], "disableall"))
{
SuccessOrExit(value = mCommissioner->DisableAllJoiners(type));
}
else if (CaseInsensitiveEqual(aExpr[1], "getport"))
{
uint16_t port;
SuccessOrExit(value = mCommissioner->GetJoinerUdpPort(port, type));
value = std::to_string(port);
}
else if (CaseInsensitiveEqual(aExpr[1], "setport"))
{
uint16_t port;
VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(port, aExpr[3]));
SuccessOrExit(value = mCommissioner->SetJoinerUdpPort(type, port));
}
else
{
value = ERROR_INVALID_COMMAND("{} is not a valid sub-command", aExpr[1]);
}
exit:
return value;
}
Interpreter::Value Interpreter::ProcessCommDataset(const Expression &aExpr)
{
Value value;
VerifyOrExit(aExpr.size() >= 2, value = ERROR_INVALID_ARGS("too few arguments"));
if (CaseInsensitiveEqual(aExpr[1], "get"))
{
CommissionerDataset dataset;
SuccessOrExit(value = mCommissioner->GetCommissionerDataset(dataset, 0xFFFF));
value = CommissionerDatasetToJson(dataset);
}
else if (CaseInsensitiveEqual(aExpr[1], "set"))
{
CommissionerDataset dataset;
VerifyOrExit(aExpr.size() >= 3, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = CommissionerDatasetFromJson(dataset, aExpr[2]));
SuccessOrExit(value = mCommissioner->SetCommissionerDataset(dataset));
}
else
{
value = ERROR_INVALID_COMMAND("{} is not a valid sub-command", aExpr[1]);
}
exit:
return value;
}
Interpreter::Value Interpreter::ProcessOpDataset(const Expression &aExpr)
{
Value value;
bool isSet;
VerifyOrExit(aExpr.size() >= 3, value = ERROR_INVALID_ARGS("too few arguments"));
if (CaseInsensitiveEqual(aExpr[1], "get"))
{
isSet = false;
}
else if (CaseInsensitiveEqual(aExpr[1], "set"))
{
isSet = true;
}
else
{
ExitNow(value = ERROR_INVALID_COMMAND("{} is not a valid sub-command", aExpr[1]));
}
if (CaseInsensitiveEqual(aExpr[2], "activetimestamp"))
{
Timestamp activeTimestamp;
VerifyOrExit(!isSet, value = ERROR_INVALID_ARGS("cannot set activetimestamp"));
SuccessOrExit(value = mCommissioner->GetActiveTimestamp(activeTimestamp));
value = ToString(activeTimestamp);
}
else if (CaseInsensitiveEqual(aExpr[2], "channel"))
{
Channel channel;
if (isSet)
{
uint32_t delay;
VerifyOrExit(aExpr.size() >= 6, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(channel.mPage, aExpr[3]));
SuccessOrExit(value = ParseInteger(channel.mNumber, aExpr[4]));
SuccessOrExit(value = ParseInteger(delay, aExpr[5]));
SuccessOrExit(value = mCommissioner->SetChannel(channel, CommissionerApp::MilliSeconds(delay)));
}
else
{
SuccessOrExit(value = mCommissioner->GetChannel(channel));
value = ToString(channel);
}
}
else if (CaseInsensitiveEqual(aExpr[2], "channelmask"))
{
ChannelMask channelMask;
if (isSet)
{
SuccessOrExit(value = ParseChannelMask(channelMask, aExpr, 3));
SuccessOrExit(value = mCommissioner->SetChannelMask(channelMask));
}
else
{
SuccessOrExit(value = mCommissioner->GetChannelMask(channelMask));
value = ToString(channelMask);
}
}
else if (CaseInsensitiveEqual(aExpr[2], "xpanid"))
{
ByteArray xpanid;
if (isSet)
{
VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = utils::Hex(xpanid, aExpr[3]));
SuccessOrExit(value = mCommissioner->SetExtendedPanId(xpanid));
}
else
{
SuccessOrExit(value = mCommissioner->GetExtendedPanId(xpanid));
value = utils::Hex(xpanid);
}
}
else if (CaseInsensitiveEqual(aExpr[2], "meshlocalprefix"))
{
std::string prefix;
if (isSet)
{
uint32_t delay;
VerifyOrExit(aExpr.size() >= 5, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(delay, aExpr[4]));
SuccessOrExit(value = mCommissioner->SetMeshLocalPrefix(aExpr[3], CommissionerApp::MilliSeconds(delay)));
}
else
{
SuccessOrExit(value = mCommissioner->GetMeshLocalPrefix(prefix));
value = prefix;
}
}
else if (CaseInsensitiveEqual(aExpr[2], "networkmasterkey"))
{
ByteArray masterKey;
if (isSet)
{
uint32_t delay;
VerifyOrExit(aExpr.size() >= 5, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = utils::Hex(masterKey, aExpr[3]));
SuccessOrExit(value = ParseInteger(delay, aExpr[4]));
SuccessOrExit(value = mCommissioner->SetNetworkMasterKey(masterKey, CommissionerApp::MilliSeconds(delay)));
}
else
{
SuccessOrExit(value = mCommissioner->GetNetworkMasterKey(masterKey));
value = utils::Hex(masterKey);
}
}
else if (CaseInsensitiveEqual(aExpr[2], "networkname"))
{
std::string networkName;
if (isSet)
{
VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = mCommissioner->SetNetworkName(aExpr[3]));
}
else
{
SuccessOrExit(value = mCommissioner->GetNetworkName(networkName));
value = networkName;
}
}
else if (CaseInsensitiveEqual(aExpr[2], "panid"))
{
uint16_t panid;
if (isSet)
{
uint32_t delay;
VerifyOrExit(aExpr.size() >= 5, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(panid, aExpr[3]));
SuccessOrExit(value = ParseInteger(delay, aExpr[4]));
SuccessOrExit(value = mCommissioner->SetPanId(panid, CommissionerApp::MilliSeconds(delay)));
}
else
{
SuccessOrExit(value = mCommissioner->GetPanId(panid));
value = std::to_string(panid);
}
}
else if (CaseInsensitiveEqual(aExpr[2], "pskc"))
{
ByteArray pskc;
if (isSet)
{
VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = utils::Hex(pskc, aExpr[3]));
SuccessOrExit(value = mCommissioner->SetPSKc(pskc));
}
else
{
SuccessOrExit(value = mCommissioner->GetPSKc(pskc));
value = utils::Hex(pskc);
}
}
else if (CaseInsensitiveEqual(aExpr[2], "securitypolicy"))
{
SecurityPolicy policy;
if (isSet)
{
VerifyOrExit(aExpr.size() >= 5, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(policy.mRotationTime, aExpr[3]));
SuccessOrExit(value = utils::Hex(policy.mFlags, aExpr[4]));
SuccessOrExit(value = mCommissioner->SetSecurityPolicy(policy));
}
else
{
SuccessOrExit(value = mCommissioner->GetSecurityPolicy(policy));
value = ToString(policy);
}
}
else if (CaseInsensitiveEqual(aExpr[2], "active"))
{
ActiveOperationalDataset dataset;
if (isSet)
{
VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ActiveDatasetFromJson(dataset, aExpr[3]));
SuccessOrExit(value = mCommissioner->SetActiveDataset(dataset));
}
else
{
SuccessOrExit(value = mCommissioner->GetActiveDataset(dataset, 0xFFFF));
value = ActiveDatasetToJson(dataset);
}
}
else if (CaseInsensitiveEqual(aExpr[2], "pending"))
{
PendingOperationalDataset dataset;
if (isSet)
{
VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = PendingDatasetFromJson(dataset, aExpr[3]));
SuccessOrExit(value = mCommissioner->SetPendingDataset(dataset));
}
else
{
SuccessOrExit(value = mCommissioner->GetPendingDataset(dataset, 0xFFFF));
value = PendingDatasetToJson(dataset);
}
}
else
{
value = ERROR_INVALID_ARGS("{} is not a valid Operational Dataset field", aExpr[2]);
}
exit:
return value;
}
Interpreter::Value Interpreter::ProcessBbrDataset(const Expression &aExpr)
{
Value value;
bool isSet;
VerifyOrExit(aExpr.size() >= 2, value = ERROR_INVALID_ARGS("too few arguments"));
if (CaseInsensitiveEqual(aExpr[1], "get"))
{
isSet = false;
}
else if (CaseInsensitiveEqual(aExpr[1], "set"))
{
isSet = true;
}
else
{
ExitNow(value = ERROR_INVALID_COMMAND("{} is not a valid sub-command", aExpr[1]));
}
if (aExpr.size() == 2 && !isSet)
{
BbrDataset dataset;
SuccessOrExit(value = mCommissioner->GetBbrDataset(dataset, 0xFFFF));
ExitNow(value = BbrDatasetToJson(dataset));
}
VerifyOrExit(aExpr.size() >= 3, value = ERROR_INVALID_ARGS("too few arguments"));
if (CaseInsensitiveEqual(aExpr[2], "trihostname"))
{
std::string triHostname;
if (isSet)
{
VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = mCommissioner->SetTriHostname(aExpr[3]));
}
else
{
SuccessOrExit(value = mCommissioner->GetTriHostname(triHostname));
value = triHostname;
}
}
else if (CaseInsensitiveEqual(aExpr[2], "reghostname"))
{
std::string regHostname;
if (isSet)
{
VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = mCommissioner->SetRegistrarHostname(aExpr[3]));
}
else
{
SuccessOrExit(value = mCommissioner->GetRegistrarHostname(regHostname));
value = regHostname;
}
}
else if (CaseInsensitiveEqual(aExpr[2], "regaddr"))
{
std::string regAddr;
VerifyOrExit(!isSet, value = ERROR_INVALID_ARGS("cannot set read-only Registrar Address"));
SuccessOrExit(value = mCommissioner->GetRegistrarIpv6Addr(regAddr));
value = regAddr;
}
else
{
if (isSet)
{
BbrDataset dataset;
SuccessOrExit(value = BbrDatasetFromJson(dataset, aExpr[2]));
SuccessOrExit(value = mCommissioner->SetBbrDataset(dataset));
}
else
{
value = ERROR_INVALID_ARGS("{} is not a valid BBR Dataset field", aExpr[2]);
}
}
exit:
return value;
}
Interpreter::Value Interpreter::ProcessReenroll(const Expression &aExpr)
{
Value value;
VerifyOrExit(aExpr.size() >= 2, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = mCommissioner->Reenroll(aExpr[1]));
exit:
return value;
}
Interpreter::Value Interpreter::ProcessDomainReset(const Expression &aExpr)
{
Value value;
VerifyOrExit(aExpr.size() >= 2, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = mCommissioner->DomainReset(aExpr[1]));
exit:
return value;
}
Interpreter::Value Interpreter::ProcessMigrate(const Expression &aExpr)
{
Value value;
VerifyOrExit(aExpr.size() >= 3, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = mCommissioner->Migrate(aExpr[1], aExpr[2]));
exit:
return value;
}
Interpreter::Value Interpreter::ProcessMlr(const Expression &aExpr)
{
Value value;
uint32_t timeout;
VerifyOrExit(aExpr.size() >= 3, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(timeout, aExpr.back()));
SuccessOrExit(value = mCommissioner->RegisterMulticastListener({aExpr.begin() + 1, aExpr.end() - 1},
CommissionerApp::Seconds(timeout)));
exit:
return value;
}
Interpreter::Value Interpreter::ProcessAnnounce(const Expression &aExpr)
{
Value value;
uint32_t channelMask;
uint8_t count;
uint16_t period;
VerifyOrExit(aExpr.size() >= 5, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(channelMask, aExpr[1]));
SuccessOrExit(value = ParseInteger(count, aExpr[2]));
SuccessOrExit(value = ParseInteger(period, aExpr[3]));
SuccessOrExit(
value = mCommissioner->AnnounceBegin(channelMask, count, CommissionerApp::MilliSeconds(period), aExpr[4]));
exit:
return value;
}
Interpreter::Value Interpreter::ProcessPanId(const Expression &aExpr)
{
Value value;
VerifyOrExit(aExpr.size() >= 2, value = ERROR_INVALID_ARGS("too few arguments"));
if (CaseInsensitiveEqual(aExpr[1], "query"))
{
uint32_t channelMask;
uint16_t panId;
VerifyOrExit(aExpr.size() >= 5, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(channelMask, aExpr[2]));
SuccessOrExit(value = ParseInteger(panId, aExpr[3]));
SuccessOrExit(value = mCommissioner->PanIdQuery(channelMask, panId, aExpr[4]));
}
else if (CaseInsensitiveEqual(aExpr[1], "conflict"))
{
uint16_t panId;
bool conflict;
VerifyOrExit(aExpr.size() >= 3, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(panId, aExpr[2]));
conflict = mCommissioner->HasPanIdConflict(panId);
value = std::to_string(conflict);
}
else
{
value = ERROR_INVALID_COMMAND("{} is not a valid sub-command", aExpr[1]);
}
exit:
return value;
}
Interpreter::Value Interpreter::ProcessEnergy(const Expression &aExpr)
{
Value value;
VerifyOrExit(aExpr.size() >= 2, value = ERROR_INVALID_ARGS("too few arguments"));
if (CaseInsensitiveEqual(aExpr[1], "scan"))
{
uint32_t channelMask;
uint8_t count;
uint16_t period;
uint16_t scanDuration;
VerifyOrExit(aExpr.size() >= 7, value = ERROR_INVALID_ARGS("too few arguments"));
SuccessOrExit(value = ParseInteger(channelMask, aExpr[2]));
SuccessOrExit(value = ParseInteger(count, aExpr[3]));
SuccessOrExit(value = ParseInteger(period, aExpr[4]));
SuccessOrExit(value = ParseInteger(scanDuration, aExpr[5]));
SuccessOrExit(value = mCommissioner->EnergyScan(channelMask, count, period, scanDuration, aExpr[6]));
}
else if (CaseInsensitiveEqual(aExpr[1], "report"))
{
if (aExpr.size() >= 3)
{
const EnergyReport *report = nullptr;
Address dstAddr;
SuccessOrExit(value = dstAddr.Set(aExpr[2]));
report = mCommissioner->GetEnergyReport(dstAddr);
value = report == nullptr ? "null" : EnergyReportToJson(*report);
}
else
{
auto reports = mCommissioner->GetAllEnergyReports();
value = reports.empty() ? "null" : EnergyReportMapToJson(reports);
}
}
else
{
value = ERROR_INVALID_COMMAND("{} is not a valid sub-command", aExpr[1]);
}
exit:
return value;
}
Interpreter::Value Interpreter::ProcessExit(const Expression &)
{
mCommissioner->Stop();
mShouldExit = true;
return ERROR_NONE;
}
Interpreter::Value Interpreter::ProcessHelp(const Expression &aExpr)
{
Value value;
if (aExpr.size() == 1)
{
std::string data;
for (auto &kv : mEvaluatorMap)
{
data += kv.first + "\n";
}
data += "\ntype 'help <command>' for help of specific command.";
value = data;
}
else
{
std::string usage = Usage({aExpr[1]});
VerifyOrExit(!usage.empty(), value = ERROR_INVALID_ARGS("{} is not a valid command", aExpr[1]));
value = "usage:\n" + usage;
}
exit:
return value;
}
void Interpreter::BorderAgentHandler(const BorderAgent *aBorderAgent, const Error &aError)
{
if (aError != ErrorCode::kNone)
{
Console::Write(aError.ToString(), Console::Color::kRed);
}
else
{
ASSERT(aBorderAgent != nullptr);
Console::Write(ToString(*aBorderAgent), Console::Color::kGreen);
}
}
const std::string Interpreter::Usage(Expression aExpr)
{
ASSERT(aExpr.size() >= 1);
auto usage = mUsageMap.find(aExpr[0]);
return usage != mUsageMap.end() ? usage->second : "";
}
Error Interpreter::GetJoinerType(JoinerType &aType, const std::string &aStr)
{
Error error;
if (CaseInsensitiveEqual(aStr, "meshcop"))
{
aType = JoinerType::kMeshCoP;
}
else if (CaseInsensitiveEqual(aStr, "ae"))
{
aType = JoinerType::kAE;
}
else if (CaseInsensitiveEqual(aStr, "nmkp"))
{
aType = JoinerType::kNMKP;
}
else
{
error = ERROR_INVALID_ARGS("{} is not a valid joiner type", aStr);
}
return error;
}
Error Interpreter::ParseChannelMask(ChannelMask &aChannelMask, const Expression &aExpr, size_t aIndex)
{
Error error;
VerifyOrExit(aExpr.size() >= aIndex && ((aExpr.size() - aIndex) % 2 == 0),
error = ERROR_INVALID_ARGS("too few arguments"));
for (size_t i = aIndex; i < aExpr.size(); i += 2)
{
ChannelMaskEntry entry;
SuccessOrExit(error = ParseInteger(entry.mPage, aExpr[i]));
SuccessOrExit(error = utils::Hex(entry.mMasks, aExpr[i + 1]));
aChannelMask.emplace_back(entry);
}
exit:
return error;
}
std::string Interpreter::ToString(const Timestamp &aTimestamp)
{
std::string ret;
ret += "seconds=" + std::to_string(aTimestamp.mSeconds) + "\n";
ret += "ticks=" + std::to_string(aTimestamp.mTicks) + "\n";
ret += "u=" + std::to_string(aTimestamp.mU);
return ret;
}
std::string Interpreter::ToString(const Channel &aChannel)
{
std::string ret;
ret += "page=" + std::to_string(aChannel.mPage) + "\n";
ret += "channel=" + std::to_string(aChannel.mNumber);
return ret;
}
std::string Interpreter::ToString(const ChannelMask &aChannelMask)
{
std::string ret;
for (const auto &entry : aChannelMask)
{
ret += "page=" + std::to_string(entry.mPage) + "\n";
ret += "masks=" + utils::Hex(entry.mMasks) + "\n";
}
if (!ret.empty())
{
ret.pop_back();
}
return ret;
}
std::string Interpreter::ToString(const SecurityPolicy &aSecurityPolicy)
{
std::string ret;
ret += "rotationTime=" + std::to_string(aSecurityPolicy.mRotationTime) + "\n";
ret += "flags=" + utils::Hex(aSecurityPolicy.mFlags);
return ret;
}
std::string Interpreter::ToString(const EnergyReport &aReport)
{
std::string ret;
ret += ToString(aReport.mChannelMask) + "\n";
ret += "energyList=" + utils::Hex(aReport.mEnergyList);
return ret;
}
std::string Interpreter::ToString(const BorderAgent &aBorderAgent)
{
std::string ret;
#define BUILD_STRING(name, nameStr) \
if (aBorderAgent.mPresentFlags & BorderAgent::k##name##Bit) \
{ \
ret += std::string(#name "=") + nameStr + "\n"; \
};
BUILD_STRING(Addr, aBorderAgent.mAddr);
BUILD_STRING(Port, std::to_string(aBorderAgent.mPort));
BUILD_STRING(ThreadVersion, aBorderAgent.mThreadVersion);
if (aBorderAgent.mPresentFlags & BorderAgent::kStateBit)
{
ret += ToString(aBorderAgent.mState) + "\n";
}
BUILD_STRING(NetworkName, aBorderAgent.mNetworkName);
BUILD_STRING(ExtendedPanId, ToHex(aBorderAgent.mExtendedPanId));
BUILD_STRING(VendorName, aBorderAgent.mVendorName);
BUILD_STRING(ModelName, aBorderAgent.mModelName);
// TODO(wgtdkp): more fields
#undef TO_STRING
return ret;
}
std::string Interpreter::ToString(const BorderAgent::State &aState)
{
std::string ret;
ret += "State.ConnectionMode=" + std::to_string(aState.mConnectionMode) + "(" +
BaConnModeToString(aState.mConnectionMode) + ")\n";
ret += "State.ThreadIfStatus=" + std::to_string(aState.mThreadIfStatus) + "(" +
BaThreadIfStatusToString(aState.mThreadIfStatus) + ")\n";
ret += "State.Availability=" + std::to_string(aState.mAvailability) + "(" +
BaAvailabilityToString(aState.mAvailability) + ")\n";
ret += "State.BbrIsActive=" + std::to_string(aState.mBbrIsActive) + "\n";
ret += "State.BbrIsPrimary=" + std::to_string(aState.mBbrIsPrimary);
return ret;
}
std::string Interpreter::BaConnModeToString(uint32_t aConnMode)
{
switch (aConnMode)
{
case 0:
return "disallowed";
case 1:
return "PSKc";
case 2:
return "PSKd";
case 3:
return "vendor";
case 4:
return "X.509";
default:
return "reserved";
}
}
std::string Interpreter::BaThreadIfStatusToString(uint32_t aIfStatus)
{
switch (aIfStatus)
{
case 0:
return "uninitialized";
case 1:
return "inactive";
case 2:
return "active";
default:
return "reserved";
}
}
std::string Interpreter::BaAvailabilityToString(uint32_t aAvailability)
{
switch (aAvailability)
{
case 0:
return "low";
case 1:
return "high";
default:
return "reserved";
}
}
} // namespace commissioner
} // namespace ot
|
; Blinky.asm: toggles an LED attached to pin 17 (P3.7)
$MODLP52
org 0000H
ljmp myprogram
; When using a 22.1184MHz crystal in fast mode
; one cycle takes 1.0/22.1184MHz = 45.21123 ns
WaitHalfSec:
mov R2, #89
L3: mov R1, #250
L2: mov R0, #166
L1: djnz R0, L1 ; 3 cycles->3*45.21123ns*166=22.51519us
djnz R1, L2 ; 22.51519us*250=5.629ms
djnz R2, L3 ; 5.629ms*89=0.5s (approximately)
ret
myprogram:
mov SP, #7FH
mov PMOD, #0 ; Configure all ports in bidirectional mode
M0:
cpl P3.7
lcall WaitHalfSec
sjmp M0
END |
_append: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
char buf[512];
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
int fd, i=0, k=0, count=0;
char a[2]=" ", b=' ';
11: bb 20 00 00 00 mov $0x20,%ebx
{
16: 83 ec 18 sub $0x18,%esp
19: 8b 01 mov (%ecx),%eax
1b: 8b 79 04 mov 0x4(%ecx),%edi
char a[2]=" ", b=' ';
1e: 66 89 5d e6 mov %bx,-0x1a(%ebp)
if(argc <= 2){
22: 83 f8 02 cmp $0x2,%eax
25: 7f 13 jg 3a <main+0x3a>
printf(1, "need 2 argument");
27: 51 push %ecx
28: 51 push %ecx
29: 68 b8 07 00 00 push $0x7b8
2e: 6a 01 push $0x1
30: e8 2b 04 00 00 call 460 <printf>
exit();
35: e8 d8 02 00 00 call 312 <exit>
}
if((fd = open(argv[1], O_CREATE|O_RDWR)) < 0){
3a: 52 push %edx
3b: 52 push %edx
3c: 68 02 02 00 00 push $0x202
41: ff 77 04 pushl 0x4(%edi)
44: e8 09 03 00 00 call 352 <open>
49: 83 c4 10 add $0x10,%esp
4c: 85 c0 test %eax,%eax
4e: 89 c3 mov %eax,%ebx
50: 78 59 js ab <main+0xab>
printf(1, "wc: cannot open %s\n", argv[1]);
exit();
}
for(i = 2; ; i++) {
if(argv[i]){
52: 8b 57 08 mov 0x8(%edi),%edx
55: 85 d2 test %edx,%edx
57: 74 44 je 9d <main+0x9d>
59: 8d 75 e6 lea -0x1a(%ebp),%esi
5c: 83 c7 0c add $0xc,%edi
5f: 90 nop
for(k = 0; argv[i][k] != '\0'; k++){
60: 31 c0 xor %eax,%eax
if(argv[i][k] == b)
62: f6 02 df testb $0xdf,(%edx)
65: 74 12 je 79 <main+0x79>
67: 89 f6 mov %esi,%esi
69: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
break;
else
count = count + 1;
70: 83 c0 01 add $0x1,%eax
if(argv[i][k] == b)
73: f6 04 02 df testb $0xdf,(%edx,%eax,1)
77: 75 f7 jne 70 <main+0x70>
}
write ( fd,argv[i], count);
79: 83 ec 04 sub $0x4,%esp
7c: 83 c7 04 add $0x4,%edi
7f: 50 push %eax
80: 52 push %edx
81: 53 push %ebx
82: e8 ab 02 00 00 call 332 <write>
count=0;
write ( fd,a,1);
87: 83 c4 0c add $0xc,%esp
8a: 6a 01 push $0x1
8c: 56 push %esi
8d: 53 push %ebx
8e: e8 9f 02 00 00 call 332 <write>
if(argv[i]){
93: 8b 57 fc mov -0x4(%edi),%edx
96: 83 c4 10 add $0x10,%esp
99: 85 d2 test %edx,%edx
9b: 75 c3 jne 60 <main+0x60>
}
else{
close(fd);
9d: 83 ec 0c sub $0xc,%esp
a0: 53 push %ebx
a1: e8 94 02 00 00 call 33a <close>
exit();
a6: e8 67 02 00 00 call 312 <exit>
printf(1, "wc: cannot open %s\n", argv[1]);
ab: 50 push %eax
ac: ff 77 04 pushl 0x4(%edi)
af: 68 c8 07 00 00 push $0x7c8
b4: 6a 01 push $0x1
b6: e8 a5 03 00 00 call 460 <printf>
exit();
bb: e8 52 02 00 00 call 312 <exit>
000000c0 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, const char *t)
{
c0: 55 push %ebp
c1: 89 e5 mov %esp,%ebp
c3: 53 push %ebx
c4: 8b 45 08 mov 0x8(%ebp),%eax
c7: 8b 4d 0c mov 0xc(%ebp),%ecx
char *os;
os = s;
while((*s++ = *t++) != 0)
ca: 89 c2 mov %eax,%edx
cc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
d0: 83 c1 01 add $0x1,%ecx
d3: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
d7: 83 c2 01 add $0x1,%edx
da: 84 db test %bl,%bl
dc: 88 5a ff mov %bl,-0x1(%edx)
df: 75 ef jne d0 <strcpy+0x10>
;
return os;
}
e1: 5b pop %ebx
e2: 5d pop %ebp
e3: c3 ret
e4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
ea: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
000000f0 <strcmp>:
int
strcmp(const char *p, const char *q)
{
f0: 55 push %ebp
f1: 89 e5 mov %esp,%ebp
f3: 53 push %ebx
f4: 8b 55 08 mov 0x8(%ebp),%edx
f7: 8b 4d 0c mov 0xc(%ebp),%ecx
while(*p && *p == *q)
fa: 0f b6 02 movzbl (%edx),%eax
fd: 0f b6 19 movzbl (%ecx),%ebx
100: 84 c0 test %al,%al
102: 75 1c jne 120 <strcmp+0x30>
104: eb 2a jmp 130 <strcmp+0x40>
106: 8d 76 00 lea 0x0(%esi),%esi
109: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
p++, q++;
110: 83 c2 01 add $0x1,%edx
while(*p && *p == *q)
113: 0f b6 02 movzbl (%edx),%eax
p++, q++;
116: 83 c1 01 add $0x1,%ecx
119: 0f b6 19 movzbl (%ecx),%ebx
while(*p && *p == *q)
11c: 84 c0 test %al,%al
11e: 74 10 je 130 <strcmp+0x40>
120: 38 d8 cmp %bl,%al
122: 74 ec je 110 <strcmp+0x20>
return (uchar)*p - (uchar)*q;
124: 29 d8 sub %ebx,%eax
}
126: 5b pop %ebx
127: 5d pop %ebp
128: c3 ret
129: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
130: 31 c0 xor %eax,%eax
return (uchar)*p - (uchar)*q;
132: 29 d8 sub %ebx,%eax
}
134: 5b pop %ebx
135: 5d pop %ebp
136: c3 ret
137: 89 f6 mov %esi,%esi
139: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000140 <strlen>:
uint
strlen(const char *s)
{
140: 55 push %ebp
141: 89 e5 mov %esp,%ebp
143: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
146: 80 39 00 cmpb $0x0,(%ecx)
149: 74 15 je 160 <strlen+0x20>
14b: 31 d2 xor %edx,%edx
14d: 8d 76 00 lea 0x0(%esi),%esi
150: 83 c2 01 add $0x1,%edx
153: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
157: 89 d0 mov %edx,%eax
159: 75 f5 jne 150 <strlen+0x10>
;
return n;
}
15b: 5d pop %ebp
15c: c3 ret
15d: 8d 76 00 lea 0x0(%esi),%esi
for(n = 0; s[n]; n++)
160: 31 c0 xor %eax,%eax
}
162: 5d pop %ebp
163: c3 ret
164: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
16a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000170 <memset>:
void*
memset(void *dst, int c, uint n)
{
170: 55 push %ebp
171: 89 e5 mov %esp,%ebp
173: 57 push %edi
174: 8b 55 08 mov 0x8(%ebp),%edx
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
177: 8b 4d 10 mov 0x10(%ebp),%ecx
17a: 8b 45 0c mov 0xc(%ebp),%eax
17d: 89 d7 mov %edx,%edi
17f: fc cld
180: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
182: 89 d0 mov %edx,%eax
184: 5f pop %edi
185: 5d pop %ebp
186: c3 ret
187: 89 f6 mov %esi,%esi
189: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000190 <strchr>:
char*
strchr(const char *s, char c)
{
190: 55 push %ebp
191: 89 e5 mov %esp,%ebp
193: 53 push %ebx
194: 8b 45 08 mov 0x8(%ebp),%eax
197: 8b 5d 0c mov 0xc(%ebp),%ebx
for(; *s; s++)
19a: 0f b6 10 movzbl (%eax),%edx
19d: 84 d2 test %dl,%dl
19f: 74 1d je 1be <strchr+0x2e>
if(*s == c)
1a1: 38 d3 cmp %dl,%bl
1a3: 89 d9 mov %ebx,%ecx
1a5: 75 0d jne 1b4 <strchr+0x24>
1a7: eb 17 jmp 1c0 <strchr+0x30>
1a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
1b0: 38 ca cmp %cl,%dl
1b2: 74 0c je 1c0 <strchr+0x30>
for(; *s; s++)
1b4: 83 c0 01 add $0x1,%eax
1b7: 0f b6 10 movzbl (%eax),%edx
1ba: 84 d2 test %dl,%dl
1bc: 75 f2 jne 1b0 <strchr+0x20>
return (char*)s;
return 0;
1be: 31 c0 xor %eax,%eax
}
1c0: 5b pop %ebx
1c1: 5d pop %ebp
1c2: c3 ret
1c3: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
1c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000001d0 <gets>:
char*
gets(char *buf, int max)
{
1d0: 55 push %ebp
1d1: 89 e5 mov %esp,%ebp
1d3: 57 push %edi
1d4: 56 push %esi
1d5: 53 push %ebx
int i, cc;
char c;
for(i=0; i+1 < max; ){
1d6: 31 f6 xor %esi,%esi
1d8: 89 f3 mov %esi,%ebx
{
1da: 83 ec 1c sub $0x1c,%esp
1dd: 8b 7d 08 mov 0x8(%ebp),%edi
for(i=0; i+1 < max; ){
1e0: eb 2f jmp 211 <gets+0x41>
1e2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
cc = read(0, &c, 1);
1e8: 8d 45 e7 lea -0x19(%ebp),%eax
1eb: 83 ec 04 sub $0x4,%esp
1ee: 6a 01 push $0x1
1f0: 50 push %eax
1f1: 6a 00 push $0x0
1f3: e8 32 01 00 00 call 32a <read>
if(cc < 1)
1f8: 83 c4 10 add $0x10,%esp
1fb: 85 c0 test %eax,%eax
1fd: 7e 1c jle 21b <gets+0x4b>
break;
buf[i++] = c;
1ff: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
203: 83 c7 01 add $0x1,%edi
206: 88 47 ff mov %al,-0x1(%edi)
if(c == '\n' || c == '\r')
209: 3c 0a cmp $0xa,%al
20b: 74 23 je 230 <gets+0x60>
20d: 3c 0d cmp $0xd,%al
20f: 74 1f je 230 <gets+0x60>
for(i=0; i+1 < max; ){
211: 83 c3 01 add $0x1,%ebx
214: 3b 5d 0c cmp 0xc(%ebp),%ebx
217: 89 fe mov %edi,%esi
219: 7c cd jl 1e8 <gets+0x18>
21b: 89 f3 mov %esi,%ebx
break;
}
buf[i] = '\0';
return buf;
}
21d: 8b 45 08 mov 0x8(%ebp),%eax
buf[i] = '\0';
220: c6 03 00 movb $0x0,(%ebx)
}
223: 8d 65 f4 lea -0xc(%ebp),%esp
226: 5b pop %ebx
227: 5e pop %esi
228: 5f pop %edi
229: 5d pop %ebp
22a: c3 ret
22b: 90 nop
22c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
230: 8b 75 08 mov 0x8(%ebp),%esi
233: 8b 45 08 mov 0x8(%ebp),%eax
236: 01 de add %ebx,%esi
238: 89 f3 mov %esi,%ebx
buf[i] = '\0';
23a: c6 03 00 movb $0x0,(%ebx)
}
23d: 8d 65 f4 lea -0xc(%ebp),%esp
240: 5b pop %ebx
241: 5e pop %esi
242: 5f pop %edi
243: 5d pop %ebp
244: c3 ret
245: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
249: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000250 <stat>:
int
stat(const char *n, struct stat *st)
{
250: 55 push %ebp
251: 89 e5 mov %esp,%ebp
253: 56 push %esi
254: 53 push %ebx
int fd;
int r;
fd = open(n, O_RDONLY);
255: 83 ec 08 sub $0x8,%esp
258: 6a 00 push $0x0
25a: ff 75 08 pushl 0x8(%ebp)
25d: e8 f0 00 00 00 call 352 <open>
if(fd < 0)
262: 83 c4 10 add $0x10,%esp
265: 85 c0 test %eax,%eax
267: 78 27 js 290 <stat+0x40>
return -1;
r = fstat(fd, st);
269: 83 ec 08 sub $0x8,%esp
26c: ff 75 0c pushl 0xc(%ebp)
26f: 89 c3 mov %eax,%ebx
271: 50 push %eax
272: e8 f3 00 00 00 call 36a <fstat>
close(fd);
277: 89 1c 24 mov %ebx,(%esp)
r = fstat(fd, st);
27a: 89 c6 mov %eax,%esi
close(fd);
27c: e8 b9 00 00 00 call 33a <close>
return r;
281: 83 c4 10 add $0x10,%esp
}
284: 8d 65 f8 lea -0x8(%ebp),%esp
287: 89 f0 mov %esi,%eax
289: 5b pop %ebx
28a: 5e pop %esi
28b: 5d pop %ebp
28c: c3 ret
28d: 8d 76 00 lea 0x0(%esi),%esi
return -1;
290: be ff ff ff ff mov $0xffffffff,%esi
295: eb ed jmp 284 <stat+0x34>
297: 89 f6 mov %esi,%esi
299: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000002a0 <atoi>:
int
atoi(const char *s)
{
2a0: 55 push %ebp
2a1: 89 e5 mov %esp,%ebp
2a3: 53 push %ebx
2a4: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
n = 0;
while('0' <= *s && *s <= '9')
2a7: 0f be 11 movsbl (%ecx),%edx
2aa: 8d 42 d0 lea -0x30(%edx),%eax
2ad: 3c 09 cmp $0x9,%al
n = 0;
2af: b8 00 00 00 00 mov $0x0,%eax
while('0' <= *s && *s <= '9')
2b4: 77 1f ja 2d5 <atoi+0x35>
2b6: 8d 76 00 lea 0x0(%esi),%esi
2b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
n = n*10 + *s++ - '0';
2c0: 8d 04 80 lea (%eax,%eax,4),%eax
2c3: 83 c1 01 add $0x1,%ecx
2c6: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
while('0' <= *s && *s <= '9')
2ca: 0f be 11 movsbl (%ecx),%edx
2cd: 8d 5a d0 lea -0x30(%edx),%ebx
2d0: 80 fb 09 cmp $0x9,%bl
2d3: 76 eb jbe 2c0 <atoi+0x20>
return n;
}
2d5: 5b pop %ebx
2d6: 5d pop %ebp
2d7: c3 ret
2d8: 90 nop
2d9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
000002e0 <memmove>:
void*
memmove(void *vdst, const void *vsrc, int n)
{
2e0: 55 push %ebp
2e1: 89 e5 mov %esp,%ebp
2e3: 56 push %esi
2e4: 53 push %ebx
2e5: 8b 5d 10 mov 0x10(%ebp),%ebx
2e8: 8b 45 08 mov 0x8(%ebp),%eax
2eb: 8b 75 0c mov 0xc(%ebp),%esi
char *dst;
const char *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
2ee: 85 db test %ebx,%ebx
2f0: 7e 14 jle 306 <memmove+0x26>
2f2: 31 d2 xor %edx,%edx
2f4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
*dst++ = *src++;
2f8: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
2fc: 88 0c 10 mov %cl,(%eax,%edx,1)
2ff: 83 c2 01 add $0x1,%edx
while(n-- > 0)
302: 39 d3 cmp %edx,%ebx
304: 75 f2 jne 2f8 <memmove+0x18>
return vdst;
}
306: 5b pop %ebx
307: 5e pop %esi
308: 5d pop %ebp
309: c3 ret
0000030a <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
30a: b8 01 00 00 00 mov $0x1,%eax
30f: cd 40 int $0x40
311: c3 ret
00000312 <exit>:
SYSCALL(exit)
312: b8 02 00 00 00 mov $0x2,%eax
317: cd 40 int $0x40
319: c3 ret
0000031a <wait>:
SYSCALL(wait)
31a: b8 03 00 00 00 mov $0x3,%eax
31f: cd 40 int $0x40
321: c3 ret
00000322 <pipe>:
SYSCALL(pipe)
322: b8 04 00 00 00 mov $0x4,%eax
327: cd 40 int $0x40
329: c3 ret
0000032a <read>:
SYSCALL(read)
32a: b8 05 00 00 00 mov $0x5,%eax
32f: cd 40 int $0x40
331: c3 ret
00000332 <write>:
SYSCALL(write)
332: b8 10 00 00 00 mov $0x10,%eax
337: cd 40 int $0x40
339: c3 ret
0000033a <close>:
SYSCALL(close)
33a: b8 15 00 00 00 mov $0x15,%eax
33f: cd 40 int $0x40
341: c3 ret
00000342 <kill>:
SYSCALL(kill)
342: b8 06 00 00 00 mov $0x6,%eax
347: cd 40 int $0x40
349: c3 ret
0000034a <exec>:
SYSCALL(exec)
34a: b8 07 00 00 00 mov $0x7,%eax
34f: cd 40 int $0x40
351: c3 ret
00000352 <open>:
SYSCALL(open)
352: b8 0f 00 00 00 mov $0xf,%eax
357: cd 40 int $0x40
359: c3 ret
0000035a <mknod>:
SYSCALL(mknod)
35a: b8 11 00 00 00 mov $0x11,%eax
35f: cd 40 int $0x40
361: c3 ret
00000362 <unlink>:
SYSCALL(unlink)
362: b8 12 00 00 00 mov $0x12,%eax
367: cd 40 int $0x40
369: c3 ret
0000036a <fstat>:
SYSCALL(fstat)
36a: b8 08 00 00 00 mov $0x8,%eax
36f: cd 40 int $0x40
371: c3 ret
00000372 <link>:
SYSCALL(link)
372: b8 13 00 00 00 mov $0x13,%eax
377: cd 40 int $0x40
379: c3 ret
0000037a <mkdir>:
SYSCALL(mkdir)
37a: b8 14 00 00 00 mov $0x14,%eax
37f: cd 40 int $0x40
381: c3 ret
00000382 <chdir>:
SYSCALL(chdir)
382: b8 09 00 00 00 mov $0x9,%eax
387: cd 40 int $0x40
389: c3 ret
0000038a <dup>:
SYSCALL(dup)
38a: b8 0a 00 00 00 mov $0xa,%eax
38f: cd 40 int $0x40
391: c3 ret
00000392 <getpid>:
SYSCALL(getpid)
392: b8 0b 00 00 00 mov $0xb,%eax
397: cd 40 int $0x40
399: c3 ret
0000039a <sbrk>:
SYSCALL(sbrk)
39a: b8 0c 00 00 00 mov $0xc,%eax
39f: cd 40 int $0x40
3a1: c3 ret
000003a2 <sleep>:
SYSCALL(sleep)
3a2: b8 0d 00 00 00 mov $0xd,%eax
3a7: cd 40 int $0x40
3a9: c3 ret
000003aa <uptime>:
SYSCALL(uptime)
3aa: b8 0e 00 00 00 mov $0xe,%eax
3af: cd 40 int $0x40
3b1: c3 ret
000003b2 <cps>:
SYSCALL(cps)
3b2: b8 16 00 00 00 mov $0x16,%eax
3b7: cd 40 int $0x40
3b9: c3 ret
3ba: 66 90 xchg %ax,%ax
3bc: 66 90 xchg %ax,%ax
3be: 66 90 xchg %ax,%ax
000003c0 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
3c0: 55 push %ebp
3c1: 89 e5 mov %esp,%ebp
3c3: 57 push %edi
3c4: 56 push %esi
3c5: 53 push %ebx
3c6: 83 ec 3c sub $0x3c,%esp
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
3c9: 85 d2 test %edx,%edx
{
3cb: 89 45 c0 mov %eax,-0x40(%ebp)
neg = 1;
x = -xx;
3ce: 89 d0 mov %edx,%eax
if(sgn && xx < 0){
3d0: 79 76 jns 448 <printint+0x88>
3d2: f6 45 08 01 testb $0x1,0x8(%ebp)
3d6: 74 70 je 448 <printint+0x88>
x = -xx;
3d8: f7 d8 neg %eax
neg = 1;
3da: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
} else {
x = xx;
}
i = 0;
3e1: 31 f6 xor %esi,%esi
3e3: 8d 5d d7 lea -0x29(%ebp),%ebx
3e6: eb 0a jmp 3f2 <printint+0x32>
3e8: 90 nop
3e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
do{
buf[i++] = digits[x % base];
3f0: 89 fe mov %edi,%esi
3f2: 31 d2 xor %edx,%edx
3f4: 8d 7e 01 lea 0x1(%esi),%edi
3f7: f7 f1 div %ecx
3f9: 0f b6 92 e4 07 00 00 movzbl 0x7e4(%edx),%edx
}while((x /= base) != 0);
400: 85 c0 test %eax,%eax
buf[i++] = digits[x % base];
402: 88 14 3b mov %dl,(%ebx,%edi,1)
}while((x /= base) != 0);
405: 75 e9 jne 3f0 <printint+0x30>
if(neg)
407: 8b 45 c4 mov -0x3c(%ebp),%eax
40a: 85 c0 test %eax,%eax
40c: 74 08 je 416 <printint+0x56>
buf[i++] = '-';
40e: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1)
413: 8d 7e 02 lea 0x2(%esi),%edi
416: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi
41a: 8b 7d c0 mov -0x40(%ebp),%edi
41d: 8d 76 00 lea 0x0(%esi),%esi
420: 0f b6 06 movzbl (%esi),%eax
write(fd, &c, 1);
423: 83 ec 04 sub $0x4,%esp
426: 83 ee 01 sub $0x1,%esi
429: 6a 01 push $0x1
42b: 53 push %ebx
42c: 57 push %edi
42d: 88 45 d7 mov %al,-0x29(%ebp)
430: e8 fd fe ff ff call 332 <write>
while(--i >= 0)
435: 83 c4 10 add $0x10,%esp
438: 39 de cmp %ebx,%esi
43a: 75 e4 jne 420 <printint+0x60>
putc(fd, buf[i]);
}
43c: 8d 65 f4 lea -0xc(%ebp),%esp
43f: 5b pop %ebx
440: 5e pop %esi
441: 5f pop %edi
442: 5d pop %ebp
443: c3 ret
444: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
neg = 0;
448: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
44f: eb 90 jmp 3e1 <printint+0x21>
451: eb 0d jmp 460 <printf>
453: 90 nop
454: 90 nop
455: 90 nop
456: 90 nop
457: 90 nop
458: 90 nop
459: 90 nop
45a: 90 nop
45b: 90 nop
45c: 90 nop
45d: 90 nop
45e: 90 nop
45f: 90 nop
00000460 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
460: 55 push %ebp
461: 89 e5 mov %esp,%ebp
463: 57 push %edi
464: 56 push %esi
465: 53 push %ebx
466: 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++){
469: 8b 75 0c mov 0xc(%ebp),%esi
46c: 0f b6 1e movzbl (%esi),%ebx
46f: 84 db test %bl,%bl
471: 0f 84 b3 00 00 00 je 52a <printf+0xca>
ap = (uint*)(void*)&fmt + 1;
477: 8d 45 10 lea 0x10(%ebp),%eax
47a: 83 c6 01 add $0x1,%esi
state = 0;
47d: 31 ff xor %edi,%edi
ap = (uint*)(void*)&fmt + 1;
47f: 89 45 d4 mov %eax,-0x2c(%ebp)
482: eb 2f jmp 4b3 <printf+0x53>
484: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
488: 83 f8 25 cmp $0x25,%eax
48b: 0f 84 a7 00 00 00 je 538 <printf+0xd8>
write(fd, &c, 1);
491: 8d 45 e2 lea -0x1e(%ebp),%eax
494: 83 ec 04 sub $0x4,%esp
497: 88 5d e2 mov %bl,-0x1e(%ebp)
49a: 6a 01 push $0x1
49c: 50 push %eax
49d: ff 75 08 pushl 0x8(%ebp)
4a0: e8 8d fe ff ff call 332 <write>
4a5: 83 c4 10 add $0x10,%esp
4a8: 83 c6 01 add $0x1,%esi
for(i = 0; fmt[i]; i++){
4ab: 0f b6 5e ff movzbl -0x1(%esi),%ebx
4af: 84 db test %bl,%bl
4b1: 74 77 je 52a <printf+0xca>
if(state == 0){
4b3: 85 ff test %edi,%edi
c = fmt[i] & 0xff;
4b5: 0f be cb movsbl %bl,%ecx
4b8: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
4bb: 74 cb je 488 <printf+0x28>
state = '%';
} else {
putc(fd, c);
}
} else if(state == '%'){
4bd: 83 ff 25 cmp $0x25,%edi
4c0: 75 e6 jne 4a8 <printf+0x48>
if(c == 'd'){
4c2: 83 f8 64 cmp $0x64,%eax
4c5: 0f 84 05 01 00 00 je 5d0 <printf+0x170>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
4cb: 81 e1 f7 00 00 00 and $0xf7,%ecx
4d1: 83 f9 70 cmp $0x70,%ecx
4d4: 74 72 je 548 <printf+0xe8>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
4d6: 83 f8 73 cmp $0x73,%eax
4d9: 0f 84 99 00 00 00 je 578 <printf+0x118>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
4df: 83 f8 63 cmp $0x63,%eax
4e2: 0f 84 08 01 00 00 je 5f0 <printf+0x190>
putc(fd, *ap);
ap++;
} else if(c == '%'){
4e8: 83 f8 25 cmp $0x25,%eax
4eb: 0f 84 ef 00 00 00 je 5e0 <printf+0x180>
write(fd, &c, 1);
4f1: 8d 45 e7 lea -0x19(%ebp),%eax
4f4: 83 ec 04 sub $0x4,%esp
4f7: c6 45 e7 25 movb $0x25,-0x19(%ebp)
4fb: 6a 01 push $0x1
4fd: 50 push %eax
4fe: ff 75 08 pushl 0x8(%ebp)
501: e8 2c fe ff ff call 332 <write>
506: 83 c4 0c add $0xc,%esp
509: 8d 45 e6 lea -0x1a(%ebp),%eax
50c: 88 5d e6 mov %bl,-0x1a(%ebp)
50f: 6a 01 push $0x1
511: 50 push %eax
512: ff 75 08 pushl 0x8(%ebp)
515: 83 c6 01 add $0x1,%esi
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
518: 31 ff xor %edi,%edi
write(fd, &c, 1);
51a: e8 13 fe ff ff call 332 <write>
for(i = 0; fmt[i]; i++){
51f: 0f b6 5e ff movzbl -0x1(%esi),%ebx
write(fd, &c, 1);
523: 83 c4 10 add $0x10,%esp
for(i = 0; fmt[i]; i++){
526: 84 db test %bl,%bl
528: 75 89 jne 4b3 <printf+0x53>
}
}
}
52a: 8d 65 f4 lea -0xc(%ebp),%esp
52d: 5b pop %ebx
52e: 5e pop %esi
52f: 5f pop %edi
530: 5d pop %ebp
531: c3 ret
532: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
state = '%';
538: bf 25 00 00 00 mov $0x25,%edi
53d: e9 66 ff ff ff jmp 4a8 <printf+0x48>
542: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
printint(fd, *ap, 16, 0);
548: 83 ec 0c sub $0xc,%esp
54b: b9 10 00 00 00 mov $0x10,%ecx
550: 6a 00 push $0x0
552: 8b 7d d4 mov -0x2c(%ebp),%edi
555: 8b 45 08 mov 0x8(%ebp),%eax
558: 8b 17 mov (%edi),%edx
55a: e8 61 fe ff ff call 3c0 <printint>
ap++;
55f: 89 f8 mov %edi,%eax
561: 83 c4 10 add $0x10,%esp
state = 0;
564: 31 ff xor %edi,%edi
ap++;
566: 83 c0 04 add $0x4,%eax
569: 89 45 d4 mov %eax,-0x2c(%ebp)
56c: e9 37 ff ff ff jmp 4a8 <printf+0x48>
571: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
s = (char*)*ap;
578: 8b 45 d4 mov -0x2c(%ebp),%eax
57b: 8b 08 mov (%eax),%ecx
ap++;
57d: 83 c0 04 add $0x4,%eax
580: 89 45 d4 mov %eax,-0x2c(%ebp)
if(s == 0)
583: 85 c9 test %ecx,%ecx
585: 0f 84 8e 00 00 00 je 619 <printf+0x1b9>
while(*s != 0){
58b: 0f b6 01 movzbl (%ecx),%eax
state = 0;
58e: 31 ff xor %edi,%edi
s = (char*)*ap;
590: 89 cb mov %ecx,%ebx
while(*s != 0){
592: 84 c0 test %al,%al
594: 0f 84 0e ff ff ff je 4a8 <printf+0x48>
59a: 89 75 d0 mov %esi,-0x30(%ebp)
59d: 89 de mov %ebx,%esi
59f: 8b 5d 08 mov 0x8(%ebp),%ebx
5a2: 8d 7d e3 lea -0x1d(%ebp),%edi
5a5: 8d 76 00 lea 0x0(%esi),%esi
write(fd, &c, 1);
5a8: 83 ec 04 sub $0x4,%esp
s++;
5ab: 83 c6 01 add $0x1,%esi
5ae: 88 45 e3 mov %al,-0x1d(%ebp)
write(fd, &c, 1);
5b1: 6a 01 push $0x1
5b3: 57 push %edi
5b4: 53 push %ebx
5b5: e8 78 fd ff ff call 332 <write>
while(*s != 0){
5ba: 0f b6 06 movzbl (%esi),%eax
5bd: 83 c4 10 add $0x10,%esp
5c0: 84 c0 test %al,%al
5c2: 75 e4 jne 5a8 <printf+0x148>
5c4: 8b 75 d0 mov -0x30(%ebp),%esi
state = 0;
5c7: 31 ff xor %edi,%edi
5c9: e9 da fe ff ff jmp 4a8 <printf+0x48>
5ce: 66 90 xchg %ax,%ax
printint(fd, *ap, 10, 1);
5d0: 83 ec 0c sub $0xc,%esp
5d3: b9 0a 00 00 00 mov $0xa,%ecx
5d8: 6a 01 push $0x1
5da: e9 73 ff ff ff jmp 552 <printf+0xf2>
5df: 90 nop
write(fd, &c, 1);
5e0: 83 ec 04 sub $0x4,%esp
5e3: 88 5d e5 mov %bl,-0x1b(%ebp)
5e6: 8d 45 e5 lea -0x1b(%ebp),%eax
5e9: 6a 01 push $0x1
5eb: e9 21 ff ff ff jmp 511 <printf+0xb1>
putc(fd, *ap);
5f0: 8b 7d d4 mov -0x2c(%ebp),%edi
write(fd, &c, 1);
5f3: 83 ec 04 sub $0x4,%esp
putc(fd, *ap);
5f6: 8b 07 mov (%edi),%eax
write(fd, &c, 1);
5f8: 6a 01 push $0x1
ap++;
5fa: 83 c7 04 add $0x4,%edi
putc(fd, *ap);
5fd: 88 45 e4 mov %al,-0x1c(%ebp)
write(fd, &c, 1);
600: 8d 45 e4 lea -0x1c(%ebp),%eax
603: 50 push %eax
604: ff 75 08 pushl 0x8(%ebp)
607: e8 26 fd ff ff call 332 <write>
ap++;
60c: 89 7d d4 mov %edi,-0x2c(%ebp)
60f: 83 c4 10 add $0x10,%esp
state = 0;
612: 31 ff xor %edi,%edi
614: e9 8f fe ff ff jmp 4a8 <printf+0x48>
s = "(null)";
619: bb dc 07 00 00 mov $0x7dc,%ebx
while(*s != 0){
61e: b8 28 00 00 00 mov $0x28,%eax
623: e9 72 ff ff ff jmp 59a <printf+0x13a>
628: 66 90 xchg %ax,%ax
62a: 66 90 xchg %ax,%ax
62c: 66 90 xchg %ax,%ax
62e: 66 90 xchg %ax,%ax
00000630 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
630: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
631: a1 a0 0a 00 00 mov 0xaa0,%eax
{
636: 89 e5 mov %esp,%ebp
638: 57 push %edi
639: 56 push %esi
63a: 53 push %ebx
63b: 8b 5d 08 mov 0x8(%ebp),%ebx
bp = (Header*)ap - 1;
63e: 8d 4b f8 lea -0x8(%ebx),%ecx
641: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
648: 39 c8 cmp %ecx,%eax
64a: 8b 10 mov (%eax),%edx
64c: 73 32 jae 680 <free+0x50>
64e: 39 d1 cmp %edx,%ecx
650: 72 04 jb 656 <free+0x26>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
652: 39 d0 cmp %edx,%eax
654: 72 32 jb 688 <free+0x58>
break;
if(bp + bp->s.size == p->s.ptr){
656: 8b 73 fc mov -0x4(%ebx),%esi
659: 8d 3c f1 lea (%ecx,%esi,8),%edi
65c: 39 fa cmp %edi,%edx
65e: 74 30 je 690 <free+0x60>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
660: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
663: 8b 50 04 mov 0x4(%eax),%edx
666: 8d 34 d0 lea (%eax,%edx,8),%esi
669: 39 f1 cmp %esi,%ecx
66b: 74 3a je 6a7 <free+0x77>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
66d: 89 08 mov %ecx,(%eax)
freep = p;
66f: a3 a0 0a 00 00 mov %eax,0xaa0
}
674: 5b pop %ebx
675: 5e pop %esi
676: 5f pop %edi
677: 5d pop %ebp
678: c3 ret
679: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
680: 39 d0 cmp %edx,%eax
682: 72 04 jb 688 <free+0x58>
684: 39 d1 cmp %edx,%ecx
686: 72 ce jb 656 <free+0x26>
{
688: 89 d0 mov %edx,%eax
68a: eb bc jmp 648 <free+0x18>
68c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
bp->s.size += p->s.ptr->s.size;
690: 03 72 04 add 0x4(%edx),%esi
693: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
696: 8b 10 mov (%eax),%edx
698: 8b 12 mov (%edx),%edx
69a: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
69d: 8b 50 04 mov 0x4(%eax),%edx
6a0: 8d 34 d0 lea (%eax,%edx,8),%esi
6a3: 39 f1 cmp %esi,%ecx
6a5: 75 c6 jne 66d <free+0x3d>
p->s.size += bp->s.size;
6a7: 03 53 fc add -0x4(%ebx),%edx
freep = p;
6aa: a3 a0 0a 00 00 mov %eax,0xaa0
p->s.size += bp->s.size;
6af: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
6b2: 8b 53 f8 mov -0x8(%ebx),%edx
6b5: 89 10 mov %edx,(%eax)
}
6b7: 5b pop %ebx
6b8: 5e pop %esi
6b9: 5f pop %edi
6ba: 5d pop %ebp
6bb: c3 ret
6bc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
000006c0 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
6c0: 55 push %ebp
6c1: 89 e5 mov %esp,%ebp
6c3: 57 push %edi
6c4: 56 push %esi
6c5: 53 push %ebx
6c6: 83 ec 0c sub $0xc,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
6c9: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
6cc: 8b 15 a0 0a 00 00 mov 0xaa0,%edx
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
6d2: 8d 78 07 lea 0x7(%eax),%edi
6d5: c1 ef 03 shr $0x3,%edi
6d8: 83 c7 01 add $0x1,%edi
if((prevp = freep) == 0){
6db: 85 d2 test %edx,%edx
6dd: 0f 84 9d 00 00 00 je 780 <malloc+0xc0>
6e3: 8b 02 mov (%edx),%eax
6e5: 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){
6e8: 39 cf cmp %ecx,%edi
6ea: 76 6c jbe 758 <malloc+0x98>
6ec: 81 ff 00 10 00 00 cmp $0x1000,%edi
6f2: bb 00 10 00 00 mov $0x1000,%ebx
6f7: 0f 43 df cmovae %edi,%ebx
p = sbrk(nu * sizeof(Header));
6fa: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi
701: eb 0e jmp 711 <malloc+0x51>
703: 90 nop
704: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
708: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
70a: 8b 48 04 mov 0x4(%eax),%ecx
70d: 39 f9 cmp %edi,%ecx
70f: 73 47 jae 758 <malloc+0x98>
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
711: 39 05 a0 0a 00 00 cmp %eax,0xaa0
717: 89 c2 mov %eax,%edx
719: 75 ed jne 708 <malloc+0x48>
p = sbrk(nu * sizeof(Header));
71b: 83 ec 0c sub $0xc,%esp
71e: 56 push %esi
71f: e8 76 fc ff ff call 39a <sbrk>
if(p == (char*)-1)
724: 83 c4 10 add $0x10,%esp
727: 83 f8 ff cmp $0xffffffff,%eax
72a: 74 1c je 748 <malloc+0x88>
hp->s.size = nu;
72c: 89 58 04 mov %ebx,0x4(%eax)
free((void*)(hp + 1));
72f: 83 ec 0c sub $0xc,%esp
732: 83 c0 08 add $0x8,%eax
735: 50 push %eax
736: e8 f5 fe ff ff call 630 <free>
return freep;
73b: 8b 15 a0 0a 00 00 mov 0xaa0,%edx
if((p = morecore(nunits)) == 0)
741: 83 c4 10 add $0x10,%esp
744: 85 d2 test %edx,%edx
746: 75 c0 jne 708 <malloc+0x48>
return 0;
}
}
748: 8d 65 f4 lea -0xc(%ebp),%esp
return 0;
74b: 31 c0 xor %eax,%eax
}
74d: 5b pop %ebx
74e: 5e pop %esi
74f: 5f pop %edi
750: 5d pop %ebp
751: c3 ret
752: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
if(p->s.size == nunits)
758: 39 cf cmp %ecx,%edi
75a: 74 54 je 7b0 <malloc+0xf0>
p->s.size -= nunits;
75c: 29 f9 sub %edi,%ecx
75e: 89 48 04 mov %ecx,0x4(%eax)
p += p->s.size;
761: 8d 04 c8 lea (%eax,%ecx,8),%eax
p->s.size = nunits;
764: 89 78 04 mov %edi,0x4(%eax)
freep = prevp;
767: 89 15 a0 0a 00 00 mov %edx,0xaa0
}
76d: 8d 65 f4 lea -0xc(%ebp),%esp
return (void*)(p + 1);
770: 83 c0 08 add $0x8,%eax
}
773: 5b pop %ebx
774: 5e pop %esi
775: 5f pop %edi
776: 5d pop %ebp
777: c3 ret
778: 90 nop
779: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
base.s.ptr = freep = prevp = &base;
780: c7 05 a0 0a 00 00 a4 movl $0xaa4,0xaa0
787: 0a 00 00
78a: c7 05 a4 0a 00 00 a4 movl $0xaa4,0xaa4
791: 0a 00 00
base.s.size = 0;
794: b8 a4 0a 00 00 mov $0xaa4,%eax
799: c7 05 a8 0a 00 00 00 movl $0x0,0xaa8
7a0: 00 00 00
7a3: e9 44 ff ff ff jmp 6ec <malloc+0x2c>
7a8: 90 nop
7a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
prevp->s.ptr = p->s.ptr;
7b0: 8b 08 mov (%eax),%ecx
7b2: 89 0a mov %ecx,(%edx)
7b4: eb b1 jmp 767 <malloc+0xa7>
|
TITLE MVPATH - Copyright (c) SLR Systems 1994
INCLUDE MACROS
INCLUDE IO_STRUC
PUBLIC MOVE_ECXPATH_EAX
.DATA
.CODE PHASE1_TEXT
externdef _move_ecxpath_eax:proc
MOVE_ECXPATH_EAX PROC
;
;MOVE PATH FROM ECX TO EAX, PRESERVE EAX
;
push ECX
push EAX
call _move_ecxpath_eax
add ESP, 8
ret
PUSH EDI
MOV EDX,EAX
ASSUME EDX:PTR NFN_STRUCT,EAX:PTR NFN_STRUCT
;
;FIRST, GET RID OF EXISTING PATH
;
PUSHM ESI,EBX
MOV EAX,[EAX].NFN_PATHLEN
MOV EBX,ECX
ASSUME EAX:NOTHING,EBX:PTR NFN_STRUCT
TEST EAX,EAX
JZ L1$
MOV ECX,[EDX].NFN_TOTAL_LENGTH
LEA ESI,[EDX].NFN_TEXT
SUB ECX,EAX
MOV EDI,ESI
ADD ESI,EAX
MOV [EDX].NFN_TOTAL_LENGTH,ECX
REP MOVSB
L1$:
;
;NEXT MOVE ALL DOWN PATHLEN BYTES
;
LEA ESI,[EDX].NFN_TEXT-1
MOV ECX,[EDX].NFN_TOTAL_LENGTH
ADD ESI,ECX
MOV EAX,[EBX].NFN_PATHLEN
STD
LEA EDI,[EAX+ESI]
REP MOVSB
CLD
MOV ECX,[EBX].NFN_PATHLEN
MOV EAX,[EDX].NFN_TOTAL_LENGTH
MOV [EDX].NFN_PATHLEN,ECX
ADD EAX,ECX
LEA ESI,[EBX].NFN_TEXT
MOV [EDX].NFN_TOTAL_LENGTH,EAX
LEA EDI,[EDX].NFN_TEXT
POP EBX
REP MOVSB
POPM ESI,EDI
MOV DPTR [EAX+EDX].NFN_TEXT,ECX
MOV EAX,EDX
RET
MOVE_ECXPATH_EAX ENDP
END
|
/*
* This file is part of hipSYCL, a SYCL implementation based on CUDA/HIP
*
* Copyright (c) 2018, 2019 Aksel Alpay
* 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 "hipSYCL/sycl/detail/local_memory_allocator.hpp"
namespace hipsycl {
namespace sycl {
namespace detail {
char* host_local_memory::_local_mem = nullptr;
char host_local_memory::_static_local_mem [host_local_memory::_max_static_local_mem_size] = {};
host_local_memory_origin host_local_memory::_origin = host_local_memory_origin::custom_threadprivate;
}
}
}
|
#ifndef CNET_Visitor_HPP
#define CNET_Visitor_HPP
#include <string>
#include <iostream>
#include <experimental/filesystem>
#include <opencv2/core/core.hpp>
#include <opencv/cv.hpp>
#include <opencv2/core/eigen.hpp>
#include <experimental/filesystem>
#include "cnet_layer.hpp"
namespace Cnet
{
class Layer;
class Visitor
{
protected:
friend class Layer;
size_t _current_iter;
public:
Visitor()
{
_current_iter = 0;
}
virtual void visit(Layer* layer) = 0;
void set_current_iter(size_t current_iter)
{
_current_iter = current_iter;
}
};
}
#endif // ! CNET_Visitor_HPP
|
; BSD 3-Clause License
; Copyright (c) 2021, AtieP
; All rights reserved.
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are met:
; 1. Redistributions of source code must retain the above copyright notice, this
; list of conditions and the following disclaimer.
; 2. Redistributions in binary form must reproduce the above copyright notice,
; this list of conditions and the following disclaimer in the documentation
; and/or other materials provided with the distribution.
; 3. Neither the name of the copyright holder nor the names of its
; contributors may be used to endorse or promote products derived from
; this software without specific prior written permission.
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
stivale2_load:
panic "stivale2", "Not supported for now"
|
;;
;; Copyright (c) 2012-2021, Intel Corporation
;;
;; 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.
;;
%include "include/os.asm"
%include "include/imb_job.asm"
%include "include/mb_mgr_datastruct.asm"
%include "include/reg_sizes.asm"
%include "include/memcpy.asm"
%include "include/const.inc"
extern sha_256_mult_avx
mksection .rodata
default rel
align 16
byteswap: ;ddq 0x0c0d0e0f08090a0b0405060700010203
dq 0x0405060700010203, 0x0c0d0e0f08090a0b
mksection .text
%ifndef FUNC
%define FUNC submit_job_hmac_sha_256_avx
%endif
%if 1
%ifdef LINUX
%define arg1 rdi
%define arg2 rsi
%define reg3 rcx
%define reg4 rdx
%else
%define arg1 rcx
%define arg2 rdx
%define reg3 rdi
%define reg4 rsi
%endif
%define state arg1
%define job arg2
%define len2 arg2
; idx needs to be in rbx, rbp, r13-r15
%define last_len rbp
%define idx rbp
%define p r11
%define start_offset r11
%define unused_lanes rbx
%define tmp4 rbx
%define job_rax rax
%define len rax
%define size_offset reg3
%define tmp2 reg3
%define lane reg4
%define tmp3 reg4
%define extra_blocks r8
%define tmp r9
%define p2 r9
%define lane_data r10
%endif
; This routine clobbers rbx, rbp, rsi, rdi; called routine also clobbers r12
struc STACK
_gpr_save: resq 5
_rsp_save: resq 1
endstruc
; JOB* FUNC(MB_MGR_HMAC_SHA_256_OOO *state, IMB_JOB *job)
; arg 1 : rcx : state
; arg 2 : rdx : job
MKGLOBAL(FUNC,function,internal)
FUNC:
mov rax, rsp
sub rsp, STACK_size
and rsp, -16
mov [rsp + _gpr_save + 8*0], rbx
mov [rsp + _gpr_save + 8*1], rbp
mov [rsp + _gpr_save + 8*2], r12
%ifndef LINUX
mov [rsp + _gpr_save + 8*3], rsi
mov [rsp + _gpr_save + 8*4], rdi
%endif
mov [rsp + _rsp_save], rax ; original SP
mov unused_lanes, [state + _unused_lanes_sha256]
movzx lane, BYTE(unused_lanes)
shr unused_lanes, 8
imul lane_data, lane, _HMAC_SHA1_LANE_DATA_size
lea lane_data, [state + _ldata_sha256 + lane_data]
mov [state + _unused_lanes_sha256], unused_lanes
mov len, [job + _msg_len_to_hash_in_bytes]
mov tmp, len
shr tmp, 6 ; divide by 64, len in terms of blocks
mov [lane_data + _job_in_lane], job
mov dword [lane_data + _outer_done], 0
vmovdqa xmm0, [state + _lens_sha256]
XVPINSRW xmm0, xmm1, p, lane, tmp, scale_x16
vmovdqa [state + _lens_sha256], xmm0
mov last_len, len
and last_len, 63
lea extra_blocks, [last_len + 9 + 63]
shr extra_blocks, 6
mov [lane_data + _extra_blocks], DWORD(extra_blocks)
mov p, [job + _src]
add p, [job + _hash_start_src_offset_in_bytes]
mov [state + _args_data_ptr_sha256 + 8*lane], p
cmp len, 64
jb copy_lt64
fast_copy:
add p, len
vmovdqu xmm0, [p - 64 + 0*16]
vmovdqu xmm1, [p - 64 + 1*16]
vmovdqu xmm2, [p - 64 + 2*16]
vmovdqu xmm3, [p - 64 + 3*16]
vmovdqa [lane_data + _extra_block + 0*16], xmm0
vmovdqa [lane_data + _extra_block + 1*16], xmm1
vmovdqa [lane_data + _extra_block + 2*16], xmm2
vmovdqa [lane_data + _extra_block + 3*16], xmm3
end_fast_copy:
mov size_offset, extra_blocks
shl size_offset, 6
sub size_offset, last_len
add size_offset, 64-8
mov [lane_data + _size_offset], DWORD(size_offset)
mov start_offset, 64
sub start_offset, last_len
mov [lane_data + _start_offset], DWORD(start_offset)
lea tmp, [8*64 + 8*len]
bswap tmp
mov [lane_data + _extra_block + size_offset], tmp
mov tmp, [job + _auth_key_xor_ipad]
vmovdqu xmm0, [tmp]
vmovdqu xmm1, [tmp + 4*4]
vmovd [state + _args_digest_sha256 + 4*lane + 0*SHA256_DIGEST_ROW_SIZE], xmm0
vpextrd [state + _args_digest_sha256 + 4*lane + 1*SHA256_DIGEST_ROW_SIZE], xmm0, 1
vpextrd [state + _args_digest_sha256 + 4*lane + 2*SHA256_DIGEST_ROW_SIZE], xmm0, 2
vpextrd [state + _args_digest_sha256 + 4*lane + 3*SHA256_DIGEST_ROW_SIZE], xmm0, 3
vmovd [state + _args_digest_sha256 + 4*lane + 4*SHA256_DIGEST_ROW_SIZE], xmm1
vpextrd [state + _args_digest_sha256 + 4*lane + 5*SHA256_DIGEST_ROW_SIZE], xmm1, 1
vpextrd [state + _args_digest_sha256 + 4*lane + 6*SHA256_DIGEST_ROW_SIZE], xmm1, 2
vpextrd [state + _args_digest_sha256 + 4*lane + 7*SHA256_DIGEST_ROW_SIZE], xmm1, 3
test len, ~63
jnz ge64_bytes
lt64_bytes:
vmovdqa xmm0, [state + _lens_sha256]
XVPINSRW xmm0, xmm1, tmp, lane, extra_blocks, scale_x16
vmovdqa [state + _lens_sha256], xmm0
lea tmp, [lane_data + _extra_block + start_offset]
mov [state + _args_data_ptr_sha256 + 8*lane], tmp
mov dword [lane_data + _extra_blocks], 0
ge64_bytes:
cmp unused_lanes, 0xff
jne return_null
jmp start_loop
align 16
start_loop:
; Find min length
vmovdqa xmm0, [state + _lens_sha256]
vphminposuw xmm1, xmm0
vpextrw DWORD(len2), xmm1, 0 ; min value
vpextrw DWORD(idx), xmm1, 1 ; min index (0...3)
cmp len2, 0
je len_is_0
vpshuflw xmm1, xmm1, 0
vpsubw xmm0, xmm0, xmm1
vmovdqa [state + _lens_sha256], xmm0
; "state" and "args" are the same address, arg1
; len is arg2
call sha_256_mult_avx
; state and idx are intact
len_is_0:
; process completed job "idx"
imul lane_data, idx, _HMAC_SHA1_LANE_DATA_size
lea lane_data, [state + _ldata_sha256 + lane_data]
mov DWORD(extra_blocks), [lane_data + _extra_blocks]
cmp extra_blocks, 0
jne proc_extra_blocks
cmp dword [lane_data + _outer_done], 0
jne end_loop
proc_outer:
mov dword [lane_data + _outer_done], 1
mov DWORD(size_offset), [lane_data + _size_offset]
mov qword [lane_data + _extra_block + size_offset], 0
vmovdqa xmm0, [state + _lens_sha256]
XVPINSRW xmm0, xmm1, tmp, idx, 1, scale_x16
vmovdqa [state + _lens_sha256], xmm0
lea tmp, [lane_data + _outer_block]
mov job, [lane_data + _job_in_lane]
mov [state + _args_data_ptr_sha256 + 8*idx], tmp
vmovd xmm0, [state + _args_digest_sha256 + 4*idx + 0*SHA256_DIGEST_ROW_SIZE]
vpinsrd xmm0, xmm0, [state + _args_digest_sha256 + 4*idx + 1*SHA256_DIGEST_ROW_SIZE], 1
vpinsrd xmm0, xmm0, [state + _args_digest_sha256 + 4*idx + 2*SHA256_DIGEST_ROW_SIZE], 2
vpinsrd xmm0, xmm0, [state + _args_digest_sha256 + 4*idx + 3*SHA256_DIGEST_ROW_SIZE], 3
vpshufb xmm0, xmm0, [rel byteswap]
vmovd xmm1, [state + _args_digest_sha256 + 4*idx + 4*SHA256_DIGEST_ROW_SIZE]
vpinsrd xmm1, xmm1, [state + _args_digest_sha256 + 4*idx + 5*SHA256_DIGEST_ROW_SIZE], 1
vpinsrd xmm1, xmm1, [state + _args_digest_sha256 + 4*idx + 6*SHA256_DIGEST_ROW_SIZE], 2
%ifndef SHA224
vpinsrd xmm1, xmm1, [state + _args_digest_sha256 + 4*idx + 7*SHA256_DIGEST_ROW_SIZE], 3
%endif
vpshufb xmm1, xmm1, [rel byteswap]
vmovdqa [lane_data + _outer_block], xmm0
vmovdqa [lane_data + _outer_block + 4*4], xmm1
%ifdef SHA224
mov dword [lane_data + _outer_block + 7*4], 0x80
%endif
mov tmp, [job + _auth_key_xor_opad]
vmovdqu xmm0, [tmp]
vmovdqu xmm1, [tmp + 4*4]
vmovd [state + _args_digest_sha256 + 4*idx + 0*SHA256_DIGEST_ROW_SIZE], xmm0
vpextrd [state + _args_digest_sha256 + 4*idx + 1*SHA256_DIGEST_ROW_SIZE], xmm0, 1
vpextrd [state + _args_digest_sha256 + 4*idx + 2*SHA256_DIGEST_ROW_SIZE], xmm0, 2
vpextrd [state + _args_digest_sha256 + 4*idx + 3*SHA256_DIGEST_ROW_SIZE], xmm0, 3
vmovd [state + _args_digest_sha256 + 4*idx + 4*SHA256_DIGEST_ROW_SIZE], xmm1
vpextrd [state + _args_digest_sha256 + 4*idx + 5*SHA256_DIGEST_ROW_SIZE], xmm1, 1
vpextrd [state + _args_digest_sha256 + 4*idx + 6*SHA256_DIGEST_ROW_SIZE], xmm1, 2
vpextrd [state + _args_digest_sha256 + 4*idx + 7*SHA256_DIGEST_ROW_SIZE], xmm1, 3
jmp start_loop
align 16
proc_extra_blocks:
mov DWORD(start_offset), [lane_data + _start_offset]
vmovdqa xmm0, [state + _lens_sha256]
XVPINSRW xmm0, xmm1, tmp, idx, extra_blocks, scale_x16
vmovdqa [state + _lens_sha256], xmm0
lea tmp, [lane_data + _extra_block + start_offset]
mov [state + _args_data_ptr_sha256 + 8*idx], tmp
mov dword [lane_data + _extra_blocks], 0
jmp start_loop
align 16
copy_lt64:
;; less than one message block of data
;; beginning of source block
;; destination extrablock but backwards by len from where 0x80 pre-populated
;; p2 clobbers unused_lanes, undo before exit
lea p2, [lane_data + _extra_block + 64]
sub p2, len
memcpy_avx_64_1 p2, p, len, tmp4, tmp2, xmm0, xmm1, xmm2, xmm3
mov unused_lanes, [state + _unused_lanes_sha256]
jmp end_fast_copy
return_null:
xor job_rax, job_rax
jmp return
align 16
end_loop:
mov job_rax, [lane_data + _job_in_lane]
mov unused_lanes, [state + _unused_lanes_sha256]
mov qword [lane_data + _job_in_lane], 0
or dword [job_rax + _status], IMB_STATUS_COMPLETED_AUTH
shl unused_lanes, 8
or unused_lanes, idx
mov [state + _unused_lanes_sha256], unused_lanes
mov p, [job_rax + _auth_tag_output]
%ifdef SHA224
cmp qword [job_rax + _auth_tag_output_len_in_bytes], 14
jne copy_full_digest
%else
cmp qword [job_rax + _auth_tag_output_len_in_bytes], 16
jne copy_full_digest
%endif
; copy 14 bytes for SHA224 / 16 bytes for SHA256
mov DWORD(tmp), [state + _args_digest_sha256 + 4*idx + 0*SHA256_DIGEST_ROW_SIZE]
mov DWORD(tmp2), [state + _args_digest_sha256 + 4*idx + 1*SHA256_DIGEST_ROW_SIZE]
mov DWORD(tmp3), [state + _args_digest_sha256 + 4*idx + 2*SHA256_DIGEST_ROW_SIZE]
mov DWORD(tmp4), [state + _args_digest_sha256 + 4*idx + 3*SHA256_DIGEST_ROW_SIZE]
bswap DWORD(tmp)
bswap DWORD(tmp2)
bswap DWORD(tmp3)
bswap DWORD(tmp4)
mov [p + 0*4], DWORD(tmp)
mov [p + 1*4], DWORD(tmp2)
mov [p + 2*4], DWORD(tmp3)
%ifdef SHA224
mov [p + 3*4], WORD(tmp4)
%else
mov [p + 3*4], DWORD(tmp4)
%endif
jmp clear_ret
copy_full_digest:
;; copy 28 bytes for SHA224 / 32 bytes for SHA256
mov DWORD(tmp), [state + _args_digest_sha256 + 4*idx + 0*SHA256_DIGEST_ROW_SIZE]
mov DWORD(tmp2), [state + _args_digest_sha256 + 4*idx + 1*SHA256_DIGEST_ROW_SIZE]
mov DWORD(tmp3), [state + _args_digest_sha256 + 4*idx + 2*SHA256_DIGEST_ROW_SIZE]
mov DWORD(tmp4), [state + _args_digest_sha256 + 4*idx + 3*SHA256_DIGEST_ROW_SIZE]
bswap DWORD(tmp)
bswap DWORD(tmp2)
bswap DWORD(tmp3)
bswap DWORD(tmp4)
mov [p + 0*4], DWORD(tmp)
mov [p + 1*4], DWORD(tmp2)
mov [p + 2*4], DWORD(tmp3)
mov [p + 3*4], DWORD(tmp4)
mov DWORD(tmp), [state + _args_digest_sha256 + 4*idx + 4*SHA256_DIGEST_ROW_SIZE]
mov DWORD(tmp2), [state + _args_digest_sha256 + 4*idx + 5*SHA256_DIGEST_ROW_SIZE]
mov DWORD(tmp3), [state + _args_digest_sha256 + 4*idx + 6*SHA256_DIGEST_ROW_SIZE]
%ifndef SHA224
mov DWORD(tmp4), [state + _args_digest_sha256 + 4*idx + 7*SHA256_DIGEST_ROW_SIZE]
%endif
bswap DWORD(tmp)
bswap DWORD(tmp2)
bswap DWORD(tmp3)
%ifndef SHA224
bswap DWORD(tmp4)
%endif
mov [p + 4*4], DWORD(tmp)
mov [p + 5*4], DWORD(tmp2)
mov [p + 6*4], DWORD(tmp3)
%ifndef SHA224
mov [p + 7*4], DWORD(tmp4)
%endif
clear_ret:
%ifdef SAFE_DATA
;; Clear digest (28B/32B), outer_block (28B/32B) and extra_block (64B) of returned job
%assign J 0
%rep 7
mov dword [state + _args_digest_sha256 + SHA256_DIGEST_WORD_SIZE*idx + J*SHA256_DIGEST_ROW_SIZE], 0
%assign J (J+1)
%endrep
%ifndef SHA224
mov dword [state + _args_digest_sha256 + SHA256_DIGEST_WORD_SIZE*idx + 7*SHA256_DIGEST_ROW_SIZE], 0
%endif
vpxor xmm0, xmm0
imul lane_data, idx, _HMAC_SHA1_LANE_DATA_size
lea lane_data, [state + _ldata_sha256 + lane_data]
;; Clear first 64 bytes of extra_block
%assign offset 0
%rep 4
vmovdqa [lane_data + _extra_block + offset], xmm0
%assign offset (offset + 16)
%endrep
;; Clear first 28 bytes (SHA-224) or 32 bytes (SHA-256) of outer_block
vmovdqa [lane_data + _outer_block], xmm0
%ifdef SHA224
mov qword [lane_data + _outer_block + 16], 0
mov dword [lane_data + _outer_block + 24], 0
%else
vmovdqa [lane_data + _outer_block + 16], xmm0
%endif
%endif ;; SAFE_DATA
return:
mov rbx, [rsp + _gpr_save + 8*0]
mov rbp, [rsp + _gpr_save + 8*1]
mov r12, [rsp + _gpr_save + 8*2]
%ifndef LINUX
mov rsi, [rsp + _gpr_save + 8*3]
mov rdi, [rsp + _gpr_save + 8*4]
%endif
mov rsp, [rsp + _rsp_save] ; original SP
ret
mksection stack-noexec
|
sty $ff
ora $ff
|
; A274070: Integer part of the sum of the inverses of the first n primes.
; 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
add $0,6
log $0,8
mov $1,$0
|
; A155664: 10^n+8^n-1
; 1,17,163,1511,14095,132767,1262143,12097151,116777215,1134217727,11073741823,108589934591,1068719476735,10549755813887,104398046511103,1035184372088831,10281474976710655,102251799813685247,1018014398509481983,10144115188075855871,101152921504606846975,1009223372036854775807,10073786976294838206463,100590295810358705651711,1004722366482869645213695,10037778931862957161709567,100302231454903657293676543,1002417851639229258349412351,10019342813113834066795298815,100154742504910672534362390527
mov $1,8
pow $1,$0
mov $2,10
pow $2,$0
add $1,$2
mov $0,$1
sub $0,1
|
; A010487: Decimal expansion of square root of 32.
; Submitted by Jamie Morken(s4)
; 5,6,5,6,8,5,4,2,4,9,4,9,2,3,8,0,1,9,5,2,0,6,7,5,4,8,9,6,8,3,8,7,9,2,3,1,4,2,7,8,6,8,7,5,0,1,5,0,7,7,9,2,2,9,2,7,0,6,7,1,8,9,5,1,9,6,2,9,2,9,9,1,3,8,4,8,4,2,8,1,5,5,4,0,1,5,5,0,1,3,7,3,1,0,5,6,6,2,9,0
add $0,2
seq $0,11547 ; Decimal expansion of sqrt(2) truncated to n places.
div $0,25
mod $0,10
|
; A051375: Number of Boolean functions of n variables and rank 3 from Post class F(5,inf).
; Submitted by Christian Krause
; 0,0,9,66,345,1590,6909,29106,120465,493230,2005509,8116746,32744985,131801670,529647309,2125861986,8525167905,34165634910,136857036309,548010848826,2193789933225,8780396200950,35137287916509,140596248421266,562526258784945,2250528780107790,9003386254671909,36017358220083306,144080872081867065,576357805126763430,2305534169294326509,9222445520317898946,36890708604250923585,147565613973056775870,590270794534616544309,2361108194014094892186,9444507823580186498505,37778256436686008353110
add $0,1
mov $1,3
pow $1,$0
div $1,-2
add $1,1
mov $2,2
pow $2,$0
sub $2,1
bin $2,2
add $1,$2
mov $0,$1
|
.global s_prepare_buffers
s_prepare_buffers:
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r8
push %rbp
push %rbx
push %rdi
push %rdx
push %rsi
// Load
lea addresses_RW+0x16ce1, %r11
nop
nop
nop
nop
dec %rbp
vmovaps (%r11), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $0, %xmm3, %rdx
nop
nop
add $59146, %rbp
// Store
lea addresses_UC+0x12871, %rsi
nop
cmp %rbx, %rbx
movb $0x51, (%rsi)
nop
nop
sub %r8, %r8
// Faulty Load
lea addresses_A+0x122e1, %rdi
nop
nop
nop
nop
add $51593, %rbp
movups (%rdi), %xmm3
vpextrq $0, %xmm3, %r11
lea oracles, %rdx
and $0xff, %r11
shlq $12, %r11
mov (%rdx,%r11,1), %r11
pop %rsi
pop %rdx
pop %rdi
pop %rbx
pop %rbp
pop %r8
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_A', 'same': False, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_RW', 'same': False, 'size': 32, 'congruent': 8, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_UC', 'same': False, 'size': 1, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_A', 'same': True, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'f3': 21}
f3 f3 f3 f3 f3 f3 f3 f3 f3 f3 f3 f3 f3 f3 f3 f3 f3 f3 f3 f3 f3
*/
|
; A165743: The greatest common divisor of n and 210.
; 1,2,3,2,5,6,7,2,3,10,1,6,1,14,15,2,1,6,1,10,21,2,1,6,5,2,3,14,1,30,1,2,3,2,35,6,1,2,3,10,1,42,1,2,15,2,1,6,7,10,3,2,1,6,5,14,3,2,1,30,1,2,21,2,5,6,1,2,3,70,1,6,1,2,15,2,7,6,1,10,3,2,1,42,5,2,3,2,1,30,7,2,3,2,5,6
add $0,1
gcd $0,210
|
copyright zengfr site:http://github.com/zengfr/romhack
00042A move.l D1, (A0)+
00042C dbra D0, $42a
000708 move.l ($6c8,A5), ($860,A5)
00070E move.w #$300, D0 [base+860, base+862]
0AAACA move.l (A0), D2
0AAACC move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAACE move.w D0, ($2,A0)
0AAAD2 cmp.l (A0), D0
0AAAD4 bne $aaafc
0AAAD8 move.l D2, (A0)+
0AAADA cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAAE6 move.l (A0), D2
0AAAE8 move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAAF4 move.l D2, (A0)+
0AAAF6 cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
copyright zengfr site:http://github.com/zengfr/romhack
|
;
; Philips VG5000
;
; getkey() Wait for keypress
;
; Jun 2014 - Joaopa
;
;
; $Id: getk.asm,v 1.5 2016-06-16 19:40:21 dom Exp $
;
SECTION code_clib
PUBLIC getk
.getk
._getk
call $aa
IF STANDARDESCAPECHARS
cp 13
jr nz,not_return
ld a,10
.not_return
ENDIF
ld l,a
ld h,0
ret
|
/******************************************************************************
* $Id$
*
* Project: WFS Translator
* Purpose: Implements OGRWFSLayer class.
* Author: Even Rouault, <even dot rouault at mines dash paris dot org>
*
******************************************************************************
* Copyright (c) 2010-2013, Even Rouault <even dot rouault at mines-paris dot org>
*
* 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 "cpl_port.h"
#include "ogr_wfs.h"
#include "ogr_api.h"
#include "cpl_minixml.h"
#include "cpl_http.h"
#include "parsexsd.h"
CPL_CVSID("$Id$");
/************************************************************************/
/* OGRWFSRecursiveUnlink() */
/************************************************************************/
void OGRWFSRecursiveUnlink( const char *pszName )
{
char **papszFileList;
int i;
papszFileList = CPLReadDir( pszName );
for( i = 0; papszFileList != NULL && papszFileList[i] != NULL; i++ )
{
VSIStatBufL sStatBuf;
if( EQUAL(papszFileList[i],".") || EQUAL(papszFileList[i],"..") )
continue;
CPLString osFullFilename =
CPLFormFilename( pszName, papszFileList[i], NULL );
if( VSIStatL( osFullFilename, &sStatBuf ) == 0 )
{
if( VSI_ISREG( sStatBuf.st_mode ) )
{
VSIUnlink( osFullFilename );
}
else if( VSI_ISDIR( sStatBuf.st_mode ) )
{
OGRWFSRecursiveUnlink( osFullFilename );
}
}
}
CSLDestroy( papszFileList );
VSIRmdir( pszName );
}
/************************************************************************/
/* OGRWFSLayer() */
/************************************************************************/
OGRWFSLayer::OGRWFSLayer( OGRWFSDataSource* poDSIn,
OGRSpatialReference* poSRSIn,
int bAxisOrderAlreadyInvertedIn,
const char* pszBaseURLIn,
const char* pszNameIn,
const char* pszNSIn,
const char* pszNSValIn )
{
this->poDS = poDSIn;
this->poSRS = poSRSIn;
this->bAxisOrderAlreadyInverted = bAxisOrderAlreadyInvertedIn;
this->pszBaseURL = CPLStrdup(pszBaseURLIn);
this->pszName = CPLStrdup(pszNameIn);
this->pszNS = pszNSIn ? CPLStrdup(pszNSIn) : NULL;
this->pszNSVal = pszNSValIn ? CPLStrdup(pszNSValIn) : NULL;
SetDescription( pszName );
poFeatureDefn = NULL;
poGMLFeatureClass = NULL;
bGotApproximateLayerDefn = FALSE;
bStreamingDS = FALSE;
poBaseDS = NULL;
poBaseLayer = NULL;
bReloadNeeded = FALSE;
bHasFetched = FALSE;
eGeomType = wkbUnknown;
nFeatures = -1;
bCountFeaturesInGetNextFeature = FALSE;
dfMinX = dfMinY = dfMaxX = dfMaxY = 0;
bHasExtents = FALSE;
poFetchedFilterGeom = NULL;
nExpectedInserts = 0;
bInTransaction = FALSE;
bUseFeatureIdAtLayerLevel = FALSE;
bPagingActive = FALSE;
nPagingStartIndex = 0;
nFeatureRead = 0;
nFeatureCountRequested = 0;
pszRequiredOutputFormat = NULL;
}
/************************************************************************/
/* Clone() */
/************************************************************************/
OGRWFSLayer* OGRWFSLayer::Clone()
{
OGRWFSLayer* poDupLayer = new OGRWFSLayer(poDS, poSRS, bAxisOrderAlreadyInverted,
pszBaseURL, pszName, pszNS, pszNSVal);
if (poSRS)
poSRS->Reference();
poDupLayer->poFeatureDefn = GetLayerDefn()->Clone();
poDupLayer->poFeatureDefn->Reference();
poDupLayer->bGotApproximateLayerDefn = bGotApproximateLayerDefn;
poDupLayer->eGeomType = poDupLayer->poFeatureDefn->GetGeomType();
poDupLayer->pszRequiredOutputFormat = pszRequiredOutputFormat ? CPLStrdup(pszRequiredOutputFormat) : NULL;
/* Copy existing schema file if already found */
CPLString osSrcFileName = CPLSPrintf("/vsimem/tempwfs_%p/file.xsd", this);
CPLString osTargetFileName = CPLSPrintf("/vsimem/tempwfs_%p/file.xsd", poDupLayer);
CPLCopyFile(osTargetFileName, osSrcFileName);
return poDupLayer;
}
/************************************************************************/
/* ~OGRWFSLayer() */
/************************************************************************/
OGRWFSLayer::~OGRWFSLayer()
{
if (bInTransaction)
CommitTransaction();
if( poSRS != NULL )
poSRS->Release();
if (poFeatureDefn != NULL)
poFeatureDefn->Release();
delete poGMLFeatureClass;
CPLFree(pszBaseURL);
CPLFree(pszName);
CPLFree(pszNS);
CPLFree(pszNSVal);
GDALClose(poBaseDS);
delete poFetchedFilterGeom;
CPLString osTmpDirName = CPLSPrintf("/vsimem/tempwfs_%p", this);
OGRWFSRecursiveUnlink(osTmpDirName);
CPLFree(pszRequiredOutputFormat);
}
/************************************************************************/
/* GetDescribeFeatureTypeURL() */
/************************************************************************/
CPLString OGRWFSLayer::GetDescribeFeatureTypeURL(CPL_UNUSED int bWithNS)
{
CPLString osURL(pszBaseURL);
osURL = CPLURLAddKVP(osURL, "SERVICE", "WFS");
osURL = CPLURLAddKVP(osURL, "VERSION", poDS->GetVersion());
osURL = CPLURLAddKVP(osURL, "REQUEST", "DescribeFeatureType");
osURL = CPLURLAddKVP(osURL, "TYPENAME", WFS_EscapeURL(pszName));
osURL = CPLURLAddKVP(osURL, "PROPERTYNAME", NULL);
osURL = CPLURLAddKVP(osURL, "MAXFEATURES", NULL);
osURL = CPLURLAddKVP(osURL, "COUNT", NULL);
osURL = CPLURLAddKVP(osURL, "FILTER", NULL);
osURL = CPLURLAddKVP(osURL, "OUTPUTFORMAT", pszRequiredOutputFormat ? WFS_EscapeURL(pszRequiredOutputFormat).c_str() : NULL);
if (pszNS && poDS->GetNeedNAMESPACE())
{
/* Older Deegree version require NAMESPACE (e.g. http://www.nokis.org/deegree2/ogcwebservice) */
/* This has been now corrected */
CPLString osValue("xmlns(");
osValue += pszNS;
osValue += "=";
osValue += pszNSVal;
osValue += ")";
osURL = CPLURLAddKVP(osURL, "NAMESPACE", WFS_EscapeURL(osValue));
}
return osURL;
}
/************************************************************************/
/* DescribeFeatureType() */
/************************************************************************/
OGRFeatureDefn* OGRWFSLayer::DescribeFeatureType()
{
CPLString osURL = GetDescribeFeatureTypeURL(TRUE);
CPLDebug("WFS", "%s", osURL.c_str());
CPLHTTPResult* psResult = poDS->HTTPFetch( osURL, NULL);
if (psResult == NULL)
{
return NULL;
}
if (strstr((const char*)psResult->pabyData, "<ServiceExceptionReport") != NULL)
{
if (poDS->IsOldDeegree((const char*)psResult->pabyData))
{
CPLHTTPDestroyResult(psResult);
return DescribeFeatureType();
}
CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
psResult->pabyData);
CPLHTTPDestroyResult(psResult);
return NULL;
}
CPLXMLNode* psXML = CPLParseXMLString( (const char*) psResult->pabyData );
if (psXML == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s",
psResult->pabyData);
CPLHTTPDestroyResult(psResult);
return NULL;
}
CPLHTTPDestroyResult(psResult);
CPLXMLNode* psSchema = WFSFindNode(psXML, "schema");
if (psSchema == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Cannot find <Schema>");
CPLDestroyXMLNode( psXML );
return NULL;
}
OGRFeatureDefn* poFDefn = ParseSchema(psSchema);
if (poFDefn)
poDS->SaveLayerSchema(pszName, psSchema);
CPLDestroyXMLNode( psXML );
return poFDefn;
}
/************************************************************************/
/* ParseSchema() */
/************************************************************************/
OGRFeatureDefn* OGRWFSLayer::ParseSchema(CPLXMLNode* psSchema)
{
osTargetNamespace = CPLGetXMLValue(psSchema, "targetNamespace", "");
CPLString osTmpFileName;
osTmpFileName = CPLSPrintf("/vsimem/tempwfs_%p/file.xsd", this);
CPLSerializeXMLTreeToFile(psSchema, osTmpFileName);
std::vector<GMLFeatureClass*> aosClasses;
bool bFullyUnderstood = false;
bool bHaveSchema = GMLParseXSD( osTmpFileName, aosClasses, bFullyUnderstood );
if (bHaveSchema && aosClasses.size() == 1)
{
//CPLDebug("WFS", "Creating %s for %s", osTmpFileName.c_str(), GetName());
return BuildLayerDefnFromFeatureClass(aosClasses[0]);
}
else if (bHaveSchema)
{
std::vector<GMLFeatureClass*>::const_iterator oIter = aosClasses.begin();
std::vector<GMLFeatureClass*>::const_iterator oEndIter = aosClasses.end();
while (oIter != oEndIter)
{
GMLFeatureClass* poClass = *oIter;
oIter ++;
delete poClass;
}
}
VSIUnlink(osTmpFileName);
return NULL;
}
/************************************************************************/
/* BuildLayerDefnFromFeatureClass() */
/************************************************************************/
OGRFeatureDefn* OGRWFSLayer::BuildLayerDefnFromFeatureClass(GMLFeatureClass* poClass)
{
this->poGMLFeatureClass = poClass;
OGRFeatureDefn* poFDefn = new OGRFeatureDefn( pszName );
poFDefn->SetGeomType(wkbNone);
if( poGMLFeatureClass->GetGeometryPropertyCount() > 0 )
{
poFDefn->SetGeomType( (OGRwkbGeometryType)poGMLFeatureClass->GetGeometryProperty(0)->GetType() );
poFDefn->GetGeomFieldDefn(0)->SetSpatialRef(poSRS);
}
/* -------------------------------------------------------------------- */
/* Added attributes (properties). */
/* -------------------------------------------------------------------- */
if( poDS->ExposeGMLId() )
{
OGRFieldDefn oField( "gml_id", OFTString );
oField.SetNullable(FALSE);
poFDefn->AddFieldDefn( &oField );
}
for( int iField = 0; iField < poGMLFeatureClass->GetPropertyCount(); iField++ )
{
GMLPropertyDefn *poProperty = poGMLFeatureClass->GetProperty( iField );
OGRFieldType eFType;
if( poProperty->GetType() == GMLPT_Untyped )
eFType = OFTString;
else if( poProperty->GetType() == GMLPT_String )
eFType = OFTString;
else if( poProperty->GetType() == GMLPT_Integer ||
poProperty->GetType() == GMLPT_Boolean ||
poProperty->GetType() == GMLPT_Short )
eFType = OFTInteger;
else if( poProperty->GetType() == GMLPT_Integer64 )
eFType = OFTInteger64;
else if( poProperty->GetType() == GMLPT_Real ||
poProperty->GetType() == GMLPT_Float )
eFType = OFTReal;
else if( poProperty->GetType() == GMLPT_StringList )
eFType = OFTStringList;
else if( poProperty->GetType() == GMLPT_IntegerList ||
poProperty->GetType() == GMLPT_BooleanList )
eFType = OFTIntegerList;
else if( poProperty->GetType() == GMLPT_Integer64List )
eFType = OFTInteger64List;
else if( poProperty->GetType() == GMLPT_RealList )
eFType = OFTRealList;
else
eFType = OFTString;
OGRFieldDefn oField( poProperty->GetName(), eFType );
if ( STARTS_WITH_CI(oField.GetNameRef(), "ogr:") )
oField.SetName(poProperty->GetName()+4);
if( poProperty->GetWidth() > 0 )
oField.SetWidth( poProperty->GetWidth() );
if( poProperty->GetPrecision() > 0 )
oField.SetPrecision( poProperty->GetPrecision() );
if( poProperty->GetType() == GMLPT_Boolean ||
poProperty->GetType() == GMLPT_BooleanList )
oField.SetSubType(OFSTBoolean);
else if( poProperty->GetType() == GMLPT_Short)
oField.SetSubType(OFSTInt16);
else if( poProperty->GetType() == GMLPT_Float)
oField.SetSubType(OFSTFloat32);
if( !poDS->IsEmptyAsNull() )
oField.SetNullable(poProperty->IsNullable());
poFDefn->AddFieldDefn( &oField );
}
if( poGMLFeatureClass->GetGeometryPropertyCount() > 0 )
{
const char* pszGeometryColumnName = poGMLFeatureClass->GetGeometryProperty(0)->GetSrcElement();
if (pszGeometryColumnName[0] != '\0')
{
osGeometryColumnName = pszGeometryColumnName;
if( poFDefn->GetGeomFieldCount() > 0 )
{
poFDefn->GetGeomFieldDefn(0)->SetNullable(poGMLFeatureClass->GetGeometryProperty(0)->IsNullable());
poFDefn->GetGeomFieldDefn(0)->SetName(pszGeometryColumnName);
}
}
}
return poFDefn;
}
/************************************************************************/
/* MakeGetFeatureURL() */
/************************************************************************/
CPLString OGRWFSLayer::MakeGetFeatureURL(int nRequestMaxFeatures, int bRequestHits)
{
CPLString osURL(pszBaseURL);
osURL = CPLURLAddKVP(osURL, "SERVICE", "WFS");
osURL = CPLURLAddKVP(osURL, "VERSION", poDS->GetVersion());
osURL = CPLURLAddKVP(osURL, "REQUEST", "GetFeature");
if( atoi(poDS->GetVersion()) >= 2 )
osURL = CPLURLAddKVP(osURL, "TYPENAMES", WFS_EscapeURL(pszName));
else
osURL = CPLURLAddKVP(osURL, "TYPENAME", WFS_EscapeURL(pszName));
if (pszRequiredOutputFormat)
osURL = CPLURLAddKVP(osURL, "OUTPUTFORMAT", WFS_EscapeURL(pszRequiredOutputFormat));
if (poDS->IsPagingAllowed() && !bRequestHits)
{
osURL = CPLURLAddKVP(osURL, "STARTINDEX",
CPLSPrintf("%d", nPagingStartIndex +
poDS->GetBaseStartIndex()));
nRequestMaxFeatures = poDS->GetPageSize();
nFeatureCountRequested = nRequestMaxFeatures;
bPagingActive = TRUE;
}
if (nRequestMaxFeatures)
{
osURL = CPLURLAddKVP(osURL,
atoi(poDS->GetVersion()) >= 2 ? "COUNT" : "MAXFEATURES",
CPLSPrintf("%d", nRequestMaxFeatures));
}
if (pszNS && poDS->GetNeedNAMESPACE())
{
/* Older Deegree version require NAMESPACE (e.g. http://www.nokis.org/deegree2/ogcwebservice) */
/* This has been now corrected */
CPLString osValue("xmlns(");
osValue += pszNS;
osValue += "=";
osValue += pszNSVal;
osValue += ")";
osURL = CPLURLAddKVP(osURL, "NAMESPACE", WFS_EscapeURL(osValue));
}
delete poFetchedFilterGeom;
poFetchedFilterGeom = NULL;
CPLString osGeomFilter;
if (m_poFilterGeom != NULL && osGeometryColumnName.size() > 0)
{
OGREnvelope oEnvelope;
m_poFilterGeom->getEnvelope(&oEnvelope);
poFetchedFilterGeom = m_poFilterGeom->clone();
osGeomFilter = "<BBOX>";
if (atoi(poDS->GetVersion()) >= 2)
osGeomFilter += "<ValueReference>";
else
osGeomFilter += "<PropertyName>";
if (pszNS)
{
osGeomFilter += pszNS;
osGeomFilter += ":";
}
osGeomFilter += osGeometryColumnName;
if (atoi(poDS->GetVersion()) >= 2)
osGeomFilter += "</ValueReference>";
else
osGeomFilter += "</PropertyName>";
if ( atoi(poDS->GetVersion()) >= 2 )
{
osGeomFilter += "<gml:Envelope";
CPLString osSRSName = CPLURLGetValue(pszBaseURL, "SRSNAME");
if( osSRSName.size() )
{
osGeomFilter += " srsName=\"";
osGeomFilter += osSRSName;
osGeomFilter += "\"";
}
osGeomFilter += ">";
if (bAxisOrderAlreadyInverted)
{
osGeomFilter += CPLSPrintf("<gml:lowerCorner>%.16f %.16f</gml:lowerCorner><gml:upperCorner>%.16f %.16f</gml:upperCorner>",
oEnvelope.MinY, oEnvelope.MinX, oEnvelope.MaxY, oEnvelope.MaxX);
}
else
osGeomFilter += CPLSPrintf("<gml:lowerCorner>%.16f %.16f</gml:lowerCorner><gml:upperCorner>%.16f %.16f</gml:upperCorner>",
oEnvelope.MinX, oEnvelope.MinY, oEnvelope.MaxX, oEnvelope.MaxY);
osGeomFilter += "</gml:Envelope>";
}
else if ( poDS->RequiresEnvelopeSpatialFilter() )
{
osGeomFilter += "<Envelope xmlns=\"http://www.opengis.net/gml\">";
if (bAxisOrderAlreadyInverted)
{
/* We can go here in WFS 1.1 with geographic coordinate systems */
/* that are natively return in lat,long order, but as we have */
/* presented long,lat order to the user, we must switch back */
/* for the server... */
osGeomFilter += CPLSPrintf("<coord><X>%.16f</X><Y>%.16f</Y></coord><coord><X>%.16f</X><Y>%.16f</Y></coord>",
oEnvelope.MinY, oEnvelope.MinX, oEnvelope.MaxY, oEnvelope.MaxX);
}
else
osGeomFilter += CPLSPrintf("<coord><X>%.16f</X><Y>%.16f</Y></coord><coord><X>%.16f</X><Y>%.16f</Y></coord>",
oEnvelope.MinX, oEnvelope.MinY, oEnvelope.MaxX, oEnvelope.MaxY);
osGeomFilter += "</Envelope>";
}
else
{
osGeomFilter += "<gml:Box>";
osGeomFilter += "<gml:coordinates>";
if (bAxisOrderAlreadyInverted)
{
/* We can go here in WFS 1.1 with geographic coordinate systems */
/* that are natively return in lat,long order, but as we have */
/* presented long,lat order to the user, we must switch back */
/* for the server... */
osGeomFilter += CPLSPrintf("%.16f,%.16f %.16f,%.16f", oEnvelope.MinY, oEnvelope.MinX, oEnvelope.MaxY, oEnvelope.MaxX);
}
else
osGeomFilter += CPLSPrintf("%.16f,%.16f %.16f,%.16f", oEnvelope.MinX, oEnvelope.MinY, oEnvelope.MaxX, oEnvelope.MaxY);
osGeomFilter += "</gml:coordinates>";
osGeomFilter += "</gml:Box>";
}
osGeomFilter += "</BBOX>";
}
if (osGeomFilter.size() != 0 || osWFSWhere.size() != 0)
{
CPLString osFilter;
if (atoi(poDS->GetVersion()) >= 2)
osFilter = "<Filter xmlns=\"http://www.opengis.net/fes/2.0\"";
else
osFilter = "<Filter xmlns=\"http://www.opengis.net/ogc\"";
if (pszNS)
{
osFilter += " xmlns:";
osFilter += pszNS;
osFilter += "=\"";
osFilter += pszNSVal;
osFilter += "\"";
}
if (atoi(poDS->GetVersion()) >= 2)
osFilter += " xmlns:gml=\"http://www.opengis.net/gml/3.2\">";
else
osFilter += " xmlns:gml=\"http://www.opengis.net/gml\">";
if (osGeomFilter.size() != 0 && osWFSWhere.size() != 0)
osFilter += "<And>";
osFilter += osWFSWhere;
osFilter += osGeomFilter;
if (osGeomFilter.size() != 0 && osWFSWhere.size() != 0)
osFilter += "</And>";
osFilter += "</Filter>";
osURL = CPLURLAddKVP(osURL, "FILTER", WFS_EscapeURL(osFilter));
}
if (bRequestHits)
{
osURL = CPLURLAddKVP(osURL, "RESULTTYPE", "hits");
}
else if (aoSortColumns.size() != 0)
{
CPLString osSortBy;
for( int i=0; i < (int)aoSortColumns.size(); i++)
{
if( i > 0 )
osSortBy += ",";
osSortBy += aoSortColumns[i].osColumn;
if( !aoSortColumns[i].bAsc )
{
if (atoi(poDS->GetVersion()) >= 2)
osSortBy += " DESC";
else
osSortBy += " D";
}
}
osURL = CPLURLAddKVP(osURL, "SORTBY", WFS_EscapeURL(osSortBy));
}
/* If no PROPERTYNAME is specified, build one if there are ignored fields */
CPLString osPropertyName = CPLURLGetValue(osURL, "PROPERTYNAME");
const char* pszPropertyName = osPropertyName.c_str();
if (pszPropertyName[0] == 0 && poFeatureDefn != NULL)
{
int bHasIgnoredField = FALSE;
osPropertyName.clear();
for( int iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++ )
{
if (EQUAL(poFeatureDefn->GetFieldDefn(iField)->GetNameRef(), "gml_id"))
{
/* fake field : skip it */
}
else if (poFeatureDefn->GetFieldDefn(iField)->IsIgnored())
{
bHasIgnoredField = TRUE;
}
else
{
if (osPropertyName.size() != 0)
osPropertyName += ",";
osPropertyName += poFeatureDefn->GetFieldDefn(iField)->GetNameRef();
}
}
if (osGeometryColumnName.size() != 0)
{
if (poFeatureDefn->IsGeometryIgnored())
{
bHasIgnoredField = TRUE;
}
else
{
if (osPropertyName.size() != 0)
osPropertyName += ",";
osPropertyName += osGeometryColumnName;
}
}
if (bHasIgnoredField && osPropertyName.size())
{
osPropertyName = "(" + osPropertyName + ")";
osURL = CPLURLAddKVP(osURL, "PROPERTYNAME", WFS_EscapeURL(osPropertyName));
}
}
return osURL;
}
/************************************************************************/
/* OGRWFSFetchContentDispositionFilename() */
/************************************************************************/
static const char* OGRWFSFetchContentDispositionFilename(char** papszHeaders)
{
char** papszIter = papszHeaders;
while(papszIter && *papszIter)
{
/* For multipart, we have in raw format, but without end-of-line characters */
if (STARTS_WITH(*papszIter, "Content-Disposition: attachment; filename="))
{
return *papszIter + 42;
}
/* For single part, the headers are in KEY=VAL format, but with e-o-l ... */
else if (STARTS_WITH(*papszIter, "Content-Disposition=attachment; filename="))
{
char* pszVal = (char*)(*papszIter + 41);
char* pszEOL = strchr(pszVal, '\r');
if (pszEOL) *pszEOL = 0;
pszEOL = strchr(pszVal, '\n');
if (pszEOL) *pszEOL = 0;
return pszVal;
}
papszIter ++;
}
return NULL;
}
/************************************************************************/
/* MustRetryIfNonCompliantServer() */
/************************************************************************/
int OGRWFSLayer::MustRetryIfNonCompliantServer(const char* pszServerAnswer)
{
int bRetry = FALSE;
/* Deegree server does not support PropertyIsNotEqualTo */
/* We have to turn it into <Not><PropertyIsEqualTo> */
if (osWFSWhere.size() != 0 && poDS->PropertyIsNotEqualToSupported() &&
strstr(pszServerAnswer, "Unknown comparison operation: 'PropertyIsNotEqualTo'") != NULL)
{
poDS->SetPropertyIsNotEqualToUnSupported();
bRetry = TRUE;
}
/* Deegree server requires the gml: prefix in GmlObjectId element, but ESRI */
/* doesn't like it at all ! Other servers don't care... */
if (osWFSWhere.size() != 0 && !poDS->DoesGmlObjectIdNeedGMLPrefix() &&
strstr(pszServerAnswer, "<GmlObjectId> requires 'gml:id'-attribute!") != NULL)
{
poDS->SetGmlObjectIdNeedsGMLPrefix();
bRetry = TRUE;
}
/* GeoServer can return the error 'Only FeatureIds are supported when encoding id filters to SDE' */
if (osWFSWhere.size() != 0 && !bUseFeatureIdAtLayerLevel &&
strstr(pszServerAnswer, "Only FeatureIds are supported") != NULL)
{
bUseFeatureIdAtLayerLevel = TRUE;
bRetry = TRUE;
}
if (bRetry)
{
SetAttributeFilter(osSQLWhere);
bHasFetched = TRUE;
bReloadNeeded = FALSE;
}
return bRetry;
}
/************************************************************************/
/* FetchGetFeature() */
/************************************************************************/
GDALDataset* OGRWFSLayer::FetchGetFeature(int nRequestMaxFeatures)
{
CPLString osURL = MakeGetFeatureURL(nRequestMaxFeatures, FALSE);
CPLDebug("WFS", "%s", osURL.c_str());
CPLHTTPResult* psResult = NULL;
CPLString osOutputFormat = CPLURLGetValue(osURL, "OUTPUTFORMAT");
/* Try streaming when the output format is GML and that we have a .xsd */
/* that we are able to understand */
CPLString osXSDFileName = CPLSPrintf("/vsimem/tempwfs_%p/file.xsd", this);
VSIStatBufL sBuf;
if (CPLTestBool(CPLGetConfigOption("OGR_WFS_USE_STREAMING", "YES")) &&
(osOutputFormat.size() == 0 || osOutputFormat.ifind("GML") != std::string::npos) &&
VSIStatL(osXSDFileName, &sBuf) == 0 && GDALGetDriverByName("GML") != NULL)
{
const char* pszStreamingName = CPLSPrintf("/vsicurl_streaming/%s",
osURL.c_str());
if( STARTS_WITH(osURL, "/vsimem/") &&
CPLTestBool(CPLGetConfigOption("CPL_CURL_ENABLE_VSIMEM", "FALSE")) )
{
pszStreamingName = osURL.c_str();
}
const char* const apszAllowedDrivers[] = { "GML", NULL };
const char* apszOpenOptions[6] = { NULL, NULL, NULL, NULL, NULL, NULL };
apszOpenOptions[0] = CPLSPrintf("XSD=%s", osXSDFileName.c_str());
apszOpenOptions[1] = CPLSPrintf("EMPTY_AS_NULL=%s", poDS->IsEmptyAsNull() ? "YES" : "NO");
int iGMLOOIdex = 2;
if( CPLGetConfigOption("GML_INVERT_AXIS_ORDER_IF_LAT_LONG", NULL) == NULL )
{
apszOpenOptions[iGMLOOIdex] = CPLSPrintf("INVERT_AXIS_ORDER_IF_LAT_LONG=%s",
poDS->InvertAxisOrderIfLatLong() ? "YES" : "NO");
iGMLOOIdex ++;
}
if( CPLGetConfigOption("GML_CONSIDER_EPSG_AS_URN", NULL) == NULL )
{
apszOpenOptions[iGMLOOIdex] = CPLSPrintf("CONSIDER_EPSG_AS_URN=%s",
poDS->GetConsiderEPSGAsURN().c_str());
iGMLOOIdex ++;
}
if( CPLGetConfigOption("GML_EXPOSE_GML_ID", NULL) == NULL )
{
apszOpenOptions[iGMLOOIdex] = CPLSPrintf("EXPOSE_GML_ID=%s",
poDS->ExposeGMLId() ? "YES" : "NO");
iGMLOOIdex ++;
}
GDALDataset* poGML_DS = (GDALDataset*)
GDALOpenEx(pszStreamingName, GDAL_OF_VECTOR, apszAllowedDrivers,
apszOpenOptions, NULL);
if (poGML_DS)
{
bStreamingDS = TRUE;
return poGML_DS;
}
/* In case of failure, read directly the content to examine */
/* it, if it is XML error content */
char szBuffer[2048];
int nRead = 0;
VSILFILE* fp = VSIFOpenL(pszStreamingName, "rb");
if (fp)
{
nRead = (int)VSIFReadL(szBuffer, 1, sizeof(szBuffer) - 1, fp);
szBuffer[nRead] = '\0';
VSIFCloseL(fp);
}
if (nRead != 0)
{
if (MustRetryIfNonCompliantServer(szBuffer))
return FetchGetFeature(nRequestMaxFeatures);
if (strstr(szBuffer, "<ServiceExceptionReport") != NULL ||
strstr(szBuffer, "<ows:ExceptionReport") != NULL)
{
if (poDS->IsOldDeegree(szBuffer))
{
return FetchGetFeature(nRequestMaxFeatures);
}
CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
szBuffer);
return NULL;
}
}
}
bStreamingDS = FALSE;
psResult = poDS->HTTPFetch( osURL, NULL);
if (psResult == NULL)
{
return NULL;
}
const char* pszContentType = "";
if (psResult->pszContentType)
pszContentType = psResult->pszContentType;
CPLString osTmpDirName = CPLSPrintf("/vsimem/tempwfs_%p", this);
VSIMkdir(osTmpDirName, 0);
GByte *pabyData = psResult->pabyData;
int nDataLen = psResult->nDataLen;
int bIsMultiPart = FALSE;
const char* pszAttachmentFilename = NULL;
if(strstr(pszContentType,"multipart")
&& CPLHTTPParseMultipartMime(psResult) )
{
int i;
bIsMultiPart = TRUE;
OGRWFSRecursiveUnlink(osTmpDirName);
VSIMkdir(osTmpDirName, 0);
for(i=0;i<psResult->nMimePartCount;i++)
{
CPLString osTmpFileName = osTmpDirName + "/";
pszAttachmentFilename =
OGRWFSFetchContentDispositionFilename(
psResult->pasMimePart[i].papszHeaders);
if (pszAttachmentFilename)
osTmpFileName += pszAttachmentFilename;
else
osTmpFileName += CPLSPrintf("file_%d", i);
GByte* pData = (GByte*)VSI_MALLOC_VERBOSE(psResult->pasMimePart[i].nDataLen);
if (pData)
{
memcpy(pData, psResult->pasMimePart[i].pabyData, psResult->pasMimePart[i].nDataLen);
VSILFILE *fp = VSIFileFromMemBuffer( osTmpFileName,
pData,
psResult->pasMimePart[i].nDataLen, TRUE);
VSIFCloseL(fp);
}
}
}
else
pszAttachmentFilename =
OGRWFSFetchContentDispositionFilename(
psResult->papszHeaders);
int bJSON = FALSE;
int bCSV = FALSE;
int bKML = FALSE;
int bKMZ = FALSE;
int bZIP = FALSE;
int bGZIP = FALSE;
const char* pszOutputFormat = osOutputFormat.c_str();
if (FindSubStringInsensitive(pszContentType, "json") ||
FindSubStringInsensitive(pszOutputFormat, "json"))
{
bJSON = TRUE;
}
else if (FindSubStringInsensitive(pszContentType, "csv") ||
FindSubStringInsensitive(pszOutputFormat, "csv"))
{
bCSV = TRUE;
}
else if (FindSubStringInsensitive(pszContentType, "kml") ||
FindSubStringInsensitive(pszOutputFormat, "kml"))
{
bKML = TRUE;
}
else if (FindSubStringInsensitive(pszContentType, "kmz") ||
FindSubStringInsensitive(pszOutputFormat, "kmz"))
{
bKMZ = TRUE;
}
else if (strstr(pszContentType, "application/zip") != NULL)
{
bZIP = TRUE;
}
else if (strstr(pszContentType, "application/gzip") != NULL)
{
bGZIP = TRUE;
}
if (MustRetryIfNonCompliantServer((const char*)pabyData))
{
CPLHTTPDestroyResult(psResult);
return FetchGetFeature(nRequestMaxFeatures);
}
if (strstr((const char*)pabyData, "<ServiceExceptionReport") != NULL ||
strstr((const char*)pabyData, "<ows:ExceptionReport") != NULL)
{
if (poDS->IsOldDeegree((const char*)pabyData))
{
CPLHTTPDestroyResult(psResult);
return FetchGetFeature(nRequestMaxFeatures);
}
CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
pabyData);
CPLHTTPDestroyResult(psResult);
return NULL;
}
CPLString osTmpFileName;
if (!bIsMultiPart)
{
if (bJSON)
osTmpFileName = osTmpDirName + "/file.geojson";
else if (bZIP)
osTmpFileName = osTmpDirName + "/file.zip";
else if (bCSV)
osTmpFileName = osTmpDirName + "/file.csv";
else if (bKML)
osTmpFileName = osTmpDirName + "/file.kml";
else if (bKMZ)
osTmpFileName = osTmpDirName + "/file.kmz";
/* GML is a special case. It needs the .xsd file that has been saved */
/* as file.xsd, so we cannot used the attachment filename */
else if (pszAttachmentFilename &&
!EQUAL(CPLGetExtension(pszAttachmentFilename), "GML"))
{
osTmpFileName = osTmpDirName + "/";
osTmpFileName += pszAttachmentFilename;
}
else
{
osTmpFileName = osTmpDirName + "/file.gfs";
VSIUnlink(osTmpFileName);
osTmpFileName = osTmpDirName + "/file.gml";
}
VSILFILE *fp = VSIFileFromMemBuffer( osTmpFileName, pabyData,
nDataLen, TRUE);
VSIFCloseL(fp);
psResult->pabyData = NULL;
if (bZIP)
{
osTmpFileName = "/vsizip/" + osTmpFileName;
}
else if (bGZIP)
{
osTmpFileName = "/vsigzip/" + osTmpFileName;
}
}
else
{
pabyData = NULL;
nDataLen = 0;
osTmpFileName = osTmpDirName;
}
CPLHTTPDestroyResult(psResult);
const char* const * papszOpenOptions = NULL;
const char* apszGMLOpenOptions[4] = { NULL, NULL, NULL, NULL };
int iGMLOOIdex = 0;
if( CPLGetConfigOption("GML_INVERT_AXIS_ORDER_IF_LAT_LONG", NULL) == NULL )
{
apszGMLOpenOptions[iGMLOOIdex] = CPLSPrintf("INVERT_AXIS_ORDER_IF_LAT_LONG=%s",
poDS->InvertAxisOrderIfLatLong() ? "YES" : "NO");
iGMLOOIdex ++;
}
if( CPLGetConfigOption("GML_CONSIDER_EPSG_AS_URN", NULL) == NULL )
{
apszGMLOpenOptions[iGMLOOIdex] = CPLSPrintf("CONSIDER_EPSG_AS_URN=%s",
poDS->GetConsiderEPSGAsURN().c_str());
iGMLOOIdex ++;
}
if( CPLGetConfigOption("GML_EXPOSE_GML_ID", NULL) == NULL )
{
apszGMLOpenOptions[iGMLOOIdex] = CPLSPrintf("EXPOSE_GML_ID=%s",
poDS->ExposeGMLId() ? "YES" : "NO");
iGMLOOIdex ++;
}
GDALDriverH hDrv = GDALIdentifyDriver(osTmpFileName, NULL);
if( hDrv != NULL && hDrv == GDALGetDriverByName("GML") )
papszOpenOptions = apszGMLOpenOptions;
GDALDataset* poPageDS = (GDALDataset*) GDALOpenEx(osTmpFileName,
GDAL_OF_VECTOR, NULL, papszOpenOptions, NULL);
if (poPageDS == NULL && (bZIP || bIsMultiPart))
{
char** papszFileList = VSIReadDir(osTmpFileName);
int i;
for( i = 0; papszFileList != NULL && papszFileList[i] != NULL; i++ )
{
CPLString osFullFilename =
CPLFormFilename( osTmpFileName, papszFileList[i], NULL );
hDrv = GDALIdentifyDriver(osFullFilename, NULL);
if( hDrv != NULL && hDrv == GDALGetDriverByName("GML") )
papszOpenOptions = apszGMLOpenOptions;
poPageDS = (GDALDataset*) GDALOpenEx(osFullFilename,
GDAL_OF_VECTOR, NULL, papszOpenOptions, NULL);
if (poPageDS != NULL)
break;
}
CSLDestroy( papszFileList );
}
if (poPageDS == NULL)
{
if (pabyData != NULL && !bJSON && !bZIP &&
strstr((const char*)pabyData, "<wfs:FeatureCollection") == NULL &&
strstr((const char*)pabyData, "<gml:FeatureCollection") == NULL)
{
if (nDataLen > 1000)
pabyData[1000] = 0;
CPLError(CE_Failure, CPLE_AppDefined,
"Error: cannot parse %s", pabyData);
}
return NULL;
}
OGRLayer* poLayer = poPageDS->GetLayer(0);
if (poLayer == NULL)
{
GDALClose(poPageDS);
return NULL;
}
return poPageDS;
}
/************************************************************************/
/* GetLayerDefn() */
/************************************************************************/
OGRFeatureDefn * OGRWFSLayer::GetLayerDefn()
{
if (poFeatureDefn)
return poFeatureDefn;
poDS->LoadMultipleLayerDefn(GetName(), pszNS, pszNSVal);
if (poFeatureDefn)
return poFeatureDefn;
return BuildLayerDefn();
}
/************************************************************************/
/* BuildLayerDefn() */
/************************************************************************/
OGRFeatureDefn * OGRWFSLayer::BuildLayerDefn(OGRFeatureDefn* poSrcFDefn)
{
int bUnsetWidthPrecision = FALSE;
poFeatureDefn = new OGRFeatureDefn( pszName );
poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(poSRS);
poFeatureDefn->Reference();
GDALDataset* l_poDS = NULL;
if (poSrcFDefn == NULL)
poSrcFDefn = DescribeFeatureType();
if (poSrcFDefn == NULL)
{
l_poDS = FetchGetFeature(1);
if (l_poDS == NULL)
{
return poFeatureDefn;
}
poSrcFDefn = l_poDS->GetLayer(0)->GetLayerDefn();
bGotApproximateLayerDefn = TRUE;
/* We cannot trust width and precision based on a single feature */
bUnsetWidthPrecision = TRUE;
}
CPLString osPropertyName = CPLURLGetValue(pszBaseURL, "PROPERTYNAME");
const char* pszPropertyName = osPropertyName.c_str();
int i;
poFeatureDefn->SetGeomType(poSrcFDefn->GetGeomType());
if( poSrcFDefn->GetGeomFieldCount() > 0 )
poFeatureDefn->GetGeomFieldDefn(0)->SetName(poSrcFDefn->GetGeomFieldDefn(0)->GetNameRef());
for(i=0;i<poSrcFDefn->GetFieldCount();i++)
{
if (pszPropertyName[0] != 0)
{
if (strstr(pszPropertyName,
poSrcFDefn->GetFieldDefn(i)->GetNameRef()) != NULL)
poFeatureDefn->AddFieldDefn(poSrcFDefn->GetFieldDefn(i));
else
bGotApproximateLayerDefn = TRUE;
}
else
{
OGRFieldDefn oFieldDefn(poSrcFDefn->GetFieldDefn(i));
if (bUnsetWidthPrecision)
{
oFieldDefn.SetWidth(0);
oFieldDefn.SetPrecision(0);
}
poFeatureDefn->AddFieldDefn(&oFieldDefn);
}
}
if (l_poDS)
GDALClose(l_poDS);
else
delete poSrcFDefn;
return poFeatureDefn;
}
/************************************************************************/
/* ResetReading() */
/************************************************************************/
void OGRWFSLayer::ResetReading()
{
GetLayerDefn();
if (bPagingActive)
bReloadNeeded = TRUE;
nPagingStartIndex = 0;
nFeatureRead = 0;
nFeatureCountRequested = 0;
if (bReloadNeeded)
{
GDALClose(poBaseDS);
poBaseDS = NULL;
poBaseLayer = NULL;
bHasFetched = FALSE;
bReloadNeeded = FALSE;
}
if (poBaseLayer)
poBaseLayer->ResetReading();
}
/************************************************************************/
/* GetNextFeature() */
/************************************************************************/
OGRFeature *OGRWFSLayer::GetNextFeature()
{
GetLayerDefn();
while( true )
{
if (bPagingActive && nFeatureRead == nPagingStartIndex + nFeatureCountRequested)
{
bReloadNeeded = TRUE;
nPagingStartIndex = nFeatureRead;
}
if (bReloadNeeded)
{
GDALClose(poBaseDS);
poBaseDS = NULL;
poBaseLayer = NULL;
bHasFetched = FALSE;
bReloadNeeded = FALSE;
}
if (poBaseDS == NULL && !bHasFetched)
{
bHasFetched = TRUE;
poBaseDS = FetchGetFeature(0);
poBaseLayer = NULL;
if (poBaseDS)
{
poBaseLayer = poBaseDS->GetLayer(0);
poBaseLayer->ResetReading();
/* Check that the layer field definition is consistent with the one */
/* we got in BuildLayerDefn() */
if (poFeatureDefn->GetFieldCount() != poBaseLayer->GetLayerDefn()->GetFieldCount())
bGotApproximateLayerDefn = TRUE;
else
{
int iField;
for(iField = 0;iField < poFeatureDefn->GetFieldCount(); iField++)
{
OGRFieldDefn* poFDefn1 = poFeatureDefn->GetFieldDefn(iField);
OGRFieldDefn* poFDefn2 = poBaseLayer->GetLayerDefn()->GetFieldDefn(iField);
if (strcmp(poFDefn1->GetNameRef(), poFDefn2->GetNameRef()) != 0 ||
poFDefn1->GetType() != poFDefn2->GetType())
{
bGotApproximateLayerDefn = TRUE;
break;
}
}
}
}
}
if (poBaseDS == NULL || poBaseLayer == NULL)
return NULL;
OGRFeature* poSrcFeature = poBaseLayer->GetNextFeature();
if (poSrcFeature == NULL)
return NULL;
nFeatureRead ++;
if( bCountFeaturesInGetNextFeature )
nFeatures ++;
OGRGeometry* poGeom = poSrcFeature->GetGeometryRef();
if( m_poFilterGeom != NULL && poGeom != NULL &&
!FilterGeometry( poGeom ) )
{
delete poSrcFeature;
continue;
}
/* Client-side attribute filtering with underlying layer defn */
/* identical to exposed layer defn. */
if( !bGotApproximateLayerDefn &&
osWFSWhere.size() == 0 &&
m_poAttrQuery != NULL &&
!m_poAttrQuery->Evaluate( poSrcFeature ) )
{
delete poSrcFeature;
continue;
}
OGRFeature* poNewFeature = new OGRFeature(poFeatureDefn);
if (bGotApproximateLayerDefn)
{
poNewFeature->SetFrom(poSrcFeature);
/* Client-side attribute filtering. */
if( m_poAttrQuery != NULL &&
osWFSWhere.size() == 0 &&
!m_poAttrQuery->Evaluate( poNewFeature ) )
{
delete poSrcFeature;
delete poNewFeature;
continue;
}
}
else
{
int iField;
for(iField = 0;iField < poFeatureDefn->GetFieldCount(); iField++)
poNewFeature->SetField( iField, poSrcFeature->GetRawFieldRef(iField) );
poNewFeature->SetStyleString(poSrcFeature->GetStyleString());
poNewFeature->SetGeometryDirectly(poSrcFeature->StealGeometry());
}
poNewFeature->SetFID(poSrcFeature->GetFID());
poGeom = poNewFeature->GetGeometryRef();
/* FIXME? I don't really know what we should do with WFS 1.1.0 */
/* and non-GML format !!! I guess 50% WFS servers must do it wrong anyway */
/* GeoServer does currently axis inversion for non GML output, but */
/* apparently this is not correct : http://jira.codehaus.org/browse/GEOS-3657 */
if (poGeom != NULL &&
bAxisOrderAlreadyInverted &&
strcmp(poBaseDS->GetDriverName(), "GML") != 0)
{
poGeom->swapXY();
}
if (poGeom && poSRS)
poGeom->assignSpatialReference(poSRS);
delete poSrcFeature;
return poNewFeature;
}
}
/************************************************************************/
/* SetSpatialFilter() */
/************************************************************************/
void OGRWFSLayer::SetSpatialFilter( OGRGeometry * poGeom )
{
if (bStreamingDS)
bReloadNeeded = TRUE;
else if (poFetchedFilterGeom == NULL && poBaseDS != NULL)
{
/* If there was no filter set, and that we set one */
/* the new result set can only be a subset of the whole */
/* so no need to reload from source */
bReloadNeeded = FALSE;
}
else if (poFetchedFilterGeom != NULL && poGeom != NULL && poBaseDS != NULL)
{
OGREnvelope oOldEnvelope, oNewEnvelope;
poFetchedFilterGeom->getEnvelope(&oOldEnvelope);
poGeom->getEnvelope(&oNewEnvelope);
/* Optimization : we don't need to request the server */
/* if the new BBOX is inside the old BBOX as we have */
/* already all the features */
bReloadNeeded = ! oOldEnvelope.Contains(oNewEnvelope);
}
else
bReloadNeeded = TRUE;
nFeatures = -1;
OGRLayer::SetSpatialFilter(poGeom);
ResetReading();
}
/************************************************************************/
/* SetAttributeFilter() */
/************************************************************************/
OGRErr OGRWFSLayer::SetAttributeFilter( const char * pszFilter )
{
if (pszFilter != NULL && pszFilter[0] == 0)
pszFilter = NULL;
CPLString osOldWFSWhere(osWFSWhere);
CPLFree(m_pszAttrQueryString);
m_pszAttrQueryString = (pszFilter) ? CPLStrdup(pszFilter) : NULL;
delete m_poAttrQuery;
m_poAttrQuery = NULL;
if( pszFilter != NULL )
{
m_poAttrQuery = new OGRFeatureQuery();
OGRErr eErr = m_poAttrQuery->Compile( GetLayerDefn(), pszFilter, TRUE,
WFSGetCustomFuncRegistrar() );
if( eErr != OGRERR_NONE )
{
delete m_poAttrQuery;
m_poAttrQuery = NULL;
return eErr;
}
}
if (poDS->HasMinOperators() && m_poAttrQuery != NULL )
{
swq_expr_node* poNode = (swq_expr_node*) m_poAttrQuery->GetSWQExpr();
poNode->ReplaceBetweenByGEAndLERecurse();
int bNeedsNullCheck = FALSE;
int nVersion = (strcmp(poDS->GetVersion(),"1.0.0") == 0) ? 100 :
(atoi(poDS->GetVersion()) >= 2) ? 200 : 110;
if( poNode->field_type != SWQ_BOOLEAN )
osWFSWhere = "";
else
osWFSWhere = WFS_TurnSQLFilterToOGCFilter(poNode,
NULL,
GetLayerDefn(),
nVersion,
poDS->PropertyIsNotEqualToSupported(),
poDS->UseFeatureId() || bUseFeatureIdAtLayerLevel,
poDS->DoesGmlObjectIdNeedGMLPrefix(),
"",
&bNeedsNullCheck);
if (bNeedsNullCheck && !poDS->HasNullCheck())
osWFSWhere = "";
}
else
osWFSWhere = "";
if (m_poAttrQuery != NULL && osWFSWhere.size() == 0)
{
CPLDebug("WFS", "Using client-side only mode for filter \"%s\"", pszFilter);
OGRErr eErr = OGRLayer::SetAttributeFilter(pszFilter);
if (eErr != OGRERR_NONE)
return eErr;
}
ResetReading();
osSQLWhere = (pszFilter) ? pszFilter : "";
if (osWFSWhere != osOldWFSWhere)
bReloadNeeded = TRUE;
else
bReloadNeeded = FALSE;
nFeatures = -1;
return OGRERR_NONE;
}
/************************************************************************/
/* TestCapability() */
/************************************************************************/
int OGRWFSLayer::TestCapability( const char * pszCap )
{
if( EQUAL(pszCap,OLCFastFeatureCount) )
{
if (nFeatures >= 0)
return TRUE;
return poBaseLayer != NULL && m_poFilterGeom == NULL &&
m_poAttrQuery == NULL && poBaseLayer->TestCapability(pszCap) &&
(!poDS->IsPagingAllowed() && poBaseLayer->GetFeatureCount() < poDS->GetPageSize());
}
else if( EQUAL(pszCap,OLCFastGetExtent) )
{
if (bHasExtents)
return TRUE;
return poBaseLayer != NULL &&
poBaseLayer->TestCapability(pszCap);
}
else if( EQUAL(pszCap,OLCStringsAsUTF8) )
return poBaseLayer != NULL && poBaseLayer->TestCapability(pszCap);
else if( EQUAL(pszCap, OLCSequentialWrite) ||
EQUAL(pszCap, OLCDeleteFeature) ||
EQUAL(pszCap, OLCRandomWrite) )
{
GetLayerDefn();
return poDS->SupportTransactions() && poDS->UpdateMode() &&
poFeatureDefn->GetFieldIndex("gml_id") == 0;
}
else if ( EQUAL(pszCap, OLCTransactions) )
{
return poDS->SupportTransactions() && poDS->UpdateMode();
}
else if( EQUAL(pszCap,OLCIgnoreFields) )
{
return poBaseDS == NULL;
}
return FALSE;
}
/************************************************************************/
/* ExecuteGetFeatureResultTypeHits() */
/************************************************************************/
GIntBig OGRWFSLayer::ExecuteGetFeatureResultTypeHits()
{
char* pabyData = NULL;
CPLString osURL = MakeGetFeatureURL(0, TRUE);
if (pszRequiredOutputFormat)
osURL = CPLURLAddKVP(osURL, "OUTPUTFORMAT", WFS_EscapeURL(pszRequiredOutputFormat));
CPLDebug("WFS", "%s", osURL.c_str());
CPLHTTPResult* psResult = poDS->HTTPFetch( osURL, NULL);
if (psResult == NULL)
{
return -1;
}
/* http://demo.snowflakesoftware.com:8080/Obstacle_AIXM_ZIP/GOPublisherWFS returns */
/* zip content, including for RESULTTYPE=hits */
if (psResult->pszContentType != NULL &&
strstr(psResult->pszContentType, "application/zip") != NULL)
{
CPLString osTmpFileName;
osTmpFileName.Printf("/vsimem/wfstemphits_%p.zip", this);
VSILFILE *fp = VSIFileFromMemBuffer( osTmpFileName, psResult->pabyData,
psResult->nDataLen, FALSE);
VSIFCloseL(fp);
CPLString osZipTmpFileName("/vsizip/" + osTmpFileName);
char** papszDirContent = CPLReadDir(osZipTmpFileName);
if (CSLCount(papszDirContent) != 1)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot parse result of RESULTTYPE=hits request : more than one file in zip");
CSLDestroy(papszDirContent);
CPLHTTPDestroyResult(psResult);
VSIUnlink(osTmpFileName);
return -1;
}
CPLString osFileInZipTmpFileName = osZipTmpFileName + "/";
osFileInZipTmpFileName += papszDirContent[0];
fp = VSIFOpenL(osFileInZipTmpFileName.c_str(), "rb");
VSIStatBufL sBuf;
if (fp == NULL || VSIStatL(osFileInZipTmpFileName.c_str(), &sBuf) != 0 )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot parse result of RESULTTYPE=hits request : cannot open one file in zip");
CSLDestroy(papszDirContent);
CPLHTTPDestroyResult(psResult);
VSIUnlink(osTmpFileName);
if( fp )
VSIFCloseL(fp);
return -1;
}
pabyData = (char*) CPLMalloc((size_t)(sBuf.st_size + 1));
pabyData[sBuf.st_size] = 0;
VSIFReadL(pabyData, 1, (size_t)sBuf.st_size, fp);
VSIFCloseL(fp);
CSLDestroy(papszDirContent);
VSIUnlink(osTmpFileName);
}
else
{
pabyData = (char*) psResult->pabyData;
psResult->pabyData = NULL;
}
if (strstr(pabyData, "<ServiceExceptionReport") != NULL ||
strstr(pabyData, "<ows:ExceptionReport") != NULL)
{
if (poDS->IsOldDeegree(pabyData))
{
CPLHTTPDestroyResult(psResult);
return ExecuteGetFeatureResultTypeHits();
}
CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
pabyData);
CPLHTTPDestroyResult(psResult);
CPLFree(pabyData);
return -1;
}
CPLXMLNode* psXML = CPLParseXMLString( pabyData );
if (psXML == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s",
pabyData);
CPLHTTPDestroyResult(psResult);
CPLFree(pabyData);
return -1;
}
CPLStripXMLNamespace( psXML, NULL, TRUE );
CPLXMLNode* psRoot = CPLGetXMLNode( psXML, "=FeatureCollection" );
if (psRoot == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Cannot find <FeatureCollection>");
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
CPLFree(pabyData);
return -1;
}
const char* pszValue = CPLGetXMLValue(psRoot, "numberOfFeatures", NULL);
if (pszValue == NULL)
pszValue = CPLGetXMLValue(psRoot, "numberMatched", NULL); /* WFS 2.0.0 */
if (pszValue == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Cannot find numberOfFeatures");
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
CPLFree(pabyData);
poDS->DisableSupportHits();
return -1;
}
GIntBig l_nFeatures = CPLAtoGIntBig(pszValue);
/* Hum, http://deegree3-testing.deegree.org:80/deegree-inspire-node/services?MAXFEATURES=10&SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=ad:Address&OUTPUTFORMAT=text/xml;%20subtype=gml/3.2.1&RESULTTYPE=hits */
/* returns more than MAXFEATURES features... So truncate to MAXFEATURES */
CPLString osMaxFeatures = CPLURLGetValue(osURL, atoi(poDS->GetVersion()) >= 2 ? "COUNT" : "MAXFEATURES");
if (osMaxFeatures.size() != 0)
{
GIntBig nMaxFeatures = CPLAtoGIntBig(osMaxFeatures);
if (l_nFeatures > nMaxFeatures)
{
CPLDebug("WFS", "Truncating result from " CPL_FRMT_GIB " to " CPL_FRMT_GIB,
l_nFeatures, nMaxFeatures);
l_nFeatures = nMaxFeatures;
}
}
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
CPLFree(pabyData);
return l_nFeatures;
}
/************************************************************************/
/* CanRunGetFeatureCountAndGetExtentTogether() */
/************************************************************************/
int OGRWFSLayer::CanRunGetFeatureCountAndGetExtentTogether()
{
/* In some cases, we can evaluate the result of GetFeatureCount() */
/* and GetExtent() with the same data */
CPLString osRequestURL = MakeGetFeatureURL(0, FALSE);
return( !bHasExtents && nFeatures < 0 &&
osRequestURL.ifind("FILTER") == std::string::npos &&
osRequestURL.ifind("MAXFEATURES") == std::string::npos &&
osRequestURL.ifind("COUNT") == std::string::npos &&
!(GetLayerDefn()->IsGeometryIgnored()) );
}
/************************************************************************/
/* GetFeatureCount() */
/************************************************************************/
GIntBig OGRWFSLayer::GetFeatureCount( int bForce )
{
if (nFeatures >= 0)
return nFeatures;
if (TestCapability(OLCFastFeatureCount))
return poBaseLayer->GetFeatureCount(bForce);
if ((m_poAttrQuery == NULL || osWFSWhere.size() != 0) &&
poDS->GetFeatureSupportHits())
{
nFeatures = ExecuteGetFeatureResultTypeHits();
if (nFeatures >= 0)
return nFeatures;
}
/* If we have not yet the base layer, try to read one */
/* feature, and then query again OLCFastFeatureCount on the */
/* base layer. In case the WFS response would contain the */
/* number of features */
if (poBaseLayer == NULL)
{
ResetReading();
OGRFeature* poFeature = GetNextFeature();
delete poFeature;
ResetReading();
if (TestCapability(OLCFastFeatureCount))
return poBaseLayer->GetFeatureCount(bForce);
}
/* In some cases, we can evaluate the result of GetFeatureCount() */
/* and GetExtent() with the same data */
if( CanRunGetFeatureCountAndGetExtentTogether() )
{
OGREnvelope sDummy;
GetExtent(&sDummy);
}
if( nFeatures < 0 )
nFeatures = OGRLayer::GetFeatureCount(bForce);
return nFeatures;
}
/************************************************************************/
/* SetExtent() */
/************************************************************************/
void OGRWFSLayer::SetExtents(double dfMinXIn, double dfMinYIn, double dfMaxXIn, double dfMaxYIn)
{
this->dfMinX = dfMinXIn;
this->dfMinY = dfMinYIn;
this->dfMaxX = dfMaxXIn;
this->dfMaxY = dfMaxYIn;
bHasExtents = TRUE;
}
/************************************************************************/
/* GetExtent() */
/************************************************************************/
OGRErr OGRWFSLayer::GetExtent(OGREnvelope *psExtent, int bForce)
{
if (bHasExtents)
{
psExtent->MinX = dfMinX;
psExtent->MinY = dfMinY;
psExtent->MaxX = dfMaxX;
psExtent->MaxY = dfMaxY;
return OGRERR_NONE;
}
/* If we have not yet the base layer, try to read one */
/* feature, and then query again OLCFastGetExtent on the */
/* base layer. In case the WFS response would contain the */
/* global extent */
if (poBaseLayer == NULL)
{
ResetReading();
OGRFeature* poFeature = GetNextFeature();
delete poFeature;
ResetReading();
}
if (TestCapability(OLCFastGetExtent))
return poBaseLayer->GetExtent(psExtent, bForce);
/* In some cases, we can evaluate the result of GetFeatureCount() */
/* and GetExtent() with the same data */
if( CanRunGetFeatureCountAndGetExtentTogether() )
{
bCountFeaturesInGetNextFeature = TRUE;
nFeatures = 0;
}
OGRErr eErr = OGRLayer::GetExtent(psExtent, bForce);
if( bCountFeaturesInGetNextFeature )
{
if( eErr == OGRERR_NONE )
{
dfMinX = psExtent->MinX;
dfMinY = psExtent->MinY;
dfMaxX = psExtent->MaxX;
dfMaxY = psExtent->MaxY;
bHasExtents = TRUE;
}
else
{
nFeatures = -1;
}
bCountFeaturesInGetNextFeature = FALSE;
}
return eErr;
}
/************************************************************************/
/* GetShortName() */
/************************************************************************/
const char* OGRWFSLayer::GetShortName()
{
const char* pszShortName = strchr(pszName, ':');
if (pszShortName == NULL)
pszShortName = pszName;
else
pszShortName ++;
return pszShortName;
}
/************************************************************************/
/* GetPostHeader() */
/************************************************************************/
CPLString OGRWFSLayer::GetPostHeader()
{
CPLString osPost;
osPost += "<?xml version=\"1.0\"?>\n";
osPost += "<wfs:Transaction xmlns:wfs=\"http://www.opengis.net/wfs\"\n";
osPost += " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
osPost += " service=\"WFS\" version=\""; osPost += poDS->GetVersion(); osPost += "\"\n";
osPost += " xmlns:gml=\"http://www.opengis.net/gml\"\n";
osPost += " xmlns:ogc=\"http://www.opengis.net/ogc\"\n";
osPost += " xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/";
osPost += poDS->GetVersion();
osPost += "/wfs.xsd ";
osPost += osTargetNamespace;
osPost += " ";
char* pszXMLEncoded = CPLEscapeString(
GetDescribeFeatureTypeURL(FALSE), -1, CPLES_XML);
osPost += pszXMLEncoded;
CPLFree(pszXMLEncoded);
osPost += "\">\n";
return osPost;
}
/************************************************************************/
/* ICreateFeature() */
/************************************************************************/
OGRErr OGRWFSLayer::ICreateFeature( OGRFeature *poFeature )
{
if (!TestCapability(OLCSequentialWrite))
{
if (!poDS->SupportTransactions())
CPLError(CE_Failure, CPLE_AppDefined,
"CreateFeature() not supported: no WMS-T features advertized by server");
else if (!poDS->UpdateMode())
CPLError(CE_Failure, CPLE_AppDefined,
"CreateFeature() not supported: datasource opened as read-only");
return OGRERR_FAILURE;
}
if (poGMLFeatureClass == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot insert feature because we didn't manage to parse the .XSD schema");
return OGRERR_FAILURE;
}
if (poFeatureDefn->GetFieldIndex("gml_id") != 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find gml_id field");
return OGRERR_FAILURE;
}
if (poFeature->IsFieldSet(0))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot insert a feature when gml_id field is already set");
return OGRERR_FAILURE;
}
CPLString osPost;
const char* pszShortName = GetShortName();
if (!bInTransaction)
{
osPost += GetPostHeader();
osPost += " <wfs:Insert>\n";
}
osPost += " <feature:"; osPost += pszShortName; osPost += " xmlns:feature=\"";
osPost += osTargetNamespace; osPost += "\">\n";
int i;
for(i=1; i <= poFeature->GetFieldCount(); i++)
{
if (poGMLFeatureClass->GetGeometryPropertyCount() == 1 &&
poGMLFeatureClass->GetGeometryProperty(0)->GetAttributeIndex() == i - 1)
{
OGRGeometry* poGeom = poFeature->GetGeometryRef();
if (poGeom != NULL && osGeometryColumnName.size() != 0)
{
if (poGeom->getSpatialReference() == NULL)
poGeom->assignSpatialReference(poSRS);
char* pszGML;
if (strcmp(poDS->GetVersion(), "1.1.0") == 0)
{
char** papszOptions = CSLAddString(NULL, "FORMAT=GML3");
pszGML = OGR_G_ExportToGMLEx((OGRGeometryH)poGeom, papszOptions);
CSLDestroy(papszOptions);
}
else
pszGML = OGR_G_ExportToGML((OGRGeometryH)poGeom);
osPost += " <feature:"; osPost += osGeometryColumnName; osPost += ">";
osPost += pszGML;
osPost += "</feature:"; osPost += osGeometryColumnName; osPost += ">\n";
CPLFree(pszGML);
}
}
if (i == poFeature->GetFieldCount())
break;
if (poFeature->IsFieldSet(i))
{
OGRFieldDefn* poFDefn = poFeature->GetFieldDefnRef(i);
osPost += " <feature:";
osPost += poFDefn->GetNameRef();
osPost += ">";
if (poFDefn->GetType() == OFTInteger)
osPost += CPLSPrintf("%d", poFeature->GetFieldAsInteger(i));
else if (poFDefn->GetType() == OFTInteger64)
osPost += CPLSPrintf(CPL_FRMT_GIB, poFeature->GetFieldAsInteger64(i));
else if (poFDefn->GetType() == OFTReal)
osPost += CPLSPrintf("%.16g", poFeature->GetFieldAsDouble(i));
else
{
char* pszXMLEncoded = CPLEscapeString(poFeature->GetFieldAsString(i),
-1, CPLES_XML);
osPost += pszXMLEncoded;
CPLFree(pszXMLEncoded);
}
osPost += "</feature:";
osPost += poFDefn->GetNameRef();
osPost += ">\n";
}
}
osPost += " </feature:"; osPost += pszShortName; osPost += ">\n";
if (!bInTransaction)
{
osPost += " </wfs:Insert>\n";
osPost += "</wfs:Transaction>\n";
}
else
{
osGlobalInsert += osPost;
nExpectedInserts ++;
return OGRERR_NONE;
}
CPLDebug("WFS", "Post : %s", osPost.c_str());
char** papszOptions = NULL;
papszOptions = CSLAddNameValue(papszOptions, "POSTFIELDS", osPost.c_str());
papszOptions = CSLAddNameValue(papszOptions, "HEADERS",
"Content-Type: application/xml; charset=UTF-8");
CPLHTTPResult* psResult = poDS->HTTPFetch(poDS->GetPostTransactionURL(), papszOptions);
CSLDestroy(papszOptions);
if (psResult == NULL)
{
return OGRERR_FAILURE;
}
if (strstr((const char*)psResult->pabyData,
"<ServiceExceptionReport") != NULL ||
strstr((const char*)psResult->pabyData,
"<ows:ExceptionReport") != NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
psResult->pabyData);
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
CPLDebug("WFS", "Response: %s", psResult->pabyData);
CPLXMLNode* psXML = CPLParseXMLString( (const char*) psResult->pabyData );
if (psXML == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s",
psResult->pabyData);
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
CPLStripXMLNamespace( psXML, NULL, TRUE );
int bUse100Schema = FALSE;
CPLXMLNode* psRoot = CPLGetXMLNode( psXML, "=TransactionResponse" );
if (psRoot == NULL)
{
psRoot = CPLGetXMLNode( psXML, "=WFS_TransactionResponse" );
if (psRoot)
bUse100Schema = TRUE;
}
if (psRoot == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find <TransactionResponse>");
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
CPLXMLNode* psFeatureID = NULL;
if (bUse100Schema)
{
if (CPLGetXMLNode( psRoot, "TransactionResult.Status.FAILED" ))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Insert failed : %s",
psResult->pabyData);
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
psFeatureID =
CPLGetXMLNode( psRoot, "InsertResult.FeatureId");
if (psFeatureID == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find InsertResult.FeatureId");
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
}
else
{
psFeatureID =
CPLGetXMLNode( psRoot, "InsertResults.Feature.FeatureId");
if (psFeatureID == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find InsertResults.Feature.FeatureId");
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
}
const char* pszFID = CPLGetXMLValue(psFeatureID, "fid", NULL);
if (pszFID == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Cannot find fid");
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
poFeature->SetField("gml_id", pszFID);
/* If the returned fid is of the form layer_name.num, then use */
/* num as the OGR FID */
if (strncmp(pszFID, pszShortName, strlen(pszShortName)) == 0 &&
pszFID[strlen(pszShortName)] == '.')
{
GIntBig nFID = CPLAtoGIntBig(pszFID + strlen(pszShortName) + 1);
poFeature->SetFID(nFID);
}
CPLDebug("WFS", "Got FID = " CPL_FRMT_GIB, poFeature->GetFID());
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
/* Invalidate layer */
bReloadNeeded = TRUE;
nFeatures = -1;
bHasExtents = FALSE;
return OGRERR_NONE;
}
/************************************************************************/
/* ISetFeature() */
/************************************************************************/
OGRErr OGRWFSLayer::ISetFeature( OGRFeature *poFeature )
{
if (!TestCapability(OLCRandomWrite))
{
if (!poDS->SupportTransactions())
CPLError(CE_Failure, CPLE_AppDefined,
"SetFeature() not supported: no WMS-T features advertized by server");
else if (!poDS->UpdateMode())
CPLError(CE_Failure, CPLE_AppDefined,
"SetFeature() not supported: datasource opened as read-only");
return OGRERR_FAILURE;
}
if (poFeatureDefn->GetFieldIndex("gml_id") != 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find gml_id field");
return OGRERR_FAILURE;
}
if (poFeature->IsFieldSet(0) == FALSE)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot update a feature when gml_id field is not set");
return OGRERR_FAILURE;
}
if (bInTransaction)
{
CPLError(CE_Warning, CPLE_AppDefined,
"SetFeature() not yet dealt in transaction. Issued immediately");
}
const char* pszShortName = GetShortName();
CPLString osPost;
osPost += GetPostHeader();
osPost += " <wfs:Update typeName=\"feature:"; osPost += pszShortName; osPost += "\" xmlns:feature=\"";
osPost += osTargetNamespace; osPost += "\">\n";
OGRGeometry* poGeom = poFeature->GetGeometryRef();
if ( osGeometryColumnName.size() != 0 )
{
osPost += " <wfs:Property>\n";
osPost += " <wfs:Name>"; osPost += osGeometryColumnName; osPost += "</wfs:Name>\n";
if (poGeom != NULL)
{
if (poGeom->getSpatialReference() == NULL)
poGeom->assignSpatialReference(poSRS);
char* pszGML;
if (strcmp(poDS->GetVersion(), "1.1.0") == 0)
{
char** papszOptions = CSLAddString(NULL, "FORMAT=GML3");
pszGML = OGR_G_ExportToGMLEx((OGRGeometryH)poGeom, papszOptions);
CSLDestroy(papszOptions);
}
else
pszGML = OGR_G_ExportToGML((OGRGeometryH)poGeom);
osPost += " <wfs:Value>";
osPost += pszGML;
osPost += "</wfs:Value>\n";
CPLFree(pszGML);
}
osPost += " </wfs:Property>\n";
}
int i;
for(i=1; i < poFeature->GetFieldCount(); i++)
{
OGRFieldDefn* poFDefn = poFeature->GetFieldDefnRef(i);
osPost += " <wfs:Property>\n";
osPost += " <wfs:Name>"; osPost += poFDefn->GetNameRef(); osPost += "</wfs:Name>\n";
if (poFeature->IsFieldSet(i))
{
osPost += " <wfs:Value>";
if (poFDefn->GetType() == OFTInteger)
osPost += CPLSPrintf("%d", poFeature->GetFieldAsInteger(i));
else if (poFDefn->GetType() == OFTInteger64)
osPost += CPLSPrintf(CPL_FRMT_GIB, poFeature->GetFieldAsInteger64(i));
else if (poFDefn->GetType() == OFTReal)
osPost += CPLSPrintf("%.16g", poFeature->GetFieldAsDouble(i));
else
{
char* pszXMLEncoded = CPLEscapeString(poFeature->GetFieldAsString(i),
-1, CPLES_XML);
osPost += pszXMLEncoded;
CPLFree(pszXMLEncoded);
}
osPost += "</wfs:Value>\n";
}
osPost += " </wfs:Property>\n";
}
osPost += " <ogc:Filter>\n";
if (poDS->UseFeatureId() || bUseFeatureIdAtLayerLevel)
osPost += " <ogc:FeatureId fid=\"";
else if (atoi(poDS->GetVersion()) >= 2)
osPost += " <ogc:ResourceId rid=\"";
else
osPost += " <ogc:GmlObjectId gml:id=\"";
osPost += poFeature->GetFieldAsString(0); osPost += "\"/>\n";
osPost += " </ogc:Filter>\n";
osPost += " </wfs:Update>\n";
osPost += "</wfs:Transaction>\n";
CPLDebug("WFS", "Post : %s", osPost.c_str());
char** papszOptions = NULL;
papszOptions = CSLAddNameValue(papszOptions, "POSTFIELDS", osPost.c_str());
papszOptions = CSLAddNameValue(papszOptions, "HEADERS",
"Content-Type: application/xml; charset=UTF-8");
CPLHTTPResult* psResult = poDS->HTTPFetch(poDS->GetPostTransactionURL(), papszOptions);
CSLDestroy(papszOptions);
if (psResult == NULL)
{
return OGRERR_FAILURE;
}
if (strstr((const char*)psResult->pabyData,
"<ServiceExceptionReport") != NULL ||
strstr((const char*)psResult->pabyData,
"<ows:ExceptionReport") != NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
psResult->pabyData);
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
CPLDebug("WFS", "Response: %s", psResult->pabyData);
CPLXMLNode* psXML = CPLParseXMLString( (const char*) psResult->pabyData );
if (psXML == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s",
psResult->pabyData);
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
CPLStripXMLNamespace( psXML, NULL, TRUE );
int bUse100Schema = FALSE;
CPLXMLNode* psRoot = CPLGetXMLNode( psXML, "=TransactionResponse" );
if (psRoot == NULL)
{
psRoot = CPLGetXMLNode( psXML, "=WFS_TransactionResponse" );
if (psRoot)
bUse100Schema = TRUE;
}
if (psRoot == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find <TransactionResponse>");
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
if (bUse100Schema)
{
if (CPLGetXMLNode( psRoot, "TransactionResult.Status.FAILED" ))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Update failed : %s",
psResult->pabyData);
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
}
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
/* Invalidate layer */
bReloadNeeded = TRUE;
nFeatures = -1;
bHasExtents = FALSE;
return OGRERR_NONE;
}
/************************************************************************/
/* GetFeature() */
/************************************************************************/
OGRFeature* OGRWFSLayer::GetFeature(GIntBig nFID)
{
GetLayerDefn();
if (poBaseLayer == NULL && poFeatureDefn->GetFieldIndex("gml_id") == 0)
{
/* This is lovely hackish. We assume that then gml_id will be */
/* layer_name.number. This is actually what we can observe with */
/* GeoServer and TinyOWS */
CPLString osVal = CPLSPrintf("gml_id = '%s." CPL_FRMT_GIB "'", GetShortName(), nFID);
CPLString osOldSQLWhere(osSQLWhere);
SetAttributeFilter(osVal);
OGRFeature* poFeature = GetNextFeature();
const char* pszOldFilter = osOldSQLWhere.size() ? osOldSQLWhere.c_str() : NULL;
SetAttributeFilter(pszOldFilter);
if (poFeature)
return poFeature;
}
return OGRLayer::GetFeature(nFID);
}
/************************************************************************/
/* DeleteFromFilter() */
/************************************************************************/
OGRErr OGRWFSLayer::DeleteFromFilter( CPLString osOGCFilter )
{
if (!TestCapability(OLCDeleteFeature))
{
if (!poDS->SupportTransactions())
CPLError(CE_Failure, CPLE_AppDefined,
"DeleteFromFilter() not supported: no WMS-T features advertized by server");
else if (!poDS->UpdateMode())
CPLError(CE_Failure, CPLE_AppDefined,
"DeleteFromFilter() not supported: datasource opened as read-only");
return OGRERR_FAILURE;
}
if (poFeatureDefn->GetFieldIndex("gml_id") != 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find gml_id field");
return OGRERR_FAILURE;
}
const char* pszShortName = GetShortName();
CPLString osPost;
osPost += GetPostHeader();
osPost += " <wfs:Delete xmlns:feature=\""; osPost += osTargetNamespace;
osPost += "\" typeName=\"feature:"; osPost += pszShortName; osPost += "\">\n";
osPost += " <ogc:Filter>\n";
osPost += osOGCFilter;
osPost += " </ogc:Filter>\n";
osPost += " </wfs:Delete>\n";
osPost += "</wfs:Transaction>\n";
CPLDebug("WFS", "Post : %s", osPost.c_str());
char** papszOptions = NULL;
papszOptions = CSLAddNameValue(papszOptions, "POSTFIELDS", osPost.c_str());
papszOptions = CSLAddNameValue(papszOptions, "HEADERS",
"Content-Type: application/xml; charset=UTF-8");
CPLHTTPResult* psResult = poDS->HTTPFetch(poDS->GetPostTransactionURL(), papszOptions);
CSLDestroy(papszOptions);
if (psResult == NULL)
{
return OGRERR_FAILURE;
}
if (strstr((const char*)psResult->pabyData, "<ServiceExceptionReport") != NULL ||
strstr((const char*)psResult->pabyData, "<ows:ExceptionReport") != NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
psResult->pabyData);
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
CPLDebug("WFS", "Response: %s", psResult->pabyData);
CPLXMLNode* psXML = CPLParseXMLString( (const char*) psResult->pabyData );
if (psXML == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s",
psResult->pabyData);
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
CPLStripXMLNamespace( psXML, NULL, TRUE );
int bUse100Schema = FALSE;
CPLXMLNode* psRoot = CPLGetXMLNode( psXML, "=TransactionResponse" );
if (psRoot == NULL)
{
psRoot = CPLGetXMLNode( psXML, "=WFS_TransactionResponse" );
if (psRoot)
bUse100Schema = TRUE;
}
if (psRoot == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Cannot find <TransactionResponse>");
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
if (bUse100Schema)
{
if (CPLGetXMLNode( psRoot, "TransactionResult.Status.FAILED" ))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Delete failed : %s",
psResult->pabyData);
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
}
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
/* Invalidate layer */
bReloadNeeded = TRUE;
nFeatures = -1;
bHasExtents = FALSE;
return OGRERR_NONE;
}
/************************************************************************/
/* DeleteFeature() */
/************************************************************************/
OGRErr OGRWFSLayer::DeleteFeature( GIntBig nFID )
{
if (!TestCapability(OLCDeleteFeature))
{
if (!poDS->SupportTransactions())
CPLError(CE_Failure, CPLE_AppDefined,
"DeleteFeature() not supported: no WMS-T features advertized by server");
else if (!poDS->UpdateMode())
CPLError(CE_Failure, CPLE_AppDefined,
"DeleteFeature() not supported: datasource opened as read-only");
return OGRERR_FAILURE;
}
if (poFeatureDefn->GetFieldIndex("gml_id") != 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find gml_id field");
return OGRERR_FAILURE;
}
OGRFeature* poFeature = GetFeature(nFID);
if (poFeature == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find feature " CPL_FRMT_GIB, nFID);
return OGRERR_FAILURE;
}
const char* pszGMLID = poFeature->GetFieldAsString("gml_id");
if (pszGMLID == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot delete a feature with gml_id unset");
delete poFeature;
return OGRERR_FAILURE;
}
if (bInTransaction)
{
CPLError(CE_Warning, CPLE_AppDefined,
"DeleteFeature() not yet dealt in transaction. Issued immediately");
}
CPLString osGMLID = pszGMLID;
pszGMLID = NULL;
delete poFeature;
poFeature = NULL;
CPLString osFilter;
osFilter = "<ogc:FeatureId fid=\""; osFilter += osGMLID; osFilter += "\"/>\n";
return DeleteFromFilter(osFilter);
}
/************************************************************************/
/* StartTransaction() */
/************************************************************************/
OGRErr OGRWFSLayer::StartTransaction()
{
if (!TestCapability(OLCTransactions))
{
if (!poDS->SupportTransactions())
CPLError(CE_Failure, CPLE_AppDefined,
"StartTransaction() not supported: no WMS-T features advertized by server");
else if (!poDS->UpdateMode())
CPLError(CE_Failure, CPLE_AppDefined,
"StartTransaction() not supported: datasource opened as read-only");
return OGRERR_FAILURE;
}
if (bInTransaction)
{
CPLError(CE_Failure, CPLE_AppDefined,
"StartTransaction() has already been called");
return OGRERR_FAILURE;
}
bInTransaction = TRUE;
osGlobalInsert = "";
nExpectedInserts = 0;
aosFIDList.resize(0);
return OGRERR_NONE;
}
/************************************************************************/
/* CommitTransaction() */
/************************************************************************/
OGRErr OGRWFSLayer::CommitTransaction()
{
if (!TestCapability(OLCTransactions))
{
if (!poDS->SupportTransactions())
CPLError(CE_Failure, CPLE_AppDefined,
"CommitTransaction() not supported: no WMS-T features advertized by server");
else if (!poDS->UpdateMode())
CPLError(CE_Failure, CPLE_AppDefined,
"CommitTransaction() not supported: datasource opened as read-only");
return OGRERR_FAILURE;
}
if (!bInTransaction)
{
CPLError(CE_Failure, CPLE_AppDefined,
"StartTransaction() has not yet been called");
return OGRERR_FAILURE;
}
if (osGlobalInsert.size() != 0)
{
CPLString osPost = GetPostHeader();
osPost += " <wfs:Insert>\n";
osPost += osGlobalInsert;
osPost += " </wfs:Insert>\n";
osPost += "</wfs:Transaction>\n";
bInTransaction = FALSE;
osGlobalInsert = "";
int l_nExpectedInserts = this->nExpectedInserts;
this->nExpectedInserts = 0;
CPLDebug("WFS", "Post : %s", osPost.c_str());
char** papszOptions = NULL;
papszOptions = CSLAddNameValue(papszOptions, "POSTFIELDS", osPost.c_str());
papszOptions = CSLAddNameValue(papszOptions, "HEADERS",
"Content-Type: application/xml; charset=UTF-8");
CPLHTTPResult* psResult = poDS->HTTPFetch(poDS->GetPostTransactionURL(), papszOptions);
CSLDestroy(papszOptions);
if (psResult == NULL)
{
return OGRERR_FAILURE;
}
if (strstr((const char*)psResult->pabyData,
"<ServiceExceptionReport") != NULL ||
strstr((const char*)psResult->pabyData,
"<ows:ExceptionReport") != NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
psResult->pabyData);
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
CPLDebug("WFS", "Response: %s", psResult->pabyData);
CPLXMLNode* psXML = CPLParseXMLString( (const char*) psResult->pabyData );
if (psXML == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s",
psResult->pabyData);
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
CPLStripXMLNamespace( psXML, NULL, TRUE );
int bUse100Schema = FALSE;
CPLXMLNode* psRoot = CPLGetXMLNode( psXML, "=TransactionResponse" );
if (psRoot == NULL)
{
psRoot = CPLGetXMLNode( psXML, "=WFS_TransactionResponse" );
if (psRoot)
bUse100Schema = TRUE;
}
if (psRoot == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find <TransactionResponse>");
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
if (bUse100Schema)
{
if (CPLGetXMLNode( psRoot, "TransactionResult.Status.FAILED" ))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Insert failed : %s",
psResult->pabyData);
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
/* TODO */
}
else
{
int nGotInserted = atoi(CPLGetXMLValue(psRoot, "TransactionSummary.totalInserted", ""));
if (nGotInserted != l_nExpectedInserts)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Only %d features were inserted whereas %d where expected",
nGotInserted, l_nExpectedInserts);
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
CPLXMLNode* psInsertResults =
CPLGetXMLNode( psRoot, "InsertResults");
if (psInsertResults == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find node InsertResults");
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
aosFIDList.resize(0);
CPLXMLNode* psChild = psInsertResults->psChild;
while(psChild)
{
const char* pszFID = CPLGetXMLValue(psChild, "FeatureId.fid", NULL);
if (pszFID == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "Cannot find fid");
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
aosFIDList.push_back(pszFID);
psChild = psChild->psNext;
}
if ((int)aosFIDList.size() != nGotInserted)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Inconsistent InsertResults: did not get expected FID count");
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
return OGRERR_FAILURE;
}
}
CPLDestroyXMLNode( psXML );
CPLHTTPDestroyResult(psResult);
}
bInTransaction = FALSE;
osGlobalInsert = "";
nExpectedInserts = 0;
return OGRERR_NONE;
}
/************************************************************************/
/* RollbackTransaction() */
/************************************************************************/
OGRErr OGRWFSLayer::RollbackTransaction()
{
if (!TestCapability(OLCTransactions))
{
if (!poDS->SupportTransactions())
CPLError(CE_Failure, CPLE_AppDefined,
"RollbackTransaction() not supported: no WMS-T features advertized by server");
else if (!poDS->UpdateMode())
CPLError(CE_Failure, CPLE_AppDefined,
"RollbackTransaction() not supported: datasource opened as read-only");
return OGRERR_FAILURE;
}
if (!bInTransaction)
{
CPLError(CE_Failure, CPLE_AppDefined,
"StartTransaction() has not yet been called");
return OGRERR_FAILURE;
}
bInTransaction = FALSE;
osGlobalInsert = "";
nExpectedInserts = 0;
return OGRERR_NONE;
}
/************************************************************************/
/* SetRequiredOutputFormat() */
/************************************************************************/
void OGRWFSLayer::SetRequiredOutputFormat(const char* pszRequiredOutputFormatIn)
{
CPLFree(pszRequiredOutputFormat);
if (pszRequiredOutputFormatIn)
{
pszRequiredOutputFormat = CPLStrdup(pszRequiredOutputFormatIn);
}
else
{
pszRequiredOutputFormat = NULL;
}
}
/************************************************************************/
/* SetOrderBy() */
/************************************************************************/
void OGRWFSLayer::SetOrderBy(const std::vector<OGRWFSSortDesc>& aoSortColumnsIn)
{
aoSortColumns = aoSortColumnsIn;
}
|
SECTION code_clib
PUBLIC asm_interrupt_handler
EXTERN l_jphl
; Calls the registered handlers in order
; Entry: hl = table to call
;
asm_interrupt_handler:
push bc
push de
; af, hl already preserved
loop:
ld a,(hl)
inc hl
or (hl)
jr z,done
push hl
ld a,(hl)
dec hl
ld l,(hl)
ld h,a
call l_jphl
pop hl
inc hl
jr loop
done:
pop de
pop bc
ret
|
/*
equal distribution over triangulated surface.
This file is part of the source code used for the calculation of the moment invariants
as described in the dissertation of Max Langbein
https://nbn-resolving.org/urn:nbn:de:hbz:386-kluedo-38558
Copyright (C) 2020 TU Kaiserslautern, Prof.Dr. Hans Hagen (AG Computergraphik und HCI) (hagen@cs.uni-kl.de)
Author: Max Langbein (m_langbe@cs.uni-kl.de)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include<stdlib.h>
#include<vector>
#include<cmath>
#include "d3op.h"
#include "momentSet.h"
#include "equaldist.h"
using namespace std;
mynum equaldist::area()
{
mynum ret=0;
for(int i=0;i<tris.size();i+=3)
{
ret+=area(tris[i],tris[i+1],tris[i+2]);
}
for(int i=0;i<quads.size();i+=4)
{
ret+=area(quads[i],quads[i+1],quads[i+2]);
ret+=area(quads[i],quads[i+2],quads[i+3]);
}
for(int i=0;i<polygons.size();++i)
{
vector<int>&p=polygons[i];
mynum vec[3]={0,0,0};mynum g[3];
for(int j=2;j<p.size();++j)
{
areaNormal(g,p[0],p[j-1],p[j]);
d3op2(,vec,+=,g,);
}
ret += sqrt(d3prod(vec,vec))/2;
}
return ret;
}
void equaldist::addPointsForTri(std::vector<mynum>&points,mynum density,int i1,int i2,int i3)
{
mynum num = density*area(i1,i2,i3);
int n=(int)floor(num);
//force expectance of n to be num
if( rand() < RAND_MAX *( num-n) )
++n;
mynum a[3],b[3],c[3],ret[3];
extract(i1,a);
extract(i2,b);
extract(i3,c);
for(int i=0;i<n;++i)
{
mynum u = rand()*1.0/RAND_MAX;
mynum v = rand()*1.0/RAND_MAX;
mynum w=1-u-v;
if(w<0){
u=1-u;
v=1-v;
w=-w;
}
d3op4(,ret,=u*,a,+v*,b,+w*,c,);
points.push_back(ret[0]);
points.push_back(ret[1]);
points.push_back(ret[2]);
}
}
void equaldist::createEqualDensity(std::vector<mynum>&points,mynum density)
{
mynum ret=0;
points.clear();
for(int i=0;i<tris.size();i+=3)
{
addPointsForTri(points,density,tris[i],tris[i+1],tris[i+2]);
}
for(int i=0;i<quads.size();i+=4)
{
addPointsForTri(points,density,quads[i],quads[i+1],quads[i+2]);
addPointsForTri(points,density,quads[i],quads[i+2],quads[i+3]);
}
for(int i=0;i<polygons.size();++i)
{
//todo:triangulate and process.
}
}
|
#include "ui_connectionsettingsdialog.h"
#include "ConnectionSettings.h"
#include "CurrencyAdapter.h"
#include "NewNodeDialog.h"
#include "MainWindow.h"
#include "NodeModel.h"
#include "Settings.h"
#include <QDebug>
namespace Ui {
class ConnectionSettingsDialog;
}
namespace WalletGui {
ConnectionSettingsDialog::ConnectionSettingsDialog(QWidget* _parent) : QDialog(_parent),
m_nodeModel(new NodeModel(this)),
m_ui(new Ui::ConnectionSettingsDialog) {
m_ui->setupUi(this);
m_ui->remoteNodesComboBox->setModel(m_nodeModel);
// m_ui->remoteNodesComboBox->setValidator(new QRegExpValidator( QRegExp("[^\\:]+:[0-9]"), this ));
}
ConnectionSettingsDialog::~ConnectionSettingsDialog() {
}
void ConnectionSettingsDialog::initConnectionSettings() {
QString connection = Settings::instance().getConnection();
if(connection.compare("auto") == 0) {
m_ui->radioButton_1->setChecked(true);
}
else if(connection.compare("embedded") == 0) {
m_ui->radioButton_2->setChecked(true);
}
else if(connection.compare("local") == 0) {
m_ui->radioButton_3->setChecked(true);
}
else if(connection.compare("remote") == 0) {
m_ui->radioButton_4->setChecked(true);
}
quint16 localDaemonPort = Settings::instance().getCurrentLocalDaemonPort();
if(localDaemonPort == 0) {
localDaemonPort = CryptoNote::RPC_DEFAULT_PORT;
}
m_ui->m_localDaemonPort->setValue(localDaemonPort);
QString currentRemoteNode = Settings::instance().getCurrentRemoteNode().split(":")[0];
int index = m_ui->remoteNodesComboBox->findData(currentRemoteNode);
if ( index != -1 ) {
m_ui->remoteNodesComboBox->setCurrentIndex(index);
}
}
QString ConnectionSettingsDialog::setConnectionMode() const {
QString connectionMode;
if(m_ui->radioButton_1->isChecked())
{
connectionMode = "auto";
}
if(m_ui->radioButton_2->isChecked())
{
connectionMode = "embedded";
}
else if(m_ui->radioButton_3->isChecked())
{
connectionMode = "local";
}
else if(m_ui->radioButton_4->isChecked())
{
connectionMode = "remote";
}
return connectionMode;
}
QString ConnectionSettingsDialog::setRemoteNode() const {
QString selectedRemoteNode;
selectedRemoteNode = m_ui->remoteNodesComboBox->currentText();
return selectedRemoteNode;
}
quint16 ConnectionSettingsDialog::setLocalDaemonPort() const {
quint16 localDaemonPort;
localDaemonPort = m_ui->m_localDaemonPort->value();
return localDaemonPort;
}
void ConnectionSettingsDialog::addNodeClicked() {
/*
QString host = m_ui->remoteNodesComboBox->currentText().split(":")[0];
quint16 port = m_ui->remoteNodesComboBox->currentText().split(":")[1].toInt();
if (host.isEmpty()) {
return;
}
m_nodeModel->addNode(host, port);
*/
NewNodeDialog dlg(&MainWindow::instance());
if (dlg.exec() == QDialog::Accepted) {
QString host = dlg.getHost();
quint16 port = dlg.getPort();
if (host.isEmpty()) {
return;
}
m_nodeModel->addNode(host, port);
}
}
void ConnectionSettingsDialog::removeNodeClicked() {
m_nodeModel->removeRow(m_ui->remoteNodesComboBox->currentIndex());
Settings::instance().setRpcNodesList(m_nodeModel->stringList());
}
}
|
#include <aikido/rviz/InteractiveMarkerViewer.hpp>
#include <dart/dynamics/JacobianNode.hpp>
#include <pybind11/cast.h>
#include <pybind11/eigen.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <aikido/planner/World.hpp>
#include "libada/Ada.hpp"
#include "aikido/constraint/Satisfied.hpp"
#include "aikido/planner/kunzretimer/KunzRetimer.hpp"
#include "aikido/planner/parabolic/ParabolicSmoother.hpp"
#include "aikido/statespace/ScopedState.hpp"
namespace py = pybind11;
using aikido::planner::kunzretimer::KunzRetimer;
using aikido::planner::parabolic::ParabolicSmoother;
//==============================================================================
// NOTE: These functions define the Python API for Ada.
aikido::constraint::TestablePtr get_self_collision_constraint(ada::Ada* self)
{
return self->getArm()->getSelfCollisionConstraint();
}
bool start_trajectory_controllers(ada::Ada* self)
{
return self->startTrajectoryControllers();
}
bool stop_trajectory_controllers(ada::Ada* self)
{
return self->stopTrajectoryControllers();
}
std::string get_name(ada::Ada* self)
{
return self->getName();
}
aikido::planner::WorldPtr get_world(ada::Ada* self)
{
return self->getWorld();
}
std::shared_ptr<ada::Ada::AdaHand> get_hand(ada::Ada* self)
{
return self->getHand();
}
dart::dynamics::MetaSkeletonPtr get_skeleton(ada::Ada* self)
{
return self->getMetaSkeleton();
}
dart::dynamics::MetaSkeletonPtr get_arm_skeleton(ada::Ada* self)
{
return self->getArm()->getMetaSkeleton();
}
aikido::statespace::dart::MetaSkeletonStateSpacePtr get_arm_state_space(
ada::Ada* self)
{
auto armSkeleton = self->getArm()->getMetaSkeleton();
auto armSpace
= std::make_shared<aikido::statespace::dart::MetaSkeletonStateSpace>(
armSkeleton.get());
return armSpace;
}
void set_arm_positions(ada::Ada* self, const Eigen::VectorXd& configuration)
{
auto arm = self->getArm();
auto armSkeleton = arm->getMetaSkeleton();
armSkeleton->setPositions(configuration);
}
Eigen::VectorXd get_arm_positions(ada::Ada* self)
{
return self->getArm()->getCurrentConfiguration();
}
aikido::constraint::TestablePtr get_world_collision_constraint(
ada::Ada* self, const std::vector<std::string> bodyNames)
{
return self->getArm()->getWorldCollisionConstraint(bodyNames);
}
aikido::trajectory::TrajectoryPtr compute_joint_space_path(
ada::Ada* self,
const std::vector<std::pair<double, Eigen::VectorXd>>& waypoints)
{
return self->computeArmJointSpacePath(waypoints);
}
aikido::trajectory::TrajectoryPtr compute_smooth_joint_space_path(
ada::Ada* self,
const std::vector<std::pair<double, Eigen::VectorXd>>& waypoints,
const aikido::constraint::dart::CollisionFreePtr& collisionFreeConstraint
= nullptr)
{
auto vLimits = self->getVelocityLimits(true);
auto aLimits = self->getAccelerationLimits(true);
ParabolicSmoother postprocessor(vLimits, aLimits, ada::SmoothParams());
auto traj = self->computeArmJointSpacePath(waypoints);
if (traj)
{
// Cast to interpolated or spline:
auto interpolated
= dynamic_cast<const aikido::trajectory::Interpolated*>(traj.get());
if (interpolated)
{
return postprocessor.postprocess(
*interpolated, *(self->cloneRNG().get()), collisionFreeConstraint);
}
auto spline = dynamic_cast<const aikido::trajectory::Spline*>(traj.get());
if (spline)
{
return postprocessor.postprocess(
*spline, *(self->cloneRNG().get()), collisionFreeConstraint);
}
// Else return null
}
return traj;
}
aikido::trajectory::TrajectoryPtr compute_retime_path(
ada::Ada* self, aikido::trajectory::InterpolatedPtr trajectory_ptr)
{
auto vLimits = self->getVelocityLimits(true);
auto aLimits = self->getAccelerationLimits(true);
KunzRetimer postprocessor(vLimits, aLimits, ada::KunzParams());
return postprocessor.postprocess(
*(trajectory_ptr),
*(self->cloneRNG().get()),
self->getSelfCollisionConstraint());
}
aikido::trajectory::TrajectoryPtr plan_to_configuration(
ada::Ada* self, const Eigen::VectorXd& configuration)
{
auto trajectory = self->getArm()->planToConfiguration(configuration);
return trajectory;
}
void execute_trajectory(
ada::Ada* self, const aikido::trajectory::TrajectoryPtr& trajectory)
{
auto future = self->getArm()->executeTrajectory(trajectory);
if (!future.valid())
{
std::__throw_future_error(0);
}
future.wait();
// Throw any exceptions
future.get();
}
std::shared_ptr<aikido::rviz::InteractiveMarkerViewer> start_viewer(
ada::Ada* self,
const std::string& topicName,
const std::string& baseFrameName)
{
auto viewer = std::make_shared<aikido::rviz::InteractiveMarkerViewer>(
topicName, baseFrameName, self->getWorld());
viewer->setAutoUpdate(true);
return viewer;
}
//==============================================================================
// NOTE: These functions define the Python API for AdaHand.
dart::dynamics::MetaSkeletonPtr hand_get_skeleton(ada::Ada::AdaHand* self)
{
return self->getMetaSkeleton();
}
aikido::statespace::dart::MetaSkeletonStateSpacePtr hand_get_state_space(
ada::Ada::AdaHand* self)
{
auto handSkeleton = self->getMetaSkeleton();
auto handSpace
= std::make_shared<aikido::statespace::dart::MetaSkeletonStateSpace>(
handSkeleton.get());
return handSpace;
}
void execute_preshape(ada::Ada::AdaHand* self, const Eigen::VectorXd& d)
{
auto future = self->executePreshape(d);
if (!future.valid())
{
std::__throw_future_error(0);
}
future.wait();
// Throw any exceptions
future.get();
}
void hand_open(ada::Ada::AdaHand* self)
{
auto future = self->executePreshape("open");
if (!future.valid())
{
std::__throw_future_error(0);
}
future.wait();
// Throw any exceptions
future.get();
}
void hand_close(ada::Ada::AdaHand* self)
{
auto future = self->executePreshape("closed");
if (!future.valid())
{
std::__throw_future_error(0);
}
future.wait();
// Throw any exceptions
future.get();
}
dart::dynamics::BodyNode* get_end_effector_body_node(ada::Ada::AdaHand* self)
{
return self->getEndEffectorBodyNode();
}
void grab(ada::Ada::AdaHand* self, dart::dynamics::SkeletonPtr object)
{
self->grab(object);
}
void ungrab(ada::Ada::AdaHand* self)
{
self->ungrab();
}
//====================================LIBADA====================================
void Ada(pybind11::module& m)
{
py::class_<ada::Ada, std::shared_ptr<ada::Ada>>(m, "Ada")
.def(py::init([](bool simulation) -> std::shared_ptr<ada::Ada> {
return std::make_shared<ada::Ada>(simulation);
}))
.def("get_self_collision_constraint", get_self_collision_constraint)
.def("start_trajectory_controllers", start_trajectory_controllers)
.def("stop_trajectory_controllers", stop_trajectory_controllers)
.def("get_name", get_name)
.def("get_world", get_world)
.def("get_hand", get_hand)
.def("get_skeleton", get_skeleton)
.def("get_arm_skeleton", get_arm_skeleton)
.def("get_arm_state_space", get_arm_state_space)
.def("set_arm_positions", set_arm_positions)
.def("get_arm_positions", get_arm_positions)
.def(
"get_world_collision_constraint",
get_world_collision_constraint,
"Get collision constraint with requested bodies in world (or all "
"bodies if left blank)",
py::arg("bodyNames") = std::vector<std::string>())
.def("compute_joint_space_path", compute_joint_space_path)
.def("compute_smooth_joint_space_path", compute_smooth_joint_space_path)
.def("compute_retime_path", compute_retime_path)
.def("plan_to_configuration", plan_to_configuration)
.def("execute_trajectory", execute_trajectory)
.def("start_viewer", start_viewer);
py::class_<ada::Ada::AdaHand, std::shared_ptr<ada::Ada::AdaHand>>(
m, "AdaHand")
.def("get_skeleton", hand_get_skeleton)
.def("get_state_space", hand_get_state_space)
.def("execute_preshape", execute_preshape)
.def("open", hand_open)
.def("close", hand_close)
.def("get_end_effector_body_node", get_end_effector_body_node)
.def("grab", grab)
.def("ungrab", ungrab);
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fuchsia/hardware/hidbus/c/banjo.h>
#include <lib/ddk/platform-defs.h>
#include <lib/fit/defer.h>
#include <hid/boot.h>
#include <virtio/input.h>
#include <zxtest/zxtest.h>
#include "input_kbd.h"
#include "input_mouse.h"
#include "input_touch.h"
#include "src/ui/input/lib/hid-input-report/keyboard.h"
#include "src/ui/input/lib/hid-input-report/mouse.h"
namespace virtio {
namespace {
void SendTouchEvent(HidTouch& touch, uint16_t type, uint16_t code, uint32_t value) {
virtio_input_event_t event = {};
event.type = type;
event.code = code;
event.value = value;
touch.ReceiveEvent(&event);
}
} // namespace
class VirtioInputTest : public zxtest::Test {};
TEST_F(VirtioInputTest, MultiTouchReportDescriptor) {
virtio_input_absinfo_t x_info = {};
virtio_input_absinfo_t y_info = {};
HidTouch touch(x_info, y_info);
// Assert that the report descriptor is correct.
// In this case correct means a copy of the paradise touch report descriptor.
uint8_t desc[HID_MAX_DESC_LEN];
size_t desc_len;
zx_status_t status =
touch.GetDescriptor(HID_DESCRIPTION_TYPE_REPORT, desc, sizeof(desc), &desc_len);
ASSERT_OK(status);
size_t paradise_size;
const uint8_t* paradise_desc = get_paradise_touch_report_desc(¶dise_size);
ASSERT_EQ(paradise_size, desc_len);
ASSERT_EQ(0, memcmp(paradise_desc, desc, desc_len));
}
TEST_F(VirtioInputTest, MultiTouchFingerEvents) {
int VAL_MAX = 100;
int X_VAL = 50;
int Y_VAL = 100;
virtio_input_absinfo_t x_info = {};
x_info.min = 0;
x_info.max = static_cast<uint16_t>(VAL_MAX);
virtio_input_absinfo_t y_info = {};
y_info.min = 0;
y_info.max = static_cast<uint16_t>(VAL_MAX);
HidTouch touch(x_info, y_info);
// Assert that a single finger works.
SendTouchEvent(touch, VIRTIO_INPUT_EV_ABS, VIRTIO_INPUT_EV_MT_SLOT, 0);
SendTouchEvent(touch, VIRTIO_INPUT_EV_ABS, VIRTIO_INPUT_EV_MT_TRACKING_ID, 1);
SendTouchEvent(touch, VIRTIO_INPUT_EV_ABS, VIRTIO_INPUT_EV_MT_POSITION_X,
static_cast<uint16_t>(X_VAL));
SendTouchEvent(touch, VIRTIO_INPUT_EV_ABS, VIRTIO_INPUT_EV_MT_POSITION_Y,
static_cast<uint16_t>(Y_VAL));
size_t paradise_size;
const void* report = touch.GetReport(¶dise_size);
const paradise_touch_t* paradise_touch = reinterpret_cast<const paradise_touch_t*>(report);
ASSERT_EQ(sizeof(paradise_touch_t), paradise_size);
ASSERT_EQ(1, paradise_touch->contact_count);
ASSERT_EQ(PARADISE_FINGER_FLAGS_TSWITCH_MASK,
paradise_touch->fingers[0].flags & PARADISE_FINGER_FLAGS_TSWITCH_MASK);
ASSERT_EQ(X_VAL * PARADISE_X_MAX / VAL_MAX, paradise_touch->fingers[0].x);
ASSERT_EQ(Y_VAL * PARADISE_Y_MAX / VAL_MAX, paradise_touch->fingers[0].y);
ASSERT_EQ(0, paradise_touch->fingers[1].flags);
ASSERT_EQ(0, paradise_touch->fingers[2].flags);
ASSERT_EQ(0, paradise_touch->fingers[3].flags);
ASSERT_EQ(0, paradise_touch->fingers[4].flags);
// Assert that a second finger tracks.
SendTouchEvent(touch, VIRTIO_INPUT_EV_ABS, VIRTIO_INPUT_EV_MT_SLOT, 1);
SendTouchEvent(touch, VIRTIO_INPUT_EV_ABS, VIRTIO_INPUT_EV_MT_TRACKING_ID, 2);
report = touch.GetReport(¶dise_size);
paradise_touch = reinterpret_cast<const paradise_touch_t*>(report);
ASSERT_EQ(sizeof(paradise_touch_t), paradise_size);
ASSERT_EQ(2, paradise_touch->contact_count);
ASSERT_EQ(PARADISE_FINGER_FLAGS_TSWITCH_MASK,
paradise_touch->fingers[0].flags & PARADISE_FINGER_FLAGS_TSWITCH_MASK);
ASSERT_EQ(PARADISE_FINGER_FLAGS_TSWITCH_MASK,
paradise_touch->fingers[1].flags & PARADISE_FINGER_FLAGS_TSWITCH_MASK);
ASSERT_EQ(0, paradise_touch->fingers[2].flags);
ASSERT_EQ(0, paradise_touch->fingers[3].flags);
ASSERT_EQ(0, paradise_touch->fingers[4].flags);
// Pick up the second finger.
// We don't send another SLOT event because we will rely on the slot already
// being 1.
SendTouchEvent(touch, VIRTIO_INPUT_EV_ABS, VIRTIO_INPUT_EV_MT_TRACKING_ID, -1);
report = touch.GetReport(¶dise_size);
paradise_touch = reinterpret_cast<const paradise_touch_t*>(report);
ASSERT_EQ(sizeof(paradise_touch_t), paradise_size);
ASSERT_EQ(1, paradise_touch->contact_count);
ASSERT_EQ(PARADISE_FINGER_FLAGS_TSWITCH_MASK,
paradise_touch->fingers[0].flags & PARADISE_FINGER_FLAGS_TSWITCH_MASK);
ASSERT_EQ(0, paradise_touch->fingers[1].flags);
ASSERT_EQ(0, paradise_touch->fingers[2].flags);
ASSERT_EQ(0, paradise_touch->fingers[3].flags);
ASSERT_EQ(0, paradise_touch->fingers[4].flags);
}
TEST_F(VirtioInputTest, MouseTest) {
// Get the HID descriptor.
HidMouse hid_mouse;
uint8_t report_descriptor[2048] = {};
size_t report_descriptor_size = 0;
ASSERT_OK(hid_mouse.GetDescriptor(HID_DESCRIPTION_TYPE_REPORT, report_descriptor,
sizeof(report_descriptor), &report_descriptor_size));
// Parse the HID descriptor.
hid::DeviceDescriptor* dev_desc = nullptr;
auto parse_res = hid::ParseReportDescriptor(report_descriptor, report_descriptor_size, &dev_desc);
ASSERT_EQ(parse_res, hid::ParseResult::kParseOk);
ASSERT_EQ(1, dev_desc->rep_count);
auto free_descriptor = fit::defer([dev_desc]() { hid::FreeDeviceDescriptor(dev_desc); });
hid_input_report::Mouse mouse;
ASSERT_EQ(hid_input_report::ParseResult::kOk, mouse.ParseReportDescriptor(dev_desc->report[0]));
// Send the Virtio mouse keys.
virtio_input_event_t event = {};
event.type = VIRTIO_INPUT_EV_KEY;
event.value = VIRTIO_INPUT_EV_KEY_PRESSED;
event.code = 0x110; // BTN_LEFT.
hid_mouse.ReceiveEvent(&event);
// Parse the HID report.
size_t report_size;
const uint8_t* report = hid_mouse.GetReport(&report_size);
{
fidl::Arena<2048> report_allocator;
fuchsia_input_report::wire::InputReport input_report(report_allocator);
EXPECT_EQ(hid_input_report::ParseResult::kOk,
mouse.ParseInputReport(report, report_size, report_allocator, input_report));
ASSERT_EQ(input_report.mouse().pressed_buttons().count(), 1U);
EXPECT_EQ(input_report.mouse().pressed_buttons()[0], 1U);
}
// ------------------------------------------------------------------
// Send another Virtio mouse key event.
event.type = VIRTIO_INPUT_EV_KEY;
event.value = VIRTIO_INPUT_EV_KEY_PRESSED;
event.code = 0x111; // BTN_RIGHT.
hid_mouse.ReceiveEvent(&event);
// Parse the HID report.
report = hid_mouse.GetReport(&report_size);
{
fidl::Arena<2048> report_allocator;
fuchsia_input_report::wire::InputReport input_report(report_allocator);
EXPECT_EQ(hid_input_report::ParseResult::kOk,
mouse.ParseInputReport(report, report_size, report_allocator, input_report));
ASSERT_EQ(input_report.mouse().pressed_buttons().count(), 2U);
EXPECT_EQ(input_report.mouse().pressed_buttons()[0], 1U);
EXPECT_EQ(input_report.mouse().pressed_buttons()[1], 2U);
}
// ------------------------------------------------------------------
// Release one Virtio mouse key.
event.type = VIRTIO_INPUT_EV_KEY;
event.value = VIRTIO_INPUT_EV_KEY_RELEASED;
event.code = 0x110; // BTN_LEFT.
hid_mouse.ReceiveEvent(&event);
// Parse the HID report.
report = hid_mouse.GetReport(&report_size);
{
fidl::Arena<2048> report_allocator;
fuchsia_input_report::wire::InputReport input_report(report_allocator);
EXPECT_EQ(hid_input_report::ParseResult::kOk,
mouse.ParseInputReport(report, report_size, report_allocator, input_report));
ASSERT_EQ(input_report.mouse().pressed_buttons().count(), 1U);
EXPECT_EQ(input_report.mouse().pressed_buttons()[0], 2U);
}
// ------------------------------------------------------------------
// Send another Virtio mouse key event.
event.type = VIRTIO_INPUT_EV_KEY;
event.value = VIRTIO_INPUT_EV_KEY_PRESSED;
event.code = 0x112; // BTN_MID.
hid_mouse.ReceiveEvent(&event);
// Parse the HID report.
report = hid_mouse.GetReport(&report_size);
{
fidl::Arena<2048> report_allocator;
fuchsia_input_report::wire::InputReport input_report(report_allocator);
EXPECT_EQ(hid_input_report::ParseResult::kOk,
mouse.ParseInputReport(report, report_size, report_allocator, input_report));
ASSERT_EQ(input_report.mouse().pressed_buttons().count(), 2U);
EXPECT_EQ(input_report.mouse().pressed_buttons()[0], 2U);
EXPECT_EQ(input_report.mouse().pressed_buttons()[1], 3U);
}
// ------------------------------------------------------------------
// Send a Virtio mouse rel event on X axis.
event.type = VIRTIO_INPUT_EV_REL;
event.code = VIRTIO_INPUT_EV_REL_X;
event.value = 0x0abc;
hid_mouse.ReceiveEvent(&event);
// Parse the HID report.
report = hid_mouse.GetReport(&report_size);
{
fidl::Arena<2048> report_allocator;
fuchsia_input_report::wire::InputReport input_report(report_allocator);
EXPECT_EQ(hid_input_report::ParseResult::kOk,
mouse.ParseInputReport(report, report_size, report_allocator, input_report));
ASSERT_TRUE(input_report.mouse().has_movement_x());
EXPECT_EQ(input_report.mouse().movement_x(), 0x0abc);
}
// ------------------------------------------------------------------
// Send a Virtio mouse rel event on Y axis.
event.type = VIRTIO_INPUT_EV_REL;
event.code = VIRTIO_INPUT_EV_REL_Y;
event.value = 0x0123;
hid_mouse.ReceiveEvent(&event);
// Parse the HID report.
report = hid_mouse.GetReport(&report_size);
{
fidl::Arena<2048> report_allocator;
fuchsia_input_report::wire::InputReport input_report(report_allocator);
EXPECT_EQ(hid_input_report::ParseResult::kOk,
mouse.ParseInputReport(report, report_size, report_allocator, input_report));
ASSERT_TRUE(input_report.mouse().has_movement_y());
EXPECT_EQ(input_report.mouse().movement_y(), 0x0123);
}
// ------------------------------------------------------------------
// Send a Virtio mouse rel event on wheel.
event.type = VIRTIO_INPUT_EV_REL;
event.code = VIRTIO_INPUT_EV_REL_WHEEL;
event.value = 0x0345;
hid_mouse.ReceiveEvent(&event);
// Parse the HID report.
report = hid_mouse.GetReport(&report_size);
{
fidl::Arena<2048> report_allocator;
fuchsia_input_report::wire::InputReport input_report(report_allocator);
EXPECT_EQ(hid_input_report::ParseResult::kOk,
mouse.ParseInputReport(report, report_size, report_allocator, input_report));
ASSERT_TRUE(input_report.mouse().has_scroll_v());
EXPECT_EQ(input_report.mouse().scroll_v(), 0x0345);
}
}
TEST_F(VirtioInputTest, KeyboardTest) {
// Get the HID descriptor.
HidKeyboard hid_keyboard;
uint8_t report_descriptor[2048] = {};
size_t report_descriptor_size = 0;
ASSERT_OK(hid_keyboard.GetDescriptor(HID_DESCRIPTION_TYPE_REPORT, report_descriptor,
sizeof(report_descriptor), &report_descriptor_size));
// Parse the HID descriptor.
hid::DeviceDescriptor* dev_desc = nullptr;
auto parse_res = hid::ParseReportDescriptor(report_descriptor, report_descriptor_size, &dev_desc);
ASSERT_EQ(parse_res, hid::ParseResult::kParseOk);
ASSERT_EQ(1, dev_desc->rep_count);
auto free_descriptor = fit::defer([dev_desc]() { hid::FreeDeviceDescriptor(dev_desc); });
hid_input_report::Keyboard keyboard;
ASSERT_EQ(hid_input_report::ParseResult::kOk,
keyboard.ParseReportDescriptor(dev_desc->report[0]));
// Send the Virtio keys.
virtio_input_event_t event = {};
event.type = VIRTIO_INPUT_EV_KEY;
event.value = VIRTIO_INPUT_EV_KEY_PRESSED;
event.code = 42; // LEFTSHIFT.
hid_keyboard.ReceiveEvent(&event);
event.code = 30; // KEY_A
hid_keyboard.ReceiveEvent(&event);
event.code = 100; // KEY_RIGHTALT
hid_keyboard.ReceiveEvent(&event);
event.code = 108; // KEY_DOWN
hid_keyboard.ReceiveEvent(&event);
// Parse the HID report.
size_t report_size;
const uint8_t* report = hid_keyboard.GetReport(&report_size);
{
fidl::Arena<2048> report_allocator;
fuchsia_input_report::wire::InputReport input_report(report_allocator);
EXPECT_EQ(hid_input_report::ParseResult::kOk,
keyboard.ParseInputReport(report, report_size, report_allocator, input_report));
ASSERT_EQ(input_report.keyboard().pressed_keys3().count(), 4U);
EXPECT_EQ(input_report.keyboard().pressed_keys3()[0], fuchsia_input::wire::Key::kLeftShift);
EXPECT_EQ(input_report.keyboard().pressed_keys3()[1], fuchsia_input::wire::Key::kA);
EXPECT_EQ(input_report.keyboard().pressed_keys3()[2], fuchsia_input::wire::Key::kRightAlt);
EXPECT_EQ(input_report.keyboard().pressed_keys3()[3], fuchsia_input::wire::Key::kDown);
}
}
} // namespace virtio
|
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/metrics/clean_exit_beacon.h"
#include <memory>
#include <string>
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_refptr.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/test/gtest_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/metrics/metrics_pref_names.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service_factory.h"
#include "components/prefs/testing_pref_service.h"
#include "components/prefs/testing_pref_store.h"
#include "components/variations/pref_names.h"
#include "components/variations/service/variations_safe_mode_constants.h"
#include "components/variations/variations_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace metrics {
namespace {
using ::variations::SetUpExtendedSafeModeExperiment;
const wchar_t kDummyWindowsRegistryKey[] = L"";
// Creates and returns well-formed beacon file contents with the given values.
std::string CreateWellFormedBeaconFileContents(bool exited_cleanly,
int crash_streak) {
const std::string exited_cleanly_str = exited_cleanly ? "true" : "false";
return base::StringPrintf(
"{\n"
" \"user_experience_metrics.stability.exited_cleanly\": %s,\n"
" \"variations_crash_streak\": %s\n"
"}",
exited_cleanly_str.data(), base::NumberToString(crash_streak).data());
}
} // namespace
class TestCleanExitBeacon : public CleanExitBeacon {
public:
explicit TestCleanExitBeacon(
PrefService* local_state,
const base::FilePath& user_data_dir = base::FilePath())
: CleanExitBeacon(kDummyWindowsRegistryKey,
user_data_dir,
local_state,
version_info::Channel::UNKNOWN) {
Initialize();
}
~TestCleanExitBeacon() override = default;
};
class CleanExitBeaconTest : public ::testing::Test {
public:
void SetUp() override {
metrics::CleanExitBeacon::RegisterPrefs(prefs_.registry());
ASSERT_TRUE(user_data_dir_.CreateUniqueTempDir());
}
protected:
base::HistogramTester histogram_tester_;
TestingPrefServiceSimple prefs_;
base::ScopedTempDir user_data_dir_;
private:
base::test::TaskEnvironment task_environment_;
};
class BeaconFileTest : public testing::WithParamInterface<std::string>,
public CleanExitBeaconTest {};
struct BadBeaconTestParams {
const std::string test_name;
bool beacon_file_exists;
const std::string beacon_file_contents;
BeaconFileState beacon_file_state;
};
// Used for testing beacon files that are not well-formed, do not exist, etc.
class BadBeaconFileTest
: public testing::WithParamInterface<BadBeaconTestParams>,
public CleanExitBeaconTest {};
struct BeaconConsistencyTestParams {
// Inputs:
const std::string test_name;
absl::optional<bool> beacon_file_beacon_value;
absl::optional<bool> platform_specific_beacon_value;
absl::optional<bool> local_state_beacon_value;
// Result:
CleanExitBeaconConsistency expected_consistency;
};
// Used for testing the logic that emits CleanExitBeaconConsistency to
// histograms.
#if defined(OS_IOS)
class BackupBeaconConsistencyTest
: public testing::WithParamInterface<BeaconConsistencyTestParams>,
public CleanExitBeaconTest {};
#endif // defined(OS_IOS)
class BeaconFileConsistencyTest
: public testing::WithParamInterface<BeaconConsistencyTestParams>,
public CleanExitBeaconTest {};
// Verify that the crash streak metric is 0 when default pref values are used.
TEST_F(CleanExitBeaconTest, CrashStreakMetricWithDefaultPrefs) {
CleanExitBeacon::ResetStabilityExitedCleanlyForTesting(&prefs_);
TestCleanExitBeacon clean_exit_beacon(&prefs_);
histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes", 0,
1);
}
// Verify that the crash streak metric is 0 when prefs are explicitly set to
// their defaults.
TEST_F(CleanExitBeaconTest, CrashStreakMetricWithNoCrashes) {
// The default value for kStabilityExitedCleanly is true, but defaults can
// change, so we explicitly set it to true here. Similarly, we explicitly set
// kVariationsCrashStreak to 0.
CleanExitBeacon::SetStabilityExitedCleanlyForTesting(&prefs_, true);
prefs_.SetInteger(variations::prefs::kVariationsCrashStreak, 0);
TestCleanExitBeacon clean_exit_beacon(&prefs_);
histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes", 0,
1);
}
// Verify that the crash streak metric is correctly recorded when there is a
// non-zero crash streak.
TEST_F(CleanExitBeaconTest, CrashStreakMetricWithSomeCrashes) {
// The default value for kStabilityExitedCleanly is true, but defaults can
// change, so we explicitly set it to true here.
CleanExitBeacon::SetStabilityExitedCleanlyForTesting(&prefs_, true);
prefs_.SetInteger(variations::prefs::kVariationsCrashStreak, 1);
TestCleanExitBeacon clean_exit_beacon(&prefs_);
histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes", 1,
1);
}
// Verify that the crash streak is correctly incremented and recorded when the
// last Chrome session did not exit cleanly.
TEST_F(CleanExitBeaconTest, CrashIncrementsCrashStreak) {
CleanExitBeacon::SetStabilityExitedCleanlyForTesting(&prefs_, false);
prefs_.SetInteger(variations::prefs::kVariationsCrashStreak, 1);
TestCleanExitBeacon clean_exit_beacon(&prefs_);
EXPECT_EQ(prefs_.GetInteger(variations::prefs::kVariationsCrashStreak), 2);
histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes", 2,
1);
}
// Verify that the crash streak is correctly incremented and recorded when the
// last Chrome session did not exit cleanly and the default crash streak value
// is used.
TEST_F(CleanExitBeaconTest,
CrashIncrementsCrashStreakWithDefaultCrashStreakPref) {
CleanExitBeacon::SetStabilityExitedCleanlyForTesting(&prefs_, false);
TestCleanExitBeacon clean_exit_beacon(&prefs_);
EXPECT_EQ(prefs_.GetInteger(variations::prefs::kVariationsCrashStreak), 1);
histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes", 1,
1);
}
// Verify that (a) the client is excluded from the Extended Variations Safe Mode
// experiment and (b) no attempt is made to read the beacon file when no user
// data dir is provided.
TEST_F(CleanExitBeaconTest, InitWithoutUserDataDir) {
TestCleanExitBeacon beacon(&prefs_, base::FilePath());
EXPECT_FALSE(
base::FieldTrialList::IsTrialActive(variations::kExtendedSafeModeTrial));
histogram_tester_.ExpectTotalCount(
"Variations.ExtendedSafeMode.BeaconFileStateAtStartup", 0);
}
// Verify that the beacon file is not read when the client is not in the
// SignalAndWriteViaFileUtil experiment group. It is possible for a client to
// have the file and to not be in the SignalAndWriteViaFileUtil group when the
// client was in the group in a previous session and then switched groups, e.g.
// via kResetVariationState.
TEST_F(CleanExitBeaconTest, FileIgnoredByControlGroup) {
// Deliberately set the prefs so that we can later verify that their values
// have not changed.
int expected_crash_streak = 0;
prefs_.SetInteger(variations::prefs::kVariationsCrashStreak,
expected_crash_streak);
CleanExitBeacon::SetStabilityExitedCleanlyForTesting(&prefs_, true);
// Prepare a well-formed beacon file, which we expect to be ignored. (If it
// were used, then the prefs' values would change.)
const base::FilePath user_data_dir_path = user_data_dir_.GetPath();
const base::FilePath temp_beacon_file_path =
user_data_dir_path.Append(variations::kVariationsFilename);
ASSERT_LT(0, base::WriteFile(temp_beacon_file_path,
CreateWellFormedBeaconFileContents(
/*exited_cleanly=*/false, /*crash_streak=*/2)
.data()));
const std::string group_name = variations::kControlGroup;
SetUpExtendedSafeModeExperiment(group_name);
ASSERT_EQ(group_name, base::FieldTrialList::FindFullName(
variations::kExtendedSafeModeTrial));
TestCleanExitBeacon beacon(&prefs_, user_data_dir_path);
EXPECT_TRUE(prefs_.GetBoolean(prefs::kStabilityExitedCleanly));
EXPECT_EQ(prefs_.GetInteger(variations::prefs::kVariationsCrashStreak),
expected_crash_streak);
histogram_tester_.ExpectTotalCount(
"Variations.ExtendedSafeMode.BeaconFileStateAtStartup", 0);
}
INSTANTIATE_TEST_SUITE_P(
All,
BadBeaconFileTest,
::testing::Values(
BadBeaconTestParams{
.test_name = "NoVariationsFile",
.beacon_file_exists = false,
.beacon_file_contents = "",
.beacon_file_state = BeaconFileState::kNotDeserializable},
BadBeaconTestParams{
.test_name = "EmptyVariationsFile",
.beacon_file_exists = true,
.beacon_file_contents = "",
.beacon_file_state = BeaconFileState::kNotDeserializable},
BadBeaconTestParams{
.test_name = "NotDictionary",
.beacon_file_exists = true,
.beacon_file_contents = "{abc123",
.beacon_file_state = BeaconFileState::kNotDeserializable},
BadBeaconTestParams{
.test_name = "EmptyDictionary",
.beacon_file_exists = true,
.beacon_file_contents = "{}",
.beacon_file_state = BeaconFileState::kMissingDictionary},
BadBeaconTestParams{
.test_name = "MissingCrashStreak",
.beacon_file_exists = true,
.beacon_file_contents =
"{\"user_experience_metrics.stability.exited_cleanly\": true}",
.beacon_file_state = BeaconFileState::kMissingCrashStreak},
BadBeaconTestParams{
.test_name = "MissingBeacon",
.beacon_file_exists = true,
.beacon_file_contents = "{\"variations_crash_streak\": 1}",
.beacon_file_state = BeaconFileState::kMissingBeacon}),
[](const ::testing::TestParamInfo<BadBeaconTestParams>& params) {
return params.param.test_name;
});
// Verify that the inability to get the beacon file's contents for a plethora of
// reasons (a) doesn't crash and (b) correctly records the BeaconFileState
// metric.
TEST_P(BadBeaconFileTest, InitWithUnusableBeaconFile) {
SetUpExtendedSafeModeExperiment(variations::kSignalAndWriteViaFileUtilGroup);
BadBeaconTestParams params = GetParam();
const base::FilePath user_data_dir_path = user_data_dir_.GetPath();
if (params.beacon_file_exists) {
const base::FilePath temp_beacon_file_path =
user_data_dir_path.Append(variations::kVariationsFilename);
ASSERT_LT(0, base::WriteFile(temp_beacon_file_path,
params.beacon_file_contents.data()));
}
TestCleanExitBeacon beacon(&prefs_, user_data_dir_path);
histogram_tester_.ExpectUniqueSample(
"Variations.ExtendedSafeMode.BeaconFileStateAtStartup",
params.beacon_file_state, 1);
}
// TODO(crbug/1248239): Enable these tests on Android when the Extended
// Variations Safe Mode experiment is fully enabled on Android Chrome.
#if !defined(OS_ANDROID)
// Verify that successfully reading the beacon file's contents results in
// correctly (a) setting the |did_previous_session_exit_cleanly_| field and (b)
// recording metrics when the last session exited cleanly.
TEST_F(CleanExitBeaconTest, InitWithBeaconFile) {
SetUpExtendedSafeModeExperiment(variations::kSignalAndWriteViaFileUtilGroup);
const base::FilePath user_data_dir_path = user_data_dir_.GetPath();
const base::FilePath temp_beacon_file_path =
user_data_dir_path.Append(variations::kVariationsFilename);
const int num_crashes = 2;
ASSERT_LT(0, base::WriteFile(
temp_beacon_file_path,
CreateWellFormedBeaconFileContents(
/*exited_cleanly=*/true, /*crash_streak=*/num_crashes)
.data()));
TestCleanExitBeacon clean_exit_beacon(&prefs_, user_data_dir_path);
histogram_tester_.ExpectUniqueSample(
"Variations.ExtendedSafeMode.BeaconFileStateAtStartup",
BeaconFileState::kReadable, 1);
EXPECT_TRUE(clean_exit_beacon.exited_cleanly());
histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes",
num_crashes, 1);
}
// Verify that successfully reading the beacon file's contents results in
// correctly (a) setting the |did_previous_session_exit_cleanly_| field and (b)
// recording metrics when the last session did not exit cleanly.
TEST_F(CleanExitBeaconTest, InitWithCrashAndBeaconFile) {
SetUpExtendedSafeModeExperiment(variations::kSignalAndWriteViaFileUtilGroup);
const base::FilePath user_data_dir_path = user_data_dir_.GetPath();
const base::FilePath temp_beacon_file_path =
user_data_dir_path.Append(variations::kVariationsFilename);
const int last_session_num_crashes = 2;
ASSERT_LT(0, base::WriteFile(temp_beacon_file_path,
CreateWellFormedBeaconFileContents(
/*exited_cleanly=*/false,
/*crash_streak=*/last_session_num_crashes)
.data()));
const int updated_num_crashes = last_session_num_crashes + 1;
TestCleanExitBeacon clean_exit_beacon(&prefs_, user_data_dir_path);
histogram_tester_.ExpectUniqueSample(
"Variations.ExtendedSafeMode.BeaconFileStateAtStartup",
BeaconFileState::kReadable, 1);
EXPECT_FALSE(clean_exit_beacon.exited_cleanly());
histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes",
updated_num_crashes, 1);
}
#endif // !defined(OS_ANDROID)
// The below CleanExitBeaconTest.BeaconState*ExtendedSafeMode tests verify that
// the logic for recording UMA.CleanExitBeacon.BeaconFileConsistency is correct
// for clients in the SignalAndWriteViaFileUtil group.
INSTANTIATE_TEST_SUITE_P(
All,
BeaconFileConsistencyTest,
::testing::Values(
BeaconConsistencyTestParams{
.test_name = "MissingMissing",
.expected_consistency =
CleanExitBeaconConsistency::kMissingMissing},
BeaconConsistencyTestParams{
.test_name = "MissingClean",
.local_state_beacon_value = true,
.expected_consistency = CleanExitBeaconConsistency::kMissingClean},
BeaconConsistencyTestParams{
.test_name = "MissingDirty",
.local_state_beacon_value = false,
.expected_consistency = CleanExitBeaconConsistency::kMissingDirty},
BeaconConsistencyTestParams{
.test_name = "CleanMissing",
.beacon_file_beacon_value = true,
.expected_consistency = CleanExitBeaconConsistency::kCleanMissing},
BeaconConsistencyTestParams{
.test_name = "DirtyMissing",
.beacon_file_beacon_value = false,
.expected_consistency = CleanExitBeaconConsistency::kDirtyMissing},
BeaconConsistencyTestParams{
.test_name = "CleanClean",
.beacon_file_beacon_value = true,
.local_state_beacon_value = true,
.expected_consistency = CleanExitBeaconConsistency::kCleanClean},
BeaconConsistencyTestParams{
.test_name = "CleanDirty",
.beacon_file_beacon_value = true,
.local_state_beacon_value = false,
.expected_consistency = CleanExitBeaconConsistency::kCleanDirty},
BeaconConsistencyTestParams{
.test_name = "DirtyClean",
.beacon_file_beacon_value = false,
.local_state_beacon_value = true,
.expected_consistency = CleanExitBeaconConsistency::kDirtyClean},
BeaconConsistencyTestParams{
.test_name = "DirtyDirty",
.beacon_file_beacon_value = false,
.local_state_beacon_value = false,
.expected_consistency = CleanExitBeaconConsistency::kDirtyDirty}),
[](const ::testing::TestParamInfo<BeaconConsistencyTestParams>& params) {
return params.param.test_name;
});
TEST_P(BeaconFileConsistencyTest, BeaconConsistency) {
// Verify that the beacon file is not present. Unless set below, this beacon
// is considered missing.
const base::FilePath user_data_dir_path = user_data_dir_.GetPath();
const base::FilePath temp_beacon_file_path =
user_data_dir_path.Append(variations::kVariationsFilename);
ASSERT_FALSE(base::PathExists(temp_beacon_file_path));
// Clear the Local State beacon. Unless set below, it is also considered
// missing.
prefs_.ClearPref(prefs::kStabilityExitedCleanly);
BeaconConsistencyTestParams params = GetParam();
if (params.beacon_file_beacon_value) {
ASSERT_LT(
0, base::WriteFile(
temp_beacon_file_path,
CreateWellFormedBeaconFileContents(
/*exited_cleanly=*/params.beacon_file_beacon_value.value(),
/*crash_streak=*/0)
.data()));
}
if (params.local_state_beacon_value) {
prefs_.SetBoolean(prefs::kStabilityExitedCleanly,
params.local_state_beacon_value.value());
}
TestCleanExitBeacon clean_exit_beacon(&prefs_, user_data_dir_path);
histogram_tester_.ExpectUniqueSample(
"UMA.CleanExitBeacon.BeaconFileConsistency", params.expected_consistency,
1);
}
#if defined(OS_ANDROID)
// TODO(crbug/1248239): Remove this test once the Extended Variations Safe Mode
// experiment is fully enabled on Android Chrome.
// Verify that the beacon file, if any, is ignored on Android.
TEST_F(CleanExitBeaconTest, BeaconFileIgnoredOnAndroid) {
// Set up the beacon file such that the previous session did not exit cleanly
// and the running crash streak is 2. The file (and thus these values) are
// expected to be ignored.
const base::FilePath user_data_dir_path = user_data_dir_.GetPath();
const base::FilePath temp_beacon_file_path =
user_data_dir_path.Append(variations::kVariationsFilename);
const int last_session_num_crashes = 2;
ASSERT_LT(0, base::WriteFile(temp_beacon_file_path,
CreateWellFormedBeaconFileContents(
/*exited_cleanly=*/false,
/*crash_streak=*/last_session_num_crashes)
.data()));
// Set up the PrefService such that the previous session exited cleanly and
// the running crash streak is 0. The PrefService (and thus these values) are
// expected to be used.
CleanExitBeacon::SetStabilityExitedCleanlyForTesting(&prefs_, true);
const int expected_num_crashes = 0;
prefs_.SetInteger(variations::prefs::kVariationsCrashStreak,
expected_num_crashes);
TestCleanExitBeacon clean_exit_beacon(&prefs_, user_data_dir_path);
// Verify that the Local State beacon was used (not the beacon file beacon).
EXPECT_TRUE(clean_exit_beacon.exited_cleanly());
histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes",
expected_num_crashes, 1);
}
#endif // defined(OS_ANDROID)
// Verify that attempting to write synchronously DCHECKs for clients that do not
// belong to the SignalAndWriteViaFileUtil experiment group.
TEST_F(CleanExitBeaconTest, WriteBeaconValue_SynchronousWriteDcheck) {
SetUpExtendedSafeModeExperiment(variations::kControlGroup);
ASSERT_EQ(variations::kControlGroup, base::FieldTrialList::FindFullName(
variations::kExtendedSafeModeTrial));
TestCleanExitBeacon clean_exit_beacon(&prefs_, user_data_dir_.GetPath());
EXPECT_DCHECK_DEATH(
clean_exit_beacon.WriteBeaconValue(/*exited_cleanly=*/false,
/*write_synchronously=*/true));
// Verify metrics.
histogram_tester_.ExpectTotalCount(
"Variations.ExtendedSafeMode.WritePrefsTime", 0);
histogram_tester_.ExpectTotalCount(
"Variations.ExtendedSafeMode.BeaconFileWrite", 0);
}
// The below CleanExitBeaconTest.BeaconState_* tests verify that the logic for
// recording UMA.CleanExitBeaconConsistency2 is correct.
#if defined(OS_IOS)
INSTANTIATE_TEST_SUITE_P(
All,
BackupBeaconConsistencyTest,
::testing::Values(
BeaconConsistencyTestParams{
.test_name = "MissingMissing",
.expected_consistency =
CleanExitBeaconConsistency::kMissingMissing},
BeaconConsistencyTestParams{
.test_name = "MissingClean",
.local_state_beacon_value = true,
.expected_consistency = CleanExitBeaconConsistency::kMissingClean},
BeaconConsistencyTestParams{
.test_name = "MissingDirty",
.local_state_beacon_value = false,
.expected_consistency = CleanExitBeaconConsistency::kMissingDirty},
BeaconConsistencyTestParams{
.test_name = "CleanMissing",
.platform_specific_beacon_value = true,
.expected_consistency = CleanExitBeaconConsistency::kCleanMissing},
BeaconConsistencyTestParams{
.test_name = "DirtyMissing",
.platform_specific_beacon_value = false,
.expected_consistency = CleanExitBeaconConsistency::kDirtyMissing},
BeaconConsistencyTestParams{
.test_name = "CleanClean",
.platform_specific_beacon_value = true,
.local_state_beacon_value = true,
.expected_consistency = CleanExitBeaconConsistency::kCleanClean},
BeaconConsistencyTestParams{
.test_name = "CleanDirty",
.platform_specific_beacon_value = true,
.local_state_beacon_value = false,
.expected_consistency = CleanExitBeaconConsistency::kCleanDirty},
BeaconConsistencyTestParams{
.test_name = "DirtyClean",
.platform_specific_beacon_value = false,
.local_state_beacon_value = true,
.expected_consistency = CleanExitBeaconConsistency::kDirtyClean},
BeaconConsistencyTestParams{
.test_name = "DirtyDirty",
.platform_specific_beacon_value = false,
.local_state_beacon_value = false,
.expected_consistency = CleanExitBeaconConsistency::kDirtyDirty}),
[](const ::testing::TestParamInfo<BeaconConsistencyTestParams>& params) {
return params.param.test_name;
});
TEST_P(BackupBeaconConsistencyTest, BeaconConsistency) {
// Clear the platform-specific and Local State beacons. Unless set below, the
// beacons are considered missing.
CleanExitBeacon::ResetStabilityExitedCleanlyForTesting(&prefs_);
BeaconConsistencyTestParams params = GetParam();
if (params.platform_specific_beacon_value) {
CleanExitBeacon::SetUserDefaultsBeacon(
/*exited_cleanly=*/params.platform_specific_beacon_value.value());
}
if (params.local_state_beacon_value) {
prefs_.SetBoolean(prefs::kStabilityExitedCleanly,
params.local_state_beacon_value.value());
}
TestCleanExitBeacon clean_exit_beacon(&prefs_);
histogram_tester_.ExpectUniqueSample("UMA.CleanExitBeaconConsistency2",
params.expected_consistency, 1);
}
#endif // defined(OS_IOS)
} // namespace metrics
|
; Listing generated by Microsoft (R) Optimizing Compiler Version 17.00.50727.1
include listing.inc
INCLUDELIB LIBCMT
INCLUDELIB OLDNAMES
PUBLIC ?century@@3EA ; century
PUBLIC ?year@@3EA ; year
PUBLIC ?month@@3EA ; month
PUBLIC ?day@@3EA ; day
PUBLIC ?hour@@3EA ; hour
PUBLIC ?minute@@3EA ; minute
PUBLIC ?second@@3EA ; second
_BSS SEGMENT
?century@@3EA DB 01H DUP (?) ; century
?year@@3EA DB 01H DUP (?) ; year
?month@@3EA DB 01H DUP (?) ; month
?day@@3EA DB 01H DUP (?) ; day
?hour@@3EA DB 01H DUP (?) ; hour
?minute@@3EA DB 01H DUP (?) ; minute
?second@@3EA DB 01H DUP (?) ; second
_BSS ENDS
PUBLIC ?initialize_rtc@@YAXXZ ; initialize_rtc
PUBLIC ?rtc_get_year@@YAEXZ ; rtc_get_year
PUBLIC ?rtc_get_second@@YAEXZ ; rtc_get_second
PUBLIC ?rtc_get_day@@YAEXZ ; rtc_get_day
PUBLIC ?rtc_get_hour@@YAEXZ ; rtc_get_hour
PUBLIC ?rtc_get_minutes@@YAEXZ ; rtc_get_minutes
PUBLIC ?rtc_get_century@@YAEXZ ; rtc_get_century
PUBLIC ?rtc_get_month@@YAEXZ ; rtc_get_month
PUBLIC ?get_rtc_register@@YAEH@Z ; get_rtc_register
PUBLIC ?set_rtc_register@@YAXGE@Z ; set_rtc_register
PUBLIC ?is_updating_rtc@@YAHXZ ; is_updating_rtc
PUBLIC ?rtc_read_datetime@@YAXXZ ; rtc_read_datetime
PUBLIC ?rtc_clock_update@@YAX_KPEAX@Z ; rtc_clock_update
EXTRN x64_inportb:PROC
EXTRN x64_outportb:PROC
EXTRN ?interrupt_end@@YAXI@Z:PROC ; interrupt_end
EXTRN ?interrupt_set@@YAX_KP6AX0PEAX@ZE@Z:PROC ; interrupt_set
EXTRN ?unblock_thread@@YAXPEAU_thread_@@@Z:PROC ; unblock_thread
EXTRN ?is_multi_task_enable@@YA_NXZ:PROC ; is_multi_task_enable
EXTRN ?thread_iterate_block_list@@YAPEAU_thread_@@H@Z:PROC ; thread_iterate_block_list
_BSS SEGMENT
bcd DB 01H DUP (?)
_BSS ENDS
pdata SEGMENT
$pdata$?initialize_rtc@@YAXXZ DD imagerel $LN5
DD imagerel $LN5+167
DD imagerel $unwind$?initialize_rtc@@YAXXZ
$pdata$?get_rtc_register@@YAEH@Z DD imagerel $LN3
DD imagerel $LN3+36
DD imagerel $unwind$?get_rtc_register@@YAEH@Z
$pdata$?set_rtc_register@@YAXGE@Z DD imagerel $LN3
DD imagerel $LN3+46
DD imagerel $unwind$?set_rtc_register@@YAXGE@Z
$pdata$?is_updating_rtc@@YAHXZ DD imagerel $LN3
DD imagerel $LN3+45
DD imagerel $unwind$?is_updating_rtc@@YAHXZ
$pdata$?rtc_read_datetime@@YAXXZ DD imagerel $LN6
DD imagerel $LN6+455
DD imagerel $unwind$?rtc_read_datetime@@YAXXZ
$pdata$?rtc_clock_update@@YAX_KPEAX@Z DD imagerel $LN9
DD imagerel $LN9+146
DD imagerel $unwind$?rtc_clock_update@@YAX_KPEAX@Z
pdata ENDS
xdata SEGMENT
$unwind$?initialize_rtc@@YAXXZ DD 010401H
DD 06204H
$unwind$?get_rtc_register@@YAEH@Z DD 010801H
DD 04208H
$unwind$?set_rtc_register@@YAXGE@Z DD 010d01H
DD 0420dH
$unwind$?is_updating_rtc@@YAHXZ DD 010401H
DD 06204H
$unwind$?rtc_read_datetime@@YAXXZ DD 010401H
DD 08204H
$unwind$?rtc_clock_update@@YAX_KPEAX@Z DD 010e01H
DD 0620eH
xdata ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
tv69 = 32
ready$ = 33
t$1 = 40
s$ = 64
p$ = 72
?rtc_clock_update@@YAX_KPEAX@Z PROC ; rtc_clock_update
; 84 : void rtc_clock_update(size_t s, void* p) {
$LN9:
mov QWORD PTR [rsp+16], rdx
mov QWORD PTR [rsp+8], rcx
sub rsp, 56 ; 00000038H
; 85 : bool ready = get_rtc_register(0x0C) & 0x10;
mov ecx, 12
call ?get_rtc_register@@YAEH@Z ; get_rtc_register
movzx eax, al
and eax, 16
test eax, eax
je SHORT $LN7@rtc_clock_
mov BYTE PTR tv69[rsp], 1
jmp SHORT $LN8@rtc_clock_
$LN7@rtc_clock_:
mov BYTE PTR tv69[rsp], 0
$LN8@rtc_clock_:
movzx eax, BYTE PTR tv69[rsp]
mov BYTE PTR ready$[rsp], al
; 86 : if (ready) {
movzx eax, BYTE PTR ready$[rsp]
test eax, eax
je SHORT $LN4@rtc_clock_
; 87 : rtc_read_datetime();
call ?rtc_read_datetime@@YAXXZ ; rtc_read_datetime
$LN4@rtc_clock_:
; 88 : }
; 89 :
; 90 : /*message_t msg;
; 91 : msg.type = CLOCK_MESSAGE;
; 92 : msg.dword = second;
; 93 : msg.dword2 = minute;
; 94 : msg.dword3 = hour;
; 95 : msg.dword5 = day;
; 96 : msg.dword6 = month;
; 97 : msg.dword7 = year;
; 98 : message_send (4, &msg);*/
; 99 : if (is_multi_task_enable()) {
call ?is_multi_task_enable@@YA_NXZ ; is_multi_task_enable
movzx eax, al
test eax, eax
je SHORT $LN3@rtc_clock_
; 100 : thread_t *t = thread_iterate_block_list(2);
mov ecx, 2
call ?thread_iterate_block_list@@YAPEAU_thread_@@H@Z ; thread_iterate_block_list
mov QWORD PTR t$1[rsp], rax
; 101 : if (t != NULL) {
cmp QWORD PTR t$1[rsp], 0
je SHORT $LN2@rtc_clock_
; 102 : if (t->state == THREAD_STATE_BLOCKED)
mov rax, QWORD PTR t$1[rsp]
movzx eax, BYTE PTR [rax+232]
cmp eax, 3
jne SHORT $LN1@rtc_clock_
; 103 : unblock_thread(t);
mov rcx, QWORD PTR t$1[rsp]
call ?unblock_thread@@YAXPEAU_thread_@@@Z ; unblock_thread
$LN1@rtc_clock_:
$LN2@rtc_clock_:
$LN3@rtc_clock_:
; 104 : }
; 105 : }
; 106 : //!send a EOI to apic
; 107 : interrupt_end(8);
mov ecx, 8
call ?interrupt_end@@YAXI@Z ; interrupt_end
; 108 : }
add rsp, 56 ; 00000038H
ret 0
?rtc_clock_update@@YAX_KPEAX@Z ENDP ; rtc_clock_update
_TEXT ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
registerB$ = 32
tv84 = 36
tv91 = 40
tv130 = 44
tv141 = 48
tv148 = 52
tv155 = 56
?rtc_read_datetime@@YAXXZ PROC ; rtc_read_datetime
; 58 : void rtc_read_datetime() {
$LN6:
sub rsp, 72 ; 00000048H
$LN3@rtc_read_d:
; 59 : // Wait until rtc is not updating
; 60 : while(is_updating_rtc());
call ?is_updating_rtc@@YAHXZ ; is_updating_rtc
test eax, eax
je SHORT $LN2@rtc_read_d
jmp SHORT $LN3@rtc_read_d
$LN2@rtc_read_d:
; 61 :
; 62 : second = get_rtc_register(0x00);
xor ecx, ecx
call ?get_rtc_register@@YAEH@Z ; get_rtc_register
mov BYTE PTR ?second@@3EA, al ; second
; 63 : minute = get_rtc_register(0x02);
mov ecx, 2
call ?get_rtc_register@@YAEH@Z ; get_rtc_register
mov BYTE PTR ?minute@@3EA, al ; minute
; 64 : hour = get_rtc_register(0x04);
mov ecx, 4
call ?get_rtc_register@@YAEH@Z ; get_rtc_register
mov BYTE PTR ?hour@@3EA, al ; hour
; 65 : day = get_rtc_register(0x07);
mov ecx, 7
call ?get_rtc_register@@YAEH@Z ; get_rtc_register
mov BYTE PTR ?day@@3EA, al ; day
; 66 : month = get_rtc_register(0x08);
mov ecx, 8
call ?get_rtc_register@@YAEH@Z ; get_rtc_register
mov BYTE PTR ?month@@3EA, al ; month
; 67 : year = get_rtc_register(0x09);
mov ecx, 9
call ?get_rtc_register@@YAEH@Z ; get_rtc_register
mov BYTE PTR ?year@@3EA, al ; year
; 68 :
; 69 : uint8_t registerB = get_rtc_register(0x0B);
mov ecx, 11
call ?get_rtc_register@@YAEH@Z ; get_rtc_register
mov BYTE PTR registerB$[rsp], al
; 70 :
; 71 : // Convert BCD to binary values if necessary
; 72 : if (!(registerB & 0x04)) {
movzx eax, BYTE PTR registerB$[rsp]
and eax, 4
test eax, eax
jne $LN1@rtc_read_d
; 73 : second = (second & 0x0F) + ((second / 16) * 10);
movzx eax, BYTE PTR ?second@@3EA ; second
and eax, 15
mov DWORD PTR tv84[rsp], eax
movzx ecx, BYTE PTR ?second@@3EA ; second
mov eax, ecx
cdq
and edx, 15
add eax, edx
sar eax, 4
imul eax, 10
mov ecx, DWORD PTR tv84[rsp]
add ecx, eax
mov eax, ecx
mov BYTE PTR ?second@@3EA, al ; second
; 74 : minute = (minute & 0x0F) + ((minute / 16) * 10);
movzx eax, BYTE PTR ?minute@@3EA ; minute
and eax, 15
mov DWORD PTR tv91[rsp], eax
movzx ecx, BYTE PTR ?minute@@3EA ; minute
mov eax, ecx
cdq
and edx, 15
add eax, edx
sar eax, 4
imul eax, 10
mov ecx, DWORD PTR tv91[rsp]
add ecx, eax
mov eax, ecx
mov BYTE PTR ?minute@@3EA, al ; minute
; 75 : hour = ( (hour & 0x0F) + (((hour & 0x70) / 16) * 10) ) | (hour & 0x80);
movzx eax, BYTE PTR ?hour@@3EA ; hour
and eax, 15
mov DWORD PTR tv130[rsp], eax
movzx ecx, BYTE PTR ?hour@@3EA ; hour
and ecx, 112 ; 00000070H
mov eax, ecx
cdq
and edx, 15
add eax, edx
sar eax, 4
imul eax, 10
mov ecx, DWORD PTR tv130[rsp]
add ecx, eax
mov eax, ecx
movzx ecx, BYTE PTR ?hour@@3EA ; hour
and ecx, 128 ; 00000080H
or eax, ecx
mov BYTE PTR ?hour@@3EA, al ; hour
; 76 : day = (day & 0x0F) + ((day / 16) * 10);
movzx eax, BYTE PTR ?day@@3EA ; day
and eax, 15
mov DWORD PTR tv141[rsp], eax
movzx ecx, BYTE PTR ?day@@3EA ; day
mov eax, ecx
cdq
and edx, 15
add eax, edx
sar eax, 4
imul eax, 10
mov ecx, DWORD PTR tv141[rsp]
add ecx, eax
mov eax, ecx
mov BYTE PTR ?day@@3EA, al ; day
; 77 : month = (month & 0x0F) + ((month / 16) * 10);
movzx eax, BYTE PTR ?month@@3EA ; month
and eax, 15
mov DWORD PTR tv148[rsp], eax
movzx ecx, BYTE PTR ?month@@3EA ; month
mov eax, ecx
cdq
and edx, 15
add eax, edx
sar eax, 4
imul eax, 10
mov ecx, DWORD PTR tv148[rsp]
add ecx, eax
mov eax, ecx
mov BYTE PTR ?month@@3EA, al ; month
; 78 : year = (year & 0x0F) + ((year / 16) * 10);
movzx eax, BYTE PTR ?year@@3EA ; year
and eax, 15
mov DWORD PTR tv155[rsp], eax
movzx ecx, BYTE PTR ?year@@3EA ; year
mov eax, ecx
cdq
and edx, 15
add eax, edx
sar eax, 4
imul eax, 10
mov ecx, DWORD PTR tv155[rsp]
add ecx, eax
mov eax, ecx
mov BYTE PTR ?year@@3EA, al ; year
$LN1@rtc_read_d:
; 79 : }
; 80 : }
add rsp, 72 ; 00000048H
ret 0
?rtc_read_datetime@@YAXXZ ENDP ; rtc_read_datetime
_TEXT ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
status$ = 32
?is_updating_rtc@@YAHXZ PROC ; is_updating_rtc
; 48 : int is_updating_rtc() {
$LN3:
sub rsp, 56 ; 00000038H
; 49 : x64_outportb(CMOS_ADDR, 0x0A);
mov dl, 10
mov cx, 112 ; 00000070H
call x64_outportb
; 50 : uint32_t status = x64_inportb(CMOS_DATA);
mov cx, 113 ; 00000071H
call x64_inportb
movzx eax, al
mov DWORD PTR status$[rsp], eax
; 51 : return (status & 0x80);
mov eax, DWORD PTR status$[rsp]
and eax, 128 ; 00000080H
; 52 : }
add rsp, 56 ; 00000038H
ret 0
?is_updating_rtc@@YAHXZ ENDP ; is_updating_rtc
_TEXT ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
reg_num$ = 48
val$ = 56
?set_rtc_register@@YAXGE@Z PROC ; set_rtc_register
; 39 : void set_rtc_register(uint16_t reg_num, uint8_t val) {
$LN3:
mov BYTE PTR [rsp+16], dl
mov WORD PTR [rsp+8], cx
sub rsp, 40 ; 00000028H
; 40 : x64_outportb(CMOS_ADDR, reg_num);
movzx edx, BYTE PTR reg_num$[rsp]
mov cx, 112 ; 00000070H
call x64_outportb
; 41 : x64_outportb(CMOS_DATA, val);
movzx edx, BYTE PTR val$[rsp]
mov cx, 113 ; 00000071H
call x64_outportb
; 42 : }
add rsp, 40 ; 00000028H
ret 0
?set_rtc_register@@YAXGE@Z ENDP ; set_rtc_register
_TEXT ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
reg_num$ = 48
?get_rtc_register@@YAEH@Z PROC ; get_rtc_register
; 31 : uint8_t get_rtc_register(int reg_num) {
$LN3:
mov DWORD PTR [rsp+8], ecx
sub rsp, 40 ; 00000028H
; 32 : x64_outportb(CMOS_ADDR, reg_num);
movzx edx, BYTE PTR reg_num$[rsp]
mov cx, 112 ; 00000070H
call x64_outportb
; 33 : return x64_inportb(CMOS_DATA);
mov cx, 113 ; 00000071H
call x64_inportb
; 34 : }
add rsp, 40 ; 00000028H
ret 0
?get_rtc_register@@YAEH@Z ENDP ; get_rtc_register
_TEXT ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
?rtc_get_month@@YAEXZ PROC ; rtc_get_month
; 160 : return month;
movzx eax, BYTE PTR ?month@@3EA ; month
; 161 : }
ret 0
?rtc_get_month@@YAEXZ ENDP ; rtc_get_month
_TEXT ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
?rtc_get_century@@YAEXZ PROC ; rtc_get_century
; 140 : return century;
movzx eax, BYTE PTR ?century@@3EA ; century
; 141 : }
ret 0
?rtc_get_century@@YAEXZ ENDP ; rtc_get_century
_TEXT ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
?rtc_get_minutes@@YAEXZ PROC ; rtc_get_minutes
; 144 : return minute;
movzx eax, BYTE PTR ?minute@@3EA ; minute
; 145 : }
ret 0
?rtc_get_minutes@@YAEXZ ENDP ; rtc_get_minutes
_TEXT ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
?rtc_get_hour@@YAEXZ PROC ; rtc_get_hour
; 156 : return hour;
movzx eax, BYTE PTR ?hour@@3EA ; hour
; 157 : }
ret 0
?rtc_get_hour@@YAEXZ ENDP ; rtc_get_hour
_TEXT ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
?rtc_get_day@@YAEXZ PROC ; rtc_get_day
; 152 : return day;
movzx eax, BYTE PTR ?day@@3EA ; day
; 153 : }
ret 0
?rtc_get_day@@YAEXZ ENDP ; rtc_get_day
_TEXT ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
?rtc_get_second@@YAEXZ PROC ; rtc_get_second
; 148 : return second;
movzx eax, BYTE PTR ?second@@3EA ; second
; 149 : }
ret 0
?rtc_get_second@@YAEXZ ENDP ; rtc_get_second
_TEXT ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
?rtc_get_year@@YAEXZ PROC ; rtc_get_year
; 136 : return year;
movzx eax, BYTE PTR ?year@@3EA ; year
; 137 : }
ret 0
?rtc_get_year@@YAEXZ ENDP ; rtc_get_year
_TEXT ENDS
; Function compile flags: /Odtpy
; File e:\xeneva project\xeneva\aurora\aurora\drivers\rtc.cpp
_TEXT SEGMENT
status$ = 32
tv81 = 36
?initialize_rtc@@YAXXZ PROC ; initialize_rtc
; 110 : void initialize_rtc () {
$LN5:
sub rsp, 56 ; 00000038H
; 111 :
; 112 : unsigned char status = get_rtc_register (0x0B);
mov ecx, 11
call ?get_rtc_register@@YAEH@Z ; get_rtc_register
mov BYTE PTR status$[rsp], al
; 113 : status |= 0x02;
movzx eax, BYTE PTR status$[rsp]
or eax, 2
mov BYTE PTR status$[rsp], al
; 114 : status |= 0x10;
movzx eax, BYTE PTR status$[rsp]
or eax, 16
mov BYTE PTR status$[rsp], al
; 115 : status &= ~0x20;
movzx eax, BYTE PTR status$[rsp]
and eax, -33 ; ffffffffffffffdfH
mov BYTE PTR status$[rsp], al
; 116 : status &= ~0x40;
movzx eax, BYTE PTR status$[rsp]
and eax, -65 ; ffffffffffffffbfH
mov BYTE PTR status$[rsp], al
; 117 : bcd = !(status & 0x04);
movzx eax, BYTE PTR status$[rsp]
and eax, 4
test eax, eax
jne SHORT $LN3@initialize
mov DWORD PTR tv81[rsp], 1
jmp SHORT $LN4@initialize
$LN3@initialize:
mov DWORD PTR tv81[rsp], 0
$LN4@initialize:
movzx eax, BYTE PTR tv81[rsp]
mov BYTE PTR bcd, al
; 118 :
; 119 : //! Write status to rtc
; 120 : x64_outportb (0x70, 0x0B);
mov dl, 11
mov cx, 112 ; 00000070H
call x64_outportb
; 121 : x64_outportb (0x71, status);
movzx edx, BYTE PTR status$[rsp]
mov cx, 113 ; 00000071H
call x64_outportb
; 122 :
; 123 : //! Read status from RTC
; 124 : get_rtc_register (0x0C);
mov ecx, 12
call ?get_rtc_register@@YAEH@Z ; get_rtc_register
; 125 :
; 126 : //!register interrupt
; 127 : interrupt_set (8,rtc_clock_update, 8);
mov r8b, 8
lea rdx, OFFSET FLAT:?rtc_clock_update@@YAX_KPEAX@Z ; rtc_clock_update
mov ecx, 8
call ?interrupt_set@@YAX_KP6AX0PEAX@ZE@Z ; interrupt_set
; 128 :
; 129 : #ifdef USE_PIC
; 130 : irq_mask(8,false);
; 131 : #endif
; 132 : }
add rsp, 56 ; 00000038H
ret 0
?initialize_rtc@@YAXXZ ENDP ; initialize_rtc
_TEXT ENDS
END
|
#include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
typedef long long int lli;
typedef unsigned long long ull;
typedef complex<double> point;
template<typename P, typename Q>
ostream& operator << (ostream& os, pair<P, Q> p)
{
os << "(" << p.first << "," << p.second << ")";
return os;
}
int main(int argc, char *argv[])
{
int n;
while (cin >> n) {
lli sum = 0;
lli best = 1 << 29;
for (int i = 0; i < n; ++i) {
lli a, p;
cin >> a >> p;
best = min(best, p);
sum += best * a;
}
cout << sum << endl;
}
return 0;
}
|
; A324270: a(n) = 13*7^(7*n).
; Submitted by Christian Krause
; 13,10706059,8816899947037,7261096233082692091,5979824975081619492698413,4924642999453642161875329137259,4055655269699050826917294183685688637,3340006507773765415151949203915063077180891,2750638979431530091290481703239822791770782516813,2265269477037980585971637173331233381403285546243728459
mov $1,823543
pow $1,$0
mul $1,13
mov $0,$1
|
;-- transmat0 --------------------------------------------------------------------------------------------------------------------------
; Note XX12 comes after as some logic in normal processing uses XX15 and XX12 combines
UBnkXX12xLo DB 0 ; XX12+0
UBnkXX12xSign DB 0 ; XX12+1
UBnkXX12yLo DB 0 ; XX12+2
UBnkXX12ySign DB 0 ; XX12+3
UBnkXX12zLo DB 0 ; XX12+4
UBnkXX12zSign DB 0 ; XX12+5
XX12Save DS 6
XX12Save2 DS 6
XX12 equ UBnkXX12xLo
varXX12 equ UBnkXX12xLo
; Repurposed XX12 when plotting lines
UBnkY2 equ XX12+0
UbnKy2Lo equ XX12+0
UBnkY2Hi equ XX12+1
UBnkDeltaXLo equ XX12+2
UBnkDeltaXHi equ XX12+3
UBnkDeltaYLo equ XX12+4
UBnkDeltaYHi equ XX12+5
UbnkGradient equ XX12+2
UBnkTemp1 equ XX12+2
UBnkTemp1Lo equ XX12+2
UBnkTemp1Hi equ XX12+3
UBnkTemp2 equ XX12+3
UBnkTemp2Lo equ XX12+3
UBnkTemp2Hi equ XX12+4
|
<%
from pwnlib.shellcraft.amd64.linux import syscall
%>
<%page args="n, groups"/>
<%docstring>
Invokes the syscall setgroups. See 'man 2 setgroups' for more information.
Arguments:
n(size_t): n
groups(gid_t): groups
</%docstring>
${syscall('SYS_setgroups', n, groups)}
|
_zombie: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
#include "stat.h"
#include "user.h"
int
main(void)
{
0: 8d 4c 24 04 lea 0x4(%esp),%ecx
4: 83 e4 f0 and $0xfffffff0,%esp
7: ff 71 fc pushl -0x4(%ecx)
a: 55 push %ebp
b: 89 e5 mov %esp,%ebp
d: 51 push %ecx
e: 83 ec 04 sub $0x4,%esp
if(fork() > 0)
11: e8 03 03 00 00 call 319 <fork>
16: 85 c0 test %eax,%eax
18: 7e 0d jle 27 <main+0x27>
sleep(5); // Let child exit before parent.
1a: 83 ec 0c sub $0xc,%esp
1d: 6a 05 push $0x5
1f: e8 8d 03 00 00 call 3b1 <sleep>
24: 83 c4 10 add $0x10,%esp
exit();
27: e8 f5 02 00 00 call 321 <exit>
2c: 66 90 xchg %ax,%ax
2e: 66 90 xchg %ax,%ax
00000030 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, char *t)
{
30: 55 push %ebp
char *os;
os = s;
while((*s++ = *t++) != 0)
31: 31 d2 xor %edx,%edx
{
33: 89 e5 mov %esp,%ebp
35: 53 push %ebx
36: 8b 45 08 mov 0x8(%ebp),%eax
39: 8b 5d 0c mov 0xc(%ebp),%ebx
3c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
while((*s++ = *t++) != 0)
40: 0f b6 0c 13 movzbl (%ebx,%edx,1),%ecx
44: 88 0c 10 mov %cl,(%eax,%edx,1)
47: 83 c2 01 add $0x1,%edx
4a: 84 c9 test %cl,%cl
4c: 75 f2 jne 40 <strcpy+0x10>
;
return os;
}
4e: 5b pop %ebx
4f: 5d pop %ebp
50: c3 ret
51: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
58: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
5f: 90 nop
00000060 <strcmp>:
int
strcmp(const char *p, const char *q)
{
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
68: 8b 75 0c mov 0xc(%ebp),%esi
while(*p && *p == *q)
6b: 0f b6 13 movzbl (%ebx),%edx
6e: 0f b6 0e movzbl (%esi),%ecx
71: 84 d2 test %dl,%dl
73: 74 1e je 93 <strcmp+0x33>
75: b8 01 00 00 00 mov $0x1,%eax
7a: 38 ca cmp %cl,%dl
7c: 74 09 je 87 <strcmp+0x27>
7e: eb 20 jmp a0 <strcmp+0x40>
80: 83 c0 01 add $0x1,%eax
83: 38 ca cmp %cl,%dl
85: 75 19 jne a0 <strcmp+0x40>
87: 0f b6 14 03 movzbl (%ebx,%eax,1),%edx
8b: 0f b6 0c 06 movzbl (%esi,%eax,1),%ecx
8f: 84 d2 test %dl,%dl
91: 75 ed jne 80 <strcmp+0x20>
93: 31 c0 xor %eax,%eax
p++, q++;
return (uchar)*p - (uchar)*q;
}
95: 5b pop %ebx
96: 5e pop %esi
return (uchar)*p - (uchar)*q;
97: 29 c8 sub %ecx,%eax
}
99: 5d pop %ebp
9a: c3 ret
9b: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
9f: 90 nop
a0: 0f b6 c2 movzbl %dl,%eax
a3: 5b pop %ebx
a4: 5e pop %esi
return (uchar)*p - (uchar)*q;
a5: 29 c8 sub %ecx,%eax
}
a7: 5d pop %ebp
a8: c3 ret
a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
000000b0 <strlen>:
uint
strlen(char *s)
{
b0: 55 push %ebp
b1: 89 e5 mov %esp,%ebp
b3: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
b6: 80 39 00 cmpb $0x0,(%ecx)
b9: 74 15 je d0 <strlen+0x20>
bb: 31 d2 xor %edx,%edx
bd: 8d 76 00 lea 0x0(%esi),%esi
c0: 83 c2 01 add $0x1,%edx
c3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
c7: 89 d0 mov %edx,%eax
c9: 75 f5 jne c0 <strlen+0x10>
;
return n;
}
cb: 5d pop %ebp
cc: c3 ret
cd: 8d 76 00 lea 0x0(%esi),%esi
for(n = 0; s[n]; n++)
d0: 31 c0 xor %eax,%eax
}
d2: 5d pop %ebp
d3: c3 ret
d4: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
db: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
df: 90 nop
000000e0 <memset>:
void*
memset(void *dst, int c, uint n)
{
e0: 55 push %ebp
e1: 89 e5 mov %esp,%ebp
e3: 57 push %edi
e4: 8b 55 08 mov 0x8(%ebp),%edx
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
e7: 8b 4d 10 mov 0x10(%ebp),%ecx
ea: 8b 45 0c mov 0xc(%ebp),%eax
ed: 89 d7 mov %edx,%edi
ef: fc cld
f0: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
f2: 89 d0 mov %edx,%eax
f4: 5f pop %edi
f5: 5d pop %ebp
f6: c3 ret
f7: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
fe: 66 90 xchg %ax,%ax
00000100 <strchr>:
char*
strchr(const char *s, char c)
{
100: 55 push %ebp
101: 89 e5 mov %esp,%ebp
103: 53 push %ebx
104: 8b 45 08 mov 0x8(%ebp),%eax
107: 8b 55 0c mov 0xc(%ebp),%edx
for(; *s; s++)
10a: 0f b6 18 movzbl (%eax),%ebx
10d: 84 db test %bl,%bl
10f: 74 1d je 12e <strchr+0x2e>
111: 89 d1 mov %edx,%ecx
if(*s == c)
113: 38 d3 cmp %dl,%bl
115: 75 0d jne 124 <strchr+0x24>
117: eb 17 jmp 130 <strchr+0x30>
119: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
120: 38 ca cmp %cl,%dl
122: 74 0c je 130 <strchr+0x30>
for(; *s; s++)
124: 83 c0 01 add $0x1,%eax
127: 0f b6 10 movzbl (%eax),%edx
12a: 84 d2 test %dl,%dl
12c: 75 f2 jne 120 <strchr+0x20>
return (char*)s;
return 0;
12e: 31 c0 xor %eax,%eax
}
130: 5b pop %ebx
131: 5d pop %ebp
132: c3 ret
133: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
13a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
00000140 <gets>:
char*
gets(char *buf, int max)
{
140: 55 push %ebp
141: 89 e5 mov %esp,%ebp
143: 57 push %edi
144: 56 push %esi
int i, cc;
char c;
for(i=0; i+1 < max; ){
145: 31 f6 xor %esi,%esi
{
147: 53 push %ebx
148: 89 f3 mov %esi,%ebx
14a: 83 ec 1c sub $0x1c,%esp
14d: 8b 7d 08 mov 0x8(%ebp),%edi
for(i=0; i+1 < max; ){
150: eb 2f jmp 181 <gets+0x41>
152: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
cc = read(0, &c, 1);
158: 83 ec 04 sub $0x4,%esp
15b: 8d 45 e7 lea -0x19(%ebp),%eax
15e: 6a 01 push $0x1
160: 50 push %eax
161: 6a 00 push $0x0
163: e8 d1 01 00 00 call 339 <read>
if(cc < 1)
168: 83 c4 10 add $0x10,%esp
16b: 85 c0 test %eax,%eax
16d: 7e 1c jle 18b <gets+0x4b>
break;
buf[i++] = c;
16f: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
173: 83 c7 01 add $0x1,%edi
176: 88 47 ff mov %al,-0x1(%edi)
if(c == '\n' || c == '\r')
179: 3c 0a cmp $0xa,%al
17b: 74 23 je 1a0 <gets+0x60>
17d: 3c 0d cmp $0xd,%al
17f: 74 1f je 1a0 <gets+0x60>
for(i=0; i+1 < max; ){
181: 83 c3 01 add $0x1,%ebx
184: 89 fe mov %edi,%esi
186: 3b 5d 0c cmp 0xc(%ebp),%ebx
189: 7c cd jl 158 <gets+0x18>
18b: 89 f3 mov %esi,%ebx
break;
}
buf[i] = '\0';
return buf;
}
18d: 8b 45 08 mov 0x8(%ebp),%eax
buf[i] = '\0';
190: c6 03 00 movb $0x0,(%ebx)
}
193: 8d 65 f4 lea -0xc(%ebp),%esp
196: 5b pop %ebx
197: 5e pop %esi
198: 5f pop %edi
199: 5d pop %ebp
19a: c3 ret
19b: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
19f: 90 nop
1a0: 8b 75 08 mov 0x8(%ebp),%esi
1a3: 8b 45 08 mov 0x8(%ebp),%eax
1a6: 01 de add %ebx,%esi
1a8: 89 f3 mov %esi,%ebx
buf[i] = '\0';
1aa: c6 03 00 movb $0x0,(%ebx)
}
1ad: 8d 65 f4 lea -0xc(%ebp),%esp
1b0: 5b pop %ebx
1b1: 5e pop %esi
1b2: 5f pop %edi
1b3: 5d pop %ebp
1b4: c3 ret
1b5: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
1bc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
000001c0 <stat>:
int
stat(char *n, struct stat *st)
{
1c0: 55 push %ebp
1c1: 89 e5 mov %esp,%ebp
1c3: 56 push %esi
1c4: 53 push %ebx
int fd;
int r;
fd = open(n, O_RDONLY);
1c5: 83 ec 08 sub $0x8,%esp
1c8: 6a 00 push $0x0
1ca: ff 75 08 pushl 0x8(%ebp)
1cd: e8 8f 01 00 00 call 361 <open>
if(fd < 0)
1d2: 83 c4 10 add $0x10,%esp
1d5: 85 c0 test %eax,%eax
1d7: 78 27 js 200 <stat+0x40>
return -1;
r = fstat(fd, st);
1d9: 83 ec 08 sub $0x8,%esp
1dc: ff 75 0c pushl 0xc(%ebp)
1df: 89 c3 mov %eax,%ebx
1e1: 50 push %eax
1e2: e8 92 01 00 00 call 379 <fstat>
close(fd);
1e7: 89 1c 24 mov %ebx,(%esp)
r = fstat(fd, st);
1ea: 89 c6 mov %eax,%esi
close(fd);
1ec: e8 58 01 00 00 call 349 <close>
return r;
1f1: 83 c4 10 add $0x10,%esp
}
1f4: 8d 65 f8 lea -0x8(%ebp),%esp
1f7: 89 f0 mov %esi,%eax
1f9: 5b pop %ebx
1fa: 5e pop %esi
1fb: 5d pop %ebp
1fc: c3 ret
1fd: 8d 76 00 lea 0x0(%esi),%esi
return -1;
200: be ff ff ff ff mov $0xffffffff,%esi
205: eb ed jmp 1f4 <stat+0x34>
207: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
20e: 66 90 xchg %ax,%ax
00000210 <atoi>:
#ifdef PDX_XV6
int
atoi(const char *s)
{
210: 55 push %ebp
211: 89 e5 mov %esp,%ebp
213: 56 push %esi
214: 8b 55 08 mov 0x8(%ebp),%edx
217: 53 push %ebx
int n, sign;
n = 0;
while (*s == ' ') s++;
218: 0f b6 0a movzbl (%edx),%ecx
21b: 80 f9 20 cmp $0x20,%cl
21e: 75 0b jne 22b <atoi+0x1b>
220: 83 c2 01 add $0x1,%edx
223: 0f b6 0a movzbl (%edx),%ecx
226: 80 f9 20 cmp $0x20,%cl
229: 74 f5 je 220 <atoi+0x10>
sign = (*s == '-') ? -1 : 1;
22b: 80 f9 2d cmp $0x2d,%cl
22e: 74 40 je 270 <atoi+0x60>
230: be 01 00 00 00 mov $0x1,%esi
if (*s == '+' || *s == '-')
235: 80 f9 2b cmp $0x2b,%cl
238: 74 3b je 275 <atoi+0x65>
s++;
while('0' <= *s && *s <= '9')
23a: 0f be 0a movsbl (%edx),%ecx
23d: 8d 41 d0 lea -0x30(%ecx),%eax
240: 3c 09 cmp $0x9,%al
242: b8 00 00 00 00 mov $0x0,%eax
247: 77 1f ja 268 <atoi+0x58>
249: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
n = n*10 + *s++ - '0';
250: 83 c2 01 add $0x1,%edx
253: 8d 04 80 lea (%eax,%eax,4),%eax
256: 8d 44 41 d0 lea -0x30(%ecx,%eax,2),%eax
while('0' <= *s && *s <= '9')
25a: 0f be 0a movsbl (%edx),%ecx
25d: 8d 59 d0 lea -0x30(%ecx),%ebx
260: 80 fb 09 cmp $0x9,%bl
263: 76 eb jbe 250 <atoi+0x40>
265: 0f af c6 imul %esi,%eax
return sign*n;
}
268: 5b pop %ebx
269: 5e pop %esi
26a: 5d pop %ebp
26b: c3 ret
26c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
sign = (*s == '-') ? -1 : 1;
270: be ff ff ff ff mov $0xffffffff,%esi
s++;
275: 83 c2 01 add $0x1,%edx
278: eb c0 jmp 23a <atoi+0x2a>
27a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
00000280 <atoo>:
int
atoo(const char *s)
{
280: 55 push %ebp
281: 89 e5 mov %esp,%ebp
283: 56 push %esi
284: 8b 55 08 mov 0x8(%ebp),%edx
287: 53 push %ebx
int n, sign;
n = 0;
while (*s == ' ') s++;
288: 0f b6 0a movzbl (%edx),%ecx
28b: 80 f9 20 cmp $0x20,%cl
28e: 75 0b jne 29b <atoo+0x1b>
290: 83 c2 01 add $0x1,%edx
293: 0f b6 0a movzbl (%edx),%ecx
296: 80 f9 20 cmp $0x20,%cl
299: 74 f5 je 290 <atoo+0x10>
sign = (*s == '-') ? -1 : 1;
29b: 80 f9 2d cmp $0x2d,%cl
29e: 74 40 je 2e0 <atoo+0x60>
2a0: be 01 00 00 00 mov $0x1,%esi
if (*s == '+' || *s == '-')
2a5: 80 f9 2b cmp $0x2b,%cl
2a8: 74 3b je 2e5 <atoo+0x65>
s++;
while('0' <= *s && *s <= '7')
2aa: 0f be 0a movsbl (%edx),%ecx
2ad: 8d 41 d0 lea -0x30(%ecx),%eax
2b0: 3c 07 cmp $0x7,%al
2b2: b8 00 00 00 00 mov $0x0,%eax
2b7: 77 1c ja 2d5 <atoo+0x55>
2b9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
n = n*8 + *s++ - '0';
2c0: 83 c2 01 add $0x1,%edx
2c3: 8d 44 c1 d0 lea -0x30(%ecx,%eax,8),%eax
while('0' <= *s && *s <= '7')
2c7: 0f be 0a movsbl (%edx),%ecx
2ca: 8d 59 d0 lea -0x30(%ecx),%ebx
2cd: 80 fb 07 cmp $0x7,%bl
2d0: 76 ee jbe 2c0 <atoo+0x40>
2d2: 0f af c6 imul %esi,%eax
return sign*n;
}
2d5: 5b pop %ebx
2d6: 5e pop %esi
2d7: 5d pop %ebp
2d8: c3 ret
2d9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
sign = (*s == '-') ? -1 : 1;
2e0: be ff ff ff ff mov $0xffffffff,%esi
s++;
2e5: 83 c2 01 add $0x1,%edx
2e8: eb c0 jmp 2aa <atoo+0x2a>
2ea: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
000002f0 <memmove>:
}
#endif // PDX_XV6
void*
memmove(void *vdst, void *vsrc, int n)
{
2f0: 55 push %ebp
2f1: 89 e5 mov %esp,%ebp
2f3: 57 push %edi
2f4: 8b 55 10 mov 0x10(%ebp),%edx
2f7: 8b 45 08 mov 0x8(%ebp),%eax
2fa: 56 push %esi
2fb: 8b 75 0c mov 0xc(%ebp),%esi
char *dst, *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
2fe: 85 d2 test %edx,%edx
300: 7e 13 jle 315 <memmove+0x25>
302: 01 c2 add %eax,%edx
dst = vdst;
304: 89 c7 mov %eax,%edi
306: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
30d: 8d 76 00 lea 0x0(%esi),%esi
*dst++ = *src++;
310: a4 movsb %ds:(%esi),%es:(%edi)
while(n-- > 0)
311: 39 fa cmp %edi,%edx
313: 75 fb jne 310 <memmove+0x20>
return vdst;
}
315: 5e pop %esi
316: 5f pop %edi
317: 5d pop %ebp
318: c3 ret
00000319 <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
319: b8 01 00 00 00 mov $0x1,%eax
31e: cd 40 int $0x40
320: c3 ret
00000321 <exit>:
SYSCALL(exit)
321: b8 02 00 00 00 mov $0x2,%eax
326: cd 40 int $0x40
328: c3 ret
00000329 <wait>:
SYSCALL(wait)
329: b8 03 00 00 00 mov $0x3,%eax
32e: cd 40 int $0x40
330: c3 ret
00000331 <pipe>:
SYSCALL(pipe)
331: b8 04 00 00 00 mov $0x4,%eax
336: cd 40 int $0x40
338: c3 ret
00000339 <read>:
SYSCALL(read)
339: b8 05 00 00 00 mov $0x5,%eax
33e: cd 40 int $0x40
340: c3 ret
00000341 <write>:
SYSCALL(write)
341: b8 10 00 00 00 mov $0x10,%eax
346: cd 40 int $0x40
348: c3 ret
00000349 <close>:
SYSCALL(close)
349: b8 15 00 00 00 mov $0x15,%eax
34e: cd 40 int $0x40
350: c3 ret
00000351 <kill>:
SYSCALL(kill)
351: b8 06 00 00 00 mov $0x6,%eax
356: cd 40 int $0x40
358: c3 ret
00000359 <exec>:
SYSCALL(exec)
359: b8 07 00 00 00 mov $0x7,%eax
35e: cd 40 int $0x40
360: c3 ret
00000361 <open>:
SYSCALL(open)
361: b8 0f 00 00 00 mov $0xf,%eax
366: cd 40 int $0x40
368: c3 ret
00000369 <mknod>:
SYSCALL(mknod)
369: b8 11 00 00 00 mov $0x11,%eax
36e: cd 40 int $0x40
370: c3 ret
00000371 <unlink>:
SYSCALL(unlink)
371: b8 12 00 00 00 mov $0x12,%eax
376: cd 40 int $0x40
378: c3 ret
00000379 <fstat>:
SYSCALL(fstat)
379: b8 08 00 00 00 mov $0x8,%eax
37e: cd 40 int $0x40
380: c3 ret
00000381 <link>:
SYSCALL(link)
381: b8 13 00 00 00 mov $0x13,%eax
386: cd 40 int $0x40
388: c3 ret
00000389 <mkdir>:
SYSCALL(mkdir)
389: b8 14 00 00 00 mov $0x14,%eax
38e: cd 40 int $0x40
390: c3 ret
00000391 <chdir>:
SYSCALL(chdir)
391: b8 09 00 00 00 mov $0x9,%eax
396: cd 40 int $0x40
398: c3 ret
00000399 <dup>:
SYSCALL(dup)
399: b8 0a 00 00 00 mov $0xa,%eax
39e: cd 40 int $0x40
3a0: c3 ret
000003a1 <getpid>:
SYSCALL(getpid)
3a1: b8 0b 00 00 00 mov $0xb,%eax
3a6: cd 40 int $0x40
3a8: c3 ret
000003a9 <sbrk>:
SYSCALL(sbrk)
3a9: b8 0c 00 00 00 mov $0xc,%eax
3ae: cd 40 int $0x40
3b0: c3 ret
000003b1 <sleep>:
SYSCALL(sleep)
3b1: b8 0d 00 00 00 mov $0xd,%eax
3b6: cd 40 int $0x40
3b8: c3 ret
000003b9 <uptime>:
SYSCALL(uptime)
3b9: b8 0e 00 00 00 mov $0xe,%eax
3be: cd 40 int $0x40
3c0: c3 ret
000003c1 <halt>:
SYSCALL(halt)
3c1: b8 16 00 00 00 mov $0x16,%eax
3c6: cd 40 int $0x40
3c8: c3 ret
000003c9 <date>:
SYSCALL(date)
3c9: b8 17 00 00 00 mov $0x17,%eax
3ce: cd 40 int $0x40
3d0: c3 ret
000003d1 <getgid>:
SYSCALL(getgid)
3d1: b8 18 00 00 00 mov $0x18,%eax
3d6: cd 40 int $0x40
3d8: c3 ret
000003d9 <setgid>:
SYSCALL(setgid)
3d9: b8 19 00 00 00 mov $0x19,%eax
3de: cd 40 int $0x40
3e0: c3 ret
000003e1 <getuid>:
SYSCALL(getuid)
3e1: b8 1a 00 00 00 mov $0x1a,%eax
3e6: cd 40 int $0x40
3e8: c3 ret
000003e9 <setuid>:
SYSCALL(setuid)
3e9: b8 1b 00 00 00 mov $0x1b,%eax
3ee: cd 40 int $0x40
3f0: c3 ret
000003f1 <getppid>:
SYSCALL(getppid)
3f1: b8 1c 00 00 00 mov $0x1c,%eax
3f6: cd 40 int $0x40
3f8: c3 ret
000003f9 <getprocs>:
SYSCALL(getprocs)
3f9: b8 1d 00 00 00 mov $0x1d,%eax
3fe: cd 40 int $0x40
400: c3 ret
00000401 <setpriority>:
SYSCALL(setpriority)
401: b8 1e 00 00 00 mov $0x1e,%eax
406: cd 40 int $0x40
408: c3 ret
00000409 <getpriority>:
SYSCALL(getpriority)
409: b8 1f 00 00 00 mov $0x1f,%eax
40e: cd 40 int $0x40
410: c3 ret
00000411 <chmod>:
SYSCALL(chmod)
411: b8 20 00 00 00 mov $0x20,%eax
416: cd 40 int $0x40
418: c3 ret
00000419 <chown>:
SYSCALL(chown)
419: b8 21 00 00 00 mov $0x21,%eax
41e: cd 40 int $0x40
420: c3 ret
00000421 <chgrp>:
SYSCALL(chgrp)
421: b8 22 00 00 00 mov $0x22,%eax
426: cd 40 int $0x40
428: c3 ret
429: 66 90 xchg %ax,%ax
42b: 66 90 xchg %ax,%ax
42d: 66 90 xchg %ax,%ax
42f: 90 nop
00000430 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
430: 55 push %ebp
431: 89 e5 mov %esp,%ebp
433: 57 push %edi
434: 56 push %esi
435: 53 push %ebx
uint x;
neg = 0;
if(sgn && xx < 0){
neg = 1;
x = -xx;
436: 89 d3 mov %edx,%ebx
{
438: 83 ec 3c sub $0x3c,%esp
43b: 89 45 bc mov %eax,-0x44(%ebp)
if(sgn && xx < 0){
43e: 85 d2 test %edx,%edx
440: 0f 89 92 00 00 00 jns 4d8 <printint+0xa8>
446: f6 45 08 01 testb $0x1,0x8(%ebp)
44a: 0f 84 88 00 00 00 je 4d8 <printint+0xa8>
neg = 1;
450: c7 45 c0 01 00 00 00 movl $0x1,-0x40(%ebp)
x = -xx;
457: f7 db neg %ebx
} else {
x = xx;
}
i = 0;
459: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
460: 8d 75 d7 lea -0x29(%ebp),%esi
463: eb 08 jmp 46d <printint+0x3d>
465: 8d 76 00 lea 0x0(%esi),%esi
do{
buf[i++] = digits[x % base];
468: 89 7d c4 mov %edi,-0x3c(%ebp)
}while((x /= base) != 0);
46b: 89 c3 mov %eax,%ebx
buf[i++] = digits[x % base];
46d: 89 d8 mov %ebx,%eax
46f: 31 d2 xor %edx,%edx
471: 8b 7d c4 mov -0x3c(%ebp),%edi
474: f7 f1 div %ecx
476: 83 c7 01 add $0x1,%edi
479: 0f b6 92 60 08 00 00 movzbl 0x860(%edx),%edx
480: 88 14 3e mov %dl,(%esi,%edi,1)
}while((x /= base) != 0);
483: 39 d9 cmp %ebx,%ecx
485: 76 e1 jbe 468 <printint+0x38>
if(neg)
487: 8b 45 c0 mov -0x40(%ebp),%eax
48a: 85 c0 test %eax,%eax
48c: 74 0d je 49b <printint+0x6b>
buf[i++] = '-';
48e: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1)
493: ba 2d 00 00 00 mov $0x2d,%edx
buf[i++] = digits[x % base];
498: 89 7d c4 mov %edi,-0x3c(%ebp)
49b: 8b 45 c4 mov -0x3c(%ebp),%eax
49e: 8b 7d bc mov -0x44(%ebp),%edi
4a1: 8d 5c 05 d7 lea -0x29(%ebp,%eax,1),%ebx
4a5: eb 0f jmp 4b6 <printint+0x86>
4a7: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
4ae: 66 90 xchg %ax,%ax
4b0: 0f b6 13 movzbl (%ebx),%edx
4b3: 83 eb 01 sub $0x1,%ebx
write(fd, &c, 1);
4b6: 83 ec 04 sub $0x4,%esp
4b9: 88 55 d7 mov %dl,-0x29(%ebp)
4bc: 6a 01 push $0x1
4be: 56 push %esi
4bf: 57 push %edi
4c0: e8 7c fe ff ff call 341 <write>
while(--i >= 0)
4c5: 83 c4 10 add $0x10,%esp
4c8: 39 de cmp %ebx,%esi
4ca: 75 e4 jne 4b0 <printint+0x80>
putc(fd, buf[i]);
}
4cc: 8d 65 f4 lea -0xc(%ebp),%esp
4cf: 5b pop %ebx
4d0: 5e pop %esi
4d1: 5f pop %edi
4d2: 5d pop %ebp
4d3: c3 ret
4d4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
neg = 0;
4d8: c7 45 c0 00 00 00 00 movl $0x0,-0x40(%ebp)
4df: e9 75 ff ff ff jmp 459 <printint+0x29>
4e4: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
4eb: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
4ef: 90 nop
000004f0 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, char *fmt, ...)
{
4f0: 55 push %ebp
4f1: 89 e5 mov %esp,%ebp
4f3: 57 push %edi
4f4: 56 push %esi
4f5: 53 push %ebx
4f6: 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++){
4f9: 8b 75 0c mov 0xc(%ebp),%esi
4fc: 0f b6 1e movzbl (%esi),%ebx
4ff: 84 db test %bl,%bl
501: 0f 84 b9 00 00 00 je 5c0 <printf+0xd0>
ap = (uint*)(void*)&fmt + 1;
507: 8d 45 10 lea 0x10(%ebp),%eax
50a: 83 c6 01 add $0x1,%esi
write(fd, &c, 1);
50d: 8d 7d e7 lea -0x19(%ebp),%edi
state = 0;
510: 31 d2 xor %edx,%edx
ap = (uint*)(void*)&fmt + 1;
512: 89 45 d0 mov %eax,-0x30(%ebp)
515: eb 38 jmp 54f <printf+0x5f>
517: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
51e: 66 90 xchg %ax,%ax
520: 89 55 d4 mov %edx,-0x2c(%ebp)
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
state = '%';
523: ba 25 00 00 00 mov $0x25,%edx
if(c == '%'){
528: 83 f8 25 cmp $0x25,%eax
52b: 74 17 je 544 <printf+0x54>
write(fd, &c, 1);
52d: 83 ec 04 sub $0x4,%esp
530: 88 5d e7 mov %bl,-0x19(%ebp)
533: 6a 01 push $0x1
535: 57 push %edi
536: ff 75 08 pushl 0x8(%ebp)
539: e8 03 fe ff ff call 341 <write>
53e: 8b 55 d4 mov -0x2c(%ebp),%edx
} else {
putc(fd, c);
541: 83 c4 10 add $0x10,%esp
544: 83 c6 01 add $0x1,%esi
for(i = 0; fmt[i]; i++){
547: 0f b6 5e ff movzbl -0x1(%esi),%ebx
54b: 84 db test %bl,%bl
54d: 74 71 je 5c0 <printf+0xd0>
c = fmt[i] & 0xff;
54f: 0f be cb movsbl %bl,%ecx
552: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
555: 85 d2 test %edx,%edx
557: 74 c7 je 520 <printf+0x30>
}
} else if(state == '%'){
559: 83 fa 25 cmp $0x25,%edx
55c: 75 e6 jne 544 <printf+0x54>
if(c == 'd'){
55e: 83 f8 64 cmp $0x64,%eax
561: 0f 84 99 00 00 00 je 600 <printf+0x110>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
567: 81 e1 f7 00 00 00 and $0xf7,%ecx
56d: 83 f9 70 cmp $0x70,%ecx
570: 74 5e je 5d0 <printf+0xe0>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
572: 83 f8 73 cmp $0x73,%eax
575: 0f 84 d5 00 00 00 je 650 <printf+0x160>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
57b: 83 f8 63 cmp $0x63,%eax
57e: 0f 84 8c 00 00 00 je 610 <printf+0x120>
putc(fd, *ap);
ap++;
} else if(c == '%'){
584: 83 f8 25 cmp $0x25,%eax
587: 0f 84 b3 00 00 00 je 640 <printf+0x150>
write(fd, &c, 1);
58d: 83 ec 04 sub $0x4,%esp
590: c6 45 e7 25 movb $0x25,-0x19(%ebp)
594: 6a 01 push $0x1
596: 57 push %edi
597: ff 75 08 pushl 0x8(%ebp)
59a: e8 a2 fd ff ff call 341 <write>
putc(fd, c);
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
59f: 88 5d e7 mov %bl,-0x19(%ebp)
write(fd, &c, 1);
5a2: 83 c4 0c add $0xc,%esp
5a5: 6a 01 push $0x1
5a7: 83 c6 01 add $0x1,%esi
5aa: 57 push %edi
5ab: ff 75 08 pushl 0x8(%ebp)
5ae: e8 8e fd ff ff call 341 <write>
for(i = 0; fmt[i]; i++){
5b3: 0f b6 5e ff movzbl -0x1(%esi),%ebx
putc(fd, c);
5b7: 83 c4 10 add $0x10,%esp
}
state = 0;
5ba: 31 d2 xor %edx,%edx
for(i = 0; fmt[i]; i++){
5bc: 84 db test %bl,%bl
5be: 75 8f jne 54f <printf+0x5f>
}
}
}
5c0: 8d 65 f4 lea -0xc(%ebp),%esp
5c3: 5b pop %ebx
5c4: 5e pop %esi
5c5: 5f pop %edi
5c6: 5d pop %ebp
5c7: c3 ret
5c8: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
5cf: 90 nop
printint(fd, *ap, 16, 0);
5d0: 83 ec 0c sub $0xc,%esp
5d3: b9 10 00 00 00 mov $0x10,%ecx
5d8: 6a 00 push $0x0
5da: 8b 5d d0 mov -0x30(%ebp),%ebx
5dd: 8b 45 08 mov 0x8(%ebp),%eax
5e0: 8b 13 mov (%ebx),%edx
5e2: e8 49 fe ff ff call 430 <printint>
ap++;
5e7: 89 d8 mov %ebx,%eax
5e9: 83 c4 10 add $0x10,%esp
state = 0;
5ec: 31 d2 xor %edx,%edx
ap++;
5ee: 83 c0 04 add $0x4,%eax
5f1: 89 45 d0 mov %eax,-0x30(%ebp)
5f4: e9 4b ff ff ff jmp 544 <printf+0x54>
5f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
printint(fd, *ap, 10, 1);
600: 83 ec 0c sub $0xc,%esp
603: b9 0a 00 00 00 mov $0xa,%ecx
608: 6a 01 push $0x1
60a: eb ce jmp 5da <printf+0xea>
60c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
putc(fd, *ap);
610: 8b 5d d0 mov -0x30(%ebp),%ebx
write(fd, &c, 1);
613: 83 ec 04 sub $0x4,%esp
putc(fd, *ap);
616: 8b 03 mov (%ebx),%eax
write(fd, &c, 1);
618: 6a 01 push $0x1
ap++;
61a: 83 c3 04 add $0x4,%ebx
write(fd, &c, 1);
61d: 57 push %edi
61e: ff 75 08 pushl 0x8(%ebp)
putc(fd, *ap);
621: 88 45 e7 mov %al,-0x19(%ebp)
write(fd, &c, 1);
624: e8 18 fd ff ff call 341 <write>
ap++;
629: 89 5d d0 mov %ebx,-0x30(%ebp)
62c: 83 c4 10 add $0x10,%esp
state = 0;
62f: 31 d2 xor %edx,%edx
631: e9 0e ff ff ff jmp 544 <printf+0x54>
636: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
63d: 8d 76 00 lea 0x0(%esi),%esi
putc(fd, c);
640: 88 5d e7 mov %bl,-0x19(%ebp)
write(fd, &c, 1);
643: 83 ec 04 sub $0x4,%esp
646: e9 5a ff ff ff jmp 5a5 <printf+0xb5>
64b: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
64f: 90 nop
s = (char*)*ap;
650: 8b 45 d0 mov -0x30(%ebp),%eax
653: 8b 18 mov (%eax),%ebx
ap++;
655: 83 c0 04 add $0x4,%eax
658: 89 45 d0 mov %eax,-0x30(%ebp)
if(s == 0)
65b: 85 db test %ebx,%ebx
65d: 74 17 je 676 <printf+0x186>
while(*s != 0){
65f: 0f b6 03 movzbl (%ebx),%eax
state = 0;
662: 31 d2 xor %edx,%edx
while(*s != 0){
664: 84 c0 test %al,%al
666: 0f 84 d8 fe ff ff je 544 <printf+0x54>
66c: 89 75 d4 mov %esi,-0x2c(%ebp)
66f: 89 de mov %ebx,%esi
671: 8b 5d 08 mov 0x8(%ebp),%ebx
674: eb 1a jmp 690 <printf+0x1a0>
s = "(null)";
676: bb 58 08 00 00 mov $0x858,%ebx
while(*s != 0){
67b: 89 75 d4 mov %esi,-0x2c(%ebp)
67e: b8 28 00 00 00 mov $0x28,%eax
683: 89 de mov %ebx,%esi
685: 8b 5d 08 mov 0x8(%ebp),%ebx
688: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
68f: 90 nop
write(fd, &c, 1);
690: 83 ec 04 sub $0x4,%esp
s++;
693: 83 c6 01 add $0x1,%esi
696: 88 45 e7 mov %al,-0x19(%ebp)
write(fd, &c, 1);
699: 6a 01 push $0x1
69b: 57 push %edi
69c: 53 push %ebx
69d: e8 9f fc ff ff call 341 <write>
while(*s != 0){
6a2: 0f b6 06 movzbl (%esi),%eax
6a5: 83 c4 10 add $0x10,%esp
6a8: 84 c0 test %al,%al
6aa: 75 e4 jne 690 <printf+0x1a0>
6ac: 8b 75 d4 mov -0x2c(%ebp),%esi
state = 0;
6af: 31 d2 xor %edx,%edx
6b1: e9 8e fe ff ff jmp 544 <printf+0x54>
6b6: 66 90 xchg %ax,%ax
6b8: 66 90 xchg %ax,%ax
6ba: 66 90 xchg %ax,%ax
6bc: 66 90 xchg %ax,%ax
6be: 66 90 xchg %ax,%ax
000006c0 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
6c0: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
6c1: a1 3c 0b 00 00 mov 0xb3c,%eax
{
6c6: 89 e5 mov %esp,%ebp
6c8: 57 push %edi
6c9: 56 push %esi
6ca: 53 push %ebx
6cb: 8b 5d 08 mov 0x8(%ebp),%ebx
6ce: 8b 10 mov (%eax),%edx
bp = (Header*)ap - 1;
6d0: 8d 4b f8 lea -0x8(%ebx),%ecx
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
6d3: 39 c8 cmp %ecx,%eax
6d5: 73 19 jae 6f0 <free+0x30>
6d7: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
6de: 66 90 xchg %ax,%ax
6e0: 39 d1 cmp %edx,%ecx
6e2: 72 14 jb 6f8 <free+0x38>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
6e4: 39 d0 cmp %edx,%eax
6e6: 73 10 jae 6f8 <free+0x38>
{
6e8: 89 d0 mov %edx,%eax
6ea: 8b 10 mov (%eax),%edx
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
6ec: 39 c8 cmp %ecx,%eax
6ee: 72 f0 jb 6e0 <free+0x20>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
6f0: 39 d0 cmp %edx,%eax
6f2: 72 f4 jb 6e8 <free+0x28>
6f4: 39 d1 cmp %edx,%ecx
6f6: 73 f0 jae 6e8 <free+0x28>
break;
if(bp + bp->s.size == p->s.ptr){
6f8: 8b 73 fc mov -0x4(%ebx),%esi
6fb: 8d 3c f1 lea (%ecx,%esi,8),%edi
6fe: 39 fa cmp %edi,%edx
700: 74 1e je 720 <free+0x60>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
702: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
705: 8b 50 04 mov 0x4(%eax),%edx
708: 8d 34 d0 lea (%eax,%edx,8),%esi
70b: 39 f1 cmp %esi,%ecx
70d: 74 28 je 737 <free+0x77>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
70f: 89 08 mov %ecx,(%eax)
freep = p;
}
711: 5b pop %ebx
freep = p;
712: a3 3c 0b 00 00 mov %eax,0xb3c
}
717: 5e pop %esi
718: 5f pop %edi
719: 5d pop %ebp
71a: c3 ret
71b: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
71f: 90 nop
bp->s.size += p->s.ptr->s.size;
720: 03 72 04 add 0x4(%edx),%esi
723: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
726: 8b 10 mov (%eax),%edx
728: 8b 12 mov (%edx),%edx
72a: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
72d: 8b 50 04 mov 0x4(%eax),%edx
730: 8d 34 d0 lea (%eax,%edx,8),%esi
733: 39 f1 cmp %esi,%ecx
735: 75 d8 jne 70f <free+0x4f>
p->s.size += bp->s.size;
737: 03 53 fc add -0x4(%ebx),%edx
freep = p;
73a: a3 3c 0b 00 00 mov %eax,0xb3c
p->s.size += bp->s.size;
73f: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
742: 8b 53 f8 mov -0x8(%ebx),%edx
745: 89 10 mov %edx,(%eax)
}
747: 5b pop %ebx
748: 5e pop %esi
749: 5f pop %edi
74a: 5d pop %ebp
74b: c3 ret
74c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
00000750 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
750: 55 push %ebp
751: 89 e5 mov %esp,%ebp
753: 57 push %edi
754: 56 push %esi
755: 53 push %ebx
756: 83 ec 1c sub $0x1c,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
759: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
75c: 8b 3d 3c 0b 00 00 mov 0xb3c,%edi
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
762: 8d 70 07 lea 0x7(%eax),%esi
765: c1 ee 03 shr $0x3,%esi
768: 83 c6 01 add $0x1,%esi
if((prevp = freep) == 0){
76b: 85 ff test %edi,%edi
76d: 0f 84 ad 00 00 00 je 820 <malloc+0xd0>
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
773: 8b 17 mov (%edi),%edx
if(p->s.size >= nunits){
775: 8b 4a 04 mov 0x4(%edx),%ecx
778: 39 f1 cmp %esi,%ecx
77a: 73 72 jae 7ee <malloc+0x9e>
77c: 81 fe 00 10 00 00 cmp $0x1000,%esi
782: bb 00 10 00 00 mov $0x1000,%ebx
787: 0f 43 de cmovae %esi,%ebx
p = sbrk(nu * sizeof(Header));
78a: 8d 04 dd 00 00 00 00 lea 0x0(,%ebx,8),%eax
791: 89 45 e4 mov %eax,-0x1c(%ebp)
794: eb 1b jmp 7b1 <malloc+0x61>
796: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
79d: 8d 76 00 lea 0x0(%esi),%esi
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
7a0: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
7a2: 8b 48 04 mov 0x4(%eax),%ecx
7a5: 39 f1 cmp %esi,%ecx
7a7: 73 4f jae 7f8 <malloc+0xa8>
7a9: 8b 3d 3c 0b 00 00 mov 0xb3c,%edi
7af: 89 c2 mov %eax,%edx
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
7b1: 39 d7 cmp %edx,%edi
7b3: 75 eb jne 7a0 <malloc+0x50>
p = sbrk(nu * sizeof(Header));
7b5: 83 ec 0c sub $0xc,%esp
7b8: ff 75 e4 pushl -0x1c(%ebp)
7bb: e8 e9 fb ff ff call 3a9 <sbrk>
if(p == (char*)-1)
7c0: 83 c4 10 add $0x10,%esp
7c3: 83 f8 ff cmp $0xffffffff,%eax
7c6: 74 1c je 7e4 <malloc+0x94>
hp->s.size = nu;
7c8: 89 58 04 mov %ebx,0x4(%eax)
free((void*)(hp + 1));
7cb: 83 ec 0c sub $0xc,%esp
7ce: 83 c0 08 add $0x8,%eax
7d1: 50 push %eax
7d2: e8 e9 fe ff ff call 6c0 <free>
return freep;
7d7: 8b 15 3c 0b 00 00 mov 0xb3c,%edx
if((p = morecore(nunits)) == 0)
7dd: 83 c4 10 add $0x10,%esp
7e0: 85 d2 test %edx,%edx
7e2: 75 bc jne 7a0 <malloc+0x50>
return 0;
}
}
7e4: 8d 65 f4 lea -0xc(%ebp),%esp
return 0;
7e7: 31 c0 xor %eax,%eax
}
7e9: 5b pop %ebx
7ea: 5e pop %esi
7eb: 5f pop %edi
7ec: 5d pop %ebp
7ed: c3 ret
if(p->s.size >= nunits){
7ee: 89 d0 mov %edx,%eax
7f0: 89 fa mov %edi,%edx
7f2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
if(p->s.size == nunits)
7f8: 39 ce cmp %ecx,%esi
7fa: 74 54 je 850 <malloc+0x100>
p->s.size -= nunits;
7fc: 29 f1 sub %esi,%ecx
7fe: 89 48 04 mov %ecx,0x4(%eax)
p += p->s.size;
801: 8d 04 c8 lea (%eax,%ecx,8),%eax
p->s.size = nunits;
804: 89 70 04 mov %esi,0x4(%eax)
freep = prevp;
807: 89 15 3c 0b 00 00 mov %edx,0xb3c
}
80d: 8d 65 f4 lea -0xc(%ebp),%esp
return (void*)(p + 1);
810: 83 c0 08 add $0x8,%eax
}
813: 5b pop %ebx
814: 5e pop %esi
815: 5f pop %edi
816: 5d pop %ebp
817: c3 ret
818: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
81f: 90 nop
base.s.ptr = freep = prevp = &base;
820: c7 05 3c 0b 00 00 40 movl $0xb40,0xb3c
827: 0b 00 00
base.s.size = 0;
82a: bf 40 0b 00 00 mov $0xb40,%edi
base.s.ptr = freep = prevp = &base;
82f: c7 05 40 0b 00 00 40 movl $0xb40,0xb40
836: 0b 00 00
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
839: 89 fa mov %edi,%edx
base.s.size = 0;
83b: c7 05 44 0b 00 00 00 movl $0x0,0xb44
842: 00 00 00
if(p->s.size >= nunits){
845: e9 32 ff ff ff jmp 77c <malloc+0x2c>
84a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
prevp->s.ptr = p->s.ptr;
850: 8b 08 mov (%eax),%ecx
852: 89 0a mov %ecx,(%edx)
854: eb b1 jmp 807 <malloc+0xb7>
|
; A126335: a(n) = n*(4*n^2+5*n-3)/2.
; 3,23,72,162,305,513,798,1172,1647,2235,2948,3798,4797,5957,7290,8808,10523,12447,14592,16970,19593,22473,25622,29052,32775,36803,41148,45822,50837,56205,61938,68048,74547,81447,88760,96498,104673,113297,122382,131940,141983,152523,163572,175142,187245,199893,213098,226872,241227,256175,271728,287898,304697,322137,340230,358988,378423,398547,419372,440910,463173,486173,509922,534432,559715,585783,612648,640322,668817,698145,728318,759348,791247,824027,857700,892278,927773,964197,1001562,1039880,1079163,1119423,1160672,1202922,1246185,1290473,1335798,1382172,1429607,1478115,1527708,1578398,1630197,1683117,1737170,1792368,1848723,1906247,1964952,2024850
add $0,1
mov $2,1
lpb $0
add $1,$4
add $2,$0
sub $0,1
add $1,$2
add $1,1
mov $3,4
add $3,$4
add $2,$3
add $4,5
add $2,$4
lpe
mov $0,$1
|
; A004232: a(n) = n^2 + prime(n).
; 3,7,14,23,36,49,66,83,104,129,152,181,210,239,272,309,348,385,428,471,514,563,612,665,722,777,832,891,950,1013,1088,1155,1226,1295,1374,1447,1526,1607,1688,1773,1860,1945,2040,2129,2222,2315,2420,2527,2628,2729
mov $1,$0
add $0,1
pow $0,2
seq $1,40 ; The prime numbers.
add $0,$1
|
; A118537: Number of functions f: {1, 2, ..., n} --> {1, 2, ..., n} such that f(1) != f(2), f(2) != f(3), ..., f(n-1) != f(n), f(n) != f(1).
; Submitted by Jon Maiga
; 2,6,84,1020,15630,279930,5764808,134217720,3486784410,99999999990,3138428376732,106993205379060,3937376385699302,155568095557812210,6568408355712890640,295147905179352825840,14063084452067724991026,708235345355337676357614,37589973457545958193355620,2097151999999999999999999980,122694327386105632949003612862,7511413302012830262726227918826,480250763996501976790165756943064,32009658644406818986777955348250600,2220446049250313080847263336181640650,160059109085386090080713531498405298150
mov $1,$0
add $0,2
seq $1,185634 ; Number of n-length cycles from any point in a complete graph on n nodes.
mul $1,$0
mov $0,$1
|
INCLUDE "clib_cfg.asm"
SECTION code_clib
SECTION code_math
PUBLIC l_divu_32_32x16, l0_divu_32_32x16
; compute: dehl = dehl / bc, dehl' = dehl % bc
; alters : af, bc, de, hl, bc', de', hl', ix
; alternate entry (l0_divu_32_32x16)
; skips divide by zero check
IF __CLIB_OPT_IMATH <= 50
EXTERN l_small_divu_32_32x32, l0_small_divu_32_32x32
l_divu_32_32x16:
scf
l0_divu_32_32x16:
push bc
exx
pop hl
ld de,0
jp nc, l0_small_divu_32_32x32
jp l_small_divu_32_32x32
ENDIF
IF __CLIB_OPT_IMATH > 50
EXTERN l_fast_divu_32_32x16, l0_fast_divu_32_32x16
defc l_divu_32_32x16 = l_fast_divu_32_32x16
defc l0_divu_32_32x16 = l0_fast_divu_32_32x16
ENDIF
|
object_const_def ; object_event constants
const OAKSLAB_OAK
const OAKSLAB_SCIENTIST1
const OAKSLAB_SCIENTIST2
const OAKSLAB_SCIENTIST3
OaksLab_MapScripts:
db 0 ; scene scripts
db 0 ; callbacks
.DummyScene:
end
Oak:
faceplayer
opentext
checkevent EVENT_OPENED_MT_SILVER
iftrue .CheckPokedex
checkevent EVENT_TALKED_TO_OAK_IN_KANTO
iftrue .CheckBadges
writetext OakWelcomeKantoText
buttonsound
setevent EVENT_TALKED_TO_OAK_IN_KANTO
.CheckBadges:
readvar VAR_BADGES
ifequal NUM_BADGES, .OpenMtSilver
ifequal NUM_JOHTO_BADGES, .Complain
sjump .AhGood
.CheckPokedex:
writetext OakLabDexCheckText
waitbutton
special ProfOaksPCBoot
writetext OakLabGoodbyeText
waitbutton
closetext
end
.OpenMtSilver:
writetext OakOpenMtSilverText
buttonsound
setevent EVENT_OPENED_MT_SILVER
sjump .CheckPokedex
.Complain:
writetext OakNoKantoBadgesText
buttonsound
sjump .CheckPokedex
.AhGood:
writetext OakYesKantoBadgesText
buttonsound
sjump .CheckPokedex
OaksAssistant1Script:
jumptextfaceplayer OaksAssistant1Text
OaksAssistant2Script:
jumptextfaceplayer OaksAssistant2Text
OaksAssistant3Script:
jumptextfaceplayer OaksAssistant3Text
OaksLabBookshelf:
jumpstd difficultbookshelf
OaksLabPoster1:
jumptext OaksLabPoster1Text
OaksLabPoster2:
jumptext OaksLabPoster2Text
OaksLabTrashcan:
jumptext OaksLabTrashcanText
OaksLabPC:
jumptext OaksLabPCText
OakWelcomeKantoText:
text "OAK: Ah, <PLAY_G>!"
line "It's good of you"
para "to come all this"
line "way to KANTO."
para "What do you think"
line "of the trainers"
para "out here?"
line "Pretty tough, huh?"
done
OakLabDexCheckText:
text "How is your #-"
line "DEX coming?"
para "Let's see…"
done
OakLabGoodbyeText:
text "If you're in the"
line "area, I hope you"
cont "come visit again."
done
OakOpenMtSilverText:
text "OAK: Wow! That's"
line "excellent!"
para "You collected the"
line "BADGES of GYMS in"
cont "KANTO. Well done!"
para "I was right in my"
line "assessment of you."
para "Tell you what,"
line "<PLAY_G>. I'll make"
para "arrangements so"
line "that you can go to"
cont "MT.SILVER."
para "MT.SILVER is a big"
line "mountain that is"
para "home to many wild"
line "#MON."
para "It's too dangerous"
line "for your average"
para "trainer, so it's"
line "off limits. But"
para "we can make an"
line "exception in your"
cont "case, <PLAY_G>."
para "Go up to INDIGO"
line "PLATEAU. You can"
para "reach MT.SILVER"
line "from there."
done
OakNoKantoBadgesText:
text "OAK: Hmm? You're"
line "not collecting"
cont "KANTO GYM BADGES?"
para "The GYM LEADERS in"
line "KANTO are as tough"
para "as any you battled"
line "in JOHTO."
para "I recommend that"
line "you challenge"
cont "them."
done
OakYesKantoBadgesText:
text "OAK: Ah, you're"
line "collecting KANTO"
cont "GYM BADGES."
para "I imagine that"
line "it's hard, but the"
para "experience is sure"
line "to help you."
para "Come see me when"
line "you get them all."
para "I'll have a gift"
line "for you."
para "Keep trying hard,"
line "<PLAY_G>!"
done
OaksAssistant1Text:
text "The PROF's #MON"
line "TALK radio program"
para "isn't aired here"
line "in KANTO."
para "It's a shame--I'd"
line "like to hear it."
done
OaksAssistant2Text:
text "Thanks to your"
line "work on the #-"
cont "DEX, the PROF's"
para "research is coming"
line "along great."
done
OaksAssistant3Text:
text "Don't tell anyone,"
line "but PROF.OAK'S"
para "#MON TALK isn't"
line "a live broadcast."
done
OaksLabPoster1Text:
text "Press START to"
line "open the MENU."
done
OaksLabPoster2Text:
text "The SAVE option is"
line "on the MENU."
para "Use it in a timely"
line "manner."
done
OaksLabTrashcanText:
text "There's nothing in"
line "here…"
done
OaksLabPCText:
text "There's an e-mail"
line "message on the PC."
para "…"
para "PROF.OAK, how is"
line "your research"
cont "coming along?"
para "I'm still plugging"
line "away."
para "I heard rumors"
line "that <PLAY_G> is"
para "getting quite a"
line "reputation."
para "I'm delighted to"
line "hear that."
para "ELM in NEW BARK"
line "TOWN 8-)"
done
OaksLab_MapEvents:
db 0, 0 ; filler
db 2 ; warp events
warp_event 4, 11, PALLET_TOWN, 3
warp_event 5, 11, PALLET_TOWN, 3
db 0 ; coord events
db 16 ; bg events
bg_event 6, 1, BGEVENT_READ, OaksLabBookshelf
bg_event 7, 1, BGEVENT_READ, OaksLabBookshelf
bg_event 8, 1, BGEVENT_READ, OaksLabBookshelf
bg_event 9, 1, BGEVENT_READ, OaksLabBookshelf
bg_event 0, 7, BGEVENT_READ, OaksLabBookshelf
bg_event 1, 7, BGEVENT_READ, OaksLabBookshelf
bg_event 2, 7, BGEVENT_READ, OaksLabBookshelf
bg_event 3, 7, BGEVENT_READ, OaksLabBookshelf
bg_event 6, 7, BGEVENT_READ, OaksLabBookshelf
bg_event 7, 7, BGEVENT_READ, OaksLabBookshelf
bg_event 8, 7, BGEVENT_READ, OaksLabBookshelf
bg_event 9, 7, BGEVENT_READ, OaksLabBookshelf
bg_event 4, 0, BGEVENT_READ, OaksLabPoster1
bg_event 5, 0, BGEVENT_READ, OaksLabPoster2
bg_event 9, 3, BGEVENT_READ, OaksLabTrashcan
bg_event 0, 1, BGEVENT_READ, OaksLabPC
db 4 ; object events
object_event 4, 2, SPRITE_OAK, SPRITEMOVEDATA_STANDING_DOWN, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, Oak, -1
object_event 1, 8, SPRITE_SCIENTIST, SPRITEMOVEDATA_WALK_LEFT_RIGHT, 1, 0, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_SCRIPT, 0, OaksAssistant1Script, -1
object_event 8, 9, SPRITE_SCIENTIST, SPRITEMOVEDATA_WALK_UP_DOWN, 0, 1, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_SCRIPT, 0, OaksAssistant2Script, -1
object_event 1, 4, SPRITE_SCIENTIST, SPRITEMOVEDATA_WANDER, 1, 1, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_SCRIPT, 0, OaksAssistant3Script, -1
|
; --------------------------------------
; Test LDA and STA.
; Moving data from an address to a register, and back from a register to an address.
;
; STA a: Store register A data to an address a(hb:lb).
; LDA a: Load register A with the data at the address a(hb:lb).
;
; 8085 program to add two 8 bit numbers
; https://www.geeksforgeeks.org/assembly-language-program-8085-microprocessor-add-two-8-bit-numbers/
;
; --------------------------------------
lxi sp,255 ; Set stack pointer which is used with CALL and RET.
Start:
mvi h,0 ; Address for memory address testing.
mvi l,128 ; Greater than 93, because: Write to serial port. Number of bytes: 93
out 36 ; Print the register values for H:L and the content at that address.
;
; --------------------------------------
; Test using an number for the immediate address.
;
mvi a,6 ; Move # to register A.
out 37 ; Print register A.
sta 128 ; Store register A's data value to the address(hb:lb).
out 36 ; Print the register values for H:L and the content at that address.
call doHalt
; > Register H:L = 0:96, Data: 0
; > Register A = 6 = 006 = 00000110
; > Register H:L = 0:64, Data: 6
;
mvi a,0 ; Move # to register A.
out 37 ; Print register A.
lda 128 ; Load register A from the address(hb:lb).
out 37 ; Print register A.
call doHalt
; > Register A = 0 = 000 = 00000000
; > Register A = 6 = 006 = 00000110
;
; --------------------------------------
; Test using an EQU for the immediate address.
;
mvi a,9 ; Move immediate # to register A.
out 37 ; Print register A.
sta Addr1 ; Store register A's data value to the address(hb:lb).
lxi h,Addr1 ; Load an address (value of Addr1) into H:L.
out 36 ; Print the register values for H:L, and the content at that address.
call doHalt
; + regA: 9 = 011 = 00001001
; + Register H:L = 0:128, Data: 9
;
mvi a,0 ; Move # to register A.
lda Addr1 ; Load register A from the address(hb:lb).
out 37 ; Print register A.
call doHalt
; > Register A = 58 = 072 = 00111010
; Program listing the value at address 60:
; ++ 60:00111100: 00111010 : 3A:072 > opcode: lda Addr2
;
; --------------------------------------
; Test using an DS value and label for the immediate address.
; How to put an address into 2 bytes of memory?
;
mvi a,12 ; Move # to register A.
sta Addr2 ; Store register A's content to the address at label: Addr2.
mvi a,0 ; Move # to register A.
lda Addr2 ; Load register A from the address(hb:lb).
; ++ Byte array number: 60, Byte: 00111010 Octal:072 Decimal58
out 37 ; Print register A.
;
inr a
sta Addr2 ; Store the incremented value to: Addr2.
mvi a,0 ; Move # to register A.
lda Addr2 ; Load Addr2 into register A.
out 37 ; Print register A.
; > Register A = 12 = 014 = 00001100
; > Register A = 13 = 015 = 00001101
; --------------------------------------
call doHalt
jmp Start
; --------------------------------------
; Program variables
Addr1 equ 128
Addr2 ds 2
; --------------------------------------
doHalt:
mvi a,'\r'
out 3
mvi a,'\n'
out 3
hlt
ret
; --------------------------------------
end
; --------------------------------------
; Successful run:
+ Ready to receive command.
+ runProcessor()
> Register H:L = 0:128, Data: 0 = 000 = 00000000
> Register A = 6 = 006 = 00000110
> Register H:L = 0:128, Data: 6 = 006 = 00000110
++ HALT, host_read_status_led_WAIT() = 0
+ runProcessor()
> Register A = 0 = 000 = 00000000
> Register A = 6 = 006 = 00000110
++ HALT, host_read_status_led_WAIT() = 0
+ runProcessor()
> Register A = 9 = 011 = 00001001
> Register H:L = 0:128, Data: 9 = 011 = 00001001
++ HALT, host_read_status_led_WAIT() = 0
+ runProcessor()
> Register A = 9 = 011 = 00001001
++ HALT, host_read_status_led_WAIT() = 0
+ runProcessor()
> Register A = 12 = 014 = 00001100
> Register A = 13 = 015 = 00001101
++ HALT, host_read_status_led_WAIT() = 0
;
; --------------------------------------
|
; /*****************************************************************************
; * ugBASIC - an isomorphic BASIC language compiler for retrocomputers *
; *****************************************************************************
; * Copyright 2021 Marco Spedaletti (asimov@mclink.it)
; *
; * 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.
; *----------------------------------------------------------------------------
; * Concesso in licenza secondo i termini della Licenza Apache, versione 2.0
; * (la "Licenza"); è proibito usare questo file se non in conformità alla
; * Licenza. Una copia della Licenza è disponibile all'indirizzo:
; *
; * http://www.apache.org/licenses/LICENSE-2.0
; *
; * Se non richiesto dalla legislazione vigente o concordato per iscritto,
; * il software distribuito nei termini della Licenza è distribuito
; * "COSì COM'è", SENZA GARANZIE O CONDIZIONI DI ALCUN TIPO, esplicite o
; * implicite. Consultare la Licenza per il testo specifico che regola le
; * autorizzazioni e le limitazioni previste dalla medesima.
; ****************************************************************************/
;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
;* *
;* IMAGES ROUTINE FOR ZX SPECTRUM *
;* *
;* by Marco Spedaletti *
;* *
;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
IMAGEX: DB 0
IMAGEY: DB 0
IMAGEW: DB 0
IMAGEH: DB 0
IMAGEH2: DB 0
; ----------------------------------------------------------------------------
; - Put image on bitmap
; ----------------------------------------------------------------------------
PUTIMAGE:
LD A, (CURRENTMODE)
; BITMAP_MODE_STANDARD
CP 0
JR NZ, PUTIMAGE0X
JMP PUTIMAGE0
PUTIMAGE0X:
; TILEMAP_MODE_STANDARD
CP 1
JR NZ, PUTIMAGE1X
JMP PUTIMAGE1
PUTIMAGE1X:
RET
PUTIMAGE1:
RET
PUTIMAGE0:
LD A, (HL)
LD (IMAGEW), A
ADD HL, 1
LD A, (HL)
SRL A
SRL A
SRL A
LD (IMAGEH), A
LD (IMAGEH2), A
ADD HL, 1
PUSH HL
LD A, (IMAGEX)
AND $7
LD B, A
LD A, $8
SUB B
LD B, A
LD E, 1
PUTIMAGE0A:
DEC B
JR Z,PUTIMAGE0B
SLA E
JMP PUTIMAGE0A
PUTIMAGE0B:
LD A,(IMAGEY)
LD B, A
LD A,(IMAGEX)
LD C, A
LD A,B
AND %00000111
OR %01000000
LD H,A
LD A,B
RRA
RRA
RRA
AND %00011000
OR H
LD H,A
LD A,B
RLA
RLA
AND %11100000
LD L,A
LD A,C
RRA
RRA
RRA
AND %00011111
OR L
LD L,A
PUSH HL
POP DE
POP HL
LD A, (IMAGEH)
LD C, A
SLA C
SLA C
SLA C
LD A, (IMAGEW)
LD B, A
PUTIMAGE0CP:
LD A, (HL)
LD (DE), A
INC HL
INC DE
DEC B
JR NZ, PUTIMAGE0CP
LD A, (IMAGEW)
LD B, A
PUSH HL
LD A,(IMAGEY)
ADD A, 1
LD (IMAGEY), A
LD B, A
LD A,(IMAGEX)
LD C, A
LD A,B
AND %00000111
OR %01000000
LD H,A
LD A,B
RRA
RRA
RRA
AND %00011000
OR H
LD H,A
LD A,B
RLA
RLA
AND %11100000
LD L,A
LD A,C
RRA
RRA
RRA
AND %00011111
OR L
LD L,A
PUSH HL
POP DE
POP HL
DEC C
JR NZ, PUTIMAGE0CP
;;;;
PUSH HL
LD HL,(IMAGEX)
SRA H
RR L
SRA H
RR L
SRA H
RR L
LD DE,HL
LD HL,(IMAGEY)
SLA L
RL H
SLA L
RL H
ADD HL,DE
LD DE,(COLORMAPADDRESS)
ADD HL,DE
PUSH HL
POP DE
POP HL
LD A, (IMAGEH)
LD C, A
LD A, (IMAGEW)
LD B, A
PUTIMAGE00CP:
LD A, (HL)
LD (DE), A
INC HL
INC DE
DEC B
JR NZ, PUTIMAGE00CP
LD A, (IMAGEW)
LD B, A
PUSH HL
LD A, (IMAGEW)
LD C, A
LD A, 0
LD B, A
ADD HL, 64
SUB HL, BC
DEC C
JR NZ, PUTIMAGE00CP
RET
|
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <vector>
#include <memory>
#include <string>
#include <transformations_visibility.hpp>
#include <ngraph/pass/graph_rewrite.hpp>
namespace ngraph {
namespace pass {
class TRANSFORMATIONS_API ConvertLSTMCellMatcher;
class TRANSFORMATIONS_API ConvertGRUCellMatcher;
class TRANSFORMATIONS_API ConvertRNNCellMatcher;
} // namespace pass
} // namespace ngraph
class ngraph::pass::ConvertLSTMCellMatcher : public ngraph::pass::MatcherPass {
public:
ConvertLSTMCellMatcher();
};
class ngraph::pass::ConvertGRUCellMatcher : public ngraph::pass::MatcherPass {
public:
ConvertGRUCellMatcher();
};
class ngraph::pass::ConvertRNNCellMatcher : public ngraph::pass::MatcherPass {
public:
ConvertRNNCellMatcher();
};
|
; A197728: Decimal expansion of 3*Pi/(2 + 2*Pi).
; Submitted by Christian Krause
; 1,1,3,7,8,2,0,4,8,9,4,9,2,1,6,4,2,1,8,0,1,6,6,4,6,0,3,3,5,6,7,3,3,9,2,9,6,2,0,7,6,3,9,5,4,8,4,6,0,7,9,6,4,9,5,0,0,3,4,8,2,3,2,0,6,7,3,8,2,2,2,0,5,6,5,1,4,3,6,0,6,4,4,8,0,9,4,9,7,6,1,0,2,3,0,3,3,6,5
mov $2,1
mov $3,$0
mul $3,5
lpb $3
mul $1,$3
mov $5,$3
mul $5,2
add $5,1
mul $2,$5
add $1,$2
cmp $4,0
mov $5,$0
add $5,$4
div $1,$5
div $2,$5
sub $3,1
lpe
add $2,$1
add $2,$1
mul $1,3
mov $6,10
pow $6,$0
div $2,$6
div $1,$2
add $1,$6
mov $0,$1
mod $0,10
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r15
push %r9
push %rax
push %rbx
push %rdx
push %rsi
lea addresses_WC_ht+0xe9c2, %r9
nop
cmp $42590, %rdx
movw $0x6162, (%r9)
nop
nop
nop
nop
nop
add %r12, %r12
lea addresses_A_ht+0x165c2, %rbx
cmp %rax, %rax
movl $0x61626364, (%rbx)
nop
nop
and %rsi, %rsi
lea addresses_D_ht+0x19872, %r15
nop
sub %r9, %r9
mov (%r15), %rdx
nop
nop
nop
nop
dec %r9
lea addresses_A_ht+0xbb22, %r12
clflush (%r12)
nop
and $32996, %r9
mov $0x6162636465666768, %rbx
movq %rbx, %xmm1
and $0xffffffffffffffc0, %r12
vmovntdq %ymm1, (%r12)
add $35960, %r12
lea addresses_WT_ht+0xa342, %r12
nop
nop
nop
nop
nop
xor $31389, %r9
mov $0x6162636465666768, %rbx
movq %rbx, (%r12)
nop
nop
nop
nop
nop
sub $31038, %r9
pop %rsi
pop %rdx
pop %rbx
pop %rax
pop %r9
pop %r15
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r14
push %r15
push %r8
push %rcx
push %rdi
push %rsi
// REPMOV
lea addresses_normal+0x19062, %rsi
lea addresses_RW+0x1212c, %rdi
nop
nop
nop
nop
and $4373, %r8
mov $2, %rcx
rep movsw
nop
nop
xor %r12, %r12
// Store
lea addresses_RW+0x15062, %rcx
clflush (%rcx)
nop
nop
nop
nop
nop
dec %r14
mov $0x5152535455565758, %r15
movq %r15, %xmm3
movups %xmm3, (%rcx)
cmp $38497, %r8
// Store
lea addresses_WT+0xc142, %r14
dec %rsi
movl $0x51525354, (%r14)
nop
nop
nop
nop
nop
dec %r14
// Store
mov $0x589dd20000000142, %rcx
nop
nop
nop
and %r12, %r12
mov $0x5152535455565758, %r14
movq %r14, (%rcx)
nop
nop
nop
nop
sub $25315, %r12
// Store
lea addresses_A+0xd20a, %rdi
nop
nop
nop
nop
nop
add $31351, %r14
mov $0x5152535455565758, %rcx
movq %rcx, %xmm7
movntdq %xmm7, (%rdi)
nop
nop
and $47152, %r15
// Faulty Load
lea addresses_RW+0x65c2, %r12
nop
nop
nop
nop
and %r14, %r14
mov (%r12), %r15
lea oracles, %r8
and $0xff, %r15
shlq $12, %r15
mov (%r8,%r15,1), %r15
pop %rsi
pop %rdi
pop %rcx
pop %r8
pop %r15
pop %r14
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_RW', 'size': 2, 'AVXalign': True}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_normal', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_RW', 'congruent': 1, 'same': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_RW', 'size': 16, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_WT', 'size': 4, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_NC', 'size': 8, 'AVXalign': True}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 2, 'NT': True, 'type': 'addresses_A', 'size': 16, 'AVXalign': False}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_RW', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_A_ht', 'size': 4, 'AVXalign': True}}
{'src': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': True, 'type': 'addresses_A_ht', 'size': 32, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False}}
{'32': 21829}
32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
*/
|
; A001629: Self-convolution of Fibonacci numbers.
; 0,0,1,2,5,10,20,38,71,130,235,420,744,1308,2285,3970,6865,11822,20284,34690,59155,100610,170711,289032,488400,823800,1387225,2332418,3916061,6566290,10996580,18394910,30737759,51310978,85573315,142587180,237387960,394905492,656451269,1090444930,1810142185,3002921270,4978643596,8249479162,13661617195,22612505090,37409025455,61857842448,102238082976,168903452400,278920277425,460409998850,759695287349,1253056566298,2066068144820,3405392282390,5611044289655,9242288005762,15218767591579,25052342327220,41227831944840,67828183027980,111560745754781,183441668320642,301559884395265,495611762573630,814339327146460,1337728979755378,2197013877114691,3607466317118210,5922149224693895
mov $10,1
lpb $10,1
mov $5,2
mov $9,$0
sub $10,1
lpb $5,1
mov $0,$9
sub $0,1
sub $5,1
mov $7,2
lpb $7,1
sub $7,1
add $0,$7
sub $0,1
mov $2,$0
sub $2,1
mov $3,2
mov $6,0
lpb $0,1
sub $0,1
trn $2,$6
add $2,$0
mov $4,$6
add $6,$3
mov $3,$4
add $6,3
add $6,$2
lpe
mov $8,$7
lpb $8,1
mov $1,$6
sub $8,1
lpe
lpe
lpe
lpe
div $1,5
|
addi r6 r0 256 // load r0 its thread id
addi r6 r6 256 // load r0 its thread id
addi r6 r6 256 // load r0 its thread id
addi r6 r6 256 // load r0 its thread id
addi r6 r6 256 // load r0 its thread id
lbi r5 1
slbi r5 0x400
ld r26 r5 0
addi r26 r26 1 // loop
addi r6 r6 -1 // Increment r6 by 1
st r5 r26 0
bneq r6 r0 -5
kill r1 |
#include<iostream>
using namespace std;
struct node
{
int data;
node *prev;
node *next;
int size;
}*front,*rear;
node *getNode(int data)
{
node *newNode=(node *)malloc(sizeof(node));
newNode->data=data;
newNode->prev=newNode->next=NULL;
}
void insert_front(int data)
{
node *newNode=getNode(data);
if(newNode==NULL)
{
cout<<"\nOVERFLOW";
}
else
{
newNode->next=front;
front->prev=newNode;
front=newNode;
}
}
void insert_rear(int data)
{
node *newNode=getNode(data);
if(newNode==NULL)
{
cout<<"\nOVERFLOW";
}
else
{
if(rear==NULL)
{
front=rear=newNode;
}else
{
newNode->prev=rear;
rear->next=newNode;
rear=newNode;
}
}
}
void delete_front()
{
node *temp = front;
front = front->next;
if (front == NULL)
rear = NULL;
else
front->prev = NULL;
free(temp);
}
void delete_rear()
{
node *temp = rear;
rear = rear->prev;
if (rear == NULL)
front = NULL;
else
rear->next = NULL;
free(temp);
}
void Display()
{
cout<<front->data<<"\n";
cout<<rear->data<<"\n";
}
int main(int argc, char const *argv[])
{
int ch,data;
char choice;
do{
cout<<"\n1.Insert at rear\n2.Delete at rear\n3.Insert at front\n4.Delete at front\n5.Display\n6.Exit";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\n\tEnter element to be inserted:";
cin>>data;
insert_rear(data);
break;
case 2:
delete_rear();
break;
case 3:
cout<<"\n\tEnter element to be inserted:";
cin>>data;
insert_front(data);
break;
case 4:
delete_front();
break;
case 5:
Display();
break;
case 6:
break;
}
cout<<"\n\tDo you want to continue?(y/n)";
cin>>choice;
}while(choice=='y'||choice=='Y');
return 0;
}
|
#include "ncurses_display.h"
#include <curses.h>
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include "format.h"
#include "system.h"
using std::string;
using std::to_string;
// 50 bars uniformly displayed from 0 - 100 %
// 2% is one bar(|)
std::string NCursesDisplay::ProgressBar(float percent) {
std::string result{"0%"};
int size{50};
float bars{percent * size};
for (int i{0}; i < size; ++i) {
result += i <= bars ? '|' : ' ';
}
string display{to_string(percent * 100).substr(0, 4)};
if (percent < 0.1 || percent == 1.0)
display = " " + to_string(percent * 100).substr(0, 3);
return result + " " + display + "/100%";
}
void NCursesDisplay::DisplaySystem(System& system, WINDOW* window) {
// start debug
// std::cout << "displaySystem" << std::endl;
// end debug
int row{0};
mvwprintw(window, ++row, 2, ("OS: " + system.OperatingSystem()).c_str());
mvwprintw(window, ++row, 2, ("Kernel: " + system.Kernel()).c_str());
mvwprintw(window, ++row, 2, "CPU: ");
wattron(window, COLOR_PAIR(1));
mvwprintw(window, row, 10, "");
wprintw(window, ProgressBar(system.Cpu().Utilization()).c_str());
wattroff(window, COLOR_PAIR(1));
mvwprintw(window, ++row, 2, "Memory: ");
wattron(window, COLOR_PAIR(1));
mvwprintw(window, row, 10, "");
wprintw(window, ProgressBar(system.MemoryUtilization()).c_str());
wattroff(window, COLOR_PAIR(1));
mvwprintw(window, ++row, 2,
("Total Processes: " + to_string(system.TotalProcesses())).c_str());
mvwprintw(
window, ++row, 2,
("Running Processes: " + to_string(system.RunningProcesses())).c_str());
mvwprintw(window, ++row, 2,
("Up Time: " + Format::ElapsedTime(system.UpTime())).c_str());
wrefresh(window);
}
void NCursesDisplay::DisplayProcesses(std::vector<Process>& processes,
WINDOW* window, int n) {
int row{0};
int const pid_column{2};
int const user_column{9};
int const cpu_column{16};
int const ram_column{26};
int const time_column{35};
int const command_column{46};
wattron(window, COLOR_PAIR(2));
mvwprintw(window, ++row, pid_column, "PID");
mvwprintw(window, row, user_column, "USER");
mvwprintw(window, row, cpu_column, "CPU[%%]");
mvwprintw(window, row, ram_column, "RAM[MB]");
mvwprintw(window, row, time_column, "TIME+");
mvwprintw(window, row, command_column, "COMMAND");
wattroff(window, COLOR_PAIR(2));
for (int i = 0; i < n; ++i) {
// Clear the line
mvwprintw(window, ++row, pid_column,
(string(window->_maxx - 2, ' ').c_str()));
mvwprintw(window, row, pid_column, to_string(processes[i].Pid()).c_str());
mvwprintw(window, row, user_column, processes[i].User().c_str());
float cpu = processes[i].CpuUtilization() * 100;
mvwprintw(window, row, cpu_column, to_string(cpu).substr(0, 4).c_str());
mvwprintw(window, row, ram_column, processes[i].Ram().c_str());
mvwprintw(window, row, time_column,
Format::ElapsedTime(processes[i].UpTime()).c_str());
mvwprintw(window, row, command_column,
processes[i].Command().substr(0, window->_maxx - 46).c_str());
}
}
void NCursesDisplay::Display(System& system, int n) {
// start debug
// std::cout << "Display" << std::endl;
// end debug
initscr(); // start ncurses
noecho(); // do not print input values
cbreak(); // terminate ncurses on ctrl + c
start_color(); // enable color
int x_max{getmaxx(stdscr)};
WINDOW* system_window = newwin(9, x_max - 1, 0, 0);
WINDOW* process_window =
newwin(3 + n, x_max - 1, system_window->_maxy + 1, 0);
while (1) {
init_pair(1, COLOR_BLUE, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
box(system_window, 0, 0);
box(process_window, 0, 0);
DisplaySystem(system, system_window);
DisplayProcesses(system.Processes(), process_window, n);
wrefresh(system_window);
wrefresh(process_window);
refresh();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
endwin();
}
|
;;; Test program of twi-controller.asm
;;;
;;- This program scans I²C devices and shows if a device on each address exists.
;;-
;;- To compile this file, the following files are required
;;- (These files are parts of the pAVRlib).
;;-
;;- - [[../twi-controller][twi-controller.asm]]
;;- - [[../usart][usart.asm]]
;;- - [[../usart-puts][usart-puts.asm]]
;;- - [[../usart-puthex][usart-puthex.asm]]
;;- - [[../bin2ascii][bin2ascii.asm]]
;;-
;;- See also: ~examples/README.org~
;;-
;;; ------------------------------------------------------------
;;; Define your device in device.inc or use
;;; .include "m8def.inc"
;;; and so on as usual.
.include "device.inc"
;;; .equ F_CPU = 1000000
;;; .equ USART_BAUD = 4800
;;; .equ F_SCL = 100000
;; ------------------------------------------------------------
.def SLA = r21
;;; ------------------------------------------------------------
RESET:
ldi r16, low(RAMEND)
out SPL, r16
ldi r16, high(RAMEND)
out SPH, r16
rcall USART_INITIALIZE
ldi r24, 0x0d
rcall USART_TRANSMIT
ldi r24, 0x0a
rcall USART_TRANSMIT
ldi r25, high(STR_SEARCHING)
ldi r24, low (STR_SEARCHING)
rcall USART_PUTS
rcall TWI_INITIALIZE
.equ IICSTART = 0b0001000
.equ IICEND = 0b1110111
ldi SLA, IICSTART
SEARCH:
push r24
mov r24, SLA
rcall USART_PUTHEX
ldi r24, ' '
rcall USART_TRANSMIT
ldi r24, '('
rcall USART_TRANSMIT
mov r24, SLA
lsl r24
rcall USART_PUTHEX
ldi r24, ')'
rcall USART_TRANSMIT
pop r24
; send start bit
rcall TWI_SEND_S
cpi TWISTAT, $08
brne ERROR
; send slave address
mov r24, SLA
rcall TWI_SEND_SLA_R
; send stop bit
rcall TWI_SEND_P
cpi TWISTAT, $40
breq FOUND
NOTFOUND:
#ifdef TWITEST_SHOW_NOTFOUND
ldi r25, high(STR_NOTFOUND)
ldi r24, low (STR_NOTFOUND)
rcall USART_PUTS
#else
ldi r24, 0x0d
rcall USART_TRANSMIT
#endif
rjmp NEXTLOOP
FOUND:
ldi r25, high(STR_FOUND)
ldi r24, low (STR_FOUND)
rcall USART_PUTS
NEXTLOOP:
inc SLA
cpi SLA, (IICEND + 1)
breq EXIT
rjmp SEARCH
EXIT:
ldi r24, ' '
rcall USART_TRANSMIT
ldi r24, ' '
rcall USART_TRANSMIT
ldi r24, ' '
rcall USART_TRANSMIT
ldi r24, ' '
rcall USART_TRANSMIT
ldi r24, ' '
rcall USART_TRANSMIT
ldi r24, ' '
rcall USART_TRANSMIT
ldi r24, ' '
rcall USART_TRANSMIT
ldi r24, ' '
rcall USART_TRANSMIT
ldi r24, $0d
rcall USART_TRANSMIT
ldi r25, high(STR_FINISH)
ldi r24, low (STR_FINISH)
rcall USART_PUTS
END:
rjmp END
ERROR:
ldi r25, high(STR_ERROR)
ldi r24, low (STR_ERROR)
rcall USART_PUTS
ldi r24, ':'
rcall USART_TRANSMIT
mov r24, TWISTAT
rcall USART_PUTHEX
ldi r24, $0d
rcall USART_TRANSMIT
ldi r24, $0a
rcall USART_TRANSMIT
rjmp END
; ------------------------------------------------------------
.include "twi-controller.asm"
.include "usart.asm"
.include "usart-puts.asm"
.include "usart-puthex.asm"
.include "bin2ascii.asm"
; ------------------------------------------------------------
STR_SEARCHING: .db "searching i2c devices...", 0x0d, 0x0a, 0, 0
STR_ERROR: .db "Error", 0
STR_FOUND: .db ": Found", 0x0d, 0x0a, 0
STR_NOTFOUND: .db ": Not Found", 0x0d, 0x0a, 0
STR_FINISH: .db "Scan finished", 0x0d, 0x0a, 0
|
#!/usr/local/bin/zasm -o original/
#target ram
#code CODE,0
#code RAM
#code ROM
#code ROP
#data DATA
#code GSINIT
#test TEST, 0xC000
#include "k2-rope-core-macros.s"
#include "k2-rope-core.s"
#include "k2-rope-core-macros.s"
|
; A024183: Second elementary symmetric function of 3,4,...,n+3.
; 12,47,119,245,445,742,1162,1734,2490,3465,4697,6227,8099,10360,13060,16252,19992,24339,29355,35105,41657,49082,57454,66850,77350,89037,101997,116319,132095,149420,168392,189112,211684,236215,262815,291597,322677,356174,392210,430910,472402,516817,564289,614955,668955,726432,787532,852404,921200,994075,1071187,1152697,1238769,1329570,1425270,1526042,1632062,1743509,1860565,1983415,2112247,2247252,2388624,2536560,2691260,2852927,3021767,3197989,3381805,3573430,3773082,3980982,4197354,4422425,4656425,4899587,5152147,5414344,5686420,5968620,6261192,6564387,6878459,7203665,7540265,7888522,8248702,8621074,9005910,9403485,9814077,10237967,10675439,11126780,11592280,12072232,12566932,13076679,13601775,14142525
add $0,3
lpb $0
add $1,$2
add $3,1
add $3,$0
sub $0,1
trn $1,4
add $2,$3
add $2,$0
lpe
mov $0,$1
|
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <ostream>
#include <vector>
#include <include/utility.h>
namespace PaddleOCR {
std::vector<std::string> Utility::ReadDict(const std::string &path) {
std::ifstream in(path);
std::string line;
std::vector<std::string> m_vec;
if (in) {
while (getline(in, line)) {
m_vec.push_back(line);
}
} else {
std::cout << "no such label file: " << path << ", exit the program..."
<< std::endl;
exit(1);
}
return m_vec;
}
void Utility::VisualizeBboxes(
const cv::Mat &srcimg,
const std::vector<std::vector<std::vector<int>>> &boxes) {
cv::Point rook_points[boxes.size()][4];
for (int n = 0; n < boxes.size(); n++) {
for (int m = 0; m < boxes[0].size(); m++) {
rook_points[n][m] = cv::Point(int(boxes[n][m][0]), int(boxes[n][m][1]));
}
}
cv::Mat img_vis;
srcimg.copyTo(img_vis);
for (int n = 0; n < boxes.size(); n++) {
const cv::Point *ppt[1] = {rook_points[n]};
int npt[] = {4};
cv::polylines(img_vis, ppt, npt, 1, 1, CV_RGB(0, 255, 0), 2, 8, 0);
}
cv::imwrite("./ocr_vis.png", img_vis);
std::cout << "The detection visualized image saved in ./ocr_vis.png.pn"
<< std::endl;
}
} // namespace PaddleOCR |
; **************************************************
; PSGlib - C programming library for the SEGA PSG
; ( part of devkitSMS - github.com/sverx/devkitSMS )
; **************************************************
INCLUDE "PSGlib_private.inc"
SECTION code_clib
SECTION code_PSGlib
PUBLIC asm_PSGlib_SetMusicVolumeAttenuation
EXTERN __PSGlib_MusicStatus, __PSGlib_Channel2SFX, __PSGlib_Channel3SFX
EXTERN __PSGlib_MusicVolumeAttenuation
EXTERN __PSGlib_Chan0Volume, __PSGlib_Chan1Volume, __PSGlib_Chan2Volume, __PSGlib_Chan3Volume
asm_PSGlib_SetMusicVolumeAttenuation:
; void PSGSetMusicVolumeAttenutation (void)
; sets the volume attenuation for the music (0-15)
;
; enter : l = volume attenuation (0-15)
;
; uses : af
ld a,l
ld (__PSGlib_MusicVolumeAttenuation),a
ld a,(__PSGlib_MusicStatus)
or a
ret z
ld a,(__PSGlib_Chan0Volume)
add a,l
cp 16
jr c, outchan0
ld a,15
outchan0:
or PSGLatch|PSGChannel0|PSGVolumeData
out (PSGPort),a
ld a,(__PSGlib_Chan1Volume)
add a,l
cp 16
jr c, outchan1
ld a,15
outchan1:
or PSGLatch|PSGChannel1|PSGVolumeData
out (PSGPort),a
ld a,(__PSGlib_Channel2SFX)
or a
jr nz, skipchan2
ld a,(__PSGlib_Chan2Volume)
add a,l
cp 16
jr c, outchan2
ld a,15
outchan2:
or PSGLatch|PSGChannel2|PSGVolumeData
out (PSGPort),a
skipchan2:
ld a,(__PSGlib_Channel3SFX)
or a
ret nz
ld a,(__PSGlib_Chan3Volume)
add a,l
cp 16
jr c, outchan3
ld a,15
outchan3:
or PSGLatch|PSGChannel3|PSGVolumeData
out (PSGPort),a
ret
|
; A093230: a(n) is the largest number such that all of a(n)'s length-n substrings are distinct and divisible by 30.
; 0,900,99000,9990000,999900000,99999000000,9999990000000,999999900000000,99999999000000000,9999999990000000000,999999999900000000000,99999999999000000000000,9999999999990000000000000,999999999999900000000000000,99999999999999000000000000000
mov $1,10
pow $1,$0
bin $1,2
div $1,45
mul $1,900
mov $0,$1
|
; A005367: a(n) = 2*(2^n + 1)*(2^(n+1) - 1).
; 4,18,70,270,1054,4158,16510,65790,262654,1049598,4196350,16781310,67117054,268451838,1073774590,4295032830,17180000254,68719738878,274878431230,1099512676350,4398048608254,17592190238718,70368752566270,281474993487870,1125899940397054,4503599694479358,18014398643699710,72057594306363390,288230376688582654,1152921505680588798,4611686020574871550,18446744078004518910,73786976303428141054,295147905196532695038,1180591620751771041790,4722366482938364690430,18889465931616019808254
mov $1,2
pow $1,$0
mul $1,2
add $1,1
bin $1,2
sub $1,1
mul $1,2
mov $0,$1
|
RASTER = $2f ;Hier beginnen die Linien
;*** Startadresse
*=$0801
;** BASIC-Zeile: 2018 SYS 2064:NEW
!word main-2, 2018
!byte $9e
!text " 2064:"
!byte $a2,$00,$00,$00
main
sei ;IRQs sperren
lda #<myIRQ ;Adresse unserer Routine in
sta $0314 ;den RAM-Vektor
lda #>myIRQ
sta $0315
lda #%00000001 ;Raster-IRQs vom VIC-II aktivieren
sta $d01a
lda #RASTER ;Hier soll unser Interrupt auftreten
sta $d012
lda $d011 ;Zur Sicherheit höchstes BIT
and #%01111111 ;für die Rasterzeile löschen
;*** TEST TEST TEST ***
;and #%11101111 ;BS-Ausgabe abschalten
;*** TEST TEST TEST ***
sta $D011
lda #%0111111 ;Timer-IRQs abschalten
sta $dc0d
lda $dc0d ;zur Sicherheit bestätigen
lda #%00000001 ;Sicherheitshalber auch den
sta $d019 ;Raster-IRQ bestätigen
cli ;Interrupts erlauben
rts ;zurück zum BASIC
!align 1023,0
myIRQ
;*** Wenn wir hier landen, sind bereits 38-45 Taktzyklen in der
;*** aktuellen Rasterzeile (ab jetzt als STARTROW bezeichnet) vergangen!
;*** zweiten IRQ einrichten
;*** da die Zeit bei aktivierten ROM nicht reicht, können wir den
;*** 2. Raster-IRQ erst in der übernächsten Zeile (STARTROW+2) bekommen.
lda #<doubleIRQ ;(2 TZ) 2. Raster-IRQ einrichten
sta $0314 ;(4 TZ)
lda #>doubleIRQ ;(2 TZ)
sta $0315 ;(4 TZ)
tsx ;(2 TZ) Stackpointer im X-Reg. retten
stx doubleIRQ+1 ;(4 TZ) und fürs zurückholen sichern!
nop ;(2 TZ)
nop ;(2 TZ)
nop ;(2 TZ)
lda #%00000001 ;(2 TZ) 1. Raster-IRQ später bestätigen
;------
;26 TZ
;*** Jetzt sind 64-71 Taktzyklen vergangen und wir sind
;*** auf jeden Fall in nächsten Rasterzeile (STARTROW+1)!
;*** Verbraucht wurden dort 1-8 TZ
inc $D012 ;(6 TZ) 2. IRQ in der übernächsten Zeile STARTROW+2
; $D012 wurde bereits automatisch erhöht
sta $D019 ;(4 TZ) IRQ bestätigen
cli ;(2 TZ) Interrupts für den 2. Raster-IRQ
; wieder freigeben
;*** Wir befinden uns immer noch in Rasterzeile STARTROW+1 und
;*** haben bisher 13-20 Zyklen verbraucht
;*** etwas Zeit verschwenden...
ldx #$08 ; 2 TZ
dex ;8 * 2 TZ = 16 TZ
bne *-1 ;7 * 3 TZ = 21 TZ
;1 * 2 TZ = 2 TZ
; ------
; 41 TZ
;*** Bis hier sind 54-61 Taktzyklen vergangen, jetzt auf den IRQ warten...
;*** Der nächste Rasterinterrupt wird während dieser NOPs auftreten!
nop ;2 TZ (56)
nop ;2 TZ (58)
nop ;2 TZ (60)
nop ;2 TZ (62)
nop ;2 TZ (64)
nop ;2 TZ (66)
doubleIRQ
;*** Wir sind nun in Rasterzeile STARTROW+2 und
;*** haben bisher genau 38 oder 39 Taktzyklen benötigt!!
;*** Wir können so sicher sein, da der IRQ während der NOPs auftrat.
;*** Jetzt exakt soviele Taktzyklen 'verschwenden', wie in
;*** dieser Zeile noch zu verarbeiten sind (also 24 oder 25).
ldx #$00 ;(2 TZ) Platzhalter für 1. Stackpointer
txs ;(2 TZ) Stackpointer vom 1. IRQ wiederherstellen
nop ;(2 TZ)
nop ;(2 TZ)
nop ;(2 TZ)
bit $01 ;(3 TZ)
lda #$0c ;(2 TZ) grau als 'Hauptfarbe' in den Akku
ldy #$00 ;(2 TZ) 'Zeilenfarbe' schwarz ins Y-Reg. laden
ldx $d012 ;(4 TZ)
cpx $d012 ;(4 TZ) sind wir noch in Rasterzeile STARTROW+2?
;======
;25 TZ = 63 oder 64 TZ!!!
beq myIRQMain ;(3 TZ) wenn JA einen letzten Takt 'verschwenden'
;(2 TZ) sonst einfach weiterlaufen...
;*** Wir beginnen also immer exakt nach 3 TZ in der dritten Rasterzeile (STARTROW+3)
;*** nach dem 1. Raster-IRQ (den hatten wir ja für Zeile STARTROW festgelegt
myIRQMain
; 3TZ (s. oben)
sty $D020 ; 4TZ schwarz
iny ; 2TZ
sty $D020 ; 4TZ weiß
dey ; 2TZ
sty $D020 ; 4TZ s
iny ; 2TZ
sty $D020 ; 4TZ w
dey ; 2TZ
sty $D020 ; 4TZ s
iny ; 2TZ
sty $D020 ; 4TZ w
dey ; 2TZ
sty $D020 ; 4TZ s
iny ; 2TZ
sty $D020 ; 4TZ w
dey ; 2TZ
sty $D020 ; 4TZ s
iny ; 2TZ
sty $D020 ; 4TZ w
;====
;61TZ
sta $D020 ; 4TZ grau
lda #<myIRQ ;Original IRQ-Vektor setzen
sta $0314
lda #>myIRQ
sta $0315
lda #RASTER ;ursprüngliche Rasterzeile zurücksetzen
sta $d012
lda #%00000001 ;IRQ bestätigen
sta $d019
jmp $ea31 ;zum Schluß zum 'Timer-Interrupt' springen |
; A248572: a(n) = 29*n + 1.
; 1,30,59,88,117,146,175,204,233,262,291,320,349,378,407,436,465,494,523,552,581,610,639,668,697,726,755,784,813,842,871,900,929,958,987,1016,1045,1074,1103,1132,1161,1190,1219,1248,1277,1306,1335,1364,1393,1422,1451,1480,1509,1538,1567,1596,1625,1654,1683,1712,1741,1770,1799,1828,1857,1886,1915,1944,1973,2002,2031,2060,2089,2118,2147,2176,2205,2234,2263,2292,2321,2350,2379,2408,2437,2466,2495,2524,2553,2582,2611,2640,2669,2698,2727,2756,2785,2814,2843,2872,2901,2930,2959,2988,3017,3046,3075,3104,3133,3162,3191,3220,3249,3278,3307,3336,3365,3394,3423,3452,3481,3510,3539,3568,3597,3626,3655,3684,3713,3742,3771,3800,3829,3858,3887,3916,3945,3974,4003,4032,4061,4090,4119,4148,4177,4206,4235,4264,4293,4322,4351,4380,4409,4438,4467,4496,4525,4554,4583,4612,4641,4670,4699,4728,4757,4786,4815,4844,4873,4902,4931,4960,4989,5018,5047,5076,5105,5134,5163,5192,5221,5250,5279,5308,5337,5366,5395,5424,5453,5482,5511,5540,5569,5598,5627,5656,5685,5714,5743,5772,5801,5830,5859,5888,5917,5946,5975,6004,6033,6062,6091,6120,6149,6178,6207,6236,6265,6294,6323,6352,6381,6410,6439,6468,6497,6526,6555,6584,6613,6642,6671,6700,6729,6758,6787,6816,6845,6874,6903,6932,6961,6990,7019,7048,7077,7106,7135,7164,7193,7222
mov $1,$0
mul $1,29
add $1,1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r14
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0xb697, %rsi
lea addresses_UC_ht+0x6957, %rdi
nop
nop
nop
nop
nop
add %r13, %r13
mov $37, %rcx
rep movsq
nop
nop
nop
inc %r12
lea addresses_UC_ht+0x2b7, %rax
nop
nop
nop
nop
add %r14, %r14
mov $0x6162636465666768, %rdi
movq %rdi, (%rax)
nop
nop
nop
nop
nop
xor $20027, %r14
lea addresses_normal_ht+0x10a57, %r14
nop
nop
nop
nop
and %rdi, %rdi
mov $0x6162636465666768, %rax
movq %rax, (%r14)
nop
nop
nop
nop
nop
cmp $61115, %r13
lea addresses_A_ht+0x16557, %rsi
lea addresses_UC_ht+0xc340, %rdi
nop
nop
cmp %rbx, %rbx
mov $41, %rcx
rep movsw
and $18148, %r14
lea addresses_UC_ht+0x8f7d, %rcx
cmp %r12, %r12
mov $0x6162636465666768, %r13
movq %r13, %xmm3
vmovups %ymm3, (%rcx)
nop
nop
xor $12636, %rax
lea addresses_D_ht+0xaf, %rax
nop
nop
nop
nop
and %rdi, %rdi
mov (%rax), %cx
nop
nop
nop
xor %rsi, %rsi
lea addresses_A_ht+0x1d557, %rsi
lea addresses_UC_ht+0x7d57, %rdi
nop
nop
nop
nop
nop
inc %r13
mov $117, %rcx
rep movsq
nop
nop
nop
nop
add %rsi, %rsi
lea addresses_A_ht+0x44f0, %rsi
lea addresses_WC_ht+0x605d, %rdi
xor %rax, %rax
mov $5, %rcx
rep movsl
cmp $52085, %r13
lea addresses_D_ht+0x6e57, %rcx
nop
nop
cmp %rsi, %rsi
mov $0x6162636465666768, %rbx
movq %rbx, (%rcx)
nop
nop
nop
nop
sub %rdi, %rdi
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r14
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r13
push %r14
push %r9
push %rdi
push %rdx
// Store
lea addresses_D+0x1ad57, %r14
nop
sub %rdi, %rdi
movw $0x5152, (%r14)
nop
nop
nop
nop
inc %rdx
// Faulty Load
lea addresses_normal+0x14d57, %r14
nop
nop
nop
nop
nop
and $60451, %r11
mov (%r14), %rdi
lea oracles, %r12
and $0xff, %rdi
shlq $12, %rdi
mov (%r12,%rdi,1), %rdi
pop %rdx
pop %rdi
pop %r9
pop %r14
pop %r13
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 11}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 10, 'type': 'addresses_UC_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 7}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_UC_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 1}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 3}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}}
{'OP': 'REPM', 'src': {'same': True, 'congruent': 0, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 1, 'type': 'addresses_WC_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 8}}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
;; Utilities for biboot:
;; printing, reading from disk, etc.
;; initialize video
_init_video:
push ax
mov ax, 0x0003
int 0x10
pop ax
ret
;; printf, prints to output.
;; usage:
;; mov bx, [str]
;; call printf
printf:
mov ah, 0x0e
.Loop: ;; Loop
cmp [bx], byte 0 ;; Compare bx to \0,
je .Exit ;; If it is \0, return
mov al, [bx]
int 0x10
inc bx
jmp .Loop ;; Loop
.Exit:
ret
;; print hex value
;; usage:
;; push [register]
;; call print_hex_word
print_hex_word:
mov bx, prefix
call printf
push bp
mov bp, sp ;; BP=SP, on 8086 can't use sp in memory operand
push dx ;; Save all registers we clobber
push cx
push bx
push ax
mov cx, 0x0404 ;; CH = number of nibbles to process = 4 (4*4=16 bits)
;; CL = Number of bits to rotate each iteration = 4 (a nibble)
mov dx, [bp+4] ;; DX = word parameter on stack at [bp+4] to print
mov bx, [bp+6] ;; BX = page / foreground attr is at [bp+6]
.loop:
rol dx, cl ;; Roll 4 bits left. Lower nibble is value to print
mov ax, 0x0e0f ;; AH=0E (BIOS tty print),AL=mask to get lower nibble
and al, dl ;; AL=copy of lower nibble
add al, 0x90 ;; Work as if we are packed BCD
daa ;; Decimal adjust after add.
;; If nibble in AL was between 0 and 9, then CF=0 and
;; AL=0x90 to 0x99
;; If nibble in AL was between A and F, then CF=1 and
;; AL=0x00 to 0x05
adc al, 0x40 ;; AL=0xD0 to 0xD9
;; or AL=0x41 to 0x46
daa ;; AL=0x30 to 0x39 (ASCII '0' to '9')
;; or AL=0x41 to 0x46 (ASCII 'A' to 'F')
int 0x10 ;; Print ASCII character in AL
dec ch
jnz .loop ;; Go back if more nibbles to process
pop ax ;; Restore registers
pop bx
pop cx
pop dx
pop bp
ret
prefix: db "0x", 0
;; So it's initializing stuff
_init:
;; print first thing
mov bx, splash1
call printf
;; print second thing
mov bx, splash2
call printf
;; print 3rd and final thing
mov bx, splash3
call printf
ret
splash1: db "Welcome to BiBoot", 13, 10, 0
splash2: db "Press 1 to boot default location (0x8000)", 13, 10, 0
splash3: db "Press 2 to load shell (TODO)", 13, 10, 0
|
; A020478: Number of singular 2 X 2 matrices over Z(n) (i.e., with determinant = 0).
; Submitted by Jon Maiga
; 1,10,33,88,145,330,385,736,945,1450,1441,2904,2353,3850,4785,6016,5185,9450,7201,12760,12705,14410,12673,24288,18625,23530,26001,33880,25201,47850,30721,48640,47553,51850,55825,83160,51985,72010,77649,106720,70561,127050,81313,126808,137025,126730,105985,198528,134113,186250,171105,207064,151633,260010,208945,283360,237633,252010,208801,421080,230641,307210,363825,391168,341185,475530,305185,456280,418209,558250,362881,695520,394273,519850,614625,633688,554785,776490,499201,872320,706401,705610
add $0,1
pow $0,2
sub $0,1
seq $0,78430 ; Sum of gcd(k^2,n) for 1 <= k <= n.
|
SECTION code_clib
SECTION code_sound_bit
PUBLIC asm_bit_close
INCLUDE "config_private.inc"
EXTERN __sound_bit_state
asm_bit_close:
; enter : a = output byte used for 1-bit sound
;
; uses : af, c
ld c,a
ld a,(__sound_bit_state)
and __SOUND_BIT_WRITE_MASK
or c
ld (__sound_bit_state),a
ret
|
; A041146: Numerators of continued fraction convergents to sqrt(83).
; Submitted by Jon Maiga
; 9,82,1485,13447,243531,2205226,39937599,361643617,6549522705,59307347962,1074081786021,9726043422151,176142863384739,1595011813884802,28886355513311175,261572211433685377,4737186161319647961,42896247663310517026,776869644100908954429,7034723044571491106887,127401884446387748878395,1153651683062061231012442,20893132179563489907102351,189191841299133470394933601,3426346275563965957015907169,31026308321374827083538098122,561899896060310853460701673365,5088125372864172508229853158407
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
mov $3,$1
mov $1,$2
dif $2,2
mul $2,9
add $3,$2
lpe
mov $0,$3
|
TITLE SRCINST - Copyright (C) 1994 SLR Systems
INCLUDE MACROS
INCLUDE MODULES
PUBLIC SRCNAME_INSTALL
.DATA
EXTERNDEF SYMBOL_TEXT:BYTE
EXTERNDEF THEADR_HASH:DWORD,SYMBOL_LENGTH:DWORD,SRC_COUNT:DWORD,MOD_FIRST_SRC_GINDEX:DWORD
EXTERNDEF THEADR_HASH_TABLE_PTR:DWORD,MOD_LAST_SRC_GINDEX:DWORD
EXTERNDEF SRC_GARRAY:STD_PTR_S
.CODE PASS1_TEXT
EXTERNDEF CASE_STRING_COMPARE_HARD:PROC
INIT_SRCINST PROC
;
;SAVE REGS, ZERO OUT HASH TABLE
;
MOV EDI,EBX
MOV ECX,THEADR_HASH
XOR EAX,EAX
REP STOSD
JMP SRC_CONT
INIT_SRCINST ENDP
SRCNAME_INSTALL PROC
;
;DX IS HASH VALUE, CONVERT IT, TEXT IS IN SYMBOL_TEXT
;ES MUST BE DGROUP
;
;RETURN AX IS GINDEX, DS:BX IS PHYSICAL
;
;DESTROYS ES,DS,DI,SI,DX,CX
;
PUSH EBX
MOV EAX,MOD_FIRST_SRC_GINDEX
MOV EBX,THEADR_HASH_TABLE_PTR
TEST EAX,EAX
PUSH EDI
JZ INIT_SRCINST
SRC_CONT::
MOV EAX,EDX
XOR EDX,EDX
MOV EDI,EAX
HASHDIV THEADR_HASH
PUSH ESI
MOV EAX,DPTR [EBX+EDX*4]
LEA EBX,[EBX+EDX*4 -SRC_STRUCT._SRC_NEXT_HASH_GINDEX]
SRCNAME_NEXT:
TEST EAX,EAX
JZ DO_SRCNAME_INSTALL
MOV EDX,EAX ;SAVE LOGICAL IN EDX
CONVERT EAX,EAX,SRC_GARRAY
ASSUME EAX:PTR SRC_STRUCT
MOV EBX,EAX
ASSUME EBX:PTR SRC_STRUCT
MOV ECX,[EAX]._SRC_HASH ;CATCHES
MOV EAX,[EAX]._SRC_NEXT_HASH_GINDEX
CMP ECX,EDI
JNZ SRCNAME_NEXT
;
;HASH MATCHED, TRY ACTUAL TEXT COMPARE...
;
PUSH EDI
MOV EDI,OFF SYMBOL_TEXT
MOV ECX,SYMBOL_LENGTH
LEA ESI,[EBX]._SRC_TEXT
CALL CASE_STRING_COMPARE_HARD
POP EDI
MOV EAX,[EBX]._SRC_NEXT_HASH_GINDEX
JNZ SRCNAME_NEXT
MOV EAX,EDX
MOV ECX,EBX
POPM ESI,EDI,EBX
RET
DO_SRCNAME_INSTALL:
;
;EBX GETS POINTER...DI IS HASH
;
MOV EAX,SYMBOL_LENGTH
MOV EDX,EDI
ADD EAX,SIZE SRC_STRUCT-3
TILLP2_POOL_ALLOC ;EAX IS PHYS
MOV ESI,EBX
MOV EBX,EAX
MOV EDI,EAX
INSTALL_POINTER_GINDEX SRC_GARRAY
MOV [ESI].SRC_STRUCT._SRC_NEXT_HASH_GINDEX,EAX
MOV ESI,EAX ;SI IS NEW GINDEX
MOV ECX,SRC_STRUCT._SRC_TEXT/4
XOR EAX,EAX
REP STOSD
MOV ECX,SYMBOL_LENGTH
MOV [EBX]._SRC_HASH,EDX
SHR ECX,2
MOV EAX,ESI ;NEW GINDEX
INC ECX
MOV EDX,SRC_COUNT
MOV ESI,OFF SYMBOL_TEXT
INC EDX
OPTI_MOVSD
MOV ECX,MOD_LAST_SRC_GINDEX
MOV SRC_COUNT,EDX
OR ECX,ECX
JNZ L4$
MOV MOD_FIRST_SRC_GINDEX,EAX
L5$:
MOV [EBX]._SRC_NUMBER,EDX
MOV MOD_LAST_SRC_GINDEX,EAX
MOV ECX,EBX
POPM ESI,EDI,EBX
RET
L4$:
CONVERT ECX,ECX,SRC_GARRAY
MOV [ECX].SRC_STRUCT._SRC_NEXT_GINDEX,EAX
JMP L5$
SRCNAME_INSTALL ENDP
END
|
#include <cstdio>
using namespace std;
int n;
char inp[15];
int main()
{
scanf("%d%s%s", &n, inp, inp);
if(inp[0]=='w')
{
if(n==1 || n==2 || n==3 || n==4 || n==7)
printf("%d\n", 52);
else
printf("%d\n", 53);
}
else
{
if(n<=29)
printf("%d\n", 12);
else if(n<=30)
printf("%d\n", 11);
else
printf("%d\n", 7);
}
}
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkBSplineDeformableTransform_hxx
#define itkBSplineDeformableTransform_hxx
#include "itkContinuousIndex.h"
#include "itkImageScanlineConstIterator.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkIdentityTransform.h"
namespace itk
{
// Constructor with default arguments
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::BSplineDeformableTransform()
: m_GridRegion(Superclass::m_CoefficientImages[0]->GetLargestPossibleRegion())
, m_GridOrigin(Superclass::m_CoefficientImages[0]->GetOrigin())
, m_GridSpacing(Superclass::m_CoefficientImages[0]->GetSpacing())
, m_GridDirection(Superclass::m_CoefficientImages[0]->GetDirection())
{
// Instantiate an identity transform
using IdentityTransformType = IdentityTransform<TParametersValueType, SpaceDimension>;
auto id = IdentityTransformType::New();
this->m_BulkTransform = id;
// Setup variables for computing interpolation
this->m_Offset = SplineOrder / 2;
if (SplineOrder % 2)
{
this->m_SplineOrderOdd = true;
}
else
{
this->m_SplineOrderOdd = false;
}
this->m_ValidRegion = this->m_GridRegion; // HACK: Perhaps this->m_ValidRegion is redundant also.
this->m_ValidRegionFirst.Fill(0);
this->m_ValidRegionLast.Fill(1);
/** Fixed Parameters store the following information:
* Grid Size
* Grid Origin
* Grid Spacing
* Grid Direction
* The size of these is equal to the NInputDimensions
*/
// For example 3D image has FixedParameters of:
// [size[0],size[1],size[2],
// origin[0],origin[1],origin[2],
// spacing[0],spacing[1],spacing[2],
// dir[0][0],dir[1][0],dir[2][0],
// dir[0][1],dir[1][1],dir[2][1],
// dir[0][2],dir[1][2],dir[2][2]]
this->SetFixedParametersFromTransformDomainInformation();
}
// Get the number of parameters
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
auto
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::GetNumberOfParameters() const
-> NumberOfParametersType
{
// The number of parameters equal SpaceDimension * number of
// of pixels in the grid region.
return static_cast<NumberOfParametersType>(SpaceDimension * this->m_GridRegion.GetNumberOfPixels());
}
// Get the number of parameters per dimension
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
auto
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::GetNumberOfParametersPerDimension() const
-> NumberOfParametersType
{
// The number of parameters per dimension equal number of
// of pixels in the grid region.
return static_cast<NumberOfParametersType>(this->m_GridRegion.GetNumberOfPixels());
}
// Set the grid region
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::UpdateValidGridRegion()
{
// Set the valid region
// If the grid spans the interval [start, last].
// The valid interval for evaluation is [start+offset, last-offset]
// when spline order is even.
// The valid interval for evaluation is [start+offset, last-offset)
// when spline order is odd.
// Where offset = floor(spline / 2 ).
// Note that the last pixel is not included in the valid region
// with odd spline orders.
typename RegionType::SizeType size;
typename RegionType::IndexType index;
for (unsigned int j = 0; j < NDimensions; ++j)
{
index[j] = this->m_GridRegion.GetIndex()[j];
size[j] = this->m_GridRegion.GetSize()[j];
index[j] += static_cast<typename RegionType::IndexValueType>(this->m_Offset);
size[j] -= static_cast<typename RegionType::SizeValueType>(2 * this->m_Offset);
this->m_ValidRegionFirst[j] = index[j];
this->m_ValidRegionLast[j] = index[j] + static_cast<typename RegionType::IndexValueType>(size[j]) - 1;
}
this->m_ValidRegion.SetSize(size);
this->m_ValidRegion.SetIndex(index);
}
// Set the grid region
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::SetGridRegion(const RegionType & region)
{
if (this->m_GridRegion != region)
{
this->m_CoefficientImages[0]->SetRegions(region);
// set regions for each coefficient image
for (unsigned int j = 1; j < SpaceDimension; ++j)
{
this->m_CoefficientImages[j]->SetRegions(region);
}
this->UpdateValidGridRegion();
//
// If we are using the default parameters, update their size and set to
// identity.
//
// Check if we need to resize the default parameter buffer.
if (this->m_InternalParametersBuffer.GetSize() != this->GetNumberOfParameters())
{
this->m_InternalParametersBuffer.SetSize(this->GetNumberOfParameters());
// Fill with zeros for identity.
this->m_InternalParametersBuffer.Fill(0);
}
this->SetFixedParametersGridSizeFromTransformDomainInformation();
this->Modified();
}
}
// Set the grid spacing
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::SetGridSpacing(const SpacingType & spacing)
{
if (this->m_GridSpacing != spacing)
{
this->m_CoefficientImages[0]->SetSpacing(spacing);
// set spacing for each coefficient image
for (unsigned int j = 1; j < SpaceDimension; ++j)
{
this->m_CoefficientImages[j]->SetSpacing(spacing);
}
this->SetFixedParametersGridSpacingFromTransformDomainInformation();
this->Modified();
}
}
// Set the grid direction
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::SetGridDirection(
const DirectionType & direction)
{
if (this->m_GridDirection != direction)
{
this->m_CoefficientImages[0]->SetDirection(direction);
// set direction for each coefficient image
for (unsigned int j = 1; j < SpaceDimension; ++j)
{
this->m_CoefficientImages[j]->SetDirection(direction);
}
this->SetFixedParametersGridDirectionFromTransformDomainInformation();
this->Modified();
}
}
// Set the grid origin
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::SetGridOrigin(const OriginType & origin)
{
if (this->m_GridOrigin != origin)
{
this->m_CoefficientImages[0]->SetOrigin(origin);
// set spacing for each coefficient image
for (unsigned int j = 1; j < SpaceDimension; ++j)
{
this->m_CoefficientImages[j]->SetOrigin(origin);
}
this->SetFixedParametersGridOriginFromTransformDomainInformation();
this->Modified();
}
}
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::
SetCoefficientImageInformationFromFixedParameters()
{
// Fixed Parameters store the following information:
// grid size
// grid origin
// grid spacing
// grid direction
// The size of these is equal to the NInputDimensions
{
// set the grid size parameters
SizeType gridSize;
for (unsigned int i = 0; i < NDimensions; ++i)
{
gridSize[i] = static_cast<int>(this->m_FixedParameters[i]);
}
RegionType bsplineRegion;
bsplineRegion.SetSize(gridSize);
this->SetGridRegion(bsplineRegion);
}
{
// Set the origin parameters
OriginType origin;
for (unsigned int i = 0; i < NDimensions; ++i)
{
origin[i] = this->m_FixedParameters[NDimensions + i];
}
this->SetGridOrigin(origin);
}
{
// Set the spacing parameters
SpacingType spacing;
for (unsigned int i = 0; i < NDimensions; ++i)
{
spacing[i] = this->m_FixedParameters[2 * NDimensions + i];
}
this->SetGridSpacing(spacing);
}
{
// Set the direction parameters
DirectionType direction;
for (unsigned int di = 0; di < NDimensions; ++di)
{
for (unsigned int dj = 0; dj < NDimensions; ++dj)
{
direction[di][dj] = this->m_FixedParameters[3 * NDimensions + (di * NDimensions + dj)];
}
}
this->SetGridDirection(direction);
}
}
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::
SetFixedParametersGridSizeFromTransformDomainInformation() const
{
// Set the grid size parameters
const SizeType & gridSize = this->m_CoefficientImages[0]->GetLargestPossibleRegion().GetSize();
for (unsigned int i = 0; i < NDimensions; ++i)
{
this->m_FixedParameters[i] = static_cast<FixedParametersValueType>(gridSize[i]);
}
}
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::
SetFixedParametersGridOriginFromTransformDomainInformation() const
{
// Set the origin parameters
const OriginType & origin = this->m_CoefficientImages[0]->GetOrigin();
for (unsigned int i = 0; i < NDimensions; ++i)
{
this->m_FixedParameters[NDimensions + i] = static_cast<FixedParametersValueType>(origin[i]);
}
}
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::
SetFixedParametersGridSpacingFromTransformDomainInformation() const
{
// Set the spacing parameters
const SpacingType & spacing = this->m_CoefficientImages[0]->GetSpacing();
for (unsigned int i = 0; i < NDimensions; ++i)
{
this->m_FixedParameters[2 * NDimensions + i] = static_cast<FixedParametersValueType>(spacing[i]);
}
}
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::
SetFixedParametersGridDirectionFromTransformDomainInformation() const
{
/** Set the direction parameters */
const DirectionType & direction = this->m_CoefficientImages[0]->GetDirection();
for (unsigned int di = 0; di < NDimensions; ++di)
{
for (unsigned int dj = 0; dj < NDimensions; ++dj)
{
this->m_FixedParameters[3 * NDimensions + (di * NDimensions + dj)] =
static_cast<FixedParametersValueType>(direction[di][dj]);
}
}
}
// Set the Fixed Parameters
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::SetFixedParameters(
const FixedParametersType & passedParameters)
{
// check if the number of passedParameters match the
// expected number of this->m_FixedParameters
if (passedParameters.Size() == this->m_FixedParameters.Size())
{
for (unsigned int i = 0; i < NDimensions * (3 + NDimensions); ++i)
{
this->m_FixedParameters[i] = passedParameters[i];
}
}
else if (passedParameters.Size() == NDimensions * 3)
{
// This option was originally valid for backwards compatibility
// with BSplines saved to disk from before image orientation was used.
// Those transforms would no longer be valid with respect to images
// with explicit directions.
itkExceptionMacro(<< "Mismatched between parameters size " << passedParameters.size()
<< " and required number of fixed parameters " << this->m_FixedParameters.Size()
<< ". Implicit setting of identity direction is no longer supported.");
}
else
{
itkExceptionMacro(<< "Mismatched between parameters size " << passedParameters.size()
<< " and the required number of fixed parameters " << this->m_FixedParameters.Size());
}
this->SetCoefficientImageInformationFromFixedParameters();
}
// Set the B-Spline coefficients using input images
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::SetCoefficientImages(
const CoefficientImageArray & images)
{
bool validArrayOfImages = true;
for (unsigned int j = 0; j < SpaceDimension; ++j)
{
validArrayOfImages &= (images[0].IsNotNull());
}
if (validArrayOfImages)
{
// The BufferedRegion MUST equal the LargestPossibleRegion.
this->SetGridRegion(images[0]->GetLargestPossibleRegion());
this->SetGridOrigin(images[0]->GetOrigin());
this->SetGridSpacing(images[0]->GetSpacing());
this->SetGridDirection(images[0]->GetDirection());
const SizeValueType totalParameters = this->GetNumberOfParameters();
this->m_InternalParametersBuffer.SetSize(totalParameters);
for (unsigned int j = 0; j < SpaceDimension; ++j)
{
const SizeValueType numberOfPixels = images[j]->GetLargestPossibleRegion().GetNumberOfPixels();
if (numberOfPixels * SpaceDimension != totalParameters)
{
itkExceptionMacro(<< "SetCoefficientImage() has array of images that are "
<< "not the correct size. " << numberOfPixels * SpaceDimension << " != " << totalParameters
<< " for image at index " << j << " \n"
<< images[j]);
}
const ParametersValueType * const baseImagePointer = images[j]->GetBufferPointer();
ParametersValueType * dataPointer = this->m_InternalParametersBuffer.data_block();
std::copy_n(baseImagePointer, numberOfPixels, dataPointer);
}
this->SetParameters(this->m_InternalParametersBuffer);
}
else
{
itkExceptionMacro(<< "SetCoefficientImage() requires that an array of "
<< "correctly sized images be supplied.");
}
}
// Print self
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::PrintSelf(std::ostream & os,
Indent indent) const
{
this->Superclass::PrintSelf(os, indent);
os << indent << "ValidRegion: " << this->m_ValidRegion << std::endl;
os << indent << "BulkTransform: ";
os << this->m_BulkTransform.GetPointer() << std::endl;
os << indent << "WeightsFunction: ";
os << this->m_WeightsFunction.GetPointer() << std::endl;
if (this->m_BulkTransform)
{
os << indent << "BulkTransformType: " << this->m_BulkTransform->GetNameOfClass() << std::endl;
}
os << indent << "GridOrigin: " << this->m_GridOrigin << std::endl;
os << indent << "GridSpacing: " << this->m_GridSpacing << std::endl;
os << indent << "GridDirection: " << this->m_GridDirection << std::endl;
os << indent << "GridRegion: " << this->m_GridRegion << std::endl;
}
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
bool
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::InsideValidRegion(
ContinuousIndexType & index) const
{
bool inside = true;
if (inside && this->m_SplineOrderOdd)
{
using ValueType = typename ContinuousIndexType::ValueType;
for (unsigned int j = 0; j < SpaceDimension; ++j)
{
if (index[j] >= static_cast<ValueType>(this->m_ValidRegionLast[j]))
{
inside = false;
break;
}
if (index[j] < static_cast<ValueType>(this->m_ValidRegionFirst[j]))
{
inside = false;
break;
}
}
}
return inside;
}
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::TransformPoint(
const InputPointType & inputPoint,
OutputPointType & outputPoint,
WeightsType & weights,
ParameterIndexArrayType & indices,
bool & inside) const
{
inside = true;
InputPointType point = inputPoint;
if (this->m_BulkTransform)
{
point = this->m_BulkTransform->TransformPoint(point);
}
// if no coefficients are set, this isn't a proper BSpline Transform
if (this->m_CoefficientImages[0]->GetBufferPointer() == nullptr)
{
itkExceptionMacro("B-spline coefficients have not been set");
}
ContinuousIndexType index =
this->m_CoefficientImages[0]->template TransformPhysicalPointToContinuousIndex<TParametersValueType>(inputPoint);
// NOTE: if the support region does not lie totally within the grid
// we assume zero displacement and return the input point
inside = this->InsideValidRegion(index);
if (!inside)
{
outputPoint = point;
return;
}
IndexType supportIndex;
// Compute interpolation weights
this->m_WeightsFunction->Evaluate(index, weights, supportIndex);
// For each dimension, correlate coefficient with weights
constexpr SizeType supportSize = WeightsFunctionType::SupportSize;
const RegionType supportRegion(supportIndex, supportSize);
outputPoint.Fill(NumericTraits<ScalarType>::ZeroValue());
using IteratorType = ImageScanlineConstIterator<ImageType>;
IteratorType coeffIterator[SpaceDimension];
unsigned long counter = 0;
const ParametersValueType * basePointer = this->m_CoefficientImages[0]->GetBufferPointer();
for (unsigned int j = 0; j < SpaceDimension; ++j)
{
coeffIterator[j] = IteratorType(this->m_CoefficientImages[j], supportRegion);
}
while (!coeffIterator[0].IsAtEnd())
{
while (!coeffIterator[0].IsAtEndOfLine())
{
// multiply weigth with coefficient
for (unsigned int j = 0; j < SpaceDimension; ++j)
{
outputPoint[j] += static_cast<ScalarType>(weights[counter] * coeffIterator[j].Get());
}
// populate the indices array
indices[counter] = &(coeffIterator[0].Value()) - basePointer;
// go to next coefficient in the support region
++counter;
for (unsigned int j = 0; j < SpaceDimension; ++j)
{
++(coeffIterator[j]);
}
} // end of scanline
for (unsigned int j = 0; j < SpaceDimension; ++j)
{
coeffIterator[j].NextLine();
}
}
// return results
for (unsigned int j = 0; j < SpaceDimension; ++j)
{
outputPoint[j] += point[j];
}
}
// Compute the Jacobian in one position
template <typename TParametersValueType, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineDeformableTransform<TParametersValueType, NDimensions, VSplineOrder>::ComputeJacobianWithRespectToParameters(
const InputPointType & point,
JacobianType & jacobian) const
{
// Zero all components of jacobian
jacobian.SetSize(SpaceDimension, this->GetNumberOfParameters());
jacobian.Fill(0.0);
SizeType supportSize;
supportSize.Fill(SplineOrder + 1);
ContinuousIndexType index =
this->m_CoefficientImages[0]
->template TransformPhysicalPointToContinuousIndex<typename ContinuousIndexType::ValueType>(point);
// NOTE: if the support region does not lie totally within the grid we assume
// zero displacement and do no computations beyond zeroing out the value
// return the input point
if (!this->InsideValidRegion(index))
{
return;
}
// Compute interpolation weights
WeightsType weights;
IndexType supportIndex;
this->m_WeightsFunction->Evaluate(index, weights, supportIndex);
const RegionType supportRegion(supportIndex, supportSize);
IndexType startIndex = this->m_CoefficientImages[0]->GetLargestPossibleRegion().GetIndex();
const SizeType & MeshGridSize = this->m_GridRegion.GetSize();
SizeType cumulativeGridSizes;
cumulativeGridSizes[0] = (MeshGridSize[0]);
for (unsigned int d = 1; d < SpaceDimension; ++d)
{
cumulativeGridSizes[d] = cumulativeGridSizes[d - 1] * MeshGridSize[d];
}
SizeValueType numberOfParametersPerDimension = this->GetNumberOfParametersPerDimension();
ImageRegionConstIteratorWithIndex<ImageType> It(this->m_CoefficientImages[0], supportRegion);
unsigned long counter = 0;
for (It.GoToBegin(); !It.IsAtEnd(); ++It)
{
typename ImageType::OffsetType currentIndex = It.GetIndex() - startIndex;
unsigned long number = currentIndex[0];
for (unsigned int d = 1; d < SpaceDimension; ++d)
{
number += (currentIndex[d] * cumulativeGridSizes[d - 1]);
}
for (unsigned int d = 0; d < SpaceDimension; ++d)
{
jacobian(d, number + d * numberOfParametersPerDimension) = weights[counter];
}
counter++;
}
}
} // namespace itk
#endif
|
.386p
page 58,132
;******************************************************************************
title emmfunct.asm - EMM function handlers
;******************************************************************************
;
; (C) Copyright MICROSOFT Corp. 1988-1991
; (C) Copyright COMPAQ Computer Corp. 1988-1991
;
; Title: EMM386.EXE - MICROSOFT Expanded Memory Manager 386 Driver
; EMMLIB.LIB - Expanded Memory Manager Functions Library
;
; Module: EMS Function Handler
;
; Version: 1.00
;
; Date: November 1, 1988
;
; Author: Dan Mazina (original)
; Leo Cohen (designed and implemented memory management and
; mapping functions to improve performance) LC
;
;******************************************************************************
;
; Change log:
;
; DATE REVISION DESCRIPTION
; -------- -------- -------------------------------------------------------
; 8/11/88 1 initial code
;******************************************************************************
;
; Functional Description:
; This module implements all of the functions for the EMM interface.
;
;******************************************************************************
page
;******************************************************************************
; PUBLICS
;******************************************************************************
public EMSDispatcher
public GetStatus
public GetPageFrameAddress
public GetUnallocatedPageCount
public AllocatePages
public MapHandlePage
public DeallocatePages
public GetEMMVersion
public SavePageMap
public RestorePageMap
public GetPageMappingRegisterIOArray
public GetLogicalToPhysicalPageTrans
public GetEMMHandleCount
public GetEMMHandlePages
public GetAllEMMHandlePages
public GetSetPageMap
;******************************************************************************
; INCLUDES
;******************************************************************************
include vdmseg.inc
include vdmsel.inc
include page.inc
include emmfunct.inc
include emmdata.inc
include emm386.inc
ifdef BETA
include emmfunct.pub
endif
;******************************************************************************
; DEFINES
;******************************************************************************
;******************************************************************************
; EXTERNALS
;******************************************************************************
_TEXT segment
extrn SaveWindowMapping:near
extrn RestoreWindowMapping:near
extrn AllocEMSMem:near
extrn ValidateHandle:near
extrn GetSetPartialPageMap:near
extrn MapUnmapMultipleHandlePages:near
extrn GetSetHandleAttribute:near
extrn GetSetHandleName:near
extrn GetHandleDirectory:near
extrn AlterPageMapAndJump:near
extrn AlterPageMapAndCall:near
extrn MoveExchangeMemoryRegion:near
extrn GetMappablePhysicalAddress:near
extrn GetExpandedMemoryHWInfo:near
extrn AllocateStandardRawPages:near
extrn AlternateMapRegisterSet:near
extrn PrepareForWarmBoot:near
extrn EnableDisableOSFunctions:near
extrn ReallocatePages:near
extrn GetFreeEMS:near
extrn CheckFreeEMS:near
extrn ShrinkEMSpool:near
ifdef QEMS
extrn Get4kPages:near
extrn GarbageCollect:near
extrn GetHandleSpace:near
extrn SetWindows:near
extrn SetPT0Cntxt:near
extrn RestorePT0Cntxt:near
endif
_TEXT ends
R_CODE segment
extrn CEMM_Entry:word
R_CODE ends
page
;******************************************************************************
; SEGMENTS
;******************************************************************************
_TEXT segment
assume cs:_TEXT,ds:_DATA,ss:_DATA,es:ABS0,gs:R_CODE
even
;******************************************************************************
; EMS_dispatcher
;
; ENTRY:
; DS - VDMD_GSEL
; GS - RCODEA_GSEL
; BP - if CEMM was on during call, offset to the fault stack frame
; all other registers have the user's values except for BP
; EXIT:
; the return registers are set up correctly
; DESCRIPTION:
; This routine checks the function number in AH and calls the appropriate
; subroutine. The user's register values are pushed on the stack and
; accessed through the 'RegisterStack_struc' structure.
;******************************************************************************
dispatch_vector label word
dw OFFSET GetStatus
dw OFFSET GetPageFrameAddress
dw OFFSET GetUnallocatedPageCount
dw OFFSET AllocatePages
dw OFFSET MapHandlePage
dw OFFSET DeallocatePages
dw OFFSET GetEMMVersion
dw OFFSET SavePageMap
dw OFFSET RestorePageMap
dw OFFSET GetPageMappingRegisterIOArray
dw OFFSET GetLogicalToPhysicalPageTrans
dw OFFSET GetEMMHandleCount
dw OFFSET GetEMMHandlePages
dw OFFSET GetAllEMMHandlePages
dw OFFSET GetSetPageMap
dw OFFSET GetSetPartialPageMap
dw OFFSET MapUnmapMultipleHandlePages
dw OFFSET ReallocatePages
dw OFFSET GetSetHandleAttribute
dw OFFSET GetSetHandleName
dw OFFSET GetHandleDirectory
dw OFFSET AlterPageMapAndJump
dw OFFSET AlterPageMapAndCall
dw OFFSET MoveExchangeMemoryRegion
dw OFFSET GetMappablePhysicalAddress
dw OFFSET GetExpandedMemoryHWInfo
dw OFFSET AllocateStandardRawPages
dw OFFSET AlternateMapRegisterSet
dw OFFSET PrepareForWarmBoot
dw OFFSET EnableDisableOSFunctions
cEMSFunc equ (($ - dispatch_vector)/2)
align 16
EMSDispatcher proc far
;
; The 32-bit registers are pushed and the BP is set up for the new stack frame.
; The direction flag is cleared.
;
pushad
mov bp,sp
cld
;
; The function in AH is placed in ESI
;
cmp ah,40h + cEMSFunc
jae short ED_invalid_function
movzx si,ah
sub si,40h
jb short ED_invalid_function
cmp gs:[NoEMSset],TRUE ;Q: Is EMS available?
je short EDSWmalfunc ; N: S/W malfunction
ifdef QEMS
bts gs:[GenFlags],fEMSsemBit;Q: Are EMS functions being re-entered?
jc short EDSWmalfunc ; Y: S/W malfunction
endif
;
; The function is changed into an index and executed. The only registers not
; in their original states are ESI, EBP, DS and ES.
;
add si,si
call cs:dispatch_vector[si]
ifdef QEMS
and gs:[GenFlags],not fEMSsem ; Reset EMS re-entrancy semaphore
endif
ED_return_code:
popad
ret
; If this point is reached then an invalid function
; code was seen.
ED_invalid_function:
cmp ax,0FFA5h
je short ED_special_function
EDinvalid:
mov byte ptr [bp.reg_EAX + 1],INVALID_FUNCTION
jmp short ED_return_code
EDSWmalfunc:
mov byte ptr [bp.reg_EAX+1],EMM_SW_MALFUNCTION
jmp short ED_return_code
ED_special_function:
ror al,4
mov byte ptr [bp.reg_EAX],al
mov byte ptr [bp.reg_EAX + 1],INVALID_FUNCTION
push gs:[CEMM_Entry]
pop word ptr [bp.reg_ECX]
mov word ptr [bp.reg_EBX],SEG R_CODE
jmp short ED_return_code
EMSDispatcher endp
page
align 16
;******************************************************************************
; GetStatus
;
; ENTRY
; none
; EXIT
; AH - OK
; DESCRIPTION
; This function returns the current status of the EMM subsystem which is
; always success.
;******************************************************************************
GetStatus proc near
mov byte ptr [bp.reg_EAX + 1],OK
ret
GetStatus endp
page
align 16
;***********************************************************************
; GetPageFrameAddress
;
; ENTRY
; none
; EXIT
; BX - segment address of the page frame
; AH - OK
; DESCRIPTION
; This routine returns the segment address of the page frame base.
; This is window index 0 of the EMS windows.
;***********************************************************************
GetPageFrameAddress proc near
;
; Get base address of the first EMS physical window
;
mov bx,EMS_window_location[0] ; page number
shl bx,8 ; convert to paragraph
mov word ptr [bp][reg_EBX],bx ; return to client
mov byte ptr [bp][reg_EAX+1],OK ; assume no error
cmp gs:[PF_Base],FREE ;Q: Is there a full LIM 3.2 page frame?
je short GPFAerr ; N: return error
ret
GPFAerr:
mov byte ptr [bp][reg_EAX+1],EMM_SW_MALFUNCTION ; XMA2EMS compatible
ret
GetPageFrameAddress endp
page
align 16
;==============================================================================
;==
;== GetUnallocatedPageCount: This routine returns the number of free 16k
;== pages and total number of 16k pages in the
;== system.
;==
;== Entry: (Protected Mode)
;==
;== Exit: (Protected Mode)
;== [BP]:BX = count of free 16k pages
;== [BP]:DX = total number of 16k pages (free and allocated)
;== [BP]:AH = OK
;== LC
;=============================================================================
GetUnallocatedPageCount proc near
;
; Get total EMS pages
;
mov ax,[TopOfHandleSpace]
sub ax,FIRST_HANDLE_PTE ; subtract start of handle space
shr ax,2
mov word ptr [bp][reg_EDX],ax
;
; Get free EMS pages
;
call GetFreeEMS
mov word ptr [bp][reg_EBX],ax
mov byte ptr [bp][reg_EAX+1],OK
ret
GetUnallocatedPageCount endp
page
align 16
;==============================================================================
;==
;== AllocatePages: This routine allocates EMS pages to the user.
;==
;== Entry: (Protected Mode)
;== BX = allocation size requested in 16k pages
;==
;== Exit: (Protected Mode)
;== [BP]:AH = return code
;== [BP]:DX = handle
;== LC
;=============================================================================
AllocatePages proc near
;
; If the number of requested pages is zero then exit.
;
or bx,bx
je short APzeroPagesReq
;
; Get total EMS pages
;
mov ax,[TopOfHandleSpace] ; top of handle space
sub ax,FIRST_HANDLE_PTE ; subtract start of handle space
shr ax,2 ; convert to 16K pages
cmp ax,bx ;Q: Enough free EMS pages?
jb short APnotEnoughTotEMS ; N: error
;
; Get free EMS pages (at this time!)
;
call CheckFreeEMS
jc short APnotEnoughFreeEMS
;EnterCrit ; BEGIN CRITICAL SECTION
pushf
cli
;
; Search handle table for an empty handle structure that can be used.
;
xor dx,dx
mov cx,[total_handles]
mov esi,[hndl_tbl_ptr]
mov di,4
inc dx
add si,di ; skip handle 0
APfindHandle:
cmp ds:[si].base_PTE_index,FREE
je short APhandleFound
add si,di
inc dx
cmp dx,cx
jb short APfindHandle
;ExitCrit ; END CRITICAL SECTION
popf
;
; If this is reached then no free handles could be found.
;
mov byte ptr [bp][reg_EAX+1],NO_MORE_HANDLES
jmp short APexit
;
; The PTE's are searched to find a location for the handle and its pages.
; BX is the number of requested PTE's. SI is the index into the handle space.
;
APhandleFound:
mov ds:[si].base_PTE_index,0 ; mark used
mov ds:[si].number_PTEs,0 ; with zero pages
;ExitCrit ; END CRITICAL SECTION
popf
push dx
call AllocEMSMem
pop dx
;
; If CY is set, not enough EMS pages were found! Even though we checked above,
; because this routine is re-entrant, it could have changed.
;
jc short APclearHandle
inc [handle_count]
mov word ptr [bp][reg_EDX],dx
mov byte ptr [bp][reg_EAX+1],OK
APexit:
ret
APzeroPagesReq:
mov byte ptr [bp][reg_EAX+1],ZERO_PAGES
jmp short APexit
APnotEnoughTotEMS:
mov byte ptr [bp][reg_EAX+1],NOT_ENOUGH_EXT_MEM
jmp short APexit
APclearHandle:
mov [si].base_PTE_index,FREE ; mark free
APnotEnoughFreeEMS:
mov byte ptr [bp][reg_EAX+1],NOT_ENOUGH_FREE_MEM
jmp short APexit
AllocatePages endp
page
align 16
;==============================================================================
;==
;== MapHandlePage: This routine maps a 16K EMS logical page into a physical
;== EMS window.
;==
;== Entry: (Protected Mode)
;== AL = window index
;== BX = logical page index
;== DX = EMM handle
;==
;== Exit: (Protected Mode)
;== AH = return code
;== LC
;=============================================================================
MapHandlePage proc near
;
; Assume success
;
mov byte ptr [bp][reg_EAX+1],OK ; assume error
;
; Validate window index
;
cmp [xma2ems],TRUE ;Q: Is it in XMA2EMS mode?
je MHPxma2ems ; Y: remap windows
MHPindex:
movzx edi,al
cmp di,[number_EMS_windows] ;Q: Valid window index?
jae MHPinvPhyPage ; N: error
;
; Validate handle
;
cmp dx,[total_handles] ;Q: Handle in range?
jae MHPinvHandle ; N: error
movzx ecx,bx ; CX=logical page
movzx ebx,dx ; access handle structure
shl bx,2
add ebx,[hndl_tbl_ptr] ; (ESI) = pointer to handle table
.errnz (SIZE HandleTable_struc-4)
cmp ds:[bx].base_PTE_index,FREE ;Q: Handle in use?
je MHPinvHandle ; N: error
;
; Access PTE
;
add di,di
movzx eax,[EMS_window_location][di] ; (EAX) = linear page # of window
mov di,ax
shl di,2
add edi,[page_tables] ; EDI = PTE address
cmp cx,UNMAP_WINDOW_OPCODE
je short MHPunmap
;
; Validate logical page range
;
test ch,0C0h ;Q: Is BX range too large?
jnz short MHPinvLogPage ; Y: error
shl cx,2 ; N: convert to 4K pages
cmp cx,ds:[bx].number_PTEs ;Q: Is logical page within valid range?
jae short MHPinvLogPage ; N: error
;
; Access handle space, and map logical page
;
;EnterCritical ; base PTE index for handle may change
pushf
cli
movzx esi,ds:[bx].base_PTE_index
add si,cx
shl si,2 ; quick esi*4
add esi,[page_directory] ; access handle space
mov cx,4
REP_MOVS_DWORD_USING_ES_ESI
;
;debug ExitCritical ; base PTE index for handle may change
popf
mov eax,cr3
mov cr3,eax
ret
align 16
;
; Unmap physical window by mapping one-to-one
;
MHPunmap:
mov dx,P_SIZE ; page
shl eax,P_SHIFT ; physical address
or ax,P_AVAIL ; accessible
STOS_DWORD_PTR_ES_EDI
add eax,edx
STOS_DWORD_PTR_ES_EDI
add eax,edx
STOS_DWORD_PTR_ES_EDI
add eax,edx
STOS_DWORD_PTR_ES_EDI
mov eax,cr3
mov cr3,eax
MHPexit:
ret
MHPxma2ems:
sub al,250 ;Q: P254 or P255?
ja short MHPx2aCont ; Y: continue
add al,250 ; N: restore original window number
MHPx2aCont:
cmp al,5 ;Q: Is the window in 0..5?
ja short MHPinvPhyPage ; N: no, error
jmp MHPindex
MHPinvPhyPage:
mov byte ptr [bp][reg_EAX+1],PHYS_PAGE_RANGE
jmp short MHPexit
MHPinvHandle:
mov byte ptr [bp][reg_EAX+1],INVALID_HANDLE
jmp short MHPexit
MHPinvLogPage:
mov byte ptr [bp][reg_EAX+1],LOG_PAGE_RANGE
jmp short MHPexit
MapHandlePage endp
page
align 16
;==============================================================================
;==
;== DeallocatePages: This routine freess EMS pages belonging to a handle.
;==
;== Entry: (Protected Mode)
;== DX = handle to deallocate
;==
;== Exit: (Protected Mode)
;== [BP]:AH = return code
;== LC
;=============================================================================
DeallocatePages proc near
;
; Assume success
;
mov byte ptr [bp][reg_EAX+1],OK
;
; Validate handle
;
cmp dx,[total_handles] ;Q: Handle in range?
jae DPinvHandle ; N: error
movzx ebx,dx ; Y: handle index in EBX
mov edx,ebx
mov ax,FREE
;
; Make sure save area is not being used.
;
cmp save_flag[bx],al ;Q: Is this save area FREE?
jne DPsaveAreaInUse ; N: error
;
; Address the handle structure
;
shl bx,2
.errnz (SIZE HandleTable_struc-4)
add ebx,[hndl_tbl_ptr] ; (ESI) = pointer to handle table
;EnterCrit ; BEGIN CRITICAL SECTION
pushf
cli
;
; Free handle
;
xchg ds:[bx].base_PTE_index,ax ; free handle
cmp ax,FREE ;Q: Handle already free?
je DPinvHandleX ; Y: error
dec gs:[handle_count] ; N: one less handle
;
; If the handle is index 0, then it cannot actually be freed up,
; so make it point somewhere innocuous.
;
or dx,dx
jne short DPnullName
mov ds:[bx].base_PTE_index,dx
inc gs:[handle_count]
;
; The handles name is reset to all nulls
;
DPnullName:
xor ecx,ecx
mov edi,[hndl_nam_ptr]
mov [edi][edx*8],ecx
mov [edi][edx*8+4],ecx
;
; Free its pages
;
movzx edi,ax ; start index of handle space
xor cx,cx ; free all pages for this handle
xchg cx,ds:[bx].number_PTEs ; get number of pages and zero it
jcxz short DPexitX ; if no pages, we're done
add ax,cx ; end of this handle space
cmp ax,[TopOfUsedEMSspace] ;Q: Last handle in the handle space?
jne short DPfPcont ; N: free all its pages
mov [TopOfUsedEMSspace],di ; Y: reflect change to top of used EMS
DPfPcont:
shl di,2 ; index to offset
add edi,[page_directory] ; address of handle space
shr cx,2 ; 4K to EMS pages
sub [UsedEMSPages],cx ; increase number of used EMS pages
mov ax,not fEMSPageAllocated; clear the user allocated bit
mov bx, cx ; 16k page count to bx
xor cx, cx ; cx = flag if XMS pool used for EMS
; Free EMS pages--check each EMS page to see if allocated from XMS pool,
; if so free XMS pages when done
DPfreePagesChkXMS:
bt dword ptr es:[edi], fXMSPageAllocatedBit ; from XMS?
jnc short DPfreePages
inc cx ; there is XMS memory to free
DPfreePages:
and word ptr es:[edi], ax
add edi, 10h
dec bx
jz short DPexitX
jcxz short DPfreePagesChkXMS ; don't check for XMS if already know
jmp short DPfreePages
DPexitX:
;ExitCrit ; END CRITICAL SECTION
popf
; cx != 0 if XMS memory was used for the EMS allocation
jcxz short DPexit ; Q: any XMS to free?
call ShrinkEMSpool ; Y:
DPexit:
ret
DPinvHandleX:
;ExitCrit ; END CRITICAL SECTION
popf
DPinvHandle:
mov byte ptr [bp][reg_EAX+1],INVALID_HANDLE
jmp short DPexit
DPsaveAreaInUse:
mov byte ptr [bp][reg_EAX+1],SAVED_PAGE_DEALLOC
jmp short DPexit
DeallocatePages endp
page
align 16
;***********************************************************************
; GetEMMVersion
;
; ENTRY
; none
; EXIT
; AH - OK
; AL - version number
; DESCRIPTION
; This routine returns the current version number.
;***********************************************************************
GetEMMVersion proc near
mov ah,OK
mov al,EMM_VERSION
mov word ptr [bp.reg_EAX],ax
ret
GetEMMVersion endp
page
align 16
;==============================================================================
;==
;== SavePageMap: This routine saves the LIM 3.2 page frame map context for a
;== handle. This includes only windows 0-3. The data is saved
;== in the save_map array internally.
;==
;== Entry: (Protected Mode)
;== DX = EMM handle
;==
;== Exit: (Protected Mode)
;== AH = return code
;== LC
;=============================================================================
SavePageMap proc near
;
; Assume success
;
mov byte ptr [bp][reg_EAX+1],OK
cmp gs:[PF_Base],FREE ;Q: Is there a page frame?
je short SaPMswErr ; N: error
;
; Validate handle
;
cmp dx,[total_handles] ;Q: Handle in range?
jae short SaPMinvHandle ; N: error
movzx ebx,dx ; access handle structure
mov edi,[hndl_tbl_ptr] ; (ESI) = pointer to handle table
.errnz (SIZE HandleTable_struc-4)
cmp ds:[edi+ebx*4].base_PTE_index,FREE ;Q: Handle in use?
je short SaPMinvHandle ; N: error
;
; Insure the save area for this handle is not presently being used
;
mov dl,NOT FREE
xchg save_flag[bx],dl ; mark used
cmp dl,FREE ;Q: Already saved?
jne short SaPMprevMapSaved ; Y: error
;
; Access save area
;
mov edi,ebx ; esi = bx * 16
shl di,4
.errnz size HandleSavemap_struc-16
add edi,[save_map_ptr]
add edi,[p_DATA]
;
; Access page table
;
movzx esi,[EMS_window_location][0] ; get index for page frame
shl si,2
add esi,[page_tables]
mov dx,0Ch
mov cx,4
SaPMloop:
MOVS_DWORD_USING_ES_ESI
add si,dx
dec cx
jnz short SaPMloop
SaPMexit:
ret
SaPMswErr:
mov byte ptr [bp][reg_EAX+1],EMM_SW_MALFUNCTION ; assume error
jmp short SaPMexit
SaPMinvHandle:
mov byte ptr [bp][reg_EAX+1],INVALID_HANDLE ; assume invalid handle
jmp short SaPMexit
SaPMprevMapSaved:
mov byte ptr [bp][reg_EAX+1],MAP_PREV_SAVED ; assume error
jmp short SaPMexit
SavePageMap endp
page
align 16
;==============================================================================
;==
;== RestorePageMap: This routine restores the LIM 3.2 page frame map context
;== for a handle. This includes only windows 0-3. The
;== data is restored from the internal save_map array.
;==
;== Entry: (Protected Mode)
;== DX = EMM handle
;==
;== Exit: (Protected Mode)
;== AH = return code
;== LC
;=============================================================================
RestorePageMap proc near
;
; Assume success
;
mov byte ptr [bp][reg_EAX+1],OK
cmp gs:[PF_Base],FREE ;Q: Is there a page frame?
je RePMswErr ; N: error
;
; Validate handle
;
cmp dx,[total_handles] ;Q: Handle in range?
jae short RePMinvHandle ; N: error
movzx ebx,dx ; access handle structure
mov edi,[hndl_tbl_ptr] ; (ESI) = pointer to handle table
.errnz (SIZE HandleTable_struc-4)
cmp ds:[edi+ebx*4].base_PTE_index,FREE ;Q: Handle in use?
je short RePMinvHandle ; N: error
;
; Insure the save area for this handle is not empty
;
mov dl,FREE
xchg save_flag[bx],dl ; mark used
cmp dl,FREE ;Q: Already saved?
je short RePMnoMapSaved ; Y: error
;
; Access save area
;
mov esi,ebx ; esi = bx * 16
shl si,4
.errnz size HandleSavemap_struc-16
add esi,[save_map_ptr]
add esi,[p_DATA]
;
; Access page table
;
movzx edi,[EMS_window_location][0] ; get index for page frame
shl di,2
add edi,[page_tables]
mov bx,1000h
mov cx,4
RePMloop:
LODS_DWORD_PTR_ES_ESI
STOS_DWORD_PTR_ES_EDI
add eax,ebx
STOS_DWORD_PTR_ES_EDI
add eax,ebx
STOS_DWORD_PTR_ES_EDI
add eax,ebx
STOS_DWORD_PTR_ES_EDI
dec cx
jnz short RePMloop
mov eax,cr3
mov cr3,eax
RePMexit:
ret
RePMswErr:
mov byte ptr [bp][reg_EAX+1],EMM_SW_MALFUNCTION ; assume error
jmp short RePMexit
RePMinvHandle:
mov byte ptr [bp][reg_EAX+1],INVALID_HANDLE ; assume invalid handle
jmp short RePMexit
RePMnoMapSaved:
mov byte ptr [bp][reg_EAX+1],NO_MAP_SAVED ; assume error
jmp short RePMexit
RestorePageMap endp
page
align 16
;***********************************************************************
; GetPageMappingRegisterIOArray
;
; ENTRY
; ES:DI - pointer to the users table
; EXIT
; AH - INVALID_FUNCTION
; DESCRIPTION
; This routine is no longer supported.
;***********************************************************************
GetPageMappingRegisterIOArray proc near
mov byte ptr [bp.reg_EAX + 1],INVALID_FUNCTION
ret
GetPageMappingRegisterIOArray endp
page
align 16
;***********************************************************************
; GetLogicalToPhysicalPageTrans
;
; ENTRY
; ES:DI - pointer to the users table
; DX - EMM handle
; EXIT
; AH - INVALID_FUNCTION
; DESCRIPTION
; This routine is no longer supported.
;***********************************************************************
GetLogicalToPhysicalPageTrans proc near
mov byte ptr [bp.reg_EAX + 1],INVALID_FUNCTION
ret
GetLogicalToPhysicalPageTrans endp
page
align 16
;***********************************************************************
; GetEMMHandleCount
;
; ENTRY
; none
; EXIT
; BX - handle count
; AH - OK
; DESCRIPTION
; This routine returns the number of active handles.
;***********************************************************************
GetEMMHandleCount proc near
mov bx,gs:[handle_count]
mov word ptr [bp.reg_EBX],bx
mov byte ptr [bp.reg_EAX + 1],OK
ret
GetEMMHandleCount endp
page
align 16
;***********************************************************************
; GetEMMHandlePages
;
; ENTRY
; DX - handle
; EXIT
; BX - number of 16k pages allocated to this handle
; AH - return code
; DESCRIPTION
; This routine returns the number of 16k EMS pages allocated to the
; provided handle.
;***********************************************************************
GetEMMHandlePages proc near
; The handle is validated. SI has the handle struct index.
call ValidateHandle
jc short GHP_return_code
movzx esi,dx
; The number of PTE indexes allocated for this handle is loaded
; and divided by 4 to change it into 16k pages from 4k pages.
MOV EBX, [hndl_tbl_ptr]
MOV BX, DS:[EBX+ESI*4].number_PTEs
shr bx,2
mov word ptr [bp.reg_EBX],bx
mov byte ptr [bp.reg_EAX + 1],OK
GHP_return_code:
ret
GetEMMHandlePages endp
page
align 16
;***********************************************************************
; GetAllEMMHandlePages
;
; ENTRY
; ES:DI - pointer to the users table
; EXIT
; BX - number of handles in the table
; AH - return code
; DESCRIPTION
; This routine returns an array which lists all of the active handles
; and how many 16k EMS pages are allocated to each of them. The data
; is placed in a user provided buffer.
;***********************************************************************
GetAllEMMHandlePages proc near
; The user's segment value is changed into a selector and
; the address is placed into ES:DI.
movzx eax,word ptr [bp.reg_ES]
shl eax,4
movzx edi,di
add edi,eax
;QEMS push DATA32_GSEL
;QEMS pop es
;EnterCrit ; BEGIN CRITICAL SECTION
pushf
cli
mov cx,gs:[handle_count]
mov word ptr [bp.reg_EBX],cx
xor esi,esi
dec si
;QEMS mov esi,0FFFFh ; (SI) = -1, (ESI hi) = 0
mov ebx,[hndl_tbl_ptr]
; If this handle is not being used then don't report it.
GAHP_loop_top:
inc si
cmp [ebx+esi*4].base_PTE_index,FREE
je short GAHP_loop_top
; The handle index is converted into its appropriate user
; handle number and stored.
mov es:[edi],si
add edi,2
; The number of 16k pages for this handle is returned.
mov ax,[ebx+esi*4].number_PTEs
shr ax,2
mov es:[edi],ax
add edi,2
loop GAHP_loop_top
;ExitCrit ; END CRITICAL SECTION
popf
mov byte ptr [bp.reg_EAX + 1],OK
ret
GetAllEMMHandlePages endp
page
align 16
;==============================================================================
;==
;== GetSetPageMap: This routine saves/restores the complete mapping context
;== to/from an external buffer.
;==
;== Entry: (Protected Mode)
;== AL = Subfunction code
;== 0 : get page map
;== 1 : set page map
;== 2 : get and Set page map
;== 3 : return size of page map
;==
;== Exit: (Protected Mode)
;== AH = return code
;== LC
;=============================================================================
GSPMvecTable label word
dw offset _TEXT:GSPM_get_function
dw offset _TEXT:GSPM_set_function
dw offset _TEXT:GSPM_set_get_function
dw offset _TEXT:GSPM_return_function
GSPMFuncNum equ ($-GSPMvecTable)/2
align 16
GetSetPageMap proc near
;
; The subfunction number is checked to see if it is valid.
;
cmp al,GSPMFuncNum ;Q: Invalid function?
jae short GSPMinvFunc ; Y: error
mov byte ptr [bp][reg_EAX+1],OK ; N: assume success
;
; The get and set functions will use a zero based selector in ES for addressing
; the user's buffer. The jump table is used to execute the subfunction.
;
movzx esi,al
add si,si
jmp cs:GSPMvecTable[si]
align 16
;
; If the subfunction just wants the size of the save area then just return it.
;
GSPM_return_function:
mov al,byte ptr [context_save_area_size]
mov byte ptr [bp.reg_EAX],al
GSPMexit:
ret
align 16
;
; If a Get function, save mapping in user buffer
;
GSPM_get_function:
movzx eax,word ptr [bp.reg_ES]
shl eax,4
movzx edi,di
add edi,eax
jmp SaveWindowMapping
align 16
GSPM_set_get_function:
movzx eax,word ptr [bp.reg_ES]
shl eax,4
movzx edi,di
add edi,eax
call SaveWindowMapping
; If this is a Set function then set up the user's buffer in
; ES:ESI and make the call.
GSPM_set_function:
movzx esi,word ptr [bp.reg_ESI]
movzx eax,word ptr [bp.reg_DS]
shl eax,4
add esi,eax
jmp RestoreWindowMapping
GSPMinvFunc:
mov byte ptr [bp][reg_EAX+1],INVALID_SUBFUNCTION ; assume error
jmp short GSPMexit
GetSetPageMap endp
_TEXT ends
END
|
/*=========================================================================
*
* 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 "itkSingleValuedVnlCostFunctionAdaptor.h"
#include "itkMacro.h"
namespace itk
{
/** Constructor. */
SingleValuedVnlCostFunctionAdaptor
::SingleValuedVnlCostFunctionAdaptor(unsigned int spaceDimension):
vnl_cost_function(spaceDimension)
{
m_ScalesInitialized = false;
m_NegateCostFunction = false;
m_Reporter = Object::New();
m_CachedValue = NumericTraits< MeasureType >::Zero;
m_CachedDerivative.Fill(0);
}
/** Set current parameters scaling. */
void
SingleValuedVnlCostFunctionAdaptor
::SetScales(const ScalesType & scales)
{
m_Scales = scales;
m_ScalesInitialized = true;
}
/** Delegate computation of the value to the CostFunction. */
SingleValuedVnlCostFunctionAdaptor::InternalMeasureType
SingleValuedVnlCostFunctionAdaptor
::f(const InternalParametersType & inparameters)
{
if ( !m_CostFunction )
{
itkGenericExceptionMacro(
<< "Attempt to use a SingleValuedVnlCostFunctionAdaptor without any CostFunction plugged in");
}
// Use scales if they are provided
ParametersType parameters( inparameters.size() );
if ( m_ScalesInitialized )
{
for ( unsigned int i = 0; i < parameters.size(); i++ )
{
parameters[i] = inparameters[i] / m_Scales[i];
}
}
else
{
parameters.SetData( const_cast< double * >( inparameters.data_block() ) );
}
InternalMeasureType value = static_cast< InternalMeasureType >( m_CostFunction->GetValue(parameters) );
if ( m_NegateCostFunction )
{
value *= -1.0;
}
// Notify observers. This is used for overcoming the limitaion of VNL
// optimizers of not providing callbacks per iteration.
m_CachedValue = value;
m_CachedCurrentParameters = parameters;
this->ReportIteration( FunctionEvaluationIterationEvent() );
return value;
}
/** Delegate computation of the gradient to the costfunction. */
void
SingleValuedVnlCostFunctionAdaptor
::gradf(const InternalParametersType & inparameters,
InternalDerivativeType & gradient)
{
if ( !m_CostFunction )
{
itkGenericExceptionMacro("Attempt to use a SingleValuedVnlCostFunctionAdaptor without any CostFunction plugged in");
}
// Use scales if they are provided
ParametersType parameters( inparameters.size() );
if ( m_ScalesInitialized )
{
for ( unsigned int i = 0; i < parameters.size(); i++ )
{
parameters[i] = inparameters[i] / m_Scales[i];
}
}
else
{
parameters.SetData( const_cast< double * >( inparameters.data_block() ) );
}
m_CostFunction->GetDerivative(parameters, m_CachedDerivative);
this->ConvertExternalToInternalGradient(m_CachedDerivative, gradient);
// Notify observers. This is used for overcoming the limitaion of VNL
// optimizers of not providing callbacks per iteration.
// Note that m_CachedDerivative is already loaded in the GetDerivative()
// above.
m_CachedCurrentParameters = parameters;
this->ReportIteration( GradientEvaluationIterationEvent() );
}
/** Delegate computation of value and gradient to the costfunction. */
void
SingleValuedVnlCostFunctionAdaptor
::compute(const InternalParametersType & x,
InternalMeasureType *fun,
InternalDerivativeType *g)
{
// delegate the computation to the CostFunction
ParametersType parameters( x.size() );
double measure;
if ( m_ScalesInitialized )
{
for ( unsigned int i = 0; i < parameters.size(); i++ )
{
parameters[i] = x[i] / m_Scales[i];
}
}
else
{
parameters.SetData( const_cast< double * >( x.data_block() ) );
}
m_CostFunction->GetValueAndDerivative(parameters, measure, m_CachedDerivative);
if ( g ) // sometimes Vnl doesn't pass a valid pointer
{
this->ConvertExternalToInternalGradient(m_CachedDerivative, *g);
}
if ( fun ) // paranoids have longer lives...
{
if ( !m_NegateCostFunction )
{
*fun = static_cast< InternalMeasureType >( measure );
}
else
{
*fun = static_cast< InternalMeasureType >( -measure );
}
// Notify observers. This is used for overcoming the limitaion of VNL
// optimizers of not providing callbacks per iteration.
// Note that m_CachedDerivative is already loaded in the GetDerivative()
// above.
m_CachedValue = *fun;
}
m_CachedCurrentParameters = parameters;
this->ReportIteration( FunctionAndGradientEvaluationIterationEvent() );
}
/** Convert external derviative measures into internal type */
void
SingleValuedVnlCostFunctionAdaptor
::ConvertExternalToInternalGradient(const DerivativeType & input,
InternalDerivativeType & output) const
{
const unsigned int size = input.size();
output = InternalDerivativeType(size);
for ( unsigned int i = 0; i < size; i++ )
{
if ( !m_NegateCostFunction )
{
output[i] = input[i];
}
else
{
output[i] = -input[i];
}
if ( m_ScalesInitialized )
{
output[i] /= m_Scales[i];
}
}
}
/** Set whether the cost function should be negated or not. This is useful for
* adapting optimizers that are only minimizers. */
void
SingleValuedVnlCostFunctionAdaptor
::SetNegateCostFunction(bool flag)
{
m_NegateCostFunction = flag;
}
/** Returns whether the cost function is going to be negated or not.
* This is useful for adapting optimizers that are only minimizers. */
bool
SingleValuedVnlCostFunctionAdaptor
::GetNegateCostFunction() const
{
return m_NegateCostFunction;
}
/** This method reports iterations events. It is intended to
* help monitoring the progress of the optimization process. */
void
SingleValuedVnlCostFunctionAdaptor
::ReportIteration(const EventObject & event) const
{
this->m_Reporter->InvokeEvent(event);
}
/** Connects a Command/Observer to the internal reporter class.
* This is useful for reporting iteration event to potential observers. */
unsigned long
SingleValuedVnlCostFunctionAdaptor
::AddObserver(const EventObject & event, Command *command) const
{
return m_Reporter->AddObserver(event, command);
}
/** Return the cached value of the cost function */
const SingleValuedVnlCostFunctionAdaptor::MeasureType &
SingleValuedVnlCostFunctionAdaptor
::GetCachedValue() const
{
return m_CachedValue;
}
/** Return the cached value of the cost function derivative */
const SingleValuedVnlCostFunctionAdaptor::DerivativeType &
SingleValuedVnlCostFunctionAdaptor
::GetCachedDerivative() const
{
return m_CachedDerivative;
}
/** Return the cached value of the parameters used for computing the function
*/
const SingleValuedVnlCostFunctionAdaptor::ParametersType &
SingleValuedVnlCostFunctionAdaptor
::GetCachedCurrentParameters() const
{
return m_CachedCurrentParameters;
}
} // end namespace itk
|
; A032528: Concentric hexagonal numbers: floor( 3*n^2 / 2 ).
; 0,1,6,13,24,37,54,73,96,121,150,181,216,253,294,337,384,433,486,541,600,661,726,793,864,937,1014,1093,1176,1261,1350,1441,1536,1633,1734,1837,1944,2053,2166,2281,2400,2521,2646,2773,2904,3037,3174,3313,3456,3601,3750,3901,4056,4213,4374,4537,4704,4873,5046,5221,5400,5581,5766,5953,6144,6337,6534,6733,6936,7141,7350,7561,7776,7993,8214,8437,8664,8893,9126,9361,9600,9841,10086,10333,10584,10837,11094,11353,11616,11881,12150,12421,12696,12973,13254,13537,13824,14113,14406,14701,15000,15301,15606,15913,16224,16537,16854,17173,17496,17821,18150,18481,18816,19153,19494,19837,20184,20533,20886,21241,21600,21961,22326,22693,23064,23437,23814,24193,24576,24961,25350,25741,26136,26533,26934,27337,27744,28153,28566,28981,29400,29821,30246,30673,31104,31537,31974,32413,32856,33301,33750,34201,34656,35113,35574,36037,36504,36973,37446,37921,38400,38881,39366,39853,40344,40837,41334,41833,42336,42841,43350,43861,44376,44893,45414,45937,46464,46993,47526,48061,48600,49141,49686,50233,50784,51337,51894,52453,53016,53581,54150,54721,55296,55873,56454,57037,57624,58213,58806,59401,60000,60601,61206,61813,62424,63037,63654,64273,64896,65521,66150,66781,67416,68053,68694,69337,69984,70633,71286,71941,72600,73261,73926,74593,75264,75937,76614,77293,77976,78661,79350,80041,80736,81433,82134,82837,83544,84253,84966,85681,86400,87121,87846,88573,89304,90037,90774,91513,92256,93001
mov $1,$0
pow $1,2
mul $1,6
div $1,4
|
#include <iostream>
#include <string>
#include <map>
// -------------------- OpenMesh
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
#include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh>
// -------------------- little helper
#include "generate_cube.hh"
#include "stats.hh"
#include "fill_props.hh"
// ----------------------------------------------------------------------------
// Set to 1 to use an PolyMesh type.
#define UsePolyMesh 1
// ----------------------------------------------------------------------------
using namespace OpenMesh;
// ----------------------------------------------------------------------------
typedef TriMesh_ArrayKernelT<> TriMesh;
typedef PolyMesh_ArrayKernelT<> PolyMesh;
#if UsePolyMesh
typedef PolyMesh Mesh;
#else
typedef TriMesh Mesh;
#endif
// ----------------------------------------------------------------------------
#ifndef DOXY_IGNORE_THIS
struct MyData
{
int ival;
double dval;
bool bval;
OpenMesh::Vec4f vec4fval;
MyData()
: ival(0), dval(0.0), bval(false)
{ }
MyData( const MyData& _cpy )
: ival(_cpy.ival), dval(_cpy.dval), bval(_cpy.bval),
vec4fval(_cpy.vec4fval)
{ }
// ---------- assignment
MyData& operator = (const MyData& _rhs)
{
ival = _rhs.ival;
dval = _rhs.dval;
bval = _rhs.bval;
vec4fval = _rhs.vec4fval;
return *this;
}
MyData& operator = (int _rhs) { ival = _rhs; return *this; }
MyData& operator = (double _rhs) { dval = _rhs; return *this; }
MyData& operator = (bool _rhs) { bval = _rhs; return *this; }
MyData& operator = (const OpenMesh::Vec4f& _rhs)
{ vec4fval = _rhs; return *this; }
// ---------- comparison
bool operator == (const MyData& _rhs) const
{
return ival == _rhs.ival
&& dval == _rhs.dval
&& bval == _rhs.bval
&& vec4fval == _rhs.vec4fval;
}
bool operator != (const MyData& _rhs) const { return !(*this == _rhs); }
};
#endif
// ----------------------------------------------------------------------------
typedef std::map< std::string, unsigned int > MyMap;
// ----------------------------------------------------------------------------
#ifndef DOXY_IGNORE_THIS
namespace OpenMesh {
namespace IO {
// support persistence for struct MyData
template <> struct binary<MyData>
{
typedef MyData value_type;
static const bool is_streamable = true;
// return binary size of the value
static size_t size_of(void)
{
return sizeof(int)+sizeof(double)+sizeof(bool)+sizeof(OpenMesh::Vec4f);
}
static size_t size_of(const value_type&)
{
return size_of();
}
static size_t store(std::ostream& _os, const value_type& _v, bool _swap=false)
{
size_t bytes;
bytes = IO::store( _os, _v.ival, _swap );
bytes += IO::store( _os, _v.dval, _swap );
bytes += IO::store( _os, _v.bval, _swap );
bytes += IO::store( _os, _v.vec4fval, _swap );
return _os.good() ? bytes : 0;
}
static size_t restore( std::istream& _is, value_type& _v, bool _swap=false)
{
size_t bytes;
bytes = IO::restore( _is, _v.ival, _swap );
bytes += IO::restore( _is, _v.dval, _swap );
bytes += IO::restore( _is, _v.bval, _swap );
bytes += IO::restore( _is, _v.vec4fval, _swap );
return _is.good() ? bytes : 0;
}
};
template <> struct binary< MyMap >
{
typedef MyMap value_type;
static const bool is_streamable = true;
// return generic binary size of self, if known
static size_t size_of(void) { return UnknownSize; }
// return binary size of the value
static size_t size_of(const value_type& _v)
{
if (_v.empty())
return sizeof(unsigned int);
value_type::const_iterator it = _v.begin();
unsigned int N = _v.size();
size_t bytes = IO::size_of(N);
for(;it!=_v.end(); ++it)
{
bytes += IO::size_of( it->first );
bytes += IO::size_of( it->second );
}
return bytes;
}
static
size_t store(std::ostream& _os, const value_type& _v, bool _swap=false)
{
size_t bytes = 0;
unsigned int N = _v.size();
value_type::const_iterator it = _v.begin();
bytes += IO::store( _os, N, _swap );
for (; it != _v.end() && _os.good(); ++it)
{
bytes += IO::store( _os, it->first, _swap );
bytes += IO::store( _os, it->second, _swap );
}
return _os.good() ? bytes : 0;
}
static
size_t restore( std::istream& _is, value_type& _v, bool _swap=false)
{
size_t bytes = 0;
unsigned int N = 0;
_v.clear();
bytes += IO::restore( _is, N, _swap );
std::string key;
size_t val;
for (size_t i=0; i<N && _is.good(); ++i)
{
bytes += IO::restore( _is, key, _swap );
bytes += IO::restore( _is, val, _swap );
_v[key] = val;
}
return _is.good() ? bytes : 0;
}
};
}
}
#endif
// ----------------------------------------------------------------------------
int main(void)
{
//
Mesh mesh;
// generate a geometry
generate_cube<Mesh>(mesh);
// should display 8 vertices, 18/12 edges, 12/6 faces (Tri/Poly)
mesh_stats(mesh);
// print out information about properties
mesh_property_stats(mesh);
std::cout << "Define some custom properties..\n";
OpenMesh::VPropHandleT<float> vprop_float;
OpenMesh::EPropHandleT<bool> eprop_bool;
OpenMesh::FPropHandleT<std::string> fprop_string;
OpenMesh::HPropHandleT<MyData> hprop_mydata;
OpenMesh::MPropHandleT<MyMap> mprop_map;
std::cout << ".. and registrate them at the mesh object.\n";
mesh.add_property(vprop_float, "vprop_float");
mesh.add_property(eprop_bool, "eprop_bool");
mesh.add_property(fprop_string, "fprop_string");
mesh.add_property(hprop_mydata, "hprop_mydata");
mesh.add_property(mprop_map, "mprop_map");
mesh_property_stats(mesh);
std::cout << "Now let's fill the props..\n";
fill_props(mesh, vprop_float);
fill_props(mesh, eprop_bool);
fill_props(mesh, fprop_string);
fill_props(mesh, hprop_mydata);
fill_props(mesh, mprop_map);
std::cout << "Check props..\n";
#define CHK_PROP( PH ) \
std::cout << " " << #PH << " " \
<< (fill_props(mesh, PH, true)?"ok\n":"error\n")
CHK_PROP(vprop_float);
CHK_PROP(eprop_bool);
CHK_PROP(fprop_string);
CHK_PROP(hprop_mydata);
CHK_PROP(mprop_map);
#undef CHK_PROP
std::cout << "Set persistent flag..\n";
#define SET_PERS( PH ) \
mesh.property(PH).set_persistent(true); \
std::cout << " " << #PH << " " \
<< (mesh.property(PH).persistent()?"ok\n":"failed!\n")
mesh.property(vprop_float).set_persistent(true);
std::cout << " vprop_float "
<< (mesh.property(vprop_float).persistent()?"ok\n":"failed!\n");
SET_PERS( eprop_bool );
SET_PERS( fprop_string );
SET_PERS( hprop_mydata );
mesh.mproperty(mprop_map).set_persistent(true);
std::cout << " mprop_map "
<< (mesh.mproperty(mprop_map).persistent()?"ok\n":"failed!\n");
std::cout << "Write mesh..";
if (IO::write_mesh( mesh, "persistence-check.om" ))
std::cout << " ok\n";
else
{
std::cout << " failed\n";
return 1;
}
std::cout << "Clear mesh\n";
mesh.clear();
mesh_stats(mesh, " ");
std::cout << "Read back mesh..";
try
{
if (IO::read_mesh( mesh, "persistence-check.om" ))
std::cout << " ok\n";
else
{
std::cout << " failed!\n";
return 1;
}
mesh_stats(mesh, " ");
}
catch( std::exception &x )
{
std::cerr << x.what() << std::endl;
return 1;
}
std::cout << "Check props..\n";
#define CHK_PROP( PH ) \
std::cout << " " << #PH << " " \
<< (fill_props(mesh, PH, true)?"ok\n":"error\n")
CHK_PROP(vprop_float);
CHK_PROP(eprop_bool);
CHK_PROP(fprop_string);
CHK_PROP(hprop_mydata);
CHK_PROP(mprop_map);
#undef CHK_PROP
return 0;
}
// end of file
// ============================================================================
|
;------------- Seccion de datos -------------
section .data
resultado db '0' ; variable pre-definido
section .bss
resultado2 resb 1 ; reserva de memoria de un bite
;------------- Seccion de texto -------------
section .text
global _start
start:
; ---- suma ----
mov eax, 2 ; asignacion del valor 2 al registro eax
mov ebx, 3 ; asignacion del valor 3 al registro ebx
add eax, ebx ; suma de los valores 2 y 3
add eax, 48 ; 48 valor ascii -> se suma el 48 + 5 para tener el valor 5 en ascii
mov [resultado], eax ; mueve el valor del registro eax a la variable resultado
mov eax, 4 ; indica a la maquina que se escrbira un dato
mov ebx, 1 ; indica a la maquina que imprimira un dato en pantalla
mov ecx, resultado ; imprime en pantalla la variable resultado en referencia de su direccion de memoria
mov edx, 1 ; indica a la maquina cuantos bites o datos se imprimira en pantalla
int 0x80
; ---- resta ----
mov eax, 8 ; asignacion del valor 8 al registro eax
mov ebx, 1 ; asignacion del valor 1 al registro ebx
add eax, ebx ; suma de los valores 8 y 1
add eax, 48 ; 48 valor ascii -> se suma el 48 + 7 para tener el valor 7
mov [resultado], eax ; mueve el valor del registro eax a la variable resultado2
mov eax, 4 ; indica a la maquina que se escrbira un dato
mov ebx, 1 ; indica a la maquina que imprimira un dato en pantalla
mov ecx, resultado ; imprime en pantalla la variable resultado2 en referencia de su direccion de memoria
mov edx, 1 ; indica a la maquina cuantos bites o datos se imprimira en pantalla
int 0x80
; indica a la maquina si el programa se ejecuto de forma exitosa
mov eax, 1
mov ebx, 0 |
format MS COFF
extrn '__imp__ExitProcess@4' as ExitProcess:dword
extrn '__imp__CreateWindowExA@48' as CreateWindowEx:dword
extrn '__imp__SetPixelFormat@12' as SetPixelFormat:dword
extrn '__imp__ChoosePixelFormat@8' as ChoosePixelFormat:dword
extrn '__imp__ShowCursor@4' as ShowCursor:dword
extrn '__imp__GetDC@4' as GetDC:dword
extrn '__imp__GetAsyncKeyState@4' as GetAsyncKeyState:dword
extrn '__imp__PeekMessageA@20' as PeekMessage:dword
extrn '__imp__timeGetTime@0' as timeGetTime:dword
extrn '__imp__timeBeginPeriod@4' as timeBeginPeriod:dword
extrn '__imp__SwapBuffers@4' as SwapBuffers:dword
extrn '__imp__ChangeDisplaySettingsA@8' as ChangeDisplaySettings:dword
extrn '__imp__wglMakeCurrent@8' as wglMakeCurrent:dword
extrn '__imp__wglCreateContext@4' as wglCreateContext:dword
extrn '__imp__wglGetProcAddress@4' as wglGetProcAddress:dword
extrn '__imp__glRecti@16' as glRecti:dword
extrn '__imp__glTexCoord1f@4' as glTexCoord1f:dword
section '.text' code readable executable
public _Start
_Start: push 00000004h ; CDS_FULLSCREEN
push ScreenSettings
call [ChangeDisplaySettings]
push 0 ; lpParam
push 0 ; hInstance
push 0 ; hMenu
push 0 ; hWndParent
push 0 ; nHeight
push 0 ; nWidth
push 0 ; y
push 0 ; x
push 91000000h ; dwStyle = WS_POPUP|WS_VISIBLE|WS_MAXIMIZE
push 0 ; lpWindowName
push S.WinClassName ; lpClassName
push 0 ; dwExStyle
call [CreateWindowEx]
push eax ; hwnd
call [GetDC]
mov ebx, eax ; ebx = hdc
push PixelFormatDesc
push ebx ; hdc
call [ChoosePixelFormat]
push PixelFormatDesc
push eax ; pixel format id
push ebx ; hdc
call [SetPixelFormat]
push ebx ; hdc
call [wglCreateContext]
push eax ; GL context
push ebx ; hdc
call [wglMakeCurrent]
push 0
call [ShowCursor]
push S.glUseProgram
call [wglGetProcAddress]
mov esi, eax ; esi = pointer to glUseProgram
push S.glCreateShaderProgramv
call [wglGetProcAddress]
push ShaderCodePtr
push 1
push 8B30h ; GL_FRAGMENT_SHADER
call eax ; glCreateShaderProgramv
push eax ; GL program to use
call esi ; glUseProgram
push 1 ; ask for 1 ms timer resolution
call [timeBeginPeriod]
call [timeGetTime]
mov edi, eax ; edi = beginTime
.mainLoop:
push 0001h ; PM_REMOVE
push 0
push 0
push 0
push Message
call [PeekMessage]
call [timeGetTime]
sub eax, edi ; currentTime = time - beginTime
push eax
fild dword [esp]
fstp dword [esp]
call [glTexCoord1f]
push 1
push 1
push -1
push -1
call [glRecti]
push ebx ; hdc
call [SwapBuffers]
push 1Bh ; VK_ESCAPE
call [GetAsyncKeyState]
test eax, eax
jnz .exit
jmp .mainLoop
.exit: call [ExitProcess]
section '.data' data readable writeable
Message:
PixelFormatDesc:
dd 0
dd 00000025h ; PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW
ScreenSettings:
db 32 dup 0
dd 0
dw .size
dw 0
dd 001c0000h ; DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL
db 60 dup 0
dd 32, 1920, 1080
dd 11 dup 0
.size = $-ScreenSettings
ShaderCodePtr dd ShaderCode
ShaderCode:
file 'qjulia-small.glsl'
db 0
S.WinClassName db 'edit', 0
S.glCreateShaderProgramv db 'glCreateShaderProgramv', 0
S.glUseProgram db 'glUseProgram', 0
|
#include "ComponentBoundingBox2D.h"
#include "Application.h"
#include "Modules/ModuleInput.h"
#include "Components/UI/ComponentTransform2D.h"
#include "GameObject.h"
#include "Utils/Logging.h"
#include "Panels/PanelScene.h"
#include "Modules/ModuleWindow.h"
#include "Modules/ModuleTime.h"
#include "Modules/ModuleRender.h"
#include "Modules/ModuleUserInterface.h"
#include "debugdraw.h"
#include "Geometry/AABB.h"
#include "Geometry/OBB2D.h"
#include "Geometry/Circle.h"
#include "imgui.h"
#include "Math/float3x3.h"
#include "Utils/Leaks.h"
#define JSON_TAG_LOCAL_BOUNDING_BOX2D "LocalBoundingBox2D"
void ComponentBoundingBox2D::Init() {
ComponentTransform2D* transform2D = GetOwner().GetComponent<ComponentTransform2D>();
if (transform2D) {
float2 minPoint = float2(-0.5f, -0.5f);
float2 maxPoint = float2(0.5f, 0.5f);
SetLocalBoundingBox(AABB2D(minPoint, maxPoint));
CalculateWorldBoundingBox();
}
}
void ComponentBoundingBox2D::OnEditorUpdate() {
ImGui::Checkbox("Show Outline Object", &drawOutline);
}
void ComponentBoundingBox2D::Update() {
CalculateWorldBoundingBox();
}
void ComponentBoundingBox2D::Save(JsonValue jComponent) const {
JsonValue jLocalBoundingBox = jComponent[JSON_TAG_LOCAL_BOUNDING_BOX2D];
jLocalBoundingBox[0] = localAABB.minPoint.x;
jLocalBoundingBox[1] = localAABB.minPoint.y;
jLocalBoundingBox[2] = localAABB.maxPoint.x;
jLocalBoundingBox[3] = localAABB.maxPoint.y;
}
void ComponentBoundingBox2D::Load(JsonValue jComponent) {
JsonValue jLocalBoundingBox = jComponent[JSON_TAG_LOCAL_BOUNDING_BOX2D];
localAABB.minPoint.Set(jLocalBoundingBox[0], jLocalBoundingBox[1]);
localAABB.maxPoint.Set(jLocalBoundingBox[2], jLocalBoundingBox[3]);
dirty = true;
}
void ComponentBoundingBox2D::SetLocalBoundingBox(const AABB2D& boundingBox) {
localAABB = boundingBox;
dirty = true;
}
void ComponentBoundingBox2D::CalculateWorldBoundingBox(bool force) {
if (dirty || force) {
ComponentTransform2D* transform2d = GetOwner().GetComponent<ComponentTransform2D>();
ComponentCanvasRenderer* canvasRenderer = GetOwner().GetComponent<ComponentCanvasRenderer>();
float screenFactor = 1.0f;
float2 screenSize(0, 0);
float3 position(0, 0, 0);
float2 pivotPosition(0, 0);
if (canvasRenderer != nullptr) {
screenFactor = canvasRenderer->GetCanvasScreenFactor();
screenSize = canvasRenderer->GetCanvasSize();
position = transform2d->GetScreenPosition();
pivotPosition = transform2d->GetPivot();
}
float2 pivotDifference = float2::zero;
pivotDifference.x = -pivotPosition.x + 0.5f;
pivotDifference.y = pivotPosition.y - 0.5f;
worldAABB.minPoint = position.xy().Mul(float2(1.0f, -1.0f).Mul(screenFactor)) + screenSize / 2.0f
+ (localAABB.minPoint + pivotDifference).Mul(transform2d->GetSize().Mul(transform2d->GetScale().xy()).Mul(screenFactor));
worldAABB.maxPoint = position.xy().Mul(float2(1.0f, -1.0f).Mul(screenFactor)) + screenSize / 2.0f
+ (localAABB.maxPoint + pivotDifference).Mul(transform2d->GetSize().Mul(transform2d->GetScale().xy()).Mul(screenFactor));
#if GAME
float2 windowPos = float2(App->window->GetPositionX(), App->window->GetPositionY());
worldAABB.minPoint += windowPos;
worldAABB.maxPoint += windowPos;
#endif
}
}
void ComponentBoundingBox2D::DrawGizmos() {
if (!App->time->HasGameStarted() && !App->userInterface->IsUsing2D() && drawOutline) {
dd::aabb(float3(worldAABB.minPoint, 0.0f), float3(worldAABB.maxPoint, 0.0f), float3::one);
}
}
void ComponentBoundingBox2D::Invalidate() {
dirty = true;
}
const AABB2D& ComponentBoundingBox2D::GetWorldAABB() const {
return worldAABB;
}
bool ComponentBoundingBox2D::CanBeRemoved() const {
return !GetOwner().GetComponent<ComponentSelectable>();
} |
SECTION .text
GLOBAL mul_p256
mul_p256:
sub rsp, 0x80 ; last 0x30 (6) for Caller - save regs
mov [ rsp + 0x50 ], rbx; saving to stack
mov [ rsp + 0x58 ], rbp; saving to stack
mov [ rsp + 0x60 ], r12; saving to stack
mov [ rsp + 0x68 ], r13; saving to stack
mov [ rsp + 0x70 ], r14; saving to stack
mov [ rsp + 0x78 ], r15; saving to stack
mov rax, [ rsi + 0x0 ]; load m64 x4 to register64
mov r10, rdx; preserving value of arg2 into a new reg
mov rdx, [ rdx + 0x8 ]; saving arg2[1] in rdx.
mulx r11, rbx, rax; x10, x9<- x4 * arg2[1]
mov rdx, rax; x4 to rdx
mulx rax, rbp, [ r10 + 0x0 ]; x12, x11<- x4 * arg2[0]
mulx r12, r13, [ r10 + 0x18 ]; x6, x5<- x4 * arg2[3]
mulx rdx, r14, [ r10 + 0x10 ]; x8, x7<- x4 * arg2[2]
xor r15, r15
adox rbx, rax
adox r14, r11
adox r13, rdx
mov rcx, 0xffffffff ; moving imm to reg
mov rdx, rbp; x11 to rdx
mulx rbp, r8, rcx; x23, x22<- x11 * 0xffffffff
adox r12, r15
mov r9, 0xffffffffffffffff ; moving imm to reg
mulx r11, rax, r9; x25, x24<- x11 * 0xffffffffffffffff
adcx r8, r11
mov r11, [ rsi + 0x8 ]; load m64 x1 to register64
adc rbp, 0x0
add rax, rdx; could be done better, if r0 has been u8 as well
adcx r8, rbx
mov rax, rdx; preserving value of x11 into a new reg
mov rdx, [ r10 + 0x0 ]; saving arg2[0] in rdx.
mulx rbx, r15, r11; x46, x45<- x1 * arg2[0]
mov r9, -0x2 ; moving imm to reg
inc r9; OF<-0x0, preserve CF (debug: 6; load -2, increase it, save as -1)
adox r15, r8
adcx rbp, r14
mov r14, 0xffffffffffffffff ; moving imm to reg
mov rdx, r14; 0xffffffffffffffff to rdx
mulx r14, r8, r15; x69, x68<- x54 * 0xffffffffffffffff
mov r9, [ rsi + 0x10 ]; load m64 x2 to register64
mov rdx, 0xffffffff00000001 ; moving imm to reg
mulx rax, rcx, rax; x21, x20<- x11 * 0xffffffff00000001
mov rdx, 0xffffffff ; moving imm to reg
mov [ rsp + 0x0 ], rdi; spilling out1 to mem
mov [ rsp + 0x8 ], r9; spilling x2 to mem
mulx rdi, r9, r15; x67, x66<- x54 * 0xffffffff
mov [ rsp + 0x10 ], rax; spilling x21 to mem
mov rax, rdx; preserving value of 0xffffffff into a new reg
mov rdx, [ r10 + 0x8 ]; saving arg2[1] in rdx.
mov [ rsp + 0x18 ], r12; spilling x19 to mem
mov [ rsp + 0x20 ], rcx; spilling x20 to mem
mulx r12, rcx, r11; x44, x43<- x1 * arg2[1]
setc al; spill CF x34 to reg (rax)
clc;
adcx r9, r14
mov r14, 0x0 ; moving imm to reg
adcx rdi, r14
mov rdx, r11; x1 to rdx
mulx r11, r14, [ r10 + 0x10 ]; x42, x41<- x1 * arg2[2]
clc;
adcx rcx, rbx
mulx rdx, rbx, [ r10 + 0x18 ]; x40, x39<- x1 * arg2[3]
adox rcx, rbp
adcx r14, r12
adcx rbx, r11
seto bpl; spill OF x57 to reg (rbp)
mov r12, -0x2 ; moving imm to reg
inc r12; OF<-0x0, preserve CF (debug: 6; load -2, increase it, save as -1)
adox r8, r15
setc r8b; spill CF x52 to reg (r8)
clc;
movzx rax, al
adcx rax, r12; loading flag
adcx r13, [ rsp + 0x20 ]
adox r9, rcx
mov rax, [ rsp + 0x10 ]; load m64 x21 to register64
mov r11, [ rsp + 0x18 ]; x37, copying x19 here, cause x19 is needed in a reg for other than x37, namely all: , x37--x38, size: 1
adcx r11, rax
movzx rax, r8b; x53, copying x52 here, cause x52 is needed in a reg for other than x53, namely all: , x53, size: 1
lea rax, [ rax + rdx ]
mov rdx, 0xffffffff00000001 ; moving imm to reg
mulx r15, rcx, r15; x65, x64<- x54 * 0xffffffff00000001
setc r8b; spill CF x38 to reg (r8)
clc;
movzx rbp, bpl
adcx rbp, r12; loading flag
adcx r13, r14
adcx rbx, r11
movzx rbp, r8b; x62, copying x38 here, cause x38 is needed in a reg for other than x62, namely all: , x62--x63, size: 1
adcx rbp, rax
adox rdi, r13
adox rcx, rbx
adox r15, rbp
seto r14b; spill OF x83 to reg (r14)
adc r14b, 0x0
movzx r14, r14b
mov r8, rdx; preserving value of 0xffffffff00000001 into a new reg
mov rdx, [ r10 + 0x0 ]; saving arg2[0] in rdx.
mulx r11, rax, [ rsp + 0x8 ]; x91, x90<- x2 * arg2[0]
adox rax, r9
mov r9, 0xffffffffffffffff ; moving imm to reg
mov rdx, rax; x99 to rdx
mulx rax, r13, r9; x114, x113<- x99 * 0xffffffffffffffff
mov rbx, 0xffffffff ; moving imm to reg
mulx rbp, r12, rbx; x112, x111<- x99 * 0xffffffff
mov rbx, rdx; preserving value of x99 into a new reg
mov rdx, [ r10 + 0x8 ]; saving arg2[1] in rdx.
mulx r8, r9, [ rsp + 0x8 ]; x89, x88<- x2 * arg2[1]
adcx r12, rax
mov rax, 0x0 ; moving imm to reg
adcx rbp, rax
clc;
adcx r13, rbx
mov rdx, [ r10 + 0x10 ]; arg2[2] to rdx
mulx r13, rax, [ rsp + 0x8 ]; x87, x86<- x2 * arg2[2]
mov byte [ rsp + 0x28 ], r14b; spilling byte x83 to mem
mov r14, [ rsi + 0x18 ]; load m64 x3 to register64
mov [ rsp + 0x30 ], r15; spilling x81 to mem
setc r15b; spill CF x119 to reg (r15)
clc;
adcx r9, r11
mov rdx, [ r10 + 0x8 ]; arg2[1] to rdx
mov [ rsp + 0x38 ], r13; spilling x87 to mem
mulx r11, r13, r14; x134, x133<- x3 * arg2[1]
adox r9, rdi
adcx rax, r8
adox rax, rcx
seto dil; spill OF x104 to reg (rdi)
mov rcx, 0x0 ; moving imm to reg
dec rcx; OF<-0x0, preserve CF (debug: state 4 (thanks Paul))
movzx r15, r15b
adox r15, rcx; loading flag
adox r9, r12
mov rdx, [ r10 + 0x0 ]; arg2[0] to rdx
mulx r8, r12, r14; x136, x135<- x3 * arg2[0]
adox rbp, rax
setc r15b; spill CF x95 to reg (r15)
clc;
adcx r13, r8
setc al; spill CF x138 to reg (rax)
clc;
adcx r12, r9
mov r9, 0xffffffffffffffff ; moving imm to reg
mov rdx, r12; x144 to rdx
mulx r12, r8, r9; x159, x158<- x144 * 0xffffffffffffffff
adcx r13, rbp
mov rbp, 0xffffffff ; moving imm to reg
mulx rcx, r9, rbp; x157, x156<- x144 * 0xffffffff
setc bpl; spill CF x147 to reg (rbp)
clc;
adcx r9, r12
mov r12, 0x0 ; moving imm to reg
adcx rcx, r12
mov r12, rdx; preserving value of x144 into a new reg
mov rdx, [ r10 + 0x18 ]; saving arg2[3] in rdx.
mov [ rsp + 0x40 ], rcx; spilling x162 to mem
mov byte [ rsp + 0x48 ], bpl; spilling byte x147 to mem
mulx rcx, rbp, [ rsp + 0x8 ]; x85, x84<- x2 * arg2[3]
clc;
adcx r8, r12
adcx r9, r13
setc r8b; spill CF x166 to reg (r8)
clc;
mov r13, -0x1 ; moving imm to reg
movzx r15, r15b
adcx r15, r13; loading flag
adcx rbp, [ rsp + 0x38 ]
mov r15, 0xffffffff00000001 ; moving imm to reg
mov rdx, r15; 0xffffffff00000001 to rdx
mulx rbx, r15, rbx; x110, x109<- x99 * 0xffffffff00000001
mov r13, 0x0 ; moving imm to reg
adcx rcx, r13
mulx r12, r13, r12; x155, x154<- x144 * 0xffffffff00000001
clc;
mov rdx, -0x1 ; moving imm to reg
movzx rdi, dil
adcx rdi, rdx; loading flag
adcx rbp, [ rsp + 0x30 ]
adox r15, rbp
mov rdx, r14; x3 to rdx
mulx r14, rdi, [ r10 + 0x10 ]; x132, x131<- x3 * arg2[2]
movzx rbp, byte [ rsp + 0x28 ]; x107, copying x83 here, cause x83 is needed in a reg for other than x107, namely all: , x107--x108, size: 1
adcx rbp, rcx
adox rbx, rbp
seto cl; spill OF x128 to reg (rcx)
adc cl, 0x0
movzx rcx, cl
mulx rdx, rbp, [ r10 + 0x18 ]; x130, x129<- x3 * arg2[3]
add al, 0x7F; load flag from rm/8 into OF, clears other flag. NODE, if operand1 is not a byte reg, this fails.
seto al; since that has deps, resore it whereever it was
adox r11, rdi
movzx rax, byte [ rsp + 0x48 ]; load byte memx147 to register64
mov rdi, -0x1 ; moving imm to reg
adcx rax, rdi; loading flag
adcx r15, r11
adox rbp, r14
mov rax, 0x0 ; moving imm to reg
adox rdx, rax
adcx rbp, rbx
dec rax; OF<-0x0, preserve CF (debug: state 1(0x0) (thanks Paul))
movzx r8, r8b
adox r8, rax; loading flag
adox r15, [ rsp + 0x40 ]
movzx r8, cl; x152, copying x128 here, cause x128 is needed in a reg for other than x152, namely all: , x152--x153, size: 1
adcx r8, rdx
adox r13, rbp
adox r12, r8
seto r14b; spill OF x173 to reg (r14)
adc r14b, 0x0
movzx r14, r14b
mov rbx, r9; x174, copying x165 here, cause x165 is needed in a reg for other than x174, namely all: , x174--x175, x184, size: 2
mov rcx, 0xffffffffffffffff ; moving imm to reg
sub rbx, rcx
mov r11, r15; x176, copying x167 here, cause x167 is needed in a reg for other than x176, namely all: , x176--x177, x185, size: 2
mov rdx, 0xffffffff ; moving imm to reg
sbb r11, rdx
mov rbp, r13; x178, copying x169 here, cause x169 is needed in a reg for other than x178, namely all: , x186, x178--x179, size: 2
sbb rbp, 0x00000000
mov r8, r12; x180, copying x171 here, cause x171 is needed in a reg for other than x180, namely all: , x187, x180--x181, size: 2
mov rax, 0xffffffff00000001 ; moving imm to reg
sbb r8, rax
movzx rdx, r14b; _, copying x173 here, cause x173 is needed in a reg for other than _, namely all: , _--x183, size: 1
sbb rdx, 0x00000000
cmovc r8, r12; if CF, x187<- x171 (nzVar)
mov r12, [ rsp + 0x0 ]; load m64 out1 to register64
mov [ r12 + 0x18 ], r8; out1[3] = x187
cmovc r11, r15; if CF, x185<- x167 (nzVar)
mov [ r12 + 0x8 ], r11; out1[1] = x185
cmovc rbp, r13; if CF, x186<- x169 (nzVar)
mov [ r12 + 0x10 ], rbp; out1[2] = x186
cmovc rbx, r9; if CF, x184<- x165 (nzVar)
mov [ r12 + 0x0 ], rbx; out1[0] = x184
mov rbx, [ rsp + 0x50 ]; restoring from stack
mov rbp, [ rsp + 0x58 ]; restoring from stack
mov r12, [ rsp + 0x60 ]; restoring from stack
mov r13, [ rsp + 0x68 ]; restoring from stack
mov r14, [ rsp + 0x70 ]; restoring from stack
mov r15, [ rsp + 0x78 ]; restoring from stack
add rsp, 0x80
ret
; cpu Intel(R) Core(TM) i9-10900K CPU @ 3.70GHz
; clocked at 4799 MHz
; first cyclecount 81.05, best 63.67857142857143, lastGood 63.88181818181818
; seed 3975821006667828
; CC / CFLAGS clang / -march=native -mtune=native -O3
; time needed: 656452 ms / 60000 runs=> 10.940866666666667ms/run
; Time spent for assembling and measureing (initial batch_size=112, initial num_batches=101): 124326 ms
; Ratio (time for assembling + measure)/(total runtime for 60000runs): 0.18939084655085214
; number reverted permutation/ tried permutation: 22223 / 29906 =74.310%
; number reverted decision/ tried decision: 23073 / 30095 =76.667% |
LoadRoomHook:
JSL.l IndoorTileTransitionCounter
.noStats
JSL Dungeon_LoadRoom
REP #$10 ; 16 bit XY
LDX $A0 ; Room ID
LDA RoomCallbackTable, X
SEP #$10 ; 8 bit XY
JSL UseImplicitRegIndexedLongJumpTable
; Callback routines:
dl NoCallback ; 00
dl IcePalaceBombosSE ; 01
dl IcePalaceBombosSW ; 02
dl IcePalaceBombosNE ; 03
NoCallback:
RTL
!RL_TILE = 2
!RL_LINE = 128
macro setTilePointer(roomX, roomY, quadX, quadY)
; Left-to-right math. Should be equivalent to 0x7e2000+(roomX*2)+(roomY*128)+(quadX*64)+(quadY*4096)
LDX.w #<quadY>*32+<roomY>*2+<quadX>*32+<roomX>*2
endmacro
macro writeTile()
STA.l $7E2000,x
INX #2
endmacro
!BOMBOS_BORDER = #$08D0
!BOMBOS_ICON_1 = #$0CCA
!BOMBOS_ICON_2 = #$0CCB
!BOMBOS_ICON_3 = #$0CDA
!BOMBOS_ICON_4 = #$0CDB
macro DrawBombosPlatform(roomX, roomY, quadX, quadY)
REP #$30 ; 16 AXY
%setTilePointer(<roomX>, <roomY>, <quadX>, <quadY>)
LDA.w !BOMBOS_BORDER
%writeTile()
%writeTile()
%writeTile()
%writeTile()
%setTilePointer(<roomX>, <roomY>+1, <quadX>, <quadY>)
%writeTile()
LDA.w !BOMBOS_ICON_1 : %writeTile()
LDA.w !BOMBOS_ICON_2 : %writeTile()
LDA.w !BOMBOS_BORDER : %writeTile()
%setTilePointer(<roomX>, <roomY>+2, <quadX>, <quadY>)
%writeTile()
LDA.w !BOMBOS_ICON_3 : %writeTile()
LDA.w !BOMBOS_ICON_4 : %writeTile()
LDA.w !BOMBOS_BORDER : %writeTile()
%setTilePointer(<roomX>, <roomY>+3, <quadX>, <quadY>)
%writeTile()
%writeTile()
%writeTile()
%writeTile()
SEP #$30 ; 8 AXY
endMacro
IcePalaceBombosSE:
LDA AllowSwordlessMedallionUse : BNE + : RTL : +
%DrawBombosPlatform(14, 18, 1, 1)
RTL
IcePalaceBombosSW:
LDA AllowSwordlessMedallionUse : BNE + : RTL : +
%DrawBombosPlatform(14, 18, 0, 1)
RTL
IcePalaceBombosNE:
LDA AllowSwordlessMedallionUse : BNE + : RTL : +
%DrawBombosPlatform(14, 18, 1, 0)
RTL
RoomCallbackTable:
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $01, $00 ; 00x
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 01x
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 02x
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 03x
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 04x
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 05x
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 06x
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $02, $00 ; 07x
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 08x
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 09x
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 0Ax
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 0Bx
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 0Cx
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $03, $00 ; 0Dx
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 0Ex
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 0Fx
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 0Fx
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 10x
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 11x
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; 12x |
; A160242: Triangle A(n,m) read by rows: a quarter of the Fourier coefficient [cos(m*t)] of the shifted Boubaker polynomial B_n(2*cos t)-2*cos(n*t).
; 1,2,1,2,2,2,1,2,2,2,2,2,1,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2
lpb $0
add $2,2
sub $0,$2
lpe
lpb $0
div $0,15
mov $1,1
lpe
add $1,1
|
LavenderHouse1Script:
call EnableAutoTextBoxDrawing
ret
LavenderHouse1TextPointers:
dw LavenderHouse1Text1
dw LavenderHouse1Text2
dw LavenderHouse1Text3
dw LavenderHouse1Text4
dw LavenderHouse1Text5
dw LavenderHouse1Text6
LavenderHouse1Text1:
TX_ASM
CheckEvent EVENT_RESCUED_MR_FUJI
jr nz, .asm_72e5d
ld hl, LavenderHouse1Text_1d8d1
call PrintText
jr .asm_6957f
.asm_72e5d
ld hl, LavenderHouse1Text_1d8d6
call PrintText
.asm_6957f
jp TextScriptEnd
LavenderHouse1Text_1d8d1:
TX_FAR _LavenderHouse1Text_1d8d1
db "@"
LavenderHouse1Text_1d8d6:
TX_FAR _LavenderHouse1Text_1d8d6
db "@"
LavenderHouse1Text2:
TX_ASM
CheckEvent EVENT_RESCUED_MR_FUJI
jr nz, .asm_06470
ld hl, LavenderHouse1Text_1d8f4
call PrintText
jr .asm_3d208
.asm_06470
ld hl, LavenderHouse1Text_1d8f9
call PrintText
.asm_3d208
jp TextScriptEnd
LavenderHouse1Text_1d8f4:
TX_FAR _LavenderHouse1Text_1d8f4
db "@"
LavenderHouse1Text_1d8f9:
TX_FAR _LavenderHouse1Text_1d8f9
db "@"
LavenderHouse1Text3:
TX_FAR _LavenderHouse1Text3
TX_ASM
ld a, PSYDUCK
call PlayCry
jp TextScriptEnd
LavenderHouse1Text4:
TX_FAR _LavenderHouse1Text4
TX_ASM
ld a, NIDORINO
call PlayCry
jp TextScriptEnd
LavenderHouse1Text5:
TX_ASM
CheckEvent EVENT_GOT_POKE_FLUTE
jr nz, .asm_15ac2
ld hl, LavenderHouse1Text_1d94c
call PrintText
lb bc, POKE_FLUTE, 1
call GiveItem
jr nc, .BagFull
ld hl, ReceivedFluteText
call PrintText
SetEvent EVENT_GOT_POKE_FLUTE
jr .asm_da749
.BagFull
ld hl, FluteNoRoomText
call PrintText
jr .asm_da749
.asm_15ac2
ld hl, MrFujiAfterFluteText
call PrintText
.asm_da749
jp TextScriptEnd
LavenderHouse1Text_1d94c:
TX_FAR _LavenderHouse1Text_1d94c
db "@"
ReceivedFluteText:
TX_FAR _ReceivedFluteText
TX_SFX_KEY_ITEM
TX_FAR _FluteExplanationText
db "@"
FluteNoRoomText:
TX_FAR _FluteNoRoomText
db "@"
MrFujiAfterFluteText:
TX_FAR _MrFujiAfterFluteText
db "@"
LavenderHouse1Text6:
TX_FAR _LavenderHouse1Text6
db "@"
|
/*F***************************************************************************
* This file is part of openSMILE.
*
* Copyright (c) audEERING GmbH. All rights reserved.
* See the file COPYING for details on license terms.
***************************************************************************E*/
/* openSMILE plugin loader */
#include <core/smileCommon.hpp>
#include <core/smileLogger.hpp>
#include <core/componentManager.hpp>
//++ include all your component headers here: ----------------
#include <exampleGuipluginSink.hpp>
#include <simpleVisualiserGUI.hpp>
#include <classifierResultGUI.hpp>
//++ ---------------------------------------------------------
// dll export for msvc++
#ifdef _MSC_VER
#define DLLEXPORT_P __declspec(dllexport)
#else
#define DLLEXPORT_P
#endif
#define MODULE "pluginLoader"
static DLLLOCAL const registerFunction complist[] = {
//++ add your component register functions here: -------------
cExampleGuipluginSink::registerComponent,
cSimpleVisualiserGUI::registerComponent,
cClassifierResultGUI::registerComponent,
//++ ---------------------------------------------------------
NULL // last element must always be NULL to terminate the list !!
};
sComponentInfo *master=NULL;
//Library:
extern "C" DLLEXPORT_P sComponentInfo * registerPluginComponent(cConfigManager *_confman, cComponentManager *_compman) {
registerFunction f;
sComponentInfo *cur = NULL, *last = NULL;
int i=0;
f = complist[i];
while (f!=NULL) {
cur = (f)(_confman, _compman);
cur->next = NULL;
if (i==0) master = cur;
else { last->next = cur; }
last = cur;
f=complist[++i];
}
return master;
}
/*extern "C" DLLEXPORT_P sComponentInfo * registerPluginComponent(cConfigManager *_confman, cComponentManager *_compman) {
return (sComponentInfo *)complist;
}*/
// this function frees all memory allocated within the scope of the dll ...
extern "C" DLLEXPORT_P void unRegisterPluginComponent() {
while (master != NULL) {
sComponentInfo *tmp = master;
if (master->next != NULL) master = master->next;
delete tmp;
}
}
|
; A081610: Number of numbers <= n having at least one 2 in their ternary representation.
; 0,0,1,1,1,2,3,4,5,5,5,6,6,6,7,8,9,10,11,12,13,14,15,16,17,18,19,19,19,20,20,20,21,22,23,24,24,24,25,25,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,65,65,66,66,66,67,68,69,70,70,70,71,71,71,72,73,74,75,76
mov $1,$0
seq $1,81611 ; Number of numbers <= n having no 2 in their ternary representation.
sub $0,$1
add $0,1
|
db ESPEON ; 196
db 65, 65, 60, 110, 130, 95
; hp atk def spd sat sdf
db PSYCHIC, PSYCHIC ; type
db 45 ; catch rate
db 197 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F12_5 ; gender ratio
db 100 ; unknown 1
db 35 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/espeon/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_FAST ; growth rate
dn EGG_GROUND, EGG_GROUND ; egg groups
; tm/hm learnset
tmhm HEADBUTT, CURSE, TOXIC, ZAP_CANNON, PSYCH_UP, HIDDEN_POWER, SUNNY_DAY, SNORE, HYPER_BEAM, PROTECT, RAIN_DANCE, ENDURE, FRUSTRATION, IRON_TAIL, RETURN, PSYCHIC_M, SHADOW_BALL, MUD_SLAP, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SWIFT, DREAM_EATER, DETECT, REST, ATTRACT, NIGHTMARE, CUT, FLASH
; end
|
//
// Created by roman Sztergbaum on 01/06/2018.
//
#pragma once
#include <shiva/entt/entt.hpp>
#include <shiva/ecs/system_type.hpp>
namespace shiva::ecs
{
/**
* \class base_system
* \note This class is an abstract class, it is documented but
* is present only to make type-erasure of the class system which is templated.
* \note This class can be manipulated when using plugins to share data between them.
*/
class base_system
{
public:
//! Constructors
inline explicit base_system(entt::dispatcher &dispatcher,
entt::entity_registry &entity_registry,
const float &fixed_delta_time, bool im_plugin = false) noexcept;
//! Destructor
virtual ~base_system() noexcept = default;
//! Pure virtual functions
virtual void update() noexcept = 0;
virtual const std::string &get_name() const noexcept = 0;
virtual system_type get_system_type_RTTI() const noexcept = 0;
//! Public member functions
/**
* \note This function marks the system, it will be destroyed in the next turn of the game loop by the system_manager.
*/
inline void mark() noexcept;
/**
* \note This function unmark the system, allows the prevention of a destruction in the next turn of the game loop by the system_manager.
*/
inline void unmark() noexcept;
/**
* \note This function tell you if a system is marked or no.
* \return true if the system is marked, false otherwise
*/
inline bool is_marked() const noexcept;
/**
* \note This function enable a system.
* \note by default a system is enabled.
*/
inline void enable() noexcept;
/**
* \note This function disable a system.
*/
inline void disable() noexcept;
/**
* \note This function tell you if a system is enable or no.
*/
inline bool is_enabled() const noexcept;
/**
* \note This function defines the system as a plugin, and therefore will use more feature in runtime to work properly
*/
inline void im_a_plugin() noexcept;
/**
* \note This function tell you if a system is a plugin or no
* \return true if the system is a plugin, false otherwise
*/
inline bool is_a_plugin() const noexcept;
/**
* \note This function retrieve a user data previously set by set_user_data
* \note by default a user_data is a void pointer equal to nullptr.
* \return user data of a system
*/
inline void *get_user_data() noexcept;
/**
* \note This function set a user data for this system
* \note This function is very usefull to transfer (with get_user_data) data between plugins since they are base_class.
* \note This function will call on_set_user_data callback at the epilogue, by default on_set_user_data is empty and you need
* to override it if you need it.
* \note user should be aware here, that's manipulating void pointer is as your own risk.
* \param data a void pointer representing the user data
*/
inline void set_user_data(void *data) noexcept;
protected:
//! Protected virtual functions
virtual void on_set_user_data_() noexcept
{}
//! Protected data members
entt::dispatcher &dispatcher_;
entt::entity_registry &entity_registry_;
const float &fixed_delta_time_;
void *user_data_{nullptr};
private:
//! Private data members
bool is_plugin{false};
bool marked_{false};
bool enabled_{true};
};
}
namespace shiva::ecs
{
//! Constructors
base_system::base_system(entt::dispatcher &dispatcher, entt::entity_registry &entity_registry,
const float &fixed_delta_time, bool im_plugin) noexcept :
dispatcher_(dispatcher),
entity_registry_(entity_registry),
fixed_delta_time_(fixed_delta_time),
is_plugin{im_plugin}
{
}
//! Public member functions
void base_system::mark() noexcept
{
marked_ = true;
}
void base_system::unmark() noexcept
{
marked_ = false;
}
bool base_system::is_marked() const noexcept
{
return marked_;
}
void base_system::enable() noexcept
{
enabled_ = true;
}
void base_system::disable() noexcept
{
enabled_ = false;
}
bool base_system::is_enabled() const noexcept
{
return enabled_;
}
void base_system::im_a_plugin() noexcept
{
is_plugin = true;
}
bool base_system::is_a_plugin() const noexcept
{
return is_plugin;
}
void *base_system::get_user_data() noexcept
{
return user_data_;
}
void base_system::set_user_data(void *data) noexcept
{
user_data_ = data;
on_set_user_data_();
}
} |
// Distributed under the MIT License.
// See LICENSE.txt for details.
/// \file
/// Defines all group definitions
#pragma once
/*!
* \defgroup ActionsGroup Actions
* \brief A collection of steps used in algorithms.
*/
/*!
* \defgroup AnalyticDataGroup Analytic Data
* \brief Analytic data used to specify (for example) initial data to the
* equations implemented in \ref EvolutionSystemsGroup.
*/
/*!
* \defgroup AnalyticSolutionsGroup Analytic Solutions
* \brief Analytic solutions to the equations implemented in \ref
* EvolutionSystemsGroup and \ref EllipticSystemsGroup.
*/
/*!
* \defgroup BoundaryConditionsGroup Boundary Conditions
* A collection of boundary conditions used for evolutions.
*/
/*!
* \defgroup CharmExtensionsGroup Charm++ Extensions
* \brief Classes and functions used to make Charm++ easier and safer to use.
*/
/*!
* \defgroup ComputationalDomainGroup Computational Domain
* \brief The building blocks used to describe the computational domain.
*
* ### Description
* The VolumeDim-dimensional computational Domain is constructed from a set of
* non-overlapping Block%s. Each Block is a distorted VolumeDim-dimensional
* hypercube. Each codimension-1 boundary of a Block is either part of the
* external boundary of the computational domain, or is identical to a boundary
* of one other Block. Each Block is subdivided into one or more Element%s
* that may be changed dynamically if AMR is enabled.
*/
/*!
* \defgroup ConservativeGroup Conservative System Evolution
* \brief Contains generic functions used for evolving conservative
* systems.
*/
/*!
* \defgroup ConstantExpressionsGroup Constant Expressions
* \brief Contains an assortment of constexpr functions
*
* ### Description
* Contains an assortment of constexpr functions that are useful for
* metaprogramming, or efficient mathematical computations, such as
* exponentiating to an integer power, where the power is known at compile
* time.
*/
/*!
* \defgroup ControlSystemGroup Control System
* \brief Contains control system elements
*
* The control system manages the time-dependent mapping between frames, such as
* the fixed computational frame (grid frame) and the inertial frame. The
* time-dependent parameters of the mapping are adjusted by a feedback control
* system in order to follow the dynamical evolution of objects such as horizons
* of black holes or surfaces of neutron stars. For example, in binary black
* hole simulations the map is typically a composition of maps that include
* translation, rotation, scaling, shape, etc.
* Each map under the governance of the control system has an associated
* time-dependent map parameter \f$\lambda(t)\f$ that is a piecewise Nth order
* polynomial. At discrete times (called reset times), the control system resets
* the Nth time derivative of \f$\lambda(t)\f$ to a new constant value, in order
* to minimize an error function \f$Q(t)\f$ that is specific to each map. At
* each reset time, the Nth derivative of \f$\lambda(t)\f$ is set to a function
* \f$U(t)\f$, called the control signal, that is determined by \f$Q(t)\f$ and
* its time derivatives and time integral. Note that \f$\lambda(t)\f$,
* \f$U(t)\f$, and \f$Q(t)\f$ can be vectors.
*
* The key components of the control system are:
* - FunctionsOfTime: each map has an associated FunctionOfTime that represents
* the map parameter \f$\lambda(t)\f$ and relevant time derivatives.
* - ControlError: each map has an associated ControlError that computes
* the error, \f$Q(t)\f$. Note that for each map, \f$Q(t)\f$ is defined to
* follow the convention that \f$dQ = -d \lambda\f$ as \f$Q \rightarrow 0\f$.
* - Averager: an averager can be used to average out the noise in the 'raw'
* \f$Q(t)\f$ returned by the ControlError.
* - Controller: the map controller computes the control signal \f$U(t)\f$ from
* \f$Q(t)\f$ and its time integral and time derivatives.
* The control is accomplished by setting the Nth derivative of
* \f$\lambda(t)\f$ to \f$U(t)\f$. Two common controllers are PID
* (proportional/integral/derivative)
* \f[U(t) = a_{0}\int_{t_{0}}^{t} Q(t') dt'+a_{1}Q(t)+a_{2}\frac{dQ}{dt}\f]
* or
* PND (proportional/N derivatives)
* \f[ U(t) = \sum_{k=0}^{N} a_{k} \frac{d^kQ}{dt^k} \f]
* The coefficients \f$ a_{k} \f$ in the computation of \f$U(t)\f$ are chosen
* at each time such that the error \f$Q(t)\f$ will be critically damped
* on a timescale of \f$\tau\f$ (the damping time),
* i.e. \f$Q(t) \propto e^{-t/\tau}\f$.
* - TimescaleTuner: each map has a TimescaleTuner that dynamically adjusts
* the damping timescale \f$\tau\f$ appropriately to keep the error \f$Q(t)\f$
* within some specified error bounds. Note that the reset time interval,
* \f$\Delta t\f$, is a constant fraction of this damping timescale,
* i.e. \f$\Delta t = \alpha \tau\f$ (empirically, we have found
* \f$\alpha=0.3\f$ to be a good choice).
*
*
* For additional details describing our control system approach, see
* \cite Hemberger2012jz.
*/
/*!
* \defgroup CoordinateMapsGroup Coordinate Maps
* \brief Functions for mapping coordinates between different frames
*
* Coordinate maps provide the maps themselves, the inverse maps, along
* with the Jacobian and inverse Jacobian of the maps.
*/
/*!
* \defgroup CoordMapsTimeDependentGroup Coordinate Maps, Time-dependent
* \brief Functions for mapping time-dependent coordinates between different
* frames
*
* Coordinate maps provide the maps themselves, the inverse maps, the Jacobian
* and inverse Jacobian of the maps, and the frame velocity (time derivative of
* the map)
*/
/*!
* \defgroup DataBoxGroup DataBox
* \brief Documentation, functions, metafunctions, and classes necessary for
* using DataBox
*
* DataBox is a heterogeneous compile-time associative container with lazy
* evaluation of functions. DataBox can not only store data, but can also store
* functions that depend on other data inside the DataBox. The functions will be
* evaluated when the data they return is requested. The result is cached, and
* if a dependency of the function is modified the cache is invalidated.
*
* #### Simple and Compute Tags and Their Items
*
* The compile-time keys are `struct`s called tags, while the values are called
* items. Tags are quite minimal, containing only the information necessary to
* store the data and evaluate functions. There are two different types of tags
* that a DataBox can hold: simple tags and compute tags. Simple tags are for
* data that is inserted into the DataBox at the time of creation, while compute
* tags are for data that will be computed from a function when the compute item
* is retrieved. If a compute item is never retrieved from the DataBox then it
* is never evaluated.
*
* Simple tags must have a member type alias `type` that is the type of the data
* to be stored and a `static std::string name()` method that returns the name
* of the tag. Simple tags must inherit from `db::SimpleTag`.
*
* Compute tags must also have a `static std::string name()` method that returns
* the name of the tag, but they cannot have a `type` type alias. Instead,
* compute tags must have a static member function or static member function
* pointer named `function`. `function` can be a function template if necessary.
* The `function` must take all its arguments by `const` reference. The
* arguments to the function are retrieved using tags from the DataBox that the
* compute tag is in. The tags for the arguments are set in the member type
* alias `argument_tags`, which must be a `tmpl::list` of the tags corresponding
* to each argument. Note that the order of the tags in the `argument_list` is
* the order that they will be passed to the function. Compute tags must inherit
* from `db::ComputeTag`.
*
* Here is an example of a simple tag:
*
* \snippet Test_DataBox.cpp databox_tag_example
*
* and an example of a compute tag with a function pointer:
*
* \snippet Test_DataBox.cpp databox_compute_item_tag_example
*
* If the compute item's tag is inline then the compute item is of the form:
*
* \snippet Test_DataBox.cpp compute_item_tag_function
*
* Compute tags can also have their functions be overloaded on the type of its
* arguments:
*
* \snippet Test_DataBox.cpp overload_compute_tag_type
*
* or be overloaded on the number of arguments:
*
* \snippet Test_DataBox.cpp overload_compute_tag_number_of_args
*
* Compute tag function templates are implemented as follows:
*
* \snippet Test_DataBox.cpp overload_compute_tag_template
*
* Finally, overloading, function templates, and variadic functions can be
* combined to produce extremely generic compute tags. The below compute tag
* takes as template parameters a parameter pack of integers, which is used to
* specify several of the arguments. The function is overloaded for the single
* argument case, and a variadic function template is provided for the multiple
* arguments case. Note that in practice few compute tags will be this complex.
*
* \snippet Test_BaseTags.cpp compute_template_base_tags
*
* #### Subitems and Prefix Tags
*
* A simple or compute tag might also hold a collection of data, such as a
* container of `Tensor`s. In many cases you will want to be able to retrieve
* individual elements of the collection from the DataBox without having to
* first retrieve the collection. The infrastructure that allows for this is
* called *Subitems*. The subitems of the parent tag must refer to a subset of
* the data inside the parent tag, e.g. one `Tensor` in the collection. If the
* parent tag is `Parent` and the subitems tags are `Sub<0>, Sub<1>`, then when
* `Parent` is added to the DataBox, so are `Sub<0>` and `Sub<1>`. This means
* the retrieval mechanisms described below will work on `Parent`, `Sub<0>`, and
* `Sub<1>`.
*
* Subitems specify requirements on the tags they act on. For example, there
* could be a requirement that all tags with a certain type are to be treated as
* a Subitms. Let's say that the `Parent` tag holds a `Variables`, and
* `Variables` can be used with the Subitems infrastructure to add the nested
* `Tensor`s. Then all tags that hold a `Variables` will have their subitems
* added into the DataBox. To add a new type as a subitem the `db::Subitems`
* struct must be specialized. See the documentation of `db::Subitems` for more
* details.
*
* The DataBox also supports *prefix tags*, which are commonly used for items
* that are related to a different item by some operation. Specifically, say
* you have a tag `MyTensor` and you want to also have the time derivative of
* `MyTensor`, then you can use the prefix tag `dt` to get `dt<MyTensor>`. The
* benefit of a prefix tag over, say, a separate tag `dtMyTensor` is that prefix
* tags can be added and removed by the compute tags acting on the original tag.
* Prefix tags can also be composed, so a second time derivative would be
* `dt<dt<MyTensor>>`. The net result of the prefix tags infrastructure is that
* the compute tag that returns `dt<MyTensor>` only needs to know its input
* tags, it knows how to name its output based off that. In addition to the
* normal things a simple or a compute tag must hold, prefix tags must have a
* nested type alias `tag`, which is the tag being prefixed. Prefix tags must
* also inherit from `db::PrefixTag` in addition to inheriting from
* `db::SimpleTag` or `db::ComputeTag`.
*
* #### Creating a DataBox
*
* You should never call the constructor of a DataBox directly. DataBox
* construction is quite complicated and the helper functions `db::create` and
* `db::create_from` should be used instead. `db::create` is used to construct a
* new DataBox. It takes two typelists as explicit template parameters, the
* first being a list of the simple tags to add and the second being a list of
* compute tags to add. If no compute tags are being added then only the simple
* tags list must be specified. The tags lists should be passed as
* `db::create<db::AddSimpleTags<simple_tags...>,
* db::AddComputeTags<compute_tags...>>`. The arguments to `db::create` are the
* initial values of the simple tags and must be passed in the same order as the
* tags in the `db::AddSimpleTags` list. If the type of an argument passed to
* `db::create` does not match the type of the corresponding simple tag a static
* assertion will trigger. Here is an example of how to use `db::create`:
*
* \snippet Test_DataBox.cpp create_databox
*
* To create a new DataBox from an existing one use the `db::create_from`
* function. The only time a new DataBox needs to be created is when tags need
* to be removed or added. Like `db::create`, `db::create_from` also takes
* typelists as explicit template parameter. The first template parameter is the
* list of tags to be removed, which is passed using `db::RemoveTags`, second is
* the list of simple tags to add, and the third is the list of compute tags to
* add. If tags are only removed then only the first template parameter needs to
* be specified. If tags are being removed and only simple tags are being added
* then only the first two template parameters need to be specified. Here is an
* example of removing a tag or compute tag:
*
* \snippet Test_DataBox.cpp create_from_remove
*
* Adding a simple tag is done using:
*
* \snippet Test_DataBox.cpp create_from_add_item
*
* Adding a compute tag is done using:
*
* \snippet Test_DataBox.cpp create_from_add_compute_item
*
* #### Accessing and Mutating Items
*
* To retrieve an item from a DataBox use the `db::get` function. `db::get`
* will always return a `const` reference to the object stored in the DataBox
* and will also have full type information available. This means you are able
* to use `const auto&` when retrieving tags from the DataBox. For example,
* \snippet Test_DataBox.cpp using_db_get
*
* If you want to mutate the value of a simple item in the DataBox use
* `db::mutate`. Any compute item that depends on the mutated item will have its
* cached value invalidated and be recomputed the next time it is retrieved from
* the DataBox. `db::mutate` takes a parameter pack of tags to mutate as
* explicit template parameters, a `gsl::not_null` of the DataBox whose items
* will be mutated, an invokable, and extra arguments to forward to the
* invokable. The invokable takes the arguments passed from the DataBox by
* `const gsl::not_null` while the extra arguments are forwarded to the
* invokable. The invokable is not allowed to retrieve anything from the
* DataBox, so any items must be passed as extra arguments using `db::get` to
* retrieve them. For example,
*
* \snippet Test_DataBox.cpp databox_mutate_example
*
* In addition to retrieving items using `db::get` and mutating them using
* `db::mutate`, there is a facility to invoke an invokable with tags from the
* DataBox. `db::apply` takes a `tmpl::list` of tags as an explicit template
* parameter, will retrieve all the tags from the DataBox passed in and then
* invoke the invokable with the items in the tag list. Similarly,
* `db::mutate_apply` invokes the invokable but allows for mutating some of
* the tags. See the documentation of `db::apply` and `db::mutate_apply` for
* examples of how to use them.
*
* #### The Base Tags Mechanism
*
* Retrieving items by tags should not require knowing whether the item being
* retrieved was computed using a compute tag or simply added using a simple
* tag. The framework that handles this falls under the umbrella term
* *base tags*. The reason is that a compute tag can inherit from a simple tag
* with the same item type, and then calls to `db::get` with the simple tag can
* be used to retrieve the compute item as well. That is, say you have a compute
* tag `ArrayCompute` that derives off of the simple tag `Array`, then you can
* retrieve the compute tag `ArrayCompute` and `Array` by calling
* `db::get<Array>(box)`. The base tags mechanism requires that only one `Array`
* tag be present in the DataBox, otherwise a static assertion is triggered.
*
* The inheritance idea can be generalized further with what are called base
* tags. A base tag is an empty `struct` that inherits from `db::BaseTag`. Any
* simple or compute item that derives off of the base tag can be retrieved
* using `db::get`. Consider the following `VectorBase` and `Vector` tag:
*
* \snippet Test_BaseTags.cpp vector_base_definitions
*
* It is possible to retrieve `Vector<1>` from the DataBox using
* `VectorBase<1>`. Most importantly, base tags can also be used in compute tag
* arguments, as follows:
*
* \snippet Test_BaseTags.cpp compute_template_base_tags
*
* As shown in the code example, the base tag mechanism works with function
* template compute tags, enabling generic programming to be combined with the
* lazy evaluation and automatic dependency analysis offered by the DataBox. To
* really demonstrate the power of base tags, let's also have `ArrayComputeBase`
* inherit from a simple tag `Array`, which inherits from a base tag `ArrayBase`
* as follows:
*
* \snippet Test_BaseTags.cpp array_base_definitions
*
* To start, let's create a DataBox that holds a `Vector<0>` and an
* `ArrayComputeBase<0>` (the concrete tag must be used when creating the
* DataBox, not the base tags), retrieve the tags using the base tag mechanism,
* including mutating `Vector<0>`, and then verifying that the dependencies are
* handled correctly.
*
* \snippet Test_BaseTags.cpp base_simple_and_compute_mutate
*
* Notice that we are able to retrieve `ArrayComputeBase<0>` with `ArrayBase<0>`
* and `Array<0>`. We were also able to mutate `Vector<0>` using
* `VectorBase<0>`.
*
* We can even remove tags using their base tags with `db::create_from`:
*
* \snippet Test_BaseTags.cpp remove_using_base
*
* The base tags infrastructure even works with Subitems. Even if you mutate the
* subitem of a parent using a base tag, the appropriate compute item caches
* will be invalidated.
*
* \note All of the base tags infrastructure works for `db::get`, `db::mutate`,
* `db::apply` and `db::mutate_apply`.
*/
/*!
* \defgroup DataBoxTagsGroup DataBox Tags
* \brief Structures and metafunctions for labeling the contents of DataBoxes
*/
/*!
* \defgroup DataStructuresGroup Data Structures
* \brief Various useful data structures used in SpECTRE
*/
/*!
* \defgroup DiscontinuousGalerkinGroup Discontinuous Galerkin
* \brief Functions and classes specific to the Discontinuous Galerkin
* algorithm.
*/
/*!
* \defgroup EllipticSystemsGroup Elliptic Systems
* \brief All available elliptic systems and information on how to implement
* elliptic systems
*
* \details Actions and parallel components may require an elliptic system to
* expose the following types:
*
* - `volume_dim`: The number of spatial dimensions
* - `fields_tag`: A \ref DataBoxGroup tag that represents the fields being
* solved for.
* - `variables_tag`: The variables to compute DG volume contributions and
* fluxes for. Use `db::add_tag_prefix<LinearSolver::Tags::Operand, fields_tag>`
* unless you have a reason not to.
* - `compute_operator_action`: A struct that computes the bulk contribution to
* the DG operator. Must expose a `tmpl::list` of `argument_tags` and a static
* `apply` function that takes the following arguments in this order:
* - First, the types of the tensors in
* `db::add_tag_prefix<Metavariables::temporal_id::step_prefix, variables_tag>`
* (which represent the linear operator applied to the variables) as not-null
* pointers.
* - Followed by the types of the `argument_tags` as constant references.
*
* Actions and parallel components may also require the Metavariables to expose
* the following types:
*
* - `system`: See above.
* - `temporal_id`: A DataBox tag that identifies steps in the algorithm.
* Generally use `LinearSolver::Tags::IterationId`.
*/
/*!
* \defgroup EquationsOfStateGroup Equations of State
* \brief The various available equations of state
*/
/*!
* \defgroup ErrorHandlingGroup Error Handling
* Macros and functions used for handling errors
*/
/*!
* \defgroup EventsAndTriggersGroup Events and Triggers
* \brief Classes and functions related to events and triggers
*/
/*!
* \defgroup EvolutionSystemsGroup Evolution Systems
* \brief All available evolution systems and information on how to implement
* evolution systems
*
* \details Actions and parallel components may require an evolution system to
* expose the following types:
*
* - `volume_dim`: The number of spatial dimensions
* - `variables_tag`: The evolved variables to compute DG volume contributions
* and fluxes for.
* - `compute_time_derivative`: A struct that computes the bulk contribution to
* the DG discretization of the time derivative. Must expose a `tmpl::list` of
* `argument_tags` and a static `apply` function that takes the following
* arguments in this order:
* - First, the types of the tensors in
* `db::add_tag_prefix<Metavariables::temporal_id::step_prefix, variables_tag>`
* (which represent the time derivatives of the variables) as not-null pointers.
* - The types of the `argument_tags` as constant references.
*
* Actions and parallel components may also require the Metavariables to expose
* the following types:
*
* - `system`: See above.
* - `temporal_id`: A DataBox tag that identifies steps in the algorithm.
* Generally use `Tags::TimeStepId`.
*/
/*!
* \defgroup ExecutablesGroup Executables
* \brief A list of executables and how to use them
*
* <table class="doxtable">
* <tr>
* <th>Executable Name </th><th>Description </th>
* </tr>
* <tr>
* <td> \ref ParallelInfoExecutablePage "ParallelInfo" </td>
* <td> Executable for checking number of nodes, cores, etc.</td>
* </tr>
* </table>
*/
/*!
* \defgroup FileSystemGroup File System
* \brief A light-weight file system library.
*/
/*!
* \defgroup GeneralRelativityGroup General Relativity
* \brief Contains functions used in General Relativistic simulations
*/
/*!
* \defgroup HDF5Group HDF5
* \brief Functions and classes for manipulating HDF5 files
*/
/*!
* \defgroup InitializationGroup Initialization
* \brief Actions and metafunctions used for initialization of parallel
* components.
*/
/*!
* \defgroup LimitersGroup Limiters
* \brief Limiters to control shocks and surfaces in the solution.
*/
/*!
* \defgroup LinearSolverGroup Linear Solver
* \brief Algorithms to solve linear systems of equations
*
* \details In a way, the linear solver is for elliptic systems what time
* stepping is for the evolution code. This is because the DG scheme for an
* elliptic system reduces to a linear system of equations of the type
* \f$Ax=b\f$, where \f$A\f$ is a global matrix representing the DG
* discretization of the problem. Since this is one equation for each node in
* the computational domain it becomes unfeasible to numerically invert the
* global matrix \f$A\f$. Instead, we solve the problem iteratively so that we
* never need to construct \f$A\f$ globally but only need \f$Ax\f$ that can be
* evaluated locally by virtue of the DG formulation. This action of the
* operator is what we have to supply in each step of the iterative algorithms
* implemented here. It is where most of the computational cost goes and usually
* involves computing a volume contribution for each element and communicating
* fluxes with neighboring elements. Since the iterative algorithms typically
* scale badly with increasing grid size, a preconditioner \f$P\f$ is needed
* in order to make \f$P^{-1}A\f$ easier to invert.
*
* In the iterative algorithms we usually don't work with the physical field
* \f$x\f$ directly. Instead we need to apply the operator to an internal
* variable defined by the respective algorithm. This variable is exposed as the
* `LinearSolver::Tags::Operand` prefix, and the algorithm expects that the
* computed operator action is written into
* `db::add_tag_prefix<LinearSolver::Tags::OperatorAppliedTo,
* LinearSolver::Tags::Operand<...>>` in each step.
*
* Each linear solver is expected to expose the following compile-time
* interface:
* - `component_list`: A `tmpl::list` that collects the additional parallel
* components this linear solver uses. The executables will append these to
* their own `component_list`.
* - `initialize_element`: An action that initializes the DataBox items
* required by the linear solver.
* - `reinitialize_element`: An action that resets the linear solver to its
* initial state.
* - `perform_step`: The action to be executed after the linear operator has
* been applied to the operand and written to the DataBox (see above). It will
* converge the fields towards their solution and update the operand before
* handing responsibility back to the algorithm for the next application of the
* linear operator:
* \snippet LinearSolverAlgorithmTestHelpers.hpp action_list
*/
/// \defgroup LoggingGroup Logging
/// \brief Functions for logging progress of running code
/// \defgroup MathFunctionsGroup Math Functions
/// \brief Useful analytic functions
/*!
* \defgroup NumericalAlgorithmsGroup Numerical Algorithms
* \brief Generic numerical algorithms
*/
/*!
* \defgroup NumericalFluxesGroup Numerical Fluxes
* \brief The set of available numerical fluxes
*/
/*!
* \defgroup ObserversGroup Observers
* \brief Observing/writing data to disk.
*/
/*!
* \defgroup OptionGroupsGroup Option Groups
* \brief Tags used for grouping input file options.
*
* An \ref OptionTagsGroup "option tag" can be placed in a group with other
* option tags to give the input file more structure. To assign a group to an
* option tag, set its `group` type alias to a struct that provides a help
* string and may override a static `name()` function:
*
* \snippet Test_Options.cpp options_example_group
*
* A number of commonly used groups are listed here.
*
* See also the \ref dev_guide_option_parsing "option parsing guide".
*/
/*!
* \defgroup OptionParsingGroup Option Parsing
* Things related to parsing YAML input files.
*/
/*!
* \defgroup OptionTagsGroup Option Tags
* \brief Tags used for options parsed from the input file.
*
* These can be stored in the ConstGlobalCache or passed to the `initialize`
* function of a parallel component.
*/
/*!
* \defgroup ParallelGroup Parallelization
* \brief Functions, classes and documentation related to parallelization and
* Charm++
*
* See
* \ref dev_guide_parallelization_foundations "Parallelization infrastructure"
* for details.
*/
/*!
* \defgroup PeoGroup Performance, Efficiency, and Optimizations
* \brief Classes and functions useful for performance optimizations.
*/
/*!
* \defgroup PrettyTypeGroup Pretty Type
* \brief Pretty printing of types
*/
/*!
* \defgroup ProtocolsGroup Protocols
* \brief Classes that define metaprogramming interfaces
*
* See the \ref protocols section of the dev guide for details.
*/
/*!
* \defgroup PythonBindingsGroup Python Bindings
* \brief Classes and functions useful when writing python bindings.
*
* See the \ref spectre_writing_python_bindings "Writing Python Bindings"
* section of the dev guide for details on how to write python bindings.
*/
/*!
* \defgroup SpectralGroup Spectral
* Things related to spectral transformations.
*/
// Note: this group is ordered by how it appears in the rendered Doxygen pages
// (i.e., "Spin-weighted..."), rather than the group's name (i.e., "Swsh...").
/*!
* \defgroup SwshGroup Spin-weighted spherical harmonics
* Utilities, tags, and metafunctions for using and manipulating spin-weighted
* spherical harmonics
*/
/*!
* \defgroup SurfacesGroup Surfaces
* Things related to surfaces.
*/
/*!
* \defgroup TensorGroup Tensor
* Tensor use documentation.
*/
/*!
* \defgroup TensorExpressionsGroup Tensor Expressions
* Tensor Expressions allow writing expressions of
* tensors in a way similar to what is used with pen and paper.
*
* Tensor expressions are implemented using (smart) expression templates. This
* allows a domain specific language making expressions such as
* \code
* auto T = evaluate<Indices::_a_t, Indices::_b_t>(F(Indices::_b,
* Indices::_a));
* \endcode
* possible.
*/
/*!
* \defgroup TestingFrameworkGroup Testing Framework
* \brief Classes, functions, macros, and instructions for developing tests
*
* \details
*
* SpECTRE uses the testing framework
* [Catch](https://github.com/philsquared/Catch). Catch supports a variety of
* different styles of tests including BDD and fixture tests. The file
* `cmake/SpectreAddCatchTests.cmake` parses the source files and adds the found
* tests to ctest with the correct properties specified by tags and attributes.
*
* ### Usage
*
* To run the tests, type `ctest` in the build directory. You can specify
* a regex to match the test name using `ctest -R Unit.Blah`, or run all
* tests with a certain tag using `ctest -L tag`.
*
* ### Comparing double-precision results
*
* To compare two floating-point numbers that may differ by round-off, use the
* helper object `approx`. This is an instance of Catch's comparison class
* `Approx` in which the relative tolerance for comparisons is set to roughly
* \f$10^{-14}\f$ (i.e. `std::numeric_limits<double>::%epsilon()*100`).
* When possible, we recommend using `approx` for fuzzy comparisons as follows:
* \example
* \snippet Test_TestingFramework.cpp approx_default
*
* For checks that need more control over the precision (e.g. an algorithm in
* which round-off errors accumulate to a higher level), we recommend using
* the `approx` helper with a one-time tolerance adjustment. A comment
* should explain the reason for the adjustment:
* \example
* \snippet Test_TestingFramework.cpp approx_single_custom
*
* For tests in which the same precision adjustment is re-used many times, a new
* helper object can be created from Catch's `Approx` with a custom precision:
* \example
* \snippet Test_TestingFramework.cpp approx_new_custom
*
* Note: We provide the `approx` object because Catch's `Approx` defaults to a
* very loose tolerance (`std::numeric_limits<float>::%epsilon()*100`, or
* roughly \f$10^{-5}\f$ relative error), and so is poorly-suited to checking
* many numerical algorithms that rely on double-precision accuracy. By
* providing a tighter tolerance with `approx`, we avoid having to redefine the
* tolerance in every test.
*
* ### Attributes
*
* Attributes allow you to modify properties of the test. Attributes are
* specified as follows:
* \code
* // [[TimeOut, 10]]
* // [[OutputRegex, The error message expected from the test]]
* SPECTRE_TEST_CASE("Unit.Blah", "[Unit]") {
* \endcode
*
* Available attributes are:
*
* <table class="doxtable">
* <tr>
* <th>Attribute </th><th>Description </th>
* </tr>
* <tr>
* <td>TimeOut </td>
* <td>override the default timeout and set the timeout to N seconds. This
* should be set very sparingly since unit tests are designed to be
* short. If your test is too long you should consider testing smaller
* portions of the code if possible, or writing an integration test instead.
* </td>
* </tr>
* <tr>
* <td>OutputRegex </td>
* <td>
* When testing failure modes the exact error message must be tested, not
* just that the test failed. Since the string passed is a regular
* expression you must escape any regex tokens. For example, to match
* `some (word) and` you must specify the string `some \(word\) and`.
* If your error message contains a newline, you can match it using the
* dot operator `.`, which matches any character.
* </td>
* </tr>
* </table>
*
* \example
* \snippet Test_H5.cpp willfail_example_for_dev_doc
*
* ### Debugging Tests in GDB or LLDB
*
* Several tests fail intentionally at the executable level to test error
* handling like ASSERT statements in the code. CTest is aware of which
* should fail and passes them. If you want to debug an individual test
* in a debugger you need to run a single test
* using the %RunTests executable (in dg-charm-build/bin/RunTests) you
* must specify the name of the test as the first argument. For example, if you
* want to run just the "Unit.Gradient" test you can run
* `./bin/RunTests Unit.Gradient`. If you are using a debugger launch the
* debugger, for example if you're using LLDB then run `lldb ./bin/RunTests`
* and then to run the executable inside the debugger use `run Unit.Gradient`
* inside the debugger.
*/
/*!
* \defgroup TimeGroup Time
* \brief Code related to the representation of time during simulations.
*
* The time covered by a simulation is divided up into a sequence of
* adjacent, non-overlapping (except at endpoints) intervals referred
* to as "slabs". The boundaries between slabs can be placed at
* arbitrary times. Slabs, as represented in the code as the Slab
* class, provide comparison operators comparing slabs agreeing with
* the definition as a sequence of intervals. Slabs that do not
* jointly belong to any such sequence should not be compared.
*
* The specific time is represented by the Time class, which encodes
* the slab containing the time and the fraction of the slab that has
* elapsed as an exact rational. Times are comparable according to
* their natural time ordering, except for times belonging to
* incomparable slabs.
*
* Differences in time within a slab are represented as exact
* fractions of that slab by the TimeDelta class. TimeDeltas are only
* meaningful within a single slab, with the exception that the ratio
* of objects with different slabs may be taken, resulting in an
* inexact floating-point result. Longer intervals of time are
* represented using floating-point values.
*/
/*!
* \defgroup TimeSteppersGroup Time Steppers
* A collection of ODE integrators primarily used for time stepping.
*/
/*!
* \defgroup TypeTraitsGroup Type Traits
* A collection of useful type traits, including C++14 and C++17 additions to
* the standard library.
*/
/*!
* \defgroup UtilitiesGroup Utilities
* \brief A collection of useful classes, functions and metafunctions.
*/
/*!
* \defgroup VariableFixingGroup Variable Fixing
* \brief A collection of different variable fixers ranging in sophistication.
*
* Build-up of numerical error can cause physical quantities to evolve
* toward non-physical values. For example, pressure and density may become
* negative. This will subsequently lead to failures in numerical inversion
* schemes to recover the corresponding convervative values. A rough fix that
* enforces physical quantities stay physical is to simply change them by hand
* when needed. This can be done at various degrees of sophistication, but in
* general the fixed quantities make up a negligible amount of the physics of
* the simulation; a rough fix is vastly preferred to a simulation that fails
* to complete due to nonphysical quantities.
*/
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/eager/eager_op_rewrite_registry.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
class TestEagerOpRewrite : public EagerOpRewrite {
public:
TestEagerOpRewrite(string name, string file, string line)
: EagerOpRewrite(name, file, line), executor_(/*async=*/false) {}
static int count_;
EagerExecutor executor_;
Status Run(EagerOperation* orig_op,
std::unique_ptr<tensorflow::EagerOperation>* out_op) override {
++count_;
// Create a new NoOp Eager operation.
tensorflow::EagerOperation* op =
new tensorflow::EagerOperation(&orig_op->EagerContext());
TF_RETURN_IF_ERROR(op->Reset("NoOp", nullptr, false, &executor_));
out_op->reset(op);
return Status::OK();
}
};
int TestEagerOpRewrite::count_ = 0;
REGISTER_REWRITE(EagerOpRewriteRegistry::PRE_EXECUTION, TestEagerOpRewrite);
TEST(EagerOpRewriteRegistryTest, RegisterRewritePass) {
EXPECT_EQ(0, TestEagerOpRewrite::count_);
StaticDeviceMgr device_mgr(DeviceFactory::NewDevice(
"CPU", {}, "/job:localhost/replica:0/task:0/device:CPU:0"));
tensorflow::EagerContext* ctx = new tensorflow::EagerContext(
SessionOptions(),
tensorflow::ContextDevicePlacementPolicy::DEVICE_PLACEMENT_SILENT, false,
&device_mgr, false, nullptr, nullptr);
EagerOperation orig_op(ctx);
std::unique_ptr<tensorflow::EagerOperation> out_op;
EXPECT_EQ(Status::OK(),
EagerOpRewriteRegistry::Global()->RunRewrite(
EagerOpRewriteRegistry::PRE_EXECUTION, &orig_op, &out_op));
EXPECT_EQ(1, TestEagerOpRewrite::count_);
EXPECT_EQ("NoOp", out_op->Name());
ctx->Unref();
}
} // namespace tensorflow
|
; A081184: 7th binomial transform of (0,1,0,2,0,4,0,8,0,16,...).
; Submitted by Jamie Morken(s3)
; 0,1,14,149,1428,12989,114730,995737,8548008,72872473,618458246,5233409213,44200191420,372832446869,3142245259426,26468308629121,222870793614672,1876180605036721,15791601170624510,132901927952017253,1118421736308889572,9411513694579643117,79195370117597193754,666394038001117486057,5607334136488576698360,47182158124787551932361,397005509332062622230134,3340515698783861770400909,28107960844367121540796428,236507213978298198362307269,1990026836010920064654869650,16744536647172865582139733457
mov $1,1
lpb $0
sub $0,1
mov $2,$3
mul $3,8
add $3,$1
mul $1,6
add $1,$2
lpe
mov $0,$3
|
.global s_prepare_buffers
s_prepare_buffers:
push %r15
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WC_ht+0x4b85, %rsi
lea addresses_UC_ht+0x12e9, %rdi
nop
nop
nop
nop
dec %rdx
mov $19, %rcx
rep movsw
cmp $55731, %r15
lea addresses_A_ht+0xb1dd, %rsi
lea addresses_A_ht+0xace9, %rdi
nop
nop
nop
nop
add %rbx, %rbx
mov $12, %rcx
rep movsl
nop
nop
nop
nop
sub $22824, %r15
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %r15
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r14
push %r15
push %r8
push %rax
push %rdx
// Store
mov $0x369, %rdx
nop
nop
sub %r8, %r8
mov $0x5152535455565758, %r15
movq %r15, %xmm1
movups %xmm1, (%rdx)
nop
nop
xor %r11, %r11
// Store
lea addresses_RW+0x67e9, %r14
nop
nop
nop
and %rax, %rax
mov $0x5152535455565758, %r15
movq %r15, (%r14)
nop
nop
nop
nop
nop
inc %r11
// Store
lea addresses_D+0x12369, %rdx
nop
sub %r14, %r14
mov $0x5152535455565758, %r15
movq %r15, %xmm5
vmovntdq %ymm5, (%rdx)
nop
nop
nop
nop
sub %r13, %r13
// Store
lea addresses_US+0x1bb69, %r8
nop
and %r15, %r15
movb $0x51, (%r8)
sub %r15, %r15
// Store
lea addresses_UC+0x18de9, %rax
nop
nop
nop
xor %r15, %r15
mov $0x5152535455565758, %r11
movq %r11, %xmm1
vmovups %ymm1, (%rax)
nop
nop
nop
xor %r14, %r14
// Store
lea addresses_D+0x15569, %r14
nop
nop
nop
dec %r8
mov $0x5152535455565758, %rax
movq %rax, (%r14)
nop
nop
nop
nop
nop
dec %r11
// Faulty Load
lea addresses_US+0x1bb69, %r13
nop
nop
nop
inc %r8
mov (%r13), %r14d
lea oracles, %r15
and $0xff, %r14
shlq $12, %r14
mov (%r15,%r14,1), %r14
pop %rdx
pop %rax
pop %r8
pop %r15
pop %r14
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': True, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_P', 'AVXalign': False, 'congruent': 11, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 7, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'congruent': 11, 'size': 32, 'same': False, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 5, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'congruent': 8, 'size': 8, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}}
{'51': 21829}
51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51
*/
|
; A175540: a(n) = A067076(n) + n.
; 1,3,5,8,10,13,15,18,22,24,28,31,33,36,40,44,46,50,53,55,59,62,66,71,74,76,79,81,84,92,95,99,101,107,109,113,117,120,124,128,130,136,138,141,143,150,157,160,162,165,169,171,177,181,185,189,191,195,198,200,206
mov $1,$0
seq $1,98090 ; Numbers k such that 2k-3 is prime.
add $0,$1
sub $0,2
|
; ########################################################################
GetFileName PROTO :DWORD, :DWORD, :DWORD
SaveFileName PROTO :DWORD, :DWORD, :DWORD
FillBuffer PROTO :DWORD, :DWORD, :BYTE
.data
szFileName db 260 dup(0)
ofn OPENFILENAME <> ; structure
.code
; ########################################################################
GetFileName proc hParent:DWORD,lpTitle:DWORD,lpFilter:DWORD
mov ofn.lStructSize, sizeof OPENFILENAME
m2m ofn.hWndOwner, hParent
m2m ofn.hInstance, hInstance
m2m ofn.lpstrFilter, lpFilter
m2m ofn.lpstrFile, offset szFileName
mov ofn.nMaxFile, sizeof szFileName
m2m ofn.lpstrTitle, lpTitle
mov ofn.Flags, OFN_EXPLORER or OFN_FILEMUSTEXIST or \
OFN_LONGNAMES
invoke GetOpenFileName,ADDR ofn
ret
GetFileName endp
; #########################################################################
SaveFileName proc hParent:DWORD,lpTitle:DWORD,lpFilter:DWORD
mov ofn.lStructSize, sizeof OPENFILENAME
m2m ofn.hWndOwner, hParent
m2m ofn.hInstance, hInstance
m2m ofn.lpstrFilter, lpFilter
m2m ofn.lpstrFile, offset szFileName
mov ofn.nMaxFile, sizeof szFileName
m2m ofn.lpstrTitle, lpTitle
mov ofn.Flags, OFN_EXPLORER or OFN_LONGNAMES
invoke GetSaveFileName,ADDR ofn
ret
SaveFileName endp
; ########################################################################
FillBuffer proc lpBuffer:DWORD,lenBuffer:DWORD,TheChar:BYTE
push edi
mov edi, lpBuffer ; address of buffer
mov ecx, lenBuffer ; buffer length
mov al, TheChar ; load al with character
rep stosb ; write character to buffer until ecx = 0
pop edi
ret
FillBuffer endp
; #########################################################################
|
// Copyright (c) 2015 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include "encoder/time_util.h"
#include "glog/logging.h"
namespace webmlive {
const size_t kTimeUtilBufferSize = 256;
std::string LocalDateString() {
char date_buffer[kTimeUtilBufferSize] = {0};
// %Y - year
// %m - month, zero padded (01-12)
// %d - day of month, zero padded (01-31).
const char format_string[] = "%Y%m%d";
const time_t raw_time_now = time(NULL);
const struct tm* time_now = localtime(&raw_time_now);
if (strftime(&date_buffer[0], sizeof(date_buffer), format_string,
time_now) == 0) {
LOG(ERROR) << "DateString failed..";
return "";
}
const std::string date_string = date_buffer;
return date_string;
}
std::string LocalTimeString() {
char time_buffer[kTimeUtilBufferSize] = {0};
// %H - hour, zero padded, 24 hour clock (00-23)
// %M - minute, zero padded (00-59)
// %S - second, zero padded (00-61)
const char format_string[] = "%H%M%S";
const time_t raw_time_now = time(NULL);
const struct tm* time_now = localtime(&raw_time_now);
if (strftime(&time_buffer[0], sizeof(time_buffer), format_string,
time_now) == 0) {
LOG(ERROR) << "TimeString failed.";
return "";
}
const std::string time_string = time_buffer;
return time_string;
}
std::string StrFTime(const struct tm* time_value,
const std::string& format_string) {
char strftime_buffer[kTimeUtilBufferSize] = {0};
if (strftime(&strftime_buffer[0], sizeof(strftime_buffer),
format_string.c_str(), time_value) == 0) {
LOG(ERROR) << "StrFTime failed.";
return "";
}
const std::string out_string = strftime_buffer;
return out_string;
}
} // namespace webmlive
|
; A165618: Binomial(n+8,8)-1
; 0,8,44,164,494,1286,3002,6434,12869,24309,43757,75581,125969,203489,319769,490313,735470,1081574,1562274,2220074,3108104,4292144,5852924,7888724,10518299,13884155,18156203,23535819,30260339,38608019,48903491,61523747,76904684,95548244,118030184,145008512,177232626,215553194,260932814,314457494,377348993,450978065,536878649,636763049,752538149,886322709,1040465789,1217566349,1420494074,1652411474,1916797310,2217471398,2558620844,2944827764,3381098544,3872894696,4426165367,5047381559,5743572119
add $0,8
bin $0,8
sub $0,1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.