text stringlengths 1 1.05M |
|---|
; void __FASTCALL__ sp1_RemoveCharStruct(struct sp1_cs *cs)
; 05.2007 aralbrec, Sprite Pack v3.0
; sinclair spectrum version
XLIB sp1_RemoveCharStruct
LIB SP1RemoveSprChar
; remove an independent char struct that may be
; inserted into a struct_sp1_update's draw list
;
; enter : hl = struct sp1_cs *
; uses : af, bc, de, hl
.sp1_RemoveCharStruct
inc hl
inc hl
ld a,(hl)
or a
ret z ; not in any struct update draw list
ld d,a
ld (hl),0 ; not part of this draw list anymore
inc hl
ld e,(hl) ; de = struct update *
inc hl
inc hl ; hl = & sp1_cs.type
bit 7,(hl)
ex de,hl
jr z, notoccluding
dec (hl) ; reduce occluding count in struct update
.notoccluding
inc de ; de = & sp1_cs.attr_mask
ld hl,17
add hl,de ; hl = & sp1_cs.prev_in_upd + 1b
ex de,hl
jp SP1RemoveSprChar
|
; A114846: Numbers of the form p^p - p!, where p is a prime.
; Submitted by Christian Krause
; 2,21,3005,818503,285271753811,302868879571453,827239906198908668177,1978419534015213180291979,20880467973995895295470056270567,2567686153152369372568088512776472510483469,17069174130715013119956465106241589193164734431
seq $0,40 ; The prime numbers.
seq $0,36679 ; a(n) = n^n - n!.
|
; A270257: Number of 2X2X2 triangular 0..n arrays with some element plus some adjacent element totalling n exactly once.
; 0,12,24,48,72,108,144,192,240,300,360,432,504,588,672,768,864,972,1080,1200,1320,1452,1584,1728,1872,2028,2184,2352,2520,2700,2880,3072,3264,3468,3672,3888,4104,4332,4560,4800,5040,5292,5544,5808,6072,6348,6624
add $0,1
mov $1,$0
pow $1,2
div $1,2
mul $1,6
|
; Small C+ Maths Routines
;
; transcendental floating point routines
;
SECTION code_fp
PUBLIC atan
EXTERN evenpol
EXTERN hlsub
EXTERN odd
EXTERN sgn
EXTERN fdiv
EXTERN dload
EXTERN fa
PUBLIC __halfpi
PUBLIC __pi
;double atan(double val)
.atan
CALL sgn
CALL M,odd ;negate argument & answer
LD A,(fa+5)
CP $81
JR C,ATAN5 ;c => argument less than 1
LD BC,$8100 ;1.0
LD IX,0
LD D,C
LD E,C
CALL fdiv
ld hl,hlsub
push hl
.ATAN5 LD HL,ATNCOEF
CALL evenpol
LD HL,__halfpi ;may use for subtraction
ret
SECTION rodata_fp
.__pi
DEFB $22,$A2,$DA,$0F,$49,$82 ;pi
.__halfpi
DEFB $22,$A2,$DA,$0F,$49,$81 ; pi/2
;
.ATNCOEF
defb 13 ;hmmm? $13?
defb $14, $7,$BA,$FE,$62,$75
defb $51,$16,$CE,$D8,$D6,$78
defb $4C,$BD,$7D,$D1,$3E,$7A
defb $1, $CB,$23,$C4,$D7,$7B
defb $DC,$3A,$A, $17,$34,$7C
defb $36,$C1,$A3,$81,$F7,$7C
defb $EB,$16,$61,$AE,$19,$7D
defb $5D,$78,$8F,$60,$B9,$7D
defb $A2,$44,$12,$72,$63,$7D
defb $16,$62,$FB,$47,$92,$7E
defb $C0,$F0,$BF,$CC,$4C,$7E
defb $7E,$8E,$AA,$AA,$AA,$7F
defb $F6,$FF,$FF,$FF,$7F,$80
|
; A020768: Decimal expansion of 1/sqrt(11).
; Submitted by Jamie Morken(s4)
; 3,0,1,5,1,1,3,4,4,5,7,7,7,6,3,6,2,2,6,4,6,8,1,2,0,6,6,9,7,0,0,6,2,4,2,5,8,1,1,5,5,3,5,0,4,1,4,4,4,8,6,6,9,0,6,4,1,6,9,8,3,7,6,9,1,9,6,8,0,4,2,2,0,5,5,3,6,7,6,2,2,4,2,8,0,7,6,6,7,2,6,4,8,0,2,6,4,2,2,8
mov $1,1
mov $2,1
mov $3,$0
add $3,8
mov $4,$0
mov $0,2
sub $3,3
add $4,3
mov $7,10
pow $7,$4
mov $9,10
lpb $3
mov $4,$2
pow $4,2
mul $4,99
mov $5,$1
pow $5,2
add $4,$5
mov $6,$1
mov $1,$4
mul $6,$2
mul $6,2
mov $2,$6
mov $8,$4
div $8,$7
div $8,3
max $8,2
div $1,$8
div $2,$8
sub $3,1
lpe
mov $3,$9
pow $3,$0
div $2,$3
mov $0,$2
mod $0,10
|
; A293615: a(n) = Pochhammer(n, 5) / 2.
; 0,60,360,1260,3360,7560,15120,27720,47520,77220,120120,180180,262080,371280,514080,697680,930240,1220940,1580040,2018940,2550240,3187800,3946800,4843800,5896800,7125300,8550360,10194660,12082560,14240160,16695360,19477920,22619520,26153820,30116520,34545420,39480480,44963880,51040080,57755880,65160480,73305540,82245240,92036340,102738240,114413040,127125600,140943600,155937600,172181100,189750600,208725660,229188960,251226360,274926960,300383160,327690720,356948820,388260120,421730820,457470720,495593280,536215680,579458880,625447680,674310780,726180840,781194540,839492640,901220040,966525840,1035563400,1108490400,1185468900,1266665400,1352250900,1442400960,1537295760,1637120160,1742063760,1852320960,1968091020,2089578120,2216991420,2350545120,2490458520,2636956080,2790267480,2950627680,3118276980,3293461080,3476431140,3667443840,3866761440,4074651840,4291388640,4517251200,4752524700,4997500200,5252474700
add $0,4
bin $0,5
mul $0,60
|
; A187532: a(n) = 4^n mod 19.
; 1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11,6,5,1,4,16,7,9,17,11
mul $0,2
mov $1,2
lpb $0,1
sub $0,1
mod $1,19
mul $1,2
lpe
sub $1,2
div $1,2
add $1,1
|
; A133496: a(n) = (29*n)^2.
; 0,841,3364,7569,13456,21025,30276,41209,53824,68121,84100,101761,121104,142129,164836,189225,215296,243049,272484,303601,336400,370881,407044,444889,484416,525625,568516,613089,659344,707281,756900,808201,861184,915849,972196,1030225,1089936,1151329,1214404,1279161,1345600,1413721,1483524,1555009,1628176,1703025,1779556,1857769,1937664,2019241,2102500,2187441,2274064,2362369,2452356,2544025,2637376,2732409,2829124,2927521,3027600,3129361,3232804,3337929,3444736,3553225,3663396,3775249,3888784,4004001,4120900,4239481,4359744,4481689,4605316,4730625,4857616,4986289,5116644,5248681,5382400,5517801,5654884,5793649,5934096,6076225,6220036,6365529,6512704,6661561,6812100,6964321,7118224,7273809,7431076,7590025,7750656,7912969,8076964,8242641,8410000,8579041,8749764,8922169,9096256,9272025,9449476,9628609,9809424,9991921,10176100,10361961,10549504,10738729,10929636,11122225,11316496,11512449,11710084,11909401,12110400,12313081,12517444,12723489,12931216,13140625,13351716,13564489,13778944,13995081,14212900,14432401,14653584,14876449,15100996,15327225,15555136,15784729,16016004,16248961,16483600,16719921,16957924,17197609,17438976,17682025,17926756,18173169,18421264,18671041,18922500,19175641,19430464,19686969,19945156,20205025,20466576,20729809,20994724,21261321,21529600,21799561,22071204,22344529,22619536,22896225,23174596,23454649,23736384,24019801,24304900,24591681,24880144,25170289,25462116,25755625,26050816,26347689,26646244,26946481,27248400,27552001,27857284,28164249,28472896,28783225,29095236,29408929,29724304,30041361,30360100,30680521,31002624,31326409,31651876,31979025,32307856,32638369,32970564,33304441,33640000,33977241,34316164,34656769,34999056,35343025,35688676,36036009,36385024,36735721,37088100,37442161,37797904,38155329,38514436,38875225,39237696,39601849,39967684,40335201,40704400,41075281,41447844,41822089,42198016,42575625,42954916,43335889,43718544,44102881,44488900,44876601,45265984,45657049,46049796,46444225,46840336,47238129,47637604,48038761,48441600,48846121,49252324,49660209,50069776,50481025,50893956,51308569,51724864,52142841
mov $1,$0
pow $1,2
mul $1,841
|
/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-base-impl.h>
using namespace Dali;
namespace Dali
{
namespace Toolkit
{
namespace Internal
{
///////////////////////////////////////////////////////////////////////////////////////////////////
// ScrollBase
///////////////////////////////////////////////////////////////////////////////////////////////////
ScrollBase::ScrollBase()
: Scrollable(),
mParent(NULL),
mDelay(0.0f)
{
}
ScrollBase::ScrollBase( ControlBehaviour behaviourFlags )
: Scrollable( behaviourFlags ),
mParent(NULL),
mDelay(0.0f)
{
}
void ScrollBase::SetParent(ScrollBase *parent)
{
mParent = parent;
}
void ScrollBase::BindActor(Actor child)
{
FindAndUnbindActor(child);
ActorInfoPtr actorInfo(new ActorInfo(child));
mBoundActors.push_back(actorInfo);
// Apply all our constraints to this new child.
ConstraintStack::iterator i;
for(i = mConstraintStack.begin();i!=mConstraintStack.end();i++)
{
actorInfo->ApplyConstraint(*i);
}
}
void ScrollBase::UnbindActor(Actor child)
{
// Find the child in mBoundActors, and unparent it
for (ActorInfoIter iter = mBoundActors.begin(); iter != mBoundActors.end(); ++iter)
{
ActorInfoPtr actorInfo = *iter;
if( actorInfo->mActor == child )
{
mBoundActors.erase(iter);
break;
}
}
}
void ScrollBase::FindAndUnbindActor(Actor child)
{
// Since we don't know if and where child may have been bound
// (as we cannot store such information inside the Actor), we
// perform a search on all associated ScrollBases
// This is done by recursively calling the parent of this ScrollBase
// until reaching the top (at which point implementation may be
// different as this is virtual)
if(mParent) // continuously ascend until reaches root ScrollBase.
{
mParent->FindAndUnbindActor(child);
}
}
void ScrollBase::ApplyConstraintToBoundActors(Constraint constraint)
{
mConstraintStack.push_back(constraint);
for(ActorInfoIter i = mBoundActors.begin();i != mBoundActors.end(); ++i)
{
(*i)->ApplyConstraint(constraint);
}
}
void ScrollBase::RemoveConstraintsFromBoundActors()
{
mConstraintStack.clear();
for(ActorInfoIter i = mBoundActors.begin();i != mBoundActors.end(); ++i)
{
(*i)->RemoveConstraints();
}
}
} // namespace Internal
} // namespace Toolkit
} // namespace Dali
|
test:
int 0 ; will generate division by zero exception/panic
jmp $ |
; A087420: a(n) is the sum of the squares of the sizes of the conjugacy classes in the dihedral group D_2n.
; 2,4,14,14,34,28,62,46,98,68,142,94,194,124,254,158,322,196,398,238,482,284,574,334,674,388,782,446,898,508,1022,574,1154,644,1294,718,1442,796,1598,878,1762,964,1934,1054,2114,1148,2302,1246,2498,1348,2702,1454,2914,1564,3134,1678,3362,1796,3598,1918,3842,2044,4094,2174,4354,2308,4622,2446,4898,2588,5182,2734,5474,2884,5774,3038,6082,3196,6398,3358,6722,3524,7054,3694,7394,3868,7742,4046,8098,4228,8462,4414,8834,4604,9214,4798,9602,4996,9998,5198,10402,5404,10814,5614,11234,5828,11662,6046,12098,6268,12542,6494,12994,6724,13454,6958,13922,7196,14398,7438,14882,7684,15374,7934,15874,8188,16382,8446,16898,8708,17422,8974,17954,9244,18494,9518,19042,9796,19598,10078,20162,10364,20734,10654,21314,10948,21902,11246,22498,11548,23102,11854,23714,12164,24334,12478,24962,12796,25598,13118,26242,13444,26894,13774,27554,14108,28222,14446,28898,14788,29582,15134,30274,15484,30974,15838,31682,16196,32398,16558,33122,16924,33854,17294,34594,17668,35342,18046,36098,18428,36862,18814,37634,19204,38414,19598,39202,19996,39998,20398,40802,20804,41614,21214,42434,21628,43262,22046,44098,22468,44942,22894,45794,23324,46654,23758,47522,24196,48398,24638,49282,25084,50174,25534,51074,25988,51982,26446,52898,26908,53822,27374,54754,27844,55694,28318,56642,28796,57598,29278,58562,29764,59534,30254,60514,30748,61502,31246,62498,31748
mov $1,$0
mov $4,$0
mov $0,3
lpb $0
mul $0,2
gcd $0,2
add $1,1
add $3,$1
pow $1,$0
gcd $3,2
lpe
add $1,1
div $1,$3
mov $2,$4
mul $2,2
add $1,$2
|
// Copyright (c) 2011 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 "base/files/file_path_watcher.h"
#include "base/bind.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/win/object_watcher.h"
namespace base {
namespace {
class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate,
public base::win::ObjectWatcher::Delegate,
public MessageLoop::DestructionObserver {
public:
FilePathWatcherImpl()
: handle_(INVALID_HANDLE_VALUE),
recursive_watch_(false) {}
// FilePathWatcher::PlatformDelegate overrides.
bool Watch(const FilePath& path,
bool recursive,
const FilePathWatcher::Callback& callback) override;
void Cancel() override;
// Deletion of the FilePathWatcher will call Cancel() to dispose of this
// object in the right thread. This also observes destruction of the required
// cleanup thread, in case it quits before Cancel() is called.
void WillDestroyCurrentMessageLoop() override;
// Callback from MessageLoopForIO.
void OnObjectSignaled(HANDLE object) override;
private:
~FilePathWatcherImpl() override {}
// Setup a watch handle for directory |dir|. Set |recursive| to true to watch
// the directory sub trees. Returns true if no fatal error occurs. |handle|
// will receive the handle value if |dir| is watchable, otherwise
// INVALID_HANDLE_VALUE.
static bool SetupWatchHandle(const FilePath& dir,
bool recursive,
HANDLE* handle) WARN_UNUSED_RESULT;
// (Re-)Initialize the watch handle.
bool UpdateWatch() WARN_UNUSED_RESULT;
// Destroy the watch handle.
void DestroyWatch();
// Cleans up and stops observing the |task_runner_| thread.
void CancelOnMessageLoopThread() override;
// Callback to notify upon changes.
FilePathWatcher::Callback callback_;
// Path we're supposed to watch (passed to callback).
FilePath target_;
// Handle for FindFirstChangeNotification.
HANDLE handle_;
// ObjectWatcher to watch handle_ for events.
base::win::ObjectWatcher watcher_;
// Set to true to watch the sub trees of the specified directory file path.
bool recursive_watch_;
// Keep track of the last modified time of the file. We use nulltime
// to represent the file not existing.
Time last_modified_;
// The time at which we processed the first notification with the
// |last_modified_| time stamp.
Time first_notification_;
DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
};
bool FilePathWatcherImpl::Watch(const FilePath& path,
bool recursive,
const FilePathWatcher::Callback& callback) {
DCHECK(target_.value().empty()); // Can only watch one path.
set_task_runner(ThreadTaskRunnerHandle::Get());
callback_ = callback;
target_ = path;
recursive_watch_ = recursive;
MessageLoop::current()->AddDestructionObserver(this);
File::Info file_info;
if (GetFileInfo(target_, &file_info)) {
last_modified_ = file_info.last_modified;
first_notification_ = Time::Now();
}
if (!UpdateWatch())
return false;
watcher_.StartWatching(handle_, this);
return true;
}
void FilePathWatcherImpl::Cancel() {
if (callback_.is_null()) {
// Watch was never called, or the |task_runner_| has already quit.
set_cancelled();
return;
}
// Switch to the file thread if necessary so we can stop |watcher_|.
if (!task_runner()->BelongsToCurrentThread()) {
task_runner()->PostTask(FROM_HERE, Bind(&FilePathWatcher::CancelWatch,
make_scoped_refptr(this)));
} else {
CancelOnMessageLoopThread();
}
}
void FilePathWatcherImpl::CancelOnMessageLoopThread() {
DCHECK(task_runner()->BelongsToCurrentThread());
set_cancelled();
if (handle_ != INVALID_HANDLE_VALUE)
DestroyWatch();
if (!callback_.is_null()) {
MessageLoop::current()->RemoveDestructionObserver(this);
callback_.Reset();
}
}
void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() {
CancelOnMessageLoopThread();
}
void FilePathWatcherImpl::OnObjectSignaled(HANDLE object) {
DCHECK(object == handle_);
// Make sure we stay alive through the body of this function.
scoped_refptr<FilePathWatcherImpl> keep_alive(this);
if (!UpdateWatch()) {
callback_.Run(target_, true /* error */);
return;
}
// Check whether the event applies to |target_| and notify the callback.
File::Info file_info;
bool file_exists = GetFileInfo(target_, &file_info);
if (recursive_watch_) {
// Only the mtime of |target_| is tracked but in a recursive watch,
// some other file or directory may have changed so all notifications
// are passed through. It is possible to figure out which file changed
// using ReadDirectoryChangesW() instead of FindFirstChangeNotification(),
// but that function is quite complicated:
// http://qualapps.blogspot.com/2010/05/understanding-readdirectorychangesw.html
callback_.Run(target_, false);
} else if (file_exists && (last_modified_.is_null() ||
last_modified_ != file_info.last_modified)) {
last_modified_ = file_info.last_modified;
first_notification_ = Time::Now();
callback_.Run(target_, false);
} else if (file_exists && last_modified_ == file_info.last_modified &&
!first_notification_.is_null()) {
// The target's last modification time is equal to what's on record. This
// means that either an unrelated event occurred, or the target changed
// again (file modification times only have a resolution of 1s). Comparing
// file modification times against the wall clock is not reliable to find
// out whether the change is recent, since this code might just run too
// late. Moreover, there's no guarantee that file modification time and wall
// clock times come from the same source.
//
// Instead, the time at which the first notification carrying the current
// |last_notified_| time stamp is recorded. Later notifications that find
// the same file modification time only need to be forwarded until wall
// clock has advanced one second from the initial notification. After that
// interval, client code is guaranteed to having seen the current revision
// of the file.
if (Time::Now() - first_notification_ > TimeDelta::FromSeconds(1)) {
// Stop further notifications for this |last_modification_| time stamp.
first_notification_ = Time();
}
callback_.Run(target_, false);
} else if (!file_exists && !last_modified_.is_null()) {
last_modified_ = Time();
callback_.Run(target_, false);
}
// The watch may have been cancelled by the callback.
if (handle_ != INVALID_HANDLE_VALUE)
watcher_.StartWatching(handle_, this);
}
// static
bool FilePathWatcherImpl::SetupWatchHandle(const FilePath& dir,
bool recursive,
HANDLE* handle) {
*handle = FindFirstChangeNotification(
dir.value().c_str(),
recursive,
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_SIZE |
FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_DIR_NAME |
FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SECURITY);
if (*handle != INVALID_HANDLE_VALUE) {
// Make sure the handle we got points to an existing directory. It seems
// that windows sometimes hands out watches to directories that are
// about to go away, but doesn't sent notifications if that happens.
if (!DirectoryExists(dir)) {
FindCloseChangeNotification(*handle);
*handle = INVALID_HANDLE_VALUE;
}
return true;
}
// If FindFirstChangeNotification failed because the target directory
// doesn't exist, access is denied (happens if the file is already gone but
// there are still handles open), or the target is not a directory, try the
// immediate parent directory instead.
DWORD error_code = GetLastError();
if (error_code != ERROR_FILE_NOT_FOUND &&
error_code != ERROR_PATH_NOT_FOUND &&
error_code != ERROR_ACCESS_DENIED &&
error_code != ERROR_SHARING_VIOLATION &&
error_code != ERROR_DIRECTORY) {
DPLOG(ERROR) << "FindFirstChangeNotification failed for "
<< dir.value();
return false;
}
return true;
}
bool FilePathWatcherImpl::UpdateWatch() {
if (handle_ != INVALID_HANDLE_VALUE)
DestroyWatch();
// Start at the target and walk up the directory chain until we succesfully
// create a watch handle in |handle_|. |child_dirs| keeps a stack of child
// directories stripped from target, in reverse order.
std::vector<FilePath> child_dirs;
FilePath watched_path(target_);
while (true) {
if (!SetupWatchHandle(watched_path, recursive_watch_, &handle_))
return false;
// Break if a valid handle is returned. Try the parent directory otherwise.
if (handle_ != INVALID_HANDLE_VALUE)
break;
// Abort if we hit the root directory.
child_dirs.push_back(watched_path.BaseName());
FilePath parent(watched_path.DirName());
if (parent == watched_path) {
DLOG(ERROR) << "Reached the root directory";
return false;
}
watched_path = parent;
}
// At this point, handle_ is valid. However, the bottom-up search that the
// above code performs races against directory creation. So try to walk back
// down and see whether any children appeared in the mean time.
while (!child_dirs.empty()) {
watched_path = watched_path.Append(child_dirs.back());
child_dirs.pop_back();
HANDLE temp_handle = INVALID_HANDLE_VALUE;
if (!SetupWatchHandle(watched_path, recursive_watch_, &temp_handle))
return false;
if (temp_handle == INVALID_HANDLE_VALUE)
break;
FindCloseChangeNotification(handle_);
handle_ = temp_handle;
}
return true;
}
void FilePathWatcherImpl::DestroyWatch() {
watcher_.StopWatching();
FindCloseChangeNotification(handle_);
handle_ = INVALID_HANDLE_VALUE;
}
} // namespace
FilePathWatcher::FilePathWatcher() {
impl_ = new FilePathWatcherImpl();
}
} // namespace base
|
; CONFIGURATION {{{
cm_main_goto_config:
%cm_submenu("Configuration", cm_submenu_config)
cm_submenu_config:
dw cm_gameplay_rerandomize
dw cm_config_music
dw cm_config_autoload_preset
dw cm_config_preset_category
dw cm_config_hud_font
dw !menu_end
%cm_header("CONFIGURATION")
cm_gameplay_rerandomize:
%cm_toggle("Rerandomize", !ram_rerandomize_toggle)
cm_config_music:
%cm_toggle_jsr("Music", !ram_feature_music)
.toggle
JSL music_reload
LDA $0130 : CMP #$FF : BEQ .muted
STA $012C : STZ $0133
.muted
RTS
cm_config_autoload_preset:
%cm_toggle("Death reload", !ram_autoload_preset)
cm_config_preset_category:
dw !CM_ACTION_CHOICE
dl !ram_preset_category
%cm_item("Preset cat")
%cm_item("NMG")
%cm_item("Hundo")
%cm_item("Low")
%cm_item("AD")
db !list_end
cm_config_hud_font:
dw !CM_ACTION_CHOICE
dl !ram_hud_font
%cm_item("HUD font")
%cm_item("Classic")
%cm_item("Normal")
%cm_item("Italic")
%cm_item("Mario World")
%cm_item("DKC")
%cm_item("ZAMN")
%cm_item("SMT")
%cm_item("Earthbound")
%cm_item("FF6")
%cm_item("Lufia 2")
%cm_item("Goonies 2")
%cm_item("Emerald")
%cm_item("Klonoa")
%cm_item("TI-83")
%cm_item("Pac-Man")
%cm_item("DOOM")
db !list_end
; }}}
|
ADDI $t0, $zero, 0x9
ADDI $t1, $zero, 0x9
MULT $t0, $t1
DIV $t0, $t1
MULT $t0, $t1
MFHI $t0 |
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#ifndef MODEL_COILHEATINGDXVARIABLESPEED_IMPL_HPP
#define MODEL_COILHEATINGDXVARIABLESPEED_IMPL_HPP
#include "ModelAPI.hpp"
#include "StraightComponent_Impl.hpp"
namespace openstudio {
namespace model {
class Curve;
class CoilHeatingDXVariableSpeedSpeedData;
class ModelObjectList;
namespace detail {
/** CoilHeatingDXVariableSpeed_Impl is a StraightComponent_Impl that is the implementation class for CoilHeatingDXVariableSpeed.*/
class MODEL_API CoilHeatingDXVariableSpeed_Impl : public StraightComponent_Impl
{
public:
/** @name Constructors and Destructors */
//@{
CoilHeatingDXVariableSpeed_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle);
CoilHeatingDXVariableSpeed_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle);
CoilHeatingDXVariableSpeed_Impl(const CoilHeatingDXVariableSpeed_Impl& other, Model_Impl* model, bool keepHandle);
virtual ~CoilHeatingDXVariableSpeed_Impl() {}
//@}
/** @name Virtual Methods */
//@{
virtual const std::vector<std::string>& outputVariableNames() const override;
virtual IddObjectType iddObjectType() const override;
virtual unsigned inletPort() const override;
virtual unsigned outletPort() const override;
virtual ModelObject clone(Model model) const override;
virtual std::vector<ModelObject> children() const override;
virtual boost::optional<HVACComponent> containingHVACComponent() const override;
virtual boost::optional<ZoneHVACComponent> containingZoneHVACComponent() const override;
virtual bool addToNode(Node& node) override;
//@}
/** @name Getters */
//@{
int nominalSpeedLevel() const;
boost::optional<double> ratedHeatingCapacityAtSelectedNominalSpeedLevel() const;
bool isRatedHeatingCapacityAtSelectedNominalSpeedLevelAutosized() const;
boost::optional<double> ratedAirFlowRateAtSelectedNominalSpeedLevel() const;
bool isRatedAirFlowRateAtSelectedNominalSpeedLevelAutosized() const;
Curve energyPartLoadFractionCurve() const;
boost::optional<Curve> defrostEnergyInputRatioFunctionofTemperatureCurve() const;
double minimumOutdoorDryBulbTemperatureforCompressorOperation() const;
boost::optional<double> outdoorDryBulbTemperaturetoTurnOnCompressor() const;
double maximumOutdoorDryBulbTemperatureforDefrostOperation() const;
double crankcaseHeaterCapacity() const;
double maximumOutdoorDryBulbTemperatureforCrankcaseHeaterOperation() const;
std::string defrostStrategy() const;
std::string defrostControl() const;
double defrostTimePeriodFraction() const;
boost::optional<double> resistiveDefrostHeaterCapacity() const;
bool isResistiveDefrostHeaterCapacityAutosized() const;
boost::optional<double> autosizedRatedHeatingCapacityAtSelectedNominalSpeedLevel() const;
boost::optional<double> autosizedRatedAirFlowRateAtSelectedNominalSpeedLevel() const;
boost::optional<double> autosizedResistiveDefrostHeaterCapacity() const;
virtual void autosize() override;
virtual void applySizingValues() override;
//@}
/** @name Setters */
//@{
bool setNominalSpeedLevel(int nominalSpeedLevel);
bool setRatedHeatingCapacityAtSelectedNominalSpeedLevel(boost::optional<double> ratedHeatingCapacityAtSelectedNominalSpeedLevel);
void autosizeRatedHeatingCapacityAtSelectedNominalSpeedLevel();
bool setRatedAirFlowRateAtSelectedNominalSpeedLevel(boost::optional<double> ratedAirFlowRateAtSelectedNominalSpeedLevel);
void autosizeRatedAirFlowRateAtSelectedNominalSpeedLevel();
bool setEnergyPartLoadFractionCurve(const Curve& curve);
bool setDefrostEnergyInputRatioFunctionofTemperatureCurve(const boost::optional<Curve>& curve);
void resetDefrostEnergyInputRatioFunctionofTemperatureCurve();
bool setMinimumOutdoorDryBulbTemperatureforCompressorOperation(double minimumOutdoorDryBulbTemperatureforCompressorOperation);
bool setOutdoorDryBulbTemperaturetoTurnOnCompressor(boost::optional<double> outdoorDryBulbTemperaturetoTurnOnCompressor);
void resetOutdoorDryBulbTemperaturetoTurnOnCompressor();
bool setMaximumOutdoorDryBulbTemperatureforDefrostOperation(double maximumOutdoorDryBulbTemperatureforDefrostOperation);
bool setCrankcaseHeaterCapacity(double crankcaseHeaterCapacity);
bool setMaximumOutdoorDryBulbTemperatureforCrankcaseHeaterOperation(double maximumOutdoorDryBulbTemperatureforCrankcaseHeaterOperation);
bool setDefrostStrategy(std::string defrostStrategy);
bool setDefrostControl(std::string defrostControl);
bool setDefrostTimePeriodFraction(double defrostTimePeriodFraction);
bool setResistiveDefrostHeaterCapacity(boost::optional<double> resistiveDefrostHeaterCapacity);
void autosizeResistiveDefrostHeaterCapacity();
//@}
/** @name Other */
//@{
bool setSpeedDataList(const boost::optional<ModelObjectList>& modelObjectList);
void resetSpeedDataList();
boost::optional<ModelObjectList> speedDataList() const;
std::vector<CoilHeatingDXVariableSpeedSpeedData> speeds() const;
bool addSpeed(const CoilHeatingDXVariableSpeedSpeedData& speed);
void removeSpeed(const CoilHeatingDXVariableSpeedSpeedData& speed);
void removeAllSpeeds();
std::vector<IdfObject> remove() override;
//@}
protected:
private:
REGISTER_LOGGER("openstudio.model.CoilHeatingDXVariableSpeed");
// Optional getters for use by methods like children() so can remove() if the constructor fails.
// There are other ways for the public versions of these getters to fail--perhaps all required
// objects should be returned as boost::optionals
boost::optional<Curve> optionalEnergyPartLoadFractionCurve() const;
};
} // namespace detail
} // namespace model
} // namespace openstudio
#endif // MODEL_COILHEATINGDXVARIABLESPEED_IMPL_HPP
|
add $sp, $zero, $imm, 1500 #set $sp to random place to start stack
add $sp, $sp, $imm, -4 #make place for 4 variables
sw $s0, $sp, $imm, 0 # save $s0
sw $s1, $sp, $imm, 1 # save $s1
sw $s2, $sp, $imm, 2 # save $s2
sw $a0, $sp, $imm, 3 #save $a0
add $t3, $zero, $imm, -1 #init $t3 =0 = hitwall
add $s0, $zero, $imm, 1 #init $s0 =1 = pull_reg
add $s1, $zero, $zero #init $s1 = click
add $s2, $zero, $zero #init $s2 = counter
add $a0, $zero, $imm, 1 #init $a0 = 1
add $a1, $zero, $imm, 1 #init $a1= 1 =mask
led $s0, $a0, $a0 #write $s0 = 1 into IOReg[1]
while:
add $s2, $s2, $imm, 100000 #counter++
add $t0, $zero $imm, 2 #set $t0=2
led $s1, $t0, $zero #read from IOReg[2] into $s1 AKA number of clicks
BOUNDSUP:
add $t0, $zero, $imm, 127 # $t0 = 127
led $s0, $a0, $zero #read IOReg[1] into $s0
bgt $imm, $s0, $t0, UPPER #jump to upper if $s0 > $t0
BOUNDSLOW:
add $t0, $zero, $imm, 1 #set $t0 to be 2
led $s0, $a0, $zero #read IOReg[1] into $s0
ble $imm, $s0, $t0, LOWER #jump to lower if $s0 <= 1
beq $imm, $zero, $zero, condEE #didn't trigger any conditions, go back to while
UPPER:
add $s0, $zero, $imm, 128 #set $s0 to 128
led $s0, $a0, $a0 #write $s0 to IOReg[1]
add $t3, $t3, $imm, 1 #hitwall++
beq $imm, $zero, $zero, BOUNDSLOW #check lower boundary aswell
LOWER:
add $s0, $zero, $imm, 1 #init $s0 to 1
led $s0, $a0, $a0 #write $s0 to IOReg[1]
add $t3, $t3, $imm, 1 #hitwall++
condEE:
and $t1, $a1, $s1 # $t1 = click &mask
and $t2, $t3, $a1 # $t2 = hitwall & mask
add $t2, $t1, $t2 # sum both results
beq $imm, $zero, $t2, LEFT # if clicks and hitwall are both even then their sum is 0 and we can enter condition and go left
condOO:
add $t0, $zero, $imm, 2 #set $t0=2
and $t1, $a1, $s1 # $t1 = click &mask
and $t2, $t3, $a1 # $t2 = hitwall & mask
add $t2, $t1, $t2 # sum both results
beq $imm, $t0, $t2, LEFT # if clicks and hitwall are both odd then their sum is 2 and we can enter condition and go left
condOE:
add $t0, $zero, $imm, 1
and $t1, $a1, $s1 # $t1 = click &mask
and $t2, $t3, $a1 # $t2 = hitwall & mask
add $t2, $t1, $t2 # sum both results
beq $imm, $t0, $t2, RIGHT # if clicks is odd and hitwall is even or vice versa then their sum is 1 and we can enter condition and go RIGHT
LEFT:
led $s0, $a0, $zero #read IOReg[1] into $s0
add $t0, $zero $imm, 1 #init $t0 = 1
sll $s0, $s0, $t0 #shift $s0 left by $t0
led $s0, $a0, $a0 #write $s0 into ldreg
add $s2, $zero, $zero #init counter = 0
beq $imm, $zero, $zero, while #check bounds
RIGHT:
led $s0, $a0, $zero #read IOReg[1] into $s0
add $t0, $zero $imm, 1 #init $t0 = 1
sra $s0, $s0, $t0 #shift right arithmetic $s0 >> $t0
led $s0, $a0, $a0 #write $s0 into ldreg
add $s2, $zero, $zero #init counter = 0;
beq $imm, $zero, $zero, while #check bounds
|
.nds
.relativeinclude on
.erroronwarning on
.open "ftc/overlay9_19", 021FFDE0h
.org 0x022130E8 ; Code run for the intro logos.
push r1, r14
mov r0, 1h
ldr r1, =021075F1h
strb r0, [r1] ; Set this to 1 (loading a save) so equipment stays equipped.
; Load the save file.
mov r0, 0h ; Save file 0.
ldr r1, =02106F60h ; TODO 3C
bl 020393B4h
; Set the game state to 08 (ingame).
mov r0, 8h
mov r1, 10h
mov r2, 1h
bl 0203A544h
ldr r1, =021074DCh
; Set the area, sector, and room indexes.
mov r2, 01h
strb r2, [r1, 0Ch] ; Area index, 021074E8
mov r0, 02h
strb r0, [r1, 0Dh] ; Sector index, 021074E9
mov r0, 07h
strb r0, [r1, 0Eh] ; Room index, 021074EA
; Next set the x,y position in the room (default is 80,60).
; The reason for the extra 1 subpixel is so the assembler doesn't optimize these ldr statements into mov statements. If it did that then DSVEdit couldn't change the position at runtime.
ldr r0, =80001h
str r0, [r1, 00h] ; X pos, 021074DC
ldr r0, =60001h
str r0, [r1, 04h] ; Y pos, 021074E0
cmp r2, 1h ; Check if area is Wygol or not.
ldr r1, =021075A9h
ldrb r0, [r1] ; Load top screen from save file.
bne @NotInWygol
@InWygol:
cmp r0, 5h
moveq r0, 8h ; If the save file had the normal map, set it to Wygol map.
streqb r0, [r1] ; Store it back to 0210078D in case the player spawns in a warp room.
b @AfterWygol
@NotInWygol:
cmp r0, 8h
moveq r0, 5h ; If the save file had the Wygol map, set it to the normal map.
streqb r0, [r1] ; Store it back to 0210078D in case the player spawns in a warp room.
@AfterWygol:
mov r1, 10h
mov r2, 1h
bl 0208C7F8h ; Change the top screen to that value.
pop r1, r15
.pool
.close
|
; A086594: a(n) = 8*a(n-1) + a(n-2), starting with a(0)=2 and a(1)=8.
; Submitted by Jon Maiga
; 2,8,66,536,4354,35368,287298,2333752,18957314,153992264,1250895426,10161155672,82540140802,670482282088,5446398397506,44241669462136,359379754094594,2919279702218888,23713617371845698,192628218676984472,1564739366787721474,12710543152978756264,103249084590617771586,838703219877920928952,6812874843613985203202,55341701968789802554568,449546490593932405639746,3651713626720249047672536,29663255504355924787020034,240957757661567647343832808,1957325316796897103537682498,15899560292036744475645292792
mov $3,1
lpb $0
sub $0,1
add $2,$3
mov $3,$1
mov $1,$2
mul $2,4
add $3,$2
lpe
mov $0,$3
mul $0,2
|
; A165797: a(n) = n^( sigma(n) - tau(n) ).
; Submitted by Christian Krause
; 1,2,9,256,625,1679616,117649,8589934592,3486784401,100000000000000,25937424601,552061438912436417593344,23298085122481,83668255425284801560576,332525673007965087890625,20282409603651670423947251286016,48661191875666868481,265456074833292280954988944586975024775168,104127350297911241532841,68719476736000000000000000000000000000000000000,10523016528610349434285830688358359761,9068298061633453450429559033030337013743616,907846434775996175406740561329
mov $1,$0
add $0,1
seq $1,65608 ; Sum of divisors of n minus the number of divisors of n.
pow $0,$1
|
/*
* VueceAACDecoder.cc
*
* Created on: Nov 1, 2014
* Author: jingjing
*/
//Note - Must use extern "C" here otherwise you will get 'undefined reference' errors
extern "C"
{
#include "libavformat/avformat.h"
#include "libavutil/log.h"
#include "libavcodec/avcodec.h"
#include "libavutil/mem.h"
}
#include "VueceLogger.h"
#include "VueceConstants.h"
#include "VueceAACDecoder.h"
VueceAACDecoder::VueceAACDecoder()
{
VueceLogger::Debug("VueceAACDecoder - Constructor called");
dec_data = NULL;
}
VueceAACDecoder::~VueceAACDecoder()
{
VueceLogger::Debug("VueceAACDecoder - Destructor called");
}
void VueceAACDecoder::Uninit()
{
VueceLogger::Debug("VUECE AAC DECODER - Uninit");
if(dec_data != NULL)
{
av_free(dec_data->outbuf);
avcodec_close(dec_data->pCodecCtx);
free(dec_data);
dec_data = NULL;
}
VueceLogger::Debug("VUECE AAC DECODER - Uninit Done");
}
bool VueceAACDecoder::Init(int sample_rate, int bit_rate, int channel_num)
{
VueceLogger::Debug("VueceAACDecoder - Init called, sample_rate = %d, bit_rate = %d, channel_num = %d",
sample_rate, bit_rate, channel_num);
dec_data = (VueceAACDecData*)malloc(sizeof(VueceAACDecData));
dec_data->pCodecCtx = NULL;
dec_data->pCodec = NULL;
dec_data->outbuf = NULL;
dec_data->decoded_raw_pkt_size = 0;
dec_data->buf_count = 0;
VueceAACDecData* d = dec_data;
d->outbuf =(int16_t*)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
// Register all formats and codecs
av_register_all();
d->pCodec = avcodec_find_decoder(CODEC_ID_AAC);
if(d->pCodec == NULL)
{
VueceLogger::Fatal("VUECE AAC DECODER - Decoder not found.");
return false;
}
VueceLogger::Debug("VUECE AAC DECODER - Init: Decoder located.");
d->pCodecCtx = avcodec_alloc_context3(d->pCodec);
if(d->pCodecCtx != NULL)
{
VueceLogger::Debug("VUECE AAC DECODER - Init: Decoder context allocated.");
}
else
{
//TODO: May be we need to do this in a gracefull way
VueceLogger::Fatal("VUECE AAC DECODER - Init: Decoder context allocation failed! Abort.");
return false;
}
d->pCodecCtx->sample_fmt = AV_SAMPLE_FMT_S16;
//set default values, they will be updated in later SET methods
d->pCodecCtx->sample_rate = 44100;
d->pCodecCtx->channels = 2;
d->decoded_raw_pkt_size = 4096;
//this is hard-coded for now
d->pCodecCtx->bit_rate = 1411200;//64000;//1411200;//1411200;//100035;
d->pCodecCtx->profile = FF_PROFILE_AAC_MAIN;
d->pCodecCtx->codec_type = AVMEDIA_TYPE_AUDIO;
d->pCodecCtx->frame_size = 1024;
//customize settings based on actual input
d->pCodecCtx->sample_rate = sample_rate;
d->pCodecCtx->bit_rate = bit_rate;
set_num_channels(channel_num);
VueceLogger::Debug("VUECE AAC DECODER - Opening codec, sample_rate: %d, channels: %d, bit_rate: %d",
d->pCodecCtx->sample_rate, d->pCodecCtx->channels, d->pCodecCtx->bit_rate);
if(avcodec_open(d->pCodecCtx, d->pCodec)<0)
{
VueceLogger::Fatal("VUECE AAC DECODER - Init:Cannot open AAC codec!");
return false;
}
VueceLogger::Debug("VUECE AAC DECODER - Init: Decoder successfully opened, init OK");
return true;
}
void VueceAACDecoder::set_num_channels(int channels){
VueceAACDecData* d = dec_data;
d->pCodecCtx->channels = channels;
VueceLogger::Debug("VUECE AAC DECODER - set_num_channels: %d", d->pCodecCtx->channels);
if(channels == 1)
{
d->decoded_raw_pkt_size = 2048;
}
else if(channels == 2)
{
d->decoded_raw_pkt_size = 4096;
}
else
{
VueceLogger::Fatal("VUECE AAC DECODER - set_num_channels: wrong channel number.");
return;
}
VueceLogger::Debug("VUECE AAC DECODER - set_num_channels, decoded_raw_pkt_size is updated to: %d", d->decoded_raw_pkt_size);
return;
}
void VueceAACDecoder::Process(VueceMemQueue* in_q, VueceMemQueue* out_q)
{
VueceMemBulk *im,*om;
int nbytes;
int resultSize, decLen;
VueceAACDecData *d = dec_data;
// VueceLogger::Debug("VUECE AAC DECODER - Process: Input queue bulk count: %d", in_q->BulkCount());
if(in_q->IsEmpty())
{
// VueceLogger::Debug("VUECE AAC DECODER - Process - Input queue is empty, do nothing and return");
return;
}
VueceLogger::Debug("VUECE AAC DECODER - Process: Input queue bulk count: %d", in_q->BulkCount());
while ( (im = in_q->Remove()) != NULL)
{
AVPacket pkt;
nbytes = im->size_orginal;
if (nbytes <= 0)
{
VueceLogger::Fatal("VUECE AAC DECODER - Process - Got a empty iput bulk, sth is wrong");
return;
}
om = VueceMemQueue::AllocMemBulk(d->decoded_raw_pkt_size);
// VueceLogger::Debug("VUECE AAC DECODER - processing data, size = %d", nbytes);
av_init_packet(&pkt);
pkt.data = (uint8_t *)im->data;
pkt.size = nbytes;
resultSize = d->decoded_raw_pkt_size;
decLen = avcodec_decode_audio3(d->pCodecCtx, (int16_t *)om->data, &resultSize, &pkt);
if(decLen <= 0)
{
VueceMemQueue::FreeMemBulk(om);
VueceLogger::Fatal("VUECE AAC DECODER - avcodec_decode_audio3 returned a negative value: %d", decLen);
return;
}
om->size_orginal = resultSize;
om->end += resultSize;
// VueceLogger::Debug("VUECE AAC DECODER - Number of bytes decompressed: %d, result data size: %d ", decLen, resultSize);
out_q->Put(om);
d->buf_count++;
VueceMemQueue::FreeMemBulk(im);
}
}
|
;
; Copyright(c) 2019 Intel Corporation
; SPDX - License - Identifier: BSD - 2 - Clause - Patent
;
%include "x64inc.asm"
%include "x64Macro.asm"
section .text
; ----------------------------------------------------------------------------------------
cglobal _picture_copy_kernel_sse2
cglobal picture_copy_kernel_sse2
; Requirement: areaWidthInBytes = 4, 8, 12, 16, 24, 32, 48, 64 or 128
; Requirement: area_height % 2 = 0
%define src r0
%define srcStrideInBytes r1
%define dst r2
%define dstStrideInBytes r3
%define areaWidthInBytes r4
%define area_height r5
GET_PARAM_5UXD
GET_PARAM_6UXD
XMM_SAVE
cmp areaWidthInBytes, 16
jg Label_PictureCopyKernel_SSE2_WIDTH_Big
je Label_PictureCopyKernel_SSE2_WIDTH16
cmp areaWidthInBytes, 4
je Label_PictureCopyKernel_SSE2_WIDTH4
cmp areaWidthInBytes, 8
je Label_PictureCopyKernel_SSE2_WIDTH8
Label_PictureCopyKernel_SSE2_WIDTH12:
movq xmm0, [src]
movd xmm1, [src+8]
movq xmm2, [src+srcStrideInBytes]
movd xmm3, [src+srcStrideInBytes+8]
lea src, [src+2*srcStrideInBytes]
movq [dst], xmm0
movd [dst+8], xmm1
movq [dst+dstStrideInBytes], xmm2
movd [dst+dstStrideInBytes+8], xmm3
lea dst, [dst+2*dstStrideInBytes]
sub area_height, 2
jne Label_PictureCopyKernel_SSE2_WIDTH12
XMM_RESTORE
ret
Label_PictureCopyKernel_SSE2_WIDTH8:
movq xmm0, [src]
movq xmm1, [src+srcStrideInBytes]
lea src, [src+2*srcStrideInBytes]
movq [dst], xmm0
movq [dst+dstStrideInBytes], xmm1
lea dst, [dst+2*dstStrideInBytes]
sub area_height, 2
jne Label_PictureCopyKernel_SSE2_WIDTH8
XMM_RESTORE
ret
Label_PictureCopyKernel_SSE2_WIDTH4:
movd xmm0, [src]
movd xmm1, [src+srcStrideInBytes]
lea src, [src+2*srcStrideInBytes]
movd [dst], xmm0
movd [dst+dstStrideInBytes], xmm1
lea dst, [dst+2*dstStrideInBytes]
sub area_height, 2
jne Label_PictureCopyKernel_SSE2_WIDTH4
XMM_RESTORE
ret
Label_PictureCopyKernel_SSE2_WIDTH_Big:
cmp areaWidthInBytes, 24
je Label_PictureCopyKernel_SSE2_WIDTH24
cmp areaWidthInBytes, 32
je Label_PictureCopyKernel_SSE2_WIDTH32
cmp areaWidthInBytes, 48
je Label_PictureCopyKernel_SSE2_WIDTH48
cmp areaWidthInBytes, 64
je Label_PictureCopyKernel_SSE2_WIDTH64
Label_PictureCopyKernel_SSE2_WIDTH128:
movdqu xmm0, [src]
movdqu xmm1, [src+16]
movdqu xmm2, [src+32]
movdqu xmm3, [src+48]
movdqu xmm4, [src+64]
movdqu xmm5, [src+80]
movdqu xmm6, [src+96]
movdqu xmm7, [src+112]
lea src, [src+srcStrideInBytes]
movdqu [dst], xmm0
movdqu [dst+16], xmm1
movdqu [dst+32], xmm2
movdqu [dst+48], xmm3
movdqu [dst+64], xmm4
movdqu [dst+80], xmm5
movdqu [dst+96], xmm6
movdqu [dst+112], xmm7
lea dst, [dst+dstStrideInBytes]
sub area_height, 1
jne Label_PictureCopyKernel_SSE2_WIDTH128
XMM_RESTORE
ret
Label_PictureCopyKernel_SSE2_WIDTH64:
movdqu xmm0, [src]
movdqu xmm1, [src+16]
movdqu xmm2, [src+32]
movdqu xmm3, [src+48]
movdqu xmm4, [src+srcStrideInBytes]
movdqu xmm5, [src+srcStrideInBytes+16]
movdqu xmm6, [src+srcStrideInBytes+32]
movdqu xmm7, [src+srcStrideInBytes+48]
lea src, [src+2*srcStrideInBytes]
movdqu [dst], xmm0
movdqu [dst+16], xmm1
movdqu [dst+32], xmm2
movdqu [dst+48], xmm3
movdqu [dst+dstStrideInBytes], xmm4
movdqu [dst+dstStrideInBytes+16], xmm5
movdqu [dst+dstStrideInBytes+32], xmm6
movdqu [dst+dstStrideInBytes+48], xmm7
lea dst, [dst+2*dstStrideInBytes]
sub area_height, 2
jne Label_PictureCopyKernel_SSE2_WIDTH64
XMM_RESTORE
ret
Label_PictureCopyKernel_SSE2_WIDTH48:
movdqu xmm0, [src]
movdqu xmm1, [src+16]
movdqu xmm2, [src+32]
movdqu xmm3, [src+srcStrideInBytes]
movdqu xmm4, [src+srcStrideInBytes+16]
movdqu xmm5, [src+srcStrideInBytes+32]
lea src, [src+2*srcStrideInBytes]
movdqu [dst], xmm0
movdqu [dst+16], xmm1
movdqu [dst+32], xmm2
movdqu [dst+dstStrideInBytes], xmm3
movdqu [dst+dstStrideInBytes+16], xmm4
movdqu [dst+dstStrideInBytes+32], xmm5
lea dst, [dst+2*dstStrideInBytes]
sub area_height, 2
jne Label_PictureCopyKernel_SSE2_WIDTH48
XMM_RESTORE
ret
Label_PictureCopyKernel_SSE2_WIDTH32:
movdqu xmm0, [src]
movdqu xmm1, [src+16]
movdqu xmm2, [src+srcStrideInBytes]
movdqu xmm3, [src+srcStrideInBytes+16]
lea src, [src+2*srcStrideInBytes]
movdqu [dst], xmm0
movdqu [dst+16], xmm1
movdqu [dst+dstStrideInBytes], xmm2
movdqu [dst+dstStrideInBytes+16], xmm3
lea dst, [dst+2*dstStrideInBytes]
sub area_height, 2
jne Label_PictureCopyKernel_SSE2_WIDTH32
XMM_RESTORE
ret
Label_PictureCopyKernel_SSE2_WIDTH24:
movdqu xmm0, [src]
movq xmm1, [src+16]
movdqu xmm2, [src+srcStrideInBytes]
movq xmm3, [src+srcStrideInBytes+16]
lea src, [src+2*srcStrideInBytes]
movdqu [dst], xmm0
movq [dst+16], xmm1
movdqu [dst+dstStrideInBytes], xmm2
movq [dst+dstStrideInBytes+16], xmm3
lea dst, [dst+2*dstStrideInBytes]
sub area_height, 2
jne Label_PictureCopyKernel_SSE2_WIDTH24
XMM_RESTORE
ret
Label_PictureCopyKernel_SSE2_WIDTH16:
movdqu xmm0, [src]
movdqu xmm1, [src+srcStrideInBytes]
lea src, [src+2*srcStrideInBytes]
movdqu [dst], xmm0
movdqu [dst+dstStrideInBytes], xmm1
lea dst, [dst+2*dstStrideInBytes]
sub area_height, 2
jne Label_PictureCopyKernel_SSE2_WIDTH16
XMM_RESTORE
ret
; ----------------------------------------------------------------------------------------
cglobal _zero_out_coeff4x4_sse
cglobal zero_out_coeff4x4_sse
lea r0, [r0+2*r2]
lea r3, [r1+2*r1]
pxor mm0, mm0
movq [r0], mm0
movq [r0+2*r1], mm0
movq [r0+4*r1], mm0
movq [r0+2*r3], mm0
%if NEED_EMMS
emms
%endif
ret
; ----------------------------------------------------------------------------------------
cglobal _zero_out_coeff8x8_sse2
cglobal zero_out_coeff8x8_sse2
; TODO: use "movdqa" if coeff_buffer is guaranteed to be 16-byte aligned.
lea r0, [r0+2*r2]
lea r3, [r1+2*r1]
pxor xmm0, xmm0
movdqu [r0], xmm0
movdqu [r0+2*r1], xmm0
movdqu [r0+4*r1], xmm0
movdqu [r0+2*r3], xmm0
lea r0, [r0+8*r1]
movdqu [r0], xmm0
movdqu [r0+2*r1], xmm0
movdqu [r0+4*r1], xmm0
movdqu [r0+2*r3], xmm0
ret
; ----------------------------------------------------------------------------------------
cglobal _zero_out_coeff16x16_sse2
cglobal zero_out_coeff16x16_sse2
; TODO: use "movdqa" if coeff_buffer is guaranteed to be 16-byte aligned.
lea r0, [r0+2*r2]
lea r3, [r1+2*r1]
pxor xmm0, xmm0
movdqu [r0], xmm0
movdqu [r0+16], xmm0
movdqu [r0+2*r1], xmm0
movdqu [r0+2*r1+16], xmm0
movdqu [r0+4*r1], xmm0
movdqu [r0+4*r1+16], xmm0
movdqu [r0+2*r3], xmm0
movdqu [r0+2*r3+16], xmm0
lea r0, [r0+8*r1]
movdqu [r0], xmm0
movdqu [r0+16], xmm0
movdqu [r0+2*r1], xmm0
movdqu [r0+2*r1+16], xmm0
movdqu [r0+4*r1], xmm0
movdqu [r0+4*r1+16], xmm0
movdqu [r0+2*r3], xmm0
movdqu [r0+2*r3+16], xmm0
lea r0, [r0+8*r1]
movdqu [r0], xmm0
movdqu [r0+16], xmm0
movdqu [r0+2*r1], xmm0
movdqu [r0+2*r1+16], xmm0
movdqu [r0+4*r1], xmm0
movdqu [r0+4*r1+16], xmm0
movdqu [r0+2*r3], xmm0
movdqu [r0+2*r3+16], xmm0
lea r0, [r0+8*r1]
movdqu [r0], xmm0
movdqu [r0+16], xmm0
movdqu [r0+2*r1], xmm0
movdqu [r0+2*r1+16], xmm0
movdqu [r0+4*r1], xmm0
movdqu [r0+4*r1+16], xmm0
movdqu [r0+2*r3], xmm0
movdqu [r0+2*r3+16], xmm0
ret
; ----------------------------------------------------------------------------------------
cglobal _zero_out_coeff32x32_sse2
cglobal zero_out_coeff32x32_sse2
; TODO: use "movdqa" if coeff_buffer is guaranteed to be 16-byte aligned.
lea r0, [r0+2*r2]
lea r3, [r1+2*r1]
mov r4, 4
pxor xmm0, xmm0
Label_ZeroOutCoeff32x32_SSE2_01:
movdqu [r0], xmm0
movdqu [r0+16], xmm0
movdqu [r0+32], xmm0
movdqu [r0+48], xmm0
movdqu [r0+2*r1], xmm0
movdqu [r0+2*r1+16], xmm0
movdqu [r0+2*r1+32], xmm0
movdqu [r0+2*r1+48], xmm0
movdqu [r0+4*r1], xmm0
movdqu [r0+4*r1+16], xmm0
movdqu [r0+4*r1+32], xmm0
movdqu [r0+4*r1+48], xmm0
movdqu [r0+2*r3], xmm0
movdqu [r0+2*r3+16], xmm0
movdqu [r0+2*r3+32], xmm0
movdqu [r0+2*r3+48], xmm0
lea r0, [r0+8*r1]
movdqu [r0], xmm0
movdqu [r0+16], xmm0
movdqu [r0+32], xmm0
movdqu [r0+48], xmm0
movdqu [r0+2*r1], xmm0
movdqu [r0+2*r1+16], xmm0
movdqu [r0+2*r1+32], xmm0
movdqu [r0+2*r1+48], xmm0
movdqu [r0+4*r1], xmm0
movdqu [r0+4*r1+16], xmm0
movdqu [r0+4*r1+32], xmm0
movdqu [r0+4*r1+48], xmm0
movdqu [r0+2*r3], xmm0
movdqu [r0+2*r3+16], xmm0
movdqu [r0+2*r3+32], xmm0
movdqu [r0+2*r3+48], xmm0
lea r0, [r0+8*r1]
sub r4, 1
jne Label_ZeroOutCoeff32x32_SSE2_01
ret
; ----------------------------------------------------------------------------------------
cglobal _picture_average_kernel_sse2
cglobal picture_average_kernel_sse2
; Requirement: pu_width = 4, 8, 12, 16, 24, 32, 48 or 64
; Requirement: pu_height % 2 = 0
; Requirement: src0 % 16 = 0 when pu_width >= 16
; Requirement: src1 % 16 = 0 when pu_width >= 16
; Requirement: dst % 16 = 0 when pu_width >= 16
; Requirement: src0_stride % 16 = 0 when pu_width >= 16
; Requirement: src1_stride % 16 = 0 when pu_width >= 16
; Requirement: dst_stride % 16 = 0 when pu_width >= 16
%define src0 r0
%define src0_stride r1
%define src1 r2
%define src1_stride r3
%define dst r4
%define dst_stride r5
%define area_width r6
%define area_height r7
GET_PARAM_5Q
GET_PARAM_6UXD
GET_PARAM_7UXD
PUSH_REG 7
XMM_SAVE
GET_PARAM_8UXD r7d ; area_height
cmp area_width, 16
jg Label_PictureAverageKernel_SSE2_WIDTH_Big
je Label_PictureAverageKernel_SSE2_WIDTH16
cmp area_width, 4
je Label_PictureAverageKernel_SSE2_WIDTH4
cmp area_width, 8
je Label_PictureAverageKernel_SSE2_WIDTH8
Label_PictureAverageKernel_SSE2_WIDTH12:
movq mm0, [src0]
movd mm1, [src0+8]
movq mm2, [src0+src0_stride]
movd mm3, [src0+src0_stride+8]
pavgb mm0, [src1]
pavgb mm1, [src1+8]
pavgb mm2, [src1+src1_stride]
pavgb mm3, [src1+src1_stride+8]
lea src0, [src0+2*src0_stride]
lea src1, [src1+2*src1_stride]
movq [dst], mm0
movd [dst+8], mm1
movq [dst+dst_stride], mm2
movd [dst+dst_stride+8], mm3
lea dst, [dst+2*dst_stride]
sub area_height, 2
jne Label_PictureAverageKernel_SSE2_WIDTH12
XMM_RESTORE
POP_REG 7
%if NEED_EMMS
emms
%endif
ret
Label_PictureAverageKernel_SSE2_WIDTH8:
movq mm0, [src0]
movq mm1, [src0+src0_stride]
pavgb mm0, [src1]
pavgb mm1, [src1+src1_stride]
lea src0, [src0+2*src0_stride]
lea src1, [src1+2*src1_stride]
movq [dst], mm0
movq [dst+dst_stride], mm1
lea dst, [dst+2*dst_stride]
sub area_height, 2
jne Label_PictureAverageKernel_SSE2_WIDTH8
XMM_RESTORE
POP_REG 7
%if NEED_EMMS
emms
%endif
ret
Label_PictureAverageKernel_SSE2_WIDTH4:
movd mm0, [src0]
movd mm1, [src0+src0_stride]
pavgb mm0, [src1]
pavgb mm1, [src1+src1_stride]
lea src0, [src0+2*src0_stride]
lea src1, [src1+2*src1_stride]
movd [dst], mm0
movd [dst+dst_stride], mm1
lea dst, [dst+2*dst_stride]
sub area_height, 2
jne Label_PictureAverageKernel_SSE2_WIDTH4
XMM_RESTORE
POP_REG 7
%if NEED_EMMS
emms
%endif
ret
Label_PictureAverageKernel_SSE2_WIDTH_Big:
cmp area_width, 24
je Label_PictureAverageKernel_SSE2_WIDTH24
cmp area_width, 32
je Label_PictureAverageKernel_SSE2_WIDTH32
cmp area_width, 48
je Label_PictureAverageKernel_SSE2_WIDTH48
Label_PictureAverageKernel_SSE2_WIDTH64:
movdqu xmm0, [src0]
movdqu xmm1, [src0+16]
movdqu xmm2, [src0+32]
movdqu xmm3, [src0+48]
movdqu xmm4, [src0+src0_stride]
movdqu xmm5, [src0+src0_stride+16]
movdqu xmm6, [src0+src0_stride+32]
movdqu xmm7, [src0+src0_stride+48]
movdqu xmm8, [src1]
pavgb xmm0, xmm8
movdqu xmm8, [src1+16]
pavgb xmm1, xmm8
movdqu xmm8, [src1+32]
pavgb xmm2, xmm8
movdqu xmm8, [src1+48]
pavgb xmm3, xmm8
movdqu xmm8, [src1+src1_stride]
pavgb xmm4, xmm8
movdqu xmm8, [src1+src1_stride+16]
pavgb xmm5, xmm8
movdqu xmm8, [src1+src1_stride+32]
pavgb xmm6, xmm8
movdqu xmm8, [src1+src1_stride+48]
pavgb xmm7, xmm8
lea src0, [src0+2*src0_stride]
lea src1, [src1+2*src1_stride]
movdqu [dst], xmm0
movdqu [dst+16], xmm1
movdqu [dst+32], xmm2
movdqu [dst+48], xmm3
movdqu [dst+dst_stride], xmm4
movdqu [dst+dst_stride+16], xmm5
movdqu [dst+dst_stride+32], xmm6
movdqu [dst+dst_stride+48], xmm7
lea dst, [dst+2*dst_stride]
sub area_height, 2
jne Label_PictureAverageKernel_SSE2_WIDTH64
XMM_RESTORE
POP_REG 7
ret
Label_PictureAverageKernel_SSE2_WIDTH48:
movdqu xmm0, [src0]
movdqu xmm1, [src0+16]
movdqu xmm2, [src0+32]
movdqu xmm3, [src0+src0_stride]
movdqu xmm4, [src0+src0_stride+16]
movdqu xmm5, [src0+src0_stride+32]
movdqu xmm6, [src1]
pavgb xmm0, xmm6
movdqu xmm6, [src1+16]
pavgb xmm1, xmm6
movdqu xmm6, [src1+32]
pavgb xmm2, xmm6
movdqu xmm6, [src1+src1_stride]
pavgb xmm3, xmm6
movdqu xmm6, [src1+src1_stride+16]
pavgb xmm4, xmm6
movdqu xmm6, [src1+src1_stride+32]
pavgb xmm5, xmm6
lea src0, [src0+2*src0_stride]
lea src1, [src1+2*src1_stride]
movdqu [dst], xmm0
movdqu [dst+16], xmm1
movdqu [dst+32], xmm2
movdqu [dst+dst_stride], xmm3
movdqu [dst+dst_stride+16], xmm4
movdqu [dst+dst_stride+32], xmm5
lea dst, [dst+2*dst_stride]
sub area_height, 2
jne Label_PictureAverageKernel_SSE2_WIDTH48
XMM_RESTORE
POP_REG 7
ret
Label_PictureAverageKernel_SSE2_WIDTH32:
movdqu xmm0, [src0]
movdqu xmm1, [src0+16]
movdqu xmm2, [src0+src0_stride]
movdqu xmm3, [src0+src0_stride+16]
movdqu xmm4, [src1]
pavgb xmm0, xmm4
movdqu xmm4, [src1+16]
pavgb xmm1, xmm4
movdqu xmm4, [src1+src1_stride]
pavgb xmm2, xmm4
movdqu xmm4, [src1+src1_stride+16]
pavgb xmm3, xmm4
lea src0, [src0+2*src0_stride]
lea src1, [src1+2*src1_stride]
movdqu [dst], xmm0
movdqu [dst+16], xmm1
movdqu [dst+dst_stride], xmm2
movdqu [dst+dst_stride+16], xmm3
lea dst, [dst+2*dst_stride]
sub area_height, 2
jne Label_PictureAverageKernel_SSE2_WIDTH32
XMM_RESTORE
POP_REG 7
ret
Label_PictureAverageKernel_SSE2_WIDTH24:
movdqu xmm0, [src0]
movq mm0, [src0+16]
movdqu xmm1, [src0+src0_stride]
movq mm1, [src0+src0_stride+16]
movdqu xmm2, [src1]
pavgb xmm0, xmm2
pavgb mm0, [src1+16]
movdqu xmm3, [src1+src1_stride]
pavgb xmm1, xmm3
pavgb mm1, [src1+src1_stride+16]
lea src0, [src0+2*src0_stride]
lea src1, [src1+2*src1_stride]
movdqu [dst], xmm0
movq [dst+16], mm0
movdqu [dst+dst_stride], xmm1
movq [dst+dst_stride+16], mm1
lea dst, [dst+2*dst_stride]
sub area_height, 2
jne Label_PictureAverageKernel_SSE2_WIDTH24
XMM_RESTORE
POP_REG 7
%if NEED_EMMS
emms
%endif
ret
Label_PictureAverageKernel_SSE2_WIDTH16:
movdqu xmm0, [src0]
movdqu xmm1, [src0+src0_stride]
movdqu xmm4, [src1]
pavgb xmm0, xmm4
movdqu xmm4, [src1+src1_stride]
pavgb xmm1, xmm4
lea src0, [src0+2*src0_stride]
lea src1, [src1+2*src1_stride]
movdqu [dst], xmm0
movdqu [dst+dst_stride], xmm1
lea dst, [dst+2*dst_stride]
sub area_height, 2
jne Label_PictureAverageKernel_SSE2_WIDTH16
XMM_RESTORE
POP_REG 7
ret
; ----------------------------------------------------------------------------------------
cglobal _Log2f_SSE2
cglobal Log2f_SSE2
bsr rax, r0
ret
|
//===-- StopInfo.cpp ------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <string>
#include "lldb/Breakpoint/Breakpoint.h"
#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Breakpoint/StoppointCallbackContext.h"
#include "lldb/Breakpoint/Watchpoint.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/Expression/UserExpression.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Target/ThreadPlan.h"
#include "lldb/Target/UnixSignals.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/StreamString.h"
using namespace lldb;
using namespace lldb_private;
StopInfo::StopInfo(Thread &thread, uint64_t value)
: m_thread_wp(thread.shared_from_this()),
m_stop_id(thread.GetProcess()->GetStopID()),
m_resume_id(thread.GetProcess()->GetResumeID()), m_value(value),
m_description(), m_override_should_notify(eLazyBoolCalculate),
m_override_should_stop(eLazyBoolCalculate), m_extended_info() {}
bool StopInfo::IsValid() const {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp)
return thread_sp->GetProcess()->GetStopID() == m_stop_id;
return false;
}
void StopInfo::MakeStopInfoValid() {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp) {
m_stop_id = thread_sp->GetProcess()->GetStopID();
m_resume_id = thread_sp->GetProcess()->GetResumeID();
}
}
bool StopInfo::HasTargetRunSinceMe() {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp) {
lldb::StateType ret_type = thread_sp->GetProcess()->GetPrivateState();
if (ret_type == eStateRunning) {
return true;
} else if (ret_type == eStateStopped) {
// This is a little tricky. We want to count "run and stopped again
// before you could ask this question as a "TRUE" answer to
// HasTargetRunSinceMe. But we don't want to include any running of the
// target done for expressions. So we track both resumes, and resumes
// caused by expressions, and check if there are any resumes
// NOT caused
// by expressions.
uint32_t curr_resume_id = thread_sp->GetProcess()->GetResumeID();
uint32_t last_user_expression_id =
thread_sp->GetProcess()->GetLastUserExpressionResumeID();
if (curr_resume_id == m_resume_id) {
return false;
} else if (curr_resume_id > last_user_expression_id) {
return true;
}
}
}
return false;
}
// StopInfoBreakpoint
namespace lldb_private {
class StopInfoBreakpoint : public StopInfo {
public:
StopInfoBreakpoint(Thread &thread, break_id_t break_id)
: StopInfo(thread, break_id), m_should_stop(false),
m_should_stop_is_valid(false), m_should_perform_action(true),
m_address(LLDB_INVALID_ADDRESS), m_break_id(LLDB_INVALID_BREAK_ID),
m_was_one_shot(false) {
StoreBPInfo();
}
StopInfoBreakpoint(Thread &thread, break_id_t break_id, bool should_stop)
: StopInfo(thread, break_id), m_should_stop(should_stop),
m_should_stop_is_valid(true), m_should_perform_action(true),
m_address(LLDB_INVALID_ADDRESS), m_break_id(LLDB_INVALID_BREAK_ID),
m_was_one_shot(false) {
StoreBPInfo();
}
~StopInfoBreakpoint() override = default;
void StoreBPInfo() {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp) {
BreakpointSiteSP bp_site_sp(
thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
if (bp_site_sp) {
if (bp_site_sp->GetNumberOfOwners() == 1) {
BreakpointLocationSP bp_loc_sp = bp_site_sp->GetOwnerAtIndex(0);
if (bp_loc_sp) {
m_break_id = bp_loc_sp->GetBreakpoint().GetID();
m_was_one_shot = bp_loc_sp->GetBreakpoint().IsOneShot();
}
}
m_address = bp_site_sp->GetLoadAddress();
}
}
}
bool IsValidForOperatingSystemThread(Thread &thread) override {
ProcessSP process_sp(thread.GetProcess());
if (process_sp) {
BreakpointSiteSP bp_site_sp(
process_sp->GetBreakpointSiteList().FindByID(m_value));
if (bp_site_sp)
return bp_site_sp->ValidForThisThread(thread);
}
return false;
}
StopReason GetStopReason() const override { return eStopReasonBreakpoint; }
bool ShouldStopSynchronous(Event *event_ptr) override {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp) {
if (!m_should_stop_is_valid) {
// Only check once if we should stop at a breakpoint
BreakpointSiteSP bp_site_sp(
thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
if (bp_site_sp) {
ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
StoppointCallbackContext context(event_ptr, exe_ctx, true);
bp_site_sp->BumpHitCounts();
m_should_stop = bp_site_sp->ShouldStop(&context);
} else {
Log *log = GetLog(LLDBLog::Process);
LLDB_LOGF(log,
"Process::%s could not find breakpoint site id: %" PRId64
"...",
__FUNCTION__, m_value);
m_should_stop = true;
}
m_should_stop_is_valid = true;
}
return m_should_stop;
}
return false;
}
bool DoShouldNotify(Event *event_ptr) override {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp) {
BreakpointSiteSP bp_site_sp(
thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
if (bp_site_sp) {
bool all_internal = true;
for (uint32_t i = 0; i < bp_site_sp->GetNumberOfOwners(); i++) {
if (!bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint().IsInternal()) {
all_internal = false;
break;
}
}
return !all_internal;
}
}
return true;
}
const char *GetDescription() override {
if (m_description.empty()) {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp) {
BreakpointSiteSP bp_site_sp(
thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
if (bp_site_sp) {
StreamString strm;
// If we have just hit an internal breakpoint, and it has a kind
// description, print that instead of the full breakpoint printing:
if (bp_site_sp->IsInternal()) {
size_t num_owners = bp_site_sp->GetNumberOfOwners();
for (size_t idx = 0; idx < num_owners; idx++) {
const char *kind = bp_site_sp->GetOwnerAtIndex(idx)
->GetBreakpoint()
.GetBreakpointKind();
if (kind != nullptr) {
m_description.assign(kind);
return kind;
}
}
}
strm.Printf("breakpoint ");
bp_site_sp->GetDescription(&strm, eDescriptionLevelBrief);
m_description = std::string(strm.GetString());
} else {
StreamString strm;
if (m_break_id != LLDB_INVALID_BREAK_ID) {
BreakpointSP break_sp =
thread_sp->GetProcess()->GetTarget().GetBreakpointByID(
m_break_id);
if (break_sp) {
if (break_sp->IsInternal()) {
const char *kind = break_sp->GetBreakpointKind();
if (kind)
strm.Printf("internal %s breakpoint(%d).", kind, m_break_id);
else
strm.Printf("internal breakpoint(%d).", m_break_id);
} else {
strm.Printf("breakpoint %d.", m_break_id);
}
} else {
if (m_was_one_shot)
strm.Printf("one-shot breakpoint %d", m_break_id);
else
strm.Printf("breakpoint %d which has been deleted.",
m_break_id);
}
} else if (m_address == LLDB_INVALID_ADDRESS)
strm.Printf("breakpoint site %" PRIi64
" which has been deleted - unknown address",
m_value);
else
strm.Printf("breakpoint site %" PRIi64
" which has been deleted - was at 0x%" PRIx64,
m_value, m_address);
m_description = std::string(strm.GetString());
}
}
}
return m_description.c_str();
}
protected:
bool ShouldStop(Event *event_ptr) override {
// This just reports the work done by PerformAction or the synchronous
// stop. It should only ever get called after they have had a chance to
// run.
assert(m_should_stop_is_valid);
return m_should_stop;
}
void PerformAction(Event *event_ptr) override {
if (!m_should_perform_action)
return;
m_should_perform_action = false;
bool internal_breakpoint = true;
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp) {
Log *log = GetLog(LLDBLog::Breakpoints | LLDBLog::Step);
if (!thread_sp->IsValid()) {
// This shouldn't ever happen, but just in case, don't do more harm.
if (log) {
LLDB_LOGF(log, "PerformAction got called with an invalid thread.");
}
m_should_stop = true;
m_should_stop_is_valid = true;
return;
}
BreakpointSiteSP bp_site_sp(
thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
std::unordered_set<break_id_t> precondition_breakpoints;
if (bp_site_sp) {
// Let's copy the owners list out of the site and store them in a local
// list. That way if one of the breakpoint actions changes the site,
// then we won't be operating on a bad list.
BreakpointLocationCollection site_locations;
size_t num_owners = bp_site_sp->CopyOwnersList(site_locations);
if (num_owners == 0) {
m_should_stop = true;
} else {
// We go through each location, and test first its precondition -
// this overrides everything. Note, we only do this once per
// breakpoint - not once per location... Then check the condition.
// If the condition says to stop, then we run the callback for that
// location. If that callback says to stop as well, then we set
// m_should_stop to true; we are going to stop. But we still want to
// give all the breakpoints whose conditions say we are going to stop
// a chance to run their callbacks. Of course if any callback
// restarts the target by putting "continue" in the callback, then
// we're going to restart, without running the rest of the callbacks.
// And in this case we will end up not stopping even if another
// location said we should stop. But that's better than not running
// all the callbacks.
// There's one other complication here. We may have run an async
// breakpoint callback that said we should stop. We only want to
// override that if another breakpoint action says we shouldn't
// stop. If nobody else has an opinion, then we should stop if the
// async callback says we should. An example of this is the async
// shared library load notification breakpoint and the setting
// stop-on-sharedlibrary-events.
// We'll keep the async value in async_should_stop, and track whether
// anyone said we should NOT stop in actually_said_continue.
bool async_should_stop = false;
if (m_should_stop_is_valid)
async_should_stop = m_should_stop;
bool actually_said_continue = false;
m_should_stop = false;
// We don't select threads as we go through them testing breakpoint
// conditions and running commands. So we need to set the thread for
// expression evaluation here:
ThreadList::ExpressionExecutionThreadPusher thread_pusher(thread_sp);
ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
Process *process = exe_ctx.GetProcessPtr();
if (process->GetModIDRef().IsLastResumeForUserExpression()) {
// If we are in the middle of evaluating an expression, don't run
// asynchronous breakpoint commands or expressions. That could
// lead to infinite recursion if the command or condition re-calls
// the function with this breakpoint.
// TODO: We can keep a list of the breakpoints we've seen while
// running expressions in the nested
// PerformAction calls that can arise when the action runs a
// function that hits another breakpoint, and only stop running
// commands when we see the same breakpoint hit a second time.
m_should_stop_is_valid = true;
// It is possible that the user has a breakpoint at the same site
// as the completed plan had (e.g. user has a breakpoint
// on a module entry point, and `ThreadPlanCallFunction` ends
// also there). We can't find an internal breakpoint in the loop
// later because it was already removed on the plan completion.
// So check if the plan was completed, and stop if so.
if (thread_sp->CompletedPlanOverridesBreakpoint()) {
m_should_stop = true;
thread_sp->ResetStopInfo();
return;
}
LLDB_LOGF(log, "StopInfoBreakpoint::PerformAction - Hit a "
"breakpoint while running an expression,"
" not running commands to avoid recursion.");
bool ignoring_breakpoints =
process->GetIgnoreBreakpointsInExpressions();
if (ignoring_breakpoints) {
m_should_stop = false;
// Internal breakpoints will always stop.
for (size_t j = 0; j < num_owners; j++) {
lldb::BreakpointLocationSP bp_loc_sp =
bp_site_sp->GetOwnerAtIndex(j);
if (bp_loc_sp->GetBreakpoint().IsInternal()) {
m_should_stop = true;
break;
}
}
} else {
m_should_stop = true;
}
LLDB_LOGF(log,
"StopInfoBreakpoint::PerformAction - in expression, "
"continuing: %s.",
m_should_stop ? "true" : "false");
Debugger::ReportWarning(
"hit breakpoint while running function, skipping commands and "
"conditions to prevent recursion",
process->GetTarget().GetDebugger().GetID());
return;
}
StoppointCallbackContext context(event_ptr, exe_ctx, false);
// For safety's sake let's also grab an extra reference to the
// breakpoint owners of the locations we're going to examine, since
// the locations are going to have to get back to their breakpoints,
// and the locations don't keep their owners alive. I'm just
// sticking the BreakpointSP's in a vector since I'm only using it to
// locally increment their retain counts.
std::vector<lldb::BreakpointSP> location_owners;
for (size_t j = 0; j < num_owners; j++) {
BreakpointLocationSP loc(site_locations.GetByIndex(j));
location_owners.push_back(loc->GetBreakpoint().shared_from_this());
}
for (size_t j = 0; j < num_owners; j++) {
lldb::BreakpointLocationSP bp_loc_sp = site_locations.GetByIndex(j);
StreamString loc_desc;
if (log) {
bp_loc_sp->GetDescription(&loc_desc, eDescriptionLevelBrief);
}
// If another action disabled this breakpoint or its location, then
// don't run the actions.
if (!bp_loc_sp->IsEnabled() ||
!bp_loc_sp->GetBreakpoint().IsEnabled())
continue;
// The breakpoint site may have many locations associated with it,
// not all of them valid for this thread. Skip the ones that
// aren't:
if (!bp_loc_sp->ValidForThisThread(*thread_sp)) {
if (log) {
LLDB_LOGF(log,
"Breakpoint %s hit on thread 0x%llx but it was not "
"for this thread, continuing.",
loc_desc.GetData(),
static_cast<unsigned long long>(thread_sp->GetID()));
}
continue;
}
internal_breakpoint = bp_loc_sp->GetBreakpoint().IsInternal();
// First run the precondition, but since the precondition is per
// breakpoint, only run it once per breakpoint.
std::pair<std::unordered_set<break_id_t>::iterator, bool> result =
precondition_breakpoints.insert(
bp_loc_sp->GetBreakpoint().GetID());
if (!result.second)
continue;
bool precondition_result =
bp_loc_sp->GetBreakpoint().EvaluatePrecondition(context);
if (!precondition_result) {
actually_said_continue = true;
continue;
}
// Next run the condition for the breakpoint. If that says we
// should stop, then we'll run the callback for the breakpoint. If
// the callback says we shouldn't stop that will win.
if (bp_loc_sp->GetConditionText() != nullptr) {
Status condition_error;
bool condition_says_stop =
bp_loc_sp->ConditionSaysStop(exe_ctx, condition_error);
if (!condition_error.Success()) {
const char *err_str =
condition_error.AsCString("<unknown error>");
LLDB_LOGF(log, "Error evaluating condition: \"%s\"\n", err_str);
StreamString strm;
strm << "stopped due to an error evaluating condition of "
"breakpoint ";
bp_loc_sp->GetDescription(&strm, eDescriptionLevelBrief);
strm << ": \"" << bp_loc_sp->GetConditionText() << "\"\n";
strm << err_str;
Debugger::ReportError(
strm.GetString().str(),
exe_ctx.GetTargetRef().GetDebugger().GetID());
} else {
LLDB_LOGF(log,
"Condition evaluated for breakpoint %s on thread "
"0x%llx condition_says_stop: %i.",
loc_desc.GetData(),
static_cast<unsigned long long>(thread_sp->GetID()),
condition_says_stop);
if (!condition_says_stop) {
// We don't want to increment the hit count of breakpoints if
// the condition fails. We've already bumped it by the time
// we get here, so undo the bump:
bp_loc_sp->UndoBumpHitCount();
actually_said_continue = true;
continue;
}
}
}
// We've done all the checks whose failure means "we consider lldb
// not to have hit the breakpoint". Now we're going to check for
// conditions that might continue after hitting. Start with the
// ignore count:
if (!bp_loc_sp->IgnoreCountShouldStop()) {
actually_said_continue = true;
continue;
}
// Check the auto-continue bit on the location, do this before the
// callback since it may change this, but that would be for the
// NEXT hit. Note, you might think you could check auto-continue
// before the condition, and not evaluate the condition if it says
// to continue. But failing the condition means the breakpoint was
// effectively NOT HIT. So these two states are different.
bool auto_continue_says_stop = true;
if (bp_loc_sp->IsAutoContinue())
{
LLDB_LOGF(log,
"Continuing breakpoint %s as AutoContinue was set.",
loc_desc.GetData());
// We want this stop reported, so you will know we auto-continued
// but only for external breakpoints:
if (!internal_breakpoint)
thread_sp->SetShouldReportStop(eVoteYes);
auto_continue_says_stop = false;
}
bool callback_says_stop = true;
// FIXME: For now the callbacks have to run in async mode - the
// first time we restart we need
// to get out of there. So set it here.
// When we figure out how to nest breakpoint hits then this will
// change.
// Don't run async callbacks in PerformAction. They have already
// been taken into account with async_should_stop.
if (!bp_loc_sp->IsCallbackSynchronous()) {
Debugger &debugger = thread_sp->CalculateTarget()->GetDebugger();
bool old_async = debugger.GetAsyncExecution();
debugger.SetAsyncExecution(true);
callback_says_stop = bp_loc_sp->InvokeCallback(&context);
debugger.SetAsyncExecution(old_async);
if (callback_says_stop && auto_continue_says_stop)
m_should_stop = true;
else
actually_said_continue = true;
}
// If we are going to stop for this breakpoint, then remove the
// breakpoint.
if (callback_says_stop && bp_loc_sp &&
bp_loc_sp->GetBreakpoint().IsOneShot()) {
thread_sp->GetProcess()->GetTarget().RemoveBreakpointByID(
bp_loc_sp->GetBreakpoint().GetID());
}
// Also make sure that the callback hasn't continued the target. If
// it did, when we'll set m_should_start to false and get out of
// here.
if (HasTargetRunSinceMe()) {
m_should_stop = false;
actually_said_continue = true;
break;
}
}
// At this point if nobody actually told us to continue, we should
// give the async breakpoint callback a chance to weigh in:
if (!actually_said_continue && !m_should_stop) {
m_should_stop = async_should_stop;
}
}
// We've figured out what this stop wants to do, so mark it as valid so
// we don't compute it again.
m_should_stop_is_valid = true;
} else {
m_should_stop = true;
m_should_stop_is_valid = true;
Log *log_process(GetLog(LLDBLog::Process));
LLDB_LOGF(log_process,
"Process::%s could not find breakpoint site id: %" PRId64
"...",
__FUNCTION__, m_value);
}
if ((!m_should_stop || internal_breakpoint) &&
thread_sp->CompletedPlanOverridesBreakpoint()) {
// Override should_stop decision when we have completed step plan
// additionally to the breakpoint
m_should_stop = true;
// We know we're stopping for a completed plan and we don't want to
// show the breakpoint stop, so compute the public stop info immediately
// here.
thread_sp->CalculatePublicStopInfo();
}
LLDB_LOGF(log,
"Process::%s returning from action with m_should_stop: %d.",
__FUNCTION__, m_should_stop);
}
}
private:
bool m_should_stop;
bool m_should_stop_is_valid;
bool m_should_perform_action; // Since we are trying to preserve the "state"
// of the system even if we run functions
// etc. behind the users backs, we need to make sure we only REALLY perform
// the action once.
lldb::addr_t m_address; // We use this to capture the breakpoint site address
// when we create the StopInfo,
// in case somebody deletes it between the time the StopInfo is made and the
// description is asked for.
lldb::break_id_t m_break_id;
bool m_was_one_shot;
};
// StopInfoWatchpoint
class StopInfoWatchpoint : public StopInfo {
public:
// Make sure watchpoint is properly disabled and subsequently enabled while
// performing watchpoint actions.
class WatchpointSentry {
public:
WatchpointSentry(ProcessSP p_sp, WatchpointSP w_sp) : process_sp(p_sp),
watchpoint_sp(w_sp) {
if (process_sp && watchpoint_sp) {
const bool notify = false;
watchpoint_sp->TurnOnEphemeralMode();
process_sp->DisableWatchpoint(watchpoint_sp.get(), notify);
process_sp->AddPreResumeAction(SentryPreResumeAction, this);
}
}
void DoReenable() {
if (process_sp && watchpoint_sp) {
bool was_disabled = watchpoint_sp->IsDisabledDuringEphemeralMode();
watchpoint_sp->TurnOffEphemeralMode();
const bool notify = false;
if (was_disabled) {
process_sp->DisableWatchpoint(watchpoint_sp.get(), notify);
} else {
process_sp->EnableWatchpoint(watchpoint_sp.get(), notify);
}
}
}
~WatchpointSentry() {
DoReenable();
if (process_sp)
process_sp->ClearPreResumeAction(SentryPreResumeAction, this);
}
static bool SentryPreResumeAction(void *sentry_void) {
WatchpointSentry *sentry = (WatchpointSentry *) sentry_void;
sentry->DoReenable();
return true;
}
private:
ProcessSP process_sp;
WatchpointSP watchpoint_sp;
};
StopInfoWatchpoint(Thread &thread, break_id_t watch_id,
lldb::addr_t watch_hit_addr)
: StopInfo(thread, watch_id), m_watch_hit_addr(watch_hit_addr) {}
~StopInfoWatchpoint() override = default;
StopReason GetStopReason() const override { return eStopReasonWatchpoint; }
const char *GetDescription() override {
if (m_description.empty()) {
StreamString strm;
strm.Printf("watchpoint %" PRIi64, m_value);
m_description = std::string(strm.GetString());
}
return m_description.c_str();
}
protected:
bool ShouldStopSynchronous(Event *event_ptr) override {
// ShouldStop() method is idempotent and should not affect hit count. See
// Process::RunPrivateStateThread()->Process()->HandlePrivateEvent()
// -->Process()::ShouldBroadcastEvent()->ThreadList::ShouldStop()->
// Thread::ShouldStop()->ThreadPlanBase::ShouldStop()->
// StopInfoWatchpoint::ShouldStop() and
// Event::DoOnRemoval()->Process::ProcessEventData::DoOnRemoval()->
// StopInfoWatchpoint::PerformAction().
if (m_should_stop_is_valid)
return m_should_stop;
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp) {
WatchpointSP wp_sp(
thread_sp->CalculateTarget()->GetWatchpointList().FindByID(
GetValue()));
if (wp_sp) {
// Check if we should stop at a watchpoint.
ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
StoppointCallbackContext context(event_ptr, exe_ctx, true);
m_should_stop = wp_sp->ShouldStop(&context);
} else {
Log *log = GetLog(LLDBLog::Process);
LLDB_LOGF(log,
"Process::%s could not find watchpoint location id: %" PRId64
"...",
__FUNCTION__, GetValue());
m_should_stop = true;
}
}
m_should_stop_is_valid = true;
return m_should_stop;
}
bool ShouldStop(Event *event_ptr) override {
// This just reports the work done by PerformAction or the synchronous
// stop. It should only ever get called after they have had a chance to
// run.
assert(m_should_stop_is_valid);
return m_should_stop;
}
void PerformAction(Event *event_ptr) override {
Log *log = GetLog(LLDBLog::Watchpoints);
// We're going to calculate if we should stop or not in some way during the
// course of this code. Also by default we're going to stop, so set that
// here.
m_should_stop = true;
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp) {
WatchpointSP wp_sp(
thread_sp->CalculateTarget()->GetWatchpointList().FindByID(
GetValue()));
if (wp_sp) {
ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
ProcessSP process_sp = exe_ctx.GetProcessSP();
{
// check if this process is running on an architecture where
// watchpoints trigger before the associated instruction runs. if so,
// disable the WP, single-step and then re-enable the watchpoint
if (process_sp) {
uint32_t num;
bool wp_triggers_after;
if (process_sp->GetWatchpointSupportInfo(num, wp_triggers_after)
.Success()) {
if (!wp_triggers_after) {
// We need to preserve the watch_index before watchpoint is
// disable. Since Watchpoint::SetEnabled will clear the watch
// index. This will fix TestWatchpointIter failure
Watchpoint *wp = wp_sp.get();
uint32_t watch_index = wp->GetHardwareIndex();
process_sp->DisableWatchpoint(wp, false);
StopInfoSP stored_stop_info_sp = thread_sp->GetStopInfo();
assert(stored_stop_info_sp.get() == this);
Status new_plan_status;
ThreadPlanSP new_plan_sp(
thread_sp->QueueThreadPlanForStepSingleInstruction(
false, // step-over
false, // abort_other_plans
true, // stop_other_threads
new_plan_status));
if (new_plan_sp && new_plan_status.Success()) {
new_plan_sp->SetIsControllingPlan(true);
new_plan_sp->SetOkayToDiscard(false);
new_plan_sp->SetPrivate(true);
}
process_sp->GetThreadList().SetSelectedThreadByID(
thread_sp->GetID());
process_sp->ResumeSynchronous(nullptr);
process_sp->GetThreadList().SetSelectedThreadByID(
thread_sp->GetID());
thread_sp->SetStopInfo(stored_stop_info_sp);
process_sp->EnableWatchpoint(wp, false);
wp->SetHardwareIndex(watch_index);
}
}
}
}
// This sentry object makes sure the current watchpoint is disabled
// while performing watchpoint actions, and it is then enabled after we
// are finished.
WatchpointSentry sentry(process_sp, wp_sp);
/*
* MIPS: Last 3bits of the watchpoint address are masked by the kernel.
* For example:
* 'n' is at 0x120010d00 and 'm' is 0x120010d04. When a watchpoint is
* set at 'm', then
* watch exception is generated even when 'n' is read/written. To handle
* this case,
* server emulates the instruction at PC and finds the base address of
* the load/store
* instruction and appends it in the description of the stop-info
* packet. If watchpoint
* is not set on this address by user then this do not stop.
*/
if (m_watch_hit_addr != LLDB_INVALID_ADDRESS) {
WatchpointSP wp_hit_sp =
thread_sp->CalculateTarget()->GetWatchpointList().FindByAddress(
m_watch_hit_addr);
if (!wp_hit_sp) {
m_should_stop = false;
wp_sp->IncrementFalseAlarmsAndReviseHitCount();
}
}
// TODO: This condition should be checked in the synchronous part of the
// watchpoint code
// (Watchpoint::ShouldStop), so that we avoid pulling an event even if
// the watchpoint fails the ignore count condition. It is moved here
// temporarily, because for archs with
// watchpoint_exceptions_received=before, the code in the previous
// lines takes care of moving the inferior to next PC. We have to check
// the ignore count condition after this is done, otherwise we will hit
// same watchpoint multiple times until we pass ignore condition, but
// we won't actually be ignoring them.
if (wp_sp->GetHitCount() <= wp_sp->GetIgnoreCount())
m_should_stop = false;
Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger();
if (m_should_stop && wp_sp->GetConditionText() != nullptr) {
// We need to make sure the user sees any parse errors in their
// condition, so we'll hook the constructor errors up to the
// debugger's Async I/O.
ExpressionResults result_code;
EvaluateExpressionOptions expr_options;
expr_options.SetUnwindOnError(true);
expr_options.SetIgnoreBreakpoints(true);
ValueObjectSP result_value_sp;
Status error;
result_code = UserExpression::Evaluate(
exe_ctx, expr_options, wp_sp->GetConditionText(),
llvm::StringRef(), result_value_sp, error);
if (result_code == eExpressionCompleted) {
if (result_value_sp) {
Scalar scalar_value;
if (result_value_sp->ResolveValue(scalar_value)) {
if (scalar_value.ULongLong(1) == 0) {
// We have been vetoed. This takes precedence over querying
// the watchpoint whether it should stop (aka ignore count
// and friends). See also StopInfoWatchpoint::ShouldStop()
// as well as Process::ProcessEventData::DoOnRemoval().
m_should_stop = false;
} else
m_should_stop = true;
LLDB_LOGF(log,
"Condition successfully evaluated, result is %s.\n",
m_should_stop ? "true" : "false");
} else {
m_should_stop = true;
LLDB_LOGF(
log,
"Failed to get an integer result from the expression.");
}
}
} else {
const char *err_str = error.AsCString("<unknown error>");
LLDB_LOGF(log, "Error evaluating condition: \"%s\"\n", err_str);
StreamString strm;
strm << "stopped due to an error evaluating condition of "
"watchpoint ";
wp_sp->GetDescription(&strm, eDescriptionLevelBrief);
strm << ": \"" << wp_sp->GetConditionText() << "\"\n";
strm << err_str;
Debugger::ReportError(strm.GetString().str(),
exe_ctx.GetTargetRef().GetDebugger().GetID());
}
}
// If the condition says to stop, we run the callback to further decide
// whether to stop.
if (m_should_stop) {
// FIXME: For now the callbacks have to run in async mode - the
// first time we restart we need
// to get out of there. So set it here.
// When we figure out how to nest watchpoint hits then this will
// change.
bool old_async = debugger.GetAsyncExecution();
debugger.SetAsyncExecution(true);
StoppointCallbackContext context(event_ptr, exe_ctx, false);
bool stop_requested = wp_sp->InvokeCallback(&context);
debugger.SetAsyncExecution(old_async);
// Also make sure that the callback hasn't continued the target. If
// it did, when we'll set m_should_stop to false and get out of here.
if (HasTargetRunSinceMe())
m_should_stop = false;
if (m_should_stop && !stop_requested) {
// We have been vetoed by the callback mechanism.
m_should_stop = false;
}
}
// Finally, if we are going to stop, print out the new & old values:
if (m_should_stop) {
wp_sp->CaptureWatchedValue(exe_ctx);
Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger();
StreamSP output_sp = debugger.GetAsyncOutputStream();
wp_sp->DumpSnapshots(output_sp.get());
output_sp->EOL();
output_sp->Flush();
}
} else {
Log *log_process(GetLog(LLDBLog::Process));
LLDB_LOGF(log_process,
"Process::%s could not find watchpoint id: %" PRId64 "...",
__FUNCTION__, m_value);
}
LLDB_LOGF(log,
"Process::%s returning from action with m_should_stop: %d.",
__FUNCTION__, m_should_stop);
m_should_stop_is_valid = true;
}
}
private:
bool m_should_stop = false;
bool m_should_stop_is_valid = false;
lldb::addr_t m_watch_hit_addr;
};
// StopInfoUnixSignal
class StopInfoUnixSignal : public StopInfo {
public:
StopInfoUnixSignal(Thread &thread, int signo, const char *description)
: StopInfo(thread, signo) {
SetDescription(description);
}
~StopInfoUnixSignal() override = default;
StopReason GetStopReason() const override { return eStopReasonSignal; }
bool ShouldStopSynchronous(Event *event_ptr) override {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp)
return thread_sp->GetProcess()->GetUnixSignals()->GetShouldStop(m_value);
return false;
}
bool ShouldStop(Event *event_ptr) override {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp)
return thread_sp->GetProcess()->GetUnixSignals()->GetShouldStop(m_value);
return false;
}
// If should stop returns false, check if we should notify of this event
bool DoShouldNotify(Event *event_ptr) override {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp) {
bool should_notify =
thread_sp->GetProcess()->GetUnixSignals()->GetShouldNotify(m_value);
if (should_notify) {
StreamString strm;
strm.Printf(
"thread %d received signal: %s", thread_sp->GetIndexID(),
thread_sp->GetProcess()->GetUnixSignals()->GetSignalAsCString(
m_value));
Process::ProcessEventData::AddRestartedReason(event_ptr,
strm.GetData());
}
return should_notify;
}
return true;
}
void WillResume(lldb::StateType resume_state) override {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp) {
if (!thread_sp->GetProcess()->GetUnixSignals()->GetShouldSuppress(
m_value))
thread_sp->SetResumeSignal(m_value);
}
}
const char *GetDescription() override {
if (m_description.empty()) {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp) {
StreamString strm;
const char *signal_name =
thread_sp->GetProcess()->GetUnixSignals()->GetSignalAsCString(
m_value);
if (signal_name)
strm.Printf("signal %s", signal_name);
else
strm.Printf("signal %" PRIi64, m_value);
m_description = std::string(strm.GetString());
}
}
return m_description.c_str();
}
};
// StopInfoTrace
class StopInfoTrace : public StopInfo {
public:
StopInfoTrace(Thread &thread) : StopInfo(thread, LLDB_INVALID_UID) {}
~StopInfoTrace() override = default;
StopReason GetStopReason() const override { return eStopReasonTrace; }
const char *GetDescription() override {
if (m_description.empty())
return "trace";
else
return m_description.c_str();
}
};
// StopInfoException
class StopInfoException : public StopInfo {
public:
StopInfoException(Thread &thread, const char *description)
: StopInfo(thread, LLDB_INVALID_UID) {
if (description)
SetDescription(description);
}
~StopInfoException() override = default;
StopReason GetStopReason() const override { return eStopReasonException; }
const char *GetDescription() override {
if (m_description.empty())
return "exception";
else
return m_description.c_str();
}
};
// StopInfoProcessorTrace
class StopInfoProcessorTrace : public StopInfo {
public:
StopInfoProcessorTrace(Thread &thread, const char *description)
: StopInfo(thread, LLDB_INVALID_UID) {
if (description)
SetDescription(description);
}
~StopInfoProcessorTrace() override = default;
StopReason GetStopReason() const override {
return eStopReasonProcessorTrace;
}
const char *GetDescription() override {
if (m_description.empty())
return "processor trace event";
else
return m_description.c_str();
}
};
// StopInfoThreadPlan
class StopInfoThreadPlan : public StopInfo {
public:
StopInfoThreadPlan(ThreadPlanSP &plan_sp, ValueObjectSP &return_valobj_sp,
ExpressionVariableSP &expression_variable_sp,
bool return_is_swift_error_value)
: StopInfo(plan_sp->GetThread(), LLDB_INVALID_UID), m_plan_sp(plan_sp),
m_return_valobj_sp(return_valobj_sp),
m_expression_variable_sp(expression_variable_sp),
m_return_value_is_swift_error_value(return_is_swift_error_value) {}
~StopInfoThreadPlan() override = default;
StopReason GetStopReason() const override { return eStopReasonPlanComplete; }
const char *GetDescription() override {
if (m_description.empty()) {
StreamString strm;
m_plan_sp->GetDescription(&strm, eDescriptionLevelBrief);
m_description = std::string(strm.GetString());
}
return m_description.c_str();
}
ValueObjectSP GetReturnValueObject(bool &is_swift_error_result) {
is_swift_error_result = m_return_value_is_swift_error_value;
return m_return_valobj_sp;
}
ExpressionVariableSP GetExpressionVariable() {
return m_expression_variable_sp;
}
protected:
bool ShouldStop(Event *event_ptr) override {
if (m_plan_sp)
return m_plan_sp->ShouldStop(event_ptr);
else
return StopInfo::ShouldStop(event_ptr);
}
private:
ThreadPlanSP m_plan_sp;
ValueObjectSP m_return_valobj_sp;
ExpressionVariableSP m_expression_variable_sp;
bool m_return_value_is_swift_error_value;
};
// StopInfoExec
class StopInfoExec : public StopInfo {
public:
StopInfoExec(Thread &thread) : StopInfo(thread, LLDB_INVALID_UID) {}
~StopInfoExec() override = default;
bool ShouldStop(Event *event_ptr) override {
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp)
return thread_sp->GetProcess()->GetStopOnExec();
return false;
}
StopReason GetStopReason() const override { return eStopReasonExec; }
const char *GetDescription() override { return "exec"; }
protected:
void PerformAction(Event *event_ptr) override {
// Only perform the action once
if (m_performed_action)
return;
m_performed_action = true;
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp)
thread_sp->GetProcess()->DidExec();
}
bool m_performed_action = false;
};
// StopInfoFork
class StopInfoFork : public StopInfo {
public:
StopInfoFork(Thread &thread, lldb::pid_t child_pid, lldb::tid_t child_tid)
: StopInfo(thread, child_pid), m_child_pid(child_pid),
m_child_tid(child_tid) {}
~StopInfoFork() override = default;
bool ShouldStop(Event *event_ptr) override { return false; }
StopReason GetStopReason() const override { return eStopReasonFork; }
const char *GetDescription() override { return "fork"; }
protected:
void PerformAction(Event *event_ptr) override {
// Only perform the action once
if (m_performed_action)
return;
m_performed_action = true;
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp)
thread_sp->GetProcess()->DidFork(m_child_pid, m_child_tid);
}
bool m_performed_action = false;
private:
lldb::pid_t m_child_pid;
lldb::tid_t m_child_tid;
};
// StopInfoVFork
class StopInfoVFork : public StopInfo {
public:
StopInfoVFork(Thread &thread, lldb::pid_t child_pid, lldb::tid_t child_tid)
: StopInfo(thread, child_pid), m_child_pid(child_pid),
m_child_tid(child_tid) {}
~StopInfoVFork() override = default;
bool ShouldStop(Event *event_ptr) override { return false; }
StopReason GetStopReason() const override { return eStopReasonVFork; }
const char *GetDescription() override { return "vfork"; }
protected:
void PerformAction(Event *event_ptr) override {
// Only perform the action once
if (m_performed_action)
return;
m_performed_action = true;
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp)
thread_sp->GetProcess()->DidVFork(m_child_pid, m_child_tid);
}
bool m_performed_action = false;
private:
lldb::pid_t m_child_pid;
lldb::tid_t m_child_tid;
};
// StopInfoVForkDone
class StopInfoVForkDone : public StopInfo {
public:
StopInfoVForkDone(Thread &thread) : StopInfo(thread, 0) {}
~StopInfoVForkDone() override = default;
bool ShouldStop(Event *event_ptr) override { return false; }
StopReason GetStopReason() const override { return eStopReasonVForkDone; }
const char *GetDescription() override { return "vforkdone"; }
protected:
void PerformAction(Event *event_ptr) override {
// Only perform the action once
if (m_performed_action)
return;
m_performed_action = true;
ThreadSP thread_sp(m_thread_wp.lock());
if (thread_sp)
thread_sp->GetProcess()->DidVForkDone();
}
bool m_performed_action = false;
};
} // namespace lldb_private
StopInfoSP StopInfo::CreateStopReasonWithBreakpointSiteID(Thread &thread,
break_id_t break_id) {
return StopInfoSP(new StopInfoBreakpoint(thread, break_id));
}
StopInfoSP StopInfo::CreateStopReasonWithBreakpointSiteID(Thread &thread,
break_id_t break_id,
bool should_stop) {
return StopInfoSP(new StopInfoBreakpoint(thread, break_id, should_stop));
}
StopInfoSP
StopInfo::CreateStopReasonWithWatchpointID(Thread &thread, break_id_t watch_id,
lldb::addr_t watch_hit_addr) {
return StopInfoSP(new StopInfoWatchpoint(thread, watch_id, watch_hit_addr));
}
StopInfoSP StopInfo::CreateStopReasonWithSignal(Thread &thread, int signo,
const char *description) {
thread.GetProcess()->GetUnixSignals()->IncrementSignalHitCount(signo);
return StopInfoSP(new StopInfoUnixSignal(thread, signo, description));
}
StopInfoSP StopInfo::CreateStopReasonToTrace(Thread &thread) {
return StopInfoSP(new StopInfoTrace(thread));
}
StopInfoSP
StopInfo::CreateStopReasonWithPlan(ThreadPlanSP &plan_sp,
ValueObjectSP return_valobj_sp,
ExpressionVariableSP expression_variable_sp,
bool return_is_swift_error_value) {
return StopInfoSP(new StopInfoThreadPlan(plan_sp, return_valobj_sp,
expression_variable_sp,
return_is_swift_error_value));
}
StopInfoSP StopInfo::CreateStopReasonWithException(Thread &thread,
const char *description) {
return StopInfoSP(new StopInfoException(thread, description));
}
StopInfoSP StopInfo::CreateStopReasonProcessorTrace(Thread &thread,
const char *description) {
return StopInfoSP(new StopInfoProcessorTrace(thread, description));
}
StopInfoSP StopInfo::CreateStopReasonWithExec(Thread &thread) {
return StopInfoSP(new StopInfoExec(thread));
}
StopInfoSP StopInfo::CreateStopReasonFork(Thread &thread,
lldb::pid_t child_pid,
lldb::tid_t child_tid) {
return StopInfoSP(new StopInfoFork(thread, child_pid, child_tid));
}
StopInfoSP StopInfo::CreateStopReasonVFork(Thread &thread,
lldb::pid_t child_pid,
lldb::tid_t child_tid) {
return StopInfoSP(new StopInfoVFork(thread, child_pid, child_tid));
}
StopInfoSP StopInfo::CreateStopReasonVForkDone(Thread &thread) {
return StopInfoSP(new StopInfoVForkDone(thread));
}
ValueObjectSP StopInfo::GetReturnValueObject(StopInfoSP &stop_info_sp,
bool &is_swift_error_result) {
if (stop_info_sp &&
stop_info_sp->GetStopReason() == eStopReasonPlanComplete) {
StopInfoThreadPlan *plan_stop_info =
static_cast<StopInfoThreadPlan *>(stop_info_sp.get());
return plan_stop_info->GetReturnValueObject(is_swift_error_result);
} else
return ValueObjectSP();
}
ExpressionVariableSP StopInfo::GetExpressionVariable(StopInfoSP &stop_info_sp) {
if (stop_info_sp &&
stop_info_sp->GetStopReason() == eStopReasonPlanComplete) {
StopInfoThreadPlan *plan_stop_info =
static_cast<StopInfoThreadPlan *>(stop_info_sp.get());
return plan_stop_info->GetExpressionVariable();
} else
return ExpressionVariableSP();
}
lldb::ValueObjectSP
StopInfo::GetCrashingDereference(StopInfoSP &stop_info_sp,
lldb::addr_t *crashing_address) {
if (!stop_info_sp) {
return ValueObjectSP();
}
const char *description = stop_info_sp->GetDescription();
if (!description) {
return ValueObjectSP();
}
ThreadSP thread_sp = stop_info_sp->GetThread();
if (!thread_sp) {
return ValueObjectSP();
}
StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
if (!frame_sp) {
return ValueObjectSP();
}
const char address_string[] = "address=";
const char *address_loc = strstr(description, address_string);
if (!address_loc) {
return ValueObjectSP();
}
address_loc += (sizeof(address_string) - 1);
uint64_t address = strtoull(address_loc, nullptr, 0);
if (crashing_address) {
*crashing_address = address;
}
return frame_sp->GuessValueForAddress(address);
}
|
/* Starshatter OpenSource Distribution
Copyright (c) 1997-2004, Destroyer Studios LLC.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* 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 "Destroyer Studios" 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.
SUBSYSTEM: Stars.exe
FILE: Player.cpp
AUTHOR: John DiCamillo
OVERVIEW
========
Player / Logbook class
*/
#include "MemDebug.h"
#include "Player.h"
#include "NetLobbyServer.h"
#include "NetLayer.h"
#include "Ship.h"
#include "SimEvent.h"
#include "Campaign.h"
#include "CampaignSaveGame.h"
#include "Random.h"
#include "HUDView.h"
#include "MFD.h"
#include "DataLoader.h"
#include "Encrypt.h"
#include "ParseUtil.h"
#include "FormatUtil.h"
#include "Bitmap.h"
#include "Game.h"
// +-------------------------------------------------------------------+
class AwardInfo
{
public:
static const char* TYPENAME() { return "AwardInfo"; }
AwardInfo() :
type(RANK),
id(0),
large_insignia(0),
small_insignia(0),
granted_ship_classes(0x7),
total_points(0),
mission_points(0),
total_missions(0),
kills(0),
lost(0),
collision(0),
campaign_id(0),
campaign_complete(false),
dynamic_campaign(false),
ceremony(true),
required_awards(0),
lottery(0),
min_rank(0),
max_rank((int) 1e9),
min_ship_class(0),
max_ship_class((int) 1e9)
{ }
~AwardInfo() { }
enum TYPE { RANK, MEDAL };
int type;
int id;
Text name;
Text abrv;
Text desc;
Text grant;
Text desc_sound;
Text grant_sound;
Bitmap* large_insignia;
Bitmap* small_insignia;
int granted_ship_classes;
int total_points;
int mission_points;
int total_missions;
int kills;
int lost;
int collision;
int campaign_id;
bool campaign_complete;
bool dynamic_campaign;
bool ceremony;
int required_awards;
int lottery;
int min_rank;
int max_rank;
int min_ship_class;
int max_ship_class;
};
static List<AwardInfo> rank_table;
static List<AwardInfo> medal_table;
static bool config_exists = false;
// +-------------------------------------------------------------------+
Player::Player(const char* n)
: uid(0), name(n), create_date(0), points(0), medals(0), flight_time(0),
missions(0), kills(0), losses(0), campaigns(0), trained(0),
flight_model(0), flying_start(0), landing_model(0),
ai_level(1), hud_mode(0), hud_color(1),
ff_level(4), grid(1), gunsight(0), award(0)
{
name.setSensitive(false);
mfd[0] = -1;
mfd[1] = -1;
mfd[2] = -1;
mfd[3] = -1;
}
Player::Player()
: uid(0), create_date(0), points(0), medals(0), flight_time(0),
missions(0), kills(0), losses(0), campaigns(0), trained(0),
flight_model(0), flying_start(0), landing_model(0),
ai_level(1), hud_mode(0), hud_color(1),
ff_level(4), grid(1), gunsight(0), award(0)
{
name.setSensitive(false);
mfd[0] = -1;
mfd[1] = -1;
mfd[2] = -1;
mfd[3] = -1;
}
Player::~Player()
{ }
// +-------------------------------------------------------------------+
void
Player::SetName(const char* n)
{
if (n && *n)
name = n;
}
void
Player::SetPassword(const char* p)
{
if (p && *p) {
pass = p;
if (pass.length() > 16)
pass = pass.substring(0, 16);
}
}
void
Player::SetSquadron(const char* s)
{
if (s && *s)
squadron = s;
}
void
Player::SetSignature(const char* s)
{
if (s && *s)
signature = s;
}
const Text&
Player::ChatMacro(int n) const
{
if (n >= 0 && n < 10)
return chat_macros[n];
return chat_macros[0];
}
void
Player::SetChatMacro(int n, const char* m)
{
if (n >= 0 && n < 10 && m && *m)
chat_macros[n] = m;
}
void
Player::SetPoints(int p)
{
if (p >= 0)
points = p;
}
void
Player::SetMedals(int m)
{
medals = m;
}
void
Player::SetCampaigns(int n)
{
campaigns = n;
}
void
Player::SetTrained(int n)
{
if (n == 0)
trained = 0;
else if (n > 0 && n <= 20)
trained = trained | (1 << (n-1));
else if (n > 20)
trained = n;
}
bool
Player::HasTrained(int n) const
{
if (n > 0 && n <= 20)
return (trained & (1 << (n-1))) ? true : false;
return false;
}
bool
Player::HasCompletedCampaign(int id) const
{
if (id > 0 && id < 30)
return (campaigns & (1 << id)) ? true : false;
return false;
}
void
Player::SetCampaignComplete(int id)
{
if (id > 0 && id < 30) {
campaigns = campaigns | (1 << id);
Save();
}
}
void
Player::SetCreateDate(int d)
{
if (d >= 0)
create_date = d;
}
void
Player::SetFlightTime(int t)
{
if (t >= 0)
flight_time = t;
}
void
Player::SetMissions(int m)
{
if (m >= 0)
missions = m;
}
void
Player::SetKills(int k)
{
if (k >= 0)
kills = k;
}
void
Player::SetLosses(int l)
{
if (l >= 0)
losses = l;
}
// +-------------------------------------------------------------------+
void
Player::AddFlightTime(int t)
{
if (t > 0)
flight_time += t;
}
void
Player::AddPoints(int p)
{
if (p > 0)
points += p;
}
void
Player::AddMissions(int m)
{
if (m > 0)
missions += m;
}
void
Player::AddKills(int k)
{
if (k > 0)
kills += k;
}
void
Player::AddLosses(int l)
{
if (l > 0)
losses += l;
}
// +-------------------------------------------------------------------+
void
Player::SetFlightModel(int n)
{
if (n >= Ship::FM_STANDARD && n <= Ship::FM_ARCADE) {
flight_model = n;
Ship::SetFlightModel(n);
}
}
void
Player::SetFlyingStart(int n)
{
flying_start = n;
}
void
Player::SetLandingModel(int n)
{
if (n >= Ship::LM_STANDARD && n <= Ship::LM_EASIER) {
landing_model = n;
Ship::SetLandingModel(landing_model);
}
}
void
Player::SetAILevel(int n)
{
ai_level = n;
}
void
Player::SetHUDMode(int n)
{
hud_mode = n;
HUDView::SetArcade(n > 0);
}
void
Player::SetHUDColor(int n)
{
hud_color = n;
HUDView::SetDefaultColorSet(n);
}
void
Player::SetFriendlyFire(int n)
{
if (n >= 0 && n <= 4) {
ff_level = n;
Ship::SetFriendlyFireLevel(n/4.0);
}
}
void
Player::SetGridMode(int n)
{
if (n >= 0 && n <= 1) {
grid = n;
}
}
void
Player::SetGunsight(int n)
{
if (n >= 0 && n <= 1) {
gunsight = n;
}
}
void
Player::ClearShowAward()
{
award = 0;
}
Text
Player::AwardName() const
{
if (award)
return award->name;
return Text();
}
Text
Player::AwardDesc() const
{
if (award)
return award->grant;
return Text();
}
Bitmap*
Player::AwardImage() const
{
if (award)
return award->large_insignia;
return 0;
}
Sound*
Player::AwardSound() const
{
if (award && award->grant_sound.length()) {
DataLoader* loader = DataLoader::GetLoader();
Sound* result = 0;
loader->LoadSound(award->grant_sound, result);
return result;
}
return 0;
}
// +-------------------------------------------------------------------+
const char*
Player::RankName(int rank)
{
ListIter<AwardInfo> iter = rank_table;
while (++iter) {
AwardInfo* award = iter.value();
if (award->id == rank)
return award->name;
}
return "Conscript";
}
const char*
Player::RankAbrv(int rank)
{
ListIter<AwardInfo> iter = rank_table;
while (++iter) {
AwardInfo* award = iter.value();
if (award->id == rank)
return award->abrv;
}
return "";
}
Bitmap*
Player::RankInsignia(int rank, int size)
{
ListIter<AwardInfo> iter = rank_table;
while (++iter) {
AwardInfo* award = iter.value();
if (award->id == rank) {
if (size == 0)
return award->small_insignia;
if (size == 1)
return award->large_insignia;
}
}
return 0;
}
const char*
Player::RankDescription(int rank)
{
ListIter<AwardInfo> iter = rank_table;
while (++iter) {
AwardInfo* award = iter.value();
if (award->id == rank)
return award->desc;
}
return "";
}
int
Player::RankFromName(const char* name)
{
ListIter<AwardInfo> iter = rank_table;
while (++iter) {
AwardInfo* award = iter.value();
if (award->name == name)
return award->id;
}
return 0;
}
int
Player::Rank() const
{
for (int i = rank_table.size()-1; i >= 0; i--) {
AwardInfo* award = rank_table[i];
if (points >= award->total_points)
return award->id;
}
return 0;
}
void
Player::SetRank(int r)
{
ListIter<AwardInfo> iter = rank_table;
while (++iter) {
AwardInfo* award = iter.value();
if (r == award->id)
points = award->total_points;
}
}
int
Player::Medal(int n) const
{
if (n < 0)
return 0;
for (int i = 0; i < 16; i++) {
int selector = 1 << (15-i);
// found a medal:
if (medals & selector) {
// and it's the nth medal!
if (n == 0) {
return selector;
}
n--;
}
}
return 0;
}
// +-------------------------------------------------------------------+
const char*
Player::MedalName(int medal)
{
ListIter<AwardInfo> iter = medal_table;
while (++iter) {
AwardInfo* award = iter.value();
if (award->id == medal)
return award->name;
}
return "";
}
Bitmap*
Player::MedalInsignia(int medal, int size)
{
ListIter<AwardInfo> iter = medal_table;
while (++iter) {
AwardInfo* award = iter.value();
if (award->id == medal) {
if (size == 0)
return award->small_insignia;
if (size == 1)
return award->large_insignia;
}
}
return 0;
}
const char*
Player::MedalDescription(int medal)
{
ListIter<AwardInfo> iter = medal_table;
while (++iter) {
AwardInfo* award = iter.value();
if (award->id == medal)
return award->desc;
}
return "";
}
// +-------------------------------------------------------------------+
bool
Player::CanCommand(int ship_class)
{
if (ship_class <= Ship::ATTACK)
return true;
for (int i = rank_table.size()-1; i >= 0; i--) {
AwardInfo* award = rank_table[i];
if (points > award->total_points) {
return (ship_class & award->granted_ship_classes) != 0;
}
}
return false;
}
int
Player::CommandRankRequired(int ship_class)
{
for (int i = 0; i < rank_table.size(); i++) {
AwardInfo* award = rank_table[i];
if ((ship_class & award->granted_ship_classes) != 0) {
return i;
}
}
return rank_table.size()-1;
}
// +-------------------------------------------------------------------+
int
Player::GetMissionPoints(ShipStats* s, DWORD start_time)
{
int result = 0;
if (s) {
result = s->GetPoints();
int flight_time = (Game::GameTime() - start_time) / 1000;
// if player survived mission, award one experience point
// for each minute of action, in ten point blocks:
if (!s->GetDeaths() && !s->GetColls()) {
int minutes = flight_time / 60;
minutes /= 10;
minutes *= 10;
result += minutes;
if (s->HasEvent(SimEvent::DOCK))
result += 100;
}
else {
result -= (int) (2.5 * Ship::Value(s->GetShipClass()));
}
if (result < 0)
result = 0;
}
return result;
}
// +-------------------------------------------------------------------+
void
Player::ProcessStats(ShipStats* s, DWORD start_time)
{
if (!s) return;
int old_rank = Rank();
int pts = GetMissionPoints(s, start_time);
AddPoints(pts);
AddPoints(s->GetCommandPoints());
AddKills(s->GetGunKills());
AddKills(s->GetMissileKills());
AddLosses(s->GetDeaths());
AddLosses(s->GetColls());
AddMissions(1);
AddFlightTime((Game::GameTime() - start_time) / 1000);
int rank = Rank();
// did the player earn a promotion?
if (old_rank != rank) {
ListIter<AwardInfo> iter = rank_table;
while (++iter) {
AwardInfo* a = iter.value();
if (rank == a->id) {
award = a;
}
}
}
// if not, did the player earn a medal?
else {
ListIter<AwardInfo> iter = medal_table;
while (++iter) {
AwardInfo* a = iter.value();
if (EarnedAward(a, s) && a->ceremony) {
award = a;
break;
}
}
}
// persist all stats, promotions, and medals:
Save();
}
bool
Player::EarnedAward(AwardInfo* a, ShipStats* s)
{
if (!a || !s)
return false;
// already earned this medal?
if (a->id & medals)
return false;
// eligible for this medal?
int rank = Rank();
if (a->min_rank > rank || a->max_rank < rank)
return false;
if ((a->required_awards & medals) < a->required_awards)
return false;
if (a->min_ship_class > s->GetShipClass() || a->max_ship_class < s->GetShipClass())
return false;
if (a->total_points > points)
return false;
if (a->total_missions > missions)
return false;
if (a->campaign_id && a->campaign_complete) {
if (!HasCompletedCampaign(a->campaign_id))
return false;
}
else {
// campaign related requirements
Campaign* c = Campaign::GetCampaign();
if (c) {
if (a->dynamic_campaign && !c->IsDynamic())
return false;
}
}
// sufficient merit for this medal?
if (a->mission_points > s->GetPoints())
return false;
if (a->kills > s->GetGunKills() + s->GetMissileKills())
return false;
if (a->mission_points > s->GetPoints())
return false;
// player must survive mission if lost = -1
if (a->lost < 0 && (s->GetDeaths() || s->GetColls()))
return false;
// do we need to be wounded in battle?
if (a->lost > s->GetDeaths() || a->collision > s->GetColls())
return false;
// final lottery check:
if (a->lottery < 2 || RandomChance(1, a->lottery)) {
medals |= a->id;
return true;
}
// what do we have for the losers, judge?
return false;
}
// +-------------------------------------------------------------------+
static List<Player> player_roster;
static Player* current_player = 0;
List<Player>&
Player::GetRoster()
{
return player_roster;
}
Player*
Player::GetCurrentPlayer()
{
return current_player;
}
void
Player::SelectPlayer(Player* p)
{
HUDView* hud = HUDView::GetInstance();
if (current_player && current_player != p) {
if (hud) {
for (int i = 0; i < 3; i++) {
MFD* mfd = hud->GetMFD(i);
if (mfd)
current_player->mfd[i] = mfd->GetMode();
}
}
}
if (player_roster.contains(p)) {
current_player = p;
Ship::SetFlightModel(p->flight_model);
Ship::SetLandingModel(p->landing_model);
HUDView::SetArcade(p->hud_mode > 0);
HUDView::SetDefaultColorSet(p->hud_color);
if (hud) {
for (int i = 0; i < 3; i++) {
if (p->mfd[i] >= 0) {
MFD* mfd = hud->GetMFD(i);
if (mfd)
mfd->SetMode(p->mfd[i]);
}
}
}
}
}
Player*
Player::Find(const char* name)
{
for (int i = 0; i < player_roster.size(); i++) {
Player* p = player_roster.at(i);
if (p->Name() == name)
return p;
}
return 0;
}
Player*
Player::Create(const char* name)
{
if (name && *name) {
// check for existence:
if (Find(name))
return 0;
Player* newbie = new(__FILE__,__LINE__) Player(name);
newbie->SetCreateDate(NetLayer::GetUTC());
player_roster.append(newbie);
newbie->CreateUniqueID();
return newbie;
}
return 0;
}
void
Player::Destroy(Player* p)
{
if (p) {
player_roster.remove(p);
if (p == current_player) {
current_player = 0;
if (player_roster.size())
current_player = player_roster.at(0);
}
CampaignSaveGame::RemovePlayer(p);
delete p;
}
}
// +-------------------------------------------------------------------+
void
Player::Initialize()
{
LoadAwardTables();
Load();
if (!current_player) {
if (!player_roster.size()) {
Create("Pilot");
}
SelectPlayer(player_roster.at(0));
}
}
void
Player::Close()
{
if (current_player && !player_roster.contains(current_player))
delete current_player;
player_roster.destroy();
current_player = 0;
rank_table.destroy();
medal_table.destroy();
}
// +-------------------------------------------------------------------+
bool
Player::ConfigExists()
{
return config_exists;
}
// +-------------------------------------------------------------------+
#define GET_DEF_BOOL(x) if(pdef->name()->value()==(#x))GetDefBool(player->x,pdef,filename)
#define GET_DEF_TEXT(x) if(pdef->name()->value()==(#x))GetDefText(player->x,pdef,filename)
#define GET_DEF_NUM(x) if(pdef->name()->value()==(#x))GetDefNumber(player->x,pdef,filename)
void
Player::Load()
{
config_exists = false;
// read the config file:
BYTE* block = 0;
int blocklen = 0;
char filename[64];
strcpy_s(filename, "player.cfg");
FILE* f;
::fopen_s(&f, filename, "rb");
if (f) {
config_exists = true;
::fseek(f, 0, SEEK_END);
blocklen = ftell(f);
::fseek(f, 0, SEEK_SET);
block = new(__FILE__,__LINE__) BYTE[blocklen+1];
block[blocklen] = 0;
::fread(block, blocklen, 1, f);
::fclose(f);
}
if (blocklen == 0)
return;
Parser parser(new(__FILE__,__LINE__) BlockReader((const char*) block, blocklen));
Term* term = parser.ParseTerm();
if (!term) {
Print("ERROR: could not parse '%s'.\n", filename);
return;
}
else {
TermText* file_type = term->isText();
if (!file_type || file_type->value() != "PLAYER_CONFIG") {
Print("WARNING: invalid '%s' file. Using defaults\n", filename);
return;
}
}
if (current_player && !player_roster.contains(current_player))
delete current_player;
player_roster.destroy();
current_player = 0;
do {
delete term;
term = parser.ParseTerm();
if (term) {
TermDef* def = term->isDef();
if (def) {
if (def->name()->value() == "player") {
if (!def->term() || !def->term()->isStruct()) {
Print("WARNING: player structure missing in '%s'\n", filename);
}
else {
Player* player = new(__FILE__,__LINE__) Player;
bool current = false;
TermStruct* val = def->term()->isStruct();
for (int i = 0; i < val->elements()->size(); i++) {
TermDef* pdef = val->elements()->at(i)->isDef();
if (pdef) {
GET_DEF_TEXT(name);
else GET_DEF_TEXT(squadron);
else GET_DEF_TEXT(signature);
else GET_DEF_NUM(uid);
else GET_DEF_NUM(flight_model);
else GET_DEF_NUM(flying_start);
else GET_DEF_NUM(landing_model);
else GET_DEF_NUM(ai_level);
else GET_DEF_NUM(hud_mode);
else GET_DEF_NUM(hud_color);
else GET_DEF_NUM(ff_level);
else GET_DEF_NUM(grid);
else GET_DEF_NUM(gunsight);
else if (pdef->name()->value() == ("chat_0"))
GetDefText(player->chat_macros[0], pdef, filename);
else if (pdef->name()->value() == ("chat_1"))
GetDefText(player->chat_macros[1], pdef, filename);
else if (pdef->name()->value() == ("chat_2"))
GetDefText(player->chat_macros[2], pdef, filename);
else if (pdef->name()->value() == ("chat_3"))
GetDefText(player->chat_macros[3], pdef, filename);
else if (pdef->name()->value() == ("chat_4"))
GetDefText(player->chat_macros[4], pdef, filename);
else if (pdef->name()->value() == ("chat_5"))
GetDefText(player->chat_macros[5], pdef, filename);
else if (pdef->name()->value() == ("chat_6"))
GetDefText(player->chat_macros[6], pdef, filename);
else if (pdef->name()->value() == ("chat_7"))
GetDefText(player->chat_macros[7], pdef, filename);
else if (pdef->name()->value() == ("chat_8"))
GetDefText(player->chat_macros[8], pdef, filename);
else if (pdef->name()->value() == ("chat_9"))
GetDefText(player->chat_macros[9], pdef, filename);
else if (pdef->name()->value() == ("mfd0"))
GetDefNumber(player->mfd[0], pdef, filename);
else if (pdef->name()->value() == ("mfd1"))
GetDefNumber(player->mfd[1], pdef, filename);
else if (pdef->name()->value() == ("mfd2"))
GetDefNumber(player->mfd[2], pdef, filename);
else if (pdef->name()->value() == ("current"))
GetDefBool(current, pdef, filename);
else if (pdef->name()->value() == ("trained"))
GetDefNumber(player->trained, pdef, filename);
else if (pdef->name()->value() == ("stats")) {
Text stats;
GetDefText(stats, pdef, filename);
player->DecodeStats(stats);
}
else if (pdef->name()->value().indexOf("XXX_CHEAT_A1B2C3_") == 0) {
if (pdef->name()->value().contains("points"))
GetDefNumber(player->points, pdef, filename);
else if (pdef->name()->value().contains("rank")) {
int rank=0;
GetDefNumber(rank, pdef, filename);
player->SetRank(rank);
}
else if (pdef->name()->value().contains("medals"))
GetDefNumber(player->medals, pdef, filename);
else if (pdef->name()->value().contains("campaigns"))
GetDefNumber(player->campaigns, pdef, filename);
else if (pdef->name()->value().contains("missions"))
GetDefNumber(player->missions, pdef, filename);
else if (pdef->name()->value().contains("kills"))
GetDefNumber(player->kills, pdef, filename);
else if (pdef->name()->value().contains("losses"))
GetDefNumber(player->losses, pdef, filename);
else if (pdef->name()->value().contains("flight_time"))
GetDefNumber(player->flight_time, pdef, filename);
}
}
}
player_roster.append(player);
player->CreateUniqueID();
if (current)
SelectPlayer(player);
}
}
else {
Print("WARNING: unknown label '%s' in '%s'\n",
def->name()->value().data(), filename);
}
}
else {
Print("WARNING: term ignored in '%s'\n", filename);
term->print();
}
}
}
while (term);
delete [] block;
}
// +-------------------------------------------------------------------+
void
Player::Save()
{
HUDView* hud = HUDView::GetInstance();
if (hud && current_player) {
for (int i = 0; i < 3; i++) {
MFD* mfd = hud->GetMFD(i);
if (mfd)
current_player->mfd[i] = mfd->GetMode();
}
}
FILE* f;
fopen_s(&f, "player.cfg", "w");
if (f) {
fprintf(f, "PLAYER_CONFIG\n\n");
ListIter<Player> iter = player_roster;
while (++iter) {
Player* p = iter.value();
fprintf(f, "player: {\n");
fprintf(f, " uid: %d,\n", p->uid);
fprintf(f, " name: \"%s\",\n", SafeQuotes(p->name.data()));
fprintf(f, " squadron: \"%s\",\n", SafeQuotes(p->squadron.data()));
fprintf(f, " signature: \"%s\",\n", SafeQuotes(p->signature.data()));
Text stat_data = p->EncodeStats();
if (stat_data.length() > 32) {
char tmp[64];
int len = stat_data.length();
for (int n = 0; n < len; n += 32) {
ZeroMemory(tmp, sizeof(tmp));
const char* p = stat_data.data() + n;
strncpy(tmp, p, 32);
if (n == 0)
fprintf(f, " stats: \"%s\"\n", tmp);
else if (n < len-32)
fprintf(f, " \"%s\"\n", tmp);
else
fprintf(f, " \"%s\",\n", tmp);
}
}
if (p == current_player)
fprintf(f, " current: true,\n");
else
fprintf(f, " current: false,\n");
fprintf(f, " trained: %d,\n", p->trained);
fprintf(f, " flight_model: %d,\n", p->flight_model);
fprintf(f, " flying_start: %d,\n", p->flying_start);
fprintf(f, " landing_model: %d,\n", p->landing_model);
fprintf(f, " ai_level: %d,\n", p->ai_level);
fprintf(f, " hud_mode: %d,\n", p->hud_mode);
fprintf(f, " hud_color: %d,\n", p->hud_color);
fprintf(f, " ff_level: %d,\n", p->ff_level);
fprintf(f, " grid: %d,\n", p->grid);
fprintf(f, " gunsight: %d,\n", p->gunsight);
for (int i = 0; i < 10; i++) {
fprintf(f, " chat_%d: \"%s\",\n", i, SafeQuotes(p->chat_macros[i].data()));
}
for (int i = 0; i < 3; i++) {
if (p->mfd[i] >= 0) {
fprintf(f, " mfd%d: %d,\n", i, p->mfd[i]);
}
}
fprintf(f, "}\n\n");
}
fclose(f);
config_exists = true;
}
}
// +-------------------------------------------------------------------+
static char stat_buf[280];
static char code_buf[280];
Text
Player::EncodeStats()
{
ZeroMemory(stat_buf, 280);
ZeroMemory(code_buf, 280);
sprintf_s(stat_buf, "%-16s%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x",
pass.data(),
create_date,
points,
flight_time,
missions,
kills,
losses,
medals,
campaigns,
11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32);
for (int i = 0; i < 16; i++)
for (int j = 0; j < 16; j++)
code_buf[i*16 + j] = stat_buf[j*16 + i];
return Encryption::Encode(Encryption::Encrypt(code_buf));
}
void
Player::DecodeStats(const char* stats)
{
ZeroMemory(stat_buf, 280);
ZeroMemory(code_buf, 280);
if (!stats || !*stats) {
Print("Player::DecodeStats() invalid or missing stats\n");
create_date = NetLayer::GetUTC();
return;
}
Text plain = Encryption::Decrypt(Encryption::Decode(stats));
if (plain.length() == 64) {
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
stat_buf[j*8 + i] = plain[i*8 +j];
}
else if (plain.length() == 256) {
for (int i = 0; i < 16; i++)
for (int j = 0; j < 16; j++)
stat_buf[j*16 + i] = plain[i*16 +j];
}
else {
Print("Player::DecodeStats() invalid plain text length %d\n", plain.length());
create_date = NetLayer::GetUTC();
return;
}
char work[32];
ZeroMemory(work, 32);
CopyMemory(work, stat_buf, 16);
for (int i = 15; i > 0; i--)
if (work[i] == ' ') work[i] = 0;
else break;
pass = work;
ZeroMemory(work, 16);
CopyMemory(work, stat_buf+16, 8);
sscanf_s(work, "%x", &create_date);
ZeroMemory(work, 16);
CopyMemory(work, stat_buf+24, 8);
sscanf_s(work, "%x", &points);
if (points < 0) points = 0;
ZeroMemory(work, 16);
CopyMemory(work, stat_buf+32, 8);
sscanf_s(work, "%x", &flight_time);
if (flight_time < 0) flight_time = 0;
ZeroMemory(work, 16);
CopyMemory(work, stat_buf+40, 8);
sscanf_s(work, "%x", &missions);
if (missions < 0) missions = 0;
ZeroMemory(work, 16);
CopyMemory(work, stat_buf+48, 8);
sscanf_s(work, "%x", &kills);
if (kills < 0) kills = 0;
ZeroMemory(work, 16);
CopyMemory(work, stat_buf+56, 8);
sscanf_s(work, "%x", &losses);
if (losses < 0) losses = 0;
if (plain.length() > 64) {
ZeroMemory(work, 16);
CopyMemory(work, stat_buf+64, 8);
sscanf_s(work, "%x", &medals);
ZeroMemory(work, 16);
CopyMemory(work, stat_buf+72, 8);
sscanf_s(work, "%x", &campaigns);
}
if (create_date == 0) {
::Print("WARNING - loaded player with zero stats '%s'\n", name.data());
create_date = NetLayer::GetUTC();
}
}
// +-------------------------------------------------------------------+
void
Player::LoadAwardTables()
{
DataLoader* loader = DataLoader::GetLoader();
if (!loader) return;
BYTE* block = 0;
const char* filename = "awards.def";
loader->SetDataPath("Awards/");
loader->LoadBuffer(filename, block, true);
Parser parser(new(__FILE__,__LINE__) BlockReader((const char*) block));
Term* term = parser.ParseTerm();
if (!term) {
return;
}
else {
TermText* file_type = term->isText();
if (!file_type || file_type->value() != "AWARDS") {
return;
}
}
rank_table.destroy();
medal_table.destroy();
::Print("Loading Ranks and Medals\n");
do {
delete term; term = 0;
term = parser.ParseTerm();
if (term) {
TermDef* def = term->isDef();
if (def) {
if (def->name()->value() == "award") {
if (!def->term() || !def->term()->isStruct()) {
Print("WARNING: award structure missing in '%s'\n", filename);
}
else {
AwardInfo* award = new(__FILE__,__LINE__) AwardInfo;
TermStruct* val = def->term()->isStruct();
for (int i = 0; i < val->elements()->size(); i++) {
TermDef* pdef = val->elements()->at(i)->isDef();
if (pdef) {
if (pdef->name()->value() == ("name")) {
GetDefText(award->name, pdef, filename);
award->name = Game::GetText(award->name);
}
else if (pdef->name()->value() == ("abrv")) {
GetDefText(award->abrv, pdef, filename);
award->abrv = Game::GetText(award->abrv);
}
else if (pdef->name()->value() == ("desc")) {
GetDefText(award->desc, pdef, filename);
if (award->desc.length() <= 40)
award->desc = Game::GetText(award->desc);
}
else if (pdef->name()->value() == ("award")) {
GetDefText(award->grant, pdef, filename);
if (award->grant.length() <= 40)
award->grant = Game::GetText(award->grant);
}
else if (pdef->name()->value() == ("desc_sound"))
GetDefText(award->desc_sound, pdef, filename);
else if (pdef->name()->value() == ("award_sound"))
GetDefText(award->grant_sound, pdef, filename);
else if (pdef->name()->value().indexOf("large") == 0) {
Text txt;
GetDefText(txt, pdef, filename);
txt.setSensitive(false);
if (!txt.contains(".pcx"))
txt.append(".pcx");
loader->CacheBitmap(txt, award->large_insignia);
}
else if (pdef->name()->value().indexOf("small") == 0) {
Text txt;
GetDefText(txt, pdef, filename);
txt.setSensitive(false);
if (!txt.contains(".pcx"))
txt.append(".pcx");
loader->CacheBitmap(txt, award->small_insignia);
if (award->small_insignia)
award->small_insignia->AutoMask();
}
else if (pdef->name()->value() == ("type")) {
Text txt;
GetDefText(txt, pdef, filename);
txt.setSensitive(false);
if (txt == "rank")
award->type = AwardInfo::RANK;
else if (txt == "medal")
award->type = AwardInfo::MEDAL;
}
else if (pdef->name()->value() == ("id"))
GetDefNumber(award->id, pdef, filename);
else if (pdef->name()->value() == ("total_points"))
GetDefNumber(award->total_points, pdef, filename);
else if (pdef->name()->value() == ("mission_points"))
GetDefNumber(award->mission_points, pdef, filename);
else if (pdef->name()->value() == ("total_missions"))
GetDefNumber(award->total_missions, pdef, filename);
else if (pdef->name()->value() == ("kills"))
GetDefNumber(award->kills, pdef, filename);
else if (pdef->name()->value() == ("lost"))
GetDefNumber(award->lost, pdef, filename);
else if (pdef->name()->value() == ("collision"))
GetDefNumber(award->collision, pdef, filename);
else if (pdef->name()->value() == ("campaign_id"))
GetDefNumber(award->campaign_id, pdef, filename);
else if (pdef->name()->value() == ("campaign_complete"))
GetDefBool(award->campaign_complete, pdef, filename);
else if (pdef->name()->value() == ("dynamic_campaign"))
GetDefBool(award->dynamic_campaign, pdef, filename);
else if (pdef->name()->value() == ("ceremony"))
GetDefBool(award->ceremony, pdef, filename);
else if (pdef->name()->value() == ("required_awards"))
GetDefNumber(award->required_awards, pdef, filename);
else if (pdef->name()->value() == ("lottery"))
GetDefNumber(award->lottery, pdef, filename);
else if (pdef->name()->value() == ("min_rank"))
GetDefNumber(award->min_rank, pdef, filename);
else if (pdef->name()->value() == ("max_rank"))
GetDefNumber(award->max_rank, pdef, filename);
else if (pdef->name()->value() == ("min_ship_class")) {
Text classname;
GetDefText(classname, pdef, filename);
award->min_ship_class = Ship::ClassForName(classname);
}
else if (pdef->name()->value() == ("max_ship_class")) {
Text classname;
GetDefText(classname, pdef, filename);
award->max_ship_class = Ship::ClassForName(classname);
}
else if (pdef->name()->value().indexOf("grant") == 0)
GetDefNumber(award->granted_ship_classes, pdef, filename);
}
}
if (award->type == AwardInfo::RANK) {
rank_table.append(award);
}
else if (award->type == AwardInfo::MEDAL) {
medal_table.append(award);
}
else {
delete award;
}
}
}
else {
Print("WARNING: unknown label '%s' in '%s'\n",
def->name()->value().data(), filename);
}
}
else {
Print("WARNING: term ignored in '%s'\n", filename);
term->print();
}
}
}
while (term);
loader->ReleaseBuffer(block);
loader->SetDataPath(0);
}
// +-------------------------------------------------------------------+
void
Player::CreateUniqueID()
{
ListIter<Player> iter = player_roster;
while (++iter) {
Player* p = iter.value();
if (p != this && p->uid >= uid)
uid = p->uid + 1;
}
if (uid < 1)
uid = 1;
}
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ZX_01_OUTPUT_CHAR_32_TTY_Z88DK
; implemented tty_z88dk terminal emulation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Windowed output terminal for fixed width fonts.
; Implements tty_z88dk terminal emulation.
;
; ;;;;;;;;;;;;;;;;;;;;
; DRIVER CLASS DIAGRAM
; ;;;;;;;;;;;;;;;;;;;;
;
; CONSOLE_01_OUTPUT_TERMINAL (root, abstract)
; CONSOLE_01_OUTPUT_TERMINAL_CHAR (abstract)
; ZX_01_OUTPUT_CHAR_32 (concrete)
; ZX_01_OUTPUT_CHAR_32_TTY_Z88DK (concrete)
;
; Can be instantiated to implement a CONSOLE_01_OUTPUT_TERMINAL.
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM STDIO
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * STDIO_MSG_PUTC
; Generates multiple OTERM_MSG_PUTC messages.
;
; * STDIO_MSG_WRIT
; Generates multiple OTERM_MSG_PUTC messages.
;
; * STDIO_MSG_SEEK -> no error, do nothing
; * STDIO_MSG_FLSH -> resets tty emulation
; * STDIO_MSG_ICTL
; * STDIO_MSG_CLOS -> no error, do nothing
;
; Any other messages are reported as errors via
; error_enotsup_zc
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM CONSOLE_01_OUTPUT_TERMINAL
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * OTERM_MSG_PUTC
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM CONSOLE_01_INPUT_TERMINAL
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * ITERM_MSG_PUTC
; * ITERM_MSG_PRINT_CURSOR - cursor changed to L or C
; * ITERM_MSG_BS
; * ITERM_MSG_BS_PWD
; * ITERM_MSG_ERASE_CURSOR
; * ITERM_MSG_ERASE_CURSOR_PWD
; * ITERM_MSG_READLINE_BEGIN
; * ITERM_MSG_READLINE_END
; * ITERM_MSG_BELL
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM CONSOLE_01_OUTPUT_TERMINAL_CHAR
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * OTERM_MSG_TTY
; * OTERM_MSG_PRINTC
; * OTERM_MSG_BELL
; * OTERM_MSG_SCROLL
; * OTERM_MSG_CLS
; * OTERM_MSG_PAUSE
; * OTERM_MSG_BELL
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; IOCTLs UNDERSTOOD BY THIS DRIVER
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * IOCTL_OTERM_CRLF
; enable / disable crlf processing
;
; * IOCTL_OTERM_BELL
; enable / disable terminal bell
;
; * IOCTL_OTERM_SIGNAL
; enable / disable signal bell
;
; * IOCTL_OTERM_COOK
; enable / disable cook mode (tty emulation)
;
; * IOCTL_OTERM_PAUSE
; enable / disable pause when window filled
;
; * IOCTL_OTERM_PAGE
; select scroll or page mode
;
; * IOCTL_OTERM_CLEAR
; enable / disable clear window when in page mode
;
; * IOCTL_OTERM_CLS
; clear window, set (x,y) = (0,0)
;
; * IOCTL_OTERM_RESET_SCROLL
; reset scroll count
;
; * IOCTL_OTERM_GET_WINDOW_COORD
; get coord of top left corner of window
;
; * IOCTL_OTERM_SET_WINDOW_COORD
; set coord of top left corner of window
;
; * IOCTL_OTERM_GET_WINDOW_RECT
; get window size
;
; * IOCTL_OTERM_SET_WINDOW_RECT
; set window size
;
; * IOCTL_OTERM_GET_CURSOR_COORD
;
; * IOCTL_OTERM_SET_CURSOR_COORD
;
; * IOCTL_OTERM_GET_OTERM
;
; * IOCTL_OTERM_SCROLL
;
; * IOCTL_OTERM_FONT
;
; * IOCTL_OTERM_BCOLOR
;
; * IOCTL_OTERM_FCOLOR
;
; * IOCTL_OTERM_FMASK
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;
; BYTES RESERVED IN FDSTRUCT
; ;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; offset (wrt FDSTRUCT.JP) description
;
; 8..13 mutex
; 14 x coordinate
; 15 y coordinate
; 16 window.x
; 17 window.width
; 18 window.y
; 19 window.height
; 20 scroll_limit
; 21..22 font address
; 23 text colour
; 24 text colour mask (set bits = keep bgnd)
; 25 background colour (cls colour)
; 26 tty_z88dk.call (205)
; 27..28 tty_z88dk.state
; 29 tty_z88dk.action
; 30 tty_z88dk.param_1
; 31 tty_z88dk.param_2
SECTION code_fcntl
PUBLIC zx_01_output_char_32_tty_z88dk
EXTERN OTERM_MSG_TTY, STDIO_MSG_FLSH, STDIO_MSG_ICTL
EXTERN zx_01_output_char_32
EXTERN zx_01_output_char_32_tty_z88dk_oterm_msg_tty
EXTERN zx_01_output_char_32_tty_z88dk_stdio_msg_flsh
EXTERN zx_01_output_char_32_tty_z88dk_stdio_msg_ictl
zx_01_output_char_32_tty_z88dk:
cp OTERM_MSG_TTY
jp z, zx_01_output_char_32_tty_z88dk_oterm_msg_tty
cp STDIO_MSG_FLSH
jp z, zx_01_output_char_32_tty_z88dk_stdio_msg_flsh
cp STDIO_MSG_ICTL
jp z, zx_01_output_char_32_tty_z88dk_stdio_msg_ictl
jp zx_01_output_char_32 ; forward to library
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkSSAAPass.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSSAAPass.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLError.h"
#include "vtkOpenGLFramebufferObject.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLShaderCache.h"
#include "vtkOpenGLState.h"
#include "vtkOpenGLVertexArrayObject.h"
#include "vtkRenderState.h"
#include "vtkRenderer.h"
#include "vtkShaderProgram.h"
#include "vtkTextureObject.h"
#include <cassert>
#include "vtkOpenGLHelper.h"
#include "vtkSSAAPassFS.h"
#include "vtkTextureObjectVS.h" // a pass through shader
vtkStandardNewMacro(vtkSSAAPass);
vtkCxxSetObjectMacro(vtkSSAAPass, DelegatePass, vtkRenderPass);
// ----------------------------------------------------------------------------
vtkSSAAPass::vtkSSAAPass()
{
this->FrameBufferObject = nullptr;
this->Pass1 = nullptr;
this->Pass2 = nullptr;
this->SSAAProgram = nullptr;
this->DelegatePass = nullptr;
}
// ----------------------------------------------------------------------------
vtkSSAAPass::~vtkSSAAPass()
{
if (this->DelegatePass != nullptr)
{
this->DelegatePass->Delete();
}
if (this->FrameBufferObject != nullptr)
{
this->FrameBufferObject->Delete();
}
if (this->Pass1 != nullptr)
{
this->Pass1->Delete();
}
if (this->Pass2 != nullptr)
{
this->Pass2->Delete();
}
delete this->SSAAProgram;
}
// ----------------------------------------------------------------------------
void vtkSSAAPass::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "DelegatePass:";
if (this->DelegatePass != nullptr)
{
this->DelegatePass->PrintSelf(os, indent);
}
else
{
os << "(none)" << endl;
}
}
// ----------------------------------------------------------------------------
// Description:
// Perform rendering according to a render state \p s.
// \pre s_exists: s!=0
void vtkSSAAPass::Render(const vtkRenderState* s)
{
assert("pre: s_exists" && s != nullptr);
vtkOpenGLClearErrorMacro();
this->NumberOfRenderedProps = 0;
vtkRenderer* r = s->GetRenderer();
vtkOpenGLRenderWindow* renWin = static_cast<vtkOpenGLRenderWindow*>(r->GetRenderWindow());
vtkOpenGLState* ostate = renWin->GetState();
if (this->DelegatePass == nullptr)
{
vtkWarningMacro(<< " no delegate.");
return;
}
// backup GL state
vtkOpenGLState::ScopedglEnableDisable dsaver(ostate, GL_DEPTH_TEST);
vtkOpenGLState::ScopedglEnableDisable bsaver(ostate, GL_BLEND);
// 1. Create a new render state with an FBO.
int width;
int height;
int size[2];
s->GetWindowSize(size);
width = size[0];
height = size[1];
int w = width * sqrt(5.0);
int h = height * sqrt(5.0);
if (this->Pass1 == nullptr)
{
this->Pass1 = vtkTextureObject::New();
this->Pass1->SetContext(renWin);
}
if (this->FrameBufferObject == nullptr)
{
this->FrameBufferObject = vtkOpenGLFramebufferObject::New();
this->FrameBufferObject->SetContext(renWin);
}
if (this->Pass1->GetWidth() != static_cast<unsigned int>(w) ||
this->Pass1->GetHeight() != static_cast<unsigned int>(h))
{
this->Pass1->Create2D(
static_cast<unsigned int>(w), static_cast<unsigned int>(h), 4, VTK_UNSIGNED_CHAR, false);
}
ostate->PushFramebufferBindings();
vtkRenderState s2(r);
s2.SetPropArrayAndCount(s->GetPropArray(), s->GetPropArrayCount());
s2.SetFrameBuffer(this->FrameBufferObject);
this->FrameBufferObject->Bind();
this->FrameBufferObject->AddColorAttachment(0, this->Pass1);
this->FrameBufferObject->ActivateDrawBuffer(0);
this->FrameBufferObject->AddDepthAttachment();
this->FrameBufferObject->StartNonOrtho(w, h);
ostate->vtkglViewport(0, 0, w, h);
ostate->vtkglScissor(0, 0, w, h);
ostate->vtkglEnable(GL_DEPTH_TEST);
this->DelegatePass->Render(&s2);
this->NumberOfRenderedProps += this->DelegatePass->GetNumberOfRenderedProps();
// 3. Same FBO, but new color attachment (new TO).
if (this->Pass2 == nullptr)
{
this->Pass2 = vtkTextureObject::New();
this->Pass2->SetContext(this->FrameBufferObject->GetContext());
}
if (this->Pass2->GetWidth() != static_cast<unsigned int>(width) ||
this->Pass2->GetHeight() != static_cast<unsigned int>(h))
{
this->Pass2->Create2D(
static_cast<unsigned int>(width), static_cast<unsigned int>(h), 4, VTK_UNSIGNED_CHAR, false);
}
this->FrameBufferObject->AddColorAttachment(0, this->Pass2);
this->FrameBufferObject->Start(width, h);
// Use a subsample shader, do it horizontally. this->Pass1 is the source
// (this->Pass2 is the fbo render target)
if (!this->SSAAProgram)
{
this->SSAAProgram = new vtkOpenGLHelper;
// build the shader source code
// std::string VSSource = vtkSSAAPassVS;
std::string VSSource = vtkTextureObjectVS;
std::string FSSource = vtkSSAAPassFS;
std::string GSSource;
// compile and bind it if needed
vtkShaderProgram* newShader = renWin->GetShaderCache()->ReadyShaderProgram(
VSSource.c_str(), FSSource.c_str(), GSSource.c_str());
// if the shader changed reinitialize the VAO
if (newShader != this->SSAAProgram->Program)
{
this->SSAAProgram->Program = newShader;
this->SSAAProgram->VAO->ShaderProgramChanged(); // reset the VAO as the shader has changed
}
this->SSAAProgram->ShaderSourceTime.Modified();
}
else
{
renWin->GetShaderCache()->ReadyShaderProgram(this->SSAAProgram->Program);
}
if (!this->SSAAProgram->Program)
{
vtkErrorMacro("Couldn't build the shader program. At this point , it can be an error in a "
"shader or a driver bug.");
// restore some state.
ostate->PopFramebufferBindings();
return;
}
this->Pass1->Activate();
int sourceId = this->Pass1->GetTextureUnit();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
this->SSAAProgram->Program->SetUniformi("source", sourceId);
// The implementation uses four steps to cover 1.5 destination pixels
// so the offset is 1.5/4.0 = 0.375
this->SSAAProgram->Program->SetUniformf("texelWidthOffset", 0.375 / width);
this->SSAAProgram->Program->SetUniformf("texelHeightOffset", 0.0);
ostate->vtkglDisable(GL_BLEND);
ostate->vtkglDisable(GL_DEPTH_TEST);
this->FrameBufferObject->RenderQuad(
0, width - 1, 0, h - 1, this->SSAAProgram->Program, this->SSAAProgram->VAO);
this->Pass1->Deactivate();
// 4. Render in original FB (from renderstate in arg)
ostate->PopFramebufferBindings();
// to2 is the source
this->Pass2->Activate();
sourceId = this->Pass2->GetTextureUnit();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
this->SSAAProgram->Program->SetUniformi("source", sourceId);
this->SSAAProgram->Program->SetUniformf("texelWidthOffset", 0.0);
this->SSAAProgram->Program->SetUniformf("texelHeightOffset", 0.375 / height);
// Use the same sample shader, this time vertical
this->Pass2->CopyToFrameBuffer(0, 0, width - 1, h - 1, 0, 0, width - 1, height - 1, width, height,
this->SSAAProgram->Program, this->SSAAProgram->VAO);
this->Pass2->Deactivate();
vtkOpenGLCheckErrorMacro("failed after Render");
}
// ----------------------------------------------------------------------------
// Description:
// Release graphics resources and ask components to release their own
// resources.
// \pre w_exists: w!=0
void vtkSSAAPass::ReleaseGraphicsResources(vtkWindow* w)
{
assert("pre: w_exists" && w != nullptr);
this->Superclass::ReleaseGraphicsResources(w);
if (this->SSAAProgram != nullptr)
{
this->SSAAProgram->ReleaseGraphicsResources(w);
}
if (this->FrameBufferObject != nullptr)
{
this->FrameBufferObject->ReleaseGraphicsResources(w);
}
if (this->Pass1 != nullptr)
{
this->Pass1->ReleaseGraphicsResources(w);
}
if (this->Pass2 != nullptr)
{
this->Pass2->ReleaseGraphicsResources(w);
}
if (this->DelegatePass != nullptr)
{
this->DelegatePass->ReleaseGraphicsResources(w);
}
}
|
; name: print_string
; desc: Prints a string terminated by 0x00
; input:
; si: pointer to string
; output:
; none
print_string:
pusha
.loop: lodsb
cmp al, 0
je .end
call print_char
jmp .loop
.end: popa
ret
read_key:
push bx
mov bh, ah
mov ah,0x00
int 0x16
mov ah, bh
pop bx
; name: print_char
; desc: Prints character
; input:
; al: character
; output:
; none
print_char:
pusha
mov ah, 0x0e
mov bx, 0x0007
int 0x10
popa
ret
; name: halt
; desc: Halts the system
; input:
; none
; ouput:
; none
halt:
hlt
jmp halt
; name: input_line
; desc: Reads a line
; input:
; al: promt char
; si: buffer to write to
; output:
; cx: number of bytes read
input_line:
pusha
call print_char ; Output prompt character
mov di, si ; Target for writing line
xchg ax, dx
.s1: cmp al,0x08 ; Backspace?
jne .s2
dec di ; Undo the backspace write
cmp si, di
je .s4
dec di ; Erase a character
mov al, " "
call print_char
mov al, 0x08
call print_char
mov al, dl
.s2: call read_key ; Read keyboard
cmp al,0x0d ; CR pressed?
jne .s3
mov al,0x00
.s3: stosb ; Save key in buffer
jne .s1 ; No, wait another key
mov word [.tmp1], di
popa
mov cx, word [.tmp1]
sub cx, si
ret ; Yes, return
.s4: mov al, dl
call print_char
jmp .s2
.tmp1: dw 0
; name: panic
; desc: panic
; input:
; none
; ouput:
; none
panic:
mov si, errors.panic
call print_string
call read_key
call reboot
; name: reboot
; desc: reboot
; input:
; none
; ouput:
; none
reboot:
jmp 0xffff:0x0000
; name: print_hex_byte
; desc: prints one byte as hex
; input:
; al: byte to print
; output:
; none
print_hex_byte:
push ax
push cx
push bx
lea bx, [.table]
mov ah, al
and al, 0x0f
mov cl, 4
shr ah, cl
xlat
xchg ah, al
xlat
mov bx, 0x0007
mov ch, ah
mov ah, 0x0e
int 0x10
mov al, ch
int 0x10
pop bx
pop cx
pop ax
ret
.table: db "0123456789ABCDEF", 0
; name: print_hex
; dex: prints an array of hex values
; input:
; si: pointer to array
; cx: length of array
; output:
; none
print_hex:
push ax
push si
push cx
.loop: lodsb
call print_hex_byte
loop .loop
pop cx
pop si
pop ax
ret
|
; A104099: n * (10n^2 - 6n + 1), or n*A087348(n).
; 0,5,58,219,548,1105,1950,3143,4744,6813,9410,12595,16428,20969,26278,32415,39440,47413,56394,66443,77620,89985,103598,118519,134808,152525,171730,192483,214844,238873,264630,292175,321568,352869,386138,421435
mov $2,$0
mul $0,4
add $0,$2
mov $1,$0
bin $0,3
mul $0,12
add $0,$1
div $0,25
|
; A037582: Decimal expansion of a(n) is given by the first n terms of the periodic sequence with initial period 1,3.
; 1,13,131,1313,13131,131313,1313131,13131313,131313131,1313131313,13131313131,131313131313,1313131313131,13131313131313,131313131313131,1313131313131313,13131313131313131,131313131313131313,1313131313131313131,13131313131313131313
seq $0,42 ; Unary representation of natural numbers.
sub $0,1
mul $0,36
add $0,39
div $0,24
mul $0,78
div $0,11
mul $0,4
div $0,36
add $0,1
|
; A066266: Product of first n primorials + 1.
; Submitted by Jon Maiga
; 3,13,361,75601,174636001,5244319080001,2677277333530800001,25968760179275365452000001,5793445238736255798985527240000001,37481813439427687898244906452608585200000001,7517370874372838151564668004911177464757864076000000001,55784440720968513813368002533861454979548176771615744085560000000001,16972430790072694934938157854257758698967290083702175348735860941628087600000000001,222046261244808869776040900239313953120666458401987626347805929809038681543479663134628000000000001
add $0,1
seq $0,6939 ; Chernoff sequence: a(n) = Product_{k=1..n} prime(k)^(n-k+1).
add $0,1
|
; reloads text box tile patterns, current map view, and tileset tile patterns
ReloadMapData::
ldh a, [hLoadedROMBank]
push af
ld a, [wCurMap]
call SwitchToMapRomBank
call DisableLCD
call LoadTextBoxTilePatterns
call LoadCurrentMapView
call LoadTilesetTilePatternData
call EnableLCD
pop af
ldh [hLoadedROMBank], a
ld [MBC1RomBank], a
ret
; reloads tileset tile patterns
ReloadTilesetTilePatterns::
ldh a, [hLoadedROMBank]
push af
ld a, [wCurMap]
call SwitchToMapRomBank
call DisableLCD
call LoadTilesetTilePatternData
call EnableLCD
pop af
ldh [hLoadedROMBank], a
ld [MBC1RomBank], a
ret
; shows the town map and lets the player choose a destination to fly to
ChooseFlyDestination::
ld hl, wd72e
res 4, [hl]
farjp LoadTownMap_Fly
; causes the text box to close without waiting for a button press after displaying text
DisableWaitingAfterTextDisplay::
ld a, $01
ld [wDoNotWaitForButtonPressAfterDisplayingText], a
ret
|
bits 64
VGATHERQPS xmm1, [xmm0 + rsi], xmm2 ; OK
VGATHERQPS xmm1, [ymm0 + rsi], xmm2 ; fail: error: invalid effective address
VGATHERDPD ymm1, [xmm0 + rsi], ymm2 ; OK
VGATHERDPD xmm1, [xmm0 + rsi], xmm2 ; OK
VGATHERQPD xmm1, [xmm0 + rsi], xmm2 ; OK
VGATHERQPD ymm1, [ymm0 + rsi], ymm2 ; OK
VPGATHERQD xmm1, [xmm0 + rsi], xmm2 ; OK
VPGATHERQD xmm1, [ymm0 + rsi], xmm2 ; fail: error: invalid effective address
VPGATHERDQ ymm1, [xmm0 + rsi], ymm2 ; OK
|
; A104234: Number of k >= 1 such that k+n == 0 mod 2^k.
; Submitted by Christian Krause
; 0,1,1,1,0,2,1,1,0,1,1,1,1,2,1,1,0,1,1,1,0,2,1,1,0,1,1,2,1,2,1,1,0,1,1,1,0,2,1,1,0,1,1,1,1,2,1,1,0,1,1,1,0,2,1,1,0,1,2,2,1,2,1,1,0,1,1,1,0,2,1,1,0,1,1,1,1,2,1,1,0,1,1,1,0,2,1,1,0,1,1,2,1,2,1,1,0,1,1,1
add $0,1
mov $2,$0
mov $4,1
lpb $2
mul $4,2
mov $5,$0
add $0,1
mov $3,1
mod $5,$4
cmp $5,0
mul $3,$5
add $1,$3
div $2,2
lpe
mov $0,$1
|
dnl ARM mpn_cnd_add_n, mpn_cnd_sub_n
dnl Copyright 2012, 2013 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
C cycles/limb
C StrongARM ?
C XScale ?
C Cortex-A7 ?
C Cortex-A8 ?
C Cortex-A9 3
C Cortex-A15 2.5
define(`cnd', `r0')
define(`rp', `r1')
define(`up', `r2')
define(`vp', `r3')
define(`n', `r12')
ifdef(`OPERATION_cnd_add_n', `
define(`ADDSUB', adds)
define(`ADDSUBC', adcs)
define(`INITCY', `cmn r0, #0')
define(`RETVAL', `adc r0, n, #0')
define(func, mpn_cnd_add_n)')
ifdef(`OPERATION_cnd_sub_n', `
define(`ADDSUB', subs)
define(`ADDSUBC', sbcs)
define(`INITCY', `cmp r0, #0')
define(`RETVAL', `adc r0, n, #0
rsb r0, r0, #1')
define(func, mpn_cnd_sub_n)')
MULFUNC_PROLOGUE(mpn_cnd_add_n mpn_cnd_sub_n)
ASM_START()
PROLOGUE(func)
push {r4-r11}
ldr n, [sp, #32]
cmp cnd, #1
sbc cnd, cnd, cnd C conditionally set to 0xffffffff
INITCY C really only needed for n = 0 (mod 4)
ands r4, n, #3
beq L(top)
cmp r4, #2
bcc L(b1)
beq L(b2)
L(b3): ldm vp!, {r4,r5,r6}
ldm up!, {r8,r9,r10}
bic r4, r4, cnd
bic r5, r5, cnd
bic r6, r6, cnd
ADDSUB r8, r8, r4
ADDSUBC r9, r9, r5
ADDSUBC r10, r10, r6
stm rp!, {r8,r9,r10}
sub n, n, #3
teq n, #0
bne L(top)
b L(end)
L(b2): ldm vp!, {r4,r5}
ldm up!, {r8,r9}
bic r4, r4, cnd
bic r5, r5, cnd
ADDSUB r8, r8, r4
ADDSUBC r9, r9, r5
stm rp!, {r8,r9}
sub n, n, #2
teq n, #0
bne L(top)
b L(end)
L(b1): ldr r4, [vp], #4
ldr r8, [up], #4
bic r4, r4, cnd
ADDSUB r8, r8, r4
str r8, [rp], #4
sub n, n, #1
teq n, #0
beq L(end)
L(top): ldm vp!, {r4,r5,r6,r7}
ldm up!, {r8,r9,r10,r11}
bic r4, r4, cnd
bic r5, r5, cnd
bic r6, r6, cnd
bic r7, r7, cnd
ADDSUBC r8, r8, r4
ADDSUBC r9, r9, r5
ADDSUBC r10, r10, r6
ADDSUBC r11, r11, r7
sub n, n, #4
stm rp!, {r8,r9,r10,r11}
teq n, #0
bne L(top)
L(end): RETVAL
pop {r4-r11}
return r14
EPILOGUE()
|
; A062112: a(0)=0; a(1)=1; a(n) = a(n-1) + (3 + (-1)^n)*a(n-2)/2.
; Submitted by Jamie Morken(s2)
; 0,1,1,2,4,6,14,20,48,68,164,232,560,792,1912,2704,6528,9232,22288,31520,76096,107616,259808,367424,887040,1254464,3028544,4283008,10340096,14623104,35303296,49926400,120532992,170459392,411525376,581984768,1405035520,1987020288,4797091328,6784111616,16378294272,23162405888,55918994432,79081400320,190919389184,270000789504,651839567872,921840357376,2225519493120,3147359850496,7598398836736,10745758687232,25942556360704,36688315047936,88573427769344,125261742817280,302408598355968,427670341173248
mov $1,1
lpb $0
sub $0,2
add $1,$2
mul $2,2
add $2,$1
lpe
lpb $0
sub $0,1
add $2,$1
lpe
mov $0,$2
|
#include "./managed.hpp"
#include "../fixed.hpp"
using namespace GS_DDMRM::S_system::S_allocator::S_chunk;
GC_managed::GC_managed( T_allocator *P_allocator, T_ptr P_ptr )
: T_simple( P_ptr )
, M2_allocator( P_allocator )
{
if( nullptr != M2_allocator )
{
// TODO if( false == M2_allocator->F_check( P_ptr ) )
// TODO {
// TODO F_ptr( nullptr );
// TODO }
}
}
GC_managed::~GC_managed()
{
F_release();
}
GC_managed & GC_managed::operator=( GC_managed const& P_other )
{
if( nullptr == P_other.F_allocator() )
{
M2_allocator = nullptr;
F_ptr( P_other.F_ptr() );
return *this;
}
P_other.F_allocator()->F_new( *this, P_other );
return *this;
}
void GC_managed::F_release( )
{
if( nullptr == F_allocator() )
{
F_ptr( nullptr );
return;
}
M2_allocator->F_release( *this );
F_ptr( nullptr );
}
|
; A037778: Decimal expansion of a(n) is given by the first n terms of the periodic sequence with initial period 3,1,0,2.
; Submitted by Jon Maiga
; 3,31,310,3102,31023,310231,3102310,31023102,310231023,3102310231,31023102310,310231023102,3102310231023,31023102310231,310231023102310,3102310231023102,31023102310231023,310231023102310231,3102310231023102310,31023102310231023102
add $0,1
mov $2,3
lpb $0
mov $3,$2
lpb $3
add $2,2
mod $3,5
sub $3,1
add $4,1
lpe
sub $0,1
add $2,2
mul $4,10
lpe
mov $0,$4
div $0,10
|
/** @file MovingAverageTest.cpp
*
* Copyright (c) 2019 IACE
*/
#define BOOST_TEST_MODULE MovingAverageTest
#include "MovingAverage.h"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE( ConstValueTest ) {
const int LEN = 5;
MovingAverage<int, LEN> myMovingAverage;
for (unsigned int i = 0; i < 2 * LEN; i++) {
myMovingAverage(10);
BOOST_CHECK_EQUAL(myMovingAverage(), 10);
}
}
BOOST_AUTO_TEST_CASE( MovAvValueTest ) {
const int LEN = 10;
MovingAverage<int, LEN> myMovingAverage;
for (unsigned int i = 0; i < LEN; i++) {
myMovingAverage(i);
BOOST_CHECK_EQUAL(myMovingAverage(), i/2.);
}
}
|
;
; Z88 Small C+ Run Time Library
; Long support functions
;
;
; aralbrec 01/2007
; sped up some more
;
; djm 25/2/99
; Rewritten for size and speed (untested, but should be OK)
;
; djm 22/3/99 Unsigned version
PUBLIC l_long_asr_u
; Shift primary (on stack) right by secondary,
; We can only shift a maximum of 32 bits (or so), so the counter can
; go in c
.l_long_asr_u
pop ix
ld a,l ;temporary store for counter
pop hl
pop de
or a
jr z, done
ld b,a
ld a,e ; primary = dahl
.loop
srl d
rra
rr h
rr l
djnz loop
ld e,a
.done
jp (ix)
|
; DV3 java HD format 1.01 @ W. Lenerz 2020
;
; 2020-04-08 1.01 Changed for new ddf_mname definition (length word) (wl)
; based on
; DV3 QXL Floppy Disk Format (actually HD format) 1993 Tony Tebby
section dv3
xdef hd_mformat
xref hd_hold
xref hd_release
xref hd_fchk
xref dv3_slen
xref gu_achp0
xref gu_rchp
xref cv_decil
include 'dev8_keys_err'
include 'dev8_dv3_keys'
include 'dev8_dv3_hd_keys'
include 'dev8_mac_assert'
include 'dev8_keys_java'
;+++
; This routine formats a medium
;
; d0 cr format type / error code
; d1 cr format dependent flag or zero / good sectors
; d2 r total sectors
; d7 c p drive ID / number
; a3 c p linkage block
; a4 c p drive definition
;
; status return standard
;---
hd_mformat
hmf.reg reg d3/d4/d5/a0/a1/a2/a5
movem.l hmf.reg,-(sp)
hmf_wstart
jsr hd_hold
bne.s hmf_wstart
move.b #ddf.dd,ddf_density(a4) ; set density
moveq #jta.qslen,d0
dc.w jva.trpa ; query sector length, return in D5
move.b d5,ddf_slflag(a4) ; set sector length flag
jsr dv3_slen
clr.l ddf_psoff(a4) ; set base of partition
lea ddf_mname(a4),a0
; jsr hd_fchk ; check format permission (asks for user input in channel 0)
; bne.s hmf_exit
lea ddf_mname(a4),a0
move.w #4,(a0)
move.l #'WIN0',2(a0) ; blat name
add.b d7,5(a0)
moveq #jta.frmt,d0 ; format drive
dc.w jva.trpa ; do it (create container of D1 megabytes)
; nbr of sectors returned in d2, also sets Z flag
bne.s hmf_fmtf ; oops
clr.l -(sp) ; no 4096 byte
clr.l -(sp) ; no 2048 byte
clr.l -(sp) ; no 1024 byte
move.l d2,-(sp) ; sectors per track !!
clr.l -(sp) ; no 256 byte
clr.l -(sp) ; no 128 byte
clr.l -(sp) ; no cylinders / heads
move.l sp,a0
jsr ddf_fselect(a4) ; select format (gets to dv3_qlf_fsel)
add.w #7*4,sp
bne.s hmf_exit ; ... oops
moveq #ddf.full,d0 ; ... the only type of format we can do
sub.l a0,a0
jsr ddf_format(a4) ; so do it! gets to qlf_ftwa_asm
st ddf_slbl(a4) ; set slave block range
hmf_exit
jsr hd_release
movem.l (sp)+,hmf.reg
tst.l d0
rts
hmf_fmtf
moveq #err.fmtf,d0
bra.s hmf_exit
hmf_inam
moveq #err.inam,d0
bra.s hmf_exit
end
|
; A113646: a(n) is the smallest composite integer which is >= n.
; 4,4,4,4,6,6,8,8,9,10,12,12,14,14,15,16,18,18,20,20,21,22,24,24,25,26,27,28,30,30,32,32,33,34,35,36,38,38,39,40,42,42,44,44,45,46,48,48,49,50,51,52,54,54,55,56,57,58,60,60,62,62,63,64,65,66,68,68,69,70,72,72,74,74,75,76,77,78,80,80,81,82,84,84,85,86,87,88,90,90,91,92,93,94,95,96,98,98,99,100
max $0,2
mov $1,$0
seq $1,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
add $0,$1
add $0,1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r15
push %r8
push %r9
push %rbp
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x2977, %rsi
nop
nop
nop
nop
and $40464, %rdx
mov (%rsi), %r15
nop
sub %r9, %r9
lea addresses_normal_ht+0x9837, %rbp
nop
nop
add %r8, %r8
vmovups (%rbp), %ymm6
vextracti128 $0, %ymm6, %xmm6
vpextrq $1, %xmm6, %rcx
nop
nop
and $23345, %r8
lea addresses_WC_ht+0x1dc37, %r8
nop
nop
nop
nop
nop
cmp %rbp, %rbp
movups (%r8), %xmm4
vpextrq $0, %xmm4, %rdx
nop
nop
xor %rcx, %rcx
lea addresses_UC_ht+0x8837, %rsi
lea addresses_A_ht+0x16947, %rdi
clflush (%rsi)
sub %rbp, %rbp
mov $19, %rcx
rep movsw
nop
nop
nop
nop
and %rdx, %rdx
lea addresses_D_ht+0xa037, %rsi
lea addresses_A_ht+0x1e337, %rdi
clflush (%rsi)
nop
nop
nop
and %r8, %r8
mov $117, %rcx
rep movsl
nop
nop
nop
nop
inc %r9
lea addresses_D_ht+0x837, %rsi
lea addresses_UC_ht+0x15ac7, %rdi
nop
nop
nop
nop
nop
add $46996, %r15
mov $61, %rcx
rep movsq
sub $64503, %rdx
lea addresses_WC_ht+0x19237, %rbp
nop
nop
nop
nop
and $58694, %rsi
mov (%rbp), %ecx
nop
nop
nop
nop
nop
xor %rbp, %rbp
lea addresses_normal_ht+0x7637, %r9
nop
nop
add %r8, %r8
movb (%r9), %r15b
nop
nop
nop
nop
add %rdx, %rdx
lea addresses_A_ht+0x14edb, %rsi
lea addresses_WT_ht+0x5837, %rdi
nop
nop
nop
xor %r9, %r9
mov $76, %rcx
rep movsq
nop
nop
xor %r9, %r9
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbp
pop %r9
pop %r8
pop %r15
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r13
push %r9
push %rbx
push %rdi
push %rdx
// Load
mov $0x485d5c0000000437, %r9
nop
nop
nop
sub $55792, %r13
mov (%r9), %rbx
nop
nop
nop
nop
nop
add %rdi, %rdi
// Store
lea addresses_D+0x8437, %r9
nop
nop
nop
cmp %r12, %r12
mov $0x5152535455565758, %rbx
movq %rbx, %xmm5
movups %xmm5, (%r9)
nop
nop
nop
nop
xor $58723, %r12
// Faulty Load
mov $0x485d5c0000000437, %r12
nop
nop
add $28197, %r13
mov (%r12), %r11
lea oracles, %r13
and $0xff, %r11
shlq $12, %r11
mov (%r13,%r11,1), %r11
pop %rdx
pop %rdi
pop %rbx
pop %r9
pop %r13
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 7}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_NC', 'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 4}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 10}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 9}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 2, 'type': 'addresses_A_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 8, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_A_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_UC_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 9}}
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 7}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 10, 'type': 'addresses_WT_ht'}}
{'b8': 131, '26': 125, '66': 131, '64': 116, '08': 100, 'ae': 153, '2a': 121, '9e': 134, 'b2': 144, '58': 5183, 'f6': 156, '84': 113, '68': 132, 'a6': 117, '98': 128, 'd2': 117, 'c2': 134, 'a2': 120, 'b0': 125, 'a4': 141, '44': 124, '56': 125, '9c': 132, 'ca': 140, '4e': 138, '6c': 141, '48': 138, 'e8': 145, 'c8': 128, 'ba': 127, 'f8': 157, '92': 139, 'e4': 145, 'de': 121, '12': 122, '8a': 131, 'cc': 139, 'fe': 128, '94': 134, '60': 127, '1c': 120, 'e0': 122, '4a': 120, '06': 108, '5a': 106, 'c6': 165, 'a0': 130, 'ec': 136, '28': 150, '70': 126, 'aa': 125, '24': 111, '2c': 119, '50': 128, '34': 122, '1e': 107, 'b6': 123, '18': 130, '0e': 113, '52': 116, '3a': 129, '82': 133, 'c4': 146, '40': 123, '80': 121, '78': 120, '96': 123, '30': 126, '2e': 120, '86': 143, '14': 137, '3e': 135, 'f4': 148, 'be': 136, '76': 136, 'fa': 156, '62': 113, '42': 121, '02': 111, '38': 151, 'b4': 118, 'dc': 123, '20': 130, '46': 128, 'e6': 139, '72': 122, 'd0': 123, 'ee': 132, 'ea': 131, '6e': 160, '04': 134, 'bc': 137, 'd8': 137, '7c': 128, 'fc': 142, '54': 100, '32': 131, '0c': 137, '3c': 135, 'e2': 131, '16': 99, '0a': 119, '6a': 136, '10': 129, 'a8': 116, '9a': 147, 'd6': 149, 'f2': 153, '8e': 137, '7a': 119, '74': 131, 'ac': 129, 'c0': 145, 'da': 132, '7e': 138, 'ce': 134, '88': 123, '8c': 105, '4c': 101, 'd4': 143, '36': 133, '90': 133, '22': 119, '00': 276, '1a': 139, '5c': 125, '5e': 144, 'f0': 150}
f4 58 90 cc 58 92 58 5c be c8 3e 58 ea 58 f8 58 2a 58 ce 58 58 58 ba 58 32 4c 58 ce 58 c0 58 58 4e 58 1c 58 58 d6 58 44 0e 58 20 58 58 58 98 58 58 58 58 58 ec 0e b6 50 58 82 14 02 40 2e 3e f0 dc 58 f8 58 58 56 8c 58 aa 7c 58 b4 e2 58 3e 12 82 58 3a 06 6a 7e 68 0a 82 7e 58 96 a8 0a 3c 2c 0e d8 58 b0 58 12 cc 58 a2 c0 be 58 ac 4e 58 1a 18 5e f4 58 58 9a 1a 58 e0 58 58 04 b0 42 5c 50 6a 9a 9c fe 58 e0 20 9a 58 e4 e0 00 ca 58 3c 28 d0 e4 70 90 3e 60 c6 22 2a fa ac f6 58 98 02 f4 aa 70 58 be 34 58 f2 2e aa 58 94 54 b6 1c 58 1a 1e 12 18 68 5a 00 58 b6 58 28 c4 58 54 c8 5a ca fa 58 aa ec 1a 74 58 6c 0e 3e 58 bc 26 12 58 5e 78 00 6e 58 9a 58 8e 58 a2 58 92 7e 44 e8 58 42 58 ae a2 32 c2 58 d8 58 4e 58 7c 1c 4c 3e 7a 58 e4 58 5a 22 0e 58 d0 58 ea 58 f0 58 ba 9e 58 1a b2 ca 58 48 58 58 c6 58 ee 58 9e 58 64 fc 58 58 3c 58 6e 7a 00 84 3a 7e 58 58 58 ae 9c 58 58 84 58 66 e6 58 58 58 e0 58 58 40 58 58 60 58 ea 58 bc 58 be 6a 58 ac 58 58 58 26 58 68 fe 58 30 14 26 58 54 58 52 88 58 58 58 58 6a 58 58 30 86 58 d8 58 9c 58 58 14 58 58 58 12 b2 34 26 e0 58 d2 58 bc 28 92 36 58 c6 58 0e 28 7c 58 58 50 de 8a cc 62 f2 58 74 92 d2 24 58 be 58 d4 a8 ae be f2 aa da 12 58 aa 0a 3c 58 18 58 32 32 1e 60 58 18 58 58 b4 3c 46 7c 04 50 98 58 06 58 fa 00 58 9a 58 58 d4 58 2a 58 58 58 24 58 c2 58 58 58 58 5c 64 58 d4 58 5a 58 ec 58 e8 58 e8 58 6c ca 58 4e 58 32 0c 6e 2e 58 4e 32 a8 58 e6 2e fa 68 58 0e f0 58 58 58 58 66 58 58 58 24 58 f8 58 0a 58 00 08 5c cc 58 7c 58 58 58 9a 58 58 fe e2 58 a4 f6 58 58 06 58 58 58 ae 08 58 58 76 58 58 58 6e 58 6c 8a 62 72 58 b2 12 58 58 7e cc 58 a4 58 58 6c 94 58 92 2e 58 58 1e d4 90 44 58 42 c8 70 00 58 58 58 86 94 58 58 8a c4 f4 f2 92 0a 92 58 dc 8c d4 38 1c b4 2a 9c fe 3a 2e 7a 58 22 1a d0 d0 00 b8 82 3c 72 b8 40 58 20 c8 44 94 f4 d6 14 72 3a 58 aa f0 58 82 78 92 58 8c 40 58 cc 98 86 58 86 d0 c4 58 5a 58 86 4c 94 58 c6 c2 b6 72 10 58 50 f2 58 58 58 58 58 54 76 58 6a 8a 62 ce 58 e6 58 56 f0 58 ea 58 58 5c 56 92 f6 58 58 de 58 58 40 48 58 58 f2 58 58 64 26 c0 40 fe 58 18 58 58 00 00 66 d0 ce 58 14 80 74 c2 58 38 28 ba cc 6c 58 60 58 c2 20 48 58 08 00 fe fe 34 aa 9e 58 c0 82 6a 2e 38 84 c4 0e ca f4 5a 02 ca fc c6 58 26 42 58 4a ee 90 3a 58 ca 68 ce 22 32 f8 58 58 58 58 58 ac 26 58 66 58 58 58 58 58 04 20 a0 58 76 58 58 14 0c d2 58 58 e2 52 64 2a 1a b8 58 a4 62 a2 1e 10 58 c4 58 ba 58 8c f2 58 fa 58 88 58 26 9c 58 58 58 06 58 aa a6 58 fa 58 00 2e 84 58 b4 d6 58 ec 84 1c d8 b6 78 58 88 fa d0 48 48 1a 38 08 74 50 5a da 56 62 58 24 be b6 b0 e2 c8 5e 64 58 86 20 94 58 1e 6a a2 8e 58 c4 b8 34 b0 ee 58 a6 58 ba 24 58 04 6e 74 16 5e 58 2a 58 26 58 14 74 28 18 22 58 50 06 e2 58 88 06 6c 06 72 bc da 58 42 a8 b4 bc e2 58 f2 58 1a 58 ea 58 58 9e 14 70 58 b8 3e 46 88 3a f6 58 f6 58 d6 58 e0 58 00 0a 9a 70 50 0a fa 58 46 5a de 58 9e b4 58 cc 58 32 c6 58 32 58 ca 58 da 58 58 da 58 f2 58 58 d6 58 44 04 10 b2 9e 94 58 7a 1c bc e0 58 3e c8 58 58 dc 58 52 b2 18 d4 58 04 58 a2 70 58 26 28 f0 58 58 ce ce 58 e0 98 58 58 fe 08 1c 58 a4 ea 58 78 ae a0 90 4e cc be 58 6e
*/
|
.size 8000
.text@60
pop af
ldff a, (80)
inc a
ldff(80), a
ei
jp lprint
.text@100
jp lbegin
.data@143
80
.text@150
lbegin:
ld b, 90
call lwaitly_b
xor a, a
ldff(40), a
ld bc, 7a00
ld hl, 8000
ld d, 00
lbegin_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lbegin_copytiles
xor a, a
ld(9800), a
ld(9801), a
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
ld a, 10
ldff(00), a
ldff(ff), a
xor a, a
ldff(0f), a
ldff(80), a
ldff(81), a
ei
jp lprint
.text@7000
lprint:
ld b, 90
lprint_waitly90:
ldff a, (44)
cmp a, b
jrnz lprint_waitly90
ldff a, (80)
rrca
rrca
rrca
rrca
and a, 0f
ld(9800), a
ldff a, (80)
and a, 0f
ld(9801), a
ldff a, (00)
ld b, a
rrca
rrca
rrca
rrca
and a, 0f
ld(9802), a
ld a, b
and a, 0f
ld(9803), a
ldff a, (81)
inc a
ldff(81), a
jrnz lprint
ld a, b
xor a, 30
ldff(00), a
jr lprint
.text@7400
lwaitly_b:
ldff a, (44)
cmp a, b
jrnz lwaitly_b
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
00 00 08 08 22 22 41 41
7f 7f 41 41 41 41 41 41
00 00 7e 7e 41 41 41 41
7e 7e 41 41 41 41 7e 7e
00 00 3e 3e 41 41 40 40
40 40 40 40 41 41 3e 3e
00 00 7e 7e 41 41 41 41
41 41 41 41 41 41 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 40 40
|
/* stuff needed for libgcc on win32.
*
* Copyright (C) 1996, 1998, 2001, 2003 Free Software Foundation, Inc.
* Written By Steve Chamberlain
*
* This file is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any
* later version.
*
* In addition to the permissions in the GNU General Public License, the
* Free Software Foundation gives you unlimited permission to link the
* compiled version of this file with other programs, and to distribute
* those programs without any restriction coming from the use of this
* file. (The General Public License restrictions do apply in other
* respects; for example, they cover modification of the file, and
* distribution when not linked into another program.)
*
* This file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* As a special exception, if you link this library with files
* compiled with GCC to produce an executable, this does not cause
* the resulting executable to be covered by the GNU General Public License.
* This exception does not however invalidate any other reasons why
* the executable file might be covered by the GNU General Public License.
*/
#ifdef L_chkstk
/* Function prologue calls _alloca to probe the stack when allocating more
than CHECK_STACK_LIMIT bytes in one go. Touching the stack at 4K
increments is necessary to ensure that the guard pages used
by the OS virtual memory manger are allocated in correct sequence. */
.global ___chkstk
.global __alloca
/* LLVM LOCAL begin mainline */
#ifndef _WIN64
___chkstk:
__alloca:
pushl %ecx /* save temp */
leal 8(%esp), %ecx /* point past return addr */
cmpl $0x1000, %eax /* > 4k ?*/
jb Ldone
Lprobe:
subl $0x1000, %ecx /* yes, move pointer down 4k*/
orl $0x0, (%ecx) /* probe there */
subl $0x1000, %eax /* decrement count */
cmpl $0x1000, %eax
ja Lprobe /* and do it again */
Ldone:
subl %eax, %ecx
orl $0x0, (%ecx) /* less than 4k, just peek here */
movl %esp, %eax /* save old stack pointer */
movl %ecx, %esp /* decrement stack */
movl (%eax), %ecx /* recover saved temp */
movl 4(%eax), %eax /* recover return address */
/* Push the return value back. Doing this instead of just
jumping to %eax preserves the cached call-return stack
used by most modern processors. */
pushl %eax
ret
#else
/* __alloca is a normal function call, which uses %rcx as the argument. And stack space
for the argument is saved. */
__alloca:
movq %rcx, %rax
addq $0x7, %rax
andq $0xfffffffffffffff8, %rax
popq %rcx /* pop return address */
popq %r10 /* Pop the reserved stack space. */
movq %rsp, %r10 /* get sp */
cmpq $0x1000, %rax /* > 4k ?*/
jb Ldone_alloca
Lprobe_alloca:
subq $0x1000, %r10 /* yes, move pointer down 4k*/
orq $0x0, (%r10) /* probe there */
subq $0x1000, %rax /* decrement count */
cmpq $0x1000, %rax
ja Lprobe_alloca /* and do it again */
Ldone_alloca:
subq %rax, %r10
orq $0x0, (%r10) /* less than 4k, just peek here */
movq %r10, %rax
subq $0x8, %r10 /* Reserve argument stack space. */
movq %r10, %rsp /* decrement stack */
/* Push the return value back. Doing this instead of just
jumping to %rcx preserves the cached call-return stack
used by most modern processors. */
pushq %rcx
ret
/* ___chkstk is a *special* function call, which uses %rax as the argument.
We avoid clobbering the 4 integer argument registers, %rcx, %rdx,
%r8 and %r9, which leaves us with %rax, %r10, and %r11 to use. */
___chkstk:
addq $0x7, %rax /* Make sure stack is on alignment of 8. */
andq $0xfffffffffffffff8, %rax
popq %r11 /* pop return address */
movq %rsp, %r10 /* get sp */
cmpq $0x1000, %rax /* > 4k ?*/
jb Ldone
Lprobe:
subq $0x1000, %r10 /* yes, move pointer down 4k*/
orl $0x0, (%r10) /* probe there */
subq $0x1000, %rax /* decrement count */
cmpq $0x1000, %rax
ja Lprobe /* and do it again */
Ldone:
subq %rax, %r10
orl $0x0, (%r10) /* less than 4k, just peek here */
movq %r10, %rsp /* decrement stack */
/* Push the return value back. Doing this instead of just
jumping to %r11 preserves the cached call-return stack
used by most modern processors. */
pushq %r11
ret
#endif
/* LLVM LOCAL end mainline */
#endif
|
//+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1994.
//
// File: stalloc.cxx
//
// Contents: CStackAllocator
//
// History: 29-Sep-94 DrewB Created
//
// Notes: Loosely based on BobDay's original PSTACK implementation
//
//----------------------------------------------------------------------------
#include "headers.cxx"
#pragma hdrstop
// Pad a count to the given alignment
// Alignment must be 2^n-1
#define ALIGN_CB(cb, align) \
(((cb)+(align)) & ~(align))
//+---------------------------------------------------------------------------
//
// Structure: SStackBlock (sb)
//
// Purpose: Header information for stack blocks
//
// History: 29-Sep-94 DrewB Created
//
//----------------------------------------------------------------------------
struct SStackBlock
{
DWORD dwNextBlock;
DWORD dwStackTop;
};
#define BLOCK_OVERHEAD (sizeof(SStackBlock))
#define BLOCK_START(mem) ((mem)+BLOCK_OVERHEAD)
#define BLOCK_AVAILABLE(cb) ((cb)-BLOCK_OVERHEAD)
//+---------------------------------------------------------------------------
//
// Function: CStackAllocator::CStackAllocator, public
//
// Arguments: [pmm] - Memory model to use
// [cbBlock] - Size of chunk to allocate when necessary
// [cbAlignment] - Alignment size, must be 2^N
//
// History: 29-Sep-94 DrewB Created
//
//----------------------------------------------------------------------------
CStackAllocator::CStackAllocator(CMemoryModel *pmm,
DWORD cbBlock,
DWORD cbAlignment)
{
thkAssert(BLOCK_AVAILABLE(cbBlock) > 0);
// Ensure that the alignment is a power of two
thkAssert((cbAlignment & (cbAlignment-1)) == 0);
// Store alignment - 1 since that's the actual value we need for
// alignment computations
_cbAlignment = cbAlignment-1;
// Ensure that overhead and tracking will not affect alignment
thkAssert(ALIGN_CB(BLOCK_OVERHEAD, _cbAlignment) == BLOCK_OVERHEAD &&
ALIGN_CB(sizeof(SStackMemTrace), _cbAlignment) ==
sizeof(SStackMemTrace));
_pmm = pmm;
_cbBlock = cbBlock;
_dwBlocks = 0;
_dwCurrent = 0;
_cbAvailable = 0;
_psaNext = NULL;
_fActive = TRUE;
}
//+---------------------------------------------------------------------------
//
// Member: CStackAllocator::~CStackAllocator, public virtual
//
// History: 29-Sep-94 DrewB Created
//
//----------------------------------------------------------------------------
CStackAllocator::~CStackAllocator(void)
{
Reset();
}
//+---------------------------------------------------------------------------
//
// Function: CStackAllocator::Alloc, public
//
// Synopsis: Allocates a chunk of memory from the stack
//
// Arguments: [cb] - Amount of memory to allocate
//
// Returns: Pointer to memory or NULL
//
// History: 29-Sep-94 DrewB Created
//
//----------------------------------------------------------------------------
DWORD CStackAllocator::Alloc(DWORD cb)
{
DWORD dwMem;
thkAssert(cb > 0);
// Round size up to maintain alignment of stack
cb = ALIGN_CB(cb, _cbAlignment);
#if DBG == 1
// Reserve space to record caller
cb += sizeof(SStackMemTrace);
#endif
thkAssert(cb <= BLOCK_AVAILABLE(_cbBlock));
// Check to see if the current block can hold the new allocation
if (cb > _cbAvailable)
{
DWORD dwBlock;
SStackBlock UNALIGNED *psb;
// It's too big, so allocate a new block
dwBlock = _pmm->AllocMemory(_cbBlock);
if (dwBlock == 0)
{
return 0;
}
if (_dwBlocks != 0)
{
// Update current top block
psb = (SStackBlock UNALIGNED *)
_pmm->ResolvePtr(_dwBlocks, sizeof(SStackBlock));
psb->dwStackTop = _dwCurrent;
_pmm->ReleasePtr(_dwBlocks);
}
// Make the new block the top block
psb = (SStackBlock UNALIGNED *)
_pmm->ResolvePtr(dwBlock, sizeof(SStackBlock));
psb->dwNextBlock = _dwBlocks;
_dwBlocks = dwBlock;
_pmm->ReleasePtr(dwBlock);
_dwCurrent = BLOCK_START(dwBlock);
_cbAvailable = BLOCK_AVAILABLE(_cbBlock);
}
thkAssert(_cbAvailable >= cb);
dwMem = _dwCurrent;
_dwCurrent += cb;
_cbAvailable -= cb;
#if DBG == 1
void *pvMem;
// Fill memory to show reuse problems
pvMem = _pmm->ResolvePtr(dwMem, cb);
memset(pvMem, 0xED, cb);
_pmm->ReleasePtr(dwMem);
#endif
#if DBG == 1
SStackMemTrace UNALIGNED *psmt;
psmt = (SStackMemTrace UNALIGNED *)
_pmm->ResolvePtr(_dwCurrent-sizeof(SStackMemTrace),
sizeof(SStackMemTrace));
psmt->cbSize = cb-sizeof(SStackMemTrace);
//
// On RISC platforms, psmt points to an unaligned structure.
// Use a temp variable so we don't get an alignment fault
// when RtlGetCallersAddress returns the value.
//
void *pv;
void *pvCaller;
RtlGetCallersAddress(&pvCaller, &pv);
psmt->pvCaller = pvCaller;
thkDebugOut((DEB_MEMORY, "Stack: %p alloc 0x%08lX:%3d, avail %d\n",
psmt->pvCaller, dwMem, cb, _cbAvailable));
_pmm->ReleasePtr(_dwCurrent-sizeof(SStackMemTrace));
#endif
return dwMem;
}
//+---------------------------------------------------------------------------
//
// Function: CStackAllocator::Free, public
//
// Synopsis: Frees allocated memory
//
// Arguments: [dwMem] - Memory
// [cb] - Amount of memory allocated
//
// History: 29-Sep-94 DrewB Created
//
//----------------------------------------------------------------------------
void CStackAllocator::Free(DWORD dwMem, DWORD cb)
{
thkAssert(dwMem != 0);
thkAssert(cb > 0);
// Round size up to maintain alignment of stack
cb = ALIGN_CB(cb, _cbAlignment);
#if DBG == 1
cb += sizeof(SStackMemTrace);
#endif
thkAssert(cb <= BLOCK_AVAILABLE(_cbBlock));
#if DBG == 1
void *pvCaller;
void *pv;
RtlGetCallersAddress(&pvCaller, &pv);
thkDebugOut((DEB_MEMORY, "Stack: %p frees 0x%08lX:%3d, avail %d\n",
pvCaller, dwMem, cb, _cbAvailable));
#endif
#if DBG == 1
if (_dwCurrent-cb != dwMem)
{
thkDebugOut((DEB_ERROR, "Free of %d:%d is not TOS (0x%08lX)\n",
dwMem, cb, _dwCurrent));
thkAssert(_dwCurrent-cb == dwMem);
}
#endif
_dwCurrent -= cb;
_cbAvailable += cb;
#if DBG == 1
void *pvMem;
// Fill memory to show reuse problems
pvMem = _pmm->ResolvePtr(dwMem, cb);
memset(pvMem, 0xDD, cb);
_pmm->ReleasePtr(dwMem);
#endif
if (_dwCurrent == BLOCK_START(_dwBlocks))
{
SStackBlock UNALIGNED *psb;
DWORD dwBlock;
// If we've just freed up an entire block and it's not the
// only block for the stack, free the block itself and
// restore stack state from the next block
// We keep the first block around forever to avoid memory
// thrashing
psb = (SStackBlock UNALIGNED *)
_pmm->ResolvePtr(_dwBlocks, sizeof(SStackBlock));
dwBlock = psb->dwNextBlock;
_pmm->ReleasePtr(_dwBlocks);
if (dwBlock != 0)
{
_pmm->FreeMemory(_dwBlocks);
_dwBlocks = dwBlock;
psb = (SStackBlock UNALIGNED *)
_pmm->ResolvePtr(_dwBlocks, sizeof(SStackBlock));
_dwCurrent = psb->dwStackTop;
_cbAvailable = _cbBlock-(_dwCurrent-_dwBlocks);
_pmm->ReleasePtr(_dwBlocks);
}
}
}
//+---------------------------------------------------------------------------
//
// Member: CStackAllocator::Reset, public
//
// Synopsis: Releases all memory in the stack
//
// History: 29-Sep-94 DrewB Created
//
//----------------------------------------------------------------------------
void CStackAllocator::Reset(void)
{
DWORD dwBlock;
SStackBlock UNALIGNED *psb;
while (_dwBlocks != 0)
{
psb = (SStackBlock UNALIGNED *)
_pmm->ResolvePtr(_dwBlocks, sizeof(SStackBlock));
dwBlock = psb->dwNextBlock;
_pmm->ReleasePtr(_dwBlocks);
_pmm->FreeMemory(_dwBlocks);
_dwBlocks = dwBlock;
}
_dwCurrent = 0;
_cbAvailable = 0;
}
//+---------------------------------------------------------------------------
//
// Function: CStackAllocator::RecordState, public debug
//
// Synopsis: Records the current state of the stack
//
// Arguments: [psr] - Storage space for information
//
// Modifies: [psr]
//
// History: 28-Apr-94 DrewB Created
//
//----------------------------------------------------------------------------
#if DBG == 1
void CStackAllocator::RecordState(SStackRecord *psr)
{
psr->dwStackPointer = _dwCurrent;
psr->dwThreadId = GetCurrentThreadId();
}
#endif
//+---------------------------------------------------------------------------
//
// Function: CStackAllocator::CheckState, public debug
//
// Synopsis: Checks recorded information about the stack against its
// current state
//
// Arguments: [psr] - Recorded information
//
// History: 28-Apr-94 DrewB Created
//
//----------------------------------------------------------------------------
#if DBG == 1
void CStackAllocator::CheckState(SStackRecord *psr)
{
thkAssert(psr->dwThreadId == GetCurrentThreadId());
if ((psr->dwStackPointer != 0 && psr->dwStackPointer != _dwCurrent) ||
(psr->dwStackPointer == 0 &&
_dwCurrent != 0 && _dwCurrent != BLOCK_START(_dwBlocks)))
{
thkDebugOut((DEB_ERROR, "Stack alloc change: 0x%08lX to 0x%08lX\n",
psr->dwStackPointer, _dwCurrent));
if (_dwCurrent > BLOCK_START(_dwBlocks))
{
SStackMemTrace UNALIGNED *psmt;
psmt = (SStackMemTrace UNALIGNED *)
_pmm->ResolvePtr(_dwCurrent-sizeof(SStackMemTrace),
sizeof(SStackMemTrace));
thkDebugOut((DEB_ERROR, "Top alloc: %d bytes by %p\n",
psmt->cbSize, psmt->pvCaller));
_pmm->ReleasePtr(_dwCurrent-sizeof(SStackMemTrace));
}
thkAssert(!((psr->dwStackPointer != 0 &&
psr->dwStackPointer != _dwCurrent) ||
(psr->dwStackPointer == 0 &&
_dwCurrent != 0 ||
_dwCurrent != BLOCK_START(_dwBlocks))));
}
}
#endif
|
.gba
.create "output.bin",0
.arm
// Test message too long (> 120)
.msg "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901"
// Test non-ASCII characters
.msg "é"
.thumb
// Test message too long (> 120)
.msg "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901"
// Test non-ASCII characters
.msg "é"
.close
|
; A320877: a(n) = 1 + Sum_{k=1..n} 2^prime(k).
; 1,5,13,45,173,2221,10413,141485,665773,9054381,545925293,2693408941,140132362413,2339155617965,11135248640173,151872736995501,9159071991736493,585619824295159981,2891462833508853933,150465415423185266861,2511648656858007873709,11956381622597298301101
mov $1,$0
bin $1,$0
lpb $0
sub $0,$1
mov $2,$0
max $2,0
seq $2,34785 ; a(n) = 2^(n-th prime).
add $3,$2
lpe
mov $0,$3
add $0,1
|
; A174889: First column of A174888.
; 1,0,0,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,0,0,0,1,1,1,1,1,0,1,1,1,0,0,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,0,0,1,1,0,0,1,0,1,1,1,1
mov $1,1
cal $0,8683 ; Möbius (or Moebius) function mu(n). mu(1) = 1; mu(n) = (-1)^k if n is the product of k different primes; otherwise mu(n) = 0.
bin $1,$0
|
%ifdef CONFIG
{
"RegData": {
"RAX": "0x4142434445464748",
"RDX": "0x0",
"RDI": "0xE0000018",
"RSI": "0xE0000008"
},
"MemoryRegions": {
"0x100000000": "4096"
}
}
%endif
mov rdx, 0xe0000000
mov rax, 0x4142434445464748
mov [rdx + 8 * 0], rax
mov rax, 0x5152535455565758
mov [rdx + 8 * 1], rax
mov rax, 0x0
mov [rdx + 8 * 2], rax
mov [rdx + 8 * 3], rax
lea rdi, [rdx + 8 * 2]
lea rsi, [rdx + 8 * 0]
cld
mov rcx, 4
repne movsw ; rdi <- rsi
mov rax, [rdx + 8 * 2]
mov rdx, [rdx + 8 * 3]
hlt
|
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "UMGEditorPrivatePCH.h"
#include "SPaletteView.h"
#include "UMGEditorActions.h"
#include "PreviewScene.h"
#include "SceneViewport.h"
#include "BlueprintEditor.h"
#include "DecoratedDragDropOp.h"
#include "WidgetTemplateDragDropOp.h"
#include "WidgetTemplate.h"
#include "WidgetTemplateClass.h"
#include "WidgetTemplateBlueprintClass.h"
#include "Developer/HotReload/Public/IHotReload.h"
#include "AssetRegistryModule.h"
#include "SSearchBox.h"
#include "WidgetBlueprintCompiler.h"
#include "WidgetBlueprintEditorUtils.h"
#include "Blueprint/UserWidget.h"
#include "WidgetBlueprint.h"
#include "ObjectEditorUtils.h"
#define LOCTEXT_NAMESPACE "UMG"
class SPaletteViewItem : public SCompoundWidget
{
public:
SLATE_BEGIN_ARGS(SPaletteViewItem) {}
/** The current text to highlight */
SLATE_ATTRIBUTE(FText, HighlightText)
SLATE_END_ARGS()
/**
* Constructs this widget
*
* @param InArgs Declaration from which to construct the widget
*/
void Construct(const FArguments& InArgs, TSharedPtr<FWidgetTemplate> InTemplate)
{
Template = InTemplate;
ChildSlot
[
SNew(SHorizontalBox)
.Visibility(EVisibility::Visible)
.ToolTip(Template->GetToolTip())
+ SHorizontalBox::Slot()
.AutoWidth()
.VAlign(VAlign_Center)
[
SNew(SImage)
.ColorAndOpacity(FLinearColor(1, 1, 1, 0.5))
.Image(Template->GetIcon())
]
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2, 0, 0, 0)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(Template->Name)
.HighlightText(InArgs._HighlightText)
]
];
}
virtual FReply OnMouseButtonDoubleClick( const FGeometry& InMyGeometry, const FPointerEvent& InMouseEvent ) override
{
return Template->OnDoubleClicked();
}
private:
TSharedPtr<FWidgetTemplate> Template;
};
class FWidgetTemplateViewModel : public FWidgetViewModel
{
public:
virtual ~FWidgetTemplateViewModel()
{
}
virtual FText GetName() const override
{
return Template->Name;
}
virtual FString GetFilterString() const override
{
return Template->Name.ToString();
}
virtual TSharedRef<ITableRow> BuildRow(const TSharedRef<STableViewBase>& OwnerTable) override
{
return SNew(STableRow< TSharedPtr<FWidgetViewModel> >, OwnerTable)
.Padding(2.0f)
.Style(FEditorStyle::Get(), "UMGEditor.PaletteItem")
.OnDragDetected(this, &FWidgetTemplateViewModel::OnDraggingWidgetTemplateItem)
[
SNew(SPaletteViewItem, Template)
.HighlightText(OwnerView, &SPaletteView::GetSearchText)
];
}
FReply OnDraggingWidgetTemplateItem(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent)
{
return FReply::Handled().BeginDragDrop(FWidgetTemplateDragDropOp::New(Template));
}
SPaletteView* OwnerView;
TSharedPtr<FWidgetTemplate> Template;
};
class FWidgetHeaderViewModel : public FWidgetViewModel
{
public:
virtual ~FWidgetHeaderViewModel()
{
}
virtual FText GetName() const override
{
return GroupName;
}
virtual FString GetFilterString() const override
{
// Headers should never be included in filtering to avoid showing a header with all of
// it's widgets filtered out, so return an empty filter string.
return TEXT("");
}
virtual TSharedRef<ITableRow> BuildRow(const TSharedRef<STableViewBase>& OwnerTable) override
{
return SNew(STableRow< TSharedPtr<FWidgetViewModel> >, OwnerTable)
.Style( FEditorStyle::Get(), "UMGEditor.PaletteHeader" )
.Padding(2.0f)
.ShowSelection(false)
[
SNew(STextBlock)
.Text(GroupName)
.Font(FEditorStyle::GetFontStyle("DetailsView.CategoryFontStyle"))
.ShadowOffset(FVector2D(1.0f, 1.0f))
];
}
virtual void GetChildren(TArray< TSharedPtr<FWidgetViewModel> >& OutChildren) override
{
for ( TSharedPtr<FWidgetViewModel>& Child : Children )
{
OutChildren.Add(Child);
}
}
FText GroupName;
TArray< TSharedPtr<FWidgetViewModel> > Children;
};
void SPaletteView::Construct(const FArguments& InArgs, TSharedPtr<FBlueprintEditor> InBlueprintEditor)
{
// Register for events that can trigger a palette rebuild
GEditor->OnBlueprintReinstanced().AddRaw(this, &SPaletteView::OnBlueprintReinstanced);
FEditorDelegates::OnAssetsDeleted.AddSP(this, &SPaletteView::HandleOnAssetsDeleted);
IHotReloadModule::Get().OnHotReload().AddSP(this, &SPaletteView::HandleOnHotReload);
// register for any objects replaced
GEditor->OnObjectsReplaced().AddRaw(this, &SPaletteView::OnObjectsReplaced);
BlueprintEditor = InBlueprintEditor;
UBlueprint* BP = InBlueprintEditor->GetBlueprintObj();
WidgetFilter = MakeShareable(new WidgetViewModelTextFilter(
WidgetViewModelTextFilter::FItemToStringArray::CreateSP(this, &SPaletteView::TransformWidgetViewModelToString)));
FilterHandler = MakeShareable(new PaletteFilterHandler());
FilterHandler->SetFilter(WidgetFilter.Get());
FilterHandler->SetRootItems(&WidgetViewModels, &TreeWidgetViewModels);
FilterHandler->SetGetChildrenDelegate(PaletteFilterHandler::FOnGetChildren::CreateRaw(this, &SPaletteView::OnGetChildren));
SAssignNew(WidgetTemplatesView, STreeView< TSharedPtr<FWidgetViewModel> >)
.ItemHeight(1.0f)
.SelectionMode(ESelectionMode::Single)
.OnGenerateRow(this, &SPaletteView::OnGenerateWidgetTemplateItem)
.OnGetChildren(FilterHandler.ToSharedRef(), &PaletteFilterHandler::OnGetFilteredChildren)
.TreeItemsSource(&TreeWidgetViewModels);
FilterHandler->SetTreeView(WidgetTemplatesView.Get());
ChildSlot
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.Padding(4)
.AutoHeight()
[
SAssignNew(SearchBoxPtr, SSearchBox)
.HintText(LOCTEXT("SearchTemplates", "Search Palette"))
.OnTextChanged(this, &SPaletteView::OnSearchChanged)
]
+ SVerticalBox::Slot()
.FillHeight(1.0f)
[
SNew(SScrollBorder, WidgetTemplatesView.ToSharedRef())
[
WidgetTemplatesView.ToSharedRef()
]
]
];
bRefreshRequested = true;
BuildWidgetList();
LoadItemExpansion();
bRebuildRequested = false;
}
SPaletteView::~SPaletteView()
{
// If the filter is enabled, disable it before saving the expanded items since
// filtering expands all items by default.
if (FilterHandler->GetIsEnabled())
{
FilterHandler->SetIsEnabled(false);
FilterHandler->RefreshAndFilterTree();
}
GEditor->OnBlueprintReinstanced().RemoveAll(this);
FEditorDelegates::OnAssetsDeleted.RemoveAll(this);
IHotReloadModule::Get().OnHotReload().RemoveAll(this);
GEditor->OnObjectsReplaced().RemoveAll( this );
SaveItemExpansion();
}
void SPaletteView::OnSearchChanged(const FText& InFilterText)
{
bRefreshRequested = true;
FilterHandler->SetIsEnabled(!InFilterText.IsEmpty());
WidgetFilter->SetRawFilterText(InFilterText);
SearchBoxPtr->SetError(WidgetFilter->GetFilterErrorText());
SearchText = InFilterText;
}
FText SPaletteView::GetSearchText() const
{
return SearchText;
}
void SPaletteView::LoadItemExpansion()
{
// Restore the expansion state of the widget groups.
for ( TSharedPtr<FWidgetViewModel>& ViewModel : WidgetViewModels )
{
bool IsExpanded;
if ( GConfig->GetBool(TEXT("WidgetTemplatesExpanded"), *ViewModel->GetName().ToString(), IsExpanded, GEditorPerProjectIni) && IsExpanded )
{
WidgetTemplatesView->SetItemExpansion(ViewModel, true);
}
}
}
void SPaletteView::SaveItemExpansion()
{
// Restore the expansion state of the widget groups.
for ( TSharedPtr<FWidgetViewModel>& ViewModel : WidgetViewModels )
{
const bool IsExpanded = WidgetTemplatesView->IsItemExpanded(ViewModel);
GConfig->SetBool(TEXT("WidgetTemplatesExpanded"), *ViewModel->GetName().ToString(), IsExpanded, GEditorPerProjectIni);
}
}
UWidgetBlueprint* SPaletteView::GetBlueprint() const
{
if ( BlueprintEditor.IsValid() )
{
UBlueprint* BP = BlueprintEditor.Pin()->GetBlueprintObj();
return Cast<UWidgetBlueprint>(BP);
}
return NULL;
}
void SPaletteView::BuildWidgetList()
{
// Clear the current list of view models and categories
WidgetViewModels.Reset();
WidgetTemplateCategories.Reset();
// Generate a list of templates
BuildClassWidgetList();
BuildSpecialWidgetList();
// For each entry in the category create a view model for the widget template
for ( auto& Entry : WidgetTemplateCategories )
{
TSharedPtr<FWidgetHeaderViewModel> Header = MakeShareable(new FWidgetHeaderViewModel());
Header->GroupName = FText::FromString(Entry.Key);
for ( auto& Template : Entry.Value )
{
TSharedPtr<FWidgetTemplateViewModel> TemplateViewModel = MakeShareable(new FWidgetTemplateViewModel());
TemplateViewModel->Template = Template;
TemplateViewModel->OwnerView = this;
Header->Children.Add(TemplateViewModel);
}
Header->Children.Sort([] (TSharedPtr<FWidgetViewModel> L, TSharedPtr<FWidgetViewModel> R) { return R->GetName().CompareTo(L->GetName()) > 0; });
WidgetViewModels.Add(Header);
}
// Sort the view models by name
WidgetViewModels.Sort([] (TSharedPtr<FWidgetViewModel> L, TSharedPtr<FWidgetViewModel> R) { return R->GetName().CompareTo(L->GetName()) > 0; });
}
void SPaletteView::BuildClassWidgetList()
{
static const FName DevelopmentStatusKey(TEXT("DevelopmentStatus"));
TMap<FName, TSubclassOf<UUserWidget>> LoadedWidgetBlueprintClassesByName;
auto ActiveWidgetBlueprintClass = GetBlueprint()->GeneratedClass;
FName ActiveWidgetBlueprintClassName = ActiveWidgetBlueprintClass->GetFName();
// Locate all UWidget classes from code and loaded widget BPs
for (TObjectIterator<UClass> ClassIt; ClassIt; ++ClassIt)
{
UClass* WidgetClass = *ClassIt;
if ( FWidgetBlueprintEditorUtils::IsUsableWidgetClass(WidgetClass) )
{
const bool bIsSameClass = WidgetClass->GetFName() == ActiveWidgetBlueprintClassName;
// Check that the asset that generated this class is valid (necessary b/c of a larger issue wherein force delete does not wipe the generated class object)
if ( bIsSameClass )
{
continue;
}
if (WidgetClass->IsChildOf(UUserWidget::StaticClass()))
{
if ( WidgetClass->ClassGeneratedBy )
{
// Track the widget blueprint classes that are already loaded
LoadedWidgetBlueprintClassesByName.Add(WidgetClass->ClassGeneratedBy->GetFName()) = WidgetClass;
}
}
else
{
TSharedPtr<FWidgetTemplateClass> Template = MakeShareable(new FWidgetTemplateClass(WidgetClass));
AddWidgetTemplate(Template);
}
//TODO UMG does not prevent deep nested circular references
}
}
// Locate all widget BP assets (include unloaded)
const FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>(TEXT("AssetRegistry"));
TArray<FAssetData> AllWidgetBPsAssetData;
AssetRegistryModule.Get().GetAssetsByClass(UWidgetBlueprint::StaticClass()->GetFName(), AllWidgetBPsAssetData, true);
FName ActiveWidgetBlueprintName = ActiveWidgetBlueprintClass->ClassGeneratedBy->GetFName();
for (auto& WidgetBPAssetData : AllWidgetBPsAssetData)
{
if (WidgetBPAssetData.AssetName == ActiveWidgetBlueprintName)
{
continue;
}
// If the blueprint generated class was found earlier, pass it to the template
TSubclassOf<UUserWidget> WidgetBPClass = nullptr;
auto LoadedWidgetBPClass = LoadedWidgetBlueprintClassesByName.Find(WidgetBPAssetData.AssetName);
if (LoadedWidgetBPClass)
{
WidgetBPClass = *LoadedWidgetBPClass;
}
auto Template = MakeShareable(new FWidgetTemplateBlueprintClass(WidgetBPAssetData, WidgetBPClass));
AddWidgetTemplate(Template);
}
}
void SPaletteView::BuildSpecialWidgetList()
{
//AddWidgetTemplate(MakeShareable(new FWidgetTemplateButton()));
//AddWidgetTemplate(MakeShareable(new FWidgetTemplateCheckBox()));
//TODO UMG Make this pluggable.
}
void SPaletteView::AddWidgetTemplate(TSharedPtr<FWidgetTemplate> Template)
{
FString Category = Template->GetCategory().ToString();
WidgetTemplateArray& Group = WidgetTemplateCategories.FindOrAdd(Category);
Group.Add(Template);
}
void SPaletteView::OnGetChildren(TSharedPtr<FWidgetViewModel> Item, TArray< TSharedPtr<FWidgetViewModel> >& Children)
{
return Item->GetChildren(Children);
}
TSharedRef<ITableRow> SPaletteView::OnGenerateWidgetTemplateItem(TSharedPtr<FWidgetViewModel> Item, const TSharedRef<STableViewBase>& OwnerTable)
{
return Item->BuildRow(OwnerTable);
}
void SPaletteView::Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime )
{
if ( bRebuildRequested )
{
bRebuildRequested = false;
// Save the old expanded items temporarily
TSet<TSharedPtr<FWidgetViewModel>> ExpandedItems;
WidgetTemplatesView->GetExpandedItems(ExpandedItems);
BuildWidgetList();
// Restore the expansion state
for ( TSharedPtr<FWidgetViewModel>& ExpandedItem : ExpandedItems )
{
for ( TSharedPtr<FWidgetViewModel>& ViewModel : WidgetViewModels )
{
if ( ViewModel->GetName().EqualTo(ExpandedItem->GetName()) )
{
WidgetTemplatesView->SetItemExpansion(ViewModel, true);
}
}
}
}
if (bRefreshRequested)
{
bRefreshRequested = false;
FilterHandler->RefreshAndFilterTree();
}
}
void SPaletteView::TransformWidgetViewModelToString(TSharedPtr<FWidgetViewModel> WidgetViewModel, OUT TArray< FString >& Array)
{
Array.Add(WidgetViewModel->GetFilterString());
}
void SPaletteView::OnObjectsReplaced(const TMap<UObject*, UObject*>& ReplacementMap)
{
//bRefreshRequested = true;
//bRebuildRequested = true;
}
void SPaletteView::OnBlueprintReinstanced()
{
bRebuildRequested = true;
bRefreshRequested = true;
}
void SPaletteView::HandleOnHotReload(bool bWasTriggeredAutomatically)
{
bRebuildRequested = true;
bRefreshRequested = true;
}
void SPaletteView::HandleOnAssetsDeleted(const TArray<UClass*>& DeletedAssetClasses)
{
for (auto DeletedAssetClass : DeletedAssetClasses)
{
if (DeletedAssetClass->IsChildOf(UWidgetBlueprint::StaticClass()))
{
bRebuildRequested = true;
bRefreshRequested = true;
}
}
}
#undef LOCTEXT_NAMESPACE
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r8
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_normal_ht+0xbc01, %rax
nop
sub %r13, %r13
movw $0x6162, (%rax)
nop
nop
nop
xor %r8, %r8
lea addresses_WC_ht+0x2b52, %rsi
lea addresses_normal_ht+0x1d3e1, %rdi
nop
nop
nop
and %r12, %r12
mov $62, %rcx
rep movsb
nop
nop
xor %r8, %r8
lea addresses_normal_ht+0x1ec1, %rsi
lea addresses_A_ht+0xdb61, %rdi
clflush (%rsi)
nop
nop
nop
cmp $28129, %r12
mov $76, %rcx
rep movsw
add $54366, %r8
lea addresses_normal_ht+0x128c9, %r8
and $26045, %rsi
mov (%r8), %rdx
nop
nop
nop
nop
nop
dec %r8
lea addresses_UC_ht+0x19361, %rsi
lea addresses_normal_ht+0x2cfa, %rdi
nop
nop
nop
nop
nop
xor $47104, %r8
mov $59, %rcx
rep movsw
xor $19412, %rax
lea addresses_UC_ht+0x18461, %r8
sub %r12, %r12
movb (%r8), %r13b
nop
nop
nop
nop
nop
and $37290, %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r8
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r8
push %rbp
push %rbx
push %rcx
push %rsi
// Faulty Load
lea addresses_WC+0x16361, %rbp
cmp $31912, %r8
vmovups (%rbp), %ymm2
vextracti128 $0, %ymm2, %xmm2
vpextrq $0, %xmm2, %rcx
lea oracles, %r8
and $0xff, %rcx
shlq $12, %rcx
mov (%r8,%rcx,1), %rcx
pop %rsi
pop %rcx
pop %rbx
pop %rbp
pop %r8
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_WC', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_WC', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 2, 'congruent': 4, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 8, 'congruent': 3, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 1, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'38': 21829}
38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38
*/
|
data segment
welcome db "********************************************************** ",13,10
db "** _ _ _ _ _____ __ __ _ _ ** ",13,10
db "** | | | | /\ | \ | |/ ____| \/ | /\ | \ | | ** +-------+ ",13,10
db "** | |__| | / \ | \| | | __| \ / | / \ | \| | ** | | ",13,10
db "** | __ | / /\ \ | . ` | | |_ | |\/| | / /\ \ | . ` | ** | | ",13,10
db "** | | | |/ ____ \| |\ | |__| | | | |/ ____ \| |\ | ** | O ",13,10
db "** |_| |_/_/ \_\_| \_|\_____|_| |_/_/ \_\_| \_| ** | /|\ ",13,10
db "** _____ __ __ ______ ** | | ",13,10
db "** / ____| /\ | \/ | ____| ** | / \ ",13,10
db "** | | __ / \ | \ / | |__ ** | ",13,10
db "** | | |_ | / /\ \ | |\/| | __| ** +----------+",13,10
db "** | |__| |/ ____ \| | | | |____ ** | | ",13,10
db "** \_____/_/ \_\_| |_|______| ** | |",13,10
db "** ** +----------+",13,10
db "********************************************************** ",13,10
db " ",13,10
db " ",13,10
db " ",13,10
db " ",13,10
db " ---Presents--- ",13,10
db " 19BPS1014 A.L.Viswanath ",13,10
db " 19BPS1010 G.Anurag ",13,10
db " ",13,10
db " ",13,10
db "$"
welcome_message db " HANGMAN - GAME $"
mode_sel db 13,10,13,10,"Select th mode: ",13,10,"1. 1-Player mode ",13,10,"2. 2-Player mode ",13,10,"3. Rapid Mode",13,10,"4. Time-Limit mode$"
sel_opt db 13,10,13,10,"Enter the mode number: $" ;13-for next line,10- carrriage return
type_message db "Type a letter: $"
new_line db 13,10,"$"
win_message db "YOU WIN!$"
win_message1 db "Correct Guesss!!!$"
lose_message db "YOU LOSE!$"
lose_message1 db "OOpss!! out of lives...$"
tie_message db 13,10,13,10,"Tie$"
word db "bollywood$"
discovered_word db 9 dup("_"),"$"
word_size db 9
lives db 5
hits db 0
errors db 0
bell db 7
msg_lives db 13,10,13,10,"Lives: $"
msg_topic db 13,10,13,10,"Enter the Genre: $"
msg_topics db 13,10,13,10,"Genre : $"
topic1 db 50,?,50 dup('$') ;50 is size,? is empty value,fill 50 value with $
msg_fplname db 13,10,13,10,"Please enter the first player's name: $"
fplname db 50,?,50 dup('$')
msg_splname db 13,10,13,10,"Please enter the second player's name: $"
splname db 50,?,50 dup('$')
msg1 db 13,10,13,10,"player 1 name: $"
msg2 db 13,10,13,10,"player 2 name: $"
topic2 db 50,?,50 dup('$')
msg_fplword db 13,10,13,10,"Player1 enter your secret word: $"
fplword db 50,?,50 dup("$")
fplword_len db ?
dis_fplword db 50,?,50 dup("$")
msg_fpl db 13,10,13,10,"Player 1 turn: $",13,10,13,10
msg_splword db 13,10,13,10,"Player2 enter your secret word: $"
splword db 50,?,50 dup("$")
splword_len db ?
dis_splword db 50,?,50 dup("$")
msg_spl db 13,10,13,10,"Player 2 turn: $",13,10,13,10
msg_win1 db 13,10,13,10,"the winner is : $"
msg_score db 13,10,13,10,"Total Score(Out of 10) is : $"
fp_lives db 5
fp_hits db 0
fp_errors db 0
fp_score db 0
sp_lives db 5
sp_hits db 0
sp_errors db 0
sp_score db 0
string1 db "canoe$"
str1_dword db 5 dup("_"),"$"
str1_size db 5h
string2 db "doberman$"
str2_dword db 8 dup("_"),"$"
str2_size db 8h
string3 db "frame$"
str3_dword db 5 dup("_"),"$"
str3_size db 5h
string4 db "banana$"
str4_dword db 6 dup("_"),"$"
str4_size db 6h
string5 db "orange$"
str5_dword db 6 dup("_"),"$"
str5_size db 6h
string6 db "frigate$"
str6_dword db 7 dup("_"),"$"
str6_size db 7h
string7 db "ketchup$"
str7_dword db 7 dup("_"),"$"
str7_size db 7h
string8 db "postal$"
str8_dword db 6 dup("_"),"$"
str8_size db 6h
string9 db "basket$"
str9_dword db 6 dup("_"),"$"
str9_size db 6h
string10 db "cabinet$"
str10_dword db 7 dup("_"),"$"
str10_size db 7h
score db 0
msg_time db 13,10,13,10,"Enter the time-limit :$"
mtime dw ?
cnt dw 0
word1 db "pneumonoultramicroscopicsilicovolcanoconiosis$"
dis_wrd db 45 dup("_"),"$"
wrd_len db 45
data ends
print macro str ;to print the string
lea dx,str
mov ah,09h
int 21h
endm
ring macro bell
mov dl,bell
mov ah,02h
int 21h
endm
type macro num
mov dl,num
mov ah,02h
int 21h
endm
scan macro str ; read a string from keyboard and return to al
lea dx,str
mov ah,0ah
int 21h
endm
check macro lives,errors,word_size,hits
mov bl,lives
mov bh,errors
cmp bl,bh
je game_over
mov bl,word_size
mov bh,hits
cmp bl,bh
je game_win
endm
check1 macro lives,errors,word_size,hits
mov bl,lives
mov bh,errors
cmp bl,bh
je game_over1
mov bl,word_size
mov bh,hits
cmp bl,bh
je game_win1
endm
check2 macro lives,errors,word_size,hits
mov bl,lives
mov bh,errors
cmp bl,bh
je game_over2
mov bl,word_size
mov bh,hits
cmp bl,bh
je game_win2
endm
update macro word,discovered_word,hits,errors
LOCAL update_loop,increment,equals,end_word,end_update ; note: while using macros need to do that if we are calling macros in repeatitions
lea si,word
lea di,discovered_word
mov bx,0
update_loop:
cmp ds:[si],"$"
je end_word
; check if letter is already taken
cmp ds:[di],al
je increment
; check if letter is on the word
cmp ds:[si],al
je equals
increment:
inc si
inc di
jmp update_loop
equals:
mov ds:[di],al
inc hits
mov bx,1
jmp increment
end_word:
cmp bx,1
je end_update
inc errors
end_update:
endm
code segment
start: ; set segment registers
mov ax,data
mov ds,ax
main:
print welcome ; main
mov cx,500
lp: loop lp
call clear_screen
print welcome_message
print mode_sel
print sel_opt
call read_keyboard
cmp al,'1'
je main_loop
cmp al,'2'
je main_loop2
cmp al,'3'
je rapid
cmp al,'4'
je time
main_loop:
call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print discovered_word
print new_line
print new_line
check lives,errors,word_size,hits
print type_message
call read_keyboard
update word,discovered_word,hits,errors
ring bell
call clear_screen
loop main_loop
main_loop2:
call clear_screen ; first player details
print welcome_message
print msg_fplname
scan fplname
print msg1
print fplname+2
print msg_topic
scan topic1
print msg_fplword
scan fplword
mov bl,fplword+1
;add bl,30h
mov fplword_len,bl
xor cx,cx ; to create dicovered word of first player with "-"
mov cl,fplword_len
lea si,dis_fplword
l1: mov al,'_'
mov [si],al
inc si
loop l1
call clear_screen ; second player details
print welcome_message
print msg_splname
scan splname
print msg2
print splname+2
print msg_topic
scan topic2
print msg_splword
scan splword
xor cx,cx
mov bl,splword+1 ; to store the int value in variable
;add bl,30h ; add will give ascii value of 4
mov splword_len,bl
mov cl,splword_len
lea si,dis_splword
l2: mov al,'_'
mov [si],al
inc si
loop l2
fpl:
call clear_screen
print welcome_message
print msg_fpl
print msg_topics
print topic1+2
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,fp_errors
add bl,30h
type bl
print new_line
print new_line
print dis_splword
print new_line
print new_line
check1 fp_lives,fp_errors,splword_len,fp_hits
print type_message
call read_keyboard
update splword+2,dis_splword,fp_hits,fp_errors
ring bell
call clear_screen
loop fpl
spl:
call clear_screen
print welcome_message
print msg_spl
print msg_topics
print topic2+2
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,sp_errors
add bl,30h
type bl
print new_line
print new_line
print dis_fplword
print new_line
print new_line
check2 sp_lives,sp_errors,fplword_len,sp_hits
print type_message
call read_keyboard
update fplword+2,dis_fplword,sp_hits,sp_errors
ring bell
call clear_screen
loop spl
rapid:
call clear_screen
print welcome_message
MOV AH, 00h ; interrupts to get system time
INT 1AH ; CX:DX now hold number of clock ticks since midnight
mov ax, dx
xor dx, dx
mov cx, 4
div cx ; here dx contains the remainder of the division - from 0 to 3
mov ch,0FFh ; resetting cx
mov cl,0FFh
add dl, '0' ; to ascii from '0' to '9'
cmp dl,'0'
je r0
cmp dl,'1'
je r1
cmp dl,'2'
je r2
cmp dl,'3'
je r3
r0: ; random words in order of 1,2,3,...,10
s1: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str1_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc11
mov bl,str1_size
mov bh,hits
cmp bl,bh
je sc1
print type_message
call read_keyboard
update string1,str1_dword,hits,errors
ring bell
loop s1
sc1:inc score
sc11:mov hits,0h
mov errors,0h
s2: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str2_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc22
mov bl,str2_size
mov bh,hits
cmp bl,bh
je sc2
print type_message
call read_keyboard
update string2,str2_dword,hits,errors
ring bell
loop s2
sc2:inc score
sc22:mov hits,0h
mov errors,0h
s3: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str3_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc33
mov bl,str3_size
mov bh,hits
cmp bl,bh
je sc3
print type_message
call read_keyboard
update string3,str3_dword,hits,errors
ring bell
loop s3
sc3:inc score
sc33:mov hits,0h
mov errors,0h
s4: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str4_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc44
mov bl,str4_size
mov bh,hits
cmp bl,bh
je sc4
print type_message
call read_keyboard
update string4,str4_dword,hits,errors
ring bell
loop s4
sc4:inc score
sc44:mov hits,0h
mov errors,0h
s5: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str5_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc55
mov bl,str5_size
mov bh,hits
cmp bl,bh
je sc5
print type_message
call read_keyboard
update string5,str5_dword,hits,errors
ring bell
loop s5
sc5:inc score
sc55:mov hits,0h
mov errors,0h
s6: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str6_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc66
mov bl,str6_size
mov bh,hits
cmp bl,bh
je sc6
print type_message
call read_keyboard
update string6,str6_dword,hits,errors
ring bell
loop s6
sc6:inc score
sc66:mov hits,0h
mov errors,0h
s7: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str7_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc77
mov bl,str7_size
mov bh,hits
cmp bl,bh
je sc7
print type_message
call read_keyboard
update string7,str7_dword,hits,errors
ring bell
loop s7
sc7:inc score
sc77:mov hits,0h
mov errors,0h
s8: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str8_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc88
mov bl,str8_size
mov bh,hits
cmp bl,bh
je sc8
print type_message
call read_keyboard
update string8,str8_dword,hits,errors
ring bell
loop s8
sc8:inc score
sc88:mov hits,0h
mov errors,0h
s9: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str9_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc99
mov bl,str9_size
mov bh,hits
cmp bl,bh
je sc9
print type_message
call read_keyboard
update string9,str9_dword,hits,errors
ring bell
loop s9
sc9:inc score
sc99:mov hits,0h
mov errors,0h
s10:call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str10_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc00
mov bl,str10_size
mov bh,hits
cmp bl,bh
je sc0
print type_message
call read_keyboard
update string10,str10_dword,hits,errors
ring bell
loop s10
sc0:inc score
sc00:mov hits,0h
mov errors,0h
jmp scoreboard
r1: ; random order in 5,2,9,8,7,6,3,10,4,1
s_5: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str5_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc_55
mov bl,str5_size
mov bh,hits
cmp bl,bh
je sc_5
print type_message
call read_keyboard
update string5,str5_dword,hits,errors
ring bell
loop s_5
sc_5:inc score
sc_55:mov hits,0h
mov errors,0h
s_2: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str2_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc_22
mov bl,str2_size
mov bh,hits
cmp bl,bh
je sc_2
print type_message
call read_keyboard
update string2,str2_dword,hits,errors
ring bell
loop s_2
sc_2:inc score
sc_22:mov hits,0h
mov errors,0h
s_9: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str9_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc_99
mov bl,str9_size
mov bh,hits
cmp bl,bh
je sc_9
print type_message
call read_keyboard
update string9,str9_dword,hits,errors
ring bell
loop s_9
sc_9:inc score
sc_99:mov hits,0h
mov errors,0h
s_8: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str8_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc_88
mov bl,str8_size
mov bh,hits
cmp bl,bh
je sc_8
print type_message
call read_keyboard
update string8,str8_dword,hits,errors
ring bell
loop s_8
sc_8:inc score
sc_88:mov hits,0h
mov errors,0h
s_7: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str7_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc_77
mov bl,str7_size
mov bh,hits
cmp bl,bh
je sc_7
print type_message
call read_keyboard
update string7,str7_dword,hits,errors
ring bell
loop s_7
sc_7:inc score
sc_77:mov hits,0h
mov errors,0h
s_6: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str6_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc_66
mov bl,str6_size
mov bh,hits
cmp bl,bh
je sc_6
print type_message
call read_keyboard
update string6,str6_dword,hits,errors
ring bell
loop s_6
sc_6:inc score
sc_66:mov hits,0h
mov errors,0h
s_10:call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str10_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc_00
mov bl,str10_size
mov bh,hits
cmp bl,bh
je sc_0
print type_message
call read_keyboard
update string10,str10_dword,hits,errors
ring bell
loop s_10
s_3: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str3_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc_33
mov bl,str3_size
mov bh,hits
cmp bl,bh
je sc_3
print type_message
call read_keyboard
update string3,str3_dword,hits,errors
ring bell
loop s_3
sc_3:inc score
sc_33:mov hits,0h
mov errors,0h
sc_0:inc score
sc_00:mov hits,0h
mov errors,0h
s_4: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str4_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc_44
mov bl,str4_size
mov bh,hits
cmp bl,bh
je sc_4
print type_message
call read_keyboard
update string4,str4_dword,hits,errors
ring bell
loop s_4
sc_4:inc score
sc_44:mov hits,0h
mov errors,0h
s_1: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str1_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc_11
mov bl,str1_size
mov bh,hits
cmp bl,bh
je sc_1
print type_message
call read_keyboard
update string1,str1_dword,hits,errors
ring bell
loop s_1
sc_1:inc score
sc_11:mov hits,0h
mov errors,0h
jmp scoreboard
r2: ; random order of 7,6,3,2,1,9,4,8,10,5
s\7: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str7_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc\77
mov bl,str7_size
mov bh,hits
cmp bl,bh
je sc\7
print type_message
call read_keyboard
update string7,str7_dword,hits,errors
ring bell
loop s\7
sc\7:inc score
sc\77:mov hits,0h
mov errors,0h
s\6: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str6_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc\66
mov bl,str6_size
mov bh,hits
cmp bl,bh
je sc\6
print type_message
call read_keyboard
update string6,str6_dword,hits,errors
ring bell
loop s\6
sc\6:inc score
sc\66:mov hits,0h
mov errors,0h
s\3: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str3_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc\33
mov bl,str3_size
mov bh,hits
cmp bl,bh
je sc\3
print type_message
call read_keyboard
update string3,str3_dword,hits,errors
ring bell
loop s\3
sc\3:inc score
sc\33:mov hits,0h
mov errors,0h
s\2: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str2_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc\22
mov bl,str2_size
mov bh,hits
cmp bl,bh
je sc\2
print type_message
call read_keyboard
update string2,str2_dword,hits,errors
ring bell
loop s\2
sc\2:inc score
sc\22:mov hits,0h
mov errors,0h
s\1: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str1_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc\11
mov bl,str1_size
mov bh,hits
cmp bl,bh
je sc\1
print type_message
call read_keyboard
update string1,str1_dword,hits,errors
ring bell
loop s\1
sc\1:inc score
sc\11:mov hits,0h
mov errors,0h
s\9: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str9_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc\99
mov bl,str9_size
mov bh,hits
cmp bl,bh
je sc\9
print type_message
call read_keyboard
update string9,str9_dword,hits,errors
ring bell
loop s\9
sc\9:inc score
sc\99:mov hits,0h
mov errors,0h
s\4: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str4_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc\44
mov bl,str4_size
mov bh,hits
cmp bl,bh
je sc\4
print type_message
call read_keyboard
update string4,str4_dword,hits,errors
ring bell
loop s\4
sc\4:inc score
sc\44:mov hits,0h
mov errors,0h
s\8: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str8_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc\88
mov bl,str8_size
mov bh,hits
cmp bl,bh
je sc\8
print type_message
call read_keyboard
update string8,str8_dword,hits,errors
ring bell
loop s\8
sc\8:inc score
sc\88:mov hits,0h
mov errors,0h
s\10:call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str10_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc\00
mov bl,str10_size
mov bh,hits
cmp bl,bh
je sc\0
print type_message
call read_keyboard
update string10,str10_dword,hits,errors
ring bell
loop s\10
sc\0:inc score
sc\00:mov hits,0h
mov errors,0h
s\5: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str5_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc\55
mov bl,str5_size
mov bh,hits
cmp bl,bh
je sc\5
print type_message
call read_keyboard
update string5,str5_dword,hits,errors
ring bell
loop s\5
sc\5:inc score
sc\55:mov hits,0h
mov errors,0h
jmp scoreboard
r3: ; random order of 9,3,10,7,1,6,8,5,2,4
s`9: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str9_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc`99
mov bl,str9_size
mov bh,hits
cmp bl,bh
je sc`9
print type_message
call read_keyboard
update string9,str9_dword,hits,errors
ring bell
loop s`9
sc`9:inc score
sc`99:mov hits,0h
mov errors,0h
s`3: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str3_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc`33
mov bl,str3_size
mov bh,hits
cmp bl,bh
je sc`3
print type_message
call read_keyboard
update string3,str3_dword,hits,errors
ring bell
loop s`3
sc`3:inc score
sc`33:mov hits,0h
mov errors,0h
s`10:call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str10_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc`00
mov bl,str10_size
mov bh,hits
cmp bl,bh
je sc`0
print type_message
call read_keyboard
update string10,str10_dword,hits,errors
ring bell
loop s`10
sc`0:inc score
sc`00:mov hits,0h
mov errors,0h
s`7: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str7_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc`77
mov bl,str7_size
mov bh,hits
cmp bl,bh
je sc`7
print type_message
call read_keyboard
update string7,str7_dword,hits,errors
ring bell
loop s`7
sc`7:inc score
sc`77:mov hits,0h
mov errors,0h
s`1: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str1_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc`11
mov bl,str1_size
mov bh,hits
cmp bl,bh
je sc`1
print type_message
call read_keyboard
update string1,str1_dword,hits,errors
ring bell
loop s`1
sc`1:inc score
sc`11:mov hits,0h
mov errors,0h
s`6: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str6_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc`66
mov bl,str6_size
mov bh,hits
cmp bl,bh
je sc`6
print type_message
call read_keyboard
update string6,str6_dword,hits,errors
ring bell
loop s`6
sc`6:inc score
sc`66:mov hits,0h
mov errors,0h
s`8: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str8_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc`88
mov bl,str8_size
mov bh,hits
cmp bl,bh
je sc`8
print type_message
call read_keyboard
update string8,str8_dword,hits,errors
ring bell
loop s`8
sc`8:inc score
sc`88:mov hits,0h
mov errors,0h
s`5: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str5_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc`55
mov bl,str5_size
mov bh,hits
cmp bl,bh
je sc`5
print type_message
call read_keyboard
update string5,str5_dword,hits,errors
ring bell
loop s`5
sc`5:inc score
sc`55:mov hits,0h
mov errors,0h
s`2: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str2_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc`22
mov bl,str2_size
mov bh,hits
cmp bl,bh
je sc`2
print type_message
call read_keyboard
update string2,str2_dword,hits,errors
ring bell
loop s`2
sc`2:inc score
sc`22:mov hits,0h
mov errors,0h
s`4: call clear_screen
print welcome_message
print new_line
print new_line
print msg_lives
mov bl,5h
sub bl,errors
add bl,30h
type bl
print new_line
print new_line
print str4_dword
print new_line
print new_line
mov bl,lives
mov bh,errors
cmp bl,bh
je sc`44
mov bl,str4_size
mov bh,hits
cmp bl,bh
je sc`4
print type_message
call read_keyboard
update string4,str4_dword,hits,errors
ring bell
loop s`4
sc`4:inc score
sc`44:mov hits,0h
mov errors,0h
jmp scoreboard
time:
call clear_screen
print welcome_message
print msg_time
xor ax,ax
mov ah,1h
int 21h
mov bx,60
mul bx
mov bx,130
mul bx
mov mtime,ax
call clear_screen
k:
print welcome_message
print new_line
print new_line
print new_line
print dis_wrd
print new_line
print new_line
mov bl,wrd_len
mov bh,hits
cmp bl,bh
je m
print type_message
call read_keyboard
update word1,dis_wrd,hits,errors
ring bell
inc cnt
call clear_screen
loop k
m: mov ax,mtime
mov bx,cnt
cmp ax,bx
jge m1
jle m2
m1: print new_line
print new_line
call game_over
m2: print new_line
print new_line
call game_win
game_over:
print lose_message
jmp fim
game_win:
print win_message
jmp fim
game_over1:
print lose_message1
mov cx,600
l: loop l
jmp spl
game_win1:
print win_message1
inc fp_score
mov cx,600
ll: loop ll
jmp spl
game_over2:
print lose_message1
mov cx,600
l3: loop l3
jmp winner
game_win2:
print win_message1
inc sp_score
mov cx,600
ll1: loop ll1
jmp winner
winner:
call clear_screen
print welcome_message
mov bl,fp_score
mov cl,sp_score
cmp bl,cl
je tie
jge greater
print msg_win1
print fplname+2
jmp fim
greater:
print msg_win1
print splname+2
jmp fim
tie:
print tie_message
jmp fim
scoreboard:
call clear_screen
print welcome_message
print msg_score
mov bl,score
add bl,30h
type bl
jmp fim
clear_screen: ; get and set video mode
mov ah,0fh
int 10h
mov ah,0
int 10h
ret
read_keyboard: ; read keyborad and return in al
mov ah,01h
int 21h
ret
fim:
jmp fim
code ends
end start |
nolist
org &a000
run &a000
write direct "a:disc.bin"
; check system memory
ld hl,&4000
xor a
ld (hl),a
; now do bank switch
ld bc,&7fc7
out (c),c
inc a
ld (hl),a
ld bc,&7fc0
out (c),c
ld a,(hl)
or a
jp nz,AbortLoading
;
ld hl,(&be7d)
ld a,(hl)
ld (drive+1),a
;
ld c,&ff
ld hl,startldr
call &bd16
.startldr
ld c,7
call &bcce
.drive
ld a,0
ld hl,(&be7d)
ld (hl),a
; set mode 0
ld a,0
call &bc0e
; set border black
ld bc,0
call &bc38
; set loader colours
ld hl,LoaderCols
ld a,15
call SetColours
; load loading screen
ld b,SprFN-LoadScrTFN
ld hl,LoadScrTFN
ld de,&4000
call LoadFile
ld hl,&4000
ld de,&c000
call depackINT
; set loader colours
ld hl,LoadScrCols
ld a,15
call SetColours
; load bank 1 file
; ld bc,&7fc5
; out (c),c
; ld b,Bank2FN-Bank1FN
; ld hl,Bank1FN
; ld de,&2000
; call LoadFile
; ld bc,&7fc4
; out (c),c
; call JoinBank
; load bank 2 file
; ld bc,&7fc7
; out (c),c
; ld b,CodeFN-Bank2FN
; ld hl,Bank2FN
; ld de,&2000
; call LoadFile
; ld bc,&7fc6
; out (c),c
; call JoinBank
; load strobe sprite bank block
ld bc,&7fc4
out (c),c
ld b,LoadScrFN-SprFN
ld hl,SprFN
ld de,&4000
call LoadFile
ld bc,&7fc0
out (c),c
; load sprite bank block
ld bc,&7fc6
out (c),c
ld b,Bank1FN-LoadScrFN
ld hl,LoadScrFN
ld de,&4000
call LoadFile
ld bc,&7fc0
out (c),c
; load compiled sprite block
ld bc,&7fc5
out (c),c
ld b,Bank2FN-Bank1FN
ld hl,Bank1FN
ld de,&4000
call LoadFile
ld bc,&7fc0
out (c),c
; load map block
ld bc,&7fc7
out (c),c
ld b,CodeFN-Bank2FN
ld hl,Bank2FN
ld de,&4000
call LoadFile
ld bc,&7fc0
out (c),c
; load code file
; ld bc,&7fc0
; out (c),c
ld b,EndFN-CodeFN
ld hl,CodeFN
ld de,&d0
call LoadFile
; go to game
jp &155
.SetColours
; HL points to list, A holds 15 or 3
ld b,(hl)
ld c,b
push af
push hl
call &bc32
pop hl
pop af
inc hl
cp a,0
ret z
dec a
jr SetColours
; load a file
.LoadFile
; B has filename length, HL points to
; filename, DE location to load file
push de
; ld de,&5000
ld de,&9000
call &bc77
pop hl
call &bc83
call &bc7a
ret
; Put split bank together
.JoinBank
; split loaded bank
ld hl,&2000
ld de,&4000
ld bc,&2000
ldir
ld hl,&8000
ld bc,&2000
ldir
ret
.AbortLoading
; set mode 0
ld a,1
call &bc0e
; set border black
ld bc,0
call &bc38
; set loader colours
ld hl,ErrorCols
ld a,3
call SetColours
; print messages
ld hl,&30a
call &bb75
ld a,2
call &bb96
ld hl,SabreLine1
call PrintMsgLp
ld hl,&30b
call &bb75
ld a,1
call &bb90
ld hl,SabreLine2
call PrintMsgLp
ld hl,&30c
call &bb75
ld a,1
call &bb96
ld hl,SabreLine3
call PrintMsgLp
ld hl,&50d
call &bb75
ld a,3
call &bb96
ld hl,SabreLine4
call PrintMsgLp
ld hl,&30e
call &bb75
ld hl,SabreLine5
call PrintMsgLp
ld hl,&f10
call &bb75
ld a,0
call &bb96
ld hl,Edition
call PrintMsgLp
ld hl,&416
call &bb75
ld hl,WontLoadMsg
call PrintMsgLp
call &bb18
ret
.PrintMsgLp
ld a,(hl)
or a
ret z
call &bb5a
inc hl
jr PrintMsgLp
.ErrorCols
defb 6,14,26,0
.LoaderCols
defb 0,0,0,0
defb 0,0,0,0
defb 0,0,0,0
defb 0,0,0,0
.LoadScrCols
; defb 16,26,24,13,23,14,15,10
; defb 5,7,3,1,6,4,0,2
; defb 0,13,26,3,16,25,9,22
; defb 23,10,1,2,4,17,6,14
defb 26,20,2,16,17,11,10,4
defb 1,24,9,6,18,15,3,0
.dummy
.LoadScrTFN
text "LOADSCR.BIN"
.SprFN
text "SPRITESS.BIN"
.LoadScrFN
text "SPRITES.BIN"
.Bank1FN
text "CS.BIN" ;;"CSTITLE.BIN"
.Bank2FN
text "BG.BIN"
.CodeFN
text "CODE.BIN"
.EndFN
.SabreLine1
defb 32,32,32,9,32,32,32,9,9,32,9,9,32,32,9,9,9,32,32,32,9,9,32,9,9,32,32,9,9,32,32,9,9,32,32,32,0
.SabreLine2
defb 127,9,9,9,9,127,9,9,127,9,127,9,127,9,127,9,9,127,9,9,9,127,9,127,9,127,9,127,9,127,9,127,9,127,0
.SabreLine3
defb 32,32,32,9,9,32,9,9,32,32,32,9,32,32,9,9,9,32,32,32,9,32,32,32,9,32,32,9,9,32,32,9,9,32,32,0
.SabreLine4
defb 127,9,9,127,9,9,127,9,127,9,127,9,127,9,9,9,9,127,9,127,9,127,9,127,9,127,9,127,9,127,9,127,0
.SabreLine5
defb 32,32,32,9,9,32,9,9,32,9,32,9,32,9,32,9,9,32,32,32,9,32,9,32,9,32,32,9,9,32,9,32,9,32,32,32,0
.Edition
Text "128K Edition",0
.WontLoadMsg
text "64K System detected. 128K required.",0
.EndLoader
read "bitbust_ldr.asm" |
; Assembly for testfor3-bytecode.bas
; compiled with mcbasic
; Equates for MC-10 MICROCOLOR BASIC 1.0
;
; Direct page equates
DP_LNUM .equ $E2 ; current line in BASIC
DP_TABW .equ $E4 ; current tab width on console
DP_LPOS .equ $E6 ; current line position on console
DP_LWID .equ $E7 ; current line width of console
;
; Memory equates
M_KBUF .equ $4231 ; keystrobe buffer (8 bytes)
M_PMSK .equ $423C ; pixel mask for SET, RESET and POINT
M_IKEY .equ $427F ; key code for INKEY$
M_CRSR .equ $4280 ; cursor location
M_LBUF .equ $42B2 ; line input buffer (130 chars)
M_MSTR .equ $4334 ; buffer for small string moves
M_CODE .equ $4346 ; start of program space
;
; ROM equates
R_BKMSG .equ $E1C1 ; 'BREAK' string location
R_ERROR .equ $E238 ; generate error and restore direct mode
R_BREAK .equ $E266 ; generate break and restore direct mode
R_RESET .equ $E3EE ; setup stack and disable CONT
R_SPACE .equ $E7B9 ; emit " " to console
R_QUEST .equ $E7BC ; emit "?" to console
R_REDO .equ $E7C1 ; emit "?REDO" to console
R_EXTRA .equ $E8AB ; emit "?EXTRA IGNORED" to console
R_DMODE .equ $F7AA ; display OK prompt and restore direct mode
R_KPOLL .equ $F879 ; if key is down, do KEYIN, else set Z CCR flag
R_KEYIN .equ $F883 ; poll key for key-down transition set Z otherwise
R_PUTC .equ $F9C9 ; write ACCA to console
R_MKTAB .equ $FA7B ; setup tabs for console
R_GETLN .equ $FAA4 ; get line, returning with X pointing to M_BUF-1
R_SETPX .equ $FB44 ; write pixel character to X
R_CLRPX .equ $FB59 ; clear pixel character in X
R_MSKPX .equ $FB7C ; get pixel screen location X and mask in R_PMSK
R_CLSN .equ $FBC4 ; clear screen with color code in ACCB
R_CLS .equ $FBD4 ; clear screen with space character
R_SOUND .equ $FFAB ; play sound with pitch in ACCA and duration in ACCB
R_MCXID .equ $FFDA ; ID location for MCX BASIC
; direct page registers
.org $80
strtcnt .block 1
strbuf .block 2
strend .block 2
strfree .block 2
strstop .block 2
dataptr .block 2
inptptr .block 2
redoptr .block 2
letptr .block 2
.org $a3
r1 .block 5
rend
rvseed .block 2
curinst .block 2
nxtinst .block 2
tmp1 .block 2
tmp2 .block 2
tmp3 .block 2
tmp4 .block 2
tmp5 .block 2
argv .block 10
.org M_CODE
.module mdmain
ldx #program
stx nxtinst
mainloop
ldx nxtinst
stx curinst
ldab ,x
ldx #catalog
abx
abx
ldx ,x
jsr 0,x
bra mainloop
program
.byte bytecode_progbegin
.byte bytecode_clear
LINE_10
; FOR T=0 TO 1.1 STEP 0.3333
.byte bytecode_for_fx_pb
.byte bytecode_FLTVAR_T
.byte 0
.byte bytecode_to_fp_fx
.byte bytecode_FLT_1p10000
.byte bytecode_ld_fr1_fx
.byte bytecode_FLT_0p33329
.byte bytecode_step_fp_fr1
LINE_20
; PRINT STR$(T);" "
.byte bytecode_str_sr1_fx
.byte bytecode_FLTVAR_T
.byte bytecode_pr_sr1
.byte bytecode_pr_ss
.text 2, " \r"
LINE_30
; NEXT T
.byte bytecode_nextvar_fx
.byte bytecode_FLTVAR_T
.byte bytecode_next
LLAST
; END
.byte bytecode_progend
; Library Catalog
bytecode_clear .equ 0
bytecode_for_fx_pb .equ 1
bytecode_ld_fr1_fx .equ 2
bytecode_next .equ 3
bytecode_nextvar_fx .equ 4
bytecode_pr_sr1 .equ 5
bytecode_pr_ss .equ 6
bytecode_progbegin .equ 7
bytecode_progend .equ 8
bytecode_step_fp_fr1 .equ 9
bytecode_str_sr1_fx .equ 10
bytecode_to_fp_fx .equ 11
catalog
.word clear
.word for_fx_pb
.word ld_fr1_fx
.word next
.word nextvar_fx
.word pr_sr1
.word pr_ss
.word progbegin
.word progend
.word step_fp_fr1
.word str_sr1_fx
.word to_fp_fx
.module mdbcode
noargs
ldx curinst
inx
stx nxtinst
rts
extend
ldx curinst
inx
ldab ,x
inx
stx nxtinst
ldx #symtbl
abx
abx
ldx ,x
rts
getaddr
ldd curinst
addd #3
std nxtinst
ldx curinst
ldx 1,x
rts
getbyte
ldx curinst
inx
ldab ,x
inx
stx nxtinst
rts
getword
ldx curinst
inx
ldd ,x
inx
inx
stx nxtinst
rts
extbyte
ldd curinst
addd #3
std nxtinst
ldx curinst
ldab 2,x
pshb
ldab 1,x
ldx #symtbl
abx
abx
ldx ,x
pulb
rts
extword
ldd curinst
addd #4
std nxtinst
ldx curinst
ldd 2,x
pshb
ldab 1,x
ldx #symtbl
abx
abx
ldx ,x
pulb
rts
byteext
ldd curinst
addd #3
std nxtinst
ldx curinst
ldab 1,x
pshb
ldab 2,x
ldx #symtbl
abx
abx
ldx ,x
pulb
rts
wordext
ldd curinst
addd #4
std nxtinst
ldx curinst
ldd 1,x
pshb
ldab 3,x
ldx #symtbl
abx
abx
ldx ,x
pulb
rts
immstr
ldx curinst
inx
ldab ,x
inx
pshx
abx
stx nxtinst
pulx
rts
.module mddivflt
; divide X by Y
; ENTRY X contains dividend in (0,x 1,x 2,x 3,x 4,x)
; scratch in (5,x 6,x 7,x 8,x 9,x)
; Y in 0+argv, 1+argv, 2+argv, 3+argv, 4+argv
; EXIT X/Y in (0,x 1,x 2,x 3,x 4,x)
; uses tmp1,tmp1+1,tmp2,tmp2+1,tmp3,tmp3+1,tmp4
divflt
ldaa #8*5
bsr divmod
tst tmp4
bmi _add1
_com
ldd 8,x
coma
comb
std 3,x
ldd 6,x
coma
comb
std 1,x
ldab 5,x
comb
stab 0,x
rts
_add1
ldd 8,x
addd #1
std 3,x
ldd 6,x
adcb #0
adca #0
std 1,x
ldab 5,x
adcb #0
stab 0,x
rts
divuflt
clr tmp4
ldab #8*5
stab tmp1
bsr divumod
bra _com
.module mddivmod
; divide/modulo X by Y with remainder
; ENTRY X contains dividend in (0,x 1,x 2,x 3,x 4,x)
; Y in 0+argv, 1+argv, 2+argv, 3+argv, 4+argv
; #shifts in ACCA (24 for modulus, 40 for division
; EXIT for division:
; NOT ABS(X)/ABS(Y) in (5,x 6,x 7,x 8,x 9,x)
; EXIT for modulus:
; NOT INT(ABS(X)/ABS(Y)) in (7,x 8,x 9,x)
; FMOD(X,Y) in (0,x 1,x 2,x 3,x 4,x)
; result sign in tmp4.(0 = pos, -1 = neg).
; uses tmp1,tmp1+1,tmp2,tmp2+1,tmp3,tmp3+1,tmp4
divmod
staa tmp1
clr tmp4
tst 0,x
bpl _posX
com tmp4
jsr negx
_posX
tst 0+argv
bpl divumod
com tmp4
jsr negargv
divumod
ldd 3,x
std 6,x
ldd 1,x
std 4,x
ldab 0,x
stab 3,x
clra
clrb
std 8,x
std 1,x
stab 0,x
_nxtdiv
rol 7,x
rol 6,x
rol 5,x
rol 4,x
rol 3,x
rol 2,x
rol 1,x
rol 0,x
bcc _trialsub
; force subtraction
ldd 3,x
subd 3+argv
std 3,x
ldd 1,x
sbcb 2+argv
sbca 1+argv
std 1,x
ldab 0,x
sbcb 0+argv
stab 0,x
clc
bra _shift
_trialsub
ldd 3,x
subd 3+argv
std tmp3
ldd 1,x
sbcb 2+argv
sbca 1+argv
std tmp2
ldab 0,x
sbcb 0+argv
stab tmp1+1
blo _shift
ldd tmp3
std 3,x
ldd tmp2
std 1,x
ldab tmp1+1
stab 0,x
_shift
rol 9,x
rol 8,x
dec tmp1
bne _nxtdiv
rol 7,x
rol 6,x
rol 5,x
rts
.module mdidivb
; fast integer division by three or five
; ENTRY+EXIT: int in tmp1+1,tmp2,tmp2+1
; ACCB contains:
; $CC for div-5
; $AA for div-3
; tmp3,tmp3+1,tmp4 used for storage
idivb
stab tmp4
ldab tmp1+1
pshb
ldd tmp2
psha
ldaa tmp4
mul
std tmp3
addd tmp2
std tmp2
ldab tmp1+1
adcb tmp3+1
stab tmp1+1
ldd tmp1+1
addd tmp3
std tmp1+1
pulb
ldaa tmp4
mul
stab tmp3+1
addd tmp1+1
std tmp1+1
pulb
ldaa tmp4
mul
addb tmp1+1
addb tmp3+1
stab tmp1+1
rts
.module mdimodb
; fast integer modulo operation by three or five
; ENTRY: int in tmp1+1,tmp2,tmp2+1
; ACCB contains modulus (3 or 5)
; EXIT: result in ACCA
imodb
pshb
ldaa tmp1+1
bpl _ok
deca
_ok
adda tmp2
adca tmp2+1
adca #0
adca #0
tab
lsra
lsra
lsra
lsra
andb #$0F
aba
pulb
_dec
sba
bhs _dec
aba
tst tmp1+1
rts
.module mdnegargv
negargv
neg 4+argv
bcs _com3
neg 3+argv
bcs _com2
neg 2+argv
bcs _com1
neg 1+argv
bcs _com0
neg 0+argv
rts
_com3
com 3+argv
_com2
com 2+argv
_com1
com 1+argv
_com0
com 0+argv
rts
.module mdnegtmp
negtmp
neg tmp3+1
bcs _com3
neg tmp3
bcs _com2
neg tmp2+1
bcs _com1
neg tmp2
bcs _com0
neg tmp1+1
rts
_com3
com tmp3
_com2
com tmp2+1
_com1
com tmp2
_com0
com tmp1+1
rts
.module mdnegx
negx
neg 4,x
bcs _com3
neg 3,x
bcs _com2
negxi
neg 2,x
bcs _com1
neg 1,x
bcs _com0
neg 0,x
rts
_com3
com 3,x
_com2
com 2,x
_com1
com 1,x
_com0
com 0,x
rts
.module mdprint
print
_loop
ldaa ,x
jsr R_PUTC
inx
decb
bne _loop
rts
.module mdstrflt
strflt
inc strtcnt
pshx
tst tmp1+1
bmi _neg
ldab #' '
bra _wdigs
_neg
jsr negtmp
ldab #'-'
_wdigs
ldx tmp3
pshx
ldx strfree
stab ,x
clr tmp1
_nxtwdig
inc tmp1
lsr tmp1+1
ror tmp2
ror tmp2+1
ror tmp3
ldab #5
jsr imodb
staa tmp3+1
lsl tmp3
rola
adda #'0'
psha
ldd tmp2
subb tmp3+1
sbca #0
std tmp2
ldab tmp1+1
sbcb #0
stab tmp1+1
ldab #$CC
jsr idivb
bne _nxtwdig
ldd tmp2
bne _nxtwdig
ldab tmp1
_nxtc
pula
inx
staa ,x
decb
bne _nxtc
inx
inc tmp1
pula
pulb
subd #0
bne _fdo
jmp _fdone
_fdo
std tmp2
ldab #'.'
stab ,x
inc tmp1
inx
ldd #6
staa tmp1+1
stab tmp3
_nxtf
ldd tmp2
lsl tmp2+1
rol tmp2
rol tmp1+1
lsl tmp2+1
rol tmp2
rol tmp1+1
addd tmp2
std tmp2
ldab tmp1+1
adcb #0
stab tmp1+1
lsl tmp2+1
rol tmp2
rol tmp1+1
ldd tmp1
addb #'0'
stab ,x
inx
inc tmp1
clrb
stab tmp1+1
dec tmp3
bne _nxtf
tst tmp2
bmi _nxtrnd
_nxtzero
dex
dec tmp1
ldaa ,x
cmpa #'0'
beq _nxtzero
bra _zdone
_nxtrnd
dex
dec tmp1
ldaa ,x
cmpa #'.'
beq _dot
inca
cmpa #'9'
bhi _nxtrnd
bra _rdone
_dot
ldaa #'0'
staa ,x
ldab tmp1
_ndot
decb
beq _dzero
dex
ldaa ,x
inca
cmpa #'9'
bls _ddone
bra _ndot
_ddone
staa ,x
ldx strfree
ldab tmp1
abx
bra _fdone
_dzero
ldaa #'1'
staa ,x
ldx strfree
ldab tmp1
abx
ldaa #'0'
_rdone
staa ,x
_zdone
inx
inc tmp1
_fdone
ldd strfree
stx strfree
pulx
rts
.module mdstrrel
; release a temporary string
; ENTRY: X holds string start
; EXIT: <all reg's preserved>
; sttrel should be called from:
; - ASC, VAL, LEN, PRINT
; - right hand side of strcat
; - relational operators
; - when LEFT$, MID$, RIGHT$ return null
strrel
cpx strend
bls _rts
cpx strstop
bhs _rts
tst strtcnt
beq _panic
dec strtcnt
beq _restore
stx strfree
_rts
rts
_restore
pshx
ldx strend
inx
inx
stx strfree
pulx
rts
_panic
ldab #1
jmp error
.module mdtobc
; push for-loop record on stack
; ENTRY: ACCB contains size of record
; r1 contains stopping variable
; and is always fixedpoint.
; r1+3 must contain zero if an integer.
to
clra
std tmp3
pulx
stx tmp1
tsx
clrb
_nxtfor
abx
ldd 1,x
subd letptr
beq _oldfor
ldab ,x
cmpb #3
bhi _nxtfor
sts tmp2
ldd tmp2
subd tmp3
std tmp2
lds tmp2
tsx
ldab tmp3+1
stab 0,x
ldd letptr
std 1,x
_oldfor
ldd nxtinst
std 3,x
ldab r1
stab 5,x
ldd r1+1
std 6,x
ldd r1+3
std 8,x
ldab tmp3+1
cmpb #15
beq _flt
inca
staa 10,x
bra _done
_flt
ldd #0
std 10,x
std 13,x
inca
staa 12,x
_done
ldx tmp1
jmp ,x
clear ; numCalls = 1
.module modclear
jsr noargs
clra
ldx #bss
bra _start
_again
staa ,x
inx
_start
cpx #bes
bne _again
stx strbuf
stx strend
inx
inx
stx strfree
ldx #$8FFF
stx strstop
ldx #startdata
stx dataptr
rts
for_fx_pb ; numCalls = 1
.module modfor_fx_pb
jsr extbyte
stx letptr
clra
staa 0,x
std 1,x
clrb
std 3,x
rts
ld_fr1_fx ; numCalls = 1
.module modld_fr1_fx
jsr extend
ldd 3,x
std r1+3
ldd 1,x
std r1+1
ldab 0,x
stab r1
rts
next ; numCalls = 1
.module modnext
jsr noargs
pulx
tsx
ldab ,x
cmpb #3
bhi _ok
ldab #NF_ERROR
jmp error
_ok
cmpb #11
bne _flt
ldd 9,x
std r1+1
ldab 8,x
stab r1
ldx 1,x
ldd r1+1
addd 1,x
std r1+1
std 1,x
ldab r1
adcb ,x
stab r1
stab ,x
tsx
tst 8,x
bpl _iopp
ldd r1+1
subd 6,x
ldab r1
sbcb 5,x
blt _idone
ldx 3,x
stx nxtinst
jmp mainloop
_iopp
ldd 6,x
subd r1+1
ldab 5,x
sbcb r1
blt _idone
ldx 3,x
stx nxtinst
jmp mainloop
_idone
ldab #11
bra _done
_flt
ldd 13,x
std r1+3
ldd 11,x
std r1+1
ldab 10,x
stab r1
ldx 1,x
ldd r1+3
addd 3,x
std r1+3
std 3,x
ldd 1,x
adcb r1+2
adca r1+1
std r1+1
std 1,x
ldab r1
adcb ,x
stab r1
stab ,x
tsx
tst 10,x
bpl _fopp
ldd r1+3
subd 8,x
ldd r1+1
sbcb 7,x
sbca 6,x
ldab r1
sbcb 5,x
blt _fdone
ldx 3,x
stx nxtinst
jmp mainloop
_fopp
ldd 8,x
subd r1+3
ldd 6,x
sbcb r1+2
sbca r1+1
ldab 5,x
sbcb r1
blt _fdone
ldx 3,x
stx nxtinst
jmp mainloop
_fdone
ldab #15
_done
abx
txs
jmp mainloop
nextvar_fx ; numCalls = 1
.module modnextvar_fx
jsr extend
stx letptr
pulx
tsx
clrb
_nxtvar
abx
ldd 1,x
subd letptr
beq _ok
ldab ,x
cmpb #3
bhi _nxtvar
_ok
txs
jmp mainloop
pr_sr1 ; numCalls = 1
.module modpr_sr1
jsr noargs
ldab r1
beq _rts
ldx r1+1
jsr print
ldx r1+1
jmp strrel
_rts
rts
pr_ss ; numCalls = 1
.module modpr_ss
ldx curinst
inx
ldab ,x
beq _null
inx
jsr print
stx nxtinst
rts
_null
inx
stx nxtinst
rts
progbegin ; numCalls = 1
.module modprogbegin
jsr noargs
ldx R_MCXID
cpx #'h'*256+'C'
bne _mcbasic
pulx
clrb
pshb
pshb
pshb
stab strtcnt
jmp ,x
_reqmsg .text "?MICROCOLOR BASIC ROM REQUIRED"
_mcbasic
ldx #_reqmsg
ldab #30
jsr print
pulx
rts
progend ; numCalls = 1
.module modprogend
jsr noargs
pulx
pula
pula
pula
jsr R_RESET
jmp R_DMODE
NF_ERROR .equ 0
RG_ERROR .equ 4
OD_ERROR .equ 6
FC_ERROR .equ 8
OV_ERROR .equ 10
OM_ERROR .equ 12
BS_ERROR .equ 16
DD_ERROR .equ 18
LS_ERROR .equ 28
error
jmp R_ERROR
step_fp_fr1 ; numCalls = 1
.module modstep_fp_fr1
jsr noargs
tsx
ldab r1
stab 12,x
ldd r1+1
std 13,x
ldd r1+3
std 15,x
ldd nxtinst
std 5,x
rts
str_sr1_fx ; numCalls = 1
.module modstr_sr1_fx
jsr extend
ldd 1,x
std tmp2
ldab 0,x
stab tmp1+1
ldd 3,x
std tmp3
jsr strflt
std r1+1
ldab tmp1
stab r1
rts
to_fp_fx ; numCalls = 1
.module modto_fp_fx
jsr extend
ldab 0,x
stab r1
ldd 1,x
std r1+1
ldd 3,x
std r1+3
ldab #15
jmp to
; data table
startdata
enddata
; Bytecode symbol lookup table
bytecode_FLT_0p33329 .equ 0
bytecode_FLT_1p10000 .equ 1
bytecode_FLTVAR_T .equ 2
symtbl
.word FLT_0p33329
.word FLT_1p10000
.word FLTVAR_T
; fixed-point constants
FLT_0p33329 .byte $00, $00, $00, $55, $53
FLT_1p10000 .byte $00, $00, $01, $19, $9a
; block started by symbol
bss
; Numeric Variables
FLTVAR_T .block 5
; String Variables
; Numeric Arrays
; String Arrays
; block ended by symbol
bes
.end
|
_Route8BattleText1::
text "You look good at"
line "#MON, but"
cont "how's your chem?"
done
_Route8EndBattleText1::
text "Ow!"
line "Meltdown!"
prompt
_Route8AfterBattleText1::
text "I am better at"
line "school than this!"
done
_Route8BattleText2::
text "All right! Let's"
line "roll the dice!"
done
_Route8EndBattleText2::
text "Drat!"
line "Came up short!"
prompt
_Route8AfterBattleText2::
text "Lady Luck's not"
line "with me today!"
done
_Route8BattleText3::
text "You need strategy"
line "to win at this!"
done
_Route8EndBattleText3::
text "It's"
line "not logical!"
prompt
_Route8AfterBattleText3::
text "Go with GRIMER"
line "first...and..."
cont "...and...then..."
done
_Route8BattleText4::
text "I like NIDORAN, so"
line "I collect them!"
done
_Route8EndBattleText4::
text "Why? Why??"
prompt
_Route8AfterBattleText4::
text "When #MON grow"
line "up they get ugly!"
cont "They shouldn't"
cont "evolve!"
done
_Route8BattleText5::
text "School is fun, but"
line "so are #MON."
done
_Route8EndBattleText5::
text "I'll"
line "stay with school."
prompt
_Route8AfterBattleText5::
text "We're stuck here"
line "because of the"
cont "gates at SAFFRON."
done
_Route8BattleText6::
text "MEOWTH is so cute,"
line "meow, meow, meow!"
done
_Route8EndBattleText6::
text "Meow!"
prompt
_Route8AfterBattleText6::
text "I think PIDGEY"
line "and RATTATA"
cont "are cute too!"
done
_Route8BattleText7::
text "We must look"
line "silly standing"
cont "here like this!"
done
_Route8EndBattleText7::
text "Look what"
line "you did!"
prompt
_Route8AfterBattleText7::
text "SAFFRON's gate-"
line "keeper won't let"
cont "us through."
cont "He's so mean!"
done
_Route8BattleText8::
text "I'm a rambling,"
line "gambling dude!"
done
_Route8EndBattleText8::
text "Missed"
line "the big score!"
prompt
_Route8AfterBattleText8::
text "Gambling and"
line "#MON are like"
cont "eating peanuts!"
cont "Just can't stop!"
done
_Route8BattleText9::
text "What's a cute,"
line "round and fluffy"
cont "#MON?"
done
_Route8EndBattleText9::
text "Stop!"
para "Don't be so mean"
line "to my CLEFAIRY!"
prompt
_Route8AfterBattleText9::
text "I heard that"
line "CLEFAIRY evolves"
cont "when it's exposed"
cont "to a MOON STONE."
done
_Route8Text10::
text "UNDERGROUND PATH"
line "CELADON CITY -"
cont "LAVENDER TOWN"
done
|
; A348327: Characteristic function of numbers that have no middle divisors.
; Submitted by Jon Maiga
; 0,0,1,0,1,0,1,0,0,1,1,0,1,1,0,0,1,0,1,0,1,1,1,0,0,1,1,0,1,0,1,0,1,1,0,0,1,1,1,0,1,0,1,1,0,1,1,0,0,0,1,1,1,0,1,0,1,1,1,0,1,1,0,0,1,0,1,1,1,0,1,0,1,1,1,1,0,1,1,0,0,1,1,0,1,1,1,0,1,0,0,1,1,1,1,0,1,0,0,0
seq $0,347266 ; a(n) is the number whose binary representation is the concatenation of terms in the n-th row of A237048.
seq $0,345927 ; Alternating sum of the binary expansion of n (row n of A030190). Replace 2^k with (-1)^(A070939(n)-k) in the binary expansion of n (compare to the definition of A065359).
seq $0,38 ; Twice A000007.
div $0,2
|
/*
* Copyright (C) 2018-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/execution_environment/execution_environment.h"
#include "shared/source/helpers/aligned_memory.h"
#include "shared/source/helpers/basic_math.h"
#include "shared/source/memory_manager/memory_manager.h"
#include "shared/source/os_interface/driver_info.h"
#include "shared/source/os_interface/linux/allocator_helper.h"
#include "shared/source/os_interface/linux/sys_calls.h"
#include "shared/source/os_interface/os_interface.h"
#include "shared/test/common/helpers/debug_manager_state_restore.h"
#include "shared/test/common/helpers/default_hw_info.inl"
#include "shared/test/common/helpers/ult_hw_config.inl"
#include "shared/test/common/helpers/variable_backup.h"
#include "opencl/test/unit_test/custom_event_listener.h"
#include "opencl/test/unit_test/linux/drm_wrap.h"
#include "opencl/test/unit_test/linux/mock_os_layer.h"
#include "opencl/test/unit_test/mocks/mock_execution_environment.h"
#include "opencl/test/unit_test/os_interface/linux/device_command_stream_fixture.h"
#include "test.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <string>
namespace NEO {
void __attribute__((destructor)) platformsDestructor();
}
using namespace NEO;
class DrmTestsFixture {
public:
void SetUp() {
executionEnvironment.prepareRootDeviceEnvironments(1);
rootDeviceEnvironment = executionEnvironment.rootDeviceEnvironments[0].get();
}
void TearDown() {
}
ExecutionEnvironment executionEnvironment;
RootDeviceEnvironment *rootDeviceEnvironment = nullptr;
};
typedef Test<DrmTestsFixture> DrmTests;
void initializeTestedDevice() {
for (uint32_t i = 0; deviceDescriptorTable[i].eGtType != GTTYPE::GTTYPE_UNDEFINED; i++) {
if (defaultHwInfo->platform.eProductFamily == deviceDescriptorTable[i].pHwInfo->platform.eProductFamily) {
deviceId = deviceDescriptorTable[i].deviceId;
break;
}
}
}
int openRetVal = 0;
std::string lastOpenedPath;
int testOpen(const char *fullPath, int, ...) {
return openRetVal;
};
int openCounter = 1;
int openWithCounter(const char *fullPath, int, ...) {
if (openCounter > 0) {
if (fullPath) {
lastOpenedPath = fullPath;
}
openCounter--;
return 1023; // valid file descriptor for ULT
}
return -1;
};
TEST(DrmTest, GivenTwoOpenableDevicesWhenDiscoverDevicesThenCreateTwoHwDeviceIds) {
VariableBackup<decltype(openFull)> backupOpenFull(&openFull);
openFull = openWithCounter;
openCounter = 2;
ExecutionEnvironment executionEnvironment;
auto hwDeviceIds = OSInterface::discoverDevices(executionEnvironment);
EXPECT_EQ(2u, hwDeviceIds.size());
}
TEST(DrmTest, GivenSelectedNotExistingDeviceWhenGetDeviceFdThenFail) {
DebugManagerStateRestore stateRestore;
DebugManager.flags.ForceDeviceId.set("1234");
VariableBackup<decltype(openFull)> backupOpenFull(&openFull);
openFull = testOpen;
openRetVal = -1;
ExecutionEnvironment executionEnvironment;
auto hwDeviceIds = OSInterface::discoverDevices(executionEnvironment);
EXPECT_TRUE(hwDeviceIds.empty());
}
TEST(DrmTest, GivenSelectedExistingDeviceWhenGetDeviceFdThenReturnFd) {
DebugManagerStateRestore stateRestore;
DebugManager.flags.ForceDeviceId.set("1234");
VariableBackup<decltype(openFull)> backupOpenFull(&openFull);
openRetVal = 1023; // fakeFd
openFull = testOpen;
ExecutionEnvironment executionEnvironment;
auto hwDeviceIds = OSInterface::discoverDevices(executionEnvironment);
EXPECT_EQ(1u, hwDeviceIds.size());
EXPECT_NE(nullptr, hwDeviceIds[0].get());
}
TEST(DrmTest, GivenSelectedExistingDeviceWhenOpenDirSuccedsThenHwDeviceIdsHaveProperPciPaths) {
VariableBackup<decltype(openFull)> backupOpenFull(&openFull);
VariableBackup<decltype(failOnOpenDir)> backupOpenDir(&failOnOpenDir, false);
VariableBackup<decltype(entryIndex)> backupEntryIndex(&entryIndex, 0u);
openFull = openWithCounter;
ExecutionEnvironment executionEnvironment;
entryIndex = 0;
openCounter = 1;
auto hwDeviceIds = OSInterface::discoverDevices(executionEnvironment);
EXPECT_EQ(1u, hwDeviceIds.size());
EXPECT_NE(nullptr, hwDeviceIds[0].get());
EXPECT_STREQ("test1", hwDeviceIds[0]->as<HwDeviceIdDrm>()->getPciPath());
entryIndex = 0;
openCounter = 2;
hwDeviceIds = OSInterface::discoverDevices(executionEnvironment);
EXPECT_EQ(2u, hwDeviceIds.size());
EXPECT_NE(nullptr, hwDeviceIds[0].get());
EXPECT_STREQ("test1", hwDeviceIds[0]->as<HwDeviceIdDrm>()->getPciPath());
EXPECT_NE(nullptr, hwDeviceIds[1].get());
EXPECT_STREQ("test2", hwDeviceIds[1]->as<HwDeviceIdDrm>()->getPciPath());
}
TEST(DrmTest, GivenSelectedExistingDeviceWhenOpenDirFailsThenRetryOpeningRenderDevices) {
VariableBackup<decltype(openFull)> backupOpenFull(&openFull);
VariableBackup<decltype(failOnOpenDir)> backupOpenDir(&failOnOpenDir, true);
VariableBackup<decltype(readLinkCalledTimes)> backupReadlink(&readLinkCalledTimes, 0);
openFull = openWithCounter;
openCounter = 1;
ExecutionEnvironment executionEnvironment;
auto hwDeviceIds = OSInterface::discoverDevices(executionEnvironment);
EXPECT_STREQ("/dev/dri/renderD128", lastOpenedPath.c_str());
EXPECT_EQ(1u, hwDeviceIds.size());
EXPECT_NE(nullptr, hwDeviceIds[0].get());
EXPECT_STREQ("00:02.0", hwDeviceIds[0]->as<HwDeviceIdDrm>()->getPciPath());
openCounter = 2;
hwDeviceIds = OSInterface::discoverDevices(executionEnvironment);
EXPECT_STREQ("/dev/dri/renderD129", lastOpenedPath.c_str());
EXPECT_EQ(2u, hwDeviceIds.size());
EXPECT_NE(nullptr, hwDeviceIds[0].get());
EXPECT_STREQ("00:02.0", hwDeviceIds[0]->as<HwDeviceIdDrm>()->getPciPath());
EXPECT_NE(nullptr, hwDeviceIds[1].get());
EXPECT_STREQ("00:03.0", hwDeviceIds[1]->as<HwDeviceIdDrm>()->getPciPath());
}
TEST(DrmTest, givenPrintIoctlEntriesWhenCallIoctlThenIoctlIsPrinted) {
::testing::internal::CaptureStdout();
auto executionEnvironment = std::make_unique<ExecutionEnvironment>();
executionEnvironment->prepareRootDeviceEnvironments(1);
auto drm = DrmWrap::createDrm(*executionEnvironment->rootDeviceEnvironments[0]);
DebugManagerStateRestore restorer;
DebugManager.flags.PrintIoctlEntries.set(true);
uint32_t contextId = 1u;
drm->destroyDrmContext(contextId);
std::string output = ::testing::internal::GetCapturedStdout();
EXPECT_STREQ(output.c_str(), "IOCTL DRM_IOCTL_I915_GEM_CONTEXT_DESTROY called\nIOCTL DRM_IOCTL_I915_GEM_CONTEXT_DESTROY returns 0, errno 9\n");
}
TEST(DrmTest, givenPrintIoctlTimesWhenCallIoctlThenStatisticsAreGathered) {
struct DrmMock : public Drm {
using Drm::ioctlStatistics;
};
::testing::internal::CaptureStdout();
auto executionEnvironment = std::make_unique<ExecutionEnvironment>();
executionEnvironment->prepareRootDeviceEnvironments(1);
auto drm = static_cast<DrmMock *>(DrmWrap::createDrm(*executionEnvironment->rootDeviceEnvironments[0]).release());
DebugManagerStateRestore restorer;
DebugManager.flags.PrintIoctlTimes.set(true);
EXPECT_TRUE(drm->ioctlStatistics.empty());
int euTotal = 0u;
uint32_t contextId = 1u;
drm->getEuTotal(euTotal);
EXPECT_EQ(drm->ioctlStatistics.size(), 1u);
drm->getEuTotal(euTotal);
EXPECT_EQ(drm->ioctlStatistics.size(), 1u);
drm->setLowPriorityContextParam(contextId);
EXPECT_EQ(drm->ioctlStatistics.size(), 2u);
auto euTotalData = drm->ioctlStatistics.find(DRM_IOCTL_I915_GETPARAM);
ASSERT_TRUE(euTotalData != drm->ioctlStatistics.end());
EXPECT_EQ(euTotalData->first, static_cast<unsigned long>(DRM_IOCTL_I915_GETPARAM));
EXPECT_EQ(euTotalData->second.second, 2u);
EXPECT_NE(euTotalData->second.first, 0);
auto firstTime = euTotalData->second.first;
auto lowPriorityData = drm->ioctlStatistics.find(DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM);
ASSERT_TRUE(lowPriorityData != drm->ioctlStatistics.end());
EXPECT_EQ(lowPriorityData->first, static_cast<unsigned long>(DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM));
EXPECT_EQ(lowPriorityData->second.second, 1u);
EXPECT_NE(lowPriorityData->second.first, 0);
drm->getEuTotal(euTotal);
EXPECT_EQ(drm->ioctlStatistics.size(), 2u);
euTotalData = drm->ioctlStatistics.find(DRM_IOCTL_I915_GETPARAM);
ASSERT_TRUE(euTotalData != drm->ioctlStatistics.end());
EXPECT_EQ(euTotalData->first, static_cast<unsigned long>(DRM_IOCTL_I915_GETPARAM));
EXPECT_EQ(euTotalData->second.second, 3u);
EXPECT_NE(euTotalData->second.first, 0);
auto secondTime = euTotalData->second.first;
EXPECT_GT(secondTime, firstTime);
lowPriorityData = drm->ioctlStatistics.find(DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM);
ASSERT_TRUE(lowPriorityData != drm->ioctlStatistics.end());
EXPECT_EQ(lowPriorityData->first, static_cast<unsigned long>(DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM));
EXPECT_EQ(lowPriorityData->second.second, 1u);
EXPECT_NE(lowPriorityData->second.first, 0);
drm->destroyDrmContext(contextId);
EXPECT_EQ(drm->ioctlStatistics.size(), 3u);
euTotalData = drm->ioctlStatistics.find(DRM_IOCTL_I915_GETPARAM);
ASSERT_TRUE(euTotalData != drm->ioctlStatistics.end());
EXPECT_EQ(euTotalData->first, static_cast<unsigned long>(DRM_IOCTL_I915_GETPARAM));
EXPECT_EQ(euTotalData->second.second, 3u);
EXPECT_NE(euTotalData->second.first, 0);
lowPriorityData = drm->ioctlStatistics.find(DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM);
ASSERT_TRUE(lowPriorityData != drm->ioctlStatistics.end());
EXPECT_EQ(lowPriorityData->first, static_cast<unsigned long>(DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM));
EXPECT_EQ(lowPriorityData->second.second, 1u);
EXPECT_NE(lowPriorityData->second.first, 0);
auto destroyData = drm->ioctlStatistics.find(DRM_IOCTL_I915_GEM_CONTEXT_DESTROY);
ASSERT_TRUE(destroyData != drm->ioctlStatistics.end());
EXPECT_EQ(destroyData->first, static_cast<unsigned long>(DRM_IOCTL_I915_GEM_CONTEXT_DESTROY));
EXPECT_EQ(destroyData->second.second, 1u);
EXPECT_NE(destroyData->second.first, 0);
delete drm;
std::string output = ::testing::internal::GetCapturedStdout();
EXPECT_STRNE(output.c_str(), "");
}
TEST(DrmTest, GivenSelectedNonExistingDeviceWhenOpenDirFailsThenRetryOpeningRenderDevicesAndNoDevicesAreCreated) {
VariableBackup<decltype(openFull)> backupOpenFull(&openFull);
VariableBackup<decltype(failOnOpenDir)> backupOpenDir(&failOnOpenDir, true);
openFull = openWithCounter;
openCounter = 0;
ExecutionEnvironment executionEnvironment;
auto hwDeviceIds = OSInterface::discoverDevices(executionEnvironment);
EXPECT_EQ(0u, hwDeviceIds.size());
}
TEST(DrmTest, GivenFailingOpenDirAndMultipleAvailableDevicesWhenCreateMultipleRootDevicesFlagIsSetThenTheFlagIsRespected) {
DebugManagerStateRestore stateRestore;
VariableBackup<decltype(openFull)> backupOpenFull(&openFull);
VariableBackup<decltype(failOnOpenDir)> backupOpenDir(&failOnOpenDir, true);
VariableBackup<decltype(readLinkCalledTimes)> backupReadlink(&readLinkCalledTimes, 0);
openFull = openWithCounter;
ExecutionEnvironment executionEnvironment;
const uint32_t requestedNumRootDevices = 2u;
DebugManager.flags.CreateMultipleRootDevices.set(requestedNumRootDevices);
openCounter = 4;
auto hwDeviceIds = OSInterface::discoverDevices(executionEnvironment);
EXPECT_STREQ("/dev/dri/renderD129", lastOpenedPath.c_str());
EXPECT_EQ(requestedNumRootDevices, hwDeviceIds.size());
EXPECT_NE(nullptr, hwDeviceIds[0].get());
EXPECT_STREQ("00:02.0", hwDeviceIds[0]->as<HwDeviceIdDrm>()->getPciPath());
EXPECT_NE(nullptr, hwDeviceIds[1].get());
EXPECT_STREQ("00:03.0", hwDeviceIds[1]->as<HwDeviceIdDrm>()->getPciPath());
}
TEST(DrmTest, GivenMultipleAvailableDevicesWhenCreateMultipleRootDevicesFlagIsSetThenTheFlagIsRespected) {
DebugManagerStateRestore stateRestore;
VariableBackup<decltype(openFull)> backupOpenFull(&openFull);
openFull = openWithCounter;
ExecutionEnvironment executionEnvironment;
const uint32_t requestedNumRootDevices = 2u;
DebugManager.flags.CreateMultipleRootDevices.set(requestedNumRootDevices);
openCounter = 4;
auto hwDeviceIds = OSInterface::discoverDevices(executionEnvironment);
EXPECT_STREQ("/dev/dri/by-path/pci-0000:test2-render", lastOpenedPath.c_str());
EXPECT_EQ(requestedNumRootDevices, hwDeviceIds.size());
EXPECT_NE(nullptr, hwDeviceIds[0].get());
EXPECT_STREQ("test1", hwDeviceIds[0]->as<HwDeviceIdDrm>()->getPciPath());
EXPECT_NE(nullptr, hwDeviceIds[1].get());
EXPECT_STREQ("test2", hwDeviceIds[1]->as<HwDeviceIdDrm>()->getPciPath());
}
TEST(DrmTest, GivenSelectedIncorectDeviceWhenGetDeviceFdThenFail) {
DebugManagerStateRestore stateRestore;
DebugManager.flags.ForceDeviceId.set("1234");
VariableBackup<decltype(openFull)> backupOpenFull(&openFull);
openFull = testOpen;
openRetVal = 1024;
ExecutionEnvironment executionEnvironment;
auto hwDeviceIds = OSInterface::discoverDevices(executionEnvironment);
EXPECT_TRUE(hwDeviceIds.empty());
}
TEST(DrmTest, givenUseVmBindFlagWhenOverrideBindSupportThenReturnProperValue) {
DebugManagerStateRestore dbgRestorer;
bool useVmBind = false;
DebugManager.flags.UseVmBind.set(1);
Drm::overrideBindSupport(useVmBind);
EXPECT_TRUE(useVmBind);
DebugManager.flags.UseVmBind.set(0);
Drm::overrideBindSupport(useVmBind);
EXPECT_FALSE(useVmBind);
DebugManager.flags.UseVmBind.set(-1);
Drm::overrideBindSupport(useVmBind);
EXPECT_FALSE(useVmBind);
}
TEST_F(DrmTests, GivenErrorCodeWhenCreatingDrmThenDrmCreatedOnlyWithSpecificErrors) {
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_NE(drm, nullptr);
drm_i915_getparam_t getParam;
int lDeviceId;
VariableBackup<decltype(ioctlCnt)> backupIoctlCnt(&ioctlCnt);
VariableBackup<int> backupIoctlSeq(&ioctlSeq[0]);
ioctlCnt = 0;
ioctlSeq[0] = -1;
errno = EINTR;
// check if device works, although there was EINTR error from KMD
getParam.param = I915_PARAM_CHIPSET_ID;
getParam.value = &lDeviceId;
auto ret = drm->ioctl(DRM_IOCTL_I915_GETPARAM, &getParam);
EXPECT_EQ(0, ret);
EXPECT_EQ(deviceId, lDeviceId);
ioctlCnt = 0;
ioctlSeq[0] = -1;
errno = EAGAIN;
// check if device works, although there was EAGAIN error from KMD
getParam.param = I915_PARAM_CHIPSET_ID;
getParam.value = &lDeviceId;
ret = drm->ioctl(DRM_IOCTL_I915_GETPARAM, &getParam);
EXPECT_EQ(0, ret);
EXPECT_EQ(deviceId, lDeviceId);
ioctlCnt = 0;
ioctlSeq[0] = -1;
errno = EBUSY;
// check if device works, although there was EBUSY error from KMD
getParam.param = I915_PARAM_CHIPSET_ID;
getParam.value = &lDeviceId;
ret = drm->ioctl(DRM_IOCTL_I915_GETPARAM, &getParam);
EXPECT_EQ(0, ret);
EXPECT_EQ(deviceId, lDeviceId);
ioctlCnt = 0;
ioctlSeq[0] = -1;
errno = 0;
// we failed with any other error code
getParam.param = I915_PARAM_CHIPSET_ID;
getParam.value = &lDeviceId;
ret = drm->ioctl(DRM_IOCTL_I915_GETPARAM, &getParam);
EXPECT_EQ(-1, ret);
EXPECT_EQ(deviceId, lDeviceId);
}
TEST_F(DrmTests, WhenCreatingTwiceThenDifferentDrmReturned) {
auto drm1 = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_NE(drm1, nullptr);
auto drm2 = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_NE(drm2, nullptr);
EXPECT_NE(drm1, drm2);
}
TEST_F(DrmTests, WhenDriDeviceFoundThenDrmCreatedOnFallback) {
VariableBackup<decltype(haveDri)> backupHaveDri(&haveDri);
haveDri = 1;
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_NE(drm, nullptr);
}
TEST_F(DrmTests, GivenNoDeviceWhenCreatingDrmThenNullIsReturned) {
VariableBackup<decltype(haveDri)> backupHaveDri(&haveDri);
haveDri = -1;
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_EQ(drm, nullptr);
}
TEST_F(DrmTests, GivenUnknownDeviceWhenCreatingDrmThenNullIsReturned) {
DebugManagerStateRestore dbgRestorer;
DebugManager.flags.PrintDebugMessages.set(true);
VariableBackup<decltype(deviceId)> backupDeviceId(&deviceId);
deviceId = -1;
::testing::internal::CaptureStderr();
::testing::internal::CaptureStdout();
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_EQ(drm, nullptr);
std::string errStr = ::testing::internal::GetCapturedStderr();
EXPECT_THAT(errStr, ::testing::HasSubstr(std::string("FATAL: Unknown device: deviceId: ffffffff, revisionId: 0000")));
::testing::internal::GetCapturedStdout();
}
TEST_F(DrmTests, GivenNoSoftPinWhenCreatingDrmThenNullIsReturned) {
VariableBackup<decltype(haveSoftPin)> backupHaveSoftPin(&haveSoftPin);
haveSoftPin = 0;
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_EQ(drm, nullptr);
}
TEST_F(DrmTests, WhenCantFindDeviceIdThenDrmIsNotCreated) {
VariableBackup<decltype(failOnDeviceId)> backupFailOnDeviceId(&failOnDeviceId);
failOnDeviceId = -1;
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_EQ(drm, nullptr);
}
TEST_F(DrmTests, WhenCantQueryEuCountThenDrmIsNotCreated) {
VariableBackup<decltype(failOnEuTotal)> backupfailOnEuTotal(&failOnEuTotal);
failOnEuTotal = -1;
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_EQ(drm, nullptr);
}
TEST_F(DrmTests, WhenCantQuerySubsliceCountThenDrmIsNotCreated) {
VariableBackup<decltype(failOnSubsliceTotal)> backupfailOnSubsliceTotal(&failOnSubsliceTotal);
failOnSubsliceTotal = -1;
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_EQ(drm, nullptr);
}
TEST_F(DrmTests, WhenCantQueryRevisionIdThenDrmIsNotCreated) {
VariableBackup<decltype(failOnRevisionId)> backupFailOnRevisionId(&failOnRevisionId);
failOnRevisionId = -1;
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_EQ(drm, nullptr);
}
TEST_F(DrmTests, WhenCantQuerySoftPinSupportThenDrmIsNotCreated) {
VariableBackup<decltype(failOnSoftPin)> backupFailOnSoftPin(&failOnSoftPin);
failOnSoftPin = -1;
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_EQ(drm, nullptr);
}
TEST_F(DrmTests, GivenFailOnParamBoostWhenCreatingDrmThenDrmIsCreated) {
VariableBackup<decltype(failOnParamBoost)> backupFailOnParamBoost(&failOnParamBoost);
failOnParamBoost = -1;
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
//non-fatal error - issue warning only
EXPECT_NE(drm, nullptr);
}
TEST_F(DrmTests, GivenFailOnContextCreateWhenCreatingDrmThenDrmIsCreated) {
VariableBackup<decltype(failOnContextCreate)> backupFailOnContextCreate(&failOnContextCreate);
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_NE(drm, nullptr);
failOnContextCreate = -1;
EXPECT_THROW(drm->createDrmContext(1, false), std::exception);
EXPECT_FALSE(drm->isPreemptionSupported());
failOnContextCreate = 0;
}
TEST_F(DrmTests, GivenFailOnSetPriorityWhenCreatingDrmThenDrmIsCreated) {
VariableBackup<decltype(failOnSetPriority)> backupFailOnSetPriority(&failOnSetPriority);
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_NE(drm, nullptr);
failOnSetPriority = -1;
auto drmContext = drm->createDrmContext(1, false);
EXPECT_THROW(drm->setLowPriorityContextParam(drmContext), std::exception);
EXPECT_FALSE(drm->isPreemptionSupported());
failOnSetPriority = 0;
}
TEST_F(DrmTests, WhenCantQueryDrmVersionThenDrmIsNotCreated) {
VariableBackup<decltype(failOnDrmVersion)> backupFailOnDrmVersion(&failOnDrmVersion);
failOnDrmVersion = -1;
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_EQ(drm, nullptr);
failOnDrmVersion = 0;
}
TEST_F(DrmTests, GivenInvalidDrmVersionNameWhenCreatingDrmThenNullIsReturned) {
VariableBackup<decltype(failOnDrmVersion)> backupFailOnDrmVersion(&failOnDrmVersion);
strcpy(providedDrmVersion, "NA");
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_EQ(drm, nullptr);
failOnDrmVersion = 0;
strcpy(providedDrmVersion, "i915");
}
TEST_F(DrmTests, whenDrmIsCreatedThenSetMemoryRegionsDoesntFailAndDrmObjectIsReturned) {
DebugManagerStateRestore restore;
DebugManager.flags.EnableLocalMemory.set(1);
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_NE(drm, nullptr);
}
TEST(AllocatorHelper, givenExpectedSizeToReserveWhenGetSizeToReserveCalledThenExpectedValueReturned) {
EXPECT_EQ((maxNBitValue(47) + 1) / 4, NEO::getSizeToReserve());
}
TEST(DrmMemoryManagerCreate, whenCallCreateMemoryManagerThenDrmMemoryManagerIsCreated) {
MockExecutionEnvironment executionEnvironment(defaultHwInfo.get());
auto drm = new DrmMockSuccess(fakeFd, *executionEnvironment.rootDeviceEnvironments[0]);
executionEnvironment.rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment.rootDeviceEnvironments[0]->osInterface->setDriverModel(std::unique_ptr<DriverModel>(drm));
auto drmMemoryManager = MemoryManager::createMemoryManager(executionEnvironment);
EXPECT_NE(nullptr, drmMemoryManager.get());
executionEnvironment.memoryManager = std::move(drmMemoryManager);
}
TEST(OsInterfaceTests, givenOsInterfaceWhenEnableLocalMemoryIsSpecifiedThenItIsSetToTrueOn64Bit) {
EXPECT_TRUE(OSInterface::osEnableLocalMemory);
}
TEST_F(DrmTests, whenDrmIsCreatedWithMultipleSubDevicesThenCreateMultipleVirtualMemoryAddressSpaces) {
DebugManagerStateRestore restore;
DebugManager.flags.CreateMultipleSubDevices.set(2);
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_NE(drm, nullptr);
if (drm->isPerContextVMRequired()) {
GTEST_SKIP();
}
auto numSubDevices = HwHelper::getSubDevicesCount(rootDeviceEnvironment->getHardwareInfo());
for (auto id = 0u; id < numSubDevices; id++) {
EXPECT_EQ(id + 1, drm->getVirtualMemoryAddressSpace(id));
}
}
TEST_F(DrmTests, givenDebuggingEnabledWhenDrmIsCreatedThenPerContextVMIsTrueGetVirtualMemoryAddressSpaceReturnsZeroAndVMsAreNotCreated) {
DebugManagerStateRestore restore;
DebugManager.flags.CreateMultipleSubDevices.set(2);
DebugManager.flags.UseVmBind.set(1);
rootDeviceEnvironment->executionEnvironment.setDebuggingEnabled();
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
ASSERT_NE(drm, nullptr);
if (drm->isVmBindAvailable()) {
EXPECT_TRUE(drm->isPerContextVMRequired());
auto numSubDevices = HwHelper::getSubDevicesCount(rootDeviceEnvironment->getHardwareInfo());
for (auto id = 0u; id < numSubDevices; id++) {
EXPECT_EQ(0u, drm->getVirtualMemoryAddressSpace(id));
}
EXPECT_EQ(0u, static_cast<DrmWrap *>(drm.get())->virtualMemoryIds.size());
}
}
TEST_F(DrmTests, givenEnabledDebuggingAndVmBindNotAvailableWhenDrmIsCreatedThenPerContextVMIsFalseVMsAreCreatedAndDebugMessageIsPrinted) {
DebugManagerStateRestore restore;
::testing::internal::CaptureStderr();
::testing::internal::CaptureStdout();
DebugManager.flags.CreateMultipleSubDevices.set(2);
DebugManager.flags.UseVmBind.set(0);
DebugManager.flags.PrintDebugMessages.set(true);
rootDeviceEnvironment->executionEnvironment.setDebuggingEnabled();
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_NE(drm, nullptr);
if (drm->isPerContextVMRequired()) {
::testing::internal::GetCapturedStdout();
::testing::internal::GetCapturedStderr();
GTEST_SKIP();
}
auto numSubDevices = HwHelper::getSubDevicesCount(rootDeviceEnvironment->getHardwareInfo());
for (auto id = 0u; id < numSubDevices; id++) {
EXPECT_NE(0u, drm->getVirtualMemoryAddressSpace(id));
}
EXPECT_NE(0u, static_cast<DrmWrap *>(drm.get())->virtualMemoryIds.size());
DebugManager.flags.PrintDebugMessages.set(false);
::testing::internal::GetCapturedStdout();
std::string errStr = ::testing::internal::GetCapturedStderr();
EXPECT_THAT(errStr, ::testing::HasSubstr(std::string("WARNING: Debugging not supported\n")));
}
TEST_F(DrmTests, givenDrmIsCreatedWhenCreateVirtualMemoryFailsThenReturnVirtualMemoryIdZeroAndPrintDebugMessage) {
DebugManagerStateRestore dbgRestorer;
DebugManager.flags.PrintDebugMessages.set(true);
VariableBackup<decltype(failOnVirtualMemoryCreate)> backupFailOnVirtualMemoryCreate(&failOnVirtualMemoryCreate);
failOnVirtualMemoryCreate = -1;
::testing::internal::CaptureStderr();
::testing::internal::CaptureStdout();
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_NE(drm, nullptr);
EXPECT_EQ(0u, drm->getVirtualMemoryAddressSpace(0));
EXPECT_EQ(0u, static_cast<DrmWrap *>(drm.get())->virtualMemoryIds.size());
std::string errStr = ::testing::internal::GetCapturedStderr();
if (!drm->isPerContextVMRequired()) {
EXPECT_THAT(errStr, ::testing::HasSubstr(std::string("INFO: Device doesn't support GEM Virtual Memory")));
}
::testing::internal::GetCapturedStdout();
}
TEST(SysCalls, WhenSysCallsPollCalledThenCallIsRedirectedToOs) {
struct pollfd pollFd;
pollFd.fd = 0;
pollFd.events = 0;
auto result = NEO::SysCalls::poll(&pollFd, 1, 0);
EXPECT_LE(0, result);
}
TEST(SysCalls, WhenSysCallsFstatCalledThenCallIsRedirectedToOs) {
struct stat st = {};
auto result = NEO::SysCalls::fstat(0, &st);
EXPECT_EQ(0, result);
}
int main(int argc, char **argv) {
bool useDefaultListener = false;
::testing::InitGoogleTest(&argc, argv);
// parse remaining args assuming they're mine
for (int i = 1; i < argc; ++i) {
if (!strcmp("--disable_default_listener", argv[i])) {
useDefaultListener = false;
} else if (!strcmp("--enable_default_listener", argv[i])) {
useDefaultListener = true;
}
}
if (useDefaultListener == false) {
auto &listeners = ::testing::UnitTest::GetInstance()->listeners();
auto defaultListener = listeners.default_result_printer();
auto customEventListener = new CCustomEventListener(defaultListener);
listeners.Release(defaultListener);
listeners.Append(customEventListener);
}
defaultHwInfo = std::make_unique<HardwareInfo>();
*defaultHwInfo = DEFAULT_TEST_PLATFORM::hwInfo;
initializeTestedDevice();
auto retVal = RUN_ALL_TESTS();
return retVal;
}
TEST_F(DrmTests, whenCreateDrmIsCalledThenProperHwInfoIsSetup) {
auto oldHwInfo = rootDeviceEnvironment->getMutableHardwareInfo();
*oldHwInfo = {};
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
EXPECT_NE(drm, nullptr);
auto currentHwInfo = rootDeviceEnvironment->getHardwareInfo();
EXPECT_NE(IGFX_UNKNOWN, currentHwInfo->platform.eProductFamily);
EXPECT_NE(IGFX_UNKNOWN_CORE, currentHwInfo->platform.eRenderCoreFamily);
EXPECT_LT(0u, currentHwInfo->gtSystemInfo.EUCount);
EXPECT_LT(0u, currentHwInfo->gtSystemInfo.SubSliceCount);
}
TEST(PlatformsDestructor, whenGlobalPlatformsDestructorIsCalledThenGlobalPlatformsAreDestroyed) {
EXPECT_NE(nullptr, platformsImpl);
platformsDestructor();
EXPECT_EQ(nullptr, platformsImpl);
platformsImpl = new std::vector<std::unique_ptr<Platform>>;
}
TEST_F(DrmTests, givenInvalidPciPathThenPciBusInfoIsNotAvailable) {
VariableBackup<decltype(openFull)> backupOpenFull(&openFull);
VariableBackup<decltype(failOnOpenDir)> backupOpenDir(&failOnOpenDir, false);
VariableBackup<decltype(entryIndex)> backupEntryIndex(&entryIndex, 0u);
openFull = openWithCounter;
entryIndex = 1;
openCounter = 1;
const uint32_t invVal = PhysicalDevicePciBusInfo::InvalidValue;
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
ASSERT_NE(drm, nullptr);
EXPECT_EQ(drm->getPciBusInfo().pciDomain, invVal);
EXPECT_EQ(drm->getPciBusInfo().pciBus, invVal);
EXPECT_EQ(drm->getPciBusInfo().pciDevice, invVal);
EXPECT_EQ(drm->getPciBusInfo().pciFunction, invVal);
}
TEST_F(DrmTests, givenValidPciPathThenPciBusInfoIsAvailable) {
VariableBackup<decltype(openFull)> backupOpenFull(&openFull);
VariableBackup<decltype(failOnOpenDir)> backupOpenDir(&failOnOpenDir, false);
VariableBackup<decltype(entryIndex)> backupEntryIndex(&entryIndex, 0u);
openFull = openWithCounter;
entryIndex = 4;
openCounter = 2;
auto drm = DrmWrap::createDrm(*rootDeviceEnvironment);
ASSERT_NE(drm, nullptr);
EXPECT_EQ(drm->getPciBusInfo().pciDomain, 0u);
EXPECT_EQ(drm->getPciBusInfo().pciBus, 0u);
EXPECT_EQ(drm->getPciBusInfo().pciDevice, 2u);
EXPECT_EQ(drm->getPciBusInfo().pciFunction, 1u);
entryIndex = 5;
openCounter = 1;
drm = DrmWrap::createDrm(*rootDeviceEnvironment);
ASSERT_NE(drm, nullptr);
EXPECT_EQ(drm->getPciBusInfo().pciDomain, 0u);
EXPECT_EQ(drm->getPciBusInfo().pciBus, 3u);
EXPECT_EQ(drm->getPciBusInfo().pciDevice, 0u);
EXPECT_EQ(drm->getPciBusInfo().pciFunction, 0u);
}
|
#include "renderer.h"
#include "vector_math.cuh"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4996)
#endif
#include <boost/gil/image.hpp>
#include <boost/gil/image_view.hpp>
#include <boost/gil/extension/io/bmp.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <chrono>
#include <iostream>
rol::Renderer::Renderer(size_t w, size_t h)
: m_width(w), m_height(h)
{
}
void
rol::Renderer::saveFrameBmp(const char* filename)
{
auto w = width();
auto h = height();
boost::gil::rgb8_image_t image(w, h);
auto const& dstImageView = boost::gil::view(image);
const fptype3* data = imageData();
// Sure, we could parallelize this, but in the grand scheme of things, how much
// time will an in-memory copy+scaling of w*h pixels (parallelizable) take
// compared to a memory->disk transfer (not parallelizable)?
for (size_t y = 0ul; y < h; ++y)
{
auto baseIdx = y * w;
auto yinv = h - 1 - y; // GIL images are 'upside down' compared to our view.
for (size_t x = 0ul; x < w; ++x)
{
auto idx = baseIdx + x;
auto fr = data[idx].x * 255.;
auto fg = data[idx].y * 255.;
auto fb = data[idx].z * 255.;
auto r = std::clamp(static_cast<int>(fr), 0, 255);
auto g = std::clamp(static_cast<int>(fg), 0, 255);
auto b = std::clamp(static_cast<int>(fb), 0, 255);
dstImageView(x, yinv) = boost::gil::rgb8_pixel_t(
static_cast<unsigned char>(r),
static_cast<unsigned char>(g),
static_cast<unsigned char>(b));
}
}
auto const& view = boost::gil::view(image);
boost::gil::write_view(filename, view, boost::gil::bmp_tag());
}
void
rol::Renderer::render(const Game& game, const Camera& camera)
{
auto aspect = aspectRatio();
auto screenMin = makeFp2(camera.origin.y - 0.5f, camera.origin.z - 0.5f / aspect);
auto screenMax = makeFp2(camera.origin.y + 0.5f, camera.origin.z + 0.5f / aspect);
using clock = std::chrono::steady_clock;
auto start = clock::now();
produceFrame(game, camera, screenMin, screenMax);
auto end = clock::now();
using ftime = std::chrono::duration<double>;
ftime frameTime = end - start;
auto frameSeconds = frameTime.count();
m_lastFrameSecs = frameSeconds;
if (frameSeconds > 1.)
{
std::cout << "Frame time: " << frameSeconds << "s" << std::endl;
}
else if (frameSeconds > 1e-3)
{
std::cout << "Frame time: " << frameSeconds * 1e3 << "ms" << std::endl;
}
else
{
std::cout << "Frame time: " << frameSeconds * 1e6 << "us" << std::endl;
}
}
|
.pushaddr
.addr =MapperTable+4*2
.data16 _Mapper4__Main
.addr =Mapper_Memory
Mapper4_BankSelect:
.fill 1
Mapper4_BankValues:
// 2 bytes per bank; [0] = current bank, [1] = non-zero when changed at least once
.fill 12
Mapper4_IRQ_Latch:
.fill 1
Mapper4_IRQ_Line:
.fill 1
Mapper4_IRQ_Enabled:
.fill 1
.pulladdr
.mx 0x00
Mapper4__Main:
// Load current bank address
ldx #_Mapper1__Main/0x10000
stx $.DP_ZeroBank
// Apply bit mask
and #0xe001
IOPort_Compare 0xe000, bne, Mapper4__e000
IOPort_Compare 0xe001, bne, Mapper4__e001
IOPort_Compare 0xc000, bne, Mapper4__c000
IOPort_Compare 0xc001, bne, Mapper4__c001
IOPort_Compare 0xa000, bne, Mapper4__a000
IOPort_Compare 0xa001, bne, Mapper4__a001
IOPort_Compare 0x8000, bne, Mapper4__8000
IOPort_Compare 0x8001, bne, Mapper4__8001
IOPort_CompareEnd
.mx 0x30
// -----------------------------------------------------------------------
Mapper4__Error:
rtl
// -----------------------------------------------------------------------
.macro Mapper4__DirectIndexed0 reg, dest0, dest1
php
xba
t{0}a
lsr a
xba
bcs $+b_else__
plp
jmp $_{1}
b_else__:
plp
jmp $_{2}
.endm
.macro Mapper4__DirectIndexed1 reg, dest0, dest1
php
xba
t{0}a
lsr a
xba
bcc $+b_else__
plp
jmp $_{1}
b_else__:
plp
jmp $_{2}
.endm
// -----------------------------------------------------------------------
// Bank select
Mapper4__8000:
iIOPort_InterfaceSwitch Mapper4__Error
case iIOPort_stax
Mapper4__DirectIndexed0 x, Mapper4__8000_stai, Mapper4__8001_stai
case iIOPort_stay
Mapper4__DirectIndexed0 y, Mapper4__8000_stai, Mapper4__8001_stai
case iIOPort_sty
php
xba
sty $_IO_temp
tya
bra $+b_in
case iIOPort_stx
php
xba
stx $_IO_temp
txa
//bra $+b_in
b_in:
// Detect changes
//lda $_IO_temp
eor $_Mapper4_BankSelect
// Test high bits
bit #0xc0
bne $+b_1
// Save current value
lda $_IO_temp
sta $_Mapper4_BankSelect
// Return
xba
plp
rtl
b_1:
// Bit 7, CHR bank rule
bit #0x80
beq $+b_1
pha
lda $_IO_temp
rol a
rol a
sta $_IO_MapperChrBankSwap
pla
b_1:
// Bit 6, PRG bank rule
bit #0x40
beq $+b_1
pha
phx
// Swap PRG bank rule
lda $_Program_BankNum_8000
ldx $_Program_BankNum_c000
sta $_Program_BankNum_c000
stx $_Program_BankNum_8000
// Reload Snes bank numbers
//ldx $_Program_BankNum_8000
lda $=RomInfo_BankLut_80,x
sta $_Program_Bank_0+2
ldx $_Program_BankNum_c000
lda $=RomInfo_BankLut_c0,x
sta $_Program_Bank_2+2
// Reset active bank
stz $_Memory_NesBank
plx
pla
b_1:
// Save current value
lda $_IO_temp
sta $_Mapper4_BankSelect
// Return
xba
plp
rtl
case iIOPort_sta
CoreCall_Begin
CoreCall_UseN
CoreCall_UseZ
CoreCall_Push
CoreCall_CopyUpTo +b_1
lock
// Detect changes
eor $_Mapper4_BankSelect
// Test high bits
bit #0xc0
beq $+b_else
jsr $=Mapper4__w8000_ai_in
bra $+b_2
b_else:
// Save current value
eor $_Mapper4_BankSelect
sta $_Mapper4_BankSelect
b_2:
unlock
b_1:
CoreCall_IfFreeP +b_1
CoreCall_Remove 1
b_1:
CoreCall_Pull
CoreCall_End
case iIOPort_stai
Mapper4__8000_stai:
php
lock
// Detect changes
eor $_Mapper4_BankSelect
// Test high bits
bit #0xc0
bne $+b_1
// Save current value
eor $_Mapper4_BankSelect
sta $_Mapper4_BankSelect
// Return
plp
rtl
Mapper4__w8000_ai_in:
// Extra push from partial inline code (TODO: Remove the use of carry)
php
b_1:
// Bit 7, CHR bank rule
bit #0x80
beq $+b_1
pha
eor $_Mapper4_BankSelect
rol a
rol a
sta $_IO_MapperChrBankSwap
pla
b_1:
// Bit 6, PRG bank rule
bit #0x40
beq $+b_1
pha
phx
// Swap PRG bank rule
lda $_Program_BankNum_8000
ldx $_Program_BankNum_c000
sta $_Program_BankNum_c000
stx $_Program_BankNum_8000
// Reload Snes bank numbers
//ldx $_Program_BankNum_8000
lda $=RomInfo_BankLut_80,x
sta $_Program_Bank_0+2
ldx $_Program_BankNum_c000
lda $=RomInfo_BankLut_c0,x
sta $_Program_Bank_2+2
// Reset active bank
stz $_Memory_NesBank
plx
pla
b_1:
// Save current value
eor $_Mapper4_BankSelect
sta $_Mapper4_BankSelect
// Return
plp
rtl
// -----------------------------------------------------------------------
// Bank value
Mapper4__8001:
iIOPort_InterfaceSwitch Mapper4__Error
case iIOPort_stax
Mapper4__DirectIndexed1 x, Mapper4__8000_stai, Mapper4__8001_stai
case iIOPort_stay
Mapper4__DirectIndexed1 y, Mapper4__8000_stai, Mapper4__8001_stai
case iIOPort_stx
php
stx $_IO_temp
bra $+b_in
case iIOPort_sty
php
sty $_IO_temp
bra $+b_in
case iIOPort_sta
case iIOPort_stai
Mapper4__8001_stai:
php
sta $_IO_temp
b_in:
xba
phx
// Get bank number and execute code for this bank
lda $_Mapper4_BankSelect
asl a
tax
jmp ($_Mapper4__8001_Switch,x)
Mapper4__8001_SwitchEnd:
.macro Mapper4__8001_ExitMac
// Return
plx
xba
plp
rtl
.endm
Mapper4__8001_ExitMac
Mapper4__8001_Switch:
.macro Mapper4__8001_Switch_RepeatMac
.data16 _Mapper4__8001_Switch_0, _Mapper4__8001_Switch_1, _Mapper4__8001_Switch_2, _Mapper4__8001_Switch_3
.data16 _Mapper4__8001_Switch_4, _Mapper4__8001_Switch_5, _Mapper4__8001_Switch_6, _Mapper4__8001_Switch_7
.data16 _Mapper4__8001_Switch_0, _Mapper4__8001_Switch_1, _Mapper4__8001_Switch_2, _Mapper4__8001_Switch_3
.data16 _Mapper4__8001_Switch_4, _Mapper4__8001_Switch_5, _Mapper4__8001_Switch_6, _Mapper4__8001_Switch_7
.endm
Mapper4__8001_Switch_RepeatMac
Mapper4__8001_Switch_RepeatMac
Mapper4__8001_Switch_RepeatMac
Mapper4__8001_Switch_RepeatMac
Mapper4__8001_Switch_RepeatMac
Mapper4__8001_Switch_RepeatMac
Mapper4__8001_Switch_RepeatMac
Mapper4__8001_Switch_RepeatMac
// Send CHR change to our NMI queue as follow:
// ChrBank(u8 highBitsVramAddr, u16 highBitsSourceAddr, u8 highBitsLength)
.macro Mapper4__8001_Switch_CHRmac ChrSetIndex, CommentAnd
lda $_IO_temp
{1}and #0xfe
sta $_CHR_{0}_NesBank
Mapper4__8001_ExitMac
.endm
Mapper4__8001_Switch_0:
Mapper4__8001_Switch_CHRmac 0, ""
Mapper4__8001_Switch_1:
Mapper4__8001_Switch_CHRmac 1, ""
Mapper4__8001_Switch_2:
Mapper4__8001_Switch_CHRmac 2, "//"
Mapper4__8001_Switch_3:
Mapper4__8001_Switch_CHRmac 3, "//"
Mapper4__8001_Switch_4:
Mapper4__8001_Switch_CHRmac 4, "//"
Mapper4__8001_Switch_5:
Mapper4__8001_Switch_CHRmac 5, "//"
Mapper4__8001_Switch_6:
// Reset active bank
stz $_Memory_NesBank
// Semi-dynamic PRG bank
ldx $_IO_temp
bit $_Mapper4_BankSelect
bvs $+b_else
// Low range
lda $=RomInfo_BankLut_80,x
sta $_Program_Bank_0+2
stx $_Program_BankNum_8000
Mapper4__8001_ExitMac
b_else:
// High range
lda $=RomInfo_BankLut_c0,x
sta $_Program_Bank_2+2
stx $_Program_BankNum_c000
Mapper4__8001_ExitMac
Mapper4__8001_Switch_7:
// Reset active bank
stz $_Memory_NesBank
// Static PRG bank
ldx $_IO_temp
lda $=RomInfo_BankLut_a0,x
sta $_Program_Bank_1+2
stx $_Program_BankNum_a000
Mapper4__8001_ExitMac
// -----------------------------------------------------------------------
// Mirroring
Mapper4__a000:
iIOPort_InterfaceSwitch Mapper4__Error
case iIOPort_stax
Mapper4__DirectIndexed0 x, Mapper4__a000_stai, Mapper4__a001_stai
case iIOPort_stay
Mapper4__DirectIndexed0 y, Mapper4__a000_stai, Mapper4__a001_stai
case iIOPort_stx
stx $_IO_temp
bra $+b_in
case iIOPort_sty
sty $_IO_temp
bra $+b_in
case iIOPort_sta
case iIOPort_stai
Mapper4__a000_stai:
sta $_IO_temp
b_in:
php
pha
phx
// Load mirrors: 2x1, 1x2
lda $_IO_temp
and #0x01
inc a
jsr $=Gfx__NameTableMirrorChange
plx
pla
plp
rtl
// -----------------------------------------------------------------------
// SRAM protection
Mapper4__a001:
iIOPort_InterfaceSwitch Mapper4__Error
case iIOPort_stax
Mapper4__DirectIndexed1 x, Mapper4__a000_stai, Mapper4__a001_stai
case iIOPort_stay
Mapper4__DirectIndexed1 y, Mapper4__a000_stai, Mapper4__a001_stai
case iIOPort_stx
case iIOPort_sty
case iIOPort_sta
CoreCall_Begin
CoreCall_End
case iIOPort_stai
Mapper4__a001_stai:
// TODO
rtl
// -----------------------------------------------------------------------
// IRQ latch
Mapper4__c000:
iIOPort_InterfaceSwitch Mapper4__Error
case iIOPort_stax
Mapper4__DirectIndexed0 x, Mapper4__c000_stai, Mapper4__c001_stai
case iIOPort_stay
Mapper4__DirectIndexed0 y, Mapper4__c000_stai, Mapper4__c001_stai
case iIOPort_stx
CoreCall_Begin
CoreCall_CopyUpTo +b_1
stx $_Mapper4_IRQ_Latch
b_1:
CoreCall_End
case iIOPort_sty
CoreCall_Begin
CoreCall_CopyUpTo +b_1
sty $_Mapper4_IRQ_Latch
b_1:
CoreCall_End
rtl
case iIOPort_sta
CoreCall_Begin
CoreCall_CopyUpTo +b_1
sta $_Mapper4_IRQ_Latch
b_1:
CoreCall_End
rtl
case iIOPort_stai
Mapper4__c000_stai:
sta $_Mapper4_IRQ_Latch
rtl
// -----------------------------------------------------------------------
// IRQ reload
Mapper4__c001:
iIOPort_InterfaceSwitch Mapper4__Error
case iIOPort_stax
Mapper4__DirectIndexed1 x, Mapper4__c000_stai, Mapper4__c001_stai
case iIOPort_stay
Mapper4__DirectIndexed1 y, Mapper4__c000_stai, Mapper4__c001_stai
case iIOPort_stx
case iIOPort_sty
case iIOPort_sta
CoreCall_Begin
CoreCall_UseA8
CoreCall_UseN
CoreCall_UseV
CoreCall_UseZ
CoreCall_UseC
CoreCall_Push
CoreCall_CopyUpTo +b_1
// Calculate next IRQ hit
lda $_Scanline
cmp #0x01
adc $_Mapper4_IRQ_Latch
clc
adc $=RomInfo_IrqOffset
sta $_Mapper4_IRQ_Line
and $_Mapper4_IRQ_Enabled
sta $_Scanline_IRQ
b_1:
CoreCall_Pull
CoreCall_End
case iIOPort_stai
Mapper4__c001_stai:
php
xba
//lda $_Mapper4_IRQ_Latch
//inc a
//sta $_Mapper4_IRQ_Line
//and $_Mapper4_IRQ_Enabled
//sta $_Scanline_IRQ
// Calculate next IRQ hit
lda $_Scanline
cmp #0x01
adc $_Mapper4_IRQ_Latch
clc
adc $=RomInfo_IrqOffset
sta $_Mapper4_IRQ_Line
and $_Mapper4_IRQ_Enabled
sta $_Scanline_IRQ
xba
plp
rtl
// -----------------------------------------------------------------------
// IRQ disable
Mapper4__e000:
iIOPort_InterfaceSwitch Mapper4__Error
case iIOPort_stax
Mapper4__DirectIndexed0 x, Mapper4__e000_stai, Mapper4__e001_stai
case iIOPort_stay
Mapper4__DirectIndexed0 y, Mapper4__e000_stai, Mapper4__e001_stai
case iIOPort_stx
case iIOPort_sty
case iIOPort_sta
CoreCall_Begin
CoreCall_CopyUpTo +b_1
stz $_Scanline_IRQ
stz $_Mapper4_IRQ_Enabled
b_1:
CoreCall_End
case iIOPort_stai
Mapper4__e000_stai:
stz $_Scanline_IRQ
stz $_Mapper4_IRQ_Enabled
rtl
// -----------------------------------------------------------------------
// IRQ enable
Mapper4__e001:
iIOPort_InterfaceSwitch Mapper4__Error
case iIOPort_stax
Mapper4__DirectIndexed1 x, Mapper4__e000_stai, Mapper4__e001_stai
case iIOPort_stay
Mapper4__DirectIndexed1 y, Mapper4__e000_stai, Mapper4__e001_stai
case iIOPort_stx
case iIOPort_sty
case iIOPort_sta
CoreCall_Begin
CoreCall_UseA8
CoreCall_UseN
CoreCall_UseZ
CoreCall_Push
CoreCall_CopyUpTo +b_1
lda #0xff
sta $_Mapper4_IRQ_Enabled
lda $_Mapper4_IRQ_Line
sta $_Scanline_IRQ
b_1:
CoreCall_Pull
CoreCall_End
case iIOPort_stai
Mapper4__e001_stai:
php
xba
lda #0xff
sta $_Mapper4_IRQ_Enabled
lda $_Mapper4_IRQ_Line
sta $_Scanline_IRQ
xba
plp
rtl
// -----------------------------------------------------------------------
|
********************************************************************************
* Draw an interlaced image to data area
* !!! IRQ should be disabled !!!
*
* input REG : [x] image data address
********************************************************************************
DrawFullscreenInterlacedEvenImage
ldb #$18
stb DFII_a_start+3
stb DFII_b_start+3
ldb #0
stb DFII_a_end+3
stb DFII_b_end+3
bra DrawFullscreenInterlacedImage
DrawFullscreenInterlacedOddImage
ldb #$40
stb DFII_a_start+3
stb DFII_b_start+3
ldb #$28
stb DFII_a_end+3
stb DFII_b_end+3
DrawFullscreenInterlacedImage
pshs u,y,dp,a
sts DFII_a_rts+2
_GetCartPageA
sta DFII_rts+1 ; backup cart page
lda ,x
_SetCartPageA
ldu 1,x
DFII_a_start
lds #$DF40 ; (dynamic)
DFII_a
pulu a,b,dp,x,y
pshs y,x,dp,b,a
pulu a,b,dp,x,y
pshs y,x,dp,b,a
pulu a,b,dp,x,y
pshs y,x,dp,b,a
pulu a,b,dp,x,y
pshs y,x,dp,b,a
pulu a,b,dp,x,y
pshs y,x,dp,b,a
pulu dp,x,y
pshs y,x,dp
DFII_a_end
cmps #$C000 ; (dynamic)
leas -40,s
leau 40,u
bne DFII_a
DFII_b_start
lds #$BF40 ; (dynamic)
DFII_b
pulu a,b,dp,x,y
pshs y,x,dp,b,a
pulu a,b,dp,x,y
pshs y,x,dp,b,a
pulu a,b,dp,x,y
pshs y,x,dp,b,a
pulu a,b,dp,x,y
pshs y,x,dp,b,a
pulu a,b,dp,x,y
pshs y,x,dp,b,a
pulu dp,x,y
pshs y,x,dp
DFII_b_end
cmps #$A000 ; (dynamic)
leas -40,s
leau 40,u
bne DFII_b
DFII_a_rts
lds #$0000 ; (dynamic)
DFII_rts
lda #$00
_SetCartPageA
puls a,dp,y,u,pc |
%include "include/u7si-all-includes.asm"
%include "../u7-common/patch-eop-displayVersion.asm"
|
VIDMEM equ 0xB8000
White_on_Black equ 0x0F
VDriver:
.X: dd 0x00 ; Characters X
.Y: dd 0x00 ; Characters Y
.N: dd 0x00 ; Characters # (X + Y*80)
.W: dd 0x50 ; Screen width
.H: dd 0x18 ; Screen height
.printChr:
pusha
mov ax, bx
push edi
mov edi, [.N]
shl edi, 1
add edi, VIDMEM
mov [edi], ax
mov edi, .N
mov eax, 1
add [edi], eax
jmp .end
.printStr:
pusha
.loop1:
mov bl, [esi]
cmp bl, 0
je .end1
mov bh, White_on_Black
call .printChr
inc esi
jmp .loop1
.end:
pop edi
popa
ret
.end1:
popa
ret
.HEXTEMPLATE: db '0x0000'
.HEXTable: dw '0123456789ABCDEF'
.printHex:
pusha
mov bx, cx
shr bx, 12
mov bl, [.HEXTable + bx]
mov [.HEXTEMPLATE+4], bl
mov bx, cx
shr bx, 8
and bx, 0fh
mov bl, [.HEXTable + bx]
mov [.HEXTEMPLATE+5], bl
mov bx, cx
shr bx, 4
and bx, 0fh
mov bl, [.HEXTable + bx]
mov [.HEXTEMPLATE+2], bl
mov bx, cx
and bx, 0fh
mov bl, [.HEXTable + bx]
mov [.HEXTEMPLATE+3], bl
mov esi, .HEXTEMPLATE
call .printStr
popa
ret
|
; ----------------------------------------------------------------
; Z88DK INTERFACE LIBRARY FOR THE BIFROST* ENGINE - RELEASE 1.2/L
;
; See "bifrost_h.h" for further details
; ----------------------------------------------------------------
; unsigned char *BIFROSTH_findAttrH(unsigned int lin,unsigned int col)
SECTION code_clib
SECTION code_bifrost_h
PUBLIC BIFROSTH_findAttrH
EXTERN asm_BIFROSTH_findAttrH
BIFROSTH_findAttrH:
ld hl,2
add hl,sp
ld c,(hl) ; C=col
inc hl
inc hl
ld l,(hl) ; L=lin
jp asm_BIFROSTH_findAttrH
|
/*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2021 Metrological
*
* 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 "Module.h"
#include "SDPSocket.h"
namespace WPEFramework {
namespace Bluetooth {
namespace SDP {
void Payload::PushDescriptor(const elementtype type, const uint32_t size)
{
ASSERT(Free() >= 1);
uint8_t* buffer = &_buffer[_writerOffset];
uint32_t offset = 0;
buffer[offset++] = (type | SIZE_8);
switch (type) {
case NIL:
ASSERT(size == 0);
// Exception: even if size descriptor says BYTE, for NIL type there's no data following.
break;
case BOOL:
ASSERT(size == 1);
break;
case INT:
case UINT:
if (size == 1) {
// already set
} else if (size == 2) {
buffer[0] |= SIZE_16;
} else if (size == 4) {
buffer[0] |= SIZE_32;
} else if (size == 8) {
buffer[0] |= SIZE_64;
} else {
ASSERT(false && "Invalid INT size");
}
break;
case UUID:
if (size == 2) {
buffer[0] |= SIZE_16;
} else if (size == 4) {
buffer[0] |= SIZE_32;
} else if (size == 16) {
buffer[0] |= SIZE_128;
} else {
ASSERT(false && "Invalid UUID size");
}
break;
case TEXT:
case SEQ:
case ALT:
case URL:
if (size <= 0xFF) {
ASSERT(Free() >= 1);
buffer[0] |= SIZE_U8_FOLLOWS;
} else if (size <= 0xFFFF) {
ASSERT(Free() >= 2);
buffer[0] |= SIZE_U16_FOLLOWS;
buffer[offset++] = (size >> 8);
} else {
ASSERT(Free() >= 4);
buffer[0] |= SIZE_U32_FOLLOWS;
buffer[offset++] = (size >> 24);
buffer[offset++] = (size >> 16);
buffer[offset++] = (size >> 8);
}
buffer[offset++] = size;
break;
}
_writerOffset += offset;
}
uint8_t Payload::ReadDescriptor(elementtype& type, uint32_t& size) const
{
uint8_t offset = 0;
uint8_t t = _buffer[_readerOffset + offset++];
switch (t & 7) {
case SIZE_8:
size = 1;
break;
case SIZE_16:
size = 2;
break;
case SIZE_32:
size = 4;
break;
case SIZE_64:
size = 8;
break;
case SIZE_128:
size = 16;
break;
case SIZE_U8_FOLLOWS:
size = _buffer[_readerOffset + offset++];
break;
case SIZE_U16_FOLLOWS:
size = (_buffer[_readerOffset + offset++] << 8);
size |= _buffer[_readerOffset + offset++];
break;
case SIZE_U32_FOLLOWS:
size = (_buffer[_readerOffset + offset++] << 24);
size |= (_buffer[_readerOffset + offset++] << 16);
size |= (_buffer[_readerOffset + offset++] << 8);
size |= _buffer[_readerOffset + offset++];
break;
default:
TRACE_L1("SDP: Unexpected descriptor size [0x%01x]", (t & 7));
size = 0;
break;
}
type = static_cast<elementtype>(t & 0xF8);
if (type == NIL) {
size = 0;
}
return (offset);
}
uint16_t ClientSocket::Command::Response::Deserialize(const uint16_t reqTransactionId, const uint8_t stream[], const uint16_t length)
{
uint16_t result = 0;
CMD_DUMP("SDP client received", stream, length);
if (length >= PDU::HEADER_SIZE) {
const Payload header(stream, PDU::HEADER_SIZE);
uint16_t transactionId{};
uint16_t payloadLength{};
// Pick up the response header
header.Pop(_type);
header.Pop(transactionId);
header.Pop(payloadLength);
if (reqTransactionId == transactionId) {
if (length >= (header.Length() + payloadLength)) {
const Payload parameters((stream + header.Length()), payloadLength);
switch(_type) {
case PDU::ErrorResponse:
parameters.Pop(_status);
break;
case PDU::ServiceSearchResponse:
// In order to tell if the packet is complete we need to parse the payload upfront,
// so let's deserialize the data along the way, too.
_status = DeserializeServiceSearchResponse(parameters);
break;
case PDU::ServiceAttributeResponse:
case PDU::ServiceSearchAttributeResponse: // same response
_status = DeserializeServiceAttributeResponse(parameters);
break;
default:
_status = PDU::DeserializationFailed;
break;
}
result = length;
} else {
TRACE_L1("SDP response too short [%d]", length);
}
} else {
TRACE_L1("Unexpected transaction Id [%d vs %d]", reqTransactionId, transactionId);
}
}
return (result);
}
ClientSocket::PDU::errorid ClientSocket::Command::Response::DeserializeServiceSearchResponse(const Payload& params)
{
PDU::errorid result = PDU::DeserializationFailed;
ASSERT(Type() == PDU::ServiceSearchResponse);
if (params.Length() >= 5) {
Payload payload;
uint16_t totalCount = 0;
uint16_t currentCount = 0;
params.Pop(totalCount);
// Pick up the payload, but not process it yet, wait until the chain of continued packets ends.
params.Pop(currentCount);
params.Peek(payload, (currentCount * sizeof(uint32_t)));
_payload.Push(payload);
// Get continuation data.
Payload::Continuation cont;
params.Pop(cont, _continuationData);
if (cont == Payload::Continuation::ABSENT) {
// No more continued packets, process all the concatenated payloads...
// The payload is a list of DWORD handles.
_payload.Pop(_handles, (_payload.Length() / sizeof(uint32_t)));
result = PDU::Success;
} else {
result = PDU::PacketContinuation;
}
} else {
TRACE_L1("Truncated payload in ServiceSearchResponse [%d]", params.Length());
}
return (result);
}
ClientSocket::PDU::errorid ClientSocket::Command::Response::DeserializeServiceAttributeResponse(const Payload& params)
{
PDU::errorid result = PDU::DeserializationFailed;
ASSERT((Type() == PDU::ServiceAttributeResponse) || (Type() == PDU::ServiceSearchAttributeResponse));
if (params.Length() >= 2) {
uint16_t byteCount = 0;
Payload payload;
// Pick up the payload, but not process it yet, wait until the chain of continued packets ends.
params.Pop(byteCount);
params.Peek(payload, byteCount);
_payload.Push(payload);
// Get continuation data.
Payload::Continuation cont;
params.Pop(cont, _continuationData);
if (cont == Payload::Continuation::ABSENT) {
// No more continued packets, process all the concatenated payloads...
// The payload is a sequence of attribute:value pairs (where value can be a sequence too).
_payload.Pop(use_descriptor, [&](const Payload& sequence) {
while (sequence.Available() > 2) {
uint32_t attribute = 0;
Buffer value;
// Pick up the pair and store it.
sequence.Pop(use_descriptor, attribute);
sequence.Pop(use_descriptor, value);
_attributes.emplace(attribute, value);
}
if (sequence.Available() == 0) {
result = PDU::Success;
}
});
} else {
result = PDU::PacketContinuation;
}
} else {
TRACE_L1("Truncated payload in ServiceAttributeResponse [%d]", params.Length());
}
return (result);
}
uint16_t ServerSocket::Request::Deserialize(const uint8_t stream[], const uint16_t length)
{
uint16_t result = 0;
if (length >= PDU::HEADER_SIZE) {
const Payload header(stream, PDU::HEADER_SIZE);
uint16_t payloadLength{};
// Pick up the response header
header.Pop(_type);
header.Pop(_transactionId);
header.Pop(payloadLength);
if (length >= (header.Length() + payloadLength)) {
const Payload parameters((stream + header.Length()), payloadLength);
switch(_type) {
case PDU::ServiceSearchAttributeRequest:
_status = DeserializeServiceSearchAttributeRequest(parameters);
break;
default:
TRACE_L1("Unknown SDP request [%d]", _type);
_status = PDU::DeserializationFailed;
break;
}
result = length;
} else {
TRACE_L1("SDP request too short [%d]", length);
}
}
return (result);
}
ServerSocket::PDU::errorid SDP::ServerSocket::Request::DeserializeServiceSearchAttributeRequest(const Payload& params)
{
// ServiceSearchAttributeRequest frame format:
// - ServiceSearchPattern (sequence of UUIDs)
// - MaximumAttributeByteCount (word)
// - AttributeIDList (sequence of UUID ranges or UUIDs)
PDU::errorid result = PDU::InvalidRequestSyntax;
if (params.Length() >= 2) {
std::list<UUID> services;
std::list<uint32_t> attributeRanges;
uint16_t maxByteCount;
params.Pop(use_descriptor, [&](const Payload& sequence) {
while (sequence.Available() > 0) {
UUID uuid;
sequence.Pop(use_descriptor, uuid);
services.push_back(uuid);
}
});
params.Pop(maxByteCount); // no descriptor!
params.Pop(use_descriptor, [&](const Payload& sequence) {
while (sequence.Available() > 0) {
uint32_t range{};
uint32_t size{};
sequence.Pop(use_descriptor, range, &size);
if (size == 4) {
attributeRanges.push_back(range);
} else {
// Not a range, but single 16-bit UUID
attributeRanges.push_back((static_cast<uint16_t>(range) << 16) | static_cast<uint16_t>(range));
}
}
});
Payload::Continuation cont;
params.Pop(cont, _continuationData);
if (cont != Payload::Continuation::ABSENT) {
// TODO: Add continuation support to the server.
ASSERT(false && "Unexpected Continuation data as not supported in SDP server");
result = PDU::InvalidContinuationState;
} else {
result = PDU::Success;
}
_server.OnServiceSearchAttribute(_transactionId, services, maxByteCount, attributeRanges);
} else {
TRACE_L1("Truncated payload in ServiceAttributeResponse [%d]", params.Length());
}
if (result != PDU::Success) {
_server.OnError(_transactionId, result);
}
return (result);
}
void ServerSocket::Response::SerializeErrorResponse(PDU::errorid error)
{
// Error Response frame format
// - ErrorCode
const uint16_t errorCode = error;
uint8_t scratchPad[8];
Payload payload(scratchPad, sizeof(scratchPad), 0);
payload.Push(errorCode);
_pdu.Construct(PDU::ErrorResponse, payload);
}
void ServerSocket::Response::SerializeServiceSearchResponse(const std::list<UUID>& /* serviceUuids */, const uint16_t /* maxResults */ )
{
// TODO?
TRACE_L1("SDP ServiceSearechResponse not supported");
SerializeErrorResponse(PDU::UnsupportedSdpVersion);
}
void ServerSocket::Response::SerializeServiceAttributeResponse(const uint32_t /* serviceHandle */ , const uint16_t /* maxBytes */, const std::list<uint32_t>& /* attributeRanges */)
{
// TODO?
TRACE_L1("SDP ServiceAttributeResponse not supported");
}
void ServerSocket::Response::SerializeServiceSearchAttributeResponse(const std::list<UUID>& uuids, uint16_t maxBytes, const std::list<uint32_t>& attributeRanges)
{
// ServiceSearchAttribute frame format:
// - AttributeListsByteCount (word)
// - AttributeLists (sequences of sequences of sequences of attribute id and attribute data)
// - ContinuationState
uint8_t scratchPad[1024];
Payload payload(scratchPad, sizeof(scratchPad), 0);
payload.Push(use_length /* no descriptor! */, [&](Payload& payload) {
payload.Push(use_descriptor, [&](Payload& payload) {
for (const UUID& uuid : uuids) {
payload.Push(use_descriptor, [&](Payload& sequence) {
std::list<uint32_t> handles;
_server.Services(uuid, handles);
for (const uint32_t handle : handles) {
for (const uint32_t range : attributeRanges) {
_server.Serialize(handle, std::pair<uint16_t, uint16_t>(range >> 16, range), [&](const uint16_t id, const Buffer& buffer) {
if (buffer.size() != 0) {
sequence.Push([&](Payload& record) {
record.Push(use_descriptor, id);
record.Push(buffer); // no descriptor here!
});
}
});
}
}
});
}
});
});
if (payload.Length() > maxBytes) {
ASSERT(false && "ServiceSearchAttribute response exceeded maxBytes");
// TODO: Add continuation support to the server.
SerializeErrorResponse(PDU::InsufficientResources); // for the lack of a better error code...
} else {
_pdu.Construct(PDU::ServiceSearchAttributeResponse, payload);
}
}
} // namespace SDP
} // namespace Bluetooth
}
|
#pragma once
#include <array.hpp>
#include <type.hpp>
#include <tuple.hpp>
#include <core/arch.hpp>
namespace eospp::core {
struct IDT_FLAGS {
estd::uint8_t TYPE : 4;
estd::uint8_t ZERO : 1;
estd::uint8_t DPL : 2;
estd::uint8_t PRESENT : 1;
} __attribute__((packed));
static_assert(sizeof(IDT_FLAGS) == 1, "sizeof IDT_FLAGS != 1 byte");
struct IDT_DSC {
estd::uint16_t LOW_OFFSET;
estd::uint16_t SELECTOR;
estd::uint8_t ZERO;
IDT_FLAGS FLAGS;
estd::uint16_t MIDDLE_OFFSET;
estd::uint32_t HIGH_OFFSET;
estd::uint32_t RESERVED;
} __attribute__((packed));
static_assert(sizeof(IDT_DSC) == 16, "sizeof IDT_DSC != 16 byte");
struct IDT {
estd::uint16_t LIMIT;
estd::uint64_t BASE;
} __attribute__((packed));
static_assert(sizeof(IDT) == 10, "sizeof IDT != 10 byte");
using sse_128 = double __attribute__((vector_size(16)));
static_assert(sizeof(sse_128) == 16, "xmm registers are 16 bytes long");
struct fault_regs {
estd::uint64_t rbp;
estd::uint64_t error_no;
estd::uint64_t error_code;
estd::uint64_t rip;
estd::uint64_t cs;
estd::uint64_t rflags;
estd::uint64_t rsp;
estd::uint64_t ss;
} __attribute__((packed));
struct syscall_regs {
estd::uint64_t rax;
estd::uint64_t rbx;
estd::uint64_t rcx;
estd::uint64_t rdx;
estd::uint64_t rsi;
estd::uint64_t rdi;
estd::uint64_t r8;
estd::uint64_t r9;
estd::uint64_t r10;
estd::uint64_t r11;
estd::uint64_t r12;
estd::uint64_t r13;
estd::uint64_t r14;
estd::uint64_t r15;
estd::uint64_t rbp;
estd::uint64_t code;
estd::uint64_t rip;
estd::uint64_t cs;
estd::uint64_t rflags;
estd::uint64_t rsp;
estd::uint64_t ss;
} __attribute__((packed));
using IrqHandler = void(*)(syscall_regs*,void*);
using SysCallHandler = void(*)(syscall_regs*);
class Interrupt {
private:
using Handler = void(*)();
using IrqHandleEntry = estd::tuple<IrqHandler,void*>;
public:
static void Init();
static void TriggerIrq(syscall_regs *regs);
static void TriggerSyscall(syscall_regs *regs);
static void Enable();
static void Disable();
private:
static void InstallIdt();
static void InstallISrs();
static void RemapIrqs();
static void InstallIrqs();
static void InstallSysCalls();
static void setGate(estd::size_t gate,Handler handler,estd::uint16_t selector,IDT_FLAGS flags);
static bool RegisterIrqHandler(estd::size_t irq,IrqHandler handler,void *data);
static bool RegisterSysCall(estd::size_t syscall,SysCallHandler handler);
static bool UnRegisterIrqHandler(estd::size_t irq,IrqHandler handler);
static bool UnRegisterSysCall(estd::size_t syscall,SysCallHandler handler);
private:
static constexpr estd::size_t size{256};
static constexpr estd::size_t syscall_count{10};
static constexpr estd::size_t irq_count{16};
static inline estd::array<IDT_DSC, size> interrupts_;
static inline estd::array<SysCallHandler,syscall_count> syscalls_;
static inline estd::array<IrqHandleEntry,irq_count> irqs_;
static inline IDT idt_;
};
class IrqGuard{
public:
IrqGuard(){
Arch::DisableHwint(rflags);
}
~IrqGuard(){
Arch::EnableHwint(rflags);
}
private:
estd::size_t rflags;
};
} // namespace eospp::core
extern "C" {
void _isr0();
void _isr1();
void _isr2();
void _isr3();
void _isr4();
void _isr5();
void _isr6();
void _isr7();
void _isr8();
void _isr9();
void _isr10();
void _isr11();
void _isr12();
void _isr13();
void _isr14();
void _isr15();
void _isr16();
void _isr17();
void _isr18();
void _isr19();
void _isr20();
void _isr21();
void _isr22();
void _isr23();
void _isr24();
void _isr25();
void _isr26();
void _isr27();
void _isr28();
void _isr29();
void _isr30();
void _isr31();
void _irq0();
void _irq1();
void _irq2();
void _irq3();
void _irq4();
void _irq5();
void _irq6();
void _irq7();
void _irq8();
void _irq9();
void _irq10();
void _irq11();
void _irq12();
void _irq13();
void _irq14();
void _irq15();
void _syscall0();
void _syscall1();
void _syscall2();
void _syscall3();
void _syscall4();
void _syscall5();
void _syscall6();
void _syscall7();
void _syscall8();
void _syscall9();
}
|
// -*- C++ -*-
//
// $Id$
#include "RepoIdSet.h"
#include "EntryExit.h"
ACE_INLINE
TAO::DCPS::RepoIdSetMap::RepoIdSetMap()
{
DBG_ENTRY("RepoIdSetMap","RepoIdSetMap");
}
ACE_INLINE TAO::DCPS::RepoIdSet*
TAO::DCPS::RepoIdSetMap::find(RepoId key)
{
DBG_ENTRY("RepoIdSetMap","find");
RepoIdSet_rch value;
if (this->map_.find(key, value) != 0)
{
return 0;
}
return value._retn();
}
ACE_INLINE size_t
TAO::DCPS::RepoIdSetMap::size() const
{
DBG_ENTRY("RepoIdSetMap","size");
return this->map_.current_size();
}
ACE_INLINE TAO::DCPS::RepoIdSet*
TAO::DCPS::RepoIdSetMap::find_or_create(RepoId key)
{
DBG_ENTRY("RepoIdSetMap","find_or_create");
RepoIdSet_rch value;
if (this->map_.find(key, value) != 0)
{
// It wasn't found. Create one and insert it.
value = new RepoIdSet();
if (this->map_.bind(key, value) != 0)
{
ACE_ERROR((LM_ERROR,
"(%P|%t) ERROR: Unable to insert new RepoIdSet into "
"the RepoIdSetMap.\n"));
// Return a 'nil' RepoIdSet*
return 0;
}
}
return value._retn();
}
ACE_INLINE TAO::DCPS::RepoIdSetMap::MapType&
TAO::DCPS::RepoIdSetMap::map()
{
DBG_SUB_ENTRY("RepoIdSetMap","map",1);
return this->map_;
}
ACE_INLINE const TAO::DCPS::RepoIdSetMap::MapType&
TAO::DCPS::RepoIdSetMap::map() const
{
DBG_SUB_ENTRY("RepoIdSetMap","map",2);
return this->map_;
}
ACE_INLINE size_t
TAO::DCPS::RepoIdSetMap::marshaled_size ()
{
DBG_ENTRY("RepoIdSetMap","marshaled_size");
// serialize len for the map size and set size information.
size_t size = (this->size () + 1) * sizeof (size_t);
size_t num_ids = 0;
MapType::ENTRY* entry;
for (MapType::ITERATOR itr(this->map_);
itr.next(entry);
itr.advance())
{
// one sub id
++ num_ids;
// num of pubids in the RepoIdSet.
num_ids += entry->int_id_->size ();
}
size += num_ids * sizeof (RepoId);
return size;
}
|
;
;
;
; This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
;
; Copyright 2007-2019 Broadcom Inc. All rights reserved.
;
; This example is used for showing the serial EGPHY LEDs on
; bcm956174r on option 11b.
;
; To start it, use the following commands from BCM:
;
; led load bcm956174r.hex
; led auto on
; led start
;
; Each GE port needs to output 2 bits stream,
; bit 0: LED_0 (Link)
; bit 1: LED_1 (Activity)
;
; Totally 24 ports need be outputed, i.e. 48 (= 24 * 2) bits.
; The output sequence for EGPHY will follow the user port sequence.
;
; The LED sequence is (User Port, Front Panel Order)
; 2-9 18-33
; Mapping onto physical port view, the sequence is:
; 26-33 42-57
; The output order should be the inverted sequence of the physical
; mapping view
; 57-42 33-26
; Link up/down info cannot be derived from LINKEN, as the LED
; processor does not always have access to link status. This program
; assumes link status is kept current in bit 0 of RAM byte (0xA0 + portnum).
; Generally, a program running on the main CPU must update these
; locations on link change; see linkscan callback in
; $SDK/src/appl/diag/ledproc.c.
;
;
; Constants
;
; the smaller the TXRX_ALT_TICKS the faster it blinks
TXRX_ALT_TICKS EQU 5
TXRX_ALT_COUNT equ 30
NUM_PORTS equ 24
START_PORT_0 equ 57
END_PORT_0 equ 42
START_PORT_1 equ 33
END_PORT_1 equ 26
;
; LED process
;
start_sec0:
ld a, START_PORT_0
iter_sec0:
port a
ld (PORT_NUM), a
call get_activity_hw
call get_link_hw
ld a, (PORT_NUM)
dec a
cmp a, END_PORT_0 - 1
jnz iter_sec0
start_sec1:
ld a, START_PORT_1
iter_sec1:
port a
ld (PORT_NUM), a
call get_activity_hw
call get_link_hw
ld a, (PORT_NUM)
dec a
cmp a, END_PORT_1 - 1
jnz iter_sec1
update:
inc (TXRX_ALT_COUNT)
end:
send 2*NUM_PORTS
;
; get_link_hw
;
; This routine finds the link status LED for a port from HW.
; Inputs: (PORT_NUM)
; Outputs: Carry flag set if link is up, clear if link is down.
; Destroys: a, b
get_link_hw:
pushst LINKEN
pop
jc led_on
jmp led_off
;
; get_link_sw
;
; This routine finds the link status LED for a port.
; Link info is in bit 0 of the byte read from PORTDATA[port]
; Inputs: (PORT_NUM)
; Outputs: Carry flag set if link is up, clear if link is down.
; Destroys: a, b
get_link_sw:
ld b, PORTDATA
add b, (PORT_NUM)
ld a, (b)
tst a, 0
jc led_on
jmp led_off
;
; get_activity_hw
;
; This routine finds the link status LED for a port from HW.
; Inputs: (PORT_NUM)
; Outputs: Carry flag set if RX or TX is up, clear if link is down.
; Destroys: a, b
get_activity_hw:
port a
pushst RX
pushst TX
tor
pop
jc led_blink ; Show activity
jmp led_off
;
; get_linkact_status
;
; This routine finds the link and activity status for a port from HW.
; The LED will blink if there is activity.
; Inputs: a
; Outputs: LED stream for on or off.
; Destroys: b
get_linkact_status:
port a
pushst LINKEN
pop
jnc led_off ; Always black, No LINK
pushst RX
pushst TX
tor
pop
jc led_blink ; Show activity
jmp led_on ; Show Link
led_blink:
ld b, (TXRX_ALT_COUNT)
and b, TXRX_ALT_TICKS
jz led_on
jmp led_off
;
; led_on
;
; Outputs: Bits to the LED stream indicating ON
;
led_on:
push 0
pack
ret
;
; led_off
;
; Outputs: Bits to the LED stream indicating OFF
;
led_off:
push 1
pack
ret
;
; led_off_2
;
; Outputs: Bits to the LED stream indicating OFF
;
led_off_2:
push 1
pack
push 1
pack
ret
;
; led_green
; For 10G port LED, outputs two bit
; Outputs: Bits to the LED stream indicating GREEN
;
led_green:
push 0
pack
push 0
pack
ret
;
; led_orange
; For 1G port LED, outputs two bit
; Outputs: Bits to the LED stream indicating GREEN
;
led_orange:
push 1
pack
push 0
pack
ret
; Variables (SDK software initializes LED memory from 0xA0-0xff to 0)
PORTDATA equ 0xA0
PORT_NUM equ 0xE0
; Symbolic names for the bits of the port status fields
RX equ 0x0 ; received packet
TX equ 0x1 ; transmitted packet
COLL equ 0x2 ; collision indicator
SPEED_C equ 0x3 ; 100 Mbps
SPEED_M equ 0x4 ; 1000 Mbps
DUPLEX equ 0x5 ; half/full duplex
FLOW equ 0x6 ; flow control capable
LINKUP equ 0x7 ; link down/up status
LINKEN equ 0x8 ; link disabled/enabled status
ZERO equ 0xE ; always 0
ONE equ 0xF ; always 1
|
;
; Copyright (c) 2010 The VP8 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.
;
EXPORT |vp8_yv12_copy_frame_yonly_neon|
EXPORT |vp8_yv12_copy_frame_yonly_no_extend_frame_borders_neon|
ARM
REQUIRE8
PRESERVE8
INCLUDE vpx_asm_offsets.asm
AREA ||.text||, CODE, READONLY, ALIGN=2
;void vpxyv12_copy_frame_yonly(YV12_BUFFER_CONFIG *src_ybc, YV12_BUFFER_CONFIG *dst_ybc);
; Note: this is VP8 function, which has border=32 and 16. Internal y_width and y_height
; are always multiples of 16.
|vp8_yv12_copy_frame_yonly_neon| PROC
push {r4 - r11, lr}
vpush {d8 - d15}
ldr r4, [r0, #yv12_buffer_config_y_height]
ldr r5, [r0, #yv12_buffer_config_y_width]
ldr r6, [r0, #yv12_buffer_config_y_stride]
ldr r7, [r1, #yv12_buffer_config_y_stride]
ldr r2, [r0, #yv12_buffer_config_y_buffer] ;srcptr1
ldr r3, [r1, #yv12_buffer_config_y_buffer] ;dstptr1
; copy two rows at one time
mov lr, r4, lsr #1
cp_src_to_dst_height_loop
mov r8, r2
mov r9, r3
add r10, r2, r6
add r11, r3, r7
mov r12, r5, lsr #7
cp_src_to_dst_width_loop
vld1.8 {q0, q1}, [r8]!
vld1.8 {q8, q9}, [r10]!
vld1.8 {q2, q3}, [r8]!
vld1.8 {q10, q11}, [r10]!
vld1.8 {q4, q5}, [r8]!
vld1.8 {q12, q13}, [r10]!
vld1.8 {q6, q7}, [r8]!
vld1.8 {q14, q15}, [r10]!
subs r12, r12, #1
vst1.8 {q0, q1}, [r9]!
vst1.8 {q8, q9}, [r11]!
vst1.8 {q2, q3}, [r9]!
vst1.8 {q10, q11}, [r11]!
vst1.8 {q4, q5}, [r9]!
vst1.8 {q12, q13}, [r11]!
vst1.8 {q6, q7}, [r9]!
vst1.8 {q14, q15}, [r11]!
bne cp_src_to_dst_width_loop
subs lr, lr, #1
add r2, r2, r6, lsl #1
add r3, r3, r7, lsl #1
bne cp_src_to_dst_height_loop
ands r10, r5, #0x7f ;check to see if extra copy is needed
sub r11, r5, r10
ldr r2, [r0, #yv12_buffer_config_y_buffer] ;srcptr1
ldr r3, [r1, #yv12_buffer_config_y_buffer] ;dstptr1
bne extra_cp_src_to_dst_width
end_of_cp_src_to_dst
;vpxyv12_extend_frame_borders_yonly
mov r0, r1
;Not need to load y_width, since: y_width = y_stride - 2*border
ldr r3, [r0, #yv12_buffer_config_border]
ldr r1, [r0, #yv12_buffer_config_y_buffer] ;srcptr1
ldr r4, [r0, #yv12_buffer_config_y_height]
ldr lr, [r0, #yv12_buffer_config_y_stride]
cmp r3, #16
beq b16_extend_frame_borders
;=======================
b32_extend_frame_borders
;border = 32
;=======================
;Border copy for Y plane
;copy the left and right most columns out
sub r5, r1, r3 ;destptr1
add r6, r1, lr
sub r6, r6, r3, lsl #1 ;destptr2
sub r2, r6, #1 ;srcptr2
;Do four rows at one time
mov r12, r4, lsr #2
copy_left_right_y
vld1.8 {d0[], d1[]}, [r1], lr
vld1.8 {d4[], d5[]}, [r2], lr
vld1.8 {d8[], d9[]}, [r1], lr
vld1.8 {d12[], d13[]}, [r2], lr
vld1.8 {d16[], d17[]}, [r1], lr
vld1.8 {d20[], d21[]}, [r2], lr
vld1.8 {d24[], d25[]}, [r1], lr
vld1.8 {d28[], d29[]}, [r2], lr
vmov q1, q0
vmov q3, q2
vmov q5, q4
vmov q7, q6
vmov q9, q8
vmov q11, q10
vmov q13, q12
vmov q15, q14
subs r12, r12, #1
vst1.8 {q0, q1}, [r5], lr
vst1.8 {q2, q3}, [r6], lr
vst1.8 {q4, q5}, [r5], lr
vst1.8 {q6, q7}, [r6], lr
vst1.8 {q8, q9}, [r5], lr
vst1.8 {q10, q11}, [r6], lr
vst1.8 {q12, q13}, [r5], lr
vst1.8 {q14, q15}, [r6], lr
bne copy_left_right_y
;Now copy the top and bottom source lines into each line of the respective borders
ldr r7, [r0, #yv12_buffer_config_y_buffer] ;srcptr1
mul r8, r3, lr
mov r12, lr, lsr #7
sub r6, r1, r3 ;destptr2
sub r2, r6, lr ;srcptr2
sub r1, r7, r3 ;srcptr1
sub r5, r1, r8 ;destptr1
copy_top_bottom_y
vld1.8 {q0, q1}, [r1]!
vld1.8 {q8, q9}, [r2]!
vld1.8 {q2, q3}, [r1]!
vld1.8 {q10, q11}, [r2]!
vld1.8 {q4, q5}, [r1]!
vld1.8 {q12, q13}, [r2]!
vld1.8 {q6, q7}, [r1]!
vld1.8 {q14, q15}, [r2]!
mov r7, r3
top_bottom_32
subs r7, r7, #1
vst1.8 {q0, q1}, [r5]!
vst1.8 {q8, q9}, [r6]!
vst1.8 {q2, q3}, [r5]!
vst1.8 {q10, q11}, [r6]!
vst1.8 {q4, q5}, [r5]!
vst1.8 {q12, q13}, [r6]!
vst1.8 {q6, q7}, [r5]!
vst1.8 {q14, q15}, [r6]!
add r5, r5, lr
sub r5, r5, #128
add r6, r6, lr
sub r6, r6, #128
bne top_bottom_32
sub r5, r1, r8
add r6, r2, lr
subs r12, r12, #1
bne copy_top_bottom_y
mov r7, lr, lsr #4 ;check to see if extra copy is needed
ands r7, r7, #0x7
bne extra_top_bottom_y
end_of_border_copy_y
vpop {d8 - d15}
pop {r4 - r11, pc}
;=====================
;extra copy part for Y
extra_top_bottom_y
vld1.8 {q0}, [r1]!
vld1.8 {q2}, [r2]!
mov r9, r3, lsr #3
extra_top_bottom_32
subs r9, r9, #1
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
bne extra_top_bottom_32
sub r5, r1, r8
add r6, r2, lr
subs r7, r7, #1
bne extra_top_bottom_y
b end_of_border_copy_y
;=======================
b16_extend_frame_borders
;border = 16
;=======================
;Border copy for Y plane
;copy the left and right most columns out
sub r5, r1, r3 ;destptr1
add r6, r1, lr
sub r6, r6, r3, lsl #1 ;destptr2
sub r2, r6, #1 ;srcptr2
;Do four rows at one time
mov r12, r4, lsr #2
copy_left_right_y_b16
vld1.8 {d0[], d1[]}, [r1], lr
vld1.8 {d4[], d5[]}, [r2], lr
vld1.8 {d8[], d9[]}, [r1], lr
vld1.8 {d12[], d13[]}, [r2], lr
vld1.8 {d16[], d17[]}, [r1], lr
vld1.8 {d20[], d21[]}, [r2], lr
vld1.8 {d24[], d25[]}, [r1], lr
vld1.8 {d28[], d29[]}, [r2], lr
subs r12, r12, #1
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q4}, [r5], lr
vst1.8 {q6}, [r6], lr
vst1.8 {q8}, [r5], lr
vst1.8 {q10}, [r6], lr
vst1.8 {q12}, [r5], lr
vst1.8 {q14}, [r6], lr
bne copy_left_right_y_b16
;Now copy the top and bottom source lines into each line of the respective borders
ldr r7, [r0, #yv12_buffer_config_y_buffer] ;srcptr1
mul r8, r3, lr
mov r12, lr, lsr #7
sub r6, r1, r3 ;destptr2
sub r2, r6, lr ;srcptr2
sub r1, r7, r3 ;srcptr1
sub r5, r1, r8 ;destptr1
copy_top_bottom_y_b16
vld1.8 {q0, q1}, [r1]!
vld1.8 {q8, q9}, [r2]!
vld1.8 {q2, q3}, [r1]!
vld1.8 {q10, q11}, [r2]!
vld1.8 {q4, q5}, [r1]!
vld1.8 {q12, q13}, [r2]!
vld1.8 {q6, q7}, [r1]!
vld1.8 {q14, q15}, [r2]!
mov r7, r3
top_bottom_16_b16
subs r7, r7, #1
vst1.8 {q0, q1}, [r5]!
vst1.8 {q8, q9}, [r6]!
vst1.8 {q2, q3}, [r5]!
vst1.8 {q10, q11}, [r6]!
vst1.8 {q4, q5}, [r5]!
vst1.8 {q12, q13}, [r6]!
vst1.8 {q6, q7}, [r5]!
vst1.8 {q14, q15}, [r6]!
add r5, r5, lr
sub r5, r5, #128
add r6, r6, lr
sub r6, r6, #128
bne top_bottom_16_b16
sub r5, r1, r8
add r6, r2, lr
subs r12, r12, #1
bne copy_top_bottom_y_b16
mov r7, lr, lsr #4 ;check to see if extra copy is needed
ands r7, r7, #0x7
bne extra_top_bottom_y_b16
end_of_border_copy_y_b16
vpop {d8 - d15}
pop {r4 - r11, pc}
;=====================
;extra copy part for Y
extra_top_bottom_y_b16
vld1.8 {q0}, [r1]!
vld1.8 {q2}, [r2]!
mov r9, r3, lsr #3
extra_top_bottom_16_b16
subs r9, r9, #1
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
vst1.8 {q0}, [r5], lr
vst1.8 {q2}, [r6], lr
bne extra_top_bottom_16_b16
sub r5, r1, r8
add r6, r2, lr
subs r7, r7, #1
bne extra_top_bottom_y_b16
b end_of_border_copy_y_b16
;=============================
extra_cp_src_to_dst_width
add r2, r2, r11
add r3, r3, r11
add r0, r8, r6
add r11, r9, r7
mov lr, r4, lsr #1
extra_cp_src_to_dst_height_loop
mov r8, r2
mov r9, r3
add r0, r8, r6
add r11, r9, r7
mov r12, r10
extra_cp_src_to_dst_width_loop
vld1.8 {q0}, [r8]!
vld1.8 {q1}, [r0]!
subs r12, r12, #16
vst1.8 {q0}, [r9]!
vst1.8 {q1}, [r11]!
bne extra_cp_src_to_dst_width_loop
subs lr, lr, #1
add r2, r2, r6, lsl #1
add r3, r3, r7, lsl #1
bne extra_cp_src_to_dst_height_loop
b end_of_cp_src_to_dst
ENDP
;===========================================================
;In vp8cx_pick_filter_level(), call vp8_yv12_copy_frame_yonly
;without extend_frame_borders.
|vp8_yv12_copy_frame_yonly_no_extend_frame_borders_neon| PROC
push {r4 - r11, lr}
vpush {d8-d15}
ldr r4, [r0, #yv12_buffer_config_y_height]
ldr r5, [r0, #yv12_buffer_config_y_width]
ldr r6, [r0, #yv12_buffer_config_y_stride]
ldr r7, [r1, #yv12_buffer_config_y_stride]
ldr r2, [r0, #yv12_buffer_config_y_buffer] ;srcptr1
ldr r3, [r1, #yv12_buffer_config_y_buffer] ;dstptr1
; copy two rows at one time
mov lr, r4, lsr #1
cp_src_to_dst_height_loop1
mov r8, r2
mov r9, r3
add r10, r2, r6
add r11, r3, r7
mov r12, r5, lsr #7
cp_src_to_dst_width_loop1
vld1.8 {q0, q1}, [r8]!
vld1.8 {q8, q9}, [r10]!
vld1.8 {q2, q3}, [r8]!
vld1.8 {q10, q11}, [r10]!
vld1.8 {q4, q5}, [r8]!
vld1.8 {q12, q13}, [r10]!
vld1.8 {q6, q7}, [r8]!
vld1.8 {q14, q15}, [r10]!
subs r12, r12, #1
vst1.8 {q0, q1}, [r9]!
vst1.8 {q8, q9}, [r11]!
vst1.8 {q2, q3}, [r9]!
vst1.8 {q10, q11}, [r11]!
vst1.8 {q4, q5}, [r9]!
vst1.8 {q12, q13}, [r11]!
vst1.8 {q6, q7}, [r9]!
vst1.8 {q14, q15}, [r11]!
bne cp_src_to_dst_width_loop1
subs lr, lr, #1
add r2, r2, r6, lsl #1
add r3, r3, r7, lsl #1
bne cp_src_to_dst_height_loop1
ands r10, r5, #0x7f ;check to see if extra copy is needed
sub r11, r5, r10
ldr r2, [r0, #yv12_buffer_config_y_buffer] ;srcptr1
ldr r3, [r1, #yv12_buffer_config_y_buffer] ;dstptr1
bne extra_cp_src_to_dst_width1
end_of_cp_src_to_dst1
vpop {d8 - d15}
pop {r4-r11, pc}
;=============================
extra_cp_src_to_dst_width1
add r2, r2, r11
add r3, r3, r11
add r0, r8, r6
add r11, r9, r7
mov lr, r4, lsr #1
extra_cp_src_to_dst_height_loop1
mov r8, r2
mov r9, r3
add r0, r8, r6
add r11, r9, r7
mov r12, r10
extra_cp_src_to_dst_width_loop1
vld1.8 {q0}, [r8]!
vld1.8 {q1}, [r0]!
subs r12, r12, #16
vst1.8 {q0}, [r9]!
vst1.8 {q1}, [r11]!
bne extra_cp_src_to_dst_width_loop1
subs lr, lr, #1
add r2, r2, r6, lsl #1
add r3, r3, r7, lsl #1
bne extra_cp_src_to_dst_height_loop1
b end_of_cp_src_to_dst1
ENDP
END
|
/* GNU/Linux/AArch64 specific low level interface, for the remote server for
GDB.
Copyright (C) 2009-2020 Free Software Foundation, Inc.
Contributed by ARM Ltd.
This file is part of GDB.
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 <http://www.gnu.org/licenses/>. */
#include "server.h"
#include "linux-low.h"
#include "nat/aarch64-linux.h"
#include "nat/aarch64-linux-hw-point.h"
#include "arch/aarch64-insn.h"
#include "linux-aarch32-low.h"
#include "elf/common.h"
#include "ax.h"
#include "tracepoint.h"
#include "debug.h"
#include <signal.h>
#include <sys/user.h>
#include "nat/gdb_ptrace.h"
#include <asm/ptrace.h>
#include <inttypes.h>
#include <endian.h>
#include <sys/uio.h>
#include "gdb_proc_service.h"
#include "arch/aarch64.h"
#include "linux-aarch32-tdesc.h"
#include "linux-aarch64-tdesc.h"
#include "nat/aarch64-sve-linux-ptrace.h"
#include "tdesc.h"
#ifdef HAVE_SYS_REG_H
#include <sys/reg.h>
#endif
/* Linux target op definitions for the AArch64 architecture. */
class aarch64_target : public linux_process_target
{
public:
const regs_info *get_regs_info () override;
int breakpoint_kind_from_pc (CORE_ADDR *pcptr) override;
int breakpoint_kind_from_current_state (CORE_ADDR *pcptr) override;
const gdb_byte *sw_breakpoint_from_kind (int kind, int *size) override;
bool supports_z_point_type (char z_type) override;
bool supports_tracepoints () override;
bool supports_fast_tracepoints () override;
int install_fast_tracepoint_jump_pad
(CORE_ADDR tpoint, CORE_ADDR tpaddr, CORE_ADDR collector,
CORE_ADDR lockaddr, ULONGEST orig_size, CORE_ADDR *jump_entry,
CORE_ADDR *trampoline, ULONGEST *trampoline_size,
unsigned char *jjump_pad_insn, ULONGEST *jjump_pad_insn_size,
CORE_ADDR *adjusted_insn_addr, CORE_ADDR *adjusted_insn_addr_end,
char *err) override;
int get_min_fast_tracepoint_insn_len () override;
struct emit_ops *emit_ops () override;
protected:
void low_arch_setup () override;
bool low_cannot_fetch_register (int regno) override;
bool low_cannot_store_register (int regno) override;
bool low_supports_breakpoints () override;
CORE_ADDR low_get_pc (regcache *regcache) override;
void low_set_pc (regcache *regcache, CORE_ADDR newpc) override;
bool low_breakpoint_at (CORE_ADDR pc) override;
int low_insert_point (raw_bkpt_type type, CORE_ADDR addr,
int size, raw_breakpoint *bp) override;
int low_remove_point (raw_bkpt_type type, CORE_ADDR addr,
int size, raw_breakpoint *bp) override;
bool low_stopped_by_watchpoint () override;
CORE_ADDR low_stopped_data_address () override;
bool low_siginfo_fixup (siginfo_t *native, gdb_byte *inf,
int direction) override;
arch_process_info *low_new_process () override;
void low_delete_process (arch_process_info *info) override;
void low_new_thread (lwp_info *) override;
void low_delete_thread (arch_lwp_info *) override;
void low_new_fork (process_info *parent, process_info *child) override;
void low_prepare_to_resume (lwp_info *lwp) override;
int low_get_thread_area (int lwpid, CORE_ADDR *addrp) override;
bool low_supports_range_stepping () override;
bool low_supports_catch_syscall () override;
void low_get_syscall_trapinfo (regcache *regcache, int *sysno) override;
};
/* The singleton target ops object. */
static aarch64_target the_aarch64_target;
bool
aarch64_target::low_cannot_fetch_register (int regno)
{
gdb_assert_not_reached ("linux target op low_cannot_fetch_register "
"is not implemented by the target");
}
bool
aarch64_target::low_cannot_store_register (int regno)
{
gdb_assert_not_reached ("linux target op low_cannot_store_register "
"is not implemented by the target");
}
void
aarch64_target::low_prepare_to_resume (lwp_info *lwp)
{
aarch64_linux_prepare_to_resume (lwp);
}
/* Per-process arch-specific data we want to keep. */
struct arch_process_info
{
/* Hardware breakpoint/watchpoint data.
The reason for them to be per-process rather than per-thread is
due to the lack of information in the gdbserver environment;
gdbserver is not told that whether a requested hardware
breakpoint/watchpoint is thread specific or not, so it has to set
each hw bp/wp for every thread in the current process. The
higher level bp/wp management in gdb will resume a thread if a hw
bp/wp trap is not expected for it. Since the hw bp/wp setting is
same for each thread, it is reasonable for the data to live here.
*/
struct aarch64_debug_reg_state debug_reg_state;
};
/* Return true if the size of register 0 is 8 byte. */
static int
is_64bit_tdesc (void)
{
struct regcache *regcache = get_thread_regcache (current_thread, 0);
return register_size (regcache->tdesc, 0) == 8;
}
/* Return true if the regcache contains the number of SVE registers. */
static bool
is_sve_tdesc (void)
{
struct regcache *regcache = get_thread_regcache (current_thread, 0);
return tdesc_contains_feature (regcache->tdesc, "org.gnu.gdb.aarch64.sve");
}
static void
aarch64_fill_gregset (struct regcache *regcache, void *buf)
{
struct user_pt_regs *regset = (struct user_pt_regs *) buf;
int i;
for (i = 0; i < AARCH64_X_REGS_NUM; i++)
collect_register (regcache, AARCH64_X0_REGNUM + i, ®set->regs[i]);
collect_register (regcache, AARCH64_SP_REGNUM, ®set->sp);
collect_register (regcache, AARCH64_PC_REGNUM, ®set->pc);
collect_register (regcache, AARCH64_CPSR_REGNUM, ®set->pstate);
}
static void
aarch64_store_gregset (struct regcache *regcache, const void *buf)
{
const struct user_pt_regs *regset = (const struct user_pt_regs *) buf;
int i;
for (i = 0; i < AARCH64_X_REGS_NUM; i++)
supply_register (regcache, AARCH64_X0_REGNUM + i, ®set->regs[i]);
supply_register (regcache, AARCH64_SP_REGNUM, ®set->sp);
supply_register (regcache, AARCH64_PC_REGNUM, ®set->pc);
supply_register (regcache, AARCH64_CPSR_REGNUM, ®set->pstate);
}
static void
aarch64_fill_fpregset (struct regcache *regcache, void *buf)
{
struct user_fpsimd_state *regset = (struct user_fpsimd_state *) buf;
int i;
for (i = 0; i < AARCH64_V_REGS_NUM; i++)
collect_register (regcache, AARCH64_V0_REGNUM + i, ®set->vregs[i]);
collect_register (regcache, AARCH64_FPSR_REGNUM, ®set->fpsr);
collect_register (regcache, AARCH64_FPCR_REGNUM, ®set->fpcr);
}
static void
aarch64_store_fpregset (struct regcache *regcache, const void *buf)
{
const struct user_fpsimd_state *regset
= (const struct user_fpsimd_state *) buf;
int i;
for (i = 0; i < AARCH64_V_REGS_NUM; i++)
supply_register (regcache, AARCH64_V0_REGNUM + i, ®set->vregs[i]);
supply_register (regcache, AARCH64_FPSR_REGNUM, ®set->fpsr);
supply_register (regcache, AARCH64_FPCR_REGNUM, ®set->fpcr);
}
/* Store the pauth registers to regcache. */
static void
aarch64_store_pauthregset (struct regcache *regcache, const void *buf)
{
uint64_t *pauth_regset = (uint64_t *) buf;
int pauth_base = find_regno (regcache->tdesc, "pauth_dmask");
if (pauth_base == 0)
return;
supply_register (regcache, AARCH64_PAUTH_DMASK_REGNUM (pauth_base),
&pauth_regset[0]);
supply_register (regcache, AARCH64_PAUTH_CMASK_REGNUM (pauth_base),
&pauth_regset[1]);
}
bool
aarch64_target::low_supports_breakpoints ()
{
return true;
}
/* Implementation of linux target ops method "low_get_pc". */
CORE_ADDR
aarch64_target::low_get_pc (regcache *regcache)
{
if (register_size (regcache->tdesc, 0) == 8)
return linux_get_pc_64bit (regcache);
else
return linux_get_pc_32bit (regcache);
}
/* Implementation of linux target ops method "low_set_pc". */
void
aarch64_target::low_set_pc (regcache *regcache, CORE_ADDR pc)
{
if (register_size (regcache->tdesc, 0) == 8)
linux_set_pc_64bit (regcache, pc);
else
linux_set_pc_32bit (regcache, pc);
}
#define aarch64_breakpoint_len 4
/* AArch64 BRK software debug mode instruction.
This instruction needs to match gdb/aarch64-tdep.c
(aarch64_default_breakpoint). */
static const gdb_byte aarch64_breakpoint[] = {0x00, 0x00, 0x20, 0xd4};
/* Implementation of linux target ops method "low_breakpoint_at". */
bool
aarch64_target::low_breakpoint_at (CORE_ADDR where)
{
if (is_64bit_tdesc ())
{
gdb_byte insn[aarch64_breakpoint_len];
read_memory (where, (unsigned char *) &insn, aarch64_breakpoint_len);
if (memcmp (insn, aarch64_breakpoint, aarch64_breakpoint_len) == 0)
return true;
return false;
}
else
return arm_breakpoint_at (where);
}
static void
aarch64_init_debug_reg_state (struct aarch64_debug_reg_state *state)
{
int i;
for (i = 0; i < AARCH64_HBP_MAX_NUM; ++i)
{
state->dr_addr_bp[i] = 0;
state->dr_ctrl_bp[i] = 0;
state->dr_ref_count_bp[i] = 0;
}
for (i = 0; i < AARCH64_HWP_MAX_NUM; ++i)
{
state->dr_addr_wp[i] = 0;
state->dr_ctrl_wp[i] = 0;
state->dr_ref_count_wp[i] = 0;
}
}
/* Return the pointer to the debug register state structure in the
current process' arch-specific data area. */
struct aarch64_debug_reg_state *
aarch64_get_debug_reg_state (pid_t pid)
{
struct process_info *proc = find_process_pid (pid);
return &proc->priv->arch_private->debug_reg_state;
}
/* Implementation of target ops method "supports_z_point_type". */
bool
aarch64_target::supports_z_point_type (char z_type)
{
switch (z_type)
{
case Z_PACKET_SW_BP:
case Z_PACKET_HW_BP:
case Z_PACKET_WRITE_WP:
case Z_PACKET_READ_WP:
case Z_PACKET_ACCESS_WP:
return true;
default:
return false;
}
}
/* Implementation of linux target ops method "low_insert_point".
It actually only records the info of the to-be-inserted bp/wp;
the actual insertion will happen when threads are resumed. */
int
aarch64_target::low_insert_point (raw_bkpt_type type, CORE_ADDR addr,
int len, raw_breakpoint *bp)
{
int ret;
enum target_hw_bp_type targ_type;
struct aarch64_debug_reg_state *state
= aarch64_get_debug_reg_state (pid_of (current_thread));
if (show_debug_regs)
fprintf (stderr, "insert_point on entry (addr=0x%08lx, len=%d)\n",
(unsigned long) addr, len);
/* Determine the type from the raw breakpoint type. */
targ_type = raw_bkpt_type_to_target_hw_bp_type (type);
if (targ_type != hw_execute)
{
if (aarch64_linux_region_ok_for_watchpoint (addr, len))
ret = aarch64_handle_watchpoint (targ_type, addr, len,
1 /* is_insert */, state);
else
ret = -1;
}
else
{
if (len == 3)
{
/* LEN is 3 means the breakpoint is set on a 32-bit thumb
instruction. Set it to 2 to correctly encode length bit
mask in hardware/watchpoint control register. */
len = 2;
}
ret = aarch64_handle_breakpoint (targ_type, addr, len,
1 /* is_insert */, state);
}
if (show_debug_regs)
aarch64_show_debug_reg_state (state, "insert_point", addr, len,
targ_type);
return ret;
}
/* Implementation of linux target ops method "low_remove_point".
It actually only records the info of the to-be-removed bp/wp,
the actual removal will be done when threads are resumed. */
int
aarch64_target::low_remove_point (raw_bkpt_type type, CORE_ADDR addr,
int len, raw_breakpoint *bp)
{
int ret;
enum target_hw_bp_type targ_type;
struct aarch64_debug_reg_state *state
= aarch64_get_debug_reg_state (pid_of (current_thread));
if (show_debug_regs)
fprintf (stderr, "remove_point on entry (addr=0x%08lx, len=%d)\n",
(unsigned long) addr, len);
/* Determine the type from the raw breakpoint type. */
targ_type = raw_bkpt_type_to_target_hw_bp_type (type);
/* Set up state pointers. */
if (targ_type != hw_execute)
ret =
aarch64_handle_watchpoint (targ_type, addr, len, 0 /* is_insert */,
state);
else
{
if (len == 3)
{
/* LEN is 3 means the breakpoint is set on a 32-bit thumb
instruction. Set it to 2 to correctly encode length bit
mask in hardware/watchpoint control register. */
len = 2;
}
ret = aarch64_handle_breakpoint (targ_type, addr, len,
0 /* is_insert */, state);
}
if (show_debug_regs)
aarch64_show_debug_reg_state (state, "remove_point", addr, len,
targ_type);
return ret;
}
/* Implementation of linux target ops method "low_stopped_data_address". */
CORE_ADDR
aarch64_target::low_stopped_data_address ()
{
siginfo_t siginfo;
int pid, i;
struct aarch64_debug_reg_state *state;
pid = lwpid_of (current_thread);
/* Get the siginfo. */
if (ptrace (PTRACE_GETSIGINFO, pid, NULL, &siginfo) != 0)
return (CORE_ADDR) 0;
/* Need to be a hardware breakpoint/watchpoint trap. */
if (siginfo.si_signo != SIGTRAP
|| (siginfo.si_code & 0xffff) != 0x0004 /* TRAP_HWBKPT */)
return (CORE_ADDR) 0;
/* Check if the address matches any watched address. */
state = aarch64_get_debug_reg_state (pid_of (current_thread));
for (i = aarch64_num_wp_regs - 1; i >= 0; --i)
{
const unsigned int offset
= aarch64_watchpoint_offset (state->dr_ctrl_wp[i]);
const unsigned int len = aarch64_watchpoint_length (state->dr_ctrl_wp[i]);
const CORE_ADDR addr_trap = (CORE_ADDR) siginfo.si_addr;
const CORE_ADDR addr_watch = state->dr_addr_wp[i] + offset;
const CORE_ADDR addr_watch_aligned = align_down (state->dr_addr_wp[i], 8);
const CORE_ADDR addr_orig = state->dr_addr_orig_wp[i];
if (state->dr_ref_count_wp[i]
&& DR_CONTROL_ENABLED (state->dr_ctrl_wp[i])
&& addr_trap >= addr_watch_aligned
&& addr_trap < addr_watch + len)
{
/* ADDR_TRAP reports the first address of the memory range
accessed by the CPU, regardless of what was the memory
range watched. Thus, a large CPU access that straddles
the ADDR_WATCH..ADDR_WATCH+LEN range may result in an
ADDR_TRAP that is lower than the
ADDR_WATCH..ADDR_WATCH+LEN range. E.g.:
addr: | 4 | 5 | 6 | 7 | 8 |
|---- range watched ----|
|----------- range accessed ------------|
In this case, ADDR_TRAP will be 4.
To match a watchpoint known to GDB core, we must never
report *ADDR_P outside of any ADDR_WATCH..ADDR_WATCH+LEN
range. ADDR_WATCH <= ADDR_TRAP < ADDR_ORIG is a false
positive on kernels older than 4.10. See PR
external/20207. */
return addr_orig;
}
}
return (CORE_ADDR) 0;
}
/* Implementation of linux target ops method "low_stopped_by_watchpoint". */
bool
aarch64_target::low_stopped_by_watchpoint ()
{
return (low_stopped_data_address () != 0);
}
/* Fetch the thread-local storage pointer for libthread_db. */
ps_err_e
ps_get_thread_area (struct ps_prochandle *ph,
lwpid_t lwpid, int idx, void **base)
{
return aarch64_ps_get_thread_area (ph, lwpid, idx, base,
is_64bit_tdesc ());
}
/* Implementation of linux target ops method "low_siginfo_fixup". */
bool
aarch64_target::low_siginfo_fixup (siginfo_t *native, gdb_byte *inf,
int direction)
{
/* Is the inferior 32-bit? If so, then fixup the siginfo object. */
if (!is_64bit_tdesc ())
{
if (direction == 0)
aarch64_compat_siginfo_from_siginfo ((struct compat_siginfo *) inf,
native);
else
aarch64_siginfo_from_compat_siginfo (native,
(struct compat_siginfo *) inf);
return true;
}
return false;
}
/* Implementation of linux target ops method "low_new_process". */
arch_process_info *
aarch64_target::low_new_process ()
{
struct arch_process_info *info = XCNEW (struct arch_process_info);
aarch64_init_debug_reg_state (&info->debug_reg_state);
return info;
}
/* Implementation of linux target ops method "low_delete_process". */
void
aarch64_target::low_delete_process (arch_process_info *info)
{
xfree (info);
}
void
aarch64_target::low_new_thread (lwp_info *lwp)
{
aarch64_linux_new_thread (lwp);
}
void
aarch64_target::low_delete_thread (arch_lwp_info *arch_lwp)
{
aarch64_linux_delete_thread (arch_lwp);
}
/* Implementation of linux target ops method "low_new_fork". */
void
aarch64_target::low_new_fork (process_info *parent,
process_info *child)
{
/* These are allocated by linux_add_process. */
gdb_assert (parent->priv != NULL
&& parent->priv->arch_private != NULL);
gdb_assert (child->priv != NULL
&& child->priv->arch_private != NULL);
/* Linux kernel before 2.6.33 commit
72f674d203cd230426437cdcf7dd6f681dad8b0d
will inherit hardware debug registers from parent
on fork/vfork/clone. Newer Linux kernels create such tasks with
zeroed debug registers.
GDB core assumes the child inherits the watchpoints/hw
breakpoints of the parent, and will remove them all from the
forked off process. Copy the debug registers mirrors into the
new process so that all breakpoints and watchpoints can be
removed together. The debug registers mirror will become zeroed
in the end before detaching the forked off process, thus making
this compatible with older Linux kernels too. */
*child->priv->arch_private = *parent->priv->arch_private;
}
/* Matches HWCAP_PACA in kernel header arch/arm64/include/uapi/asm/hwcap.h. */
#define AARCH64_HWCAP_PACA (1 << 30)
/* Implementation of linux target ops method "low_arch_setup". */
void
aarch64_target::low_arch_setup ()
{
unsigned int machine;
int is_elf64;
int tid;
tid = lwpid_of (current_thread);
is_elf64 = linux_pid_exe_is_elf_64_file (tid, &machine);
if (is_elf64)
{
uint64_t vq = aarch64_sve_get_vq (tid);
unsigned long hwcap = linux_get_hwcap (8);
bool pauth_p = hwcap & AARCH64_HWCAP_PACA;
current_process ()->tdesc = aarch64_linux_read_description (vq, pauth_p);
}
else
current_process ()->tdesc = aarch32_linux_read_description ();
aarch64_linux_get_debug_reg_capacity (lwpid_of (current_thread));
}
/* Wrapper for aarch64_sve_regs_copy_to_reg_buf. */
static void
aarch64_sve_regs_copy_to_regcache (struct regcache *regcache, const void *buf)
{
return aarch64_sve_regs_copy_to_reg_buf (regcache, buf);
}
/* Wrapper for aarch64_sve_regs_copy_from_reg_buf. */
static void
aarch64_sve_regs_copy_from_regcache (struct regcache *regcache, void *buf)
{
return aarch64_sve_regs_copy_from_reg_buf (regcache, buf);
}
static struct regset_info aarch64_regsets[] =
{
{ PTRACE_GETREGSET, PTRACE_SETREGSET, NT_PRSTATUS,
sizeof (struct user_pt_regs), GENERAL_REGS,
aarch64_fill_gregset, aarch64_store_gregset },
{ PTRACE_GETREGSET, PTRACE_SETREGSET, NT_FPREGSET,
sizeof (struct user_fpsimd_state), FP_REGS,
aarch64_fill_fpregset, aarch64_store_fpregset
},
{ PTRACE_GETREGSET, PTRACE_SETREGSET, NT_ARM_PAC_MASK,
AARCH64_PAUTH_REGS_SIZE, OPTIONAL_REGS,
NULL, aarch64_store_pauthregset },
NULL_REGSET
};
static struct regsets_info aarch64_regsets_info =
{
aarch64_regsets, /* regsets */
0, /* num_regsets */
NULL, /* disabled_regsets */
};
static struct regs_info regs_info_aarch64 =
{
NULL, /* regset_bitmap */
NULL, /* usrregs */
&aarch64_regsets_info,
};
static struct regset_info aarch64_sve_regsets[] =
{
{ PTRACE_GETREGSET, PTRACE_SETREGSET, NT_PRSTATUS,
sizeof (struct user_pt_regs), GENERAL_REGS,
aarch64_fill_gregset, aarch64_store_gregset },
{ PTRACE_GETREGSET, PTRACE_SETREGSET, NT_ARM_SVE,
SVE_PT_SIZE (AARCH64_MAX_SVE_VQ, SVE_PT_REGS_SVE), EXTENDED_REGS,
aarch64_sve_regs_copy_from_regcache, aarch64_sve_regs_copy_to_regcache
},
{ PTRACE_GETREGSET, PTRACE_SETREGSET, NT_ARM_PAC_MASK,
AARCH64_PAUTH_REGS_SIZE, OPTIONAL_REGS,
NULL, aarch64_store_pauthregset },
NULL_REGSET
};
static struct regsets_info aarch64_sve_regsets_info =
{
aarch64_sve_regsets, /* regsets. */
0, /* num_regsets. */
NULL, /* disabled_regsets. */
};
static struct regs_info regs_info_aarch64_sve =
{
NULL, /* regset_bitmap. */
NULL, /* usrregs. */
&aarch64_sve_regsets_info,
};
/* Implementation of linux target ops method "get_regs_info". */
const regs_info *
aarch64_target::get_regs_info ()
{
if (!is_64bit_tdesc ())
return ®s_info_aarch32;
if (is_sve_tdesc ())
return ®s_info_aarch64_sve;
return ®s_info_aarch64;
}
/* Implementation of target ops method "supports_tracepoints". */
bool
aarch64_target::supports_tracepoints ()
{
if (current_thread == NULL)
return true;
else
{
/* We don't support tracepoints on aarch32 now. */
return is_64bit_tdesc ();
}
}
/* Implementation of linux target ops method "low_get_thread_area". */
int
aarch64_target::low_get_thread_area (int lwpid, CORE_ADDR *addrp)
{
struct iovec iovec;
uint64_t reg;
iovec.iov_base = ®
iovec.iov_len = sizeof (reg);
if (ptrace (PTRACE_GETREGSET, lwpid, NT_ARM_TLS, &iovec) != 0)
return -1;
*addrp = reg;
return 0;
}
bool
aarch64_target::low_supports_catch_syscall ()
{
return true;
}
/* Implementation of linux target ops method "low_get_syscall_trapinfo". */
void
aarch64_target::low_get_syscall_trapinfo (regcache *regcache, int *sysno)
{
int use_64bit = register_size (regcache->tdesc, 0) == 8;
if (use_64bit)
{
long l_sysno;
collect_register_by_name (regcache, "x8", &l_sysno);
*sysno = (int) l_sysno;
}
else
collect_register_by_name (regcache, "r7", sysno);
}
/* List of condition codes that we need. */
enum aarch64_condition_codes
{
EQ = 0x0,
NE = 0x1,
LO = 0x3,
GE = 0xa,
LT = 0xb,
GT = 0xc,
LE = 0xd,
};
enum aarch64_operand_type
{
OPERAND_IMMEDIATE,
OPERAND_REGISTER,
};
/* Representation of an operand. At this time, it only supports register
and immediate types. */
struct aarch64_operand
{
/* Type of the operand. */
enum aarch64_operand_type type;
/* Value of the operand according to the type. */
union
{
uint32_t imm;
struct aarch64_register reg;
};
};
/* List of registers that we are currently using, we can add more here as
we need to use them. */
/* General purpose scratch registers (64 bit). */
static const struct aarch64_register x0 = { 0, 1 };
static const struct aarch64_register x1 = { 1, 1 };
static const struct aarch64_register x2 = { 2, 1 };
static const struct aarch64_register x3 = { 3, 1 };
static const struct aarch64_register x4 = { 4, 1 };
/* General purpose scratch registers (32 bit). */
static const struct aarch64_register w0 = { 0, 0 };
static const struct aarch64_register w2 = { 2, 0 };
/* Intra-procedure scratch registers. */
static const struct aarch64_register ip0 = { 16, 1 };
/* Special purpose registers. */
static const struct aarch64_register fp = { 29, 1 };
static const struct aarch64_register lr = { 30, 1 };
static const struct aarch64_register sp = { 31, 1 };
static const struct aarch64_register xzr = { 31, 1 };
/* Dynamically allocate a new register. If we know the register
statically, we should make it a global as above instead of using this
helper function. */
static struct aarch64_register
aarch64_register (unsigned num, int is64)
{
return (struct aarch64_register) { num, is64 };
}
/* Helper function to create a register operand, for instructions with
different types of operands.
For example:
p += emit_mov (p, x0, register_operand (x1)); */
static struct aarch64_operand
register_operand (struct aarch64_register reg)
{
struct aarch64_operand operand;
operand.type = OPERAND_REGISTER;
operand.reg = reg;
return operand;
}
/* Helper function to create an immediate operand, for instructions with
different types of operands.
For example:
p += emit_mov (p, x0, immediate_operand (12)); */
static struct aarch64_operand
immediate_operand (uint32_t imm)
{
struct aarch64_operand operand;
operand.type = OPERAND_IMMEDIATE;
operand.imm = imm;
return operand;
}
/* Helper function to create an offset memory operand.
For example:
p += emit_ldr (p, x0, sp, offset_memory_operand (16)); */
static struct aarch64_memory_operand
offset_memory_operand (int32_t offset)
{
return (struct aarch64_memory_operand) { MEMORY_OPERAND_OFFSET, offset };
}
/* Helper function to create a pre-index memory operand.
For example:
p += emit_ldr (p, x0, sp, preindex_memory_operand (16)); */
static struct aarch64_memory_operand
preindex_memory_operand (int32_t index)
{
return (struct aarch64_memory_operand) { MEMORY_OPERAND_PREINDEX, index };
}
/* Helper function to create a post-index memory operand.
For example:
p += emit_ldr (p, x0, sp, postindex_memory_operand (16)); */
static struct aarch64_memory_operand
postindex_memory_operand (int32_t index)
{
return (struct aarch64_memory_operand) { MEMORY_OPERAND_POSTINDEX, index };
}
/* System control registers. These special registers can be written and
read with the MRS and MSR instructions.
- NZCV: Condition flags. GDB refers to this register under the CPSR
name.
- FPSR: Floating-point status register.
- FPCR: Floating-point control registers.
- TPIDR_EL0: Software thread ID register. */
enum aarch64_system_control_registers
{
/* op0 op1 crn crm op2 */
NZCV = (0x1 << 14) | (0x3 << 11) | (0x4 << 7) | (0x2 << 3) | 0x0,
FPSR = (0x1 << 14) | (0x3 << 11) | (0x4 << 7) | (0x4 << 3) | 0x1,
FPCR = (0x1 << 14) | (0x3 << 11) | (0x4 << 7) | (0x4 << 3) | 0x0,
TPIDR_EL0 = (0x1 << 14) | (0x3 << 11) | (0xd << 7) | (0x0 << 3) | 0x2
};
/* Write a BLR instruction into *BUF.
BLR rn
RN is the register to branch to. */
static int
emit_blr (uint32_t *buf, struct aarch64_register rn)
{
return aarch64_emit_insn (buf, BLR | ENCODE (rn.num, 5, 5));
}
/* Write a RET instruction into *BUF.
RET xn
RN is the register to branch to. */
static int
emit_ret (uint32_t *buf, struct aarch64_register rn)
{
return aarch64_emit_insn (buf, RET | ENCODE (rn.num, 5, 5));
}
static int
emit_load_store_pair (uint32_t *buf, enum aarch64_opcodes opcode,
struct aarch64_register rt,
struct aarch64_register rt2,
struct aarch64_register rn,
struct aarch64_memory_operand operand)
{
uint32_t opc;
uint32_t pre_index;
uint32_t write_back;
if (rt.is64)
opc = ENCODE (2, 2, 30);
else
opc = ENCODE (0, 2, 30);
switch (operand.type)
{
case MEMORY_OPERAND_OFFSET:
{
pre_index = ENCODE (1, 1, 24);
write_back = ENCODE (0, 1, 23);
break;
}
case MEMORY_OPERAND_POSTINDEX:
{
pre_index = ENCODE (0, 1, 24);
write_back = ENCODE (1, 1, 23);
break;
}
case MEMORY_OPERAND_PREINDEX:
{
pre_index = ENCODE (1, 1, 24);
write_back = ENCODE (1, 1, 23);
break;
}
default:
return 0;
}
return aarch64_emit_insn (buf, opcode | opc | pre_index | write_back
| ENCODE (operand.index >> 3, 7, 15)
| ENCODE (rt2.num, 5, 10)
| ENCODE (rn.num, 5, 5) | ENCODE (rt.num, 5, 0));
}
/* Write a STP instruction into *BUF.
STP rt, rt2, [rn, #offset]
STP rt, rt2, [rn, #index]!
STP rt, rt2, [rn], #index
RT and RT2 are the registers to store.
RN is the base address register.
OFFSET is the immediate to add to the base address. It is limited to a
-512 .. 504 range (7 bits << 3). */
static int
emit_stp (uint32_t *buf, struct aarch64_register rt,
struct aarch64_register rt2, struct aarch64_register rn,
struct aarch64_memory_operand operand)
{
return emit_load_store_pair (buf, STP, rt, rt2, rn, operand);
}
/* Write a LDP instruction into *BUF.
LDP rt, rt2, [rn, #offset]
LDP rt, rt2, [rn, #index]!
LDP rt, rt2, [rn], #index
RT and RT2 are the registers to store.
RN is the base address register.
OFFSET is the immediate to add to the base address. It is limited to a
-512 .. 504 range (7 bits << 3). */
static int
emit_ldp (uint32_t *buf, struct aarch64_register rt,
struct aarch64_register rt2, struct aarch64_register rn,
struct aarch64_memory_operand operand)
{
return emit_load_store_pair (buf, LDP, rt, rt2, rn, operand);
}
/* Write a LDP (SIMD&VFP) instruction using Q registers into *BUF.
LDP qt, qt2, [rn, #offset]
RT and RT2 are the Q registers to store.
RN is the base address register.
OFFSET is the immediate to add to the base address. It is limited to
-1024 .. 1008 range (7 bits << 4). */
static int
emit_ldp_q_offset (uint32_t *buf, unsigned rt, unsigned rt2,
struct aarch64_register rn, int32_t offset)
{
uint32_t opc = ENCODE (2, 2, 30);
uint32_t pre_index = ENCODE (1, 1, 24);
return aarch64_emit_insn (buf, LDP_SIMD_VFP | opc | pre_index
| ENCODE (offset >> 4, 7, 15)
| ENCODE (rt2, 5, 10)
| ENCODE (rn.num, 5, 5) | ENCODE (rt, 5, 0));
}
/* Write a STP (SIMD&VFP) instruction using Q registers into *BUF.
STP qt, qt2, [rn, #offset]
RT and RT2 are the Q registers to store.
RN is the base address register.
OFFSET is the immediate to add to the base address. It is limited to
-1024 .. 1008 range (7 bits << 4). */
static int
emit_stp_q_offset (uint32_t *buf, unsigned rt, unsigned rt2,
struct aarch64_register rn, int32_t offset)
{
uint32_t opc = ENCODE (2, 2, 30);
uint32_t pre_index = ENCODE (1, 1, 24);
return aarch64_emit_insn (buf, STP_SIMD_VFP | opc | pre_index
| ENCODE (offset >> 4, 7, 15)
| ENCODE (rt2, 5, 10)
| ENCODE (rn.num, 5, 5) | ENCODE (rt, 5, 0));
}
/* Write a LDRH instruction into *BUF.
LDRH wt, [xn, #offset]
LDRH wt, [xn, #index]!
LDRH wt, [xn], #index
RT is the register to store.
RN is the base address register.
OFFSET is the immediate to add to the base address. It is limited to
0 .. 32760 range (12 bits << 3). */
static int
emit_ldrh (uint32_t *buf, struct aarch64_register rt,
struct aarch64_register rn,
struct aarch64_memory_operand operand)
{
return aarch64_emit_load_store (buf, 1, LDR, rt, rn, operand);
}
/* Write a LDRB instruction into *BUF.
LDRB wt, [xn, #offset]
LDRB wt, [xn, #index]!
LDRB wt, [xn], #index
RT is the register to store.
RN is the base address register.
OFFSET is the immediate to add to the base address. It is limited to
0 .. 32760 range (12 bits << 3). */
static int
emit_ldrb (uint32_t *buf, struct aarch64_register rt,
struct aarch64_register rn,
struct aarch64_memory_operand operand)
{
return aarch64_emit_load_store (buf, 0, LDR, rt, rn, operand);
}
/* Write a STR instruction into *BUF.
STR rt, [rn, #offset]
STR rt, [rn, #index]!
STR rt, [rn], #index
RT is the register to store.
RN is the base address register.
OFFSET is the immediate to add to the base address. It is limited to
0 .. 32760 range (12 bits << 3). */
static int
emit_str (uint32_t *buf, struct aarch64_register rt,
struct aarch64_register rn,
struct aarch64_memory_operand operand)
{
return aarch64_emit_load_store (buf, rt.is64 ? 3 : 2, STR, rt, rn, operand);
}
/* Helper function emitting an exclusive load or store instruction. */
static int
emit_load_store_exclusive (uint32_t *buf, uint32_t size,
enum aarch64_opcodes opcode,
struct aarch64_register rs,
struct aarch64_register rt,
struct aarch64_register rt2,
struct aarch64_register rn)
{
return aarch64_emit_insn (buf, opcode | ENCODE (size, 2, 30)
| ENCODE (rs.num, 5, 16) | ENCODE (rt2.num, 5, 10)
| ENCODE (rn.num, 5, 5) | ENCODE (rt.num, 5, 0));
}
/* Write a LAXR instruction into *BUF.
LDAXR rt, [xn]
RT is the destination register.
RN is the base address register. */
static int
emit_ldaxr (uint32_t *buf, struct aarch64_register rt,
struct aarch64_register rn)
{
return emit_load_store_exclusive (buf, rt.is64 ? 3 : 2, LDAXR, xzr, rt,
xzr, rn);
}
/* Write a STXR instruction into *BUF.
STXR ws, rt, [xn]
RS is the result register, it indicates if the store succeeded or not.
RT is the destination register.
RN is the base address register. */
static int
emit_stxr (uint32_t *buf, struct aarch64_register rs,
struct aarch64_register rt, struct aarch64_register rn)
{
return emit_load_store_exclusive (buf, rt.is64 ? 3 : 2, STXR, rs, rt,
xzr, rn);
}
/* Write a STLR instruction into *BUF.
STLR rt, [xn]
RT is the register to store.
RN is the base address register. */
static int
emit_stlr (uint32_t *buf, struct aarch64_register rt,
struct aarch64_register rn)
{
return emit_load_store_exclusive (buf, rt.is64 ? 3 : 2, STLR, xzr, rt,
xzr, rn);
}
/* Helper function for data processing instructions with register sources. */
static int
emit_data_processing_reg (uint32_t *buf, uint32_t opcode,
struct aarch64_register rd,
struct aarch64_register rn,
struct aarch64_register rm)
{
uint32_t size = ENCODE (rd.is64, 1, 31);
return aarch64_emit_insn (buf, opcode | size | ENCODE (rm.num, 5, 16)
| ENCODE (rn.num, 5, 5) | ENCODE (rd.num, 5, 0));
}
/* Helper function for data processing instructions taking either a register
or an immediate. */
static int
emit_data_processing (uint32_t *buf, enum aarch64_opcodes opcode,
struct aarch64_register rd,
struct aarch64_register rn,
struct aarch64_operand operand)
{
uint32_t size = ENCODE (rd.is64, 1, 31);
/* The opcode is different for register and immediate source operands. */
uint32_t operand_opcode;
if (operand.type == OPERAND_IMMEDIATE)
{
/* xxx1 000x xxxx xxxx xxxx xxxx xxxx xxxx */
operand_opcode = ENCODE (8, 4, 25);
return aarch64_emit_insn (buf, opcode | operand_opcode | size
| ENCODE (operand.imm, 12, 10)
| ENCODE (rn.num, 5, 5)
| ENCODE (rd.num, 5, 0));
}
else
{
/* xxx0 101x xxxx xxxx xxxx xxxx xxxx xxxx */
operand_opcode = ENCODE (5, 4, 25);
return emit_data_processing_reg (buf, opcode | operand_opcode, rd,
rn, operand.reg);
}
}
/* Write an ADD instruction into *BUF.
ADD rd, rn, #imm
ADD rd, rn, rm
This function handles both an immediate and register add.
RD is the destination register.
RN is the input register.
OPERAND is the source operand, either of type OPERAND_IMMEDIATE or
OPERAND_REGISTER. */
static int
emit_add (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, struct aarch64_operand operand)
{
return emit_data_processing (buf, ADD, rd, rn, operand);
}
/* Write a SUB instruction into *BUF.
SUB rd, rn, #imm
SUB rd, rn, rm
This function handles both an immediate and register sub.
RD is the destination register.
RN is the input register.
IMM is the immediate to substract to RN. */
static int
emit_sub (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, struct aarch64_operand operand)
{
return emit_data_processing (buf, SUB, rd, rn, operand);
}
/* Write a MOV instruction into *BUF.
MOV rd, #imm
MOV rd, rm
This function handles both a wide immediate move and a register move,
with the condition that the source register is not xzr. xzr and the
stack pointer share the same encoding and this function only supports
the stack pointer.
RD is the destination register.
OPERAND is the source operand, either of type OPERAND_IMMEDIATE or
OPERAND_REGISTER. */
static int
emit_mov (uint32_t *buf, struct aarch64_register rd,
struct aarch64_operand operand)
{
if (operand.type == OPERAND_IMMEDIATE)
{
uint32_t size = ENCODE (rd.is64, 1, 31);
/* Do not shift the immediate. */
uint32_t shift = ENCODE (0, 2, 21);
return aarch64_emit_insn (buf, MOV | size | shift
| ENCODE (operand.imm, 16, 5)
| ENCODE (rd.num, 5, 0));
}
else
return emit_add (buf, rd, operand.reg, immediate_operand (0));
}
/* Write a MOVK instruction into *BUF.
MOVK rd, #imm, lsl #shift
RD is the destination register.
IMM is the immediate.
SHIFT is the logical shift left to apply to IMM. */
static int
emit_movk (uint32_t *buf, struct aarch64_register rd, uint32_t imm,
unsigned shift)
{
uint32_t size = ENCODE (rd.is64, 1, 31);
return aarch64_emit_insn (buf, MOVK | size | ENCODE (shift, 2, 21) |
ENCODE (imm, 16, 5) | ENCODE (rd.num, 5, 0));
}
/* Write instructions into *BUF in order to move ADDR into a register.
ADDR can be a 64-bit value.
This function will emit a series of MOV and MOVK instructions, such as:
MOV xd, #(addr)
MOVK xd, #(addr >> 16), lsl #16
MOVK xd, #(addr >> 32), lsl #32
MOVK xd, #(addr >> 48), lsl #48 */
static int
emit_mov_addr (uint32_t *buf, struct aarch64_register rd, CORE_ADDR addr)
{
uint32_t *p = buf;
/* The MOV (wide immediate) instruction clears to top bits of the
register. */
p += emit_mov (p, rd, immediate_operand (addr & 0xffff));
if ((addr >> 16) != 0)
p += emit_movk (p, rd, (addr >> 16) & 0xffff, 1);
else
return p - buf;
if ((addr >> 32) != 0)
p += emit_movk (p, rd, (addr >> 32) & 0xffff, 2);
else
return p - buf;
if ((addr >> 48) != 0)
p += emit_movk (p, rd, (addr >> 48) & 0xffff, 3);
return p - buf;
}
/* Write a SUBS instruction into *BUF.
SUBS rd, rn, rm
This instruction update the condition flags.
RD is the destination register.
RN and RM are the source registers. */
static int
emit_subs (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, struct aarch64_operand operand)
{
return emit_data_processing (buf, SUBS, rd, rn, operand);
}
/* Write a CMP instruction into *BUF.
CMP rn, rm
This instruction is an alias of SUBS xzr, rn, rm.
RN and RM are the registers to compare. */
static int
emit_cmp (uint32_t *buf, struct aarch64_register rn,
struct aarch64_operand operand)
{
return emit_subs (buf, xzr, rn, operand);
}
/* Write a AND instruction into *BUF.
AND rd, rn, rm
RD is the destination register.
RN and RM are the source registers. */
static int
emit_and (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, struct aarch64_register rm)
{
return emit_data_processing_reg (buf, AND, rd, rn, rm);
}
/* Write a ORR instruction into *BUF.
ORR rd, rn, rm
RD is the destination register.
RN and RM are the source registers. */
static int
emit_orr (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, struct aarch64_register rm)
{
return emit_data_processing_reg (buf, ORR, rd, rn, rm);
}
/* Write a ORN instruction into *BUF.
ORN rd, rn, rm
RD is the destination register.
RN and RM are the source registers. */
static int
emit_orn (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, struct aarch64_register rm)
{
return emit_data_processing_reg (buf, ORN, rd, rn, rm);
}
/* Write a EOR instruction into *BUF.
EOR rd, rn, rm
RD is the destination register.
RN and RM are the source registers. */
static int
emit_eor (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, struct aarch64_register rm)
{
return emit_data_processing_reg (buf, EOR, rd, rn, rm);
}
/* Write a MVN instruction into *BUF.
MVN rd, rm
This is an alias for ORN rd, xzr, rm.
RD is the destination register.
RM is the source register. */
static int
emit_mvn (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rm)
{
return emit_orn (buf, rd, xzr, rm);
}
/* Write a LSLV instruction into *BUF.
LSLV rd, rn, rm
RD is the destination register.
RN and RM are the source registers. */
static int
emit_lslv (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, struct aarch64_register rm)
{
return emit_data_processing_reg (buf, LSLV, rd, rn, rm);
}
/* Write a LSRV instruction into *BUF.
LSRV rd, rn, rm
RD is the destination register.
RN and RM are the source registers. */
static int
emit_lsrv (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, struct aarch64_register rm)
{
return emit_data_processing_reg (buf, LSRV, rd, rn, rm);
}
/* Write a ASRV instruction into *BUF.
ASRV rd, rn, rm
RD is the destination register.
RN and RM are the source registers. */
static int
emit_asrv (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, struct aarch64_register rm)
{
return emit_data_processing_reg (buf, ASRV, rd, rn, rm);
}
/* Write a MUL instruction into *BUF.
MUL rd, rn, rm
RD is the destination register.
RN and RM are the source registers. */
static int
emit_mul (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, struct aarch64_register rm)
{
return emit_data_processing_reg (buf, MUL, rd, rn, rm);
}
/* Write a MRS instruction into *BUF. The register size is 64-bit.
MRS xt, system_reg
RT is the destination register.
SYSTEM_REG is special purpose register to read. */
static int
emit_mrs (uint32_t *buf, struct aarch64_register rt,
enum aarch64_system_control_registers system_reg)
{
return aarch64_emit_insn (buf, MRS | ENCODE (system_reg, 15, 5)
| ENCODE (rt.num, 5, 0));
}
/* Write a MSR instruction into *BUF. The register size is 64-bit.
MSR system_reg, xt
SYSTEM_REG is special purpose register to write.
RT is the input register. */
static int
emit_msr (uint32_t *buf, enum aarch64_system_control_registers system_reg,
struct aarch64_register rt)
{
return aarch64_emit_insn (buf, MSR | ENCODE (system_reg, 15, 5)
| ENCODE (rt.num, 5, 0));
}
/* Write a SEVL instruction into *BUF.
This is a hint instruction telling the hardware to trigger an event. */
static int
emit_sevl (uint32_t *buf)
{
return aarch64_emit_insn (buf, SEVL);
}
/* Write a WFE instruction into *BUF.
This is a hint instruction telling the hardware to wait for an event. */
static int
emit_wfe (uint32_t *buf)
{
return aarch64_emit_insn (buf, WFE);
}
/* Write a SBFM instruction into *BUF.
SBFM rd, rn, #immr, #imms
This instruction moves the bits from #immr to #imms into the
destination, sign extending the result.
RD is the destination register.
RN is the source register.
IMMR is the bit number to start at (least significant bit).
IMMS is the bit number to stop at (most significant bit). */
static int
emit_sbfm (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, uint32_t immr, uint32_t imms)
{
uint32_t size = ENCODE (rd.is64, 1, 31);
uint32_t n = ENCODE (rd.is64, 1, 22);
return aarch64_emit_insn (buf, SBFM | size | n | ENCODE (immr, 6, 16)
| ENCODE (imms, 6, 10) | ENCODE (rn.num, 5, 5)
| ENCODE (rd.num, 5, 0));
}
/* Write a SBFX instruction into *BUF.
SBFX rd, rn, #lsb, #width
This instruction moves #width bits from #lsb into the destination, sign
extending the result. This is an alias for:
SBFM rd, rn, #lsb, #(lsb + width - 1)
RD is the destination register.
RN is the source register.
LSB is the bit number to start at (least significant bit).
WIDTH is the number of bits to move. */
static int
emit_sbfx (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, uint32_t lsb, uint32_t width)
{
return emit_sbfm (buf, rd, rn, lsb, lsb + width - 1);
}
/* Write a UBFM instruction into *BUF.
UBFM rd, rn, #immr, #imms
This instruction moves the bits from #immr to #imms into the
destination, extending the result with zeros.
RD is the destination register.
RN is the source register.
IMMR is the bit number to start at (least significant bit).
IMMS is the bit number to stop at (most significant bit). */
static int
emit_ubfm (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, uint32_t immr, uint32_t imms)
{
uint32_t size = ENCODE (rd.is64, 1, 31);
uint32_t n = ENCODE (rd.is64, 1, 22);
return aarch64_emit_insn (buf, UBFM | size | n | ENCODE (immr, 6, 16)
| ENCODE (imms, 6, 10) | ENCODE (rn.num, 5, 5)
| ENCODE (rd.num, 5, 0));
}
/* Write a UBFX instruction into *BUF.
UBFX rd, rn, #lsb, #width
This instruction moves #width bits from #lsb into the destination,
extending the result with zeros. This is an alias for:
UBFM rd, rn, #lsb, #(lsb + width - 1)
RD is the destination register.
RN is the source register.
LSB is the bit number to start at (least significant bit).
WIDTH is the number of bits to move. */
static int
emit_ubfx (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, uint32_t lsb, uint32_t width)
{
return emit_ubfm (buf, rd, rn, lsb, lsb + width - 1);
}
/* Write a CSINC instruction into *BUF.
CSINC rd, rn, rm, cond
This instruction conditionally increments rn or rm and places the result
in rd. rn is chosen is the condition is true.
RD is the destination register.
RN and RM are the source registers.
COND is the encoded condition. */
static int
emit_csinc (uint32_t *buf, struct aarch64_register rd,
struct aarch64_register rn, struct aarch64_register rm,
unsigned cond)
{
uint32_t size = ENCODE (rd.is64, 1, 31);
return aarch64_emit_insn (buf, CSINC | size | ENCODE (rm.num, 5, 16)
| ENCODE (cond, 4, 12) | ENCODE (rn.num, 5, 5)
| ENCODE (rd.num, 5, 0));
}
/* Write a CSET instruction into *BUF.
CSET rd, cond
This instruction conditionally write 1 or 0 in the destination register.
1 is written if the condition is true. This is an alias for:
CSINC rd, xzr, xzr, !cond
Note that the condition needs to be inverted.
RD is the destination register.
RN and RM are the source registers.
COND is the encoded condition. */
static int
emit_cset (uint32_t *buf, struct aarch64_register rd, unsigned cond)
{
/* The least significant bit of the condition needs toggling in order to
invert it. */
return emit_csinc (buf, rd, xzr, xzr, cond ^ 0x1);
}
/* Write LEN instructions from BUF into the inferior memory at *TO.
Note instructions are always little endian on AArch64, unlike data. */
static void
append_insns (CORE_ADDR *to, size_t len, const uint32_t *buf)
{
size_t byte_len = len * sizeof (uint32_t);
#if (__BYTE_ORDER == __BIG_ENDIAN)
uint32_t *le_buf = (uint32_t *) xmalloc (byte_len);
size_t i;
for (i = 0; i < len; i++)
le_buf[i] = htole32 (buf[i]);
target_write_memory (*to, (const unsigned char *) le_buf, byte_len);
xfree (le_buf);
#else
target_write_memory (*to, (const unsigned char *) buf, byte_len);
#endif
*to += byte_len;
}
/* Sub-class of struct aarch64_insn_data, store information of
instruction relocation for fast tracepoint. Visitor can
relocate an instruction from BASE.INSN_ADDR to NEW_ADDR and save
the relocated instructions in buffer pointed by INSN_PTR. */
struct aarch64_insn_relocation_data
{
struct aarch64_insn_data base;
/* The new address the instruction is relocated to. */
CORE_ADDR new_addr;
/* Pointer to the buffer of relocated instruction(s). */
uint32_t *insn_ptr;
};
/* Implementation of aarch64_insn_visitor method "b". */
static void
aarch64_ftrace_insn_reloc_b (const int is_bl, const int32_t offset,
struct aarch64_insn_data *data)
{
struct aarch64_insn_relocation_data *insn_reloc
= (struct aarch64_insn_relocation_data *) data;
int64_t new_offset
= insn_reloc->base.insn_addr - insn_reloc->new_addr + offset;
if (can_encode_int32 (new_offset, 28))
insn_reloc->insn_ptr += emit_b (insn_reloc->insn_ptr, is_bl, new_offset);
}
/* Implementation of aarch64_insn_visitor method "b_cond". */
static void
aarch64_ftrace_insn_reloc_b_cond (const unsigned cond, const int32_t offset,
struct aarch64_insn_data *data)
{
struct aarch64_insn_relocation_data *insn_reloc
= (struct aarch64_insn_relocation_data *) data;
int64_t new_offset
= insn_reloc->base.insn_addr - insn_reloc->new_addr + offset;
if (can_encode_int32 (new_offset, 21))
{
insn_reloc->insn_ptr += emit_bcond (insn_reloc->insn_ptr, cond,
new_offset);
}
else if (can_encode_int32 (new_offset, 28))
{
/* The offset is out of range for a conditional branch
instruction but not for a unconditional branch. We can use
the following instructions instead:
B.COND TAKEN ; If cond is true, then jump to TAKEN.
B NOT_TAKEN ; Else jump over TAKEN and continue.
TAKEN:
B #(offset - 8)
NOT_TAKEN:
*/
insn_reloc->insn_ptr += emit_bcond (insn_reloc->insn_ptr, cond, 8);
insn_reloc->insn_ptr += emit_b (insn_reloc->insn_ptr, 0, 8);
insn_reloc->insn_ptr += emit_b (insn_reloc->insn_ptr, 0, new_offset - 8);
}
}
/* Implementation of aarch64_insn_visitor method "cb". */
static void
aarch64_ftrace_insn_reloc_cb (const int32_t offset, const int is_cbnz,
const unsigned rn, int is64,
struct aarch64_insn_data *data)
{
struct aarch64_insn_relocation_data *insn_reloc
= (struct aarch64_insn_relocation_data *) data;
int64_t new_offset
= insn_reloc->base.insn_addr - insn_reloc->new_addr + offset;
if (can_encode_int32 (new_offset, 21))
{
insn_reloc->insn_ptr += emit_cb (insn_reloc->insn_ptr, is_cbnz,
aarch64_register (rn, is64), new_offset);
}
else if (can_encode_int32 (new_offset, 28))
{
/* The offset is out of range for a compare and branch
instruction but not for a unconditional branch. We can use
the following instructions instead:
CBZ xn, TAKEN ; xn == 0, then jump to TAKEN.
B NOT_TAKEN ; Else jump over TAKEN and continue.
TAKEN:
B #(offset - 8)
NOT_TAKEN:
*/
insn_reloc->insn_ptr += emit_cb (insn_reloc->insn_ptr, is_cbnz,
aarch64_register (rn, is64), 8);
insn_reloc->insn_ptr += emit_b (insn_reloc->insn_ptr, 0, 8);
insn_reloc->insn_ptr += emit_b (insn_reloc->insn_ptr, 0, new_offset - 8);
}
}
/* Implementation of aarch64_insn_visitor method "tb". */
static void
aarch64_ftrace_insn_reloc_tb (const int32_t offset, int is_tbnz,
const unsigned rt, unsigned bit,
struct aarch64_insn_data *data)
{
struct aarch64_insn_relocation_data *insn_reloc
= (struct aarch64_insn_relocation_data *) data;
int64_t new_offset
= insn_reloc->base.insn_addr - insn_reloc->new_addr + offset;
if (can_encode_int32 (new_offset, 16))
{
insn_reloc->insn_ptr += emit_tb (insn_reloc->insn_ptr, is_tbnz, bit,
aarch64_register (rt, 1), new_offset);
}
else if (can_encode_int32 (new_offset, 28))
{
/* The offset is out of range for a test bit and branch
instruction but not for a unconditional branch. We can use
the following instructions instead:
TBZ xn, #bit, TAKEN ; xn[bit] == 0, then jump to TAKEN.
B NOT_TAKEN ; Else jump over TAKEN and continue.
TAKEN:
B #(offset - 8)
NOT_TAKEN:
*/
insn_reloc->insn_ptr += emit_tb (insn_reloc->insn_ptr, is_tbnz, bit,
aarch64_register (rt, 1), 8);
insn_reloc->insn_ptr += emit_b (insn_reloc->insn_ptr, 0, 8);
insn_reloc->insn_ptr += emit_b (insn_reloc->insn_ptr, 0,
new_offset - 8);
}
}
/* Implementation of aarch64_insn_visitor method "adr". */
static void
aarch64_ftrace_insn_reloc_adr (const int32_t offset, const unsigned rd,
const int is_adrp,
struct aarch64_insn_data *data)
{
struct aarch64_insn_relocation_data *insn_reloc
= (struct aarch64_insn_relocation_data *) data;
/* We know exactly the address the ADR{P,} instruction will compute.
We can just write it to the destination register. */
CORE_ADDR address = data->insn_addr + offset;
if (is_adrp)
{
/* Clear the lower 12 bits of the offset to get the 4K page. */
insn_reloc->insn_ptr += emit_mov_addr (insn_reloc->insn_ptr,
aarch64_register (rd, 1),
address & ~0xfff);
}
else
insn_reloc->insn_ptr += emit_mov_addr (insn_reloc->insn_ptr,
aarch64_register (rd, 1), address);
}
/* Implementation of aarch64_insn_visitor method "ldr_literal". */
static void
aarch64_ftrace_insn_reloc_ldr_literal (const int32_t offset, const int is_sw,
const unsigned rt, const int is64,
struct aarch64_insn_data *data)
{
struct aarch64_insn_relocation_data *insn_reloc
= (struct aarch64_insn_relocation_data *) data;
CORE_ADDR address = data->insn_addr + offset;
insn_reloc->insn_ptr += emit_mov_addr (insn_reloc->insn_ptr,
aarch64_register (rt, 1), address);
/* We know exactly what address to load from, and what register we
can use:
MOV xd, #(oldloc + offset)
MOVK xd, #((oldloc + offset) >> 16), lsl #16
...
LDR xd, [xd] ; or LDRSW xd, [xd]
*/
if (is_sw)
insn_reloc->insn_ptr += emit_ldrsw (insn_reloc->insn_ptr,
aarch64_register (rt, 1),
aarch64_register (rt, 1),
offset_memory_operand (0));
else
insn_reloc->insn_ptr += emit_ldr (insn_reloc->insn_ptr,
aarch64_register (rt, is64),
aarch64_register (rt, 1),
offset_memory_operand (0));
}
/* Implementation of aarch64_insn_visitor method "others". */
static void
aarch64_ftrace_insn_reloc_others (const uint32_t insn,
struct aarch64_insn_data *data)
{
struct aarch64_insn_relocation_data *insn_reloc
= (struct aarch64_insn_relocation_data *) data;
/* The instruction is not PC relative. Just re-emit it at the new
location. */
insn_reloc->insn_ptr += aarch64_emit_insn (insn_reloc->insn_ptr, insn);
}
static const struct aarch64_insn_visitor visitor =
{
aarch64_ftrace_insn_reloc_b,
aarch64_ftrace_insn_reloc_b_cond,
aarch64_ftrace_insn_reloc_cb,
aarch64_ftrace_insn_reloc_tb,
aarch64_ftrace_insn_reloc_adr,
aarch64_ftrace_insn_reloc_ldr_literal,
aarch64_ftrace_insn_reloc_others,
};
bool
aarch64_target::supports_fast_tracepoints ()
{
return true;
}
/* Implementation of target ops method
"install_fast_tracepoint_jump_pad". */
int
aarch64_target::install_fast_tracepoint_jump_pad
(CORE_ADDR tpoint, CORE_ADDR tpaddr, CORE_ADDR collector,
CORE_ADDR lockaddr, ULONGEST orig_size, CORE_ADDR *jump_entry,
CORE_ADDR *trampoline, ULONGEST *trampoline_size,
unsigned char *jjump_pad_insn, ULONGEST *jjump_pad_insn_size,
CORE_ADDR *adjusted_insn_addr, CORE_ADDR *adjusted_insn_addr_end,
char *err)
{
uint32_t buf[256];
uint32_t *p = buf;
int64_t offset;
int i;
uint32_t insn;
CORE_ADDR buildaddr = *jump_entry;
struct aarch64_insn_relocation_data insn_data;
/* We need to save the current state on the stack both to restore it
later and to collect register values when the tracepoint is hit.
The saved registers are pushed in a layout that needs to be in sync
with aarch64_ft_collect_regmap (see linux-aarch64-ipa.c). Later on
the supply_fast_tracepoint_registers function will fill in the
register cache from a pointer to saved registers on the stack we build
here.
For simplicity, we set the size of each cell on the stack to 16 bytes.
This way one cell can hold any register type, from system registers
to the 128 bit SIMD&FP registers. Furthermore, the stack pointer
has to be 16 bytes aligned anyway.
Note that the CPSR register does not exist on AArch64. Instead we
can access system bits describing the process state with the
MRS/MSR instructions, namely the condition flags. We save them as
if they are part of a CPSR register because that's how GDB
interprets these system bits. At the moment, only the condition
flags are saved in CPSR (NZCV).
Stack layout, each cell is 16 bytes (descending):
High *-------- SIMD&FP registers from 31 down to 0. --------*
| q31 |
. .
. . 32 cells
. .
| q0 |
*---- General purpose registers from 30 down to 0. ----*
| x30 |
. .
. . 31 cells
. .
| x0 |
*------------- Special purpose registers. -------------*
| SP |
| PC |
| CPSR (NZCV) | 5 cells
| FPSR |
| FPCR | <- SP + 16
*------------- collecting_t object --------------------*
| TPIDR_EL0 | struct tracepoint * |
Low *------------------------------------------------------*
After this stack is set up, we issue a call to the collector, passing
it the saved registers at (SP + 16). */
/* Push SIMD&FP registers on the stack:
SUB sp, sp, #(32 * 16)
STP q30, q31, [sp, #(30 * 16)]
...
STP q0, q1, [sp]
*/
p += emit_sub (p, sp, sp, immediate_operand (32 * 16));
for (i = 30; i >= 0; i -= 2)
p += emit_stp_q_offset (p, i, i + 1, sp, i * 16);
/* Push general purpose registers on the stack. Note that we do not need
to push x31 as it represents the xzr register and not the stack
pointer in a STR instruction.
SUB sp, sp, #(31 * 16)
STR x30, [sp, #(30 * 16)]
...
STR x0, [sp]
*/
p += emit_sub (p, sp, sp, immediate_operand (31 * 16));
for (i = 30; i >= 0; i -= 1)
p += emit_str (p, aarch64_register (i, 1), sp,
offset_memory_operand (i * 16));
/* Make space for 5 more cells.
SUB sp, sp, #(5 * 16)
*/
p += emit_sub (p, sp, sp, immediate_operand (5 * 16));
/* Save SP:
ADD x4, sp, #((32 + 31 + 5) * 16)
STR x4, [sp, #(4 * 16)]
*/
p += emit_add (p, x4, sp, immediate_operand ((32 + 31 + 5) * 16));
p += emit_str (p, x4, sp, offset_memory_operand (4 * 16));
/* Save PC (tracepoint address):
MOV x3, #(tpaddr)
...
STR x3, [sp, #(3 * 16)]
*/
p += emit_mov_addr (p, x3, tpaddr);
p += emit_str (p, x3, sp, offset_memory_operand (3 * 16));
/* Save CPSR (NZCV), FPSR and FPCR:
MRS x2, nzcv
MRS x1, fpsr
MRS x0, fpcr
STR x2, [sp, #(2 * 16)]
STR x1, [sp, #(1 * 16)]
STR x0, [sp, #(0 * 16)]
*/
p += emit_mrs (p, x2, NZCV);
p += emit_mrs (p, x1, FPSR);
p += emit_mrs (p, x0, FPCR);
p += emit_str (p, x2, sp, offset_memory_operand (2 * 16));
p += emit_str (p, x1, sp, offset_memory_operand (1 * 16));
p += emit_str (p, x0, sp, offset_memory_operand (0 * 16));
/* Push the collecting_t object. It consist of the address of the
tracepoint and an ID for the current thread. We get the latter by
reading the tpidr_el0 system register. It corresponds to the
NT_ARM_TLS register accessible with ptrace.
MOV x0, #(tpoint)
...
MRS x1, tpidr_el0
STP x0, x1, [sp, #-16]!
*/
p += emit_mov_addr (p, x0, tpoint);
p += emit_mrs (p, x1, TPIDR_EL0);
p += emit_stp (p, x0, x1, sp, preindex_memory_operand (-16));
/* Spin-lock:
The shared memory for the lock is at lockaddr. It will hold zero
if no-one is holding the lock, otherwise it contains the address of
the collecting_t object on the stack of the thread which acquired it.
At this stage, the stack pointer points to this thread's collecting_t
object.
We use the following registers:
- x0: Address of the lock.
- x1: Pointer to collecting_t object.
- x2: Scratch register.
MOV x0, #(lockaddr)
...
MOV x1, sp
; Trigger an event local to this core. So the following WFE
; instruction is ignored.
SEVL
again:
; Wait for an event. The event is triggered by either the SEVL
; or STLR instructions (store release).
WFE
; Atomically read at lockaddr. This marks the memory location as
; exclusive. This instruction also has memory constraints which
; make sure all previous data reads and writes are done before
; executing it.
LDAXR x2, [x0]
; Try again if another thread holds the lock.
CBNZ x2, again
; We can lock it! Write the address of the collecting_t object.
; This instruction will fail if the memory location is not marked
; as exclusive anymore. If it succeeds, it will remove the
; exclusive mark on the memory location. This way, if another
; thread executes this instruction before us, we will fail and try
; all over again.
STXR w2, x1, [x0]
CBNZ w2, again
*/
p += emit_mov_addr (p, x0, lockaddr);
p += emit_mov (p, x1, register_operand (sp));
p += emit_sevl (p);
p += emit_wfe (p);
p += emit_ldaxr (p, x2, x0);
p += emit_cb (p, 1, w2, -2 * 4);
p += emit_stxr (p, w2, x1, x0);
p += emit_cb (p, 1, x2, -4 * 4);
/* Call collector (struct tracepoint *, unsigned char *):
MOV x0, #(tpoint)
...
; Saved registers start after the collecting_t object.
ADD x1, sp, #16
; We use an intra-procedure-call scratch register.
MOV ip0, #(collector)
...
; And call back to C!
BLR ip0
*/
p += emit_mov_addr (p, x0, tpoint);
p += emit_add (p, x1, sp, immediate_operand (16));
p += emit_mov_addr (p, ip0, collector);
p += emit_blr (p, ip0);
/* Release the lock.
MOV x0, #(lockaddr)
...
; This instruction is a normal store with memory ordering
; constraints. Thanks to this we do not have to put a data
; barrier instruction to make sure all data read and writes are done
; before this instruction is executed. Furthermore, this instruction
; will trigger an event, letting other threads know they can grab
; the lock.
STLR xzr, [x0]
*/
p += emit_mov_addr (p, x0, lockaddr);
p += emit_stlr (p, xzr, x0);
/* Free collecting_t object:
ADD sp, sp, #16
*/
p += emit_add (p, sp, sp, immediate_operand (16));
/* Restore CPSR (NZCV), FPSR and FPCR. And free all special purpose
registers from the stack.
LDR x2, [sp, #(2 * 16)]
LDR x1, [sp, #(1 * 16)]
LDR x0, [sp, #(0 * 16)]
MSR NZCV, x2
MSR FPSR, x1
MSR FPCR, x0
ADD sp, sp #(5 * 16)
*/
p += emit_ldr (p, x2, sp, offset_memory_operand (2 * 16));
p += emit_ldr (p, x1, sp, offset_memory_operand (1 * 16));
p += emit_ldr (p, x0, sp, offset_memory_operand (0 * 16));
p += emit_msr (p, NZCV, x2);
p += emit_msr (p, FPSR, x1);
p += emit_msr (p, FPCR, x0);
p += emit_add (p, sp, sp, immediate_operand (5 * 16));
/* Pop general purpose registers:
LDR x0, [sp]
...
LDR x30, [sp, #(30 * 16)]
ADD sp, sp, #(31 * 16)
*/
for (i = 0; i <= 30; i += 1)
p += emit_ldr (p, aarch64_register (i, 1), sp,
offset_memory_operand (i * 16));
p += emit_add (p, sp, sp, immediate_operand (31 * 16));
/* Pop SIMD&FP registers:
LDP q0, q1, [sp]
...
LDP q30, q31, [sp, #(30 * 16)]
ADD sp, sp, #(32 * 16)
*/
for (i = 0; i <= 30; i += 2)
p += emit_ldp_q_offset (p, i, i + 1, sp, i * 16);
p += emit_add (p, sp, sp, immediate_operand (32 * 16));
/* Write the code into the inferior memory. */
append_insns (&buildaddr, p - buf, buf);
/* Now emit the relocated instruction. */
*adjusted_insn_addr = buildaddr;
target_read_uint32 (tpaddr, &insn);
insn_data.base.insn_addr = tpaddr;
insn_data.new_addr = buildaddr;
insn_data.insn_ptr = buf;
aarch64_relocate_instruction (insn, &visitor,
(struct aarch64_insn_data *) &insn_data);
/* We may not have been able to relocate the instruction. */
if (insn_data.insn_ptr == buf)
{
sprintf (err,
"E.Could not relocate instruction from %s to %s.",
core_addr_to_string_nz (tpaddr),
core_addr_to_string_nz (buildaddr));
return 1;
}
else
append_insns (&buildaddr, insn_data.insn_ptr - buf, buf);
*adjusted_insn_addr_end = buildaddr;
/* Go back to the start of the buffer. */
p = buf;
/* Emit a branch back from the jump pad. */
offset = (tpaddr + orig_size - buildaddr);
if (!can_encode_int32 (offset, 28))
{
sprintf (err,
"E.Jump back from jump pad too far from tracepoint "
"(offset 0x%" PRIx64 " cannot be encoded in 28 bits).",
offset);
return 1;
}
p += emit_b (p, 0, offset);
append_insns (&buildaddr, p - buf, buf);
/* Give the caller a branch instruction into the jump pad. */
offset = (*jump_entry - tpaddr);
if (!can_encode_int32 (offset, 28))
{
sprintf (err,
"E.Jump pad too far from tracepoint "
"(offset 0x%" PRIx64 " cannot be encoded in 28 bits).",
offset);
return 1;
}
emit_b ((uint32_t *) jjump_pad_insn, 0, offset);
*jjump_pad_insn_size = 4;
/* Return the end address of our pad. */
*jump_entry = buildaddr;
return 0;
}
/* Helper function writing LEN instructions from START into
current_insn_ptr. */
static void
emit_ops_insns (const uint32_t *start, int len)
{
CORE_ADDR buildaddr = current_insn_ptr;
if (debug_threads)
debug_printf ("Adding %d instrucions at %s\n",
len, paddress (buildaddr));
append_insns (&buildaddr, len, start);
current_insn_ptr = buildaddr;
}
/* Pop a register from the stack. */
static int
emit_pop (uint32_t *buf, struct aarch64_register rt)
{
return emit_ldr (buf, rt, sp, postindex_memory_operand (1 * 16));
}
/* Push a register on the stack. */
static int
emit_push (uint32_t *buf, struct aarch64_register rt)
{
return emit_str (buf, rt, sp, preindex_memory_operand (-1 * 16));
}
/* Implementation of emit_ops method "emit_prologue". */
static void
aarch64_emit_prologue (void)
{
uint32_t buf[16];
uint32_t *p = buf;
/* This function emit a prologue for the following function prototype:
enum eval_result_type f (unsigned char *regs,
ULONGEST *value);
The first argument is a buffer of raw registers. The second
argument is the result of
evaluating the expression, which will be set to whatever is on top of
the stack at the end.
The stack set up by the prologue is as such:
High *------------------------------------------------------*
| LR |
| FP | <- FP
| x1 (ULONGEST *value) |
| x0 (unsigned char *regs) |
Low *------------------------------------------------------*
As we are implementing a stack machine, each opcode can expand the
stack so we never know how far we are from the data saved by this
prologue. In order to be able refer to value and regs later, we save
the current stack pointer in the frame pointer. This way, it is not
clobbered when calling C functions.
Finally, throughout every operation, we are using register x0 as the
top of the stack, and x1 as a scratch register. */
p += emit_stp (p, x0, x1, sp, preindex_memory_operand (-2 * 16));
p += emit_str (p, lr, sp, offset_memory_operand (3 * 8));
p += emit_str (p, fp, sp, offset_memory_operand (2 * 8));
p += emit_add (p, fp, sp, immediate_operand (2 * 8));
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_epilogue". */
static void
aarch64_emit_epilogue (void)
{
uint32_t buf[16];
uint32_t *p = buf;
/* Store the result of the expression (x0) in *value. */
p += emit_sub (p, x1, fp, immediate_operand (1 * 8));
p += emit_ldr (p, x1, x1, offset_memory_operand (0));
p += emit_str (p, x0, x1, offset_memory_operand (0));
/* Restore the previous state. */
p += emit_add (p, sp, fp, immediate_operand (2 * 8));
p += emit_ldp (p, fp, lr, fp, offset_memory_operand (0));
/* Return expr_eval_no_error. */
p += emit_mov (p, x0, immediate_operand (expr_eval_no_error));
p += emit_ret (p, lr);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_add". */
static void
aarch64_emit_add (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_add (p, x0, x1, register_operand (x0));
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_sub". */
static void
aarch64_emit_sub (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_sub (p, x0, x1, register_operand (x0));
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_mul". */
static void
aarch64_emit_mul (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_mul (p, x0, x1, x0);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_lsh". */
static void
aarch64_emit_lsh (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_lslv (p, x0, x1, x0);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_rsh_signed". */
static void
aarch64_emit_rsh_signed (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_asrv (p, x0, x1, x0);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_rsh_unsigned". */
static void
aarch64_emit_rsh_unsigned (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_lsrv (p, x0, x1, x0);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_ext". */
static void
aarch64_emit_ext (int arg)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_sbfx (p, x0, x0, 0, arg);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_log_not". */
static void
aarch64_emit_log_not (void)
{
uint32_t buf[16];
uint32_t *p = buf;
/* If the top of the stack is 0, replace it with 1. Else replace it with
0. */
p += emit_cmp (p, x0, immediate_operand (0));
p += emit_cset (p, x0, EQ);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_bit_and". */
static void
aarch64_emit_bit_and (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_and (p, x0, x0, x1);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_bit_or". */
static void
aarch64_emit_bit_or (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_orr (p, x0, x0, x1);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_bit_xor". */
static void
aarch64_emit_bit_xor (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_eor (p, x0, x0, x1);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_bit_not". */
static void
aarch64_emit_bit_not (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_mvn (p, x0, x0);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_equal". */
static void
aarch64_emit_equal (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_cmp (p, x0, register_operand (x1));
p += emit_cset (p, x0, EQ);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_less_signed". */
static void
aarch64_emit_less_signed (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_cmp (p, x1, register_operand (x0));
p += emit_cset (p, x0, LT);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_less_unsigned". */
static void
aarch64_emit_less_unsigned (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_cmp (p, x1, register_operand (x0));
p += emit_cset (p, x0, LO);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_ref". */
static void
aarch64_emit_ref (int size)
{
uint32_t buf[16];
uint32_t *p = buf;
switch (size)
{
case 1:
p += emit_ldrb (p, w0, x0, offset_memory_operand (0));
break;
case 2:
p += emit_ldrh (p, w0, x0, offset_memory_operand (0));
break;
case 4:
p += emit_ldr (p, w0, x0, offset_memory_operand (0));
break;
case 8:
p += emit_ldr (p, x0, x0, offset_memory_operand (0));
break;
default:
/* Unknown size, bail on compilation. */
emit_error = 1;
break;
}
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_if_goto". */
static void
aarch64_emit_if_goto (int *offset_p, int *size_p)
{
uint32_t buf[16];
uint32_t *p = buf;
/* The Z flag is set or cleared here. */
p += emit_cmp (p, x0, immediate_operand (0));
/* This instruction must not change the Z flag. */
p += emit_pop (p, x0);
/* Branch over the next instruction if x0 == 0. */
p += emit_bcond (p, EQ, 8);
/* The NOP instruction will be patched with an unconditional branch. */
if (offset_p)
*offset_p = (p - buf) * 4;
if (size_p)
*size_p = 4;
p += emit_nop (p);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_goto". */
static void
aarch64_emit_goto (int *offset_p, int *size_p)
{
uint32_t buf[16];
uint32_t *p = buf;
/* The NOP instruction will be patched with an unconditional branch. */
if (offset_p)
*offset_p = 0;
if (size_p)
*size_p = 4;
p += emit_nop (p);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "write_goto_address". */
static void
aarch64_write_goto_address (CORE_ADDR from, CORE_ADDR to, int size)
{
uint32_t insn;
emit_b (&insn, 0, to - from);
append_insns (&from, 1, &insn);
}
/* Implementation of emit_ops method "emit_const". */
static void
aarch64_emit_const (LONGEST num)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_mov_addr (p, x0, num);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_call". */
static void
aarch64_emit_call (CORE_ADDR fn)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_mov_addr (p, ip0, fn);
p += emit_blr (p, ip0);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_reg". */
static void
aarch64_emit_reg (int reg)
{
uint32_t buf[16];
uint32_t *p = buf;
/* Set x0 to unsigned char *regs. */
p += emit_sub (p, x0, fp, immediate_operand (2 * 8));
p += emit_ldr (p, x0, x0, offset_memory_operand (0));
p += emit_mov (p, x1, immediate_operand (reg));
emit_ops_insns (buf, p - buf);
aarch64_emit_call (get_raw_reg_func_addr ());
}
/* Implementation of emit_ops method "emit_pop". */
static void
aarch64_emit_pop (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x0);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_stack_flush". */
static void
aarch64_emit_stack_flush (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_push (p, x0);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_zero_ext". */
static void
aarch64_emit_zero_ext (int arg)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_ubfx (p, x0, x0, 0, arg);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_swap". */
static void
aarch64_emit_swap (void)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_ldr (p, x1, sp, offset_memory_operand (0 * 16));
p += emit_str (p, x0, sp, offset_memory_operand (0 * 16));
p += emit_mov (p, x0, register_operand (x1));
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_stack_adjust". */
static void
aarch64_emit_stack_adjust (int n)
{
/* This is not needed with our design. */
uint32_t buf[16];
uint32_t *p = buf;
p += emit_add (p, sp, sp, immediate_operand (n * 16));
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_int_call_1". */
static void
aarch64_emit_int_call_1 (CORE_ADDR fn, int arg1)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_mov (p, x0, immediate_operand (arg1));
emit_ops_insns (buf, p - buf);
aarch64_emit_call (fn);
}
/* Implementation of emit_ops method "emit_void_call_2". */
static void
aarch64_emit_void_call_2 (CORE_ADDR fn, int arg1)
{
uint32_t buf[16];
uint32_t *p = buf;
/* Push x0 on the stack. */
aarch64_emit_stack_flush ();
/* Setup arguments for the function call:
x0: arg1
x1: top of the stack
MOV x1, x0
MOV x0, #arg1 */
p += emit_mov (p, x1, register_operand (x0));
p += emit_mov (p, x0, immediate_operand (arg1));
emit_ops_insns (buf, p - buf);
aarch64_emit_call (fn);
/* Restore x0. */
aarch64_emit_pop ();
}
/* Implementation of emit_ops method "emit_eq_goto". */
static void
aarch64_emit_eq_goto (int *offset_p, int *size_p)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_cmp (p, x1, register_operand (x0));
/* Branch over the next instruction if x0 != x1. */
p += emit_bcond (p, NE, 8);
/* The NOP instruction will be patched with an unconditional branch. */
if (offset_p)
*offset_p = (p - buf) * 4;
if (size_p)
*size_p = 4;
p += emit_nop (p);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_ne_goto". */
static void
aarch64_emit_ne_goto (int *offset_p, int *size_p)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_cmp (p, x1, register_operand (x0));
/* Branch over the next instruction if x0 == x1. */
p += emit_bcond (p, EQ, 8);
/* The NOP instruction will be patched with an unconditional branch. */
if (offset_p)
*offset_p = (p - buf) * 4;
if (size_p)
*size_p = 4;
p += emit_nop (p);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_lt_goto". */
static void
aarch64_emit_lt_goto (int *offset_p, int *size_p)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_cmp (p, x1, register_operand (x0));
/* Branch over the next instruction if x0 >= x1. */
p += emit_bcond (p, GE, 8);
/* The NOP instruction will be patched with an unconditional branch. */
if (offset_p)
*offset_p = (p - buf) * 4;
if (size_p)
*size_p = 4;
p += emit_nop (p);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_le_goto". */
static void
aarch64_emit_le_goto (int *offset_p, int *size_p)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_cmp (p, x1, register_operand (x0));
/* Branch over the next instruction if x0 > x1. */
p += emit_bcond (p, GT, 8);
/* The NOP instruction will be patched with an unconditional branch. */
if (offset_p)
*offset_p = (p - buf) * 4;
if (size_p)
*size_p = 4;
p += emit_nop (p);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_gt_goto". */
static void
aarch64_emit_gt_goto (int *offset_p, int *size_p)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_cmp (p, x1, register_operand (x0));
/* Branch over the next instruction if x0 <= x1. */
p += emit_bcond (p, LE, 8);
/* The NOP instruction will be patched with an unconditional branch. */
if (offset_p)
*offset_p = (p - buf) * 4;
if (size_p)
*size_p = 4;
p += emit_nop (p);
emit_ops_insns (buf, p - buf);
}
/* Implementation of emit_ops method "emit_ge_got". */
static void
aarch64_emit_ge_got (int *offset_p, int *size_p)
{
uint32_t buf[16];
uint32_t *p = buf;
p += emit_pop (p, x1);
p += emit_cmp (p, x1, register_operand (x0));
/* Branch over the next instruction if x0 <= x1. */
p += emit_bcond (p, LT, 8);
/* The NOP instruction will be patched with an unconditional branch. */
if (offset_p)
*offset_p = (p - buf) * 4;
if (size_p)
*size_p = 4;
p += emit_nop (p);
emit_ops_insns (buf, p - buf);
}
static struct emit_ops aarch64_emit_ops_impl =
{
aarch64_emit_prologue,
aarch64_emit_epilogue,
aarch64_emit_add,
aarch64_emit_sub,
aarch64_emit_mul,
aarch64_emit_lsh,
aarch64_emit_rsh_signed,
aarch64_emit_rsh_unsigned,
aarch64_emit_ext,
aarch64_emit_log_not,
aarch64_emit_bit_and,
aarch64_emit_bit_or,
aarch64_emit_bit_xor,
aarch64_emit_bit_not,
aarch64_emit_equal,
aarch64_emit_less_signed,
aarch64_emit_less_unsigned,
aarch64_emit_ref,
aarch64_emit_if_goto,
aarch64_emit_goto,
aarch64_write_goto_address,
aarch64_emit_const,
aarch64_emit_call,
aarch64_emit_reg,
aarch64_emit_pop,
aarch64_emit_stack_flush,
aarch64_emit_zero_ext,
aarch64_emit_swap,
aarch64_emit_stack_adjust,
aarch64_emit_int_call_1,
aarch64_emit_void_call_2,
aarch64_emit_eq_goto,
aarch64_emit_ne_goto,
aarch64_emit_lt_goto,
aarch64_emit_le_goto,
aarch64_emit_gt_goto,
aarch64_emit_ge_got,
};
/* Implementation of target ops method "emit_ops". */
emit_ops *
aarch64_target::emit_ops ()
{
return &aarch64_emit_ops_impl;
}
/* Implementation of target ops method
"get_min_fast_tracepoint_insn_len". */
int
aarch64_target::get_min_fast_tracepoint_insn_len ()
{
return 4;
}
/* Implementation of linux target ops method "low_supports_range_stepping". */
bool
aarch64_target::low_supports_range_stepping ()
{
return true;
}
/* Implementation of target ops method "sw_breakpoint_from_kind". */
const gdb_byte *
aarch64_target::sw_breakpoint_from_kind (int kind, int *size)
{
if (is_64bit_tdesc ())
{
*size = aarch64_breakpoint_len;
return aarch64_breakpoint;
}
else
return arm_sw_breakpoint_from_kind (kind, size);
}
/* Implementation of target ops method "breakpoint_kind_from_pc". */
int
aarch64_target::breakpoint_kind_from_pc (CORE_ADDR *pcptr)
{
if (is_64bit_tdesc ())
return aarch64_breakpoint_len;
else
return arm_breakpoint_kind_from_pc (pcptr);
}
/* Implementation of the target ops method
"breakpoint_kind_from_current_state". */
int
aarch64_target::breakpoint_kind_from_current_state (CORE_ADDR *pcptr)
{
if (is_64bit_tdesc ())
return aarch64_breakpoint_len;
else
return arm_breakpoint_kind_from_current_state (pcptr);
}
/* The linux target ops object. */
linux_process_target *the_linux_target = &the_aarch64_target;
void
initialize_low_arch (void)
{
initialize_low_arch_aarch32 ();
initialize_regsets_info (&aarch64_regsets_info);
initialize_regsets_info (&aarch64_sve_regsets_info);
}
|
/* 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/lite/delegates/gpu/cl/api.h"
#include <EGL/eglext.h>
#include <algorithm>
#include <cstring>
#include "absl/memory/memory.h"
#include "absl/types/span.h"
#include "tensorflow/lite/delegates/gpu/cl/cl_command_queue.h"
#include "tensorflow/lite/delegates/gpu/cl/cl_errors.h"
#include "tensorflow/lite/delegates/gpu/cl/cl_event.h"
#include "tensorflow/lite/delegates/gpu/cl/egl_sync.h"
#include "tensorflow/lite/delegates/gpu/cl/environment.h"
#include "tensorflow/lite/delegates/gpu/cl/gl_interop.h"
#include "tensorflow/lite/delegates/gpu/cl/inference_context.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/converter.h"
#include "tensorflow/lite/delegates/gpu/cl/opencl_wrapper.h"
#include "tensorflow/lite/delegates/gpu/cl/precision.h"
#include "tensorflow/lite/delegates/gpu/cl/tensor.h"
#include "tensorflow/lite/delegates/gpu/cl/tensor_type.h"
#include "tensorflow/lite/delegates/gpu/cl/tensor_type_util.h"
#include "tensorflow/lite/delegates/gpu/common/data_type.h"
#include "tensorflow/lite/delegates/gpu/common/shape.h"
#include "tensorflow/lite/delegates/gpu/common/tensor.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
// Both internal and external defs are identical, therefore nothing to connect
// here.
class NoopTensorTie : public TensorTie {
public:
NoopTensorTie(const TensorTieDef& def, TensorObject obj)
: TensorTie(def), obj_(obj) {}
static bool IsSupported(const TensorTieDef& def) {
return def.external_def == def.internal_def;
}
absl::Status SetExternalObject(TensorObject obj) final {
if (!def().external_def.object_def.user_provided) {
return absl::InvalidArgumentError("Tensor object is readonly.");
}
if (!IsValid(def().external_def, obj)) {
return absl::InvalidArgumentError("Given object is not valid");
}
obj_ = obj;
return absl::OkStatus();
}
TensorObject GetExternalObject() final { return obj_; }
absl::Status CopyToExternalObject() final { return absl::OkStatus(); }
absl::Status CopyFromExternalObject() final { return absl::OkStatus(); }
private:
TensorObject obj_;
};
// Does one-step conversion between internal and external objects.
// It may also allocate external objects if requested.
class DefaultTensorTie : public TensorTie {
public:
DefaultTensorTie(const TensorTieDef& def, TensorObject internal_obj)
: TensorTie(def), internal_obj_(internal_obj) {}
static bool IsSupported(
const TensorTieDef& def,
const TensorObjectConverterBuilder& converter_builder) {
auto object_type = def.external_def.object_def.object_type;
if (def.external_def.object_def.user_provided &&
GlClBufferCopier::IsSupported(def.external_def.object_def,
def.internal_def.object_def)) {
return true;
}
return (object_type == ObjectType::OPENCL_BUFFER ||
object_type == ObjectType::OPENCL_TEXTURE ||
object_type == ObjectType::CPU_MEMORY) &&
converter_builder.IsSupported(def.internal_def, def.external_def) &&
converter_builder.IsSupported(def.external_def, def.internal_def);
}
static absl::Status New(const TensorTieDef& def, TensorObject internal_object,
TensorObjectConverterBuilder* converter_builder,
Environment* env, std::unique_ptr<TensorTie>* tie) {
auto tie_impl = absl::make_unique<DefaultTensorTie>(def, internal_object);
RETURN_IF_ERROR(tie_impl->Init(converter_builder, env));
*tie = std::move(tie_impl);
return absl::OkStatus();
}
absl::Status CopyToExternalObject() final {
if (!converter_to_) {
return absl::UnavailableError("Conversion is not available");
}
return converter_to_->Convert(internal_obj_, GetExternalObject());
}
absl::Status CopyFromExternalObject() final {
if (!converter_from_) {
return absl::UnavailableError("Conversion is not available");
}
return converter_from_->Convert(GetExternalObject(), internal_obj_);
}
absl::Status SetExternalObject(TensorObject obj) final {
if (!def().external_def.object_def.user_provided) {
return absl::InvalidArgumentError("External object is read-only");
}
if (!IsValid(def().external_def, obj)) {
return absl::InvalidArgumentError("Given object is not valid");
}
external_obj_ = obj;
return absl::OkStatus();
}
TensorObject GetExternalObject() final { return external_obj_; }
private:
absl::Status Init(TensorObjectConverterBuilder* converter_builder,
Environment* env) {
if (def().external_def.object_def.user_provided &&
GlClBufferCopier::IsSupported(def().external_def.object_def,
def().internal_def.object_def)) {
converter_from_ = absl::make_unique<GlClBufferCopier>(
def().internal_def, def().external_def, env);
} else {
RETURN_IF_ERROR(converter_builder->MakeConverter(
def().external_def, def().internal_def, &converter_from_));
}
if (def().external_def.object_def.user_provided &&
GlClBufferCopier::IsSupported(def().internal_def.object_def,
def().external_def.object_def)) {
converter_to_ = absl::make_unique<GlClBufferCopier>(
def().internal_def, def().external_def, env);
} else {
RETURN_IF_ERROR(converter_builder->MakeConverter(
def().internal_def, def().external_def, &converter_to_));
}
return MaybeAllocateExternalObject(env);
}
absl::Status MaybeAllocateExternalObject(Environment* env) {
const TensorObjectDef& d = def().external_def;
if (d.object_def.user_provided) {
return absl::OkStatus();
}
switch (d.object_def.object_type) {
case ObjectType::CPU_MEMORY: {
size_t bytes_size = NumElements(d) * SizeOf(d.object_def.data_type);
cpu_memory_.resize(bytes_size);
external_obj_ = CpuMemory{cpu_memory_.data(), cpu_memory_.size()};
break;
}
case ObjectType::OPENCL_TEXTURE:
case ObjectType::OPENCL_BUFFER: {
auto& dims = d.dimensions;
const BHWC shape(dims.b, dims.h, dims.w, dims.c);
const TensorDescriptor desc{
d.object_def.data_type,
ToTensorStorageType(d.object_def.object_type,
d.object_def.data_layout),
Layout::BHWC};
RETURN_IF_ERROR(AllocateTensorMemory(env->context(), env->device(),
shape, desc, &cl_memory_));
if (d.object_def.object_type == ObjectType::OPENCL_TEXTURE) {
external_obj_ = OpenClTexture{cl_memory_.memory()};
} else {
external_obj_ = OpenClBuffer{cl_memory_.memory()};
}
break;
}
default:
return absl::InternalError("Unexpected object type");
}
return absl::OkStatus();
}
const TensorObject internal_obj_;
TensorObject external_obj_;
CLMemory cl_memory_;
std::vector<uint8_t> cpu_memory_;
std::unique_ptr<TensorObjectConverter> converter_to_;
std::unique_ptr<TensorObjectConverter> converter_from_;
};
// Copies data to intermediate OpenCL buffer and then does two step conversion.
// It drives the following cases were one-step conversion is not supported:
// - CPU BHWC -> CL buffer BHWC -> CL texture DHWC4.
class TwoStepTensorTie : public TensorTie {
public:
explicit TwoStepTensorTie(const TensorTieDef& def) : TensorTie(def) {}
static bool IsSupported(
const TensorTieDef& def,
const TensorObjectConverterBuilder& converter_builder) {
auto defs = MakeOuterInnerDefs(def);
return DefaultTensorTie::IsSupported(defs.first, converter_builder) &&
DefaultTensorTie::IsSupported(defs.second, converter_builder);
}
static absl::Status New(const TensorTieDef& def, TensorObject internal_object,
TensorObjectConverterBuilder* converter_builder,
Environment* env, std::unique_ptr<TensorTie>* tie) {
auto tie_impl = absl::make_unique<TwoStepTensorTie>(def);
RETURN_IF_ERROR(tie_impl->Init(internal_object, converter_builder, env));
*tie = std::move(tie_impl);
return absl::OkStatus();
}
absl::Status CopyToExternalObject() final {
RETURN_IF_ERROR(inner_tie_->CopyToExternalObject());
return outer_tie_->CopyToExternalObject();
}
absl::Status CopyFromExternalObject() final {
RETURN_IF_ERROR(outer_tie_->CopyFromExternalObject());
return inner_tie_->CopyFromExternalObject();
}
absl::Status SetExternalObject(TensorObject obj) final {
return outer_tie_->SetExternalObject(obj);
}
TensorObject GetExternalObject() final {
return outer_tie_->GetExternalObject();
}
private:
static std::pair<TensorTieDef, TensorTieDef> MakeOuterInnerDefs(
const TensorTieDef& def) {
TensorTieDef outer_def;
outer_def.external_def = def.external_def;
outer_def.internal_def = def.external_def;
outer_def.internal_def.object_def.object_type = ObjectType::OPENCL_BUFFER;
outer_def.internal_def.object_def.user_provided = true;
TensorTieDef inner_def;
inner_def.external_def = outer_def.internal_def;
inner_def.external_def.object_def.user_provided = false;
inner_def.internal_def = def.internal_def;
return std::make_pair(outer_def, inner_def);
}
absl::Status Init(TensorObject internal_object,
TensorObjectConverterBuilder* converter_builder,
Environment* env) {
auto defs = MakeOuterInnerDefs(def());
RETURN_IF_ERROR(DefaultTensorTie::New(defs.second, internal_object,
converter_builder, env, &inner_tie_));
return DefaultTensorTie::New(defs.first, inner_tie_->GetExternalObject(),
converter_builder, env, &outer_tie_);
}
std::unique_ptr<TensorTie> inner_tie_;
std::unique_ptr<TensorTie> outer_tie_;
};
// Captures GL object into CL context before performing a conversion.
class GlBufferHolder : public TensorTie {
public:
GlBufferHolder(const TensorTieDef& def, GlInteropFabric* gl_interop_fabric,
Environment* env)
: TensorTie(def),
gl_interop_fabric_(gl_interop_fabric),
environment_(env) {}
static bool IsSupported(
const TensorTieDef& def,
const TensorObjectConverterBuilder& converter_builder) {
if (!def.external_def.object_def.user_provided ||
def.external_def.object_def.object_type != ObjectType::OPENGL_SSBO) {
return false;
}
return DefaultTensorTie::IsSupported(MakeClDef(def), converter_builder);
}
static absl::Status New(const TensorTieDef& def, TensorObject internal_object,
TensorObjectConverterBuilder* converter_builder,
GlInteropFabric* gl_interop_fabric, Environment* env,
std::unique_ptr<TensorTie>* tie) {
auto tie_impl =
absl::make_unique<GlBufferHolder>(def, gl_interop_fabric, env);
RETURN_IF_ERROR(DefaultTensorTie::New(MakeClDef(def), internal_object,
converter_builder, env,
&tie_impl->tie_));
*tie = std::move(tie_impl);
return absl::OkStatus();
}
absl::Status SetExternalObject(TensorObject obj) final {
auto ssbo = absl::get_if<OpenGlBuffer>(&obj);
if (!ssbo) {
return absl::InvalidArgumentError("Missing OpenGL SSBO");
}
auto old_ssbo = absl::get_if<OpenGlBuffer>(&external_obj_);
if (old_ssbo && ssbo->id == old_ssbo->id) {
return absl::OkStatus();
}
if (cl_object_.memory()) {
gl_interop_fabric_->UnregisterMemory(cl_object_.memory());
}
RETURN_IF_ERROR(CreateClMemoryFromGlBuffer(
ssbo->id, def().access_type, &environment_->context(), &cl_object_));
external_obj_ = obj;
RETURN_IF_ERROR(tie_->SetExternalObject(OpenClBuffer{cl_object_.memory()}));
gl_interop_fabric_->RegisterMemory(cl_object_.memory());
return absl::OkStatus();
}
TensorObject GetExternalObject() final { return external_obj_; }
absl::Status CopyFromExternalObject() final {
return tie_->CopyFromExternalObject();
}
absl::Status CopyToExternalObject() final {
return tie_->CopyToExternalObject();
}
private:
static TensorTieDef MakeClDef(const TensorTieDef& def) {
auto cl_def = def;
cl_def.external_def.object_def.object_type = ObjectType::OPENCL_BUFFER;
cl_def.external_def.object_def.user_provided = true;
return cl_def;
}
CLMemory cl_object_;
GlInteropFabric* gl_interop_fabric_;
Environment* environment_;
std::unique_ptr<TensorTie> tie_;
TensorObject external_obj_;
};
TensorObject TensorToObj(const Tensor& tensor) {
if (tensor.GetStorageType() == TensorStorageType::BUFFER) {
return OpenClBuffer{tensor.GetMemoryPtr()};
}
if (tensor.GetStorageType() == TensorStorageType::IMAGE_BUFFER) {
return OpenClBuffer{tensor.GetMemoryPtrForWriting()};
}
return OpenClTexture{tensor.GetMemoryPtr()};
}
// Responsible for creating new tensor objects.
class TensorTieFactory {
public:
TensorTieFactory(Environment* env, InferenceContext* context,
GlInteropFabric* gl_interop_fabric)
: env_(*env),
context_(*context),
gl_interop_fabric_(gl_interop_fabric),
converter_builder_(NewConverterBuilder(env)) {}
bool IsSupported(const TensorTieDef& def) const {
return IsValid(def.external_def.object_def) &&
(NoopTensorTie::IsSupported(def) ||
DefaultTensorTie::IsSupported(def, *converter_builder_) ||
(gl_interop_fabric_ &&
GlBufferHolder::IsSupported(def, *converter_builder_)) ||
TwoStepTensorTie::IsSupported(def, *converter_builder_));
}
absl::Status NewTensorTie(const TensorTieDef& def,
std::unique_ptr<TensorTie>* tie) {
TensorObject internal_object = TensorToObj(*context_.GetTensor(def.id));
auto converter = converter_builder_.get();
if (NoopTensorTie::IsSupported(def)) {
*tie = absl::make_unique<NoopTensorTie>(def, internal_object);
return absl::OkStatus();
}
if (DefaultTensorTie::IsSupported(def, *converter)) {
return DefaultTensorTie::New(def, internal_object, converter, &env_, tie);
}
if (gl_interop_fabric_ && GlBufferHolder::IsSupported(def, *converter)) {
return GlBufferHolder::New(def, internal_object, converter,
gl_interop_fabric_, &env_, tie);
}
if (TwoStepTensorTie::IsSupported(def, *converter)) {
return TwoStepTensorTie::New(def, internal_object, converter, &env_, tie);
}
return absl::UnimplementedError("Unsupported tensor tie definition.");
}
private:
Environment& env_;
InferenceContext& context_;
GlInteropFabric* gl_interop_fabric_;
std::unique_ptr<TensorObjectConverterBuilder> converter_builder_;
};
class InferenceRunnerImpl : public InferenceRunner {
public:
InferenceRunnerImpl(Environment* environment,
std::unique_ptr<InferenceContext> context,
std::unique_ptr<GlInteropFabric> gl_interop_fabric)
: queue_(environment->queue()),
context_(std::move(context)),
gl_interop_fabric_(std::move(gl_interop_fabric)) {}
absl::Status Initialize(const std::vector<TensorTieDef>& inputs,
const std::vector<TensorTieDef>& outputs,
TensorTieFactory* factory) {
RETURN_IF_ERROR(LinkTensors(inputs, factory, &inputs_));
return LinkTensors(outputs, factory, &outputs_);
}
std::vector<TensorObjectDef> inputs() const override {
return GetExternalDefinitions(inputs_);
}
std::vector<TensorObjectDef> outputs() const override {
return GetExternalDefinitions(outputs_);
}
absl::Status GetInputObject(int index, TensorObject* object) override {
if (index < 0 || index >= inputs_.size()) {
return absl::OutOfRangeError("Index is out of range");
}
*object = inputs_[index]->GetExternalObject();
return absl::OkStatus();
}
absl::Status GetOutputObject(int index, TensorObject* object) override {
if (index < 0 || index >= outputs_.size()) {
return absl::OutOfRangeError("Index is out of range");
}
*object = outputs_[index]->GetExternalObject();
return absl::OkStatus();
}
absl::Status SetInputObject(int index, TensorObject object) override {
if (index < 0 || index >= inputs_.size()) {
return absl::OutOfRangeError("Index is out of range");
}
return inputs_[index]->SetExternalObject(object);
}
absl::Status SetOutputObject(int index, TensorObject object) override {
if (index < 0 || index >= outputs_.size()) {
return absl::OutOfRangeError("Index is out of range");
}
return outputs_[index]->SetExternalObject(object);
}
absl::Status Run() override {
if (gl_interop_fabric_) {
RETURN_IF_ERROR(gl_interop_fabric_->Start());
}
for (auto& obj : inputs_) {
RETURN_IF_ERROR(obj->CopyFromExternalObject());
}
RETURN_IF_ERROR(context_->AddToQueue(queue_));
clFlush(queue_->queue());
for (auto& obj : outputs_) {
RETURN_IF_ERROR(obj->CopyToExternalObject());
}
if (gl_interop_fabric_) {
RETURN_IF_ERROR(gl_interop_fabric_->Finish());
}
return absl::OkStatus();
}
private:
static absl::Status LinkTensors(
const std::vector<TensorTieDef>& defs, TensorTieFactory* factory,
std::vector<std::unique_ptr<TensorTie>>* objects) {
objects->reserve(defs.size());
for (auto& def : defs) {
std::unique_ptr<TensorTie> object;
RETURN_IF_ERROR(factory->NewTensorTie(def, &object));
objects->push_back(std::move(object));
}
return absl::OkStatus();
}
static std::vector<TensorObjectDef> GetExternalDefinitions(
const std::vector<std::unique_ptr<TensorTie>>& objects) {
std::vector<TensorObjectDef> defs;
defs.reserve(objects.size());
for (auto& obj : objects) {
defs.push_back(obj->def().external_def);
}
return defs;
}
CLCommandQueue* queue_;
std::unique_ptr<InferenceContext> context_;
std::unique_ptr<GlInteropFabric> gl_interop_fabric_;
std::vector<std::unique_ptr<TensorTie>> inputs_;
std::vector<std::unique_ptr<TensorTie>> outputs_;
};
TensorObjectDef TensorToDef(const Tensor& tensor) {
TensorObjectDef def;
def.dimensions.b = tensor.Batch();
def.dimensions.h = tensor.Height();
def.dimensions.w = tensor.Width();
def.dimensions.c = tensor.Channels();
def.object_def.data_layout = ToDataLayout(tensor.GetStorageType());
def.object_def.data_type = tensor.GetDataType();
def.object_def.object_type = ToObjectType(tensor.GetStorageType());
def.object_def.user_provided = false;
return def;
}
class InferenceBuilderImpl : public InferenceBuilder {
public:
explicit InferenceBuilderImpl(Environment* environment)
: environment_(environment) {}
absl::Status Initialize(const InferenceOptions& options,
const InferenceEnvironmentOptions& env_options,
const GraphFloat32& graph) {
context_ = absl::make_unique<InferenceContext>();
InferenceContext::CreateInferenceInfo create_info;
create_info.precision = GetPrecision(options);
create_info.storage_type = GetStorageType(options);
if (options.usage == InferenceUsage::FAST_SINGLE_ANSWER) {
create_info.hints.Add(ModelHints::kReduceKernelsCount);
create_info.hints.Add(ModelHints::kFastTuning);
}
RETURN_IF_ERROR(context_->InitFromGraph(create_info, graph, environment_));
if (env_options.IsGlAware() &&
IsGlSharingSupported(environment_->device())) {
gl_interop_fabric_ = absl::make_unique<GlInteropFabric>(
env_options.egl_display, environment_);
}
tie_factory_ = absl::make_unique<TensorTieFactory>(
environment_, context_.get(), gl_interop_fabric_.get());
inputs_ = LinkTensors(graph, graph.inputs());
outputs_ = LinkTensors(graph, graph.outputs());
return absl::OkStatus();
}
std::vector<TensorObjectDef> inputs() const override {
return GetExternalDefinitions(inputs_);
}
std::vector<TensorObjectDef> outputs() const override {
return GetExternalDefinitions(outputs_);
}
absl::Status SetInputShape(int index, const Dimensions& dimensions) override {
if (index < 0 || index >= inputs_.size()) {
return absl::OutOfRangeError("Index is out of range");
}
return absl::UnimplementedError("Changing input shapes is not supported");
}
absl::Status SetInputObjectDef(int index, ObjectDef new_def) override {
if (index < 0 || index >= inputs_.size()) {
return absl::OutOfRangeError("Index is out of range");
}
auto def = inputs_[index];
def.external_def.object_def = new_def;
if (!tie_factory_->IsSupported(def)) {
return absl::InvalidArgumentError(
"New object definition is not supported.");
}
inputs_[index] = def;
return absl::OkStatus();
}
absl::Status SetOutputObjectDef(int index, ObjectDef new_def) override {
if (index < 0 || index >= outputs_.size()) {
return absl::OutOfRangeError("Index is out of range");
}
auto def = outputs_[index];
def.external_def.object_def = new_def;
if (!tie_factory_->IsSupported(def)) {
return absl::InvalidArgumentError(
"New object definition is not supported.");
}
outputs_[index] = def;
return absl::OkStatus();
}
absl::Status Build(std::unique_ptr<InferenceRunner>* runner) override {
if (gl_interop_fabric_ && !HasGlObjects()) {
// destroy interop layer when there are no GL objects to avoid
// extra synchronization cost.
gl_interop_fabric_.reset(nullptr);
}
auto runner_impl = absl::make_unique<InferenceRunnerImpl>(
environment_, std::move(context_), std::move(gl_interop_fabric_));
RETURN_IF_ERROR(
runner_impl->Initialize(inputs_, outputs_, tie_factory_.get()));
*runner = std::move(runner_impl);
return absl::OkStatus();
}
private:
TensorStorageType GetStorageType(const InferenceOptions& options) const {
// Fallback to BUFFER that should be supported by default.
std::vector<TensorStorageType> preferred_storage_types;
if (GetRelativeImportance(options, InferencePriority::MIN_LATENCY,
InferencePriority::MIN_MEMORY_USAGE) ==
PriorityImportance::HIGHER) {
preferred_storage_types = {GetFastestStorageType(environment_->device()),
TensorStorageType::BUFFER};
} else {
preferred_storage_types = {
GetStorageTypeWithMinimalMemoryConsumption(environment_->device()),
TensorStorageType::BUFFER};
}
for (TensorStorageType storage_type : preferred_storage_types) {
if (environment_->IsSupported(storage_type)) {
return storage_type;
}
}
return TensorStorageType::UNKNOWN;
}
CalculationsPrecision GetPrecision(const InferenceOptions& options) const {
CalculationsPrecision precision;
switch (GetPosition(options, InferencePriority::MAX_PRECISION)) {
case 1:
precision = CalculationsPrecision::F32;
break;
case 2:
precision = CalculationsPrecision::F32_F16;
break;
case 3:
precision = CalculationsPrecision::F16;
break;
default:
precision = CalculationsPrecision::F16;
break;
}
// Increase precision if lower precision is not supported.
if (!environment_->IsSupported(precision)) {
precision = CalculationsPrecision::F32_F16;
if (!environment_->IsSupported(precision)) {
precision = CalculationsPrecision::F32;
}
}
return precision;
}
// Links internal tensors with external user-facing objects.
std::vector<TensorTieDef> LinkTensors(const GraphFloat32& graph,
const std::vector<Value*>& values) {
std::vector<TensorTieDef> links;
links.reserve(values.size());
for (const auto& value : values) {
TensorObjectDef def = TensorToDef(*context_->GetTensor(value->id));
AccessType access =
graph.IsGraphInput(value->id) ? AccessType::READ : AccessType::WRITE;
links.push_back({value->id, access, def, def});
}
return links;
}
bool HasGlObjects() const {
auto is_gl = [](ObjectType t) {
return t == ObjectType::OPENGL_SSBO || t == ObjectType::OPENGL_TEXTURE;
};
for (const TensorTieDef& def : inputs_) {
if (is_gl(def.external_def.object_def.object_type)) {
return true;
}
}
for (const TensorTieDef& def : outputs_) {
if (is_gl(def.external_def.object_def.object_type)) {
return true;
}
}
return false;
}
static std::vector<TensorObjectDef> GetExternalDefinitions(
const std::vector<TensorTieDef>& links) {
std::vector<TensorObjectDef> defs;
defs.reserve(links.size());
for (auto& desc : links) {
defs.push_back(desc.external_def);
}
return defs;
}
std::unique_ptr<InferenceContext> context_;
std::unique_ptr<GlInteropFabric> gl_interop_fabric_;
Environment* environment_;
std::vector<TensorTieDef> inputs_;
std::vector<TensorTieDef> outputs_;
std::unique_ptr<TensorTieFactory> tie_factory_;
};
class InferenceEnvironmentImpl : public InferenceEnvironment {
public:
explicit InferenceEnvironmentImpl(const InferenceEnvironmentOptions& options)
: options_(options) {}
absl::Status Init() {
RETURN_IF_ERROR(LoadOpenCL());
properties_.is_opencl_available = true;
CLDevice device;
if (options_.device) {
cl_platform_id platform;
RETURN_IF_ERROR(GetDeviceInfo<cl_platform_id>(
options_.device, CL_DEVICE_PLATFORM, &platform));
device = CLDevice(options_.device, platform);
} else {
RETURN_IF_ERROR(CreateDefaultGPUDevice(&device));
}
properties_.is_gl_sharing_supported = IsGlSharingSupported(device);
properties_.is_gl_to_cl_fast_sync_supported =
IsClEventFromEglSyncSupported(device);
properties_.is_cl_to_gl_fast_sync_supported =
IsEglSyncFromClEventSupported();
CLContext context;
if (options_.context) {
if (options_.IsGlAware()) {
return absl::InvalidArgumentError(
"OpenCL context and EGL parameters are set in the same time.");
}
context = CLContext(options_.context, /* has_ownership = */ false);
} else {
if (options_.IsGlAware() && properties_.is_gl_sharing_supported) {
RETURN_IF_ERROR(CreateCLGLContext(
device,
reinterpret_cast<cl_context_properties>(options_.egl_context),
reinterpret_cast<cl_context_properties>(options_.egl_display),
&context));
} else {
RETURN_IF_ERROR(CreateCLContext(device, &context));
}
}
CLCommandQueue queue;
if (options_.command_queue) {
queue =
CLCommandQueue(options_.command_queue, /* has_ownership = */ false);
} else {
RETURN_IF_ERROR(CreateCLCommandQueue(device, context, &queue));
}
// Profiling queue is used for workgroup size tuning.
ProfilingCommandQueue profiling_queue;
RETURN_IF_ERROR(
CreateProfilingCommandQueue(device, context, &profiling_queue));
environment_ = Environment(std::move(device), std::move(context),
std::move(queue), std::move(profiling_queue));
return environment_.Init();
}
absl::Status NewInferenceBuilder(
const InferenceOptions& options, GraphFloat32 model,
std::unique_ptr<InferenceBuilder>* builder) final {
if (!IsValid(options)) {
return absl::InvalidArgumentError("InferenceOptions are invalid.");
}
InferenceOptions resolved_options = options;
ResolveAutoPriority(&resolved_options);
if (environment_.program_cache() &&
!options_.serialized_binary_cache.empty()) {
// Ignore returned error. Cache is discarded.
environment_.program_cache()
->AddSerializedCache(environment_.context(), environment_.device(),
options_.serialized_binary_cache)
.IgnoreError();
}
RETURN_IF_ERROR(RunGraphTransforms(&model));
auto builder_impl = absl::make_unique<InferenceBuilderImpl>(&environment_);
RETURN_IF_ERROR(
builder_impl->Initialize(resolved_options, options_, model));
*builder = std::move(builder_impl);
return absl::OkStatus();
}
std::vector<uint8_t> GetSerializedBinaryCache() const final {
std::vector<uint8_t> data;
// Is there was a problem, data would be empty.
environment_.program_cache()
->GetSerializedCache(environment_.device(), &data)
.IgnoreError();
return data;
}
const InferenceEnvironmentProperties& properties() const {
return properties_;
}
private:
const InferenceEnvironmentOptions options_;
Environment environment_;
InferenceEnvironmentProperties properties_;
};
} // namespace
absl::Status NewInferenceEnvironment(
const InferenceEnvironmentOptions& options,
std::unique_ptr<InferenceEnvironment>* environment,
InferenceEnvironmentProperties* properties) {
auto env_impl = absl::make_unique<InferenceEnvironmentImpl>(options);
absl::Status status = env_impl->Init();
if (properties) {
*properties = env_impl->properties();
}
RETURN_IF_ERROR(status);
*environment = std::move(env_impl);
return absl::OkStatus();
}
} // namespace cl
} // namespace gpu
} // namespace tflite
|
;
; jidctred.asm - reduced-size IDCT (MMX)
;
; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
;
; Based on
; x86 SIMD extension for IJG JPEG library
; Copyright (C) 1999-2006, MIYASAKA Masaru.
; For conditions of distribution and use, see copyright notice in jsimdext.inc
;
; This file should be assembled with NASM (Netwide Assembler),
; can *not* be assembled with Microsoft's MASM or any compatible
; assembler (including Borland's Turbo Assembler).
; NASM is available from http://nasm.sourceforge.net/ or
; http://sourceforge.net/project/showfiles.php?group_id=6208
;
; This file contains inverse-DCT routines that produce reduced-size
; output: either 4x4 or 2x2 pixels from an 8x8 DCT block.
; The following code is based directly on the IJG's original jidctred.c;
; see the jidctred.c for more details.
;
; [TAB8]
%include "jsimdext.inc"
%include "jdct.inc"
; --------------------------------------------------------------------------
%define CONST_BITS 13
%define PASS1_BITS 2
%define DESCALE_P1_4 (CONST_BITS-PASS1_BITS+1)
%define DESCALE_P2_4 (CONST_BITS+PASS1_BITS+3+1)
%define DESCALE_P1_2 (CONST_BITS-PASS1_BITS+2)
%define DESCALE_P2_2 (CONST_BITS+PASS1_BITS+3+2)
%if CONST_BITS == 13
F_0_211 equ 1730 ; FIX(0.211164243)
F_0_509 equ 4176 ; FIX(0.509795579)
F_0_601 equ 4926 ; FIX(0.601344887)
F_0_720 equ 5906 ; FIX(0.720959822)
F_0_765 equ 6270 ; FIX(0.765366865)
F_0_850 equ 6967 ; FIX(0.850430095)
F_0_899 equ 7373 ; FIX(0.899976223)
F_1_061 equ 8697 ; FIX(1.061594337)
F_1_272 equ 10426 ; FIX(1.272758580)
F_1_451 equ 11893 ; FIX(1.451774981)
F_1_847 equ 15137 ; FIX(1.847759065)
F_2_172 equ 17799 ; FIX(2.172734803)
F_2_562 equ 20995 ; FIX(2.562915447)
F_3_624 equ 29692 ; FIX(3.624509785)
%else
; NASM cannot do compile-time arithmetic on floating-point constants.
%define DESCALE(x,n) (((x)+(1<<((n)-1)))>>(n))
F_0_211 equ DESCALE( 226735879,30-CONST_BITS) ; FIX(0.211164243)
F_0_509 equ DESCALE( 547388834,30-CONST_BITS) ; FIX(0.509795579)
F_0_601 equ DESCALE( 645689155,30-CONST_BITS) ; FIX(0.601344887)
F_0_720 equ DESCALE( 774124714,30-CONST_BITS) ; FIX(0.720959822)
F_0_765 equ DESCALE( 821806413,30-CONST_BITS) ; FIX(0.765366865)
F_0_850 equ DESCALE( 913142361,30-CONST_BITS) ; FIX(0.850430095)
F_0_899 equ DESCALE( 966342111,30-CONST_BITS) ; FIX(0.899976223)
F_1_061 equ DESCALE(1139878239,30-CONST_BITS) ; FIX(1.061594337)
F_1_272 equ DESCALE(1366614119,30-CONST_BITS) ; FIX(1.272758580)
F_1_451 equ DESCALE(1558831516,30-CONST_BITS) ; FIX(1.451774981)
F_1_847 equ DESCALE(1984016188,30-CONST_BITS) ; FIX(1.847759065)
F_2_172 equ DESCALE(2332956230,30-CONST_BITS) ; FIX(2.172734803)
F_2_562 equ DESCALE(2751909506,30-CONST_BITS) ; FIX(2.562915447)
F_3_624 equ DESCALE(3891787747,30-CONST_BITS) ; FIX(3.624509785)
%endif
; --------------------------------------------------------------------------
SECTION SEG_CONST
alignz 16
global EXTN(jconst_idct_red_mmx)
EXTN(jconst_idct_red_mmx):
PW_F184_MF076 times 2 dw F_1_847,-F_0_765
PW_F256_F089 times 2 dw F_2_562, F_0_899
PW_F106_MF217 times 2 dw F_1_061,-F_2_172
PW_MF060_MF050 times 2 dw -F_0_601,-F_0_509
PW_F145_MF021 times 2 dw F_1_451,-F_0_211
PW_F362_MF127 times 2 dw F_3_624,-F_1_272
PW_F085_MF072 times 2 dw F_0_850,-F_0_720
PD_DESCALE_P1_4 times 2 dd 1 << (DESCALE_P1_4-1)
PD_DESCALE_P2_4 times 2 dd 1 << (DESCALE_P2_4-1)
PD_DESCALE_P1_2 times 2 dd 1 << (DESCALE_P1_2-1)
PD_DESCALE_P2_2 times 2 dd 1 << (DESCALE_P2_2-1)
PB_CENTERJSAMP times 8 db CENTERJSAMPLE
alignz 16
; --------------------------------------------------------------------------
SECTION SEG_TEXT
BITS 32
;
; Perform dequantization and inverse DCT on one block of coefficients,
; producing a reduced-size 4x4 output block.
;
; GLOBAL(void)
; jsimd_idct_4x4_mmx (void * dct_table, JCOEFPTR coef_block,
; JSAMPARRAY output_buf, JDIMENSION output_col)
;
%define dct_table(b) (b)+8 ; void * dct_table
%define coef_block(b) (b)+12 ; JCOEFPTR coef_block
%define output_buf(b) (b)+16 ; JSAMPARRAY output_buf
%define output_col(b) (b)+20 ; JDIMENSION output_col
%define original_ebp ebp+0
%define wk(i) ebp-(WK_NUM-(i))*SIZEOF_MMWORD ; mmword wk[WK_NUM]
%define WK_NUM 2
%define workspace wk(0)-DCTSIZE2*SIZEOF_JCOEF
; JCOEF workspace[DCTSIZE2]
align 16
global EXTN(jsimd_idct_4x4_mmx)
EXTN(jsimd_idct_4x4_mmx):
push ebp
mov eax,esp ; eax = original ebp
sub esp, byte 4
and esp, byte (-SIZEOF_MMWORD) ; align to 64 bits
mov [esp],eax
mov ebp,esp ; ebp = aligned ebp
lea esp, [workspace]
pushpic ebx
; push ecx ; need not be preserved
; push edx ; need not be preserved
push esi
push edi
get_GOT ebx ; get GOT address
; ---- Pass 1: process columns from input, store into work array.
; mov eax, [original_ebp]
mov edx, POINTER [dct_table(eax)] ; quantptr
mov esi, JCOEFPTR [coef_block(eax)] ; inptr
lea edi, [workspace] ; JCOEF * wsptr
mov ecx, DCTSIZE/4 ; ctr
alignx 16,7
.columnloop:
%ifndef NO_ZERO_COLUMN_TEST_4X4_MMX
mov eax, DWORD [DWBLOCK(1,0,esi,SIZEOF_JCOEF)]
or eax, DWORD [DWBLOCK(2,0,esi,SIZEOF_JCOEF)]
jnz short .columnDCT
movq mm0, MMWORD [MMBLOCK(1,0,esi,SIZEOF_JCOEF)]
movq mm1, MMWORD [MMBLOCK(2,0,esi,SIZEOF_JCOEF)]
por mm0, MMWORD [MMBLOCK(3,0,esi,SIZEOF_JCOEF)]
por mm1, MMWORD [MMBLOCK(5,0,esi,SIZEOF_JCOEF)]
por mm0, MMWORD [MMBLOCK(6,0,esi,SIZEOF_JCOEF)]
por mm1, MMWORD [MMBLOCK(7,0,esi,SIZEOF_JCOEF)]
por mm0,mm1
packsswb mm0,mm0
movd eax,mm0
test eax,eax
jnz short .columnDCT
; -- AC terms all zero
movq mm0, MMWORD [MMBLOCK(0,0,esi,SIZEOF_JCOEF)]
pmullw mm0, MMWORD [MMBLOCK(0,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
psllw mm0,PASS1_BITS
movq mm2,mm0 ; mm0=in0=(00 01 02 03)
punpcklwd mm0,mm0 ; mm0=(00 00 01 01)
punpckhwd mm2,mm2 ; mm2=(02 02 03 03)
movq mm1,mm0
punpckldq mm0,mm0 ; mm0=(00 00 00 00)
punpckhdq mm1,mm1 ; mm1=(01 01 01 01)
movq mm3,mm2
punpckldq mm2,mm2 ; mm2=(02 02 02 02)
punpckhdq mm3,mm3 ; mm3=(03 03 03 03)
movq MMWORD [MMBLOCK(0,0,edi,SIZEOF_JCOEF)], mm0
movq MMWORD [MMBLOCK(1,0,edi,SIZEOF_JCOEF)], mm1
movq MMWORD [MMBLOCK(2,0,edi,SIZEOF_JCOEF)], mm2
movq MMWORD [MMBLOCK(3,0,edi,SIZEOF_JCOEF)], mm3
jmp near .nextcolumn
alignx 16,7
%endif
.columnDCT:
; -- Odd part
movq mm0, MMWORD [MMBLOCK(1,0,esi,SIZEOF_JCOEF)]
movq mm1, MMWORD [MMBLOCK(3,0,esi,SIZEOF_JCOEF)]
pmullw mm0, MMWORD [MMBLOCK(1,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm1, MMWORD [MMBLOCK(3,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
movq mm2, MMWORD [MMBLOCK(5,0,esi,SIZEOF_JCOEF)]
movq mm3, MMWORD [MMBLOCK(7,0,esi,SIZEOF_JCOEF)]
pmullw mm2, MMWORD [MMBLOCK(5,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm3, MMWORD [MMBLOCK(7,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
movq mm4,mm0
movq mm5,mm0
punpcklwd mm4,mm1
punpckhwd mm5,mm1
movq mm0,mm4
movq mm1,mm5
pmaddwd mm4,[GOTOFF(ebx,PW_F256_F089)] ; mm4=(tmp2L)
pmaddwd mm5,[GOTOFF(ebx,PW_F256_F089)] ; mm5=(tmp2H)
pmaddwd mm0,[GOTOFF(ebx,PW_F106_MF217)] ; mm0=(tmp0L)
pmaddwd mm1,[GOTOFF(ebx,PW_F106_MF217)] ; mm1=(tmp0H)
movq mm6,mm2
movq mm7,mm2
punpcklwd mm6,mm3
punpckhwd mm7,mm3
movq mm2,mm6
movq mm3,mm7
pmaddwd mm6,[GOTOFF(ebx,PW_MF060_MF050)] ; mm6=(tmp2L)
pmaddwd mm7,[GOTOFF(ebx,PW_MF060_MF050)] ; mm7=(tmp2H)
pmaddwd mm2,[GOTOFF(ebx,PW_F145_MF021)] ; mm2=(tmp0L)
pmaddwd mm3,[GOTOFF(ebx,PW_F145_MF021)] ; mm3=(tmp0H)
paddd mm6,mm4 ; mm6=tmp2L
paddd mm7,mm5 ; mm7=tmp2H
paddd mm2,mm0 ; mm2=tmp0L
paddd mm3,mm1 ; mm3=tmp0H
movq MMWORD [wk(0)], mm2 ; wk(0)=tmp0L
movq MMWORD [wk(1)], mm3 ; wk(1)=tmp0H
; -- Even part
movq mm4, MMWORD [MMBLOCK(0,0,esi,SIZEOF_JCOEF)]
movq mm5, MMWORD [MMBLOCK(2,0,esi,SIZEOF_JCOEF)]
movq mm0, MMWORD [MMBLOCK(6,0,esi,SIZEOF_JCOEF)]
pmullw mm4, MMWORD [MMBLOCK(0,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm5, MMWORD [MMBLOCK(2,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm0, MMWORD [MMBLOCK(6,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
pxor mm1,mm1
pxor mm2,mm2
punpcklwd mm1,mm4 ; mm1=tmp0L
punpckhwd mm2,mm4 ; mm2=tmp0H
psrad mm1,(16-CONST_BITS-1) ; psrad mm1,16 & pslld mm1,CONST_BITS+1
psrad mm2,(16-CONST_BITS-1) ; psrad mm2,16 & pslld mm2,CONST_BITS+1
movq mm3,mm5 ; mm5=in2=z2
punpcklwd mm5,mm0 ; mm0=in6=z3
punpckhwd mm3,mm0
pmaddwd mm5,[GOTOFF(ebx,PW_F184_MF076)] ; mm5=tmp2L
pmaddwd mm3,[GOTOFF(ebx,PW_F184_MF076)] ; mm3=tmp2H
movq mm4,mm1
movq mm0,mm2
paddd mm1,mm5 ; mm1=tmp10L
paddd mm2,mm3 ; mm2=tmp10H
psubd mm4,mm5 ; mm4=tmp12L
psubd mm0,mm3 ; mm0=tmp12H
; -- Final output stage
movq mm5,mm1
movq mm3,mm2
paddd mm1,mm6 ; mm1=data0L
paddd mm2,mm7 ; mm2=data0H
psubd mm5,mm6 ; mm5=data3L
psubd mm3,mm7 ; mm3=data3H
movq mm6,[GOTOFF(ebx,PD_DESCALE_P1_4)] ; mm6=[PD_DESCALE_P1_4]
paddd mm1,mm6
paddd mm2,mm6
psrad mm1,DESCALE_P1_4
psrad mm2,DESCALE_P1_4
paddd mm5,mm6
paddd mm3,mm6
psrad mm5,DESCALE_P1_4
psrad mm3,DESCALE_P1_4
packssdw mm1,mm2 ; mm1=data0=(00 01 02 03)
packssdw mm5,mm3 ; mm5=data3=(30 31 32 33)
movq mm7, MMWORD [wk(0)] ; mm7=tmp0L
movq mm6, MMWORD [wk(1)] ; mm6=tmp0H
movq mm2,mm4
movq mm3,mm0
paddd mm4,mm7 ; mm4=data1L
paddd mm0,mm6 ; mm0=data1H
psubd mm2,mm7 ; mm2=data2L
psubd mm3,mm6 ; mm3=data2H
movq mm7,[GOTOFF(ebx,PD_DESCALE_P1_4)] ; mm7=[PD_DESCALE_P1_4]
paddd mm4,mm7
paddd mm0,mm7
psrad mm4,DESCALE_P1_4
psrad mm0,DESCALE_P1_4
paddd mm2,mm7
paddd mm3,mm7
psrad mm2,DESCALE_P1_4
psrad mm3,DESCALE_P1_4
packssdw mm4,mm0 ; mm4=data1=(10 11 12 13)
packssdw mm2,mm3 ; mm2=data2=(20 21 22 23)
movq mm6,mm1 ; transpose coefficients(phase 1)
punpcklwd mm1,mm4 ; mm1=(00 10 01 11)
punpckhwd mm6,mm4 ; mm6=(02 12 03 13)
movq mm7,mm2 ; transpose coefficients(phase 1)
punpcklwd mm2,mm5 ; mm2=(20 30 21 31)
punpckhwd mm7,mm5 ; mm7=(22 32 23 33)
movq mm0,mm1 ; transpose coefficients(phase 2)
punpckldq mm1,mm2 ; mm1=(00 10 20 30)
punpckhdq mm0,mm2 ; mm0=(01 11 21 31)
movq mm3,mm6 ; transpose coefficients(phase 2)
punpckldq mm6,mm7 ; mm6=(02 12 22 32)
punpckhdq mm3,mm7 ; mm3=(03 13 23 33)
movq MMWORD [MMBLOCK(0,0,edi,SIZEOF_JCOEF)], mm1
movq MMWORD [MMBLOCK(1,0,edi,SIZEOF_JCOEF)], mm0
movq MMWORD [MMBLOCK(2,0,edi,SIZEOF_JCOEF)], mm6
movq MMWORD [MMBLOCK(3,0,edi,SIZEOF_JCOEF)], mm3
.nextcolumn:
add esi, byte 4*SIZEOF_JCOEF ; coef_block
add edx, byte 4*SIZEOF_ISLOW_MULT_TYPE ; quantptr
add edi, byte 4*DCTSIZE*SIZEOF_JCOEF ; wsptr
dec ecx ; ctr
jnz near .columnloop
; ---- Pass 2: process rows from work array, store into output array.
mov eax, [original_ebp]
lea esi, [workspace] ; JCOEF * wsptr
mov edi, JSAMPARRAY [output_buf(eax)] ; (JSAMPROW *)
mov eax, JDIMENSION [output_col(eax)]
; -- Odd part
movq mm0, MMWORD [MMBLOCK(1,0,esi,SIZEOF_JCOEF)]
movq mm1, MMWORD [MMBLOCK(3,0,esi,SIZEOF_JCOEF)]
movq mm2, MMWORD [MMBLOCK(5,0,esi,SIZEOF_JCOEF)]
movq mm3, MMWORD [MMBLOCK(7,0,esi,SIZEOF_JCOEF)]
movq mm4,mm0
movq mm5,mm0
punpcklwd mm4,mm1
punpckhwd mm5,mm1
movq mm0,mm4
movq mm1,mm5
pmaddwd mm4,[GOTOFF(ebx,PW_F256_F089)] ; mm4=(tmp2L)
pmaddwd mm5,[GOTOFF(ebx,PW_F256_F089)] ; mm5=(tmp2H)
pmaddwd mm0,[GOTOFF(ebx,PW_F106_MF217)] ; mm0=(tmp0L)
pmaddwd mm1,[GOTOFF(ebx,PW_F106_MF217)] ; mm1=(tmp0H)
movq mm6,mm2
movq mm7,mm2
punpcklwd mm6,mm3
punpckhwd mm7,mm3
movq mm2,mm6
movq mm3,mm7
pmaddwd mm6,[GOTOFF(ebx,PW_MF060_MF050)] ; mm6=(tmp2L)
pmaddwd mm7,[GOTOFF(ebx,PW_MF060_MF050)] ; mm7=(tmp2H)
pmaddwd mm2,[GOTOFF(ebx,PW_F145_MF021)] ; mm2=(tmp0L)
pmaddwd mm3,[GOTOFF(ebx,PW_F145_MF021)] ; mm3=(tmp0H)
paddd mm6,mm4 ; mm6=tmp2L
paddd mm7,mm5 ; mm7=tmp2H
paddd mm2,mm0 ; mm2=tmp0L
paddd mm3,mm1 ; mm3=tmp0H
movq MMWORD [wk(0)], mm2 ; wk(0)=tmp0L
movq MMWORD [wk(1)], mm3 ; wk(1)=tmp0H
; -- Even part
movq mm4, MMWORD [MMBLOCK(0,0,esi,SIZEOF_JCOEF)]
movq mm5, MMWORD [MMBLOCK(2,0,esi,SIZEOF_JCOEF)]
movq mm0, MMWORD [MMBLOCK(6,0,esi,SIZEOF_JCOEF)]
pxor mm1,mm1
pxor mm2,mm2
punpcklwd mm1,mm4 ; mm1=tmp0L
punpckhwd mm2,mm4 ; mm2=tmp0H
psrad mm1,(16-CONST_BITS-1) ; psrad mm1,16 & pslld mm1,CONST_BITS+1
psrad mm2,(16-CONST_BITS-1) ; psrad mm2,16 & pslld mm2,CONST_BITS+1
movq mm3,mm5 ; mm5=in2=z2
punpcklwd mm5,mm0 ; mm0=in6=z3
punpckhwd mm3,mm0
pmaddwd mm5,[GOTOFF(ebx,PW_F184_MF076)] ; mm5=tmp2L
pmaddwd mm3,[GOTOFF(ebx,PW_F184_MF076)] ; mm3=tmp2H
movq mm4,mm1
movq mm0,mm2
paddd mm1,mm5 ; mm1=tmp10L
paddd mm2,mm3 ; mm2=tmp10H
psubd mm4,mm5 ; mm4=tmp12L
psubd mm0,mm3 ; mm0=tmp12H
; -- Final output stage
movq mm5,mm1
movq mm3,mm2
paddd mm1,mm6 ; mm1=data0L
paddd mm2,mm7 ; mm2=data0H
psubd mm5,mm6 ; mm5=data3L
psubd mm3,mm7 ; mm3=data3H
movq mm6,[GOTOFF(ebx,PD_DESCALE_P2_4)] ; mm6=[PD_DESCALE_P2_4]
paddd mm1,mm6
paddd mm2,mm6
psrad mm1,DESCALE_P2_4
psrad mm2,DESCALE_P2_4
paddd mm5,mm6
paddd mm3,mm6
psrad mm5,DESCALE_P2_4
psrad mm3,DESCALE_P2_4
packssdw mm1,mm2 ; mm1=data0=(00 10 20 30)
packssdw mm5,mm3 ; mm5=data3=(03 13 23 33)
movq mm7, MMWORD [wk(0)] ; mm7=tmp0L
movq mm6, MMWORD [wk(1)] ; mm6=tmp0H
movq mm2,mm4
movq mm3,mm0
paddd mm4,mm7 ; mm4=data1L
paddd mm0,mm6 ; mm0=data1H
psubd mm2,mm7 ; mm2=data2L
psubd mm3,mm6 ; mm3=data2H
movq mm7,[GOTOFF(ebx,PD_DESCALE_P2_4)] ; mm7=[PD_DESCALE_P2_4]
paddd mm4,mm7
paddd mm0,mm7
psrad mm4,DESCALE_P2_4
psrad mm0,DESCALE_P2_4
paddd mm2,mm7
paddd mm3,mm7
psrad mm2,DESCALE_P2_4
psrad mm3,DESCALE_P2_4
packssdw mm4,mm0 ; mm4=data1=(01 11 21 31)
packssdw mm2,mm3 ; mm2=data2=(02 12 22 32)
movq mm6,[GOTOFF(ebx,PB_CENTERJSAMP)] ; mm6=[PB_CENTERJSAMP]
packsswb mm1,mm2 ; mm1=(00 10 20 30 02 12 22 32)
packsswb mm4,mm5 ; mm4=(01 11 21 31 03 13 23 33)
paddb mm1,mm6
paddb mm4,mm6
movq mm7,mm1 ; transpose coefficients(phase 1)
punpcklbw mm1,mm4 ; mm1=(00 01 10 11 20 21 30 31)
punpckhbw mm7,mm4 ; mm7=(02 03 12 13 22 23 32 33)
movq mm0,mm1 ; transpose coefficients(phase 2)
punpcklwd mm1,mm7 ; mm1=(00 01 02 03 10 11 12 13)
punpckhwd mm0,mm7 ; mm0=(20 21 22 23 30 31 32 33)
mov edx, JSAMPROW [edi+0*SIZEOF_JSAMPROW]
mov esi, JSAMPROW [edi+2*SIZEOF_JSAMPROW]
movd DWORD [edx+eax*SIZEOF_JSAMPLE], mm1
movd DWORD [esi+eax*SIZEOF_JSAMPLE], mm0
psrlq mm1,4*BYTE_BIT
psrlq mm0,4*BYTE_BIT
mov edx, JSAMPROW [edi+1*SIZEOF_JSAMPROW]
mov esi, JSAMPROW [edi+3*SIZEOF_JSAMPROW]
movd DWORD [edx+eax*SIZEOF_JSAMPLE], mm1
movd DWORD [esi+eax*SIZEOF_JSAMPLE], mm0
emms ; empty MMX state
pop edi
pop esi
; pop edx ; need not be preserved
; pop ecx ; need not be preserved
poppic ebx
mov esp,ebp ; esp <- aligned ebp
pop esp ; esp <- original ebp
pop ebp
ret
; --------------------------------------------------------------------------
;
; Perform dequantization and inverse DCT on one block of coefficients,
; producing a reduced-size 2x2 output block.
;
; GLOBAL(void)
; jsimd_idct_2x2_mmx (void * dct_table, JCOEFPTR coef_block,
; JSAMPARRAY output_buf, JDIMENSION output_col)
;
%define dct_table(b) (b)+8 ; void * dct_table
%define coef_block(b) (b)+12 ; JCOEFPTR coef_block
%define output_buf(b) (b)+16 ; JSAMPARRAY output_buf
%define output_col(b) (b)+20 ; JDIMENSION output_col
align 16
global EXTN(jsimd_idct_2x2_mmx)
EXTN(jsimd_idct_2x2_mmx):
push ebp
mov ebp,esp
push ebx
; push ecx ; need not be preserved
; push edx ; need not be preserved
push esi
push edi
get_GOT ebx ; get GOT address
; ---- Pass 1: process columns from input.
mov edx, POINTER [dct_table(ebp)] ; quantptr
mov esi, JCOEFPTR [coef_block(ebp)] ; inptr
; | input: | result: |
; | 00 01 ** 03 ** 05 ** 07 | |
; | 10 11 ** 13 ** 15 ** 17 | |
; | ** ** ** ** ** ** ** ** | |
; | 30 31 ** 33 ** 35 ** 37 | A0 A1 A3 A5 A7 |
; | ** ** ** ** ** ** ** ** | B0 B1 B3 B5 B7 |
; | 50 51 ** 53 ** 55 ** 57 | |
; | ** ** ** ** ** ** ** ** | |
; | 70 71 ** 73 ** 75 ** 77 | |
; -- Odd part
movq mm0, MMWORD [MMBLOCK(1,0,esi,SIZEOF_JCOEF)]
movq mm1, MMWORD [MMBLOCK(3,0,esi,SIZEOF_JCOEF)]
pmullw mm0, MMWORD [MMBLOCK(1,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm1, MMWORD [MMBLOCK(3,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
movq mm2, MMWORD [MMBLOCK(5,0,esi,SIZEOF_JCOEF)]
movq mm3, MMWORD [MMBLOCK(7,0,esi,SIZEOF_JCOEF)]
pmullw mm2, MMWORD [MMBLOCK(5,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm3, MMWORD [MMBLOCK(7,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
; mm0=(10 11 ** 13), mm1=(30 31 ** 33)
; mm2=(50 51 ** 53), mm3=(70 71 ** 73)
pcmpeqd mm7,mm7
pslld mm7,WORD_BIT ; mm7={0x0000 0xFFFF 0x0000 0xFFFF}
movq mm4,mm0 ; mm4=(10 11 ** 13)
movq mm5,mm2 ; mm5=(50 51 ** 53)
punpcklwd mm4,mm1 ; mm4=(10 30 11 31)
punpcklwd mm5,mm3 ; mm5=(50 70 51 71)
pmaddwd mm4,[GOTOFF(ebx,PW_F362_MF127)]
pmaddwd mm5,[GOTOFF(ebx,PW_F085_MF072)]
psrld mm0,WORD_BIT ; mm0=(11 -- 13 --)
pand mm1,mm7 ; mm1=(-- 31 -- 33)
psrld mm2,WORD_BIT ; mm2=(51 -- 53 --)
pand mm3,mm7 ; mm3=(-- 71 -- 73)
por mm0,mm1 ; mm0=(11 31 13 33)
por mm2,mm3 ; mm2=(51 71 53 73)
pmaddwd mm0,[GOTOFF(ebx,PW_F362_MF127)]
pmaddwd mm2,[GOTOFF(ebx,PW_F085_MF072)]
paddd mm4,mm5 ; mm4=tmp0[col0 col1]
movq mm6, MMWORD [MMBLOCK(1,1,esi,SIZEOF_JCOEF)]
movq mm1, MMWORD [MMBLOCK(3,1,esi,SIZEOF_JCOEF)]
pmullw mm6, MMWORD [MMBLOCK(1,1,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm1, MMWORD [MMBLOCK(3,1,edx,SIZEOF_ISLOW_MULT_TYPE)]
movq mm3, MMWORD [MMBLOCK(5,1,esi,SIZEOF_JCOEF)]
movq mm5, MMWORD [MMBLOCK(7,1,esi,SIZEOF_JCOEF)]
pmullw mm3, MMWORD [MMBLOCK(5,1,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm5, MMWORD [MMBLOCK(7,1,edx,SIZEOF_ISLOW_MULT_TYPE)]
; mm6=(** 15 ** 17), mm1=(** 35 ** 37)
; mm3=(** 55 ** 57), mm5=(** 75 ** 77)
psrld mm6,WORD_BIT ; mm6=(15 -- 17 --)
pand mm1,mm7 ; mm1=(-- 35 -- 37)
psrld mm3,WORD_BIT ; mm3=(55 -- 57 --)
pand mm5,mm7 ; mm5=(-- 75 -- 77)
por mm6,mm1 ; mm6=(15 35 17 37)
por mm3,mm5 ; mm3=(55 75 57 77)
pmaddwd mm6,[GOTOFF(ebx,PW_F362_MF127)]
pmaddwd mm3,[GOTOFF(ebx,PW_F085_MF072)]
paddd mm0,mm2 ; mm0=tmp0[col1 col3]
paddd mm6,mm3 ; mm6=tmp0[col5 col7]
; -- Even part
movq mm1, MMWORD [MMBLOCK(0,0,esi,SIZEOF_JCOEF)]
movq mm5, MMWORD [MMBLOCK(0,1,esi,SIZEOF_JCOEF)]
pmullw mm1, MMWORD [MMBLOCK(0,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm5, MMWORD [MMBLOCK(0,1,edx,SIZEOF_ISLOW_MULT_TYPE)]
; mm1=(00 01 ** 03), mm5=(** 05 ** 07)
movq mm2,mm1 ; mm2=(00 01 ** 03)
pslld mm1,WORD_BIT ; mm1=(-- 00 -- **)
psrad mm1,(WORD_BIT-CONST_BITS-2) ; mm1=tmp10[col0 ****]
pand mm2,mm7 ; mm2=(-- 01 -- 03)
pand mm5,mm7 ; mm5=(-- 05 -- 07)
psrad mm2,(WORD_BIT-CONST_BITS-2) ; mm2=tmp10[col1 col3]
psrad mm5,(WORD_BIT-CONST_BITS-2) ; mm5=tmp10[col5 col7]
; -- Final output stage
movq mm3,mm1
paddd mm1,mm4 ; mm1=data0[col0 ****]=(A0 **)
psubd mm3,mm4 ; mm3=data1[col0 ****]=(B0 **)
punpckldq mm1,mm3 ; mm1=(A0 B0)
movq mm7,[GOTOFF(ebx,PD_DESCALE_P1_2)] ; mm7=[PD_DESCALE_P1_2]
movq mm4,mm2
movq mm3,mm5
paddd mm2,mm0 ; mm2=data0[col1 col3]=(A1 A3)
paddd mm5,mm6 ; mm5=data0[col5 col7]=(A5 A7)
psubd mm4,mm0 ; mm4=data1[col1 col3]=(B1 B3)
psubd mm3,mm6 ; mm3=data1[col5 col7]=(B5 B7)
paddd mm1,mm7
psrad mm1,DESCALE_P1_2
paddd mm2,mm7
paddd mm5,mm7
psrad mm2,DESCALE_P1_2
psrad mm5,DESCALE_P1_2
paddd mm4,mm7
paddd mm3,mm7
psrad mm4,DESCALE_P1_2
psrad mm3,DESCALE_P1_2
; ---- Pass 2: process rows, store into output array.
mov edi, JSAMPARRAY [output_buf(ebp)] ; (JSAMPROW *)
mov eax, JDIMENSION [output_col(ebp)]
; | input:| result:|
; | A0 B0 | |
; | A1 B1 | C0 C1 |
; | A3 B3 | D0 D1 |
; | A5 B5 | |
; | A7 B7 | |
; -- Odd part
packssdw mm2,mm4 ; mm2=(A1 A3 B1 B3)
packssdw mm5,mm3 ; mm5=(A5 A7 B5 B7)
pmaddwd mm2,[GOTOFF(ebx,PW_F362_MF127)]
pmaddwd mm5,[GOTOFF(ebx,PW_F085_MF072)]
paddd mm2,mm5 ; mm2=tmp0[row0 row1]
; -- Even part
pslld mm1,(CONST_BITS+2) ; mm1=tmp10[row0 row1]
; -- Final output stage
movq mm0,[GOTOFF(ebx,PD_DESCALE_P2_2)] ; mm0=[PD_DESCALE_P2_2]
movq mm6,mm1
paddd mm1,mm2 ; mm1=data0[row0 row1]=(C0 C1)
psubd mm6,mm2 ; mm6=data1[row0 row1]=(D0 D1)
paddd mm1,mm0
paddd mm6,mm0
psrad mm1,DESCALE_P2_2
psrad mm6,DESCALE_P2_2
movq mm7,mm1 ; transpose coefficients
punpckldq mm1,mm6 ; mm1=(C0 D0)
punpckhdq mm7,mm6 ; mm7=(C1 D1)
packssdw mm1,mm7 ; mm1=(C0 D0 C1 D1)
packsswb mm1,mm1 ; mm1=(C0 D0 C1 D1 C0 D0 C1 D1)
paddb mm1,[GOTOFF(ebx,PB_CENTERJSAMP)]
movd ecx,mm1
movd ebx,mm1 ; ebx=(C0 D0 C1 D1)
shr ecx,2*BYTE_BIT ; ecx=(C1 D1 -- --)
mov edx, JSAMPROW [edi+0*SIZEOF_JSAMPROW]
mov esi, JSAMPROW [edi+1*SIZEOF_JSAMPROW]
mov WORD [edx+eax*SIZEOF_JSAMPLE], bx
mov WORD [esi+eax*SIZEOF_JSAMPLE], cx
emms ; empty MMX state
pop edi
pop esi
; pop edx ; need not be preserved
; pop ecx ; need not be preserved
pop ebx
pop ebp
ret
; For some reason, the OS X linker does not honor the request to align the
; segment unless we do this.
align 16
|
org $5200
import '../lib/barden_fill.asm'
import 'dist_to_hh.asm'
import 'screen.asm'
import 'step_dist.asm'
import 'timer.asm'
; _ _ _ _ _____
;| | | | | | | | |_ _|
;| |_| | __ _ _ _ _ __ | |_ ___ __| | | | _____ _____ _ __
;| _ |/ _` | | | | '_ \| __/ _ \/ _` | | |/ _ \ \ /\ / / _ \ '__|
;| | | | (_| | |_| | | | | || __/ (_| | | | (_) \ V V / __/ |
;\_| |_/\__,_|\__,_|_| |_|\__\___|\__,_| \_/\___/ \_/\_/ \___|_|
;
stack_space defs 100
stack equ $-1
; We express the player's direction (or angle) using a circle with
; 128 divisions: [0,128). One "unit" in our scheme is ~2.8125 degrees.
; 0
; - | -
; |
; 96 -----+----- 32
; |
; - | -
; 64
player_dir defb 0
cast_dir defb 0
; The player's location in world units.
player_x defb 8
player_y defb 8
main:
ld sp,stack
setup_timer
prep_screen:
; Clear the graphics buffer
ld d,$00
ld hl,gb
ld bc,gb_size
call barden_fill
; Clear the back buffer
ld d,$80
ld hl,bb
ld bc,bb_size
call barden_fill
; Clear the screen
ld d,$80
ld hl,screen
ld bc,row*16
call barden_fill
ld a,'>'
ld (screen+row*3),a
; Frame the raycasting window on the screen.
ld ix,window-row-1
ld iy,window-row-1+row*(window_height+1)
ld b,window_width+2
hline_loop:
ld (ix),$b0 ; top horizontal line
ld (iy),$83 ; bottom horizontal line
inc ix
inc iy
djnz hline_loop
ld ix,window-1
ld iy,window-1+window_width+1
ld de,row
ld b,window_height
vline_loop:
ld (ix),$bb ; left vertical line
ld (iy),$b7 ; right vertical line
add ix,de
add iy,de
djnz vline_loop
; ---------------------
; ----- GAME LOOP -----
; ---------------------
game_loop:
draw_gb_to_bb
await_vblank
draw_bb_to_screen
jp game_loop
end main
|
stack
push 1
push 2
stack
push 3
stack
pop
stack
push 5
stack
pop
pop
push 6
stack
pop
pop
stack
|
@loop1
mov r2, 0
@loop2
mov r3, r1
band r3, r2
cge r3, 1
mov r3, .*
cmov r3, 32
out r3
clt r2, 63
cadd r2, 1
cjn %loop2
out 10
clt r1, 63
cadd r1, 1
cjn %loop1
|
; A336627: Coordination sequence for the Manhattan lattice.
; 1,2,4,8,11,16,20,24,28,32,36,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,100,104,108,112,116,120,124,128,132,136,140,144,148,152,156,160,164,168,172,176,180,184,188,192,196,200,204,208,212,216,220,224
mov $2,$0
sub $0,1
lpb $2
add $0,$2
mov $1,$0
add $0,2
trn $2,2
mul $2,2
add $1,$2
cmp $2,4
lpe
mov $0,$1
add $0,1
|
; A244049: Sum of all proper divisors of all positive integers <= n.
; 0,0,0,2,2,7,7,13,16,23,23,38,38,47,55,69,69,89,89,110,120,133,133,168,173,188,200,227,227,268,268,298,312,331,343,397,397,418,434,483,483,536,536,575,607,632,632,707,714,756,776,821,821,886,902
lpb $0,1
add $3,1
lpb $2,1
add $1,$3
trn $2,$3
lpe
trn $0,2
mov $2,$0
lpe
|
#include "lib.h"
//## BUG: ALL THE *_obj_mem_size RETURN A 64-BIT INTEGER, BUT
//## I THINK THEY'RE DOING THEIR CALCULATION IN 32-BIT ARITHMETIC
uint64 seq_obj_mem_size(uint64 capacity) {
assert(capacity > 0);
return sizeof(SEQ_OBJ) + (capacity - 1) * sizeof(OBJ);
}
uint64 uint8_seq_obj_mem_size(uint64 capacity) {
assert(capacity > 0);
return sizeof(SEQ_OBJ) - sizeof(OBJ) + capacity * sizeof(uint8);
}
uint64 int8_seq_obj_mem_size(uint64 capacity) {
assert(capacity > 0);
return sizeof(SEQ_OBJ) - sizeof(OBJ) + capacity * sizeof(int8);
}
uint64 int16_seq_obj_mem_size(uint64 capacity) {
assert(capacity > 0);
return sizeof(SEQ_OBJ) - sizeof(OBJ) + capacity * sizeof(int16);
}
uint64 int32_seq_obj_mem_size(uint64 capacity) {
assert(capacity > 0);
return sizeof(SEQ_OBJ) - sizeof(OBJ) + capacity * sizeof(int32);
}
uint64 int64_seq_obj_mem_size(uint64 capacity) {
assert(capacity > 0);
return sizeof(SEQ_OBJ) - sizeof(OBJ) + capacity * sizeof(int64);
}
uint64 set_obj_mem_size(uint64 size) {
assert(size > 0);
return sizeof(SET_OBJ) + (size - 1) * sizeof(OBJ);
}
uint64 tree_set_node_mem_size() {
return sizeof(TREE_SET_NODE);
}
uint64 mixed_repr_set_mem_size() {
return sizeof(MIXED_REPR_SET_OBJ);
}
uint64 tree_map_node_mem_size() {
return sizeof(TREE_MAP_NODE);
}
uint64 mixed_repr_map_mem_size() {
return sizeof(MIXED_REPR_MAP_OBJ);
}
uint64 bin_rel_obj_mem_size(uint64 size) {
assert(size > 0);
//## IF THE MAP HAS ONLY ONE ENTRY, THERE WOULD BE NO NEED FOR THE RIGHT-TO-LEFT INDEX
//## IT COULD PROBABLY ALSO BE ELIMINATED FOR VERY SMALL SIZES
return sizeof(BIN_REL_OBJ) + (2 * size - 1) * sizeof(OBJ) + size * sizeof(uint32);
}
uint64 tern_rel_obj_mem_size(uint64 size) {
assert(size > 0);
return sizeof(TERN_REL_OBJ) + (3 * size - 1) * sizeof(OBJ) + 2 * size * sizeof(uint32);
}
uint64 map_obj_mem_size(uint64 size) {
assert(size > 0);
return bin_rel_obj_mem_size(size);
}
uint64 boxed_obj_mem_size() {
return sizeof(BOXED_OBJ);
}
////////////////////////////////////////////////////////////////////////////////
OBJ *get_left_col_array_ptr(BIN_REL_OBJ *rel) {
return rel->buffer;
}
OBJ *get_right_col_array_ptr(BIN_REL_OBJ *rel, uint32 size) {
return rel->buffer + size;
}
uint32 *get_right_to_left_indexes(BIN_REL_OBJ *rel, uint32 size) {
return (uint32 *) (rel->buffer + 2 * size);
}
////////////////////////////////////////////////////////////////////////////////
OBJ *get_col_array_ptr(TERN_REL_OBJ *rel, uint32 size, int idx) {
assert(idx >= 0 & idx <= 2);
return rel->buffer + idx * size;
}
uint32 *get_rotated_index(TERN_REL_OBJ *rel, uint32 size, int amount) {
assert(amount == 1 | amount == 2);
uint32 *base_ptr = (uint32 *) (rel->buffer + 3 * size);
return base_ptr + (amount-1) * size;
}
////////////////////////////////////////////////////////////////////////////////
uint32 seq_capacity(uint64 byte_size) {
return (byte_size - sizeof(SEQ_OBJ)) / sizeof(OBJ) + 1;
}
////////////////////////////////////////////////////////////////////////////////
SEQ_OBJ *new_obj_seq(uint32 length) {
assert(length > 0);
SEQ_OBJ *seq = (SEQ_OBJ *) new_obj(seq_obj_mem_size(length));
seq->capacity = length;
seq->used = length;
return seq;
}
SEQ_OBJ *new_obj_seq(uint32 length, uint32 capacity) {
assert(length > 0 & capacity >= length);
assert(length < 32 | 2 * length >= capacity);
SEQ_OBJ *seq = (SEQ_OBJ *) new_obj(seq_obj_mem_size(capacity));
seq->capacity = capacity;
seq->used = length;
return seq;
}
SEQ_OBJ *new_float_seq(uint32 length) {
assert(length > 0);
SEQ_OBJ *seq = (SEQ_OBJ *) new_obj(seq_obj_mem_size(length));
seq->capacity = length;
seq->used = length;
return seq;
}
SEQ_OBJ *new_float_seq(uint32 length, uint32 capacity) {
assert(length > 0 & capacity >= length);
assert(length < 32 | 2 * length >= capacity);
SEQ_OBJ *seq = (SEQ_OBJ *) new_obj(seq_obj_mem_size(capacity));
seq->capacity = capacity;
seq->used = length;
return seq;
}
SEQ_OBJ *new_uint8_seq(uint32 length) {
return new_uint8_seq(length, (length + 7) & ~7);
}
SEQ_OBJ *new_uint8_seq(uint32 length, uint32 capacity) {
assert(length > 0);
assert(capacity >= length);
assert(capacity % 8 == 0);
assert(length < 32 | 2 * length >= capacity);
SEQ_OBJ *seq = (SEQ_OBJ *) new_obj(uint8_seq_obj_mem_size(capacity));
seq->capacity = capacity;
seq->used = length;
return seq;
}
SEQ_OBJ *new_int8_seq(uint32 length) {
return new_int8_seq(length, (length + 3) & ~3);
}
SEQ_OBJ *new_int8_seq(uint32 length, uint32 capacity) {
assert(length > 0 & capacity >= length);
assert(capacity % 8 == 0);
assert(length < 32 | 2 * length >= capacity);
SEQ_OBJ *seq = (SEQ_OBJ *) new_obj(int8_seq_obj_mem_size(capacity));
seq->capacity = capacity;
seq->used = length;
return seq;
}
SEQ_OBJ *new_int16_seq(uint32 length) {
return new_int16_seq(length, (length + 3) & ~3);
}
SEQ_OBJ *new_int16_seq(uint32 length, uint32 capacity) {
assert(length > 0 & capacity >= length);
assert(capacity % 4 == 0);
assert(length < 32 | 2 * length >= capacity);
SEQ_OBJ *seq = (SEQ_OBJ *) new_obj(int16_seq_obj_mem_size(capacity));
seq->capacity = capacity;
seq->used = length;
return seq;
}
SEQ_OBJ *new_int32_seq(uint32 length) {
return new_int32_seq(length, (length + 3) & ~3);
}
SEQ_OBJ *new_int32_seq(uint32 length, uint32 capacity) {
assert(length > 0 & capacity >= length);
assert(capacity % 2 == 0);
assert(length < 32 | 2 * length >= capacity);
SEQ_OBJ *seq = (SEQ_OBJ *) new_obj(int32_seq_obj_mem_size(capacity));
seq->capacity = capacity;
seq->used = length;
return seq;
}
SEQ_OBJ *new_int64_seq(uint32 length) {
return new_int64_seq(length, (length + 3) & ~3);
}
SEQ_OBJ *new_int64_seq(uint32 length, uint32 capacity) {
assert(length > 0 & capacity >= length);
assert(length < 32 | 2 * length >= capacity);
SEQ_OBJ *seq = (SEQ_OBJ *) new_obj(int64_seq_obj_mem_size(capacity));
seq->capacity = capacity;
seq->used = length;
return seq;
}
SET_OBJ *new_set(uint32 size) {
return (SET_OBJ *) new_obj(set_obj_mem_size(size));
}
TREE_SET_NODE *new_tree_set_node() {
return (TREE_SET_NODE *) new_obj(tree_set_node_mem_size());
}
MIXED_REPR_SET_OBJ *new_mixed_repr_set() {
return (MIXED_REPR_SET_OBJ *) new_obj(mixed_repr_set_mem_size());
}
BIN_REL_OBJ *new_map(uint32 size) {
assert(size > 0);
BIN_REL_OBJ *map = (BIN_REL_OBJ *) new_obj(map_obj_mem_size(size));
uint32 *rev_idxs = get_right_to_left_indexes(map, size);
// By setting the first two elements of the right-to-left index
// to the same value, we mark the index as not yet built
rev_idxs[0] = 0;
if (size > 1)
rev_idxs[1] = 0;
return map;
}
TREE_MAP_NODE *new_tree_map_node() {
return (TREE_MAP_NODE *) new_obj(tree_map_node_mem_size());
}
MIXED_REPR_MAP_OBJ *new_mixed_repr_map() {
return (MIXED_REPR_MAP_OBJ *) new_obj(mixed_repr_map_mem_size());
}
BIN_REL_OBJ *new_bin_rel(uint32 size) {
assert(size > 0);
return (BIN_REL_OBJ *) new_obj(bin_rel_obj_mem_size(size));
}
TERN_REL_OBJ *new_tern_rel(uint32 size) {
assert(size > 0);
return (TERN_REL_OBJ *) new_obj(tern_rel_obj_mem_size(size));
}
BOXED_OBJ *new_boxed_obj() {
BOXED_OBJ *tag_obj = (BOXED_OBJ *) new_obj(boxed_obj_mem_size());
return tag_obj;
}
////////////////////////////////////////////////////////////////////////////////
static uint64 total_count_new_obj_array = 0;
static uint64 total_count_new_bool_array = 0;
static uint64 total_count_new_double_array = 0;
static uint64 total_count_new_int64_array = 0;
static uint64 total_count_new_uint64_array = 0;
static uint64 total_count_new_int32_array = 0;
static uint64 total_count_new_uint32_array = 0;
static uint64 total_count_new_int16_array = 0;
static uint64 total_count_new_uint16_array = 0;
static uint64 total_count_new_int8_array = 0;
static uint64 total_count_new_uint8_array = 0;
void print_temp_mem_alloc_stats() {
printf("Temporary allocation details:\n");
printf(" new_obj_array: %llu\n", total_count_new_obj_array);
printf(" new_bool_array: %llu\n", total_count_new_bool_array);
printf(" new_double_array: %llu\n", total_count_new_double_array);
printf(" new_int64_array: %llu\n", total_count_new_int64_array);
printf(" new_uint64_array: %llu\n", total_count_new_uint64_array);
printf(" new_int32_array: %llu\n", total_count_new_int32_array);
printf(" new_uint32_array: %llu\n", total_count_new_uint32_array);
printf(" new_int16_array: %llu\n", total_count_new_int16_array);
printf(" new_uint16_array: %llu\n", total_count_new_uint16_array);
printf(" new_int8_array: %llu\n", total_count_new_int8_array);
printf(" new_uint8_array: %llu\n", total_count_new_uint8_array);
}
OBJ *new_obj_array(uint32 size) {
total_count_new_obj_array += size * sizeof(OBJ);
return (OBJ *) new_obj(size * sizeof(OBJ));
}
bool *new_bool_array(uint32 size) {
total_count_new_bool_array += size * sizeof(bool);
return (bool *) new_obj(size * sizeof(bool));
}
double *new_float_array(uint32 size) {
total_count_new_double_array += size * sizeof(double);
return (double *) new_obj(size * sizeof(double));
}
int64 *new_int64_array(uint32 size) {
total_count_new_int64_array += size * sizeof(int64);
return (int64 *) new_obj(size * sizeof(int64));
}
uint64 *new_uint64_array(uint32 size) {
total_count_new_uint64_array += size * sizeof(uint64);
return (uint64 *) new_obj(size * sizeof(uint64));
}
int32 *new_int32_array(uint32 size) {
total_count_new_int32_array += size * sizeof(int32);
return (int32 *) new_obj(size * sizeof(int32));
}
uint32 *new_uint32_array(uint32 size) {
total_count_new_uint32_array += size * sizeof(uint32);
return (uint32 *) new_obj(size * sizeof(uint32));
}
int16 *new_int16_array(uint32 size) {
total_count_new_int16_array += size * sizeof(int16);
return (int16 *) new_obj(size * sizeof(int16));
}
uint16 *new_uint16_array(uint32 size) {
total_count_new_uint16_array += size * sizeof(uint16);
return (uint16 *) new_obj(size * sizeof(uint16));
}
int8 *new_int8_array(uint32 size) {
total_count_new_int8_array += size * sizeof(int8);
return (int8 *) new_obj(size * sizeof(int8));
}
uint8 *new_uint8_array(uint32 size) {
total_count_new_uint8_array += size * sizeof(uint8);
return (uint8 *) new_obj(size * sizeof(uint8));
}
////////////////////////////////////////////////////////////////////////////////
char *new_byte_array(uint32 size) {
return (char *) new_obj(size);
}
void *new_void_array(uint32 size) {
return new_obj(size);
}
////////////////////////////////////////////////////////////////////////////////
OBJ *resize_obj_array(OBJ* array, uint32 size, uint32 new_size) {
assert(new_size > size);
OBJ *new_array = new_obj_array(new_size);
memcpy(new_array, array, size * sizeof(OBJ));
return new_array;
}
double *resize_float_array(double* array, uint32 size, uint32 new_size) {
assert(new_size > size);
double *new_array = new_float_array(new_size);
memcpy(new_array, array, size * sizeof(double));
return new_array;
}
uint64 *resize_uint64_array(uint64 *array, uint32 size, uint32 new_size) {
assert(new_size > size);
uint64 *new_array = new_uint64_array(new_size);
memcpy(new_array, array, size * sizeof(uint64));
return new_array;
}
int64 *resize_int64_array(int64 *array, uint32 size, uint32 new_size) {
assert(new_size > size);
int64 *new_array = new_int64_array(new_size);
memcpy(new_array, array, size * sizeof(int64));
return new_array;
}
uint32 *resize_uint32_array(uint32 *array, uint32 size, uint32 new_size) {
assert(new_size > size);
uint32 *new_array = new_uint32_array(new_size);
memcpy(new_array, array, size * sizeof(uint32));
return new_array;
}
|
GLOBAL _cli
GLOBAL _sti
GLOBAL picMasterMask
GLOBAL picSlaveMask
GLOBAL haltcpu
GLOBAL _hlt
GLOBAL _exception0Handler
GLOBAL _exception6Handler
GLOBAL _irq00Handler
GLOBAL _irq01Handler
GLOBAL _irq02Handler
GLOBAL _irq03Handler
GLOBAL _irq04Handler
GLOBAL _irq05Handler
GLOBAL getStackPointer
GLOBAL _syscallHandler
GLOBAL instructionPointerBackup
GLOBAL stackPointerBackup
EXTERN exceptionDispatcher
EXTERN irqDispatcher
EXTERN syscallDispatcher
EXTERN main
SECTION .text
%macro pushState 0
push rax
push rbx
push rcx
push rdx
push rbp
push rdi
push rsi
push r8
push r9
push r10
push r11
push r12
push r13
push r14
push r15
%endmacro
%macro popState 0
pop r15
pop r14
pop r13
pop r12
pop r11
pop r10
pop r9
pop r8
pop rsi
pop rdi
pop rbp
pop rdx
pop rcx
pop rbx
pop rax
%endmacro
%macro irqHandlerMaster 1
pushState
mov rdi, %1 ; pasaje de parametro
call irqDispatcher
; signal pic EOI (End of Interrupt)
mov al, 20h
out 20h, al
popState
iretq
%endmacro
%macro exceptionHandler 1
mov rsi,[rsp] ; dirección donde ocurrió la excepción.
pushState
mov rdi, %1 ; pasaje de parametro
mov rdx, rsp; pointer al stack donde estan pusheados los registros.
call exceptionDispatcher
popState
mov rdi, [instructionPointerBackup]
mov qword [rsp], rdi; dirección del sampleCodeModule para retornar de vuelta.
mov rdi, [stackPointerBackup]
mov qword[rsp + 3*8], rdi
iretq
%endmacro
_hlt:
sti
hlt
ret
_cli:
cli
ret
_sti:
sti
ret
picMasterMask:
push rbp
mov rbp, rsp
mov ax, di
out 21h,al
pop rbp
retn
picSlaveMask:
push rbp
mov rbp, rsp
mov ax, di ; ax = mascara de 16 bits
out 0A1h,al
pop rbp
retn
;División por cero
_exception0Handler:
exceptionHandler 0
;Instrucción inválida
_exception6Handler:
exceptionHandler 6
;8254 Timer (Timer Tick)
_irq00Handler:
irqHandlerMaster 0
;Keyboard
_irq01Handler:
irqHandlerMaster 1
;Cascade pic never called
_irq02Handler:
irqHandlerMaster 2
;Serial Port 2 and 4
_irq03Handler:
irqHandlerMaster 3
;Serial Port 1 and 3
_irq04Handler:
irqHandlerMaster 4
;USB
_irq05Handler:
irqHandlerMaster 5
_syscallHandler:
push rbp
mov rbp, rsp
push r8
push rdx
push rsi
push rdi
mov rdi, rax
pop rsi
pop rdx
pop rcx
mov r8, r10
pop r9
call syscallDispatcher
leave
iretq
haltcpu:
cli
hlt
ret
getStackPointer:
mov rax, rsp
ret
SECTION .bss
sampleCodeModule equ 0x400000
stackPointerBackup resq 1
instructionPointerBackup resq 1
|
SECTION code_sound_bit
PUBLIC _bitfx_4
INCLUDE "clib_target_cfg.asm"
_bitfx_4:
; Our old squelch...
ld b,0
zap1_1:
push bc
xor __sound_bit_toggle
INCLUDE "sound/bit/z80/output_bit_device_2.inc"
zap1_2:
nop
nop
djnz zap1_2
pop bc
djnz zap1_1
ret
|
#include <nano/lib/jsonconfig.hpp>
#include <nano/node/vote_processor.hpp>
#include <nano/test_common/system.hpp>
#include <nano/test_common/testutil.hpp>
#include <gtest/gtest.h>
using namespace std::chrono_literals;
TEST (vote_processor, codes)
{
nano::system system (1);
auto & node (*system.nodes[0]);
nano::keypair key;
auto vote (std::make_shared<nano::vote> (key.pub, key.prv, nano::vote::timestamp_min * 1, 0, std::vector<nano::block_hash>{ nano::dev::genesis->hash () }));
auto vote_invalid = std::make_shared<nano::vote> (*vote);
vote_invalid->signature.bytes[0] ^= 1;
auto channel (std::make_shared<nano::transport::channel_loopback> (node));
// Invalid signature
ASSERT_EQ (nano::vote_code::invalid, node.vote_processor.vote_blocking (vote_invalid, channel, false));
// Hint of pre-validation
ASSERT_NE (nano::vote_code::invalid, node.vote_processor.vote_blocking (vote_invalid, channel, true));
// No ongoing election
ASSERT_EQ (nano::vote_code::indeterminate, node.vote_processor.vote_blocking (vote, channel));
// First vote from an account for an ongoing election
node.block_confirm (nano::dev::genesis);
ASSERT_NE (nullptr, node.active.election (nano::dev::genesis->qualified_root ()));
ASSERT_EQ (nano::vote_code::vote, node.vote_processor.vote_blocking (vote, channel));
// Processing the same vote is a replay
ASSERT_EQ (nano::vote_code::replay, node.vote_processor.vote_blocking (vote, channel));
// Invalid takes precedence
ASSERT_EQ (nano::vote_code::invalid, node.vote_processor.vote_blocking (vote_invalid, channel));
// Once the election is removed (confirmed / dropped) the vote is again indeterminate
node.active.erase (*nano::dev::genesis);
ASSERT_EQ (nano::vote_code::indeterminate, node.vote_processor.vote_blocking (vote, channel));
}
TEST (vote_processor, flush)
{
nano::system system (1);
auto & node (*system.nodes[0]);
auto channel (std::make_shared<nano::transport::channel_loopback> (node));
for (unsigned i = 0; i < 2000; ++i)
{
auto vote = std::make_shared<nano::vote> (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::vote::timestamp_min * (1 + i), 0, std::vector<nano::block_hash>{ nano::dev::genesis->hash () });
node.vote_processor.vote (vote, channel);
}
node.vote_processor.flush ();
ASSERT_TRUE (node.vote_processor.empty ());
}
TEST (vote_processor, invalid_signature)
{
nano::system system{ 1 };
auto & node = *system.nodes[0];
nano::keypair key;
auto vote = std::make_shared<nano::vote> (key.pub, key.prv, nano::vote::timestamp_min * 1, 0, std::vector<nano::block_hash>{ nano::dev::genesis->hash () });
auto vote_invalid = std::make_shared<nano::vote> (*vote);
vote_invalid->signature.bytes[0] ^= 1;
auto channel = std::make_shared<nano::transport::channel_loopback> (node);
node.block_confirm (nano::dev::genesis);
auto election = node.active.election (nano::dev::genesis->qualified_root ());
ASSERT_TRUE (election);
ASSERT_EQ (1, election->votes ().size ());
node.vote_processor.vote (vote_invalid, channel);
node.vote_processor.flush ();
ASSERT_EQ (1, election->votes ().size ());
node.vote_processor.vote (vote, channel);
node.vote_processor.flush ();
ASSERT_EQ (2, election->votes ().size ());
}
TEST (vote_processor, no_capacity)
{
nano::system system;
nano::node_flags node_flags;
node_flags.vote_processor_capacity = 0;
auto & node (*system.add_node (node_flags));
nano::keypair key;
auto vote (std::make_shared<nano::vote> (key.pub, key.prv, nano::vote::timestamp_min * 1, 0, std::vector<nano::block_hash>{ nano::dev::genesis->hash () }));
auto channel (std::make_shared<nano::transport::channel_loopback> (node));
ASSERT_TRUE (node.vote_processor.vote (vote, channel));
}
TEST (vote_processor, overflow)
{
nano::system system;
nano::node_flags node_flags;
node_flags.vote_processor_capacity = 1;
auto & node (*system.add_node (node_flags));
nano::keypair key;
auto vote (std::make_shared<nano::vote> (key.pub, key.prv, nano::vote::timestamp_min * 1, 0, std::vector<nano::block_hash>{ nano::dev::genesis->hash () }));
auto channel (std::make_shared<nano::transport::channel_loopback> (node));
// No way to lock the processor, but queueing votes in quick succession must result in overflow
size_t not_processed{ 0 };
size_t const total{ 1000 };
for (unsigned i = 0; i < total; ++i)
{
if (node.vote_processor.vote (vote, channel))
{
++not_processed;
}
}
ASSERT_GT (not_processed, 0);
ASSERT_LT (not_processed, total);
ASSERT_EQ (not_processed, node.stats.count (nano::stat::type::vote, nano::stat::detail::vote_overflow));
}
namespace nano
{
TEST (vote_processor, weights)
{
nano::system system (4);
auto & node (*system.nodes[0]);
// Create representatives of different weight levels
// The online stake will be the minimum configurable due to online_reps sampling in tests
auto const online = node.config.online_weight_minimum.number ();
auto const level0 = online / 5000; // 0.02%
auto const level1 = online / 500; // 0.2%
auto const level2 = online / 50; // 2%
nano::keypair key0;
nano::keypair key1;
nano::keypair key2;
system.wallet (0)->insert_adhoc (nano::dev::genesis_key.prv);
system.wallet (1)->insert_adhoc (key0.prv);
system.wallet (2)->insert_adhoc (key1.prv);
system.wallet (3)->insert_adhoc (key2.prv);
system.wallet (1)->store.representative_set (system.nodes[1]->wallets.tx_begin_write (), key0.pub);
system.wallet (2)->store.representative_set (system.nodes[2]->wallets.tx_begin_write (), key1.pub);
system.wallet (3)->store.representative_set (system.nodes[3]->wallets.tx_begin_write (), key2.pub);
system.wallet (0)->send_sync (nano::dev::genesis_key.pub, key0.pub, level0);
system.wallet (0)->send_sync (nano::dev::genesis_key.pub, key1.pub, level1);
system.wallet (0)->send_sync (nano::dev::genesis_key.pub, key2.pub, level2);
// Wait for representatives
ASSERT_TIMELY (10s, node.ledger.cache.rep_weights.get_rep_amounts ().size () == 4);
node.vote_processor.calculate_weights ();
ASSERT_EQ (node.vote_processor.representatives_1.end (), node.vote_processor.representatives_1.find (key0.pub));
ASSERT_EQ (node.vote_processor.representatives_2.end (), node.vote_processor.representatives_2.find (key0.pub));
ASSERT_EQ (node.vote_processor.representatives_3.end (), node.vote_processor.representatives_3.find (key0.pub));
ASSERT_NE (node.vote_processor.representatives_1.end (), node.vote_processor.representatives_1.find (key1.pub));
ASSERT_EQ (node.vote_processor.representatives_2.end (), node.vote_processor.representatives_2.find (key1.pub));
ASSERT_EQ (node.vote_processor.representatives_3.end (), node.vote_processor.representatives_3.find (key1.pub));
ASSERT_NE (node.vote_processor.representatives_1.end (), node.vote_processor.representatives_1.find (key2.pub));
ASSERT_NE (node.vote_processor.representatives_2.end (), node.vote_processor.representatives_2.find (key2.pub));
ASSERT_EQ (node.vote_processor.representatives_3.end (), node.vote_processor.representatives_3.find (key2.pub));
ASSERT_NE (node.vote_processor.representatives_1.end (), node.vote_processor.representatives_1.find (nano::dev::genesis_key.pub));
ASSERT_NE (node.vote_processor.representatives_2.end (), node.vote_processor.representatives_2.find (nano::dev::genesis_key.pub));
ASSERT_NE (node.vote_processor.representatives_3.end (), node.vote_processor.representatives_3.find (nano::dev::genesis_key.pub));
}
}
// Issue that tracks last changes on this test: https://github.com/nanocurrency/nano-node/issues/3485
// Reopen in case the nondeterministic failure appears again.
// Checks local votes (a vote with a key that is in the node's wallet) are not re-broadcast when received.
// Nodes should not relay their own votes
TEST (vote_processor, no_broadcast_local)
{
nano::system system;
nano::node_flags flags;
flags.disable_request_loop = true;
nano::node_config config1, config2;
config1.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled;
auto & node (*system.add_node (config1, flags));
config2.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled;
config2.peering_port = nano::get_available_port ();
system.add_node (config2, flags);
nano::block_builder builder;
std::error_code ec;
// Reduce the weight of genesis to 2x default min voting weight
nano::keypair key;
std::shared_ptr<nano::block> send = builder.state ()
.account (nano::dev::genesis_key.pub)
.representative (nano::dev::genesis_key.pub)
.previous (nano::dev::genesis->hash ())
.balance (2 * node.config.vote_minimum.number ())
.link (key.pub)
.sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub)
.work (*system.work.generate (nano::dev::genesis->hash ()))
.build (ec);
ASSERT_FALSE (ec);
ASSERT_EQ (nano::process_result::progress, node.process_local (send).code);
ASSERT_TIMELY (10s, !node.active.empty ());
ASSERT_EQ (2 * node.config.vote_minimum.number (), node.weight (nano::dev::genesis_key.pub));
// Insert account in wallet. Votes on node are not enabled.
system.wallet (0)->insert_adhoc (nano::dev::genesis_key.prv);
// Ensure that the node knows the genesis key in its wallet.
node.wallets.compute_reps ();
ASSERT_TRUE (node.wallets.reps ().exists (nano::dev::genesis_key.pub));
ASSERT_FALSE (node.wallets.reps ().have_half_rep ()); // Genesis balance remaining after `send' is less than the half_rep threshold
// Process a vote with a key that is in the local wallet.
auto vote = std::make_shared<nano::vote> (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::milliseconds_since_epoch (), nano::vote::duration_max, std::vector<nano::block_hash>{ send->hash () });
ASSERT_EQ (nano::vote_code::vote, node.active.vote (vote));
// Make sure the vote was processed.
auto election (node.active.election (send->qualified_root ()));
ASSERT_NE (nullptr, election);
auto votes (election->votes ());
auto existing (votes.find (nano::dev::genesis_key.pub));
ASSERT_NE (votes.end (), existing);
ASSERT_EQ (vote->timestamp (), existing->second.timestamp);
// Ensure the vote, from a local representative, was not broadcast on processing - it should be flooded on vote generation instead.
ASSERT_EQ (0, node.stats.count (nano::stat::type::message, nano::stat::detail::confirm_ack, nano::stat::dir::out));
ASSERT_EQ (1, node.stats.count (nano::stat::type::message, nano::stat::detail::publish, nano::stat::dir::out));
}
// Issue that tracks last changes on this test: https://github.com/nanocurrency/nano-node/issues/3485
// Reopen in case the nondeterministic failure appears again.
// Checks non-local votes (a vote with a key that is not in the node's wallet) are re-broadcast when received.
// Done without a representative.
TEST (vote_processor, local_broadcast_without_a_representative)
{
nano::system system;
nano::node_flags flags;
flags.disable_request_loop = true;
nano::node_config config1, config2;
config1.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled;
auto & node (*system.add_node (config1, flags));
config2.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled;
config2.peering_port = nano::get_available_port ();
system.add_node (config2, flags);
nano::block_builder builder;
std::error_code ec;
// Reduce the weight of genesis to 2x default min voting weight
nano::keypair key;
std::shared_ptr<nano::block> send = builder.state ()
.account (nano::dev::genesis_key.pub)
.representative (nano::dev::genesis_key.pub)
.previous (nano::dev::genesis->hash ())
.balance (node.config.vote_minimum.number ())
.link (key.pub)
.sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub)
.work (*system.work.generate (nano::dev::genesis->hash ()))
.build (ec);
ASSERT_FALSE (ec);
ASSERT_EQ (nano::process_result::progress, node.process_local (send).code);
ASSERT_TIMELY (10s, !node.active.empty ());
ASSERT_EQ (node.config.vote_minimum, node.weight (nano::dev::genesis_key.pub));
node.block_confirm (send);
// Process a vote without a representative
auto vote = std::make_shared<nano::vote> (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::milliseconds_since_epoch (), nano::vote::duration_max, std::vector<nano::block_hash>{ send->hash () });
ASSERT_EQ (nano::vote_code::vote, node.active.vote (vote));
// Make sure the vote was processed.
auto election (node.active.election (send->qualified_root ()));
ASSERT_NE (nullptr, election);
auto votes (election->votes ());
auto existing (votes.find (nano::dev::genesis_key.pub));
ASSERT_NE (votes.end (), existing);
ASSERT_EQ (vote->timestamp (), existing->second.timestamp);
// Ensure the vote was broadcast
ASSERT_EQ (1, node.stats.count (nano::stat::type::message, nano::stat::detail::confirm_ack, nano::stat::dir::out));
ASSERT_EQ (1, node.stats.count (nano::stat::type::message, nano::stat::detail::publish, nano::stat::dir::out));
}
// Issue that tracks last changes on this test: https://github.com/nanocurrency/nano-node/issues/3485
// Reopen in case the nondeterministic failure appears again.
// Checks local votes (a vote with a key that is in the node's wallet) are not re-broadcast when received.
// Done with a principal representative.
TEST (vote_processor, no_broadcast_local_with_a_principal_representative)
{
nano::system system;
nano::node_flags flags;
flags.disable_request_loop = true;
nano::node_config config1, config2;
config1.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled;
auto & node (*system.add_node (config1, flags));
config2.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled;
config2.peering_port = nano::get_available_port ();
system.add_node (config2, flags);
nano::block_builder builder;
std::error_code ec;
// Reduce the weight of genesis to 2x default min voting weight
nano::keypair key;
std::shared_ptr<nano::block> send = builder.state ()
.account (nano::dev::genesis_key.pub)
.representative (nano::dev::genesis_key.pub)
.previous (nano::dev::genesis->hash ())
.balance (nano::dev::constants.genesis_amount - 2 * node.config.vote_minimum.number ())
.link (key.pub)
.sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub)
.work (*system.work.generate (nano::dev::genesis->hash ()))
.build (ec);
ASSERT_FALSE (ec);
ASSERT_EQ (nano::process_result::progress, node.process_local (send).code);
ASSERT_TIMELY (10s, !node.active.empty ());
ASSERT_EQ (nano::dev::constants.genesis_amount - 2 * node.config.vote_minimum.number (), node.weight (nano::dev::genesis_key.pub));
// Insert account in wallet. Votes on node are not enabled.
system.wallet (0)->insert_adhoc (nano::dev::genesis_key.prv);
// Ensure that the node knows the genesis key in its wallet.
node.wallets.compute_reps ();
ASSERT_TRUE (node.wallets.reps ().exists (nano::dev::genesis_key.pub));
ASSERT_TRUE (node.wallets.reps ().have_half_rep ()); // Genesis balance after `send' is over both half_rep and PR threshold.
// Process a vote with a key that is in the local wallet.
auto vote = std::make_shared<nano::vote> (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::milliseconds_since_epoch (), nano::vote::duration_max, std::vector<nano::block_hash>{ send->hash () });
ASSERT_EQ (nano::vote_code::vote, node.active.vote (vote));
// Make sure the vote was processed.
auto election (node.active.election (send->qualified_root ()));
ASSERT_NE (nullptr, election);
auto votes (election->votes ());
auto existing (votes.find (nano::dev::genesis_key.pub));
ASSERT_NE (votes.end (), existing);
ASSERT_EQ (vote->timestamp (), existing->second.timestamp);
// Ensure the vote was not broadcast.
ASSERT_EQ (0, node.stats.count (nano::stat::type::message, nano::stat::detail::confirm_ack, nano::stat::dir::out));
ASSERT_EQ (1, node.stats.count (nano::stat::type::message, nano::stat::detail::publish, nano::stat::dir::out));
}
/**
* basic test to check that the timestamp mask is applied correctly on vote timestamp and duration fields
*/
TEST (vote, timestamp_and_duration_masking)
{
nano::system system;
nano::keypair key;
auto hash = std::vector<nano::block_hash>{ nano::dev::genesis->hash () };
auto vote = std::make_shared<nano::vote> (key.pub, key.prv, 0x123f, 0xf, hash);
ASSERT_EQ (vote->timestamp (), 0x1230);
ASSERT_EQ (vote->duration ().count (), 524288);
ASSERT_EQ (vote->duration_bits (), 0xf);
} |
; SPIR-V
; Version: 1.0
; Generator: Khronos Glslang Reference Front End; 10
; Bound: 90
; Schema: 0
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main" %13 %77
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 320
OpName %4 "main"
OpName %9 "ipos"
OpName %13 "gl_FragCoord"
OpName %19 "a"
OpName %46 "v"
OpName %50 "tex"
OpName %77 "_GLF_color"
OpName %85 "indexable"
OpDecorate %13 BuiltIn FragCoord
OpDecorate %50 RelaxedPrecision
OpDecorate %50 DescriptorSet 0
OpDecorate %50 Binding 0
OpDecorate %51 RelaxedPrecision
OpDecorate %54 RelaxedPrecision
OpDecorate %77 Location 0
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypeVector %6 2
%8 = OpTypePointer Function %7
%10 = OpTypeFloat 32
%11 = OpTypeVector %10 4
%12 = OpTypePointer Input %11
%13 = OpVariable %12 Input
%14 = OpTypeVector %10 2
%18 = OpTypePointer Function %6
%20 = OpTypeInt 32 0
%21 = OpConstant %20 0
%24 = OpConstant %6 5
%26 = OpConstant %20 1
%32 = OpConstant %6 10
%42 = OpConstant %6 3
%43 = OpTypeBool
%45 = OpTypePointer Function %11
%47 = OpTypeImage %10 2D 0 0 0 1 Unknown
%48 = OpTypeSampledImage %47
%49 = OpTypePointer UniformConstant %48
%50 = OpVariable %49 UniformConstant
%52 = OpConstant %10 1
%53 = OpConstantComposite %14 %52 %52
%60 = OpTypePointer Function %10
%63 = OpConstant %10 2
%65 = OpConstant %6 4
%69 = OpConstant %6 0
%76 = OpTypePointer Output %11
%77 = OpVariable %76 Output
%78 = OpConstant %20 4
%79 = OpTypeArray %11 %78
%80 = OpConstant %10 0
%81 = OpConstantComposite %11 %52 %80 %80 %52
%82 = OpConstantComposite %79 %81 %81 %81 %81
%84 = OpTypePointer Function %79
%89 = OpConstantComposite %11 %80 %80 %80 %80
%4 = OpFunction %2 None %3
%5 = OpLabel
%9 = OpVariable %8 Function
%19 = OpVariable %18 Function
%46 = OpVariable %45 Function
%85 = OpVariable %84 Function
%15 = OpLoad %11 %13
%16 = OpVectorShuffle %14 %15 %15 0 1
%17 = OpConvertFToS %7 %16
OpStore %9 %17
%22 = OpAccessChain %18 %9 %21
%23 = OpLoad %6 %22
%25 = OpBitwiseAnd %6 %23 %24
%27 = OpAccessChain %18 %9 %26
%28 = OpLoad %6 %27
%29 = OpBitwiseAnd %6 %28 %24
%30 = OpAccessChain %18 %9 %21
%31 = OpLoad %6 %30
%33 = OpBitwiseAnd %6 %31 %32
%34 = OpBitwiseOr %6 %29 %33
%35 = OpIAdd %6 %25 %34
OpStore %19 %35
OpBranch %36
%36 = OpLabel
OpLoopMerge %38 %39 None
OpBranch %40
%40 = OpLabel
%41 = OpLoad %6 %19
%44 = OpSGreaterThan %43 %41 %42
OpBranchConditional %44 %37 %38
%37 = OpLabel
%51 = OpLoad %48 %50
%54 = OpImageSampleImplicitLod %11 %51 %53
OpStore %46 %54
OpBranch %55
%55 = OpLabel
OpLoopMerge %57 %58 None
OpBranch %59
%59 = OpLabel
%61 = OpAccessChain %60 %46 %21
%62 = OpLoad %10 %61
%64 = OpFOrdGreaterThan %43 %62 %63
OpBranchConditional %64 %56 %57
%56 = OpLabel
OpBranch %58
%58 = OpLabel
OpBranch %55
%57 = OpLabel
%66 = OpLoad %6 %19
%67 = OpISub %6 %66 %65
OpStore %19 %67
OpBranch %39
%39 = OpLabel
OpBranch %36
%38 = OpLabel
%68 = OpLoad %6 %19
%70 = OpSGreaterThanEqual %43 %68 %69
%71 = OpLoad %6 %19
%72 = OpSLessThan %43 %71 %65
%73 = OpLogicalAnd %43 %70 %72
OpSelectionMerge %75 None
OpBranchConditional %73 %74 %88
%74 = OpLabel
%83 = OpLoad %6 %19
OpStore %85 %82
%86 = OpAccessChain %45 %85 %83
%87 = OpLoad %11 %86
OpStore %77 %87
OpBranch %75
%88 = OpLabel
OpStore %77 %89
OpBranch %75
%75 = OpLabel
OpReturn
OpFunctionEnd
|
; QXL_KBD.ASM Keyboard server and setup
; 2006.10.01 1.01 uses 32 bits transfer,"turn off typematic" function suppressed , optimised
qxl_kbd_setup:
ASSUME ds:DGROUP
ASSUME es:DGROUP
mov cx, OFFSET qxl_kbd_server
mov bp, OFFSET qxl_kbd_servend-4
mov si, OFFSET int_kbdi
call qxl_setvc ; set up server
; QXL reset keyboard
qxl_kbd_reset:
xor ax,ax
mov kbd_save,al
retn
qxl_kbd_server:
push ds
push es
push ax ; save accumulator
push bx
mov ax, DGROUP
mov ds,ax
mov es,ax
ASSUME ds:DGROUP
ASSUME es:DGROUP
call qld_wait_read
in al,kbd_data ; code from KBD
test al,al ; null?
jz qks_exit
cmp al,046h ; scroll lock?
jnz qks_send ; ... no
cmp kbd_save,01dh ; left control was last code?
jnz qks_send ; ... no
mov kbd_stop,-1 ; set stop flag
jmp qks_exit
qks_send:
mov kbd_save,al ; saved keystroke key
mov bx, OFFSET kbd_buff ; and put in buffer
call buff_pbyte
qks_exit:
mov al,pic_eof ; (end of interrupt)
out pic_ctrl,al
pop bx
pop ax
pop es
pop ds
iretf
jmp FAR PTR int_kbdi ; !!!!!
qxl_kbd_servend:
|
; A054489: Expansion of (1+4*x)/(1-6*x+x^2).
; 1,10,59,344,2005,11686,68111,396980,2313769,13485634,78600035,458114576,2670087421,15562409950,90704372279,528663823724,3081278570065,17959007596666,104672767009931,610077594462920,3555792799767589,20724679204142614,120792282425088095,704029015346385956,4103381809653227641,23916261842572979890,139394189245784651699,812448873632134930304,4735299052547024930125,27599345441650014650446,160860773597353062972551,937565296142468363184860,5464531003257457116136609,31849620723402274333634794,185633193337156188885672155,1081949539299534858980398136,6306064042460052964996716661,36754434715460782930999901830,214220544250304644621002694319,1248568830786367084795016264084,7277192440467897864149094890185,42414585812021020100099553077026,247210322431658222736448223571971,1440847348777928316318589788354800,8397873770235911675175090506556829,48946395272637541734731953250986174,285280497865589338733216628999360215
mov $1,4
mov $2,7
lpb $0
sub $0,1
add $1,$2
add $2,$1
add $2,$1
add $1,$2
lpe
div $1,4
mov $0,$1
|
SECTION code_fp_math16
PUBLIC ___uint2h_callee
PUBLIC _f16_u16_fastcall
EXTERN cm16_sdcc___uint2h_callee
EXTERN cm16_sdcc___uint2h_fastcall
defc ___uint2h_callee = cm16_sdcc___uint2h_callee
defc _f16_u16_fastcall = cm16_sdcc___uint2h_fastcall
|
; mem_file struct:
;
!set mem_file_struct_start = $00
; start ptr 2 bytes
!set mem_file_struct_current = mem_file_struct_start + ptr_sizeof
; current ptr 2 bytes
!set mem_file_struct_end = mem_file_struct_current + ptr_sizeof
; end ptr 2 bytes
!set mem_file_struct_length = mem_file_struct_current + ptr_sizeof
; length int 2 bytes
!set mem_file_struct_sizeof = mem_file_struct_length + int_sizeof
;!addr mem_io_zp = $fa
;!addr mem_io_zp2 = $f8
!set SEEK_SET = $00
!set SEEK_CUR = $01
!set SEEK_END = $80
!zone mem_open {
mem_open_ptr:
+reserve_ptr
mem_open_size:
+reserve_int
mem_open:
lda #<f
sta f_ptr
lda #>f
sta f_ptr + 1
ldy #$00
ldz #$02
lda mem_open_ptr
sta (f_ptr), y
sta (f_ptr), z
iny
inz
lda mem_open_ptr + 1
sta (f_ptr), y
sta (f_ptr), z
inz
lda mem_open_size
sta (f_ptr), z
inz
lda mem_open_size + 1
sta (f_ptr), z
rts
}
!zone mem_read {
mem_read_ptr:
+reserve_ptr
mem_read_size:
+reserve_int
;mem_read_stream:
; +reserve_ptr
mem_read_return:
+reserve_int
mem_read:
; At this time, this function returns a pointer directly inside the memory
; rather than a copy.
+copy_word_from_zp_offset f_ptr, .start, mem_file_struct_start
+copy_word_from_zp_y f_ptr, .current
+copy_word_from_zp_y f_ptr, .length
sec
lda .current
sbc .start
sta .max
lda .current + 1
sbc .start + 1
sta .max + 1
sec
lda .length
sbc .max
sta .max
lda .length + 1
sbc .max + 1
sta .max + 1
; lda mem_read_size + 1
; cmp .max + 1
; bmi +
; lda mem_read_size
; cmp .max
; bmi +
lda .max
sta mem_read_return
lda .max + 1
sta mem_read_return + 1
; bra ++
;+ lda mem_read_size
; sta mem_read_return
; lda mem_read_size + 1
; sta mem_read_return + 1
++
lda .current
sta mem_read_ptr
lda .current + 1
sta mem_read_ptr + 1
rts
.start:
+reserve_ptr
.current:
+reserve_ptr
.length:
+reserve_int
.max:
+reserve_int
}
!zone mem_seek {
;mem_seek_stream:
; +reserve_ptr
mem_seek_offset:
+reserve_int
mem_seek_whence:
+reserve_short
mem_seek_return:
+reserve_short
mem_seek:
;+set_zp mem_seek_stream, mem_io_zp
lda #SEEK_END
and mem_seek_whence
beq +
; Seek from the end - not supporting it at this time as libtremor
; shouldn't need it
lda #$80
sta mem_seek_return
rts
+ lda #SEEK_CUR
and mem_seek_whence
bne +
; Seek from start
ldy #$01
ldz #$03
- lda (f_ptr), y
sta (f_ptr), z
dez
dey
bpl -
; fall through
+ ; Seek from current
ldy #$02
clc
lda (f_ptr), y
adc mem_seek_offset
sta (f_ptr), y
iny
lda (f_ptr), y
adc mem_seek_offset + 1
sta (f_ptr), y
; no safeguard, at least at this time.
lda #$00
sta mem_seek_return
rts
}
!zone mem_close {
mem_close:
rts
}
!zone mem_tell {
mem_tell:
rts
}
|
#include <QApplication>
#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#if QT_VERSION >= 0x050000
#include <QUrlQuery>
#else
#include <QUrl>
#endif
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
// return if URI is not valid or is no bitcoin URI
if(!uri.isValid() || (uri.scheme() != QString("ditcoin") && uri.scheme() != QString("ditcoin")))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
#if QT_VERSION < 0x050000
QList<QPair<QString, QString> > items = uri.queryItems();
#else
QUrlQuery uriQuery(uri);
QList<QPair<QString, QString> > items = uriQuery.queryItems();
#endif
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("ditcoin://"))
{
uri.replace(0, 11, "ditcoin:");
}
if(uri.startsWith("ditcoin://"))
{
uri.replace(0, 9, "ditcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
#if QT_VERSION < 0x050000
QString escaped = Qt::escape(str);
#else
QString escaped = str.toHtmlEscaped();
#endif
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item (global clipboard)
QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard);
// Copy first item (global mouse selection for e.g. X11 - NOP on Windows)
QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection);
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != qApp->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "bitcoin.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=Bitcoin\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("Ditcoin-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" ditcoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage(HMM_BITCOIN_QT));
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("Ditcoin-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
|
/**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#pragma once
#include "thrift/compiler/test/fixtures/mcpp2-compare/gen-cpp2/ParamService.h"
#include <thrift/lib/cpp2/gen/service_tcc.h>
namespace some { namespace valid { namespace ns {
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_I16, int16_t*>> ParamService_void_ret_i16_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_i16_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_BYTE, int8_t*>, apache::thrift::FieldData<2, apache::thrift::protocol::T_I16, int16_t*>> ParamService_void_ret_byte_i16_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_byte_i16_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_MAP, ::std::map<::std::string, int64_t>*>> ParamService_void_ret_map_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_map_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_MAP, ::std::map<::std::string, int64_t>*>, apache::thrift::FieldData<3, apache::thrift::protocol::T_SET, ::std::set<::std::vector<::std::string>>*>> ParamService_void_ret_map_setlist_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_map_setlist_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_I32, ::some::valid::ns::simpleTypeDef*>> ParamService_void_ret_map_typedef_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_map_typedef_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_I32, ::some::valid::ns::MyEnumA*>> ParamService_void_ret_enum_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_enum_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_STRUCT, ::some::valid::ns::MyStruct*>> ParamService_void_ret_struct_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_struct_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_LIST, ::std::vector< ::some::valid::ns::ComplexUnion>*>> ParamService_void_ret_listunion_param_pargs;
typedef apache::thrift::ThriftPresult<true> ParamService_void_ret_listunion_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_I32, int32_t*>, apache::thrift::FieldData<3, apache::thrift::protocol::T_I64, int64_t*>> ParamService_bool_ret_i32_i64_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_BOOL, bool*>> ParamService_bool_ret_i32_i64_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_MAP, ::std::map<::std::string, int64_t>*>> ParamService_bool_ret_map_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_BOOL, bool*>> ParamService_bool_ret_map_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_STRUCT, ::some::valid::ns::ComplexUnion*>> ParamService_bool_ret_union_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_BOOL, bool*>> ParamService_bool_ret_union_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_FLOAT, float*>, apache::thrift::FieldData<3, apache::thrift::protocol::T_DOUBLE, double*>> ParamService_i64_ret_float_double_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_I64, int64_t*>> ParamService_i64_ret_float_double_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_STRING, ::std::string*>, apache::thrift::FieldData<3, apache::thrift::protocol::T_SET, ::std::set< ::some::valid::ns::mostComplexTypeDef>*>> ParamService_i64_ret_string_typedef_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_I64, int64_t*>> ParamService_i64_ret_string_typedef_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_I32, int32_t*>, apache::thrift::FieldData<2, apache::thrift::protocol::T_I32, int32_t*>, apache::thrift::FieldData<3, apache::thrift::protocol::T_I32, int32_t*>, apache::thrift::FieldData<4, apache::thrift::protocol::T_I32, int32_t*>, apache::thrift::FieldData<5, apache::thrift::protocol::T_I32, int32_t*>> ParamService_i64_ret_i32_i32_i32_i32_i32_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_I64, int64_t*>> ParamService_i64_ret_i32_i32_i32_i32_i32_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<4, apache::thrift::protocol::T_SET, ::std::set< ::some::valid::ns::MyStruct>*>> ParamService_double_ret_setstruct_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_DOUBLE, double*>> ParamService_double_ret_setstruct_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_STRING, ::std::string*>> ParamService_string_ret_string_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_STRING, ::std::string*>> ParamService_string_ret_string_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_STRING, ::std::string*>> ParamService_binary_ret_binary_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_STRING, ::std::string*>> ParamService_binary_ret_binary_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_BOOL, bool*>> ParamService_map_ret_bool_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_MAP, ::std::map<::std::string, int64_t>*>> ParamService_map_ret_bool_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_MAP, ::std::map<int32_t, ::std::vector<::std::string>>*>, apache::thrift::FieldData<2, apache::thrift::protocol::T_LIST, ::std::vector<::std::string>*>> ParamService_list_ret_map_setlist_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_LIST, ::std::vector<bool>*>> ParamService_list_ret_map_setlist_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_LIST, ::std::vector<::std::vector<::std::vector<::std::vector<int32_t>>>>*>> ParamService_mapsetlistmapliststring_ret_listlistlist_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_MAP, ::std::map<::std::set<::std::vector<int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>*>> ParamService_mapsetlistmapliststring_ret_listlistlist_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_I32, int32_t*>> ParamService_typedef_ret_i32_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_I32, ::some::valid::ns::simpleTypeDef*>> ParamService_typedef_ret_i32_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_LIST, ::some::valid::ns::complexStructTypeDef*>> ParamService_listtypedef_ret_typedef_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_LIST, ::std::vector< ::some::valid::ns::simpleTypeDef>*>> ParamService_listtypedef_ret_typedef_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<3, apache::thrift::protocol::T_DOUBLE, double*>> ParamService_enum_ret_double_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_I32, ::some::valid::ns::MyEnumA*>> ParamService_enum_ret_double_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<3, apache::thrift::protocol::T_DOUBLE, double*>, apache::thrift::FieldData<5, apache::thrift::protocol::T_I32, ::some::valid::ns::MyEnumA*>> ParamService_enum_ret_double_enum_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_I32, ::some::valid::ns::MyEnumA*>> ParamService_enum_ret_double_enum_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_MAP, ::std::map<::std::string, int64_t>*>> ParamService_listenum_ret_map_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_LIST, ::std::vector< ::some::valid::ns::MyEnumA>*>> ParamService_listenum_ret_map_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_I16, int16_t*>> ParamService_struct_ret_i16_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_STRUCT, ::some::valid::ns::MyStruct*>> ParamService_struct_ret_i16_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<8, apache::thrift::protocol::T_SET, ::std::set<::std::string>*>> ParamService_setstruct_ret_set_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_SET, ::std::set< ::some::valid::ns::MyStruct>*>> ParamService_setstruct_ret_set_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<4, apache::thrift::protocol::T_I32, int32_t*>, apache::thrift::FieldData<2, apache::thrift::protocol::T_I32, int32_t*>> ParamService_union_ret_i32_i32_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_STRUCT, ::some::valid::ns::ComplexUnion*>> ParamService_union_ret_i32_i32_param_presult;
typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, apache::thrift::protocol::T_STRING, ::std::string*>> ParamService_listunion_string_param_pargs;
typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, apache::thrift::protocol::T_LIST, ::std::vector< ::some::valid::ns::ComplexUnion>*>> ParamService_listunion_string_param_presult;
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_void_ret_i16_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_void_ret_i16_param_pargs args;
int16_t uarg_param1{0};
args.get<0>().value = &uarg_param1;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.void_ret_i16_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "void_ret_i16_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<void>>(std::move(req), std::move(ctxStack), return_void_ret_i16_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_void_ret_i16_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
ctx->setStartedProcessing();
iface_->async_eb_void_ret_i16_param(std::move(callback), args.get<0>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_void_ret_i16_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx) {
ProtocolOut_ prot;
ParamService_void_ret_i16_param_presult result;
return serializeResponse("void_ret_i16_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_void_ret_i16_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "void_ret_i16_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_void_ret_byte_i16_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_void_ret_byte_i16_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_void_ret_byte_i16_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_void_ret_byte_i16_param_pargs args;
int8_t uarg_param1{0};
args.get<0>().value = &uarg_param1;
int16_t uarg_param2{0};
args.get<1>().value = &uarg_param2;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.void_ret_byte_i16_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "void_ret_byte_i16_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<void>>(std::move(req), std::move(ctxStack), return_void_ret_byte_i16_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_void_ret_byte_i16_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_void_ret_byte_i16_param(std::move(callback), args.get<0>().ref(), args.get<1>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_void_ret_byte_i16_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx) {
ProtocolOut_ prot;
ParamService_void_ret_byte_i16_param_presult result;
return serializeResponse("void_ret_byte_i16_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_void_ret_byte_i16_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "void_ret_byte_i16_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_void_ret_map_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_void_ret_map_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_void_ret_map_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_void_ret_map_param_pargs args;
auto uarg_param1 = std::make_unique<::std::map<::std::string, int64_t>>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.void_ret_map_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "void_ret_map_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<void>>(std::move(req), std::move(ctxStack), return_void_ret_map_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_void_ret_map_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_void_ret_map_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_void_ret_map_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx) {
ProtocolOut_ prot;
ParamService_void_ret_map_param_presult result;
return serializeResponse("void_ret_map_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_void_ret_map_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "void_ret_map_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_void_ret_map_setlist_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_void_ret_map_setlist_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_void_ret_map_setlist_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_void_ret_map_setlist_param_pargs args;
auto uarg_param1 = std::make_unique<::std::map<::std::string, int64_t>>();
args.get<0>().value = uarg_param1.get();
auto uarg_param2 = std::make_unique<::std::set<::std::vector<::std::string>>>();
args.get<1>().value = uarg_param2.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.void_ret_map_setlist_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "void_ret_map_setlist_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<void>>(std::move(req), std::move(ctxStack), return_void_ret_map_setlist_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_void_ret_map_setlist_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_void_ret_map_setlist_param(std::move(callback), std::move(uarg_param1), std::move(uarg_param2));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_void_ret_map_setlist_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx) {
ProtocolOut_ prot;
ParamService_void_ret_map_setlist_param_presult result;
return serializeResponse("void_ret_map_setlist_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_void_ret_map_setlist_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "void_ret_map_setlist_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_void_ret_map_typedef_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_void_ret_map_typedef_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_void_ret_map_typedef_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_void_ret_map_typedef_param_pargs args;
::some::valid::ns::simpleTypeDef uarg_param1{0};
args.get<0>().value = &uarg_param1;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.void_ret_map_typedef_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "void_ret_map_typedef_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<void>>(std::move(req), std::move(ctxStack), return_void_ret_map_typedef_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_void_ret_map_typedef_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_void_ret_map_typedef_param(std::move(callback), args.get<0>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_void_ret_map_typedef_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx) {
ProtocolOut_ prot;
ParamService_void_ret_map_typedef_param_presult result;
return serializeResponse("void_ret_map_typedef_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_void_ret_map_typedef_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "void_ret_map_typedef_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_void_ret_enum_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_void_ret_enum_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_void_ret_enum_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_void_ret_enum_param_pargs args;
::some::valid::ns::MyEnumA uarg_param1{static_cast< ::some::valid::ns::MyEnumA>(0)};
args.get<0>().value = &uarg_param1;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.void_ret_enum_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "void_ret_enum_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<void>>(std::move(req), std::move(ctxStack), return_void_ret_enum_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_void_ret_enum_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_void_ret_enum_param(std::move(callback), args.get<0>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_void_ret_enum_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx) {
ProtocolOut_ prot;
ParamService_void_ret_enum_param_presult result;
return serializeResponse("void_ret_enum_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_void_ret_enum_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "void_ret_enum_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_void_ret_struct_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_void_ret_struct_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_void_ret_struct_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_void_ret_struct_param_pargs args;
auto uarg_param1 = std::make_unique< ::some::valid::ns::MyStruct>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.void_ret_struct_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "void_ret_struct_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<void>>(std::move(req), std::move(ctxStack), return_void_ret_struct_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_void_ret_struct_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_void_ret_struct_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_void_ret_struct_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx) {
ProtocolOut_ prot;
ParamService_void_ret_struct_param_presult result;
return serializeResponse("void_ret_struct_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_void_ret_struct_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "void_ret_struct_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_void_ret_listunion_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_void_ret_listunion_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_void_ret_listunion_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_void_ret_listunion_param_pargs args;
auto uarg_param1 = std::make_unique<::std::vector< ::some::valid::ns::ComplexUnion>>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.void_ret_listunion_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "void_ret_listunion_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<void>>(std::move(req), std::move(ctxStack), return_void_ret_listunion_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_void_ret_listunion_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_void_ret_listunion_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_void_ret_listunion_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx) {
ProtocolOut_ prot;
ParamService_void_ret_listunion_param_presult result;
return serializeResponse("void_ret_listunion_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_void_ret_listunion_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "void_ret_listunion_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_bool_ret_i32_i64_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_bool_ret_i32_i64_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_bool_ret_i32_i64_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_bool_ret_i32_i64_param_pargs args;
int32_t uarg_param1{0};
args.get<0>().value = &uarg_param1;
int64_t uarg_param2{0};
args.get<1>().value = &uarg_param2;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.bool_ret_i32_i64_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "bool_ret_i32_i64_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<bool>>(std::move(req), std::move(ctxStack), return_bool_ret_i32_i64_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_bool_ret_i32_i64_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_bool_ret_i32_i64_param(std::move(callback), args.get<0>().ref(), args.get<1>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_bool_ret_i32_i64_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, bool const& _return) {
ProtocolOut_ prot;
ParamService_bool_ret_i32_i64_param_presult result;
result.get<0>().value = const_cast<bool*>(&_return);
result.setIsSet(0, true);
return serializeResponse("bool_ret_i32_i64_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_bool_ret_i32_i64_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "bool_ret_i32_i64_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_bool_ret_map_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_bool_ret_map_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_bool_ret_map_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_bool_ret_map_param_pargs args;
auto uarg_param1 = std::make_unique<::std::map<::std::string, int64_t>>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.bool_ret_map_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "bool_ret_map_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<bool>>(std::move(req), std::move(ctxStack), return_bool_ret_map_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_bool_ret_map_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_bool_ret_map_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_bool_ret_map_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, bool const& _return) {
ProtocolOut_ prot;
ParamService_bool_ret_map_param_presult result;
result.get<0>().value = const_cast<bool*>(&_return);
result.setIsSet(0, true);
return serializeResponse("bool_ret_map_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_bool_ret_map_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "bool_ret_map_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_bool_ret_union_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_bool_ret_union_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_bool_ret_union_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_bool_ret_union_param_pargs args;
auto uarg_param1 = std::make_unique< ::some::valid::ns::ComplexUnion>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.bool_ret_union_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "bool_ret_union_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<bool>>(std::move(req), std::move(ctxStack), return_bool_ret_union_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_bool_ret_union_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_bool_ret_union_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_bool_ret_union_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, bool const& _return) {
ProtocolOut_ prot;
ParamService_bool_ret_union_param_presult result;
result.get<0>().value = const_cast<bool*>(&_return);
result.setIsSet(0, true);
return serializeResponse("bool_ret_union_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_bool_ret_union_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "bool_ret_union_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_i64_ret_float_double_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_i64_ret_float_double_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_i64_ret_float_double_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_i64_ret_float_double_param_pargs args;
float uarg_param1{0};
args.get<0>().value = &uarg_param1;
double uarg_param2{0};
args.get<1>().value = &uarg_param2;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.i64_ret_float_double_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "i64_ret_float_double_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<int64_t>>(std::move(req), std::move(ctxStack), return_i64_ret_float_double_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_i64_ret_float_double_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_i64_ret_float_double_param(std::move(callback), args.get<0>().ref(), args.get<1>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_i64_ret_float_double_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, int64_t const& _return) {
ProtocolOut_ prot;
ParamService_i64_ret_float_double_param_presult result;
result.get<0>().value = const_cast<int64_t*>(&_return);
result.setIsSet(0, true);
return serializeResponse("i64_ret_float_double_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_i64_ret_float_double_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "i64_ret_float_double_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_i64_ret_string_typedef_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_i64_ret_string_typedef_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_i64_ret_string_typedef_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_i64_ret_string_typedef_param_pargs args;
auto uarg_param1 = std::make_unique<::std::string>();
args.get<0>().value = uarg_param1.get();
auto uarg_param2 = std::make_unique<::std::set< ::some::valid::ns::mostComplexTypeDef>>();
args.get<1>().value = uarg_param2.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.i64_ret_string_typedef_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "i64_ret_string_typedef_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<int64_t>>(std::move(req), std::move(ctxStack), return_i64_ret_string_typedef_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_i64_ret_string_typedef_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_i64_ret_string_typedef_param(std::move(callback), std::move(uarg_param1), std::move(uarg_param2));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_i64_ret_string_typedef_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, int64_t const& _return) {
ProtocolOut_ prot;
ParamService_i64_ret_string_typedef_param_presult result;
result.get<0>().value = const_cast<int64_t*>(&_return);
result.setIsSet(0, true);
return serializeResponse("i64_ret_string_typedef_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_i64_ret_string_typedef_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "i64_ret_string_typedef_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_i64_ret_i32_i32_i32_i32_i32_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_i64_ret_i32_i32_i32_i32_i32_param_pargs args;
int32_t uarg_param1{0};
args.get<0>().value = &uarg_param1;
int32_t uarg_param2{0};
args.get<1>().value = &uarg_param2;
int32_t uarg_param3{0};
args.get<2>().value = &uarg_param3;
int32_t uarg_param4{0};
args.get<3>().value = &uarg_param4;
int32_t uarg_param5{0};
args.get<4>().value = &uarg_param5;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.i64_ret_i32_i32_i32_i32_i32_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "i64_ret_i32_i32_i32_i32_i32_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<int64_t>>(std::move(req), std::move(ctxStack), return_i64_ret_i32_i32_i32_i32_i32_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_i64_ret_i32_i32_i32_i32_i32_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
ctx->setStartedProcessing();
iface_->async_eb_i64_ret_i32_i32_i32_i32_i32_param(std::move(callback), args.get<0>().ref(), args.get<1>().ref(), args.get<2>().ref(), args.get<3>().ref(), args.get<4>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_i64_ret_i32_i32_i32_i32_i32_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, int64_t const& _return) {
ProtocolOut_ prot;
ParamService_i64_ret_i32_i32_i32_i32_i32_param_presult result;
result.get<0>().value = const_cast<int64_t*>(&_return);
result.setIsSet(0, true);
return serializeResponse("i64_ret_i32_i32_i32_i32_i32_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_i64_ret_i32_i32_i32_i32_i32_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "i64_ret_i32_i32_i32_i32_i32_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_double_ret_setstruct_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_double_ret_setstruct_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_double_ret_setstruct_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_double_ret_setstruct_param_pargs args;
auto uarg_param1 = std::make_unique<::std::set< ::some::valid::ns::MyStruct>>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.double_ret_setstruct_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "double_ret_setstruct_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<double>>(std::move(req), std::move(ctxStack), return_double_ret_setstruct_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_double_ret_setstruct_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_double_ret_setstruct_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_double_ret_setstruct_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, double const& _return) {
ProtocolOut_ prot;
ParamService_double_ret_setstruct_param_presult result;
result.get<0>().value = const_cast<double*>(&_return);
result.setIsSet(0, true);
return serializeResponse("double_ret_setstruct_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_double_ret_setstruct_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "double_ret_setstruct_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_string_ret_string_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_string_ret_string_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_string_ret_string_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_string_ret_string_param_pargs args;
auto uarg_param1 = std::make_unique<::std::string>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.string_ret_string_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "string_ret_string_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<std::unique_ptr<::std::string>>>(std::move(req), std::move(ctxStack), return_string_ret_string_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_string_ret_string_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_string_ret_string_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_string_ret_string_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::std::string const& _return) {
ProtocolOut_ prot;
ParamService_string_ret_string_param_presult result;
result.get<0>().value = const_cast<::std::string*>(&_return);
result.setIsSet(0, true);
return serializeResponse("string_ret_string_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_string_ret_string_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "string_ret_string_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_binary_ret_binary_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_binary_ret_binary_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_binary_ret_binary_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_binary_ret_binary_param_pargs args;
auto uarg_param1 = std::make_unique<::std::string>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.binary_ret_binary_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "binary_ret_binary_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<std::unique_ptr<::std::string>>>(std::move(req), std::move(ctxStack), return_binary_ret_binary_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_binary_ret_binary_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_binary_ret_binary_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_binary_ret_binary_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::std::string const& _return) {
ProtocolOut_ prot;
ParamService_binary_ret_binary_param_presult result;
result.get<0>().value = const_cast<::std::string*>(&_return);
result.setIsSet(0, true);
return serializeResponse("binary_ret_binary_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_binary_ret_binary_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "binary_ret_binary_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_map_ret_bool_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_map_ret_bool_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_map_ret_bool_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_map_ret_bool_param_pargs args;
bool uarg_param1{0};
args.get<0>().value = &uarg_param1;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.map_ret_bool_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "map_ret_bool_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<std::unique_ptr<::std::map<::std::string, int64_t>>>>(std::move(req), std::move(ctxStack), return_map_ret_bool_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_map_ret_bool_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_map_ret_bool_param(std::move(callback), args.get<0>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_map_ret_bool_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::std::map<::std::string, int64_t> const& _return) {
ProtocolOut_ prot;
ParamService_map_ret_bool_param_presult result;
result.get<0>().value = const_cast<::std::map<::std::string, int64_t>*>(&_return);
result.setIsSet(0, true);
return serializeResponse("map_ret_bool_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_map_ret_bool_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "map_ret_bool_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_list_ret_map_setlist_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_list_ret_map_setlist_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_list_ret_map_setlist_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_list_ret_map_setlist_param_pargs args;
auto uarg_param1 = std::make_unique<::std::map<int32_t, ::std::vector<::std::string>>>();
args.get<0>().value = uarg_param1.get();
auto uarg_param2 = std::make_unique<::std::vector<::std::string>>();
args.get<1>().value = uarg_param2.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.list_ret_map_setlist_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "list_ret_map_setlist_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<std::unique_ptr<::std::vector<bool>>>>(std::move(req), std::move(ctxStack), return_list_ret_map_setlist_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_list_ret_map_setlist_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_list_ret_map_setlist_param(std::move(callback), std::move(uarg_param1), std::move(uarg_param2));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_list_ret_map_setlist_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::std::vector<bool> const& _return) {
ProtocolOut_ prot;
ParamService_list_ret_map_setlist_param_presult result;
result.get<0>().value = const_cast<::std::vector<bool>*>(&_return);
result.setIsSet(0, true);
return serializeResponse("list_ret_map_setlist_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_list_ret_map_setlist_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "list_ret_map_setlist_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_mapsetlistmapliststring_ret_listlistlist_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_mapsetlistmapliststring_ret_listlistlist_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_mapsetlistmapliststring_ret_listlistlist_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_mapsetlistmapliststring_ret_listlistlist_param_pargs args;
auto uarg_param1 = std::make_unique<::std::vector<::std::vector<::std::vector<::std::vector<int32_t>>>>>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.mapsetlistmapliststring_ret_listlistlist_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "mapsetlistmapliststring_ret_listlistlist_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<std::unique_ptr<::std::map<::std::set<::std::vector<int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>>>>(std::move(req), std::move(ctxStack), return_mapsetlistmapliststring_ret_listlistlist_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_mapsetlistmapliststring_ret_listlistlist_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_mapsetlistmapliststring_ret_listlistlist_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_mapsetlistmapliststring_ret_listlistlist_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::std::map<::std::set<::std::vector<int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>> const& _return) {
ProtocolOut_ prot;
ParamService_mapsetlistmapliststring_ret_listlistlist_param_presult result;
result.get<0>().value = const_cast<::std::map<::std::set<::std::vector<int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>*>(&_return);
result.setIsSet(0, true);
return serializeResponse("mapsetlistmapliststring_ret_listlistlist_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_mapsetlistmapliststring_ret_listlistlist_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "mapsetlistmapliststring_ret_listlistlist_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_typedef_ret_i32_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_typedef_ret_i32_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_typedef_ret_i32_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_typedef_ret_i32_param_pargs args;
int32_t uarg_param1{0};
args.get<0>().value = &uarg_param1;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.typedef_ret_i32_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "typedef_ret_i32_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback< ::some::valid::ns::simpleTypeDef>>(std::move(req), std::move(ctxStack), return_typedef_ret_i32_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_typedef_ret_i32_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_typedef_ret_i32_param(std::move(callback), args.get<0>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_typedef_ret_i32_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::some::valid::ns::simpleTypeDef const& _return) {
ProtocolOut_ prot;
ParamService_typedef_ret_i32_param_presult result;
result.get<0>().value = const_cast< ::some::valid::ns::simpleTypeDef*>(&_return);
result.setIsSet(0, true);
return serializeResponse("typedef_ret_i32_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_typedef_ret_i32_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "typedef_ret_i32_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_listtypedef_ret_typedef_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_listtypedef_ret_typedef_param_pargs args;
auto uarg_param1 = std::make_unique< ::some::valid::ns::complexStructTypeDef>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.listtypedef_ret_typedef_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "listtypedef_ret_typedef_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<std::unique_ptr<::std::vector< ::some::valid::ns::simpleTypeDef>>>>(std::move(req), std::move(ctxStack), return_listtypedef_ret_typedef_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_listtypedef_ret_typedef_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
ctx->setStartedProcessing();
iface_->async_eb_listtypedef_ret_typedef_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_listtypedef_ret_typedef_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::std::vector< ::some::valid::ns::simpleTypeDef> const& _return) {
ProtocolOut_ prot;
ParamService_listtypedef_ret_typedef_param_presult result;
result.get<0>().value = const_cast<::std::vector< ::some::valid::ns::simpleTypeDef>*>(&_return);
result.setIsSet(0, true);
return serializeResponse("listtypedef_ret_typedef_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_listtypedef_ret_typedef_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "listtypedef_ret_typedef_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_enum_ret_double_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_enum_ret_double_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_enum_ret_double_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_enum_ret_double_param_pargs args;
double uarg_param1{0};
args.get<0>().value = &uarg_param1;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.enum_ret_double_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "enum_ret_double_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback< ::some::valid::ns::MyEnumA>>(std::move(req), std::move(ctxStack), return_enum_ret_double_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_enum_ret_double_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_enum_ret_double_param(std::move(callback), args.get<0>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_enum_ret_double_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::some::valid::ns::MyEnumA const& _return) {
ProtocolOut_ prot;
ParamService_enum_ret_double_param_presult result;
result.get<0>().value = const_cast< ::some::valid::ns::MyEnumA*>(&_return);
result.setIsSet(0, true);
return serializeResponse("enum_ret_double_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_enum_ret_double_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "enum_ret_double_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_enum_ret_double_enum_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_enum_ret_double_enum_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_enum_ret_double_enum_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_enum_ret_double_enum_param_pargs args;
double uarg_param1{0};
args.get<0>().value = &uarg_param1;
::some::valid::ns::MyEnumA uarg_param2{static_cast< ::some::valid::ns::MyEnumA>(0)};
args.get<1>().value = &uarg_param2;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.enum_ret_double_enum_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "enum_ret_double_enum_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback< ::some::valid::ns::MyEnumA>>(std::move(req), std::move(ctxStack), return_enum_ret_double_enum_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_enum_ret_double_enum_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_enum_ret_double_enum_param(std::move(callback), args.get<0>().ref(), args.get<1>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_enum_ret_double_enum_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::some::valid::ns::MyEnumA const& _return) {
ProtocolOut_ prot;
ParamService_enum_ret_double_enum_param_presult result;
result.get<0>().value = const_cast< ::some::valid::ns::MyEnumA*>(&_return);
result.setIsSet(0, true);
return serializeResponse("enum_ret_double_enum_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_enum_ret_double_enum_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "enum_ret_double_enum_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_listenum_ret_map_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_listenum_ret_map_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_listenum_ret_map_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_listenum_ret_map_param_pargs args;
auto uarg_param1 = std::make_unique<::std::map<::std::string, int64_t>>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.listenum_ret_map_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "listenum_ret_map_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<std::unique_ptr<::std::vector< ::some::valid::ns::MyEnumA>>>>(std::move(req), std::move(ctxStack), return_listenum_ret_map_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_listenum_ret_map_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_listenum_ret_map_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_listenum_ret_map_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::std::vector< ::some::valid::ns::MyEnumA> const& _return) {
ProtocolOut_ prot;
ParamService_listenum_ret_map_param_presult result;
result.get<0>().value = const_cast<::std::vector< ::some::valid::ns::MyEnumA>*>(&_return);
result.setIsSet(0, true);
return serializeResponse("listenum_ret_map_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_listenum_ret_map_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "listenum_ret_map_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_struct_ret_i16_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_struct_ret_i16_param_pargs args;
int16_t uarg_param1{0};
args.get<0>().value = &uarg_param1;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.struct_ret_i16_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "struct_ret_i16_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<std::unique_ptr< ::some::valid::ns::MyStruct>>>(std::move(req), std::move(ctxStack), return_struct_ret_i16_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_struct_ret_i16_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
ctx->setStartedProcessing();
iface_->async_eb_struct_ret_i16_param(std::move(callback), args.get<0>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_struct_ret_i16_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::some::valid::ns::MyStruct const& _return) {
ProtocolOut_ prot;
ParamService_struct_ret_i16_param_presult result;
result.get<0>().value = const_cast< ::some::valid::ns::MyStruct*>(&_return);
result.setIsSet(0, true);
return serializeResponse("struct_ret_i16_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_struct_ret_i16_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "struct_ret_i16_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_setstruct_ret_set_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_setstruct_ret_set_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_setstruct_ret_set_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_setstruct_ret_set_param_pargs args;
auto uarg_param1 = std::make_unique<::std::set<::std::string>>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.setstruct_ret_set_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "setstruct_ret_set_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<std::unique_ptr<::std::set< ::some::valid::ns::MyStruct>>>>(std::move(req), std::move(ctxStack), return_setstruct_ret_set_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_setstruct_ret_set_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_setstruct_ret_set_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_setstruct_ret_set_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::std::set< ::some::valid::ns::MyStruct> const& _return) {
ProtocolOut_ prot;
ParamService_setstruct_ret_set_param_presult result;
result.get<0>().value = const_cast<::std::set< ::some::valid::ns::MyStruct>*>(&_return);
result.setIsSet(0, true);
return serializeResponse("setstruct_ret_set_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_setstruct_ret_set_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "setstruct_ret_set_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_union_ret_i32_i32_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_union_ret_i32_i32_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_union_ret_i32_i32_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_union_ret_i32_i32_param_pargs args;
int32_t uarg_param1{0};
args.get<0>().value = &uarg_param1;
int32_t uarg_param2{0};
args.get<1>().value = &uarg_param2;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.union_ret_i32_i32_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "union_ret_i32_i32_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<std::unique_ptr< ::some::valid::ns::ComplexUnion>>>(std::move(req), std::move(ctxStack), return_union_ret_i32_i32_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_union_ret_i32_i32_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_union_ret_i32_i32_param(std::move(callback), args.get<0>().ref(), args.get<1>().ref());
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_union_ret_i32_i32_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::some::valid::ns::ComplexUnion const& _return) {
ProtocolOut_ prot;
ParamService_union_ret_i32_i32_param_presult result;
result.get<0>().value = const_cast< ::some::valid::ns::ComplexUnion*>(&_return);
result.setIsSet(0, true);
return serializeResponse("union_ret_i32_i32_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_union_ret_i32_i32_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "union_ret_i32_i32_param");
return;
}
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::_processInThread_listunion_string_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::NORMAL);
processInThread<ProtocolIn_, ProtocolOut_>(std::move(req), std::move(buf), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &ParamServiceAsyncProcessor::process_listunion_string_param<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void ParamServiceAsyncProcessor::process_listunion_string_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::Cpp2RequestContext* ctx,folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
ParamService_listunion_string_param_pargs args;
auto uarg_param1 = std::make_unique<::std::string>();
args.get<0>().value = uarg_param1.get();
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "ParamService.listunion_string_param", ctx));
try {
folly::io::Cursor cursor(buf.get());
cursor.skip(ctx->getMessageBeginSize());
ProtocolIn_ iprot;
iprot.setInput(cursor);
deserializeRequest(args, buf.get(), &iprot, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "listunion_string_param");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<std::unique_ptr<::std::vector< ::some::valid::ns::ComplexUnion>>>>(std::move(req), std::move(ctxStack), return_listunion_string_param<ProtocolIn_,ProtocolOut_>, throw_wrapped_listunion_string_param<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
callback.release()->deleteInThread();
return;
}
ctx->setStartedProcessing();
iface_->async_tm_listunion_string_param(std::move(callback), std::move(uarg_param1));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue ParamServiceAsyncProcessor::return_listunion_string_param(int32_t protoSeqId, apache::thrift::ContextStack* ctx, ::std::vector< ::some::valid::ns::ComplexUnion> const& _return) {
ProtocolOut_ prot;
ParamService_listunion_string_param_presult result;
result.get<0>().value = const_cast<::std::vector< ::some::valid::ns::ComplexUnion>*>(&_return);
result.setIsSet(0, true);
return serializeResponse("listunion_string_param", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void ParamServiceAsyncProcessor::throw_wrapped_listunion_string_param(std::unique_ptr<apache::thrift::ResponseChannelRequest> req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "listunion_string_param");
return;
}
}
}}} // some::valid::ns
|
; A091001: Number of walks of length n between adjacent nodes on the Petersen graph.
; 0,1,0,5,4,33,56,253,588,2105,5632,18261,52052,161617,473928,1443629,4287196,12948969,38672144,116365957,348398820,1046594561,3136987480,9416554845,28238479724,84737808793,254168687136,762595539893,2287607662708,6863180902065,20588826878312,61767912290701,185300873560572,555908347304777,1667713588668208,5003163672496869,15009445204506116,45028427239487329,135085098466524024,405255661903447997,1215766252702592140,3647300224123280121,10941897740338832960,32825699085078513685,98477085527111511444,295431280037582593553,886293793200251662216,2658881473425747223533,7976644232627257196828,23929933073181740538025,71789798468945283718992,215369396908035726947141,646108187721707429261092,1938324569169921790943937,5814973695500166366510488,17444921110519697112174109,52334763283520695311237036,157004289946638877984281689,471012869647763049851703904,1413038609327596317757394037,4239115827214174616867617460,12717347483179752523411981681,38152042446464800224617686440,114456127345543315365089576525,343368382024332116712795695164,1030105146097592008903333154313,3090315438243584709180107325296,9270946314829136762600106251173,27812838944290645017680750202948,83438516833265465593281387709985,250315550499009335699365888927672,750946651498602129259054215187581,2252839954492658143455249548753612,6758519863484270919009574839879097,20275559590440219779741072132400768,60826678771345845293798521171675349,182480036313987163972244953966079956,547440108942062235735036080996132049
mov $3,2
lpb $0
sub $0,1
mov $2,$1
add $3,$1
mov $1,$3
mul $1,2
sub $1,2
sub $1,$2
mul $2,3
mov $3,$2
lpe
div $1,2
mov $0,$1
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Asher Elmquist, Jayne Henry
// =============================================================================
//
// Wrapper classes for modeling an entire RCCar vehicle assembly
// (including the vehicle itself, the powertrain, and the tires).
//
// =============================================================================
#include "chrono/ChConfig.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_models/vehicle/rccar/RCCar.h"
using namespace chrono;
using namespace chrono::vehicle;
namespace chrono {
namespace vehicle {
namespace rccar {
// -----------------------------------------------------------------------------
RCCar::RCCar()
: m_system(nullptr),
m_vehicle(nullptr),
m_contactMethod(ChContactMethod::NSC),
m_chassisCollisionType(CollisionType::NONE),
m_fixed(false),
m_tireType(TireModelType::RIGID),
m_tire_step_size(-1),
m_initFwdVel(0),
m_initPos(ChCoordsys<>(ChVector<>(0, 0, 1), QUNIT)),
m_initOmega({0, 0, 0, 0}),
m_apply_drag(false) {}
RCCar::RCCar(ChSystem* system)
: m_system(system),
m_vehicle(nullptr),
m_contactMethod(ChContactMethod::NSC),
m_chassisCollisionType(CollisionType::NONE),
m_fixed(false),
m_tireType(TireModelType::RIGID),
m_tire_step_size(-1),
m_initFwdVel(0),
m_initPos(ChCoordsys<>(ChVector<>(0, 0, 1), QUNIT)),
m_initOmega({0, 0, 0, 0}),
m_apply_drag(false) {}
RCCar::~RCCar() {
delete m_vehicle;
}
// -----------------------------------------------------------------------------
void RCCar::SetAerodynamicDrag(double Cd, double area, double air_density) {
m_Cd = Cd;
m_area = area;
m_air_density = air_density;
m_apply_drag = true;
}
// -----------------------------------------------------------------------------
void RCCar::Initialize() {
// Create and initialize the RCCar vehicle
m_vehicle = m_system ? new RCCar_Vehicle(m_system, m_fixed, m_chassisCollisionType)
: new RCCar_Vehicle(m_fixed, m_contactMethod, m_chassisCollisionType);
m_vehicle->SetInitWheelAngVel(m_initOmega);
m_vehicle->Initialize(m_initPos, m_initFwdVel);
// If specified, enable aerodynamic drag
if (m_apply_drag) {
m_vehicle->GetChassis()->SetAerodynamicDrag(m_Cd, m_area, m_air_density);
}
// Create and initialize the powertrain system
auto powertrain = chrono_types::make_shared<RCCar_SimpleMapPowertrain>("Powertrain");
m_vehicle->InitializePowertrain(powertrain);
// Create the tires and set parameters depending on type.
bool use_mesh = (m_tireType == TireModelType::RIGID_MESH);
switch (m_tireType) {
case TireModelType::TMEASY: {
auto tire_FL = chrono_types::make_shared<RCCar_TMeasyTire>("FL");
auto tire_FR = chrono_types::make_shared<RCCar_TMeasyTire>("FR");
auto tire_RL = chrono_types::make_shared<RCCar_TMeasyTire>("RL");
auto tire_RR = chrono_types::make_shared<RCCar_TMeasyTire>("RR");
m_vehicle->InitializeTire(tire_FL, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE);
m_vehicle->InitializeTire(tire_FR, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE);
m_vehicle->InitializeTire(tire_RL, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE);
m_vehicle->InitializeTire(tire_RR, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE);
m_tire_mass = tire_FL->ReportMass();
break;
}
default: { // Defaults to rigid tires
auto tire_FL = chrono_types::make_shared<RCCar_RigidTire>("FL", use_mesh);
auto tire_FR = chrono_types::make_shared<RCCar_RigidTire>("FR", use_mesh);
auto tire_RL = chrono_types::make_shared<RCCar_RigidTire>("RL", use_mesh);
auto tire_RR = chrono_types::make_shared<RCCar_RigidTire>("RR", use_mesh);
m_vehicle->InitializeTire(tire_FL, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE);
m_vehicle->InitializeTire(tire_FR, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE);
m_vehicle->InitializeTire(tire_RL, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE);
m_vehicle->InitializeTire(tire_RR, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE);
m_tire_mass = tire_FL->ReportMass();
break;
}
}
for (auto& axle : m_vehicle->GetAxles()) {
for (auto& wheel : axle->GetWheels()) {
if (m_tire_step_size > 0)
wheel->GetTire()->SetStepsize(m_tire_step_size);
}
}
}
// -----------------------------------------------------------------------------
void RCCar::SetTireVisualizationType(VisualizationType vis) {
for (auto& axle : m_vehicle->GetAxles()) {
for (auto& wheel : axle->GetWheels()) {
wheel->GetTire()->SetVisualizationType(vis);
}
}
}
// -----------------------------------------------------------------------------
void RCCar::Synchronize(double time, const ChDriver::Inputs& driver_inputs, const ChTerrain& terrain) {
m_vehicle->Synchronize(time, driver_inputs, terrain);
}
// -----------------------------------------------------------------------------
void RCCar::Advance(double step) {
m_vehicle->Advance(step);
}
// -----------------------------------------------------------------------------
double RCCar::GetTotalMass() const {
return m_vehicle->GetVehicleMass() + 4 * m_tire_mass;
}
} // namespace rccar
} // namespace vehicle
} // namespace chrono
|
; A332206: Numbers k such that A332205(k) = 0.
; 0,1,3,4,12,13,15,16,48,49,51,52,60,61,63,64,192,193,195,196,204,205,207,208,240,241,243,244,252,253,255,256,768,769,771,772,780,781,783,784,816,817,819,820,828,829,831,832,960,961,963,964,972,973,975,976
seq $0,98871 ; Sums of distinct powers of 4 plus 1.
mul $0,12
div $0,16
|
; FV-1 Testing
;
; Program: Read reg 0x08
;
; POT0: Test Value
;
; Check read register 0x08
;
skp RUN,main
wlds SIN0,0x03f,0x7fff ; SIN0
wlds SIN1,0x07f,0x7fff ; SIN1
wldr RMP0,0x2000,4096 ; RMP0
wldr RMP0,0x4000,4096 ; RMP1
main: clr
rdax 0x08,1.0 ; load reg 0x08
wrax DACL,0.0 ; write to DACL
cho sof,SIN0,REG|COMPA,0.0 ; "register" SIN0
cho sof,SIN1,REG|COMPA,0.0 ; "register" SIN1
cho sof,RMP0,REG|COMPA,0.0 ; "register" RMP0
cho sof,RMP1,REG|COMPA,0.0 ; "register" RMP1
clr
;or 0x5a5a5a ; load test pattern
ldax POT0 ; load test pattern
wra 0,0.0 ; write to delay
rda 0x7fff,1.0 ; read from end of delay and into LR
wrax REG0,0.0 ; save to temp reg
or -0.5000 ; load garbage value
not ; flip all the bits
ldax 0x08 ; load test reg
rdax REG0,-1.0 ; subtract temp value from rda
skp ZRO,mark
skp 0,space
mark: or 0x7fffff ; mark equal with max val
space: wrax DACR,0.0 ; write to DACR
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
ld a, ff
ldff(45), a
ld b, 96
call lwaitly_b
ld a, 80
ldff(68), a
ld a, ff
ld c, 69
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
xor a, a
ldff(c), a
ldff(c), a
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
ld a, b
inc a
inc a
ldff(45), a
ld c, 0f
.text@1000
lstatint:
xor a, a
ldff(45), a
ld a, 50
ldff(41), a
.text@10c0
xor a, a
ldff(c), a
.text@10d8
ld a, 40
ldff(41), a
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
ldff a, (c)
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
ld bc, 7a00
ld hl, 8000
ld d, 00
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
pop af
ld b, a
srl a
srl a
srl a
srl a
ld(9800), a
ld a, b
and a, 0f
ld(9801), a
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
00 00 08 08 22 22 41 41
7f 7f 41 41 41 41 41 41
00 00 7e 7e 41 41 41 41
7e 7e 41 41 41 41 7e 7e
00 00 3e 3e 41 41 40 40
40 40 40 40 41 41 3e 3e
00 00 7e 7e 41 41 41 41
41 41 41 41 41 41 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 40 40
|
; A271027: a(n) = 3661529 + 11184810*n.
; 3661529,14846339,26031149,37215959,48400769,59585579,70770389,81955199,93140009,104324819,115509629,126694439,137879249,149064059,160248869,171433679,182618489,193803299,204988109,216172919,227357729,238542539,249727349,260912159,272096969,283281779,294466589
mul $0,11184810
add $0,3661529
|
#include "engine.h"
VAR(importcuberemip, 0, 1024, 2048);
struct cubeloader
{
enum
{
DEFAULT_LIQUID = 1,
DEFAULT_WALL,
DEFAULT_FLOOR,
DEFAULT_CEIL
};
enum // block types, order matters!
{
C_SOLID = 0, // entirely solid cube [only specifies wtex]
C_CORNER, // half full corner of a wall
C_FHF, // floor heightfield using neighbour vdelta values
C_CHF, // idem ceiling
C_SPACE, // entirely empty cube
C_SEMISOLID, // generated by mipmapping
C_MAXTYPE
};
struct c_sqr
{
uchar type; // one of the above
char floor, ceil; // height, in cubes
uchar wtex, ftex, ctex; // wall/floor/ceil texture ids
uchar vdelta; // vertex delta, used for heightfield cubes
uchar utex; // upper wall tex id
};
struct c_persistent_entity // map entity
{
short x, y, z; // cube aligned position
short attr1;
uchar type; // type is one of the above
uchar attr2, attr3, attr4;
};
struct c_header // map file format header
{
char head[4]; // "CUBE"
int version; // any >8bit quantity is little endian
int headersize; // sizeof(header)
int sfactor; // in bits
int numents;
char maptitle[128];
uchar texlists[3][256];
int waterlevel;
int reserved[15];
};
c_sqr *world;
int ssize;
int x0, x1, y0, y1, z0, z1;
c_sqr *o[4];
int lastremip;
int progress;
void create_ent(c_persistent_entity &ce)
{
if(ce.type>=7) ce.type++; // grenade ammo
if(ce.type>=8) ce.type++; // pistol ammo
if(ce.type==16) ce.type = ET_MAPMODEL;
else if(ce.type>=ET_MAPMODEL && ce.type<16) ce.type++;
if(ce.type>=ET_ENVMAP) ce.type++;
if(ce.type>=ET_PARTICLES) ce.type++;
if(ce.type>=ET_SOUND) ce.type++;
if(ce.type>=ET_SPOTLIGHT) ce.type++;
extentity &e = *entities::newentity();
entities::getents().add(&e);
e.type = ce.type;
e.spawned = false;
e.inoctanode = false;
e.o = vec(ce.x*4+worldsize/4, ce.y*4+worldsize/4, ce.z*4+worldsize/2);
e.light.color = vec(1, 1, 1);
e.light.dir = vec(0, 0, 1);
e.attr1 = ce.attr1;
e.attr2 = ce.attr2;
switch(e.type)
{
case ET_MAPMODEL:
e.o.z += ce.attr3*4;
e.attr3 = e.attr4 = 0;
break;
case ET_LIGHT:
e.attr1 *= 4;
if(!ce.attr3 && !ce.attr4) { e.attr3 = e.attr4 = e.attr2; break; }
// fall through
default:
e.attr3 = ce.attr3;
e.attr4 = ce.attr4;
break;
}
switch(e.type)
{
case ET_PLAYERSTART:
case ET_MAPMODEL:
case ET_GAMESPECIFIC+12: // teleport
case ET_GAMESPECIFIC+13: // monster
e.attr1 = (int(e.attr1)+180)%360;
break;
}
e.attr5 = 0;
}
cube &getcube(int x, int y, int z)
{
return lookupcube(x*4+worldsize/4, y*4+worldsize/4, z*4+worldsize/2, 4);
}
int neighbours(c_sqr &t)
{
o[0] = &t;
o[1] = &t+1;
o[2] = &t+ssize;
o[3] = &t+ssize+1;
int best = 0xFFFF;
loopi(4) if(o[i]->vdelta<best) best = o[i]->vdelta;
return best;
}
void preprocess_cubes() // pull up heighfields to where they don't cross cube boundaries
{
for(;;)
{
bool changed = false;
loop(x, ssize)
{
loop(y, ssize)
{
c_sqr &t = world[x+y*ssize];
if(t.type==C_FHF || t.type==C_CHF)
{
int bottom = (neighbours(t)&(~3))+4;
loopj(4) if(o[j]->vdelta>bottom) { o[j]->vdelta = bottom; changed = true; }
}
}
}
if(!changed) break;
}
}
int getfloorceil(c_sqr &s, int &floor, int &ceil)
{
floor = s.floor;
ceil = s.ceil;
int cap = 0;
switch(s.type)
{
case C_SOLID: floor = ceil; break;
case C_FHF: floor -= (cap = neighbours(s)&(~3))/4; break;
case C_CHF: ceil += (cap = neighbours(s)&(~3))/4; break;
}
return cap;
}
void boundingbox()
{
x0 = y0 = ssize;
x1 = y1 = 0;
z0 = 128;
z1 = -128;
loop(x, ssize) loop(y, ssize)
{
c_sqr &t = world[x+y*ssize];
if(t.type!=C_SOLID)
{
if(x<x0) x0 = x;
if(y<y0) y0 = y;
if(x>x1) x1 = x;
if(y>y1) y1 = y;
int floor, ceil;
getfloorceil(t, floor, ceil);
if(floor<z0) z0 = floor;
if(ceil>z1) z1 = ceil;
}
}
}
void hf(int x, int y, int z, int side, int dir, int cap)
{
cube &c = getcube(x, y, z);
loopi(2) loopj(2) edgeset(cubeedge(c, 2, i, j), side, dir*(o[(j<<1)+i]->vdelta-cap)*2+side*8);
}
bool cornersolid(int z, c_sqr *s) { return s->type==C_SOLID || z<s->floor || z>=s->ceil; }
void createcorner(cube &c, int lstart, int lend, int rstart, int rend)
{
int ledge = edgemake(lstart, lend);
int redge = edgemake(rstart, rend);
cubeedge(c, 1, 0, 0) = ledge;
cubeedge(c, 1, 1, 0) = ledge;
cubeedge(c, 1, 0, 1) = redge;
cubeedge(c, 1, 1, 1) = redge;
}
void create_cubes()
{
preprocess_cubes();
boundingbox();
lastremip = allocnodes;
progress = 0;
for(int x = x0-1; x<=x1+1; x++) for(int y = y0-1; y<=y1+1; y++)
{
c_sqr &s = world[x+y*ssize];
int floor, ceil, cap = getfloorceil(s, floor, ceil);
for(int z = z0-1; z<=z1+1; z++)
{
cube &c = getcube(x, y, z);
c.texture[O_LEFT] = c.texture[O_RIGHT] = c.texture[O_BACK] = c.texture[O_FRONT] = s.type!=C_SOLID && z<ceil ? s.wtex : s.utex;
c.texture[O_BOTTOM] = s.ctex;
c.texture[O_TOP] = s.ftex;
if(z>=floor && z<ceil)
{
setfaces(c, F_EMPTY);
}
else if(s.type==C_CORNER)
{
c_sqr *ts, *bs, *ls, *rs;
bool tc = cornersolid(z, ts = &s-ssize);
bool bc = cornersolid(z, bs = &s+ssize);
bool lc = cornersolid(z, ls = &s-1);
bool rc = cornersolid(z, rs = &s+1);
if (tc && lc && !bc && !rc) createcorner(c, 0, 8, 0, 0); // TOP LEFT
else if(tc && !lc && !bc && rc) createcorner(c, 0, 0, 0, 8); // TOP RIGHT
else if(!tc && lc && bc && !rc) createcorner(c, 0, 8, 8, 8); // BOT LEFT
else if(!tc && !lc && bc && rc) createcorner(c, 8, 8, 0, 8); // BOT RIGHT
else // fix texture on ground of a corner
{
if (ts->floor-1==z && bs->floor-1!=z) { c.texture[O_TOP] = ts->ftex; }
else if (ts->floor-1!=z && bs->floor-1==z) { c.texture[O_TOP] = bs->ftex; }
if (ts->ceil==z && bs->ceil!=z) { c.texture[O_BOTTOM] = ts->ctex; }
else if (ts->ceil!=z && bs->ceil==z) { c.texture[O_BOTTOM] = bs->ctex; }
}
}
}
switch(s.type)
{
case C_FHF: hf(x, y, floor-1, 1, -1, cap); break;
case C_CHF: hf(x, y, ceil, 0, 1, cap); break;
}
if(importcuberemip && (allocnodes - lastremip) * 8 > importcuberemip * 1024)
{
mpremip(true);
lastremip = allocnodes;
}
if((progress++&0x7F)==0)
{
float bar = float((y1-y0+2)*(x-x0+1) + y-y0+1) / float((y1-y0+2)*(x1-x0+2));
defformatstring(text)("creating cubes... %d%%", int(bar*100));
renderprogress(bar, text);
}
}
}
void load_cube_world(char *mname)
{
int loadingstart = SDL_GetTicks();
string pakname, cgzname;
formatstring(pakname)("cube/%s", mname);
formatstring(cgzname)("packages/%s.cgz", pakname);
stream *f = opengzfile(path(cgzname), "rb");
if(!f) { conoutf(CON_ERROR, "could not read cube map %s", cgzname); return; }
c_header hdr;
f->read(&hdr, sizeof(c_header)-sizeof(int)*16);
lilswap(&hdr.version, 4);
bool mod = false;
if(strncmp(hdr.head, "CUBE", 4))
{
if(!strncmp(hdr.head, "ACMP", 4)) mod = true;
else
{
conoutf(CON_ERROR, "map %s has malformatted header", cgzname);
delete f;
return;
}
}
else if(hdr.version>5) mod = true;
if(hdr.version>5 && !mod) { conoutf(CON_ERROR, "map %s requires a newer version of the Cube 1 importer", cgzname); delete f; return; }
if(!haslocalclients()) game::forceedit("");
emptymap(12, true, NULL);
freeocta(worldroot);
worldroot = newcubes(F_SOLID);
defformatstring(cs)("importing %s", cgzname);
renderbackground(cs);
if(hdr.version>=4)
{
f->read(&hdr.waterlevel, sizeof(int)*16);
lilswap(&hdr.waterlevel, 16);
}
else
{
hdr.waterlevel = -100000;
}
if(mod) f->seek(hdr.numents*sizeof(c_persistent_entity), SEEK_CUR);
else loopi(hdr.numents)
{
c_persistent_entity e;
f->read(&e, sizeof(c_persistent_entity));
lilswap(&e.x, 4);
if(i < MAXENTS) create_ent(e);
}
ssize = 1<<hdr.sfactor;
world = new c_sqr[ssize*ssize];
c_sqr *t = NULL;
loopk(ssize*ssize)
{
c_sqr *s = &world[k];
int type = f->getchar();
switch(type)
{
case 255:
{
int n = f->getchar();
for(int i = 0; i<n; i++, k++) memcpy(&world[k], t, sizeof(c_sqr));
k--;
break;
}
case 254: // only in MAPVERSION<=2
{
memcpy(s, t, sizeof(c_sqr));
f->getchar();
f->getchar();
break;
}
case C_SOLID:
{
s->type = C_SOLID;
s->wtex = f->getchar();
s->vdelta = f->getchar();
if(hdr.version<=2) { f->getchar(); f->getchar(); }
s->ftex = DEFAULT_FLOOR;
s->ctex = DEFAULT_CEIL;
s->utex = s->wtex;
s->floor = 0;
s->ceil = 16;
break;
}
default:
{
if(type<0 || type>=C_MAXTYPE)
{
defformatstring(t)("%d @ %d", type, k);
fatal("while reading map: type out of range: ", t);
}
s->type = type;
s->floor = f->getchar();
s->ceil = f->getchar();
if(s->floor>=s->ceil) s->floor = s->ceil-1; // for pre 12_13
s->wtex = f->getchar();
s->ftex = f->getchar();
s->ctex = f->getchar();
if(hdr.version<=2) { f->getchar(); f->getchar(); }
s->vdelta = f->getchar();
s->utex = (hdr.version>=2) ? f->getchar() : s->wtex;
if(hdr.version>=5) f->getchar();
s->type = type;
}
}
t = s;
}
delete f;
string cfgname;
formatstring(cfgname)("packages/cube/%s.cfg", mname);
overrideidents = true;
execfile("packages/cube/package.cfg");
execfile(path(cfgname));
overrideidents = false;
create_cubes();
mpremip(true);
clearlights();
allchanged();
loopv(entities::getents()) if(entities::getents()[i]->type!=ET_LIGHT) dropenttofloor(entities::getents()[i]);
entitiesinoctanodes();
conoutf("read cube map %s (%.1f seconds)", cgzname, (SDL_GetTicks()-loadingstart)/1000.0f);
startmap(NULL);
}
};
void importcube(char *name)
{
if(multiplayer()) return;
cubeloader().load_cube_world(name);
}
COMMAND(importcube, "s");
|
//=================================================================================================
/*!
// \file src/mathtest/dmatsmatschur/LDbMIa.cpp
// \brief Source file for the LDbMIa dense matrix/sparse matrix Schur product math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/IdentityMatrix.h>
#include <blaze/math/LowerMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatsmatschur/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'LDbMIa'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::LowerMatrix< blaze::DynamicMatrix<TypeB> > LDb;
typedef blaze::IdentityMatrix<TypeA> MIa;
// Creator type definitions
typedef blazetest::Creator<LDb> CLDb;
typedef blazetest::Creator<MIa> CMIa;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
RUN_DMATSMATSCHUR_OPERATION_TEST( CLDb( i ), CMIa( i ) );
}
// Running tests with large matrices
RUN_DMATSMATSCHUR_OPERATION_TEST( CLDb( 67UL ), CMIa( 67UL ) );
RUN_DMATSMATSCHUR_OPERATION_TEST( CLDb( 128UL ), CMIa( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix Schur product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
#ifndef liborangepower_containers_vec3_classes_hpp
#define liborangepower_containers_vec3_classes_hpp
#include "../gen_class_innards_defines.hpp"
#include "vec2_classes.hpp"
namespace liborangepower
{
namespace containers
{
template<typename Type>
class Vec3
{
public: // variables
Type x, y, z;
public: // functions
//--------
inline Vec3() = default;
inline Vec3(const Type& s_x, const Type& s_y, const Type& s_z)
: x(s_x), y(s_y), z(s_z)
{
}
GEN_CM_BOTH_CONSTRUCTORS_AND_ASSIGN(Vec3);
virtual inline ~Vec3() = default;
//--------
template<typename OtherType>
inline Vec3 operator + (const Vec3<OtherType>& other) const
{
return Vec3<Type>(x + other.x, y + other.y, z + other.z);
}
template<typename OtherType>
inline Vec3& operator += (const Vec3<OtherType>& other) const
{
*this = (*this) + other;
return *this;
}
template<typename OtherType>
inline Vec3 operator - (const Vec3<OtherType>& other) const
{
return Vec3<Type>(x - other.x, y - other.y, z - other.z);
}
template<typename OtherType>
inline Vec3& operator -= (const Vec3<OtherType>& other) const
{
*this = (*this) - other;
return *this;
}
inline Vec3 operator - () const
{
return Vec3(-x, -y, -z);
}
template<typename OtherType>
inline Vec3 operator * (const OtherType& scale) const
{
return Vec3(x * scale, y * scale, z * scale);
}
template<typename OtherType>
inline Vec3& operator *= (const OtherType& other) const
{
*this = (*this) * other;
return *this;
}
template<typename OtherType>
inline Vec3 operator / (const OtherType& scale) const
{
return Vec3<Type>(x / scale, y / scale, z / scale);
}
template<typename OtherType>
inline Vec3& operator /= (const OtherType& scale) const
{
*this = (*this) / scale;
return *this;
}
//--------
// Dot product
template<typename OtherType>
inline Type dot_prod(const Vec3<OtherType>& other) const
{
return ((x * other.x) + (y * other.y) + (z * other.z));
}
// Cross product
template<typename OtherType>
inline Vec3 cross_prod(const Vec3<OtherType>& other) const
{
return Vec3<Type>((y * other.z) - (z * other.y),
(z * other.x) - (x * other.z),
(x * other.y) - (y * other.x));
}
inline Type norm() const
{
return std::sqrt(dot_prod(*this));
}
//--------
template<typename OtherType>
inline bool operator == (const Vec3<OtherType>& other) const
{
return ((x == other.x) && (y == other.y) && (z == other.z));
}
template<typename OtherType>
inline bool operator != (const Vec3<OtherType>& other) const
{
return (!((*this) == other));
}
template<typename OtherType>
inline bool operator < (const Vec3<OtherType>& other) const
{
return ((z < other.z)
|| ((z == other.z) && (Vec2(x, y) < Vec2(other.x, other.y))));
}
template<typename OtherType>
inline bool operator > (const Vec3<OtherType>& other) const
{
return ((z > other.z)
|| ((z == other.z) && (Vec2(x, y) > Vec2(other.x, other.y))));
}
template<typename OtherType>
inline bool operator <= (const Vec3<OtherType>& other) const
{
return (!((*this) > other));
}
template<typename OtherType>
inline bool operator >= (const Vec3<OtherType>& other) const
{
return (!((*this) < other));
}
//--------
};
} // namespace containers
} // namespace liborangepower
#endif // liborangepower_containers_vec3_classes_hpp
|
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.00.23506.0
include listing.inc
INCLUDELIB MSVCRT
INCLUDELIB OLDNAMES
PUBLIC __local_stdio_printf_options
PUBLIC _vfprintf_l
PUBLIC printf
PUBLIC func
PUBLIC main
EXTRN __imp___acrt_iob_func:PROC
EXTRN __imp___stdio_common_vfprintf:PROC
EXTRN gets:PROC
EXTRN __GSHandlerCheck:PROC
EXTRN __security_check_cookie:PROC
EXTRN __security_cookie:QWORD
_DATA SEGMENT
COMM ?_OptionsStorage@?1??__local_stdio_printf_options@@9@9:QWORD ; `__local_stdio_printf_options'::`2'::_OptionsStorage
_DATA ENDS
; COMDAT pdata
pdata SEGMENT
$pdata$_vfprintf_l DD imagerel $LN4
DD imagerel $LN4+81
DD imagerel $unwind$_vfprintf_l
pdata ENDS
; COMDAT pdata
pdata SEGMENT
$pdata$printf DD imagerel $LN4
DD imagerel $LN4+66
DD imagerel $unwind$printf
pdata ENDS
; COMDAT pdata
pdata SEGMENT
$pdata$func DD imagerel $LN4
DD imagerel $LN4+83
DD imagerel $unwind$func
pdata ENDS
; COMDAT pdata
pdata SEGMENT
$pdata$main DD imagerel $LN4
DD imagerel $LN4+94
DD imagerel $unwind$main
pdata ENDS
; COMDAT xdata
xdata SEGMENT
$unwind$main DD 010401H
DD 0c204H
xdata ENDS
; COMDAT xdata
xdata SEGMENT
$unwind$func DD 021519H
DD 030025206H
DD imagerel __GSHandlerCheck
DD 028H
xdata ENDS
; COMDAT xdata
xdata SEGMENT
$unwind$printf DD 021901H
DD 030153219H
xdata ENDS
; COMDAT xdata
xdata SEGMENT
$unwind$_vfprintf_l DD 081401H
DD 0a6414H
DD 095414H
DD 083414H
DD 070105214H
xdata ENDS
; Function compile flags: /Ogtp
; File d:\projects\taintanalysis\antitaint\epilog\src\func-rets.c
; COMDAT main
_TEXT SEGMENT
b$2$ = 32
$T1 = 32
a$2$ = 56
$T2 = 72
$T3 = 72
b$ = 72
main PROC ; COMDAT
; 25 : {
$LN4:
sub rsp, 104 ; 00000068H
; 26 : struct S a,b,c;
; 27 : int z = 0;
; 28 : a = func();
lea rcx, QWORD PTR $T1[rsp]
call func
; 29 : z += a.a;
; 30 : b = func();
lea rcx, QWORD PTR $T3[rsp]
movups xmm0, XMMWORD PTR [rax]
movups XMMWORD PTR a$2$[rsp], xmm0
call func
; 31 : c = func();
lea rcx, QWORD PTR $T2[rsp]
movups xmm0, XMMWORD PTR [rax]
mov eax, DWORD PTR [rax+16]
mov DWORD PTR b$[rsp+16], eax
movups XMMWORD PTR b$2$[rsp], xmm0
call func
; 32 : z += c.c + b.b;
movups xmm0, XMMWORD PTR b$2$[rsp]
movups xmm1, XMMWORD PTR [rax]
psrldq xmm0, 4
psrldq xmm1, 8
movd eax, xmm1
movd ecx, xmm0
add eax, ecx
add eax, DWORD PTR a$2$[rsp]
; 33 : return z;
; 34 : }
add rsp, 104 ; 00000068H
ret 0
main ENDP
_TEXT ENDS
; Function compile flags: /Ogtp
; File d:\projects\taintanalysis\antitaint\epilog\src\func-rets.c
; COMDAT func
_TEXT SEGMENT
buf$ = 32
__$ArrayPad$ = 40
$T1 = 64
func PROC ; COMDAT
; 15 : {
$LN4:
push rbx
sub rsp, 48 ; 00000030H
mov rax, QWORD PTR __security_cookie
xor rax, rsp
mov QWORD PTR __$ArrayPad$[rsp], rax
mov rbx, rcx
; 16 : char buf[8];
; 17 : struct S s;
; 18 : s.a = (int)gets(buf) - (int)buf;
lea rcx, QWORD PTR buf$[rsp]
call gets
lea rcx, QWORD PTR buf$[rsp]
sub eax, ecx
; 19 : s.b = printf(buf);
lea rcx, QWORD PTR buf$[rsp]
mov DWORD PTR [rbx], eax
call printf
mov DWORD PTR [rbx+4], eax
; 20 : s.c = s.a + s.b;
add eax, DWORD PTR [rbx]
mov DWORD PTR [rbx+8], eax
; 21 : return s;
mov rax, rbx
; 22 : }
mov rcx, QWORD PTR __$ArrayPad$[rsp]
xor rcx, rsp
call __security_check_cookie
add rsp, 48 ; 00000030H
pop rbx
ret 0
func ENDP
_TEXT ENDS
; Function compile flags: /Ogtp
; File c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\stdio.h
; COMDAT printf
_TEXT SEGMENT
_Format$ = 48
printf PROC ; COMDAT
; 950 : {
$LN4:
mov QWORD PTR [rsp+8], rcx
mov QWORD PTR [rsp+16], rdx
mov QWORD PTR [rsp+24], r8
mov QWORD PTR [rsp+32], r9
push rbx
sub rsp, 32 ; 00000020H
; 951 : int _Result;
; 952 : va_list _ArgList;
; 953 : __crt_va_start(_ArgList, _Format);
; 954 : _Result = _vfprintf_l(stdout, _Format, NULL, _ArgList);
mov ecx, 1
lea rbx, QWORD PTR _Format$[rsp+8]
call QWORD PTR __imp___acrt_iob_func
mov rdx, QWORD PTR _Format$[rsp]
mov r9, rbx
mov rcx, rax
xor r8d, r8d
call _vfprintf_l
; 955 : __crt_va_end(_ArgList);
; 956 : return _Result;
; 957 : }
add rsp, 32 ; 00000020H
pop rbx
ret 0
printf ENDP
_TEXT ENDS
; Function compile flags: /Ogtp
; File c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\stdio.h
; COMDAT _vfprintf_l
_TEXT SEGMENT
_Stream$ = 64
_Format$ = 72
_Locale$ = 80
_ArgList$ = 88
_vfprintf_l PROC ; COMDAT
; 638 : {
$LN4:
mov QWORD PTR [rsp+8], rbx
mov QWORD PTR [rsp+16], rbp
mov QWORD PTR [rsp+24], rsi
push rdi
sub rsp, 48 ; 00000030H
mov rbx, r9
mov rdi, r8
mov rsi, rdx
mov rbp, rcx
; 639 : return __stdio_common_vfprintf(_CRT_INTERNAL_LOCAL_PRINTF_OPTIONS, _Stream, _Format, _Locale, _ArgList);
call __local_stdio_printf_options
mov r9, rdi
mov QWORD PTR [rsp+32], rbx
mov r8, rsi
mov rdx, rbp
mov rcx, QWORD PTR [rax]
call QWORD PTR __imp___stdio_common_vfprintf
; 640 : }
mov rbx, QWORD PTR [rsp+64]
mov rbp, QWORD PTR [rsp+72]
mov rsi, QWORD PTR [rsp+80]
add rsp, 48 ; 00000030H
pop rdi
ret 0
_vfprintf_l ENDP
_TEXT ENDS
; Function compile flags: /Ogtp
; File c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\corecrt_stdio_config.h
; COMDAT __local_stdio_printf_options
_TEXT SEGMENT
__local_stdio_printf_options PROC ; COMDAT
; 74 : static unsigned __int64 _OptionsStorage;
; 75 : return &_OptionsStorage;
lea rax, OFFSET FLAT:?_OptionsStorage@?1??__local_stdio_printf_options@@9@9 ; `__local_stdio_printf_options'::`2'::_OptionsStorage
; 76 : }
ret 0
__local_stdio_printf_options ENDP
_TEXT ENDS
END
|
db DEX_JIGGLYPUFF ; pokedex id
db 115, 45, 20, 20, 25
; hp atk def spd spc
db SOUND, SOUND ; type
db 170 ; catch rate
db 76 ; base exp
INCBIN "gfx/pokemon/front/jigglypuff.pic", 0, 1 ; sprite dimensions
dw JigglypuffPicFront, JigglypuffPicBack
db SING, NO_MOVE, NO_MOVE, NO_MOVE ; level 1 learnset
db GROWTH_FAST ; growth rate
; tm/hm learnset
tmhm MEGA_PUNCH, MEGA_KICK, TOXIC, BODY_SLAM, TAKE_DOWN, \
DOUBLE_EDGE, BUBBLEBEAM, WATER_GUN, ICE_BEAM, BLIZZARD, \
SUBMISSION, COUNTER, SEISMIC_TOSS, RAGE, SOLARBEAM, \
THUNDERBOLT, THUNDER, PSYCHIC_M, TELEPORT, MIMIC, \
DOUBLE_TEAM, REFLECT, BIDE, FIRE_BLAST, SKULL_BASH, \
REST, THUNDER_WAVE, PSYWAVE, TRI_ATTACK, SUBSTITUTE, \
STRENGTH, FLASH
; end
db 0 ; padding
|
; A152835: a(0) = -22; a(n) = n-a(n-1).
; Submitted by Jamie Morken(s2.)
; -22,23,-21,24,-20,25,-19,26,-18,27,-17,28,-16,29,-15,30,-14,31,-13,32,-12,33,-11,34,-10,35,-9,36,-8,37,-7,38,-6,39,-5,40,-4,41,-3,42,-2,43,-1,44,0,45,1,46,2,47,3,48,4,49,5,50,6,51,7,52,8,53,9,54,10,55,11,56,12,57,13,58,14,59,15,60,16,61,17,62,18,63,19,64,20,65,21,66,22,67,23,68,24,69,25,70,26,71,27,72
mov $1,$0
mod $0,2
sub $0,24
add $1,2
div $1,2
mov $2,-2
bin $2,$0
sub $1,$2
mov $0,$1
|
; $Id: bs3-mode-PagingGetRootForLM64.asm 69111 2017-10-17 14:26:02Z vboxsync $
;; @file
; BS3Kit - Bs3PagingGetRootForLM64
;
;
; Copyright (C) 2007-2017 Oracle Corporation
;
; This file is part of VirtualBox Open Source Edition (OSE), as
; available from http://www.virtualbox.org. This file is free software;
; you can redistribute it and/or modify it under the terms of the GNU
; General Public License (GPL) as published by the Free Software
; Foundation, in version 2 as it comes in the "COPYING" file of the
; VirtualBox OSE distribution. VirtualBox OSE is distributed in the
; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
;
; The contents of this file may alternatively be used under the terms
; of the Common Development and Distribution License Version 1.0
; (CDDL) only, as it comes in the "COPYING.CDDL" file of the
; VirtualBox OSE distribution, in which case the provisions of the
; CDDL are applicable instead of those of the GPL.
;
; You may elect to license modified versions of this file under the
; terms and conditions of either the GPL or the CDDL or both.
;
%include "bs3kit-template-header.mac"
%ifdef TMPL_RM
extern TMPL_NM(Bs3SwitchToPE16)
extern NAME(Bs3SwitchToRM_pe16)
%elifdef TMPL_CMN_V86
extern TMPL_NM(Bs3SwitchToRing0)
extern TMPL_NM(Bs3SwitchTo16BitV86)
%endif
BS3_EXTERN_CMN Bs3PagingInitRootForLM
BS3_EXTERN_DATA16 g_PhysPagingRootLM
TMPL_BEGIN_TEXT
;;
; @cproto BS3_DECL(uint32_t) Bs3PagingGetRootForLM64(void)
;
; @returns eax
;
; @uses ax
;
; @remarks returns value in EAX, not dx:ax!
;
BS3_PROC_BEGIN_MODE Bs3PagingGetRootForLM64, BS3_PBC_NEAR ; Internal function, no far variant necessary.
mov eax, [BS3_DATA16_WRT(g_PhysPagingRootLM)]
cmp eax, 0ffffffffh
je .init_root
%ifdef BS3_STRICT
.return:
cmp eax, 1000h
jnb .cr3_ok_low
hlt
.cr3_ok_low:
cmp eax, 16*_1M
jb .cr3_ok_high
hlt
.cr3_ok_high:
%endif
ret
.init_root:
push xBP
mov xBP, xSP
BONLY16 push es
push sDX
push sCX
push sBX
%if TMPL_BITS == 64
push r8
push r9
push r10
push r11
%endif
%ifdef TMPL_RM
;
; We don't want to be restricted to real mode addressing, so
; temporarily switch to 16-bit protected mode.
;
call TMPL_NM(Bs3SwitchToPE16)
call Bs3PagingInitRootForLM
call NAME(Bs3SwitchToRM_pe16)
%elifdef TMPL_CMN_V86
;
; V8086 mode uses real mode addressing too. Unlikly that we'll
; ever end up here though.
;
call TMPL_NM(Bs3SwitchToRing0)
call Bs3PagingInitRootForLM
call TMPL_NM(Bs3SwitchTo16BitV86)
%else
;
; Not a problematic addressing mode.
;
BONLY64 sub rsp, 20h
BS3_CALL Bs3PagingInitRootForLM, 0
BONLY64 add rsp, 20h
%endif
;
; Load the value and return.
;
mov eax, [BS3_DATA16_WRT(g_PhysPagingRootLM)]
%if TMPL_BITS == 64
pop r11
pop r10
pop r9
pop r8
%endif
pop sBX
pop sCX
pop sDX
BONLY16 pop es
leave
%ifdef BS3_STRICT
jmp .return
%else
ret
%endif
BS3_PROC_END_MODE Bs3PagingGetRootForLM64
|
/* libgcc routines for M68HC11 & M68HC12.
Copyright (C) 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.
In addition to the permissions in the GNU General Public License, the
Free Software Foundation gives you unlimited permission to link the
compiled version of this file with other programs, and to distribute
those programs without any restriction coming from the use of this
file. (The General Public License restrictions do apply in other
respects; for example, they cover modification of the file, and
distribution when not linked into another program.)
This file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA. */
/* As a special exception, if you link this library with other files,
some of which are compiled with GCC, to produce an executable,
this library does not by itself cause the resulting executable
to be covered by the GNU General Public License.
This exception does not however invalidate any other reasons why
the executable file might be covered by the GNU General Public License. */
.file "larith.asm"
#ifdef __HAVE_SHORT_INT__
.mode mshort
#else
.mode mlong
#endif
.macro declare_near name
.globl \name
.type \name,@function
.size \name,.Lend-\name
\name:
.endm
#if defined(__USE_RTC__)
# define ARG(N) N+1
.macro ret
#if defined(mc68hc12)
rtc
#else
jmp __return_32
#endif
.endm
.macro declare name
.globl \name
.type \name,@function
.size \name,.Lend-\name
.far \name
\name:
.endm
.macro farsym name
.far NAME
.endm
#else
# define ARG(N) N
.macro ret
rts
.endm
.macro farsym name
.endm
.macro declare name
.globl \name
.type \name,@function
.size \name,.Lend-\name
\name:
.endm
#endif
.sect .text
#define REG(NAME) \
NAME: .dc.w 1; \
.type NAME,@object ; \
.size NAME,2
#ifdef L_regs_min
/* Pseudo hard registers used by gcc.
They should be located in page0. */
.sect .softregs
.globl _.tmp
.globl _.z,_.xy
REG(_.tmp)
REG(_.z)
REG(_.xy)
#endif
#ifdef L_regs_frame
.sect .softregs
.globl _.frame
REG(_.frame)
#endif
#ifdef L_regs_d1_2
.sect .softregs
.globl _.d1,_.d2
REG(_.d1)
REG(_.d2)
#endif
#ifdef L_regs_d3_4
.sect .softregs
.globl _.d3,_.d4
REG(_.d3)
REG(_.d4)
#endif
#ifdef L_regs_d5_6
.sect .softregs
.globl _.d5,_.d6
REG(_.d5)
REG(_.d6)
#endif
#ifdef L_regs_d7_8
.sect .softregs
.globl _.d7,_.d8
REG(_.d7)
REG(_.d8)
#endif
#ifdef L_regs_d9_16
/* Pseudo hard registers used by gcc.
They should be located in page0. */
.sect .softregs
.globl _.d9,_.d10,_.d11,_.d12,_.d13,_.d14
.globl _.d15,_.d16
REG(_.d9)
REG(_.d10)
REG(_.d11)
REG(_.d12)
REG(_.d13)
REG(_.d14)
REG(_.d15)
REG(_.d16)
#endif
#ifdef L_regs_d17_32
/* Pseudo hard registers used by gcc.
They should be located in page0. */
.sect .softregs
.globl _.d17,_.d18,_.d19,_.d20,_.d21,_.d22
.globl _.d23,_.d24,_.d25,_.d26,_.d27,_.d28
.globl _.d29,_.d30,_.d31,_.d32
REG(_.d17)
REG(_.d18)
REG(_.d19)
REG(_.d20)
REG(_.d21)
REG(_.d22)
REG(_.d23)
REG(_.d24)
REG(_.d25)
REG(_.d26)
REG(_.d27)
REG(_.d28)
REG(_.d29)
REG(_.d30)
REG(_.d31)
REG(_.d32)
#endif
#ifdef L_premain
;;
;; Specific initialization for 68hc11 before the main.
;; Nothing special for a generic routine; Just enable interrupts.
;;
declare_near __premain
clra
tap ; Clear both I and X.
rts
#endif
#ifdef L__exit
;;
;; Exit operation. Just loop forever and wait for interrupts.
;; (no other place to go)
;; This operation is split in several pieces collected together by
;; the linker script. This allows to support destructors at the
;; exit stage while not impacting program sizes when there is no
;; destructors.
;;
;; _exit:
;; *(.fini0) /* Beginning of finish code (_exit symbol). */
;; *(.fini1) /* Place holder for applications. */
;; *(.fini2) /* C++ destructors. */
;; *(.fini3) /* Place holder for applications. */
;; *(.fini4) /* Runtime exit. */
;;
.sect .fini0,"ax",@progbits
.globl _exit
.globl exit
.weak exit
farsym exit
farsym _exit
exit:
_exit:
.sect .fini4,"ax",@progbits
fatal:
cli
wai
bra fatal
#endif
#ifdef L_abort
;;
;; Abort operation. This is defined for the GCC testsuite.
;;
declare abort
ldd #255 ;
#ifdef mc68hc12
trap #0x30
#else
.byte 0xCD ; Generate an illegal instruction trap
.byte 0x03 ; The simulator catches this and stops.
#endif
jmp _exit
#endif
#ifdef L_cleanup
;;
;; Cleanup operation used by exit().
;;
declare _cleanup
ret
#endif
;-----------------------------------------
; required gcclib code
;-----------------------------------------
#ifdef L_memcpy
declare memcpy
declare __memcpy
.weak memcpy
;;;
;;; void* memcpy(void*, const void*, size_t)
;;;
;;; D = dst Pmode
;;; 2,sp = src Pmode
;;; 4,sp = size HImode (size_t)
;;;
#ifdef mc68hc12
ldx ARG(2),sp
ldy ARG(4),sp
pshd
xgdy
lsrd
bcc Start
movb 1,x+,1,y+
Start:
beq Done
Loop:
movw 2,x+,2,y+
dbne d,Loop
Done:
puld
ret
#else
xgdy
tsx
ldd ARG(4),x
ldx ARG(2),x ; SRC = X, DST = Y
cpd #0
beq End
pshy
inca ; Correction for the deca below
L0:
psha ; Save high-counter part
L1:
ldaa 0,x ; Copy up to 256 bytes
staa 0,y
inx
iny
decb
bne L1
pula
deca
bne L0
puly ; Restore Y to return the DST
End:
xgdy
ret
#endif
#endif
#ifdef L_memset
declare memset
declare __memset
;;;
;;; void* memset(void*, int value, size_t)
;;;
#ifndef __HAVE_SHORT_INT__
;;; D = dst Pmode
;;; 2,sp = src SImode
;;; 6,sp = size HImode (size_t)
val = ARG(5)
size = ARG(6)
#else
;;; D = dst Pmode
;;; 2,sp = src SImode
;;; 6,sp = size HImode (size_t)
val = ARG(3)
size = ARG(4)
#endif
#ifdef mc68hc12
xgdx
ldab val,sp
ldy size,sp
pshx
beq End
Loop:
stab 1,x+
dbne y,Loop
End:
puld
ret
#else
xgdx
tsy
ldab val,y
ldy size,y ; DST = X, CNT = Y
beq End
pshx
L0:
stab 0,x ; Fill up to 256 bytes
inx
dey
bne L0
pulx ; Restore X to return the DST
End:
xgdx
ret
#endif
#endif
#ifdef L_adddi3
declare ___adddi3
tsx
xgdy
ldd ARG(8),x ; Add LSB
addd ARG(16),x
std 6,y ; Save (carry preserved)
ldd ARG(6),x
adcb ARG(15),x
adca ARG(14),x
std 4,y
ldd ARG(4),x
adcb ARG(13),x
adca ARG(12),x
std 2,y
ldd ARG(2),x
adcb ARG(11),x ; Add MSB
adca ARG(10),x
std 0,y
xgdy
ret
#endif
#ifdef L_subdi3
declare ___subdi3
tsx
xgdy
ldd ARG(8),x ; Subtract LSB
subd ARG(16),x
std 6,y ; Save, borrow preserved
ldd ARG(6),x
sbcb ARG(15),x
sbca ARG(14),x
std 4,y
ldd ARG(4),x
sbcb ARG(13),x
sbca ARG(12),x
std 2,y
ldd ARG(2),x ; Subtract MSB
sbcb ARG(11),x
sbca ARG(10),x
std 0,y
xgdy ;
ret
#endif
#ifdef L_notdi2
declare ___notdi2
tsy
xgdx
ldd ARG(8),y
coma
comb
std 6,x
ldd ARG(6),y
coma
comb
std 4,x
ldd ARG(4),y
coma
comb
std 2,x
ldd ARG(2),y
coma
comb
std 0,x
xgdx
ret
#endif
#ifdef L_negsi2
declare_near ___negsi2
comb
coma
xgdx
comb
coma
inx
xgdx
bne done
inx
done:
rts
#endif
#ifdef L_one_cmplsi2
declare_near ___one_cmplsi2
comb
coma
xgdx
comb
coma
xgdx
rts
#endif
#ifdef L_ashlsi3
declare_near ___ashlsi3
xgdy
clra
andb #0x1f
xgdy
beq Return
Loop:
lsld
xgdx
rolb
rola
xgdx
dey
bne Loop
Return:
rts
#endif
#ifdef L_ashrsi3
declare_near ___ashrsi3
xgdy
clra
andb #0x1f
xgdy
beq Return
Loop:
xgdx
asra
rorb
xgdx
rora
rorb
dey
bne Loop
Return:
rts
#endif
#ifdef L_lshrsi3
declare_near ___lshrsi3
xgdy
clra
andb #0x1f
xgdy
beq Return
Loop:
xgdx
lsrd
xgdx
rora
rorb
dey
bne Loop
Return:
rts
#endif
#ifdef L_lshrhi3
declare_near ___lshrhi3
cpx #16
bge Return_zero
cpx #0
beq Return
Loop:
lsrd
dex
bne Loop
Return:
rts
Return_zero:
clra
clrb
rts
#endif
#ifdef L_lshlhi3
declare_near ___lshlhi3
cpx #16
bge Return_zero
cpx #0
beq Return
Loop:
lsld
dex
bne Loop
Return:
rts
Return_zero:
clra
clrb
rts
#endif
#ifdef L_rotrhi3
declare_near ___rotrhi3
___rotrhi3:
xgdx
clra
andb #0x0f
xgdx
beq Return
Loop:
tap
rorb
rora
dex
bne Loop
Return:
rts
#endif
#ifdef L_rotlhi3
declare_near ___rotlhi3
___rotlhi3:
xgdx
clra
andb #0x0f
xgdx
beq Return
Loop:
asrb
rolb
rola
rolb
dex
bne Loop
Return:
rts
#endif
#ifdef L_ashrhi3
declare_near ___ashrhi3
cpx #16
bge Return_minus_1_or_zero
cpx #0
beq Return
Loop:
asra
rorb
dex
bne Loop
Return:
rts
Return_minus_1_or_zero:
clrb
tsta
bpl Return_zero
comb
Return_zero:
tba
rts
#endif
#ifdef L_ashrqi3
declare_near ___ashrqi3
cmpa #8
bge Return_minus_1_or_zero
tsta
beq Return
Loop:
asrb
deca
bne Loop
Return:
rts
Return_minus_1_or_zero:
clrb
tstb
bpl Return_zero
coma
Return_zero:
tab
rts
#endif
#ifdef L_lshlqi3
declare_near ___lshlqi3
cmpa #8
bge Return_zero
tsta
beq Return
Loop:
lslb
deca
bne Loop
Return:
rts
Return_zero:
clrb
rts
#endif
#ifdef L_divmodhi4
#ifndef mc68hc12
/* 68HC12 signed divisions are generated inline (idivs). */
declare_near __divmodhi4
;
;; D = numerator
;; X = denominator
;;
;; Result: D = D / X
;; X = D % X
;;
tsta
bpl Numerator_pos
comb ; D = -D <=> D = (~D) + 1
coma
xgdx
inx
tsta
bpl Numerator_neg_denominator_pos
Numerator_neg_denominator_neg:
comb ; X = -X
coma
addd #1
xgdx
idiv
coma
comb
xgdx ; Remainder <= 0 and result >= 0
inx
rts
Numerator_pos_denominator_pos:
xgdx
idiv
xgdx ; Both values are >= 0
rts
Numerator_pos:
xgdx
tsta
bpl Numerator_pos_denominator_pos
Numerator_pos_denominator_neg:
coma ; X = -X
comb
xgdx
inx
idiv
xgdx ; Remainder >= 0 but result <= 0
coma
comb
addd #1
rts
Numerator_neg_denominator_pos:
xgdx
idiv
coma ; One value is > 0 and the other < 0
comb ; Change the sign of result and remainder
xgdx
inx
coma
comb
addd #1
rts
#endif /* !mc68hc12 */
#endif
#ifdef L_mulqi3
declare_near ___mulqi3
;
; short __mulqi3(signed char a, signed char b);
;
; signed char a -> register A
; signed char b -> register B
;
; returns the signed result of A * B in register D.
;
tsta
bmi A_neg
tstb
bmi B_neg
mul
rts
B_neg:
negb
bra A_or_B_neg
A_neg:
nega
tstb
bmi AB_neg
A_or_B_neg:
mul
coma
comb
addd #1
rts
AB_neg:
negb
mul
rts
#endif
#ifdef L_mulhi3
declare_near ___mulhi3
;
;
; unsigned short ___mulhi3(unsigned short a, unsigned short b)
;
; a = register D
; b = register X
;
#ifdef mc68hc12
pshx ; Preserve X
exg x,y
emul
exg x,y
pulx
rts
#else
#ifdef NO_TMP
;
; 16-bit multiplication without temp memory location.
; (smaller but slower)
;
pshx ; (4)
ins ; (3)
pshb ; (3)
psha ; (3)
pshx ; (4)
pula ; (4)
pulx ; (5)
mul ; (10) B.high * A.low
xgdx ; (3)
mul ; (10) B.low * A.high
abx ; (3)
pula ; (4)
pulb ; (4)
mul ; (10) B.low * A.low
pshx ; (4)
tsx ; (3)
adda 1,x ; (4)
pulx ; (5)
rts ; (5) 20 bytes
; ---
; 91 cycles
#else
stx *_.tmp ; (4)
pshb ; (3)
ldab *_.tmp+1 ; (3)
mul ; (10) A.high * B.low
ldaa *_.tmp ; (3)
stab *_.tmp ; (3)
pulb ; (4)
pshb ; (4)
mul ; (10) A.low * B.high
addb *_.tmp ; (4)
stab *_.tmp ; (3)
ldaa *_.tmp+1 ; (3)
pulb ; (4)
mul ; (10) A.low * B.low
adda *_.tmp ; (4)
rts ; (5) 24/32 bytes
; 77/85 cycles
#endif
#endif
#endif
#ifdef L_mulhi32
;
;
; unsigned long __mulhi32(unsigned short a, unsigned short b)
;
; a = register D
; b = value on stack
;
; +---------------+
; | B low | <- 7,x
; +---------------+
; | B high | <- 6,x
; +---------------+
; | PC low |
; +---------------+
; | PC high |
; +---------------+
; | Tmp low |
; +---------------+
; | Tmp high |
; +---------------+
; | A low |
; +---------------+
; | A high |
; +---------------+ <- 0,x
;
;
; <B-low> 5,x
; <B-high> 4,x
; <ret> 2,x
; <A-low> 1,x
; <A-high> 0,x
;
declare_near __mulhi32
#ifdef mc68hc12
ldy 2,sp
emul
exg x,y
rts
#else
pshx ; Room for temp value
pshb
psha
tsx
ldab 6,x
mul
xgdy ; A.high * B.high
ldab 7,x
pula
mul ; A.high * B.low
std 2,x
ldaa 1,x
ldab 6,x
mul ; A.low * B.high
addd 2,x
stab 2,x
tab
aby
bcc N
ldab #0xff
aby
iny
N:
ldab 7,x
pula
mul ; A.low * B.low
adda 2,x
pulx ; Drop temp location
pshy ; Put high part in X
pulx
bcc Ret
inx
Ret:
rts
#endif
#endif
#ifdef L_mulsi3
;
; <B-low> 8,y
; <B-high> 6,y
; <ret> 4,y
; <tmp> 2,y
; <A-low> 0,y
;
; D,X -> A
; Stack -> B
;
; The result is:
;
; (((A.low * B.high) + (A.high * B.low)) << 16) + (A.low * B.low)
;
;
;
declare __mulsi3
#ifdef mc68hc12
pshd ; Save A.low
ldy ARG(4),sp
emul ; A.low * B.high
ldy ARG(6),sp
exg x,d
emul ; A.high * B.low
leax d,x
ldy ARG(6),sp
puld
emul ; A.low * B.low
exg d,y
leax d,x
exg d,y
ret
#else
B_low = ARG(8)
B_high = ARG(6)
A_low = 0
A_high = 2
pshx
pshb
psha
tsy
;
; If B.low is 0, optimize into: (A.low * B.high) << 16
;
ldd B_low,y
beq B_low_zero
;
; If A.high is 0, optimize into: (A.low * B.high) << 16 + (A.low * B.low)
;
cpx #0
beq A_high_zero
bsr ___mulhi3 ; A.high * B.low
;
; If A.low is 0, optimize into: (A.high * B.low) << 16
;
ldx A_low,y
beq A_low_zero ; X = 0, D = A.high * B.low
std 2,y
;
; If B.high is 0, we can avoid the (A.low * B.high) << 16 term.
;
ldd B_high,y
beq B_high_zero
bsr ___mulhi3 ; A.low * B.high
addd 2,y
std 2,y
;
; Here, we know that A.low and B.low are not 0.
;
B_high_zero:
ldd B_low,y ; A.low is on the stack
bsr __mulhi32 ; A.low * B.low
xgdx
tsy ; Y was clobbered, get it back
addd 2,y
A_low_zero: ; See A_low_zero_non_optimized below
xgdx
Return:
ins
ins
ins
ins
ret
;
;
; A_low_zero_non_optimized:
;
; At this step, X = 0 and D = (A.high * B.low)
; Optimize into: (A.high * B.low) << 16
;
; xgdx
; clra ; Since X was 0, clearing D is superfuous.
; clrb
; bra Return
; ----------------
; B.low == 0, the result is: (A.low * B.high) << 16
;
; At this step:
; D = B.low = 0
; X = A.high ?
; A.low is at A_low,y ?
; B.low is at B_low,y ?
;
B_low_zero:
ldd A_low,y
beq Zero1
ldx B_high,y
beq Zero2
bsr ___mulhi3
Zero1:
xgdx
Zero2:
clra
clrb
bra Return
; ----------------
; A.high is 0, optimize into: (A.low * B.high) << 16 + (A.low * B.low)
;
; At this step:
; D = B.low != 0
; X = A.high = 0
; A.low is at A_low,y ?
; B.low is at B_low,y ?
;
A_high_zero:
ldd A_low,y ; A.low
beq Zero1
ldx B_high,y ; B.high
beq A_low_B_low
bsr ___mulhi3
std 2,y
bra B_high_zero ; Do the (A.low * B.low) and the add.
; ----------------
; A.high and B.high are 0 optimize into: (A.low * B.low)
;
; At this step:
; D = B.high = 0
; X = A.low != 0
; A.low is at A_low,y != 0
; B.high is at B_high,y = 0
;
A_low_B_low:
ldd B_low,y ; A.low is on the stack
bsr __mulhi32
bra Return
#endif
#endif
#ifdef L_map_data
.sect .install2,"ax",@progbits
.globl __map_data_section
.globl __data_image
#ifdef mc68hc12
.globl __data_section_size
#endif
__map_data_section:
#ifdef mc68hc12
ldx #__data_image
ldy #__data_section_start
ldd #__data_section_size
beq Done
Loop:
movb 1,x+,1,y+
dbne d,Loop
#else
ldx #__data_image
ldy #__data_section_start
bra Start_map
Loop:
ldaa 0,x
staa 0,y
inx
iny
Start_map:
cpx #__data_image_end
blo Loop
#endif
Done:
#endif
#ifdef L_init_bss
.sect .install2,"ax",@progbits
.globl __init_bss_section
__init_bss_section:
ldd #__bss_size
beq Done
ldx #__bss_start
Loop:
#ifdef mc68hc12
clr 1,x+
dbne d,Loop
#else
clr 0,x
inx
subd #1
bne Loop
#endif
Done:
#endif
#ifdef L_ctor
; End of constructor table
.sect .install3,"ax",@progbits
.globl __do_global_ctors
__do_global_ctors:
; Start from the end - sizeof(void*)
ldx #__CTOR_END__-2
ctors_loop:
cpx #__CTOR_LIST__
blo ctors_done
pshx
ldx 0,x
jsr 0,x
pulx
dex
dex
bra ctors_loop
ctors_done:
#endif
#ifdef L_dtor
.sect .fini3,"ax",@progbits
.globl __do_global_dtors
;;
;; This piece of code is inserted in the _exit() code by the linker.
;;
__do_global_dtors:
pshb ; Save exit code
psha
ldx #__DTOR_LIST__
dtors_loop:
cpx #__DTOR_END__
bhs dtors_done
pshx
ldx 0,x
jsr 0,x
pulx
inx
inx
bra dtors_loop
dtors_done:
pula ; Restore exit code
pulb
#endif
#ifdef L_far_tramp
#ifdef mc68hc12
.sect .tramp,"ax",@progbits
.globl __far_trampoline
;; This is a trampoline used by the linker to invoke a function
;; using rtc to return and being called with jsr/bsr.
;; The trampoline generated is:
;;
;; foo_tramp:
;; ldy #foo
;; call __far_trampoline,page(foo)
;;
;; The linker transforms:
;;
;; jsr foo
;;
;; into
;; jsr foo_tramp
;;
;; The linker generated trampoline and _far_trampoline must be in
;; non-banked memory.
;;
__far_trampoline:
movb 0,sp, 2,sp ; Copy page register below the caller's return
leas 2,sp ; address.
jmp 0,y ; We have a 'call/rtc' stack layout now
; and can jump to the far handler
; (whose memory bank is mapped due to the
; call to the trampoline).
#endif
#ifdef mc68hc11
.sect .tramp,"ax",@progbits
.globl __far_trampoline
;; Trampoline generated by gcc for 68HC11:
;;
;; pshb
;; ldab #%page(func)
;; ldy #%addr(func)
;; jmp __far_trampoline
;;
__far_trampoline:
psha ; (2) Save function parameter (high)
;; <Read current page in A>
psha ; (2)
;; <Set currenge page from B>
pshx ; (4)
tsx ; (3)
ldab 4,x ; (4) Restore function parameter (low)
ldaa 2,x ; (4) Get saved page number
staa 4,x ; (4) Save it below return PC
pulx ; (5)
pula ; (3)
pula ; (3) Restore function parameter (high)
jmp 0,y ; (4)
#endif
#endif
#ifdef L_call_far
#ifdef mc68hc11
.sect .tramp,"ax",@progbits
.globl __call_a16
.globl __call_a32
;;
;; The call methods are used for 68HC11 to support memory bank switching.
;; Every far call is redirected to these call methods. Its purpose is to:
;;
;; 1/ Save the current page on the stack (1 byte to follow 68HC12 call frame)
;; 2/ Install the new page
;; 3/ Jump to the real function
;;
;; The page switching (get/save) is board dependent. The default provided
;; here does nothing (just create the appropriate call frame).
;;
;; Call sequence (10 bytes, 13 cycles):
;;
;; ldx #page ; (3)
;; ldy #func ; (4)
;; jsr __call_a16 ; (6)
;;
;; Call trampoline (11 bytes, 19 cycles):
;;
__call_a16:
;; xgdx ; (3)
;; <Read current page in A> ; (3) ldaa _current_page
psha ; (2)
;; <Set current page from B> ; (4) staa _current_page
;; xgdx ; (3)
jmp 0,y ; (4)
;;
;; Call sequence (10 bytes, 14 cycles):
;;
;; pshb ; (2)
;; ldab #page ; (2)
;; ldy #func ; (4)
;; jsr __call_a32 ; (6)
;;
;; Call trampoline (87 bytes, 57 cycles):
;;
__call_a32:
pshx ; (4)
psha ; (2)
;; <Read current page in A> ; (3) ldaa _current_page
psha ; (2)
;; <Set current page from B> ; (4) staa _current_page
tsx ; (3)
ldab 6,x ; (4) Restore function parameter
ldaa 5,x ; (4) Move PC return at good place
staa 6,x ; (4)
ldaa 4,x ; (4)
staa 5,x ; (4)
pula ; (3)
staa 4,x ; (4)
pula ; (3)
pulx ; (5)
jmp 0,y ; (4)
#endif
#endif
#ifdef L_return_far
#ifdef mc68hc11
.sect .tramp,"ax",@progbits
.globl __return_void
.globl __return_16
.globl __return_32
__return_void:
;; pulb
;; <Set current page from B> (Board specific)
;; rts
__return_16:
;; xgdx
;; pulb
;; <Set current page from B> (Board specific)
;; xgdx
;; rts
__return_32:
;; xgdy
;; pulb
;; <Set current page from B> (Board specific)
;; xgdy
;; rts
ins
rts
#endif
#endif
.Lend:
;-----------------------------------------
; end required gcclib code
;-----------------------------------------
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.