text stringlengths 1 1.05M |
|---|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r8
push %r9
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0x10039, %rsi
nop
nop
nop
nop
add $33126, %rbp
mov $0x6162636465666768, %r13
movq %r13, (%rsi)
nop
dec %rbp
lea addresses_WT_ht+0x3a1, %r9
nop
nop
nop
nop
add $60923, %rcx
mov $0x6162636465666768, %rdi
movq %rdi, %xmm0
vmovups %ymm0, (%r9)
nop
nop
nop
nop
nop
add $29585, %rcx
lea addresses_A_ht+0xc2e1, %rcx
nop
nop
sub %r12, %r12
mov $0x6162636465666768, %rdi
movq %rdi, %xmm7
vmovups %ymm7, (%rcx)
nop
nop
nop
and $53838, %rbp
lea addresses_D_ht+0x5ba1, %rcx
nop
nop
nop
add %rsi, %rsi
movb $0x61, (%rcx)
nop
nop
nop
dec %rsi
lea addresses_A_ht+0x1dba1, %r12
and $36171, %rsi
mov $0x6162636465666768, %r13
movq %r13, (%r12)
dec %rdi
lea addresses_D_ht+0x105c1, %rsi
lea addresses_UC_ht+0x5d21, %rdi
nop
nop
nop
nop
cmp $64895, %r8
mov $7, %rcx
rep movsl
nop
nop
nop
nop
nop
sub %rbp, %rbp
lea addresses_D_ht+0xdf61, %rcx
nop
and $35142, %r9
mov (%rcx), %r12w
nop
nop
nop
nop
and %rdi, %rdi
lea addresses_WC_ht+0x1d661, %rcx
clflush (%rcx)
xor %r12, %r12
movw $0x6162, (%rcx)
nop
lfence
lea addresses_WC_ht+0x1afa1, %r12
xor %r9, %r9
mov (%r12), %r8d
nop
nop
sub %rsi, %rsi
lea addresses_A_ht+0x13b41, %rdi
nop
nop
nop
dec %rcx
mov $0x6162636465666768, %rbp
movq %rbp, (%rdi)
nop
nop
nop
nop
add $27510, %rdi
lea addresses_normal_ht+0x15e05, %rsi
nop
nop
nop
nop
nop
lfence
movb (%rsi), %r8b
nop
cmp %rcx, %rcx
lea addresses_WT_ht+0x2da1, %r8
add %r13, %r13
mov $0x6162636465666768, %rcx
movq %rcx, (%r8)
nop
nop
sub $9673, %rbp
lea addresses_normal_ht+0xfce1, %rdi
clflush (%rdi)
sub %r8, %r8
movb (%rdi), %cl
nop
nop
lfence
lea addresses_WT_ht+0xa55b, %rbp
sub $14951, %r13
mov $0x6162636465666768, %rsi
movq %rsi, (%rbp)
nop
and $57709, %r9
lea addresses_UC_ht+0x191d1, %rdi
nop
nop
nop
nop
dec %rbp
mov (%rdi), %r8d
inc %rbp
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r9
pop %r8
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r14
push %r15
push %r9
push %rax
push %rcx
// Load
lea addresses_US+0xbda1, %r9
nop
nop
nop
sub %r14, %r14
mov (%r9), %r15w
nop
nop
nop
inc %rax
// Faulty Load
lea addresses_D+0x67a1, %r15
nop
nop
nop
nop
nop
cmp %r11, %r11
mov (%r15), %r9w
lea oracles, %rax
and $0xff, %r9
shlq $12, %r9
mov (%rax,%r9,1), %r9
pop %rcx
pop %rax
pop %r9
pop %r15
pop %r14
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 2, 'AVXalign': False, 'NT': True, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 1, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}}
{'36': 33}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
|
; A063120: Dimension of the space of weight 2n cusp forms for Gamma_0( 52 ).
; 5,18,32,46,60,74,88,102,116,130,144,158,172,186,200,214,228,242,256,270,284,298,312,326,340,354,368,382,396,410,424,438,452,466,480,494,508,522,536,550,564,578,592,606,620,634,648,662,676,690
mov $1,14
mul $1,$0
trn $1,1
add $1,5
mov $0,$1
|
#include "pch.hpp"
#include "Mikey.hpp"
#include "TimerCore.hpp"
#include "AudioChannel.hpp"
#include "Core.hpp"
#include "Cartridge.hpp"
#include "CPU.hpp"
#include "ComLynx.hpp"
#include "VGMWriter.hpp"
Mikey::Mikey( Core & core, ComLynx & comLynx, std::shared_ptr<IVideoSink> videoSink ) : mCore{ core }, mComLynx{ comLynx }, mAccessTick{}, mTimers{}, mAudioChannels{}, mPalette{},
mAttenuation{ 0xff, 0xff, 0xff, 0xff }, mAttenuationLeft{ 0x3c, 0x3c, 0x3c, 0x3c }, mAttenuationRight{ 0x3c, 0x3c, 0x3c, 0x3c }, mDisplayGenerator{ std::make_unique<DisplayGenerator>( std::move( videoSink ) ) },
mParallelPort{ mCore, mComLynx, *mDisplayGenerator }, mDisplayRegs{}, mSuzyDone{}, mPan{ 0xff }, mStereo{}, mSerDat{}, mIRQ{}
{
mTimers[0x0] = std::make_unique<TimerCore>( 0x0, [this]( uint64_t tick, bool interrupt )
{
mTimers[0x2]->borrowIn( tick );
uint8_t cnt = mTimers[0x02]->getCount( tick );
if ( cnt == 101 )
{
mDisplayGenerator->updateDispAddr( tick, mDisplayRegs.dispAdr );
}
mCore.newLine( cnt );
if ( cnt == 104 )
{
mDisplayGenerator->firstHblank( tick, mTimers[0x00]->getBackup( tick ) );
}
else if ( auto dma = mDisplayGenerator->hblank( tick, cnt ) )
{
mCore.requestDisplayDMA( dma.tick, dma.address );
}
if ( interrupt )
{
setIRQ( 0x01 );
}
} ); //timer 0 -> timer 2
mTimers[0x1] = std::make_unique<TimerCore>( 0x1, [this]( uint64_t tick, bool interrupt )
{
mTimers[0x3]->borrowIn( tick );
if ( interrupt )
{
setIRQ( 0x02 );
}
} ); //timer 1 -> timer 3
mTimers[0x2] = std::make_unique<TimerCore>( 0x2, [this]( uint64_t tick, bool interrupt )
{
mTimers[0x4]->borrowIn( tick );
mDisplayGenerator->vblank( tick );
if ( interrupt )
{
setIRQ( 0x04 );
}
} ); //timer 2 -> timer 4
mTimers[0x3] = std::make_unique<TimerCore>( 0x3, [this]( uint64_t tick, bool interrupt )
{
mTimers[0x5]->borrowIn( tick );
if ( interrupt )
{
setIRQ( 0x08 );
}
} ); //timer 3 -> timer 5
mTimers[0x4] = std::make_unique<TimerCore>( 0x4, [this]( uint64_t tick, bool interrupt )
{
if ( mComLynx.pulse() )
{
setIRQ( 0x10 );
}
} ); //timer 4
mTimers[0x5] = std::make_unique<TimerCore>( 0x5, [this]( uint64_t tick, bool interrupt )
{
mTimers[0x7]->borrowIn( tick );
if ( interrupt )
{
setIRQ( 0x20 );
}
} ); //timer 5 -> timer 7
mTimers[0x6] = std::make_unique<TimerCore>( 0x6, [this]( uint64_t tick, bool interrupt )
{
if ( interrupt )
{
setIRQ( 0x40 );
}
} ); //timer 6
mTimers[0x7] = std::make_unique<TimerCore>( 0x7, [this]( uint64_t tick, bool interrupt )
{
mTimers[0x8]->borrowIn( tick );
if ( interrupt )
{
setIRQ( 0x80 );
}
} ); //timer 7 -> audio 0
mTimers[0x8] = std::make_unique<TimerCore>( 0x8, [this]( uint64_t tick, bool unused )
{
mAudioChannels[0x0]->trigger( tick );
mTimers[0x9]->borrowIn( tick );
} ); //audio 0 -> audio 1
mTimers[0x9] = std::make_unique<TimerCore>( 0x9, [this]( uint64_t tick, bool unused )
{
mAudioChannels[0x1]->trigger( tick );
mTimers[0xa]->borrowIn( tick );
} ); //audio 1 -> audio 2
mTimers[0xa] = std::make_unique<TimerCore>( 0xa, [this]( uint64_t tick, bool unused )
{
mAudioChannels[0x2]->trigger( tick );
mTimers[0xb]->borrowIn( tick );
} ); //audio 2 -> audio 3
mTimers[0xb] = std::make_unique<TimerCore>( 0xb, [this]( uint64_t tick, bool unused )
{
mAudioChannels[0x3]->trigger( tick );
mTimers[0x0]->borrowIn( tick );
} ); //audio 3 -> timer 1
mAudioChannels[0x0] = std::make_unique<AudioChannel>( *mTimers[0x8] );
mAudioChannels[0x1] = std::make_unique<AudioChannel>( *mTimers[0x9] );
mAudioChannels[0x2] = std::make_unique<AudioChannel>( *mTimers[0xa] );
mAudioChannels[0x3] = std::make_unique<AudioChannel>( *mTimers[0xb] );
std::ranges::fill( mPalette, 0xff );
for ( int i = 0; i < 32; ++i )
{
mDisplayGenerator->updatePalette( 0, i, 0xff );
}
}
Mikey::~Mikey()
{
}
uint64_t Mikey::requestAccess( uint64_t tick, uint16_t address )
{
mAccessTick = tick + 5;
address &= 0xff;
int timer = -1;
if ( address < 0x20 )
{
timer = ( address & 0x1f ) >> 2;
}
else if ( address < 0x40 )
{
timer = 8 + ( ( ( address - 0x20 ) & 0x1f ) >> 3 );
}
if ( timer >= 0 )
{
auto nextTick = mAccessTick & ~0xfull + ( timer * 16 / 12 );
mAccessTick = nextTick < mAccessTick ? nextTick + 16 : nextTick;
}
return mAccessTick;
}
uint8_t Mikey::read( uint16_t address )
{
address &= 0xff;
if ( address < 0x20 )
{
switch ( address & 0x3 )
{
case TIMER::BACKUP:
return mTimers[( address >> 2 ) & 7]->getBackup( mAccessTick );
case TIMER::CONTROLA:
return mTimers[( address >> 2 ) & 7]->getControlA( mAccessTick );
case TIMER::COUNT:
return mTimers[( address >> 2 ) & 7]->getCount( mAccessTick );
case TIMER::CONTROLB:
return mTimers[( address >> 2 ) & 7]->getControlB( mAccessTick );
}
}
else if ( address < 0x40 )
{
switch ( address & 0x7 )
{
case AUDIO::VOLCNTRL:
return std::bit_cast<uint8_t>( mAudioChannels[( address >> 3 ) & 3]->getVolume() );
case AUDIO::FEEDBACK:
return mAudioChannels[( address >> 3 ) & 3]->getFeedback();
case AUDIO::OUTPUT:
return std::bit_cast<uint8_t>( mAudioChannels[( address >> 3 ) & 3]->getOutput() );
case AUDIO::SHIFT:
return mAudioChannels[( address >> 3 ) & 3]->getShift();
case AUDIO::BACKUP:
return mAudioChannels[( address >> 3 ) & 3]->getBackup( mAccessTick );
case AUDIO::CONTROL:
return mAudioChannels[( address >> 3 ) & 3]->getControl( mAccessTick );
case AUDIO::COUNTER:
return mAudioChannels[( address >> 3 ) & 3]->getCounter( mAccessTick );
case AUDIO::OTHER:
return mAudioChannels[( address >> 3 ) & 3]->getOther( mAccessTick );
}
}
else switch ( address )
{
case ATTENREG0:
return mAttenuation[0];
case ATTENREG1:
return mAttenuation[1];
case ATTENREG2:
return mAttenuation[2];
case ATTENREG3:
return mAttenuation[3];
case MPAN:
return mPan;
case MSTEREO:
return mStereo;
case INTRST:
case INTSET:
return mIRQ;
case IODIR:
return mParallelPort.getDirection();
case IODAT:
return mParallelPort.getData( mAccessTick );
case MIKEYHREV:
return 0x01;
case SERCTL:
return mComLynx.getCtrl();
case SERDAT:
return mComLynx.getData();
case GREEN + 0x00:
case GREEN + 0x01:
case GREEN + 0x02:
case GREEN + 0x03:
case GREEN + 0x04:
case GREEN + 0x05:
case GREEN + 0x06:
case GREEN + 0x07:
case GREEN + 0x08:
case GREEN + 0x09:
case GREEN + 0x0a:
case GREEN + 0x0b:
case GREEN + 0x0c:
case GREEN + 0x0d:
case GREEN + 0x0e:
case GREEN + 0x0f:
return mPalette[address - GREEN] & 0x0f;
case BLUERED + 0x00:
case BLUERED + 0x01:
case BLUERED + 0x02:
case BLUERED + 0x03:
case BLUERED + 0x04:
case BLUERED + 0x05:
case BLUERED + 0x06:
case BLUERED + 0x07:
case BLUERED + 0x08:
case BLUERED + 0x09:
case BLUERED + 0x0a:
case BLUERED + 0x0b:
case BLUERED + 0x0c:
case BLUERED + 0x0d:
case BLUERED + 0x0e:
case BLUERED + 0x0f:
return mPalette[address - GREEN];
default:
return (uint8_t)0xff;
break;
}
return uint8_t();
}
SequencedAction Mikey::write( uint16_t address, uint8_t value )
{
address &= 0xff;
if ( address < 0x20 )
{
switch ( address & 0x3 )
{
case TIMER::BACKUP:
return mTimers[(address >> 2) & 7]->setBackup( mAccessTick, value );
case TIMER::CONTROLA:
return mTimers[( address >> 2 ) & 7]->setControlA( mAccessTick, value );
case TIMER::COUNT:
return mTimers[( address >> 2 ) & 7]->setCount( mAccessTick, value );
case TIMER::CONTROLB:
return mTimers[( address >> 2 ) & 7]->setControlB( mAccessTick, value );
}
}
else if ( address < 0x40 )
{
if ( mVGMWriter )
mVGMWriter->write( mAccessTick, (uint8_t)address, value );
int idx = ( address >> 3 ) & 3;
switch ( address & 0x7 )
{
case AUDIO::VOLCNTRL:
return mAudioChannels[( address >> 3 ) & 3]->setVolume( (int8_t)value );
case AUDIO::FEEDBACK:
return mAudioChannels[( address >> 3 ) & 3]->setFeedback( value );
case AUDIO::OUTPUT:
return mAudioChannels[( address >> 3 ) & 3]->setOutput( value );
case AUDIO::SHIFT:
return mAudioChannels[( address >> 3 ) & 3]->setShift( value );
case AUDIO::BACKUP:
return mAudioChannels[( address >> 3 ) & 3]->setBackup( mAccessTick, value );
case AUDIO::CONTROL:
return mAudioChannels[( address >> 3 ) & 3]->setControl( mAccessTick, value );
case AUDIO::COUNTER:
return mAudioChannels[( address >> 3 ) & 3]->setCounter( mAccessTick, value );
case AUDIO::OTHER:
return mAudioChannels[( address >> 3 ) & 3]->setOther( mAccessTick, value );
}
}
else switch ( address )
{
case ATTENREG0:
case ATTENREG1:
case ATTENREG2:
case ATTENREG3:
mAttenuation[address & 3] = value;
mAttenuationRight[address & 3] = ( value & 0x0f ) << 2;
mAttenuationLeft[address & 3] = ( value & 0xf0 ) >> 2;
if ( mVGMWriter )
mVGMWriter->write( mAccessTick, (uint8_t)address, value );
break;
case MPAN:
mPan = value;
if ( mVGMWriter )
mVGMWriter->write( mAccessTick, (uint8_t)address, value );
break;
case MSTEREO:
mStereo = value;
if ( mVGMWriter )
mVGMWriter->write( mAccessTick, (uint8_t)address, value );
break;
case INTRST:
resetIRQ( value );
break;
case INTSET:
setIRQ( value );
break;
case SYSCTL1:
if ( ( value & SYSCTL1::POWERON ) == 0 )
{
mCore.enterMonitor();
}
mCore.getCartridge().setCartAddressStrobe( ( value & SYSCTL1::CART_ADDR_STROBE ) == 1 );
break;
case IODIR:
mParallelPort.setDirection( value );
break;
case IODAT:
mParallelPort.setData( value );
break;
case SERCTL:
mComLynx.setCtrl( value );
break;
case SERDAT:
mComLynx.setData( value );
break;
case SDONEACK:
mSuzyDone = false;
break;
case CPUSLEEP:
//The presence of an interrupt in Mikey, regardless of the state of the CPU enable interrupt bit,
//will prevent the CPU from going to sleep, and thus prevent Suzy from functioning.
//So if sprites stop working, unintentional interrupt bits can be the hidden cause.
if ( !mSuzyDone && mIRQ == 0 )
mCore.runSuzy();
break;
case DISPCTL:
mDisplayRegs.dispColor = ( value & DISPCTL::DISP_COLOR ) != 0;
mDisplayRegs.dispFourBit = ( value & DISPCTL::DISP_FOURBIT ) != 0;
mDisplayRegs.dispFlip = ( value & DISPCTL::DISP_FLIP ) != 0;
mDisplayRegs.DMAEnable = ( value & DISPCTL::DMA_ENABLE ) != 0;
mDisplayGenerator->dispCtl( mDisplayRegs.dispColor, mDisplayRegs.dispFlip, mDisplayRegs.DMAEnable );
break;
case PBKUP:
mDisplayGenerator->setPBKUP( value );
break;
case DISPADR:
mDisplayRegs.dispAdr &= 0xff00;
mDisplayRegs.dispAdr |= value;
mDisplayRegs.dispAdr &= 0xfffc;
break;
case DISPADR+1:
mDisplayRegs.dispAdr &= 0x00ff;
mDisplayRegs.dispAdr |= value << 8;
break;
case MTEST0:
break;
case MTEST1:
break;
case MTEST2:
if ( ( value & 0x01 ) != 0 )
mDisplayGenerator->updateDispAddr( mAccessTick, mDisplayRegs.dispAdr );
break;
case GREEN + 0x00:
case GREEN + 0x01:
case GREEN + 0x02:
case GREEN + 0x03:
case GREEN + 0x04:
case GREEN + 0x05:
case GREEN + 0x06:
case GREEN + 0x07:
case GREEN + 0x08:
case GREEN + 0x09:
case GREEN + 0x0a:
case GREEN + 0x0b:
case GREEN + 0x0c:
case GREEN + 0x0d:
case GREEN + 0x0e:
case GREEN + 0x0f:
case BLUERED + 0x00:
case BLUERED + 0x01:
case BLUERED + 0x02:
case BLUERED + 0x03:
case BLUERED + 0x04:
case BLUERED + 0x05:
case BLUERED + 0x06:
case BLUERED + 0x07:
case BLUERED + 0x08:
case BLUERED + 0x09:
case BLUERED + 0x0a:
case BLUERED + 0x0b:
case BLUERED + 0x0c:
case BLUERED + 0x0d:
case BLUERED + 0x0e:
case BLUERED + 0x0f:
mPalette[address - GREEN] = value;
mDisplayGenerator->updatePalette( mAccessTick, address - GREEN, value );
break;
default:
// assert( false );
break;
}
return {};
}
SequencedAction Mikey::fireTimer( uint64_t tick, uint32_t timer )
{
assert( timer < 12 );
return mTimers[timer]->fireAction( tick );
}
void Mikey::setDMAData( uint64_t tick, uint64_t data )
{
if ( auto dma = mDisplayGenerator->pushData( tick, data ) )
{
mCore.requestDisplayDMA( dma.tick, dma.address );
}
}
void Mikey::suzyDone()
{
mSuzyDone = true;
}
AudioSample Mikey::sampleAudio( uint64_t tick ) const
{
int16_t left{};
int16_t right{};
int16_t samples[4];
samples[0] = (int16_t)mAudioChannels[0]->sample( tick );
samples[1] = (int16_t)mAudioChannels[1]->sample( tick );
samples[2] = (int16_t)mAudioChannels[2]->sample( tick );
samples[3] = (int16_t)mAudioChannels[3]->sample( tick );
for ( size_t i = 0; i < 4; ++i )
{
if ( ( mStereo & ( (uint8_t)0x01 << i ) ) == 0 )
{
const int attenuation = ( mPan & ( (uint8_t)0x01 << i ) ) != 0 ? mAttenuationLeft[i] : 0x3c;
left += (int16_t)samples[i] * attenuation;
}
if ( ( mStereo & ( (uint8_t)0x10 << i ) ) == 0 )
{
const int attenuation = ( mPan & ( (uint8_t)0x01 << i ) ) != 0 ? mAttenuationRight[i] : 0x3c;
right += (int16_t)samples[i] * attenuation;
}
}
return { left, right };
}
void Mikey::setVGMWriter( std::shared_ptr<VGMWriter> writer )
{
mVGMWriter = std::move( writer );
}
void Mikey::setIRQ( uint8_t mask )
{
mIRQ |= mask;
if ( mIRQ != 0 )
{
mCore.assertInterrupt( CPUState::I_IRQ );
}
}
void Mikey::resetIRQ( uint8_t mask )
{
if ( mComLynx.interrupt() )
mask &= ~0x10; //preventing to reset serial interrupt if source is still active
mIRQ &= ~mask;
if ( mIRQ == 0 )
{
mCore.desertInterrupt( CPUState::I_IRQ );
}
}
uint16_t Mikey::debugDispAdr() const
{
return mDisplayRegs.dispAdr;
}
std::span<uint8_t const, 32> Mikey::debugPalette() const
{
return std::span<uint8_t const, 32>( mPalette.data(), mPalette.size() );
}
|
###############################################################################
# Copyright 2019 Intel Corporation
# All Rights Reserved.
#
# If this software was obtained under the Intel Simplified Software License,
# the following terms apply:
#
# The source code, information and material ("Material") contained herein is
# owned by Intel Corporation or its suppliers or licensors, and title to such
# Material remains with Intel Corporation or its suppliers or licensors. The
# Material contains proprietary information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright laws and treaty
# provisions. No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed or disclosed
# in any way without Intel's prior express written permission. No license under
# any patent, copyright or other intellectual property rights in the Material
# is granted to or conferred upon you, either expressly, by implication,
# inducement, estoppel or otherwise. Any license under such intellectual
# property rights must be express and approved by Intel in writing.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intel's
# suppliers or licensors in any way.
#
#
# If this software was obtained under the Apache License, Version 2.0 (the
# "License"), the following terms apply:
#
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
.section .note.GNU-stack,"",%progbits
.text
.p2align 6, 0x90
.globl Decrypt_RIJ128_AES_NI
.type Decrypt_RIJ128_AES_NI, @function
Decrypt_RIJ128_AES_NI:
lea (,%rdx,4), %rax
lea (,%rax,4), %rax
movdqu (%rdi), %xmm0
pxor (%rcx,%rax), %xmm0
cmp $(12), %rdx
jl .Lkey_128gas_1
jz .Lkey_192gas_1
.Lkey_256gas_1:
aesdec (208)(%rcx), %xmm0
aesdec (192)(%rcx), %xmm0
.Lkey_192gas_1:
aesdec (176)(%rcx), %xmm0
aesdec (160)(%rcx), %xmm0
.Lkey_128gas_1:
aesdec (144)(%rcx), %xmm0
aesdec (128)(%rcx), %xmm0
aesdec (112)(%rcx), %xmm0
aesdec (96)(%rcx), %xmm0
aesdec (80)(%rcx), %xmm0
aesdec (64)(%rcx), %xmm0
aesdec (48)(%rcx), %xmm0
aesdec (32)(%rcx), %xmm0
aesdec (16)(%rcx), %xmm0
aesdeclast (%rcx), %xmm0
movdqu %xmm0, (%rsi)
ret
.Lfe1:
.size Decrypt_RIJ128_AES_NI, .Lfe1-(Decrypt_RIJ128_AES_NI)
|
****************
*
* chained_scbs.asm
*
* (c) 42Bastian Schick
*
* July 2019
*
DEBUG set 1
Baudrate set 62500
_1000HZ_TIMER set 7
IRQ_SWITCHBUF_USR set 1
include <includes\hardware.inc>
****************
MACRO DoSWITCH
dec SWITCHFlag
.\wait_vbl bit SWITCHFlag
bmi .\wait_vbl
ENDM
****************
* macros
include <macros/help.mac>
include <macros/if_while.mac>
include <macros/font.mac>
include <macros/mikey.mac>
include <macros/suzy.mac>
include <macros/irq.mac>
include <macros/newkey.mac>
include <macros/debug.mac>
****************
* variables
include <vardefs/debug.var>
include <vardefs/help.var>
include <vardefs/font.var>
include <vardefs/mikey.var>
include <vardefs/suzy.var>
include <vardefs/irq.var>
include <vardefs/newkey.var>
include <vardefs/serial.var>
include <vardefs/1000Hz.var>
****************************************************
BEGIN_ZP
ptr ds 2
ptr1 ds 2
ptr2 ds 2
counter ds 1
winkel ds 1
winkel_nk ds 1 ; Nachkomma
winkel_add1 ds 1
amplitude ds 1
frame_counter ds 1
x ds 2
x1 ds 2
y ds 2
tmp ds 1
*********************
END_ZP
BEGIN_MEM
irq_vektoren ds 16
ALIGN 4
screen0 ds SCREEN.LEN
screen1 ds SCREEN.LEN
scbdata ds SCREEN.LEN+102*3
scbtab ds 102
ds 102
scbs ds 102*15
scbx ds 100
scby ds 100
END_MEM
run LOMEM
ECHO "START :%HLOMEM ZP : %HNEXT_ZP"
Start::
sei
cld
CLEAR_MEM
CLEAR_ZP
ldx #0
txs
INITMIKEY
INITSUZY
SETRGB pal
INITIRQ irq_vektoren
INITKEY
INITFONT LITTLEFNT,RED,WHITE
jsr Init1000Hz
FRAMERATE 60
jsr InitComLynx
SETIRQ 2,VBL
SCRBASE screen0,screen1
SET_MINMAX 0,0,160,102
lda #$c0
ora _SPRSYS
sta SPRSYS
sta _SPRSYS
stz _1000Hz
stz _1000Hz+1
stz _1000Hz+2
cli
lda #20
sta amplitude
stz counter
stz winkel
lda #$f0
sta winkel_add1
stz _1000Hz
stz _1000Hz+1
jsr MakeChainedSCBs
lda #8
sta size
sta size+2
stz size+1
stz size+3
again::
lda #1
sta frame_counter
pha
.loop
clc
lda size
inc:
adc #1
sta size
sta size+2
bcc .ok
inc size+1
inc size+3
stz inc+1
.ok
jsr _cls
jsr DrawSCBs5
stz $fda0
stz CurrX
lda _1000Hz
jsr PrintHex
DoSWITCH
dec $fda0
stz _1000Hz
inc counter
bne .loop
dec frame_counter
bne .loop
jmp again
****************
VBL::
inc winkel
jsr Keyboard
IRQ_SWITCHBUF
END_IRQ
****************
DrawSCBs5::
IF 1
ldy #0
ldx winkel
phx
lda winkel_nk
pha
.loop
lda amplitude
sta $fc52
stz $fc53
lda SinTab.Lo,x
sta $fc54
lda SinTab.Hi,x
sta $fc55
.wait bit SPRSYS
bmi .wait
MOVE $fc61,x
phx
lda #10
sta tmp
.loopx
lda scbtab,y
sta ptr
lda scbtab+102,y
sta ptr+1
IF 1
phy
clc
lda x
adc scbx,y
sta x1
lda x+1
adc #0
sta x1+1
ldy #1
lda #SPRCTL1_PALETTE_NO_RELOAD
sta (ptr),y
lda x1+1
bne .xok0 ; < 0 >= draw tile
lda x1
cmp #160
bcc .xok
;; skip tile if outside right border
lda #SPRCTL1_SKIP
sta (ptr),y
bra .next
.xok0
lda x1
.xok
ldy #7
sta (ptr),y
iny
lda x1+1
sta (ptr),y
.next
ply
ENDIF
IF 1
lda SinTab.Lo,x
sta $fc54
lda SinTab.Hi,x
sta $fc55
.wait1 bit SPRSYS
bmi .wait1
phy
clc
lda $fc61
//-> adc (ptr)
//-> sta (ptr)
adc scby,y
ldy #9
sta (ptr),y
iny
lda $fc62
//-> ldy #1
//-> adc (ptr),y
adc #0
sta (ptr),y
ply
txa
adc #4
tax
//-> inx
//-> inx
ENDIF
iny
dec tmp
bne .loopx
plx
clc
lda winkel_nk
adc winkel_add1
sta winkel_nk
bcc .noc
inx
.noc
cpy #100
beq .exit
jmp .loop
.exit
pla
sta winkel_nk
pla
sta winkel
ENDIF
lda #<SCB0
ldy #>SCB0
jmp DrawSprite
****************
_cls:: lda #<clsSCB
ldy #>clsSCB
jmp DrawSprite
clsSCB
dc.b $0,$10,0
dc.w 0,clsDATA
dc.w 0,0
dc.w $100*10,$100*102
clsCOLOR
dc.b $04
clsDATA
dc.b 2,%01111100
dc.b 0
MakeChainedSCBs::
MOVEI scbs,ptr2
stz y
lda #0
sta x
ldx #0
.loop
lda #SPRCTL0_16_COL|SPRCTL0_BACKGROUND_SHADOW
sta (ptr2)
ldy #1
lda #SPRCTL1_PALETTE_NO_RELOAD
sta (ptr2),y
iny
lda #0
sta (ptr2),y
clc ; nxt
lda ptr2
adc #11
iny
pha
sta (ptr2),y
lda #0
adc ptr2+1
iny
pha
sta (ptr2),y
iny ; data
lda sprite_addr_lo,x
sta (ptr2),y
lda sprite_addr_hi,x
iny
sta (ptr2),y
lda x
iny
sta (ptr2),y
sta scbx,x
iny
clc
adc #16
sta x
lda #0
sta (ptr2),y
lda y
iny
sta scby,x
sta (ptr2),y ; y
lda #0
iny
sta (ptr2),y
lda #0
iny
sta (ptr2),y
iny
iny
sta (ptr2),y
iny
phy
lda #1
sta (ptr2),y
dey
dey
sta (ptr2),y
ply
clc
lda ptr2
//-> adc #7
sta scbtab,x
lda ptr2+1
//-> adc #0
sta scbtab+102,x
MOVE ptr2,ptr
pla
sta ptr2+1
pla
sta ptr2
inx
lda x
cmp #160
bne .toloop
lda #0
sta x
lda y
clc
adc #10
sta y
cmp #100
beq .exit
.toloop
jmp .loop
.exit
ldy #4
lda #0
sta (ptr),y
rts
SCB0
dc.b SPRCTL0_16_COL|SPRCTL0_BACKGROUND_SHADOW
dc.b SPRCTL1_LITERAL|SPRCTL1_DEPTH_SIZE_RELOAD
dc.b 0
dc.w scbs ; next
dc.w SCB0_data ; data
dc.w 0 ; x
dc.w -1 ; y
size:
dc.w $100,$100 ; size
dc.b $01,$23,$45,$67,$89,$AB,$CD,$E0
SCB0_data:
dc.b 2,0,0
****************
PrintHex::
phx
pha
lsr
lsr
lsr
lsr
tax
lda digits,x
jsr PrintChar
pla
and #$f
tax
lda digits,x
jsr PrintChar
plx
rts
digits
db "0123456789ABCDEF"
****************
* Sinus-Tabelle
* 8Bit Nachkomma
****************
SinTab.Lo
ibytes <bin/sintab_8.o>
SinTab.Hi equ SinTab.Lo+256
***************************************************
****************
* INCLUDES
include <includes/draw_spr.inc>
include <includes/irq.inc>
include <includes/1000Hz.inc>
include <includes/serial.inc>
include <includes/font.inc>
include <includes/font2.hlp>
include <includes/newkey.inc>
include <includes/debug.inc>
align 2
include "sprites/sprites.inc"
include "sprites/spriteaddrlo.inc"
include "sprites/spriteaddrhi.inc"
pal DP 000,574,434,555,656,799,A9A,BCC,DCD,EFF,FAF,695,9B7,7A6,AAB,AC9
|
; A152018: Denominator of 1/n^2-1/(3n)^2 or of 8/(9n^2).
; 9,9,81,18,225,81,441,72,729,225,1089,162,1521,441,2025,288,2601,729,3249,450,3969,1089,4761,648,5625,1521,6561,882,7569,2025,8649,1152,9801,2601,11025,1458,12321,3249,13689,1800,15129,3969,16641,2178,18225
add $0,1
pow $0,2
mov $2,$0
gcd $2,8
div $0,$2
mov $1,$0
mul $1,9
|
name "calc-sum"
org 100h ; directive make tiny com file.
; calculate the sum of elements in vector,
; store result in m and print it in binary code.
; number of elements:
mov cx, 5
; al will store the sum:
mov al, 0
; bx is an index:
mov bx, 0
; sum elements:
next: add al, vector[bx]
; next byte:
inc bx
; loop until cx=0:
loop next
; store result in m:
mov m, al
; print result in binary:
mov bl, m
mov cx, 8
print: mov ah, 2 ; print function.
mov dl, '0'
test bl, 10000000b ; test first bit.
jz zero
mov dl, '1'
zero: int 21h
shl bl, 1
loop print
; print binary suffix:
mov dl, 'b'
int 21h
mov dl, 0ah ; new line.
int 21h
mov dl, 0dh ; carrige return.
int 21h
; print result in decimal:
mov al, m
call print_al
; wait for any key press:
mov ah, 0
int 16h
ret
; variables:
vector db 5, 4, 5, 2, 1
m db 0
print_al proc
cmp al, 0
jne print_al_r
push ax
mov al, '0'
mov ah, 0eh
int 10h
pop ax
ret
print_al_r:
pusha
mov ah, 0
cmp ax, 0
je pn_done
mov dl, 10
div dl
call print_al_r
mov al, ah
add al, 30h
mov ah, 0eh
int 10h
jmp pn_done
pn_done:
popa
ret
endp |
#include "Surface_mesh_deformation_test_commons.h"
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/Polyhedron_items_with_id_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/Simple_cartesian.h>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Timer.h>
#include <CGAL/Surface_mesh_deformation.h>
typedef CGAL::Simple_cartesian<double> Kernel;
//typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Polyhedron_3<Kernel, CGAL::Polyhedron_items_with_id_3> Polyhedron;
typedef CGAL::Surface_mesh_deformation<Polyhedron, CGAL::Default, CGAL::Default,
CGAL::ORIGINAL_ARAP> Deform_mesh_arap;
typedef CGAL::Surface_mesh_deformation<Polyhedron, CGAL::Default, CGAL::Default,
CGAL::SPOKES_AND_RIMS> Deform_mesh_spoke;
int main()
{
Polyhedron mesh_1;
read_to_polyhedron("data/cactus.off", mesh_1);
Polyhedron mesh_2 = mesh_1;
init_indices(mesh_1);
init_indices(mesh_2);
Deform_mesh_arap deform_mesh_arap(mesh_1);
Deform_mesh_spoke deform_mesh_spoke(mesh_2);
const int deformation_iteration = 500;
const double x = -0.55; const double y = -0.50; const double z = -0.0;
std::cerr << "ORIGINAL_ARAP performance: " << std::endl;
preprocess_and_deform(deform_mesh_arap,
"data/cactus_roi.txt",
"data/cactus_handle.txt",
CGAL::Simple_cartesian<double>::Vector_3(x, y, z),
deformation_iteration);
std::cerr << "SPOKES_AND_RIMS performance: " << std::endl;
preprocess_and_deform(deform_mesh_spoke,
"data/cactus_roi.txt",
"data/cactus_handle.txt",
CGAL::Simple_cartesian<double>::Vector_3(x, y, z),
deformation_iteration);
std::cerr << "Save deformed models" << std::endl;
std::ofstream output("data/cactus_deformed_arap.off");
output << mesh_1;
output.close();
output.open("data/cactus_deformed_spokes.off");
output << mesh_2;
std::cerr << "All done!" << std::endl;
return EXIT_SUCCESS;
}
|
; A032611: Concatenation of n and n + 6 or {n,n+6}.
; 17,28,39,410,511,612,713,814,915,1016,1117,1218,1319,1420,1521,1622,1723,1824,1925,2026,2127,2228,2329,2430,2531,2632,2733,2834,2935,3036,3137,3238,3339,3440,3541,3642,3743,3844,3945,4046,4147,4248
mov $13,$0
mov $15,$0
add $15,1
lpb $15
mov $0,$13
sub $15,1
sub $0,$15
mov $9,$0
mov $11,2
lpb $11
clr $0,9
mov $0,$9
sub $11,1
add $0,$11
sub $0,1
lpb $0
mov $1,$0
mov $0,2
mov $4,$1
add $1,4
sub $4,2
mov $3,$4
lpe
add $3,$1
mov $5,16
mul $5,$3
sub $5,$3
add $5,2
mov $1,$5
mov $12,$11
lpb $12
mov $10,$1
sub $12,1
lpe
lpe
lpb $9
mov $9,0
sub $10,$1
lpe
mov $1,$10
div $1,2
mul $1,6
add $1,11
add $14,$1
lpe
mov $1,$14
|
<%
from pwnlib.shellcraft.powerpc.linux import syscall
%>
<%page args="who, usage"/>
<%docstring>
Invokes the syscall getrusage. See 'man 2 getrusage' for more information.
Arguments:
who(rusage_who_t): who
usage(rusage): usage
</%docstring>
${syscall('SYS_getrusage', who, usage)}
|
#note: r40 (the exception handler) and r46 (the start of usermode code) must
#be specified in hex (0xwhatever)
#I just don't see any reason not to, and it makes programming the script
#much nicer to deal with...
#load exception handler
lc r40, 0x80000050
leh r40
#enable exceptions
cle
#load TLB entries
#virtual page 0 is for instructions
#virtual page 1 is for data
lc r46, 0x0000005c #usermode start address
lc r47, 1 #interrupts off
lc r48, 1 #in user mode
lc r42, 0x00000000 #denotes VPN 0
lc r43, 0x0000000d #denotes VPN 0 maps to physical page 0
#and is fetchable, readable, and valid
tlbse r0, r42 #load into entry 0
lc r42, 0x00001000 #denotes VPN 1
lc r43, 0x0000101e #denotes VPN 1 maps to physical page 1
#and is readable, writable, valid, and dirty
#(dirty to prevent taking a
#read-only exception)
tlbse r48, r42 #load into entry 1
#this last tlb entry is designed to produce a bus error
lc r44, 2 #load into TLB entry 2
lc r42, 0x3fffe000 #denotes VPN 0x3fffe
lc r43, 0x3fffe01f #map VPN 0x3fffe to page 0x3fffe
#and is readable, writable, valid, and dirty
#(dirty to prevent taking a
#read-only exception)
tlbse r44, r42
#warp to user mode
rfe r46, r47, r48
#handle exceptions
lc r49, 0xdeadbeef
halt #or rather don't =)
lc r30, 1
jnz k2, r30, r30
trap
#@expected values
#e3 = 0x000000a0
#mode = S
#interrupts = off
#exceptions = off
#r40 = 0x80000050
#r46 = 0x0000005c
#r47 = 1
#r48 = 1
#r42 = 0x3fffe000
#r43 = 0x3fffe01f
#r44 = 2
#r49 = 0xdeadbeef
#pc = 0x8000005c
#e0 = 0x00000060
#e2 = 0x00000060
#e1 = 0x00000001
#tlb 0:
# vpn = 0x00000
# os = 0x000
# ppn = 0x00000
# at = 0x00d
#tlb 1:
# vpn = 0x00001
# os = 0x000
# ppn = 0x00001
# at = 0x01e
#tlb 2:
# vpn = 0x3fffe
# os = 0x000
# ppn = 0x3fffe
# at = 0x01f
|
; A022137: Fibonacci sequence beginning 5, 12.
; 5,12,17,29,46,75,121,196,317,513,830,1343,2173,3516,5689,9205,14894,24099,38993,63092,102085,165177,267262,432439,699701,1132140,1831841,2963981,4795822,7759803,12555625,20315428,32871053,53186481,86057534,139244015
mov $1,5
mov $2,12
lpb $0,1
sub $0,1
add $3,$2
mov $2,$1
mov $1,$3
lpe
|
/*********************************************************************
*
* Copyright (C) 2001, 2003-2004, Karlsruhe University
*
* File path: amd64-getc.cc
* Description: getc() for amd64-based PCs
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: amd64-getc.cc,v 1.4.2.1 2006/12/05 17:10:41 skoglund Exp $
*
********************************************************************/
#include <config.h>
#include <l4/types.h>
#include "amd64-port.h"
extern "C" int __l4_getc (void);
extern "C" int getc (void) __attribute__ ((weak, alias ("__l4_getc")));
#if defined(CONFIG_COMPORT)
#if CONFIG_COMPORT == 0
# define COMPORT 0x3f8
#elif CONFIG_COMPORT == 1
# define COMPORT 0x2f8
#elif CONFIG_COMPORT == 2
# define COMPORT 0x3e8
#elif CONFIG_COMPORT == 3
# define COMPORT 0x2e8
#else
#define COMPORT CONFIG_COMPORT
#endif
int __l4_getc (void)
{
while ((inb(COMPORT+5) & 0x01) == 0);
return inb(COMPORT);
}
#else /* CONFIG_COMPORT */
/* No SHIFT key support!!! */
#define KBD_STATUS_REG 0x64
#define KBD_CNTL_REG 0x64
#define KBD_DATA_REG 0x60
#define KBD_STAT_OBF 0x01 /* Keyboard output buffer full */
#define kbd_read_input() inb(KBD_DATA_REG)
#define kbd_read_status() inb(KBD_STATUS_REG)
static unsigned char keyb_layout[128] =
"\000\0331234567890-+\177\t" /* 0x00 - 0x0f */
"qwertyuiop[]\r\000as" /* 0x10 - 0x1f */
"dfghjkl;'`\000\\zxcv" /* 0x20 - 0x2f */
"bnm,./\000*\000 \000\201\202\203\204\205" /* 0x30 - 0x3f */
"\206\207\210\211\212\000\000789-456+1" /* 0x40 - 0x4f */
"230\177\000\000\213\214\000\000\000\000\000\000\000\000\000\000" /* 0x50 - 0x5f */
"\r\000/"; /* 0x60 - 0x6f */
int __l4_getc(void)
{
static unsigned char last_key = 0;
char c;
while(1) {
unsigned char status = kbd_read_status();
while (status & KBD_STAT_OBF) {
unsigned char scancode;
scancode = kbd_read_input();
if (scancode & 0x80)
last_key = 0;
else if (last_key != scancode)
{
//printf("kbd: %d, %d, %c\n", scancode, last_key, keyb_layout[scancode]);
last_key = scancode;
c = keyb_layout[scancode];
if (c > 0) return c;
}
}
}
}
#endif
|
push ebp
mov ebp,esp
push ecx
call dword ptr ds:[0CDD1BCh]
mov edx,dword ptr [dev]
mov ecx,edx
shl eax,0Ch
sub ecx,eax
xor ecx,edx
and ecx,3F000h
xor ecx,edx
mov dword ptr [dev],ecx
mov esp,ebp
pop ebp
ret |
TITLE ../openssl/crypto/bn/asm/x86-mont.asm
IF @Version LT 800
ECHO MASM version 8.00 or later is strongly recommended.
ENDIF
.686
.XMM
IF @Version LT 800
XMMWORD STRUCT 16
DQ 2 dup (?)
XMMWORD ENDS
ENDIF
.MODEL FLAT
OPTION DOTNAME
IF @Version LT 800
.text$ SEGMENT PAGE 'CODE'
ELSE
.text$ SEGMENT ALIGN(64) 'CODE'
ENDIF
;EXTERN _OPENSSL_ia32cap_P:NEAR
ALIGN 16
_bn_mul_mont PROC PUBLIC
$L_bn_mul_mont_begin::
push ebp
push ebx
push esi
push edi
xor eax,eax
mov edi,DWORD PTR 40[esp]
cmp edi,4
jl $L000just_leave
lea esi,DWORD PTR 20[esp]
lea edx,DWORD PTR 24[esp]
mov ebp,esp
add edi,2
neg edi
lea esp,DWORD PTR [edi*4+esp-32]
neg edi
mov eax,esp
sub eax,edx
and eax,2047
sub esp,eax
xor edx,esp
and edx,2048
xor edx,2048
sub esp,edx
and esp,-64
mov eax,ebp
sub eax,esp
and eax,-4096
$L001page_walk:
mov edx,DWORD PTR [eax*1+esp]
sub eax,4096
DB 46
jnc $L001page_walk
mov eax,DWORD PTR [esi]
mov ebx,DWORD PTR 4[esi]
mov ecx,DWORD PTR 8[esi]
mov edx,DWORD PTR 12[esi]
mov esi,DWORD PTR 16[esi]
mov esi,DWORD PTR [esi]
mov DWORD PTR 4[esp],eax
mov DWORD PTR 8[esp],ebx
mov DWORD PTR 12[esp],ecx
mov DWORD PTR 16[esp],edx
mov DWORD PTR 20[esp],esi
lea ebx,DWORD PTR [edi-3]
mov DWORD PTR 24[esp],ebp
lea eax,DWORD PTR _OPENSSL_ia32cap_P
bt DWORD PTR [eax],26
jnc $L002non_sse2
mov eax,-1
movd mm7,eax
mov esi,DWORD PTR 8[esp]
mov edi,DWORD PTR 12[esp]
mov ebp,DWORD PTR 16[esp]
xor edx,edx
xor ecx,ecx
movd mm4,DWORD PTR [edi]
movd mm5,DWORD PTR [esi]
movd mm3,DWORD PTR [ebp]
pmuludq mm5,mm4
movq mm2,mm5
movq mm0,mm5
pand mm0,mm7
pmuludq mm5,QWORD PTR 20[esp]
pmuludq mm3,mm5
paddq mm3,mm0
movd mm1,DWORD PTR 4[ebp]
movd mm0,DWORD PTR 4[esi]
psrlq mm2,32
psrlq mm3,32
inc ecx
ALIGN 16
$L0031st:
pmuludq mm0,mm4
pmuludq mm1,mm5
paddq mm2,mm0
paddq mm3,mm1
movq mm0,mm2
pand mm0,mm7
movd mm1,DWORD PTR 4[ecx*4+ebp]
paddq mm3,mm0
movd mm0,DWORD PTR 4[ecx*4+esi]
psrlq mm2,32
movd DWORD PTR 28[ecx*4+esp],mm3
psrlq mm3,32
lea ecx,DWORD PTR 1[ecx]
cmp ecx,ebx
jl $L0031st
pmuludq mm0,mm4
pmuludq mm1,mm5
paddq mm2,mm0
paddq mm3,mm1
movq mm0,mm2
pand mm0,mm7
paddq mm3,mm0
movd DWORD PTR 28[ecx*4+esp],mm3
psrlq mm2,32
psrlq mm3,32
paddq mm3,mm2
movq QWORD PTR 32[ebx*4+esp],mm3
inc edx
$L004outer:
xor ecx,ecx
movd mm4,DWORD PTR [edx*4+edi]
movd mm5,DWORD PTR [esi]
movd mm6,DWORD PTR 32[esp]
movd mm3,DWORD PTR [ebp]
pmuludq mm5,mm4
paddq mm5,mm6
movq mm0,mm5
movq mm2,mm5
pand mm0,mm7
pmuludq mm5,QWORD PTR 20[esp]
pmuludq mm3,mm5
paddq mm3,mm0
movd mm6,DWORD PTR 36[esp]
movd mm1,DWORD PTR 4[ebp]
movd mm0,DWORD PTR 4[esi]
psrlq mm2,32
psrlq mm3,32
paddq mm2,mm6
inc ecx
dec ebx
$L005inner:
pmuludq mm0,mm4
pmuludq mm1,mm5
paddq mm2,mm0
paddq mm3,mm1
movq mm0,mm2
movd mm6,DWORD PTR 36[ecx*4+esp]
pand mm0,mm7
movd mm1,DWORD PTR 4[ecx*4+ebp]
paddq mm3,mm0
movd mm0,DWORD PTR 4[ecx*4+esi]
psrlq mm2,32
movd DWORD PTR 28[ecx*4+esp],mm3
psrlq mm3,32
paddq mm2,mm6
dec ebx
lea ecx,DWORD PTR 1[ecx]
jnz $L005inner
mov ebx,ecx
pmuludq mm0,mm4
pmuludq mm1,mm5
paddq mm2,mm0
paddq mm3,mm1
movq mm0,mm2
pand mm0,mm7
paddq mm3,mm0
movd DWORD PTR 28[ecx*4+esp],mm3
psrlq mm2,32
psrlq mm3,32
movd mm6,DWORD PTR 36[ebx*4+esp]
paddq mm3,mm2
paddq mm3,mm6
movq QWORD PTR 32[ebx*4+esp],mm3
lea edx,DWORD PTR 1[edx]
cmp edx,ebx
jle $L004outer
emms
jmp $L006common_tail
ALIGN 16
$L002non_sse2:
mov esi,DWORD PTR 8[esp]
lea ebp,DWORD PTR 1[ebx]
mov edi,DWORD PTR 12[esp]
xor ecx,ecx
mov edx,esi
and ebp,1
sub edx,edi
lea eax,DWORD PTR 4[ebx*4+edi]
or ebp,edx
mov edi,DWORD PTR [edi]
jz $L007bn_sqr_mont
mov DWORD PTR 28[esp],eax
mov eax,DWORD PTR [esi]
xor edx,edx
ALIGN 16
$L008mull:
mov ebp,edx
mul edi
add ebp,eax
lea ecx,DWORD PTR 1[ecx]
adc edx,0
mov eax,DWORD PTR [ecx*4+esi]
cmp ecx,ebx
mov DWORD PTR 28[ecx*4+esp],ebp
jl $L008mull
mov ebp,edx
mul edi
mov edi,DWORD PTR 20[esp]
add eax,ebp
mov esi,DWORD PTR 16[esp]
adc edx,0
imul edi,DWORD PTR 32[esp]
mov DWORD PTR 32[ebx*4+esp],eax
xor ecx,ecx
mov DWORD PTR 36[ebx*4+esp],edx
mov DWORD PTR 40[ebx*4+esp],ecx
mov eax,DWORD PTR [esi]
mul edi
add eax,DWORD PTR 32[esp]
mov eax,DWORD PTR 4[esi]
adc edx,0
inc ecx
jmp $L0092ndmadd
ALIGN 16
$L0101stmadd:
mov ebp,edx
mul edi
add ebp,DWORD PTR 32[ecx*4+esp]
lea ecx,DWORD PTR 1[ecx]
adc edx,0
add ebp,eax
mov eax,DWORD PTR [ecx*4+esi]
adc edx,0
cmp ecx,ebx
mov DWORD PTR 28[ecx*4+esp],ebp
jl $L0101stmadd
mov ebp,edx
mul edi
add eax,DWORD PTR 32[ebx*4+esp]
mov edi,DWORD PTR 20[esp]
adc edx,0
mov esi,DWORD PTR 16[esp]
add ebp,eax
adc edx,0
imul edi,DWORD PTR 32[esp]
xor ecx,ecx
add edx,DWORD PTR 36[ebx*4+esp]
mov DWORD PTR 32[ebx*4+esp],ebp
adc ecx,0
mov eax,DWORD PTR [esi]
mov DWORD PTR 36[ebx*4+esp],edx
mov DWORD PTR 40[ebx*4+esp],ecx
mul edi
add eax,DWORD PTR 32[esp]
mov eax,DWORD PTR 4[esi]
adc edx,0
mov ecx,1
ALIGN 16
$L0092ndmadd:
mov ebp,edx
mul edi
add ebp,DWORD PTR 32[ecx*4+esp]
lea ecx,DWORD PTR 1[ecx]
adc edx,0
add ebp,eax
mov eax,DWORD PTR [ecx*4+esi]
adc edx,0
cmp ecx,ebx
mov DWORD PTR 24[ecx*4+esp],ebp
jl $L0092ndmadd
mov ebp,edx
mul edi
add ebp,DWORD PTR 32[ebx*4+esp]
adc edx,0
add ebp,eax
adc edx,0
mov DWORD PTR 28[ebx*4+esp],ebp
xor eax,eax
mov ecx,DWORD PTR 12[esp]
add edx,DWORD PTR 36[ebx*4+esp]
adc eax,DWORD PTR 40[ebx*4+esp]
lea ecx,DWORD PTR 4[ecx]
mov DWORD PTR 32[ebx*4+esp],edx
cmp ecx,DWORD PTR 28[esp]
mov DWORD PTR 36[ebx*4+esp],eax
je $L006common_tail
mov edi,DWORD PTR [ecx]
mov esi,DWORD PTR 8[esp]
mov DWORD PTR 12[esp],ecx
xor ecx,ecx
xor edx,edx
mov eax,DWORD PTR [esi]
jmp $L0101stmadd
ALIGN 16
$L007bn_sqr_mont:
mov DWORD PTR [esp],ebx
mov DWORD PTR 12[esp],ecx
mov eax,edi
mul edi
mov DWORD PTR 32[esp],eax
mov ebx,edx
shr edx,1
and ebx,1
inc ecx
ALIGN 16
$L011sqr:
mov eax,DWORD PTR [ecx*4+esi]
mov ebp,edx
mul edi
add eax,ebp
lea ecx,DWORD PTR 1[ecx]
adc edx,0
lea ebp,DWORD PTR [eax*2+ebx]
shr eax,31
cmp ecx,DWORD PTR [esp]
mov ebx,eax
mov DWORD PTR 28[ecx*4+esp],ebp
jl $L011sqr
mov eax,DWORD PTR [ecx*4+esi]
mov ebp,edx
mul edi
add eax,ebp
mov edi,DWORD PTR 20[esp]
adc edx,0
mov esi,DWORD PTR 16[esp]
lea ebp,DWORD PTR [eax*2+ebx]
imul edi,DWORD PTR 32[esp]
shr eax,31
mov DWORD PTR 32[ecx*4+esp],ebp
lea ebp,DWORD PTR [edx*2+eax]
mov eax,DWORD PTR [esi]
shr edx,31
mov DWORD PTR 36[ecx*4+esp],ebp
mov DWORD PTR 40[ecx*4+esp],edx
mul edi
add eax,DWORD PTR 32[esp]
mov ebx,ecx
adc edx,0
mov eax,DWORD PTR 4[esi]
mov ecx,1
ALIGN 16
$L0123rdmadd:
mov ebp,edx
mul edi
add ebp,DWORD PTR 32[ecx*4+esp]
adc edx,0
add ebp,eax
mov eax,DWORD PTR 4[ecx*4+esi]
adc edx,0
mov DWORD PTR 28[ecx*4+esp],ebp
mov ebp,edx
mul edi
add ebp,DWORD PTR 36[ecx*4+esp]
lea ecx,DWORD PTR 2[ecx]
adc edx,0
add ebp,eax
mov eax,DWORD PTR [ecx*4+esi]
adc edx,0
cmp ecx,ebx
mov DWORD PTR 24[ecx*4+esp],ebp
jl $L0123rdmadd
mov ebp,edx
mul edi
add ebp,DWORD PTR 32[ebx*4+esp]
adc edx,0
add ebp,eax
adc edx,0
mov DWORD PTR 28[ebx*4+esp],ebp
mov ecx,DWORD PTR 12[esp]
xor eax,eax
mov esi,DWORD PTR 8[esp]
add edx,DWORD PTR 36[ebx*4+esp]
adc eax,DWORD PTR 40[ebx*4+esp]
mov DWORD PTR 32[ebx*4+esp],edx
cmp ecx,ebx
mov DWORD PTR 36[ebx*4+esp],eax
je $L006common_tail
mov edi,DWORD PTR 4[ecx*4+esi]
lea ecx,DWORD PTR 1[ecx]
mov eax,edi
mov DWORD PTR 12[esp],ecx
mul edi
add eax,DWORD PTR 32[ecx*4+esp]
adc edx,0
mov DWORD PTR 32[ecx*4+esp],eax
xor ebp,ebp
cmp ecx,ebx
lea ecx,DWORD PTR 1[ecx]
je $L013sqrlast
mov ebx,edx
shr edx,1
and ebx,1
ALIGN 16
$L014sqradd:
mov eax,DWORD PTR [ecx*4+esi]
mov ebp,edx
mul edi
add eax,ebp
lea ebp,DWORD PTR [eax*1+eax]
adc edx,0
shr eax,31
add ebp,DWORD PTR 32[ecx*4+esp]
lea ecx,DWORD PTR 1[ecx]
adc eax,0
add ebp,ebx
adc eax,0
cmp ecx,DWORD PTR [esp]
mov DWORD PTR 28[ecx*4+esp],ebp
mov ebx,eax
jle $L014sqradd
mov ebp,edx
add edx,edx
shr ebp,31
add edx,ebx
adc ebp,0
$L013sqrlast:
mov edi,DWORD PTR 20[esp]
mov esi,DWORD PTR 16[esp]
imul edi,DWORD PTR 32[esp]
add edx,DWORD PTR 32[ecx*4+esp]
mov eax,DWORD PTR [esi]
adc ebp,0
mov DWORD PTR 32[ecx*4+esp],edx
mov DWORD PTR 36[ecx*4+esp],ebp
mul edi
add eax,DWORD PTR 32[esp]
lea ebx,DWORD PTR [ecx-1]
adc edx,0
mov ecx,1
mov eax,DWORD PTR 4[esi]
jmp $L0123rdmadd
ALIGN 16
$L006common_tail:
mov ebp,DWORD PTR 16[esp]
mov edi,DWORD PTR 4[esp]
lea esi,DWORD PTR 32[esp]
mov eax,DWORD PTR [esi]
mov ecx,ebx
xor edx,edx
ALIGN 16
$L015sub:
sbb eax,DWORD PTR [edx*4+ebp]
mov DWORD PTR [edx*4+edi],eax
dec ecx
mov eax,DWORD PTR 4[edx*4+esi]
lea edx,DWORD PTR 1[edx]
jge $L015sub
sbb eax,0
and esi,eax
not eax
mov ebp,edi
and ebp,eax
or esi,ebp
ALIGN 16
$L016copy:
mov eax,DWORD PTR [ebx*4+esi]
mov DWORD PTR [ebx*4+edi],eax
mov DWORD PTR 32[ebx*4+esp],ecx
dec ebx
jge $L016copy
mov esp,DWORD PTR 24[esp]
mov eax,1
$L000just_leave:
pop edi
pop esi
pop ebx
pop ebp
ret
_bn_mul_mont ENDP
DB 77,111,110,116,103,111,109,101,114,121,32,77,117,108,116,105
DB 112,108,105,99,97,116,105,111,110,32,102,111,114,32,120,56
DB 54,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121
DB 32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46
DB 111,114,103,62,0
.text$ ENDS
.bss SEGMENT 'BSS'
COMM _OPENSSL_ia32cap_P:DWORD:4
.bss ENDS
END
|
; -------------------------------------------------------------------------
; Copyright (c) 2001, Dr Brian Gladman <brg@gladman.uk.net>, Worcester, UK.
; All rights reserved.
;
; LICENSE TERMS
;
; The free distribution and use of this software in both source and binary
; form is allowed (with or without changes) provided that:
;
; 1. distributions of this source code include the above copyright
; notice, this list of conditions and the following disclaimer;
;
; 2. distributions in binary form include the above copyright
; notice, this list of conditions and the following disclaimer
; in the documentation and/or other associated materials;
;
; 3. the copyright holder's name is not used to endorse products
; built using this software without specific written permission.
;
; DISCLAIMER
;
; This software is provided 'as is' with no explcit or implied warranties
; in respect of any properties, including, but not limited to, correctness
; and fitness for purpose.
; -------------------------------------------------------------------------
; Issue Date: 15/01/2002
; An AES (Rijndael) implementation for the Pentium MMX family using the NASM
; assembler <https://www.nasm.us>. This version only implements
; the standard AES block length (128 bits, 16 bytes) with the same interface
; as that used in my C/C++ implementation. This code does not preserve the
; eax, ecx or edx registers or the artihmetic status flags. However, the ebx,
; esi, edi, and ebp registers are preserved across calls. Only encryption
; and decryption are implemented here, the key schedule code being that from
; compiling aes.c with USE_ASM defined. This code uses VC++ register saving
; conentions; if it is used with another compiler, its conventions for using
; and saving registers will need to be checked.
section .text use32
; aes_rval aes_enc_blk(const unsigned char in_blk[], unsigned char out_blk[], const aes_ctx cx[1]);
; aes_rval aes_dec_blk(const unsigned char in_blk[], unsigned char out_blk[], const aes_ctx cx[1]);
global _aes_enc_blk
global _aes_dec_blk
extern _ft_tab
extern _fl_tab
extern _it_tab
extern _il_tab
;%define USE_MMX ; include this to use MMX registers for temporary storage
;%define USE_EMMS ; include this if you make use of floating point operations
%ifdef USE_MMX
%ifdef USE_EMMS
%define EMMS_ON
%endif
%endif
tlen: equ 1024 ; length of each of 4 'xor' arrays (256 32-bit words)
; offsets to parameters with one register pushed onto stack
in_blk: equ 8 ; input byte array address parameter
out_blk:equ 12 ; output byte array address parameter
ctx: equ 16 ; AES context structure
; offsets in context structure
ksch: equ 0 ; encryption key schedule base address
nrnd: equ 256 ; number of rounds
nblk: equ 260 ; number of rounds
; register mapping for encrypt and decrypt subroutines
%define r0 eax
%define r1 ebx
%define r2 ecx
%define r3 edx
%define r4 esi
%define r5 edi
%define r6 ebp
%define eaxl al
%define eaxh ah
%define ebxl bl
%define ebxh bh
%define ecxl cl
%define ecxh ch
%define edxl dl
%define edxh dh
; This macro takes a 32-bit word representing a column and uses
; each of its four bytes to index into four tables of 256 32-bit
; words to obtain values that are then xored into the appropriate
; output registers r0, r1, r4 or r5.
; Parameters:
; %1 out_state[0]
; %2 out_state[1]
; %3 out_state[2]
; %4 out_state[3]
; %5 table base address
; %6 input register for the round (destroyed)
; %7 scratch register for the round
%macro do_col 7
movzx %7,%6l
xor %1,[4*%7+%5]
movzx %7,%6h
shr %6,16
xor %2,[4*%7+%5+tlen]
movzx %7,%6l
movzx %6,%6h
xor %3,[4*%7+%5+2*tlen]
xor %4,[4*%6+%5+3*tlen]
%endmacro
; initialise output registers from the key schedule
%macro do_fcol 8
mov %1,[%8]
movzx %7,%6l
mov %2,[%8+12]
xor %1,[4*%7+%5]
mov %4,[%8+ 4]
movzx %7,%6h
shr %6,16
xor %2,[4*%7+%5+tlen]
movzx %7,%6l
movzx %6,%6h
xor %4,[4*%6+%5+3*tlen]
mov %6,%3
mov %3,[%8+ 8]
xor %3,[4*%7+%5+2*tlen]
%endmacro
; initialise output registers from the key schedule
%macro do_icol 8
mov %1,[%8]
movzx %7,%6l
mov %2,[%8+ 4]
xor %1,[4*%7+%5]
mov %4,[%8+12]
movzx %7,%6h
shr %6,16
xor %2,[4*%7+%5+tlen]
movzx %7,%6l
movzx %6,%6h
xor %4,[4*%6+%5+3*tlen]
mov %6,%3
mov %3,[%8+ 8]
xor %3,[4*%7+%5+2*tlen]
%endmacro
; These macros implement either MMX or stack based local variables
%ifdef USE_MMX
%macro save 2
movd mm%1,%2
%endmacro
%macro restore 2
movd %1,mm%2
%endmacro
%else
%macro save 2
mov [esp+4*%1],%2
%endmacro
%macro restore 2
mov %1,[esp+4*%2]
%endmacro
%endif
; This macro performs a forward encryption cycle. It is entered with
; the first previous round column values in r0, r1, r4 and r5 and
; exits with the final values in the same registers, using the MMX
; registers mm0-mm1 for temporary storage
%macro fwd_rnd 1-2 _ft_tab
; mov current column values into the MMX registers
mov r2,r0
save 0,r1
save 1,r5
; compute new column values
do_fcol r0,r5,r4,r1, %2, r2,r3, %1
do_col r4,r1,r0,r5, %2, r2,r3
restore r2,0
do_col r1,r0,r5,r4, %2, r2,r3
restore r2,1
do_col r5,r4,r1,r0, %2, r2,r3
%endmacro
; This macro performs an inverse encryption cycle. It is entered with
; the first previous round column values in r0, r1, r4 and r5 and
; exits with the final values in the same registers, using the MMX
; registers mm0-mm1 for temporary storage
%macro inv_rnd 1-2 _it_tab
; mov current column values into the MMX registers
mov r2,r0
save 0,r1
save 1,r5
; compute new column values
do_icol r0,r1,r4,r5, %2, r2,r3, %1
do_col r4,r5,r0,r1, %2, r2,r3
restore r2,0
do_col r1,r4,r5,r0, %2, r2,r3
restore r2,1
do_col r5,r0,r1,r4, %2, r2,r3
%endmacro
; AES (Rijndael) Encryption Subroutine
_aes_enc_blk:
push ebp
mov ebp,[esp+ctx] ; pointer to context
xor eax,eax
test [ebp+nblk],byte 1
je .0
cmp eax,[ebp+nrnd] ; encryption/decryption flags
jne short .1
.0: pop ebp
ret
; CAUTION: the order and the values used in these assigns
; rely on the register mappings
.1: push ebx
mov r2,[esp+in_blk+4]
push esi
mov r3,[ebp+nrnd] ; number of rounds
push edi
lea r6,[ebp+ksch] ; key pointer
; input four columns and xor in first round key
mov r0,[r2]
mov r1,[r2+4]
mov r4,[r2+8]
mov r5,[r2+12]
xor r0,[r6]
xor r1,[r6+4]
xor r4,[r6+8]
xor r5,[r6+12]
%ifndef USE_MMX
sub esp,8 ; space for register saves on stack
%endif
add r6,16 ; increment to next round key
sub r3,10
je .4 ; 10 rounds for 128-bit key
add r6,32
sub r3,2
je .3 ; 12 rounds for 128-bit key
add r6,32
.2: fwd_rnd r6-64 ; 14 rounds for 128-bit key
fwd_rnd r6-48
.3: fwd_rnd r6-32 ; 12 rounds for 128-bit key
fwd_rnd r6-16
.4: fwd_rnd r6 ; 10 rounds for 128-bit key
fwd_rnd r6+ 16
fwd_rnd r6+ 32
fwd_rnd r6+ 48
fwd_rnd r6+ 64
fwd_rnd r6+ 80
fwd_rnd r6+ 96
fwd_rnd r6+112
fwd_rnd r6+128
fwd_rnd r6+144,_fl_tab ; last round uses a different table
; move final values to the output array. CAUTION: the
; order of these assigns rely on the register mappings
%ifndef USE_MMX
add esp,8
%endif
mov r6,[esp+out_blk+12]
mov [r6+12],r5
pop edi
mov [r6+8],r4
pop esi
mov [r6+4],r1
pop ebx
mov [r6],r0
pop ebp
mov eax,1
%ifdef EMMS_ON
emms
%endif
ret
; AES (Rijndael) Decryption Subroutine
_aes_dec_blk:
push ebp
mov ebp,[esp+ctx] ; pointer to context
xor eax,eax
test [ebp+nblk],byte 2
je .0
cmp eax,[ebp+nrnd] ; encryption/decryption flags
jne short .1
.0: pop ebp
ret
; CAUTION: the order and the values used in these assigns
; rely on the register mappings
.1: push ebx
mov r2,[esp+in_blk+4]
push esi
mov r3,[ebp+nrnd] ; number of rounds
push edi
lea r6,[ebp+ksch] ; key pointer
mov r0,r3
shl r0,4
add r6,r0
; input four columns and xor in first round key
mov r0,[r2]
mov r1,[r2+4]
mov r4,[r2+8]
mov r5,[r2+12]
xor r0,[r6]
xor r1,[r6+4]
xor r4,[r6+8]
xor r5,[r6+12]
%ifndef USE_MMX
sub esp,8 ; space for register saves on stack
%endif
sub r6,16 ; increment to next round key
sub r3,10
je .4 ; 10 rounds for 128-bit key
sub r6,32
sub r3,2
je .3 ; 12 rounds for 128-bit key
sub r6,32
.2: inv_rnd r6+64 ; 14 rounds for 128-bit key
inv_rnd r6+48
.3: inv_rnd r6+32 ; 12 rounds for 128-bit key
inv_rnd r6+16
.4: inv_rnd r6 ; 10 rounds for 128-bit key
inv_rnd r6- 16
inv_rnd r6- 32
inv_rnd r6- 48
inv_rnd r6- 64
inv_rnd r6- 80
inv_rnd r6- 96
inv_rnd r6-112
inv_rnd r6-128
inv_rnd r6-144,_il_tab ; last round uses a different table
; move final values to the output array. CAUTION: the
; order of these assigns rely on the register mappings
%ifndef USE_MMX
add esp,8
%endif
mov r6,[esp+out_blk+12]
mov [r6+12],r5
pop edi
mov [r6+8],r4
pop esi
mov [r6+4],r1
pop ebx
mov [r6],r0
pop ebp
mov eax,1
%ifdef EMMS_ON
emms
%endif
ret
end
|
db 0 ; species ID placeholder
db 75, 55, 60, 45, 85, 65
; hp atk def spd sat sdf
db ELECTRIC, ELECTRIC ; type
db 120 ; catch rate
db 117 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F50 ; gender ratio
db 100 ; unknown 1
db 20 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/flaaffy/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_SLOW ; growth rate
dn EGG_MONSTER, EGG_GROUND ; egg groups
; tm/hm learnset
tmhm DYNAMICPUNCH, HEADBUTT, CURSE, TOXIC, ZAP_CANNON, ROCK_SMASH, SNORE, PROTECT, RAIN_DANCE, NUZZLE, IRON_HEAD, MOONBLAST, THUNDER, EARTHQUAKE, RETURN, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SWIFT, THUNDERPUNCH, REST, ATTRACT, SURF, STRENGTH, FLASH, WATERFALL, THUNDERBOLT
; end
|
; A332426: Number of unordered pairs of non-selfintersecting paths with nodes that cover all vertices of a convex n-gon.
; Submitted by Christian Krause
; 0,3,30,210,1260,6944,36288,182880,897600,4316928,20427264,95373824,440294400,2013020160,9126248448,41069371392,183607050240,816037560320,3607758766080,15874168848384,69544044134400,303465064562688
mov $1,2
pow $1,$0
add $0,3
bin $0,2
bin $1,2
mul $0,$1
div $0,2
|
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/web_apps/file_handler_launch_dialog_view.h"
#include <memory>
#include <string>
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_utils.h"
#include "chrome/grit/generated_resources.h"
#include "components/vector_icons/vector_icons.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/gfx/text_elider.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/view_class_properties.h"
namespace web_app {
FileHandlerLaunchDialogView::FileHandlerLaunchDialogView(
const std::vector<base::FilePath>& file_paths,
Profile* profile,
const AppId& app_id,
chrome::WebAppLaunchAcceptanceCallback close_callback)
: LaunchAppUserChoiceDialogView(profile, app_id, std::move(close_callback)),
file_paths_(file_paths) {
auto* layout_provider = views::LayoutProvider::Get();
gfx::Insets dialog_insets = layout_provider->GetDialogInsetsForContentType(
views::DialogContentType::kControl, views::DialogContentType::kControl);
#if defined(OS_CHROMEOS)
// The Chrome OS dialog has no title and no need for a top inset.
dialog_insets.set_top(0);
#endif
set_margins(dialog_insets);
set_fixed_width(layout_provider->GetDistanceMetric(
views::DISTANCE_MODAL_DIALOG_PREFERRED_WIDTH));
}
FileHandlerLaunchDialogView::~FileHandlerLaunchDialogView() = default;
std::unique_ptr<views::View>
FileHandlerLaunchDialogView::CreateAboveAppInfoView() {
return nullptr;
}
std::unique_ptr<views::View>
FileHandlerLaunchDialogView::CreateBelowAppInfoView() {
auto* layout_provider = views::LayoutProvider::Get();
// Description of permission that's being requested.
auto description_view = std::make_unique<views::View>();
auto* box_layout =
description_view->SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical,
/*inside_border_insets=*/gfx::Insets(),
layout_provider->GetDistanceMetric(
views::DISTANCE_UNRELATED_CONTROL_VERTICAL)));
// Question label.
auto* question_label = description_view->AddChildView(
std::make_unique<views::Label>(l10n_util::GetStringFUTF16(
file_paths_.size() > 1
? IDS_WEB_APP_FILE_HANDLING_PERMISSION_DESCRIPTION_MULTIPLE
: IDS_WEB_APP_FILE_HANDLING_PERMISSION_DESCRIPTION,
base::UTF8ToUTF16(web_app::WebAppProvider::GetForWebApps(profile())
->registrar()
.GetAppShortName(app_id())))));
question_label->SetMultiLine(true);
question_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
// File icon and name list.
auto* files_view =
description_view->AddChildView(std::make_unique<views::View>());
files_view->SetLayoutManager(std::make_unique<views::FlexLayout>())
->SetOrientation(views::LayoutOrientation::kHorizontal)
.SetCrossAxisAlignment(views::LayoutAlignment::kStart);
// TODO(tluk): We should be sourcing the size of the file icon from the layout
// provider rather than relying on hardcoded constants.
constexpr int kIconSize = 16;
auto* icon = files_view->AddChildView(
std::make_unique<views::ImageView>(ui::ImageModel::FromVectorIcon(
vector_icons::kDescriptionIcon, ui::kColorIcon, kIconSize)));
const int icon_margin = views::LayoutProvider::Get()->GetDistanceMetric(
views::DISTANCE_RELATED_LABEL_HORIZONTAL);
icon->SetProperty(views::kMarginsKey, gfx::Insets(0, 0, 0, icon_margin));
// File name list.
std::vector<std::u16string> file_names;
// Display at most a dozen files. After that, elide.
size_t displayed_file_name_count =
std::min(file_paths_.size(), static_cast<size_t>(12));
file_names.reserve(displayed_file_name_count + 1);
// Additionally, elide very long file names (the max width is the width
// available for the label).
const int available_width = fixed_width() -
box_layout->inside_border_insets().width() -
icon->GetPreferredSize().width() - icon_margin;
std::transform(file_paths_.begin(),
file_paths_.begin() + displayed_file_name_count,
std::back_inserter(file_names),
[available_width](const base::FilePath& file_path) {
// Use slightly less than the available width since some
// space is needed for the separator.
return gfx::ElideFilename(file_path.BaseName(),
views::Label::GetDefaultFontList(),
0.95 * available_width);
});
if (file_paths_.size() > displayed_file_name_count)
file_names.emplace_back(std::u16string(gfx::kEllipsisUTF16));
auto* files_label =
files_view->AddChildView(std::make_unique<views::Label>(base::JoinString(
file_names, l10n_util::GetStringUTF16(
IDS_WEB_APP_FILE_HANDLING_LIST_SEPARATOR))));
files_label->SetMultiLine(true);
files_label->SetMaximumWidth(available_width);
files_label->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT);
return description_view;
}
std::u16string FileHandlerLaunchDialogView::GetRememberChoiceString() {
bool multiple_associations = false;
std::u16string associations =
GetFileTypeAssociationsHandledByWebAppForDisplay(profile(), app_id(),
&multiple_associations);
return l10n_util::GetStringFUTF16(
multiple_associations
? IDS_WEB_APP_FILE_HANDLING_PERMISSION_STICKY_CHOICE_MULTIPLE
: IDS_WEB_APP_FILE_HANDLING_PERMISSION_STICKY_CHOICE,
associations);
}
BEGIN_METADATA(FileHandlerLaunchDialogView, views::DialogDelegateView)
END_METADATA
} // namespace web_app
namespace chrome {
void ShowWebAppFileLaunchDialog(const std::vector<base::FilePath>& file_paths,
Profile* profile,
const web_app::AppId& app_id,
WebAppLaunchAcceptanceCallback close_callback) {
auto view = std::make_unique<web_app::FileHandlerLaunchDialogView>(
file_paths, profile, app_id, std::move(close_callback));
view->Init();
views::DialogDelegate::CreateDialogWidget(std::move(view),
/*context=*/nullptr,
/*parent=*/nullptr)
->Show();
}
} // namespace chrome
|
/**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "msgeditautocompleter.h"
#include <QTextEdit>
#include <interfaces/core/icoreproxy.h>
#include <interfaces/core/ipluginsmanager.h>
#include "interfaces/azoth/iprovidecommands.h"
#include "core.h"
#include "util.h"
#include "xmlsettingsmanager.h"
#include "corecommandsmanager.h"
namespace LeechCraft
{
namespace Azoth
{
MsgEditAutocompleter::MsgEditAutocompleter (const QString& entryId,
QTextEdit *edit, QObject *parent)
: QObject { parent }
, EntryId_ { entryId }
, MsgEdit_ { edit }
{
}
QStringList MsgEditAutocompleter::GetPossibleCompletions (const QString& firstPart, int pos) const
{
auto result = GetNickCompletions (pos) + GetCommandCompletions (pos);
result.erase (std::remove_if (result.begin (), result.end (),
[&firstPart] (const QString& completion)
{
return !completion.startsWith (firstPart, Qt::CaseInsensitive);
}),
result.end ());
return result;
}
QStringList MsgEditAutocompleter::GetCommandCompletions (int) const
{
const auto entryObj = Core::Instance ().GetEntry (EntryId_);
const auto entry = qobject_cast<ICLEntry*> (entryObj);
if (!entry)
return {};
QStringList result;
auto cmdProvs = Core::Instance ().GetProxy ()->
GetPluginsManager ()->GetAllCastableTo<IProvideCommands*> ();
cmdProvs << Core::Instance ().GetCoreCommandsManager ();
for (const auto prov : cmdProvs)
for (const auto& cmd : prov->GetStaticCommands (entry))
result += cmd.Names_;
return result;
}
QStringList MsgEditAutocompleter::GetNickCompletions (int pos) const
{
const auto entryObj = Core::Instance ().GetEntry (EntryId_);
const auto entry = qobject_cast<IMUCEntry*> (entryObj);
if (!entry)
return {};
auto nicks = GetMucParticipants (EntryId_);
nicks.removeAll (entry->GetNick ());
std::sort (nicks.begin (), nicks.end (),
[] (const QString& left, const QString& right)
{
return QString::localeAwareCompare (left.toLower (), right.toLower ()) < 0;
});
QString postNick;
if (pos == -1)
postNick = XmlSettingsManager::Instance ().property ("PostAddressText").toString ();
postNick += " ";
for (auto& nick : nicks)
nick += postNick;
return nicks;
}
struct NickReplacement
{
int Length_;
QString NewText_;
};
NickReplacement MsgEditAutocompleter::GetNickFromState (const QStringList& completions)
{
if (AvailableNickList_.isEmpty ())
{
AvailableNickList_ = completions;
if (AvailableNickList_.isEmpty ())
return {};
return { NickFirstPart_.size (), AvailableNickList_ [CurrentNickIndex_] };
}
auto newAvailableNick = completions;
int lastNickLen = -1;
if ((newAvailableNick != AvailableNickList_) && (!newAvailableNick.isEmpty ()))
{
int newIndex = newAvailableNick.indexOf (AvailableNickList_ [CurrentNickIndex_ - 1]);
lastNickLen = AvailableNickList_ [CurrentNickIndex_ - 1].length ();
while (newIndex == -1 && CurrentNickIndex_ > 0)
newIndex = newAvailableNick.indexOf (AvailableNickList_ [--CurrentNickIndex_]);
CurrentNickIndex_ = (newIndex == -1 ? 0 : newIndex);
AvailableNickList_ = newAvailableNick;
}
if (CurrentNickIndex_ < AvailableNickList_.count () && CurrentNickIndex_)
return { AvailableNickList_ [CurrentNickIndex_ - 1].size (), AvailableNickList_ [CurrentNickIndex_] };
else if (CurrentNickIndex_)
{
CurrentNickIndex_ = 0;
return { AvailableNickList_.last ().size (), AvailableNickList_ [CurrentNickIndex_] };
}
else
return { lastNickLen, AvailableNickList_ [CurrentNickIndex_] };
}
void MsgEditAutocompleter::complete ()
{
auto cursor = MsgEdit_->textCursor ();
int cursorPosition = cursor.position ();
int pos = -1;
auto text = MsgEdit_->toPlainText ();
if (AvailableNickList_.isEmpty ())
{
pos = text.lastIndexOf (' ', cursorPosition ? cursorPosition - 1 : 0);
LastSpacePosition_ = pos;
}
else
pos = LastSpacePosition_;
if (NickFirstPart_.isNull ())
NickFirstPart_ = cursorPosition ?
text.mid (pos + 1, cursorPosition - pos - 1) :
"";
const auto& completions = GetPossibleCompletions (NickFirstPart_, pos);
const auto& replacement = GetNickFromState (completions);
if (replacement.NewText_.isEmpty ())
return;
text.replace (pos + 1, replacement.Length_, replacement.NewText_);
++CurrentNickIndex_;
MsgEdit_->setPlainText (text);
cursor.setPosition (pos + 1 + replacement.NewText_.size ());
MsgEdit_->setTextCursor (cursor);
}
void MsgEditAutocompleter::resetState ()
{
NickFirstPart_.clear ();
if (!AvailableNickList_.isEmpty ())
{
AvailableNickList_.clear ();
CurrentNickIndex_ = 0;
}
}
}
}
|
* Look for wild card entries V1.04 1985 Tony Tebby QJUMP
* 2017-11-19 1.03 Correct handling of n8_ in wc_cntsc (wl)
* 2018-01-10 1.04 Removed reference to cv_lctab to save memory (MK)
*
section exten
*
xdef wc_look1
xdef wc_look2
*
xref stat_do write out statistics
xref ut_chkri check for room on RI stack
xref ut_fopnp get name and open file
xref ut_gtnm1 get a name
xref ut_opmds open destination
xref ut_opdefx open (with default)
xref ut_fdire read directory entry
xref ut_fceof close file eof is ok
*
include dev8_sbsext_ext_keys
include 'dev8_sbsext_ut_opdefx_keys'
*
fr_source equ $00 pointer to source string
fr_dest equ $04 pointer to destination string
fr_name equ $08 pointer to actual name in source directory
fr_copy equ $0c pointer to copy name
fr_action equ $10 pointer to action routine
fr_dchan equ $14 directory channel ID
fr_diff equ $18 difference in length between names
fr_ftype equ $1a file type
frame equ $1c
fnam_len equ $28
*
* d6 c winchk control reg
* d7 c continue reg
* a0 c screen channel ID
* a4 c action routine address
* a5 s screen channel ID copy
*
* get full file name on stack
*
wc_ffnam
moveq #io.dir,d3 open a directory
bsr.l ut_fopnp
wcff_copy
bne.s wcf_rts
wc_ffcpy
move.l a1,-(sp) save pointer to complete string
moveq #fnam_len,d1 check for space
bsr.l ut_chkri ... on RI stack
sub.w #fnam_len,a1
move.l a1,bv_rip(a6) and move pointer down
*
move.l (sp)+,a2 get pointer to file name
move.w (a6,a2.l),d0 ... and length
beq.s wcf_end ... none at all
wcf_loop
move.b 2(a6,a2.l),(a6,a1.l) copy characters (not length)
addq.l #1,a2
addq.l #1,a1
subq.w #1,d0
bgt.s wcf_loop
wcf_end
clr.b (a6,a1.l) and put a zero at end
wcf_rts
rts
*
* WC_LOOK1 entry
*
wc_look1
moveq #-1,d4 single file only
subq.l #frame-$14,sp create frame
movem.l d0/d6/d7/a0/a4,-(sp) save screen controls and action
sub.l a1,a1 point to null string
bsr.s wc_ffcpy ... and copy it as destination
move.l a5,d0 check number of params
sub.l a3,d0
subq.l #8,d0
bgt.s wc_bp ... too many
bra.s wc_ffset get full filename and setup
*
* WC_LOOK2 entry
*
wc_look2
moveq #0,d4 set 2 file ops
subq.l #frame-$14,sp create frame
movem.l d0/d6/d7/a0/a4,-(sp) and save screen controls and action
move.l a5,d0 get number of parameters
sub.l a3,d0
beq.s wc2_null null parameters
subq.l #8,d0
beq.s wc2_one one parameter
subq.l #8,d0
beq.s wc2_two two parameters
wc_bp
moveq #err.bp,d0
bra.s wc_fr.1
wc2_two
addq.l #8,a3 get destination first
bsr.s wc_ffnam ... as a full file name
bne.s wc_fr.1 ... oops
moveq #io.close,d0 and close the directory
trap #2
*
subq.l #8,a3 now get source
wc_ffset
bsr.s wc_ffnam ... full file name
bne.s wc_fr.1 ... oops
bra.s wc_set
*
wc2_null
wc2_one
bsr.l ut_gtnm1 get the name on the RI stack
bne.s wc_fr.1
move.l a1,bv_rip(a6) and save the pointer
move.l a1,a3 for reuse
wc2_ddest
moveq #io.dir,d3 ... a directory
bsr.l ut_opmds as a destination
beq.s wc2_ddok ... good filename
bpl.s wc2_dev
moveq #err.bp,d4
cmp.l d0,d4 was it bad parameter?
bne.s wc_fr.1 ... no
moveq #-1,d4 ... yes, must be device
bra.s wc2_dcopy
wc2_dev
moveq #-1,d4 destination is device, set single file
wc2_ddok
move.l a1,-(sp)
moveq #io.close,d0 and close file
trap #2
move.l (sp)+,a1
wc2_dcopy
bsr.l wc_ffcpy copy name into right place
*
move.l a3,a1 open old file name
moveq #io.dir,d3 ... a directory
moveq #uod.datd,d2
jsr ut_opdefx
wc_fr.1
bne.l wc_frame ... oops
bsr.l wc_ffcpy copy name into right place
wc_set
movem.l (sp),d0/d6/d7/a5 set screen controls
move.l a0,fr_dchan(sp) save source directory ID
tst.l d7 are statistics required?
bge.s wc_set1 ... no
addq.w #2,d6 two more lines
move.l a5,a4 set screen channel
bsr.l stat_do write out the statistics
moveq #1,d7 set to do all
wc_set1
move.l bv_rip(a6),a1 source name pointer
lea fnam_len(a1),a2 destination name pointer
move.l bv_bfbas(a6),a3 name pointer (includes string length)
lea $40(a3),a4 copy pointer (includes string length)
movem.l a1-a4,fr_source(sp) and save pointers
*
move.l a1,a0 count number of sections in source
bsr.s wc_cntsc
neg.b d4
move.l a2,a0 count number of sections in destination
bsr.s wc_cntsc
move.w d4,fr_diff(sp) and save the difference
*
* Loop through directory entries
*
wc_loop
moveq #io.fstrg,d0 fetch a string
move.l fr_dchan(sp),a0 from the directory
bsr.l ut_fdire
bne.s wc_cldir oops, close the directory
move.b fh_type(a6,a1.l),fr_ftype(sp) set file type
lea fh_name(a1),a1 set start of name
move.w (a6,a1.l),d1 is there a name?
beq.s wc_loop ... no
cmp.l #fh.nmlen,d1
bls.s wc_fncheck
moveq #fh.nmlen,d1 ... name too long
move.w d1,(a6,a1.l)
move.b #'*',2+fh.nmlen-1(a6,a1.l)
wc_fncheck
bsr.s wc_check check if name matches
bne.s wc_loop
move.l a4,d0 running pointer to destination name
movem.l fr_name(sp),a3/a4 reset the two name pointers
sub.l a4,d0 length of destination name
subq.l #2,d0 (less the word at the start)
move.w d0,(a6,a4.l) set length
bsr.s wc_restu ... unblotch network
bsr.s wc_restu
move.l a5,a0 set channel ID
moveq #1,d0
add.b fr_ftype(sp),d0 set EQ for directory
move.l fr_action(sp),a1 do action
jsr (a1)
tst.w d7 ... complete?
blt.s wc_cldir ... ... yes
tst.l d0 ... errors?
bne.s wc_cldir ... ... yes
bra.s wc_loop
wc_cldir
move.l fr_dchan(sp),a0 directory channel ID
bsr.l ut_fceof ... close it
wc_frame
add.w #frame,sp remove stack frame
tst.l d0
rts
page
*
* count sections
*
wc_cntsc
move.l (a6,a0.l),d1 get first four characters
*NET and.l #$dff8ff00,d1 uc letter, any digit, character
*NET cmp.l #$4e305f00,d1 N0_?
sub.l #$00010000,d1 make range 0...7 if nX_ ***1.3
and.l #$00f8ff00,d1 any char, any digit, us, character
cmp.l #$00305f00,d1 c0_?
bne.s wc_cntlp ... no, not network name
st 2(a6,a0.l) blotch out '_'
wc_cntlp
move.b (a6,a0.l),d1 get next character
addq.l #1,a0
beq.s wcr_rts ... end
cmp.b #'_',d1 is it '_'
bne.s wc_cntlp ... no
addq.b #1,d4 ... yes, add one
bra.s wc_cntlp
*
* restore network _
*
wc_restu
exg a3,a4 do both names
cmp.b #-1,4(a6,a3.l) is it $FF (one word at front)
bne.s wcr_rts ... no, not blotched
move.b #'_',4(a6,a3.l) ... yes, unblotch
wcr_rts
rts
page
*
* check if name matches
*
wc_check
moveq #'_',d2 set end of section char
*
* first set up full name from source directory
*
move.l bv_bfbas(a6),a4 copy
addq.l #2,a4 (avoiding the length)
move.l fr_source+4(sp),a0 ... source drive
bsr.l wc_add
move.b d2,(a6,a4.l)
wc_ck_sn
addq.l #1,a4
move.b 2(a6,a1.l),(a6,a4.l) copy characters of file name
addq.l #1,a1
subq.w #1,d1
bgt.s wc_ck_sn
*
clr.b 1(a6,a4.l) put zero at end
move.l bv_bfbas(a6),a3 ... start of name
sub.l a3,a4 ... length
subq.l #1,a4 ... adjusted
move.w a4,(a6,a3.l)
*
* now set all string pointers
*
movem.l fr_source+4(sp),a1-a4
*
addq.l #2,a3 actual name and copy include length
addq.l #2,a4
move.l a3,a0 skip actual source drive name
bsr.l wc_skip
move.l a0,a3
move.l a1,a0 skip wild source drive name
bsr.l wc_skip
move.l a0,a1
move.l a2,a0 start of dest name with destination driv
move.w fr_diff+4(sp),d4 is it all of name?
bge.s wc_st_dest
st d4 ... yes, ensure all of d4 -ve
moveq #0,d2 copy to end
wc_st_dest
bsr.l wc_add
move.l a0,a2
moveq #'_',d2 reset end of section
*
tst.b d4 check length difference
ble.s wc_sect destination shorter or same
wc_st_lp
bsr.l wc_add_ dest longer, transfer section of dest
move.l a0,a2 update destination pointer
subq.b #1,d4
bgt.s wc_st_lp and next if there is one
*
* examine section of source name
*
wc_sect
cmp.b (a6,a2.l),d2 is destination section missing?
seq d3
addq.b #1,d4 (one more section)
move.b (a6,a1.l),d0 get next source character
beq.s wc_nend ... end of source name, it all matches
cmp.b d2,d0 is source section missing?
seq d5
bne.s wc_nsect ... no
*
addq.l #1,a1 skip past missing section of source
addq.b #1,d4 (one more section)
cmp.b #1,d4
ble.s wc_nsect not yet at start of destination
tst.b d3 missing destination section?
bne.s wc_sk_ms ... yes, skip it
move.l a2,a0 ... no, copy it
bsr.s wc_add_
move.l a0,a2
bra.s wc_nsect
wc_sk_ms
addq.l #1,a2
*
* examine section of actual name in directory
*
wc_nsect
tst.b (a6,a3.l) end of name?
beq.s wc_nf ... yes
move.l a3,-(sp) save running pointers to source and name
move.l a1,-(sp)
bsr.s wc_csect compare sections
move.l (sp)+,a1
move.l (sp)+,a0 (do not smash running pointer to name)
bne.s wc_no_match ... sections do not match
*
tst.b d4 still not got to start of destination?
ble.s wc_snext ... yes, do not add to copy name
move.l a1,a0 ... assume first part of copy from soucr
move.b (a6,a2.l),d0 missing section in destination?
beq.s wc_cname ... yes
cmp.b d2,d0
beq.s wc_cname ... yes
*
move.l a2,a0 ... no, get first part of name from dest
wc_cname
bsr.s wc_add_ copy first part of name
move.l a3,a0 ... and rest of actual name
bsr.s wc_add
move.l a2,a0 skip to next bit of destination
bsr.s wc_skip
move.l a0,a2
wc_snext
move.l a1,a0 skip to next bit of source
bsr.s wc_skip
move.l a0,a1
move.l a3,a0 and to next bit of name
bsr.s wc_skip
move.l a0,a3
bra.s wc_sect now next section of source
*
wc_no_match
tst.b d5 no match, missing section?
beq.s wc_nf ... no, end of check
tst.b d3 missing section on destination?
beq.s wc_nskip ... no, skip rest of section in name
bsr.s wc_add_ ... yes, copy whole of section of name
bra.s wc_nnext
wc_nskip
bsr.s wc_skip
wc_nnext
move.l a0,a3 update pointer to name
bra.s wc_nsect
*
wc_nf
moveq #err.nf,d0 set error not found
bra.s wc_rts1
wc_ok
moveq #0,d0
wc_rts1
rts
*
* end of source, copy rest of name
*
wc_nend
tst.w d4 is there a destination?
blt.s wc_ok ... no, done
tst.b (a6,a3.l) any more name?
beq.s wc_rts1 ... no
move.l a3,a0 copy from name
moveq #0,d2 ... to end
wc_add_
moveq #'_',d0 add '_'
wc_ad_loop
move.b d0,(a6,a4.l) put byte in copy name
addq.l #1,a4
wc_add
move.b (a6,a0.l),d0 is next source end of string?
beq.s wc_ad_rts ... yes
addq.l #1,a0 ... no, move on
cmp.b d2,d0 is it end of section?
bne.s wc_ad_loop ... no, add it to copy name
wc_ad_rts
rts
*
wc_skip
move.b (a6,a0.l),d0 end of string?
beq.s wc_sk_rts ... yes
addq.l #1,a0 ... no, move on
cmp.b d2,d0 end of section?
bne.s wc_skip
wc_sk_rts
rts
page
wc_csect
wstr_chk
bsr.s wstr_lc get next lc of wild
move.b d1,d0 ... into d0
beq.s wstr_exit ... end of wild name
cmp.b d2,d0 end of section?
beq.s wstr_exit
exg a1,a3
bsr.s wstr_lc and next lc of string
exg a3,a1
cmp.b d1,d0 and compare
beq.s wstr_chk ... match, carry on
wstr_exit
rts
*
wstr_lc
move.b (a6,a1.l),d1
addq.l #1,a1
cmpi.b #'a',d1
blt.s wlc_rts
cmpi.b #'z',d1
bgt.s wlc_rts
subi.b #32,d1
wlc_rts rts
end
|
; A188530: 2^(2n+1)-5*2^(n-1)-1.
; 2,21,107,471,1967,8031,32447,130431,523007,2094591,8383487,33544191,134197247,536829951,2147401727,8589770751,34359410687,137438298111,549754503167,2199020634111
add $0,3
mov $1,2
pow $1,$0
sub $1,2
bin $1,2
sub $1,15
div $1,4
add $1,2
mov $0,$1
|
INCLUDE "hardware.inc"
INCLUDE "header.inc"
;--------------------------------------------------------------------------
SECTION "Main",HOME
;------------------------------------
ClearSprites:
push hl
ld b,144
call wait_ly
xor a,a
ld b,$A0
ld hl,$FE00
.loop:
ld [hl+],a
dec b
jr nz,.loop
pop hl
ret
PrepareSprites: ; d = number of sprites in test line
ld b,144
call wait_ly
ld hl,$FE00
.loop:
ld a,d
and a,a
ret z
ld a,48+16
ld [hl+],a
ld a,50
ld [hl+],a
ld a,0
ld [hl+],a
ld [hl+],a
dec d
jr .loop
;--------------------------------------------------------------------------
;- Main() -
;--------------------------------------------------------------------------
Main:
; -------------------------------------------------------
ld a,$0A
ld [$0000],a ; enable ram
ld hl,$A000
ld a,LCDCF_ON
ld [rLCDC],a
; -------------------------------------------------------
PERFORM_TEST : MACRO
di
push hl
ld bc,$007F
ld hl,\1
ld de,$FF80
call memcopy
ld b,45
call wait_ly
ld a,50
ld [rLYC],a
ld a,STATF_LYC
ld [rSTAT],a
ld a,IEF_LCDC
ld [rIE],a
xor a,a
ld [rIF],a
pop hl
ei
halt
ENDM
call ClearSprites
ld d,0
.next_spr_number:
push de
push hl
call PrepareSprites
pop hl
ld a,$80
ld [rNR52],a
ld a,$FF
ld [rNR51],a
ld a,$77
ld [rNR50],a
ld a,$C0
ld [rNR11],a
ld a,$E0
ld [rNR12],a
ld a,$00
ld [rNR13],a
ld a,$82
ld [rNR14],a
PERFORM_TEST LCD_INT_HANDLER_0
PERFORM_TEST LCD_INT_HANDLER_1
PERFORM_TEST LCD_INT_HANDLER_2
PERFORM_TEST LCD_INT_HANDLER_3
PERFORM_TEST LCD_INT_HANDLER_4
PERFORM_TEST LCD_INT_HANDLER_5
PERFORM_TEST LCD_INT_HANDLER_6
PERFORM_TEST LCD_INT_HANDLER_7
PERFORM_TEST LCD_INT_HANDLER_8
PERFORM_TEST LCD_INT_HANDLER_9
PERFORM_TEST LCD_INT_HANDLER_10
PERFORM_TEST LCD_INT_HANDLER_11
PERFORM_TEST LCD_INT_HANDLER_12
PERFORM_TEST LCD_INT_HANDLER_13
PERFORM_TEST LCD_INT_HANDLER_14
PERFORM_TEST LCD_INT_HANDLER_15
ld a,$80
ld [rNR52],a
ld a,$FF
ld [rNR51],a
ld a,$77
ld [rNR50],a
ld a,$C0
ld [rNR11],a
ld a,$E0
ld [rNR12],a
ld a,$00
ld [rNR13],a
ld a,$83
ld [rNR14],a
PERFORM_TEST LCD_INT_HANDLER_16
PERFORM_TEST LCD_INT_HANDLER_17
PERFORM_TEST LCD_INT_HANDLER_18
PERFORM_TEST LCD_INT_HANDLER_19
PERFORM_TEST LCD_INT_HANDLER_20
PERFORM_TEST LCD_INT_HANDLER_21
PERFORM_TEST LCD_INT_HANDLER_22
PERFORM_TEST LCD_INT_HANDLER_23
PERFORM_TEST LCD_INT_HANDLER_24
PERFORM_TEST LCD_INT_HANDLER_25
PERFORM_TEST LCD_INT_HANDLER_26
PERFORM_TEST LCD_INT_HANDLER_27
PERFORM_TEST LCD_INT_HANDLER_28
PERFORM_TEST LCD_INT_HANDLER_29
PERFORM_TEST LCD_INT_HANDLER_30
PERFORM_TEST LCD_INT_HANDLER_31
ld a,$80
ld [rNR52],a
ld a,$FF
ld [rNR51],a
ld a,$77
ld [rNR50],a
ld a,$C0
ld [rNR11],a
ld a,$E0
ld [rNR12],a
ld a,$00
ld [rNR13],a
ld a,$82
ld [rNR14],a
pop de
inc d
ld a,16
cp a,d
jp nz,.next_spr_number
; --------------------------------
ld a,$80
ld [rNR52],a
ld a,$FF
ld [rNR51],a
ld a,$77
ld [rNR50],a
ld a,$C0
ld [rNR11],a
ld a,$E0
ld [rNR12],a
ld a,$00
ld [rNR13],a
ld a,$87
ld [rNR14],a
push hl
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
pop hl
ld a,$00
ld [$0000],a ; disable ram
call CPU_fast
ld a,$0A
ld [$0000],a ; enable ram
; ---------------------------------
call ClearSprites
ld d,0
.next_spr_number2:
push de
push hl
call PrepareSprites
pop hl
ld a,$80
ld [rNR52],a
ld a,$FF
ld [rNR51],a
ld a,$77
ld [rNR50],a
ld a,$C0
ld [rNR11],a
ld a,$E0
ld [rNR12],a
ld a,$00
ld [rNR13],a
ld a,$82
ld [rNR14],a
PERFORM_TEST LCD_INT_HANDLER_GBC_0
PERFORM_TEST LCD_INT_HANDLER_GBC_1
PERFORM_TEST LCD_INT_HANDLER_GBC_2
PERFORM_TEST LCD_INT_HANDLER_GBC_3
PERFORM_TEST LCD_INT_HANDLER_GBC_4
PERFORM_TEST LCD_INT_HANDLER_GBC_5
PERFORM_TEST LCD_INT_HANDLER_GBC_6
PERFORM_TEST LCD_INT_HANDLER_GBC_7
PERFORM_TEST LCD_INT_HANDLER_GBC_8
PERFORM_TEST LCD_INT_HANDLER_GBC_9
PERFORM_TEST LCD_INT_HANDLER_GBC_10
PERFORM_TEST LCD_INT_HANDLER_GBC_11
PERFORM_TEST LCD_INT_HANDLER_GBC_12
PERFORM_TEST LCD_INT_HANDLER_GBC_13
PERFORM_TEST LCD_INT_HANDLER_GBC_14
PERFORM_TEST LCD_INT_HANDLER_GBC_15
PERFORM_TEST LCD_INT_HANDLER_GBC_16
ld a,$80
ld [rNR52],a
ld a,$FF
ld [rNR51],a
ld a,$77
ld [rNR50],a
ld a,$C0
ld [rNR11],a
ld a,$E0
ld [rNR12],a
ld a,$00
ld [rNR13],a
ld a,$83
ld [rNR14],a
PERFORM_TEST LCD_INT_HANDLER_GBC_17
PERFORM_TEST LCD_INT_HANDLER_GBC_18
PERFORM_TEST LCD_INT_HANDLER_GBC_19
PERFORM_TEST LCD_INT_HANDLER_GBC_20
PERFORM_TEST LCD_INT_HANDLER_GBC_21
PERFORM_TEST LCD_INT_HANDLER_GBC_22
PERFORM_TEST LCD_INT_HANDLER_GBC_23
PERFORM_TEST LCD_INT_HANDLER_GBC_24
PERFORM_TEST LCD_INT_HANDLER_GBC_25
PERFORM_TEST LCD_INT_HANDLER_GBC_26
PERFORM_TEST LCD_INT_HANDLER_GBC_27
PERFORM_TEST LCD_INT_HANDLER_GBC_28
PERFORM_TEST LCD_INT_HANDLER_GBC_29
PERFORM_TEST LCD_INT_HANDLER_GBC_30
PERFORM_TEST LCD_INT_HANDLER_GBC_31
pop de
inc d
ld a,16
cp a,d
jp nz,.next_spr_number2
; -------------------------------------------------------
ld a,$80
ld [rNR52],a
ld a,$FF
ld [rNR51],a
ld a,$77
ld [rNR50],a
ld a,$C0
ld [rNR11],a
ld a,$E0
ld [rNR12],a
ld a,$00
ld [rNR13],a
ld a,$87
ld [rNR14],a
push hl
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
pop hl
ld a,$00
ld [$0000],a ; disable ram
.endloop:
halt
jr .endloop
; --------------------------------------------------------------
SECTION "functions",ROMX,BANK[1]
LCD_INT_HANDLER_MACRO : MACRO
REPT \1
nop
ENDR
ld a,[$FE00]
ld [hl+],a
ret
ENDM
LCD_INT_HANDLER_0: LCD_INT_HANDLER_MACRO 0
LCD_INT_HANDLER_1: LCD_INT_HANDLER_MACRO 1
LCD_INT_HANDLER_2: LCD_INT_HANDLER_MACRO 2
LCD_INT_HANDLER_3: LCD_INT_HANDLER_MACRO 3
LCD_INT_HANDLER_4: LCD_INT_HANDLER_MACRO 4
LCD_INT_HANDLER_5: LCD_INT_HANDLER_MACRO 5
LCD_INT_HANDLER_6: LCD_INT_HANDLER_MACRO 6
LCD_INT_HANDLER_7: LCD_INT_HANDLER_MACRO 7
LCD_INT_HANDLER_8: LCD_INT_HANDLER_MACRO 8
LCD_INT_HANDLER_9: LCD_INT_HANDLER_MACRO 9
LCD_INT_HANDLER_10: LCD_INT_HANDLER_MACRO 10
LCD_INT_HANDLER_11: LCD_INT_HANDLER_MACRO 11
LCD_INT_HANDLER_12: LCD_INT_HANDLER_MACRO 12
LCD_INT_HANDLER_13: LCD_INT_HANDLER_MACRO 13
LCD_INT_HANDLER_14: LCD_INT_HANDLER_MACRO 14
LCD_INT_HANDLER_15: LCD_INT_HANDLER_MACRO 15
LCD_INT_HANDLER_16: LCD_INT_HANDLER_MACRO 16
LCD_INT_HANDLER_17: LCD_INT_HANDLER_MACRO 17
LCD_INT_HANDLER_18: LCD_INT_HANDLER_MACRO 18
LCD_INT_HANDLER_19: LCD_INT_HANDLER_MACRO 19
LCD_INT_HANDLER_20: LCD_INT_HANDLER_MACRO 20
LCD_INT_HANDLER_21: LCD_INT_HANDLER_MACRO 21
LCD_INT_HANDLER_22: LCD_INT_HANDLER_MACRO 22
LCD_INT_HANDLER_23: LCD_INT_HANDLER_MACRO 23
LCD_INT_HANDLER_24: LCD_INT_HANDLER_MACRO 24
LCD_INT_HANDLER_25: LCD_INT_HANDLER_MACRO 25
LCD_INT_HANDLER_26: LCD_INT_HANDLER_MACRO 26
LCD_INT_HANDLER_27: LCD_INT_HANDLER_MACRO 27
LCD_INT_HANDLER_28: LCD_INT_HANDLER_MACRO 28
LCD_INT_HANDLER_29: LCD_INT_HANDLER_MACRO 29
LCD_INT_HANDLER_30: LCD_INT_HANDLER_MACRO 30
LCD_INT_HANDLER_31: LCD_INT_HANDLER_MACRO 31
LCD_INT_HANDLER_GBC_MACRO : MACRO
push de
pop de
push de
pop de
push de
pop de ; 21
nop
nop
nop
REPT \1
nop
ENDR
ld a,[$FE00]
ld [hl+],a
ret
ENDM
LCD_INT_HANDLER_GBC_0: LCD_INT_HANDLER_GBC_MACRO 0
LCD_INT_HANDLER_GBC_1: LCD_INT_HANDLER_GBC_MACRO 1
LCD_INT_HANDLER_GBC_2: LCD_INT_HANDLER_GBC_MACRO 2
LCD_INT_HANDLER_GBC_3: LCD_INT_HANDLER_GBC_MACRO 3
LCD_INT_HANDLER_GBC_4: LCD_INT_HANDLER_GBC_MACRO 4
LCD_INT_HANDLER_GBC_5: LCD_INT_HANDLER_GBC_MACRO 5
LCD_INT_HANDLER_GBC_6: LCD_INT_HANDLER_GBC_MACRO 6
LCD_INT_HANDLER_GBC_7: LCD_INT_HANDLER_GBC_MACRO 7
LCD_INT_HANDLER_GBC_8: LCD_INT_HANDLER_GBC_MACRO 8
LCD_INT_HANDLER_GBC_9: LCD_INT_HANDLER_GBC_MACRO 9
LCD_INT_HANDLER_GBC_10: LCD_INT_HANDLER_GBC_MACRO 10
LCD_INT_HANDLER_GBC_11: LCD_INT_HANDLER_GBC_MACRO 11
LCD_INT_HANDLER_GBC_12: LCD_INT_HANDLER_GBC_MACRO 12
LCD_INT_HANDLER_GBC_13: LCD_INT_HANDLER_GBC_MACRO 13
LCD_INT_HANDLER_GBC_14: LCD_INT_HANDLER_GBC_MACRO 14
LCD_INT_HANDLER_GBC_15: LCD_INT_HANDLER_GBC_MACRO 15
LCD_INT_HANDLER_GBC_16: LCD_INT_HANDLER_GBC_MACRO 16
LCD_INT_HANDLER_GBC_17: LCD_INT_HANDLER_GBC_MACRO 17
LCD_INT_HANDLER_GBC_18: LCD_INT_HANDLER_GBC_MACRO 18
LCD_INT_HANDLER_GBC_19: LCD_INT_HANDLER_GBC_MACRO 19
LCD_INT_HANDLER_GBC_20: LCD_INT_HANDLER_GBC_MACRO 20
LCD_INT_HANDLER_GBC_21: LCD_INT_HANDLER_GBC_MACRO 21
LCD_INT_HANDLER_GBC_22: LCD_INT_HANDLER_GBC_MACRO 22
LCD_INT_HANDLER_GBC_23: LCD_INT_HANDLER_GBC_MACRO 23
LCD_INT_HANDLER_GBC_24: LCD_INT_HANDLER_GBC_MACRO 24
LCD_INT_HANDLER_GBC_25: LCD_INT_HANDLER_GBC_MACRO 25
LCD_INT_HANDLER_GBC_26: LCD_INT_HANDLER_GBC_MACRO 26
LCD_INT_HANDLER_GBC_27: LCD_INT_HANDLER_GBC_MACRO 27
LCD_INT_HANDLER_GBC_28: LCD_INT_HANDLER_GBC_MACRO 28
LCD_INT_HANDLER_GBC_29: LCD_INT_HANDLER_GBC_MACRO 29
LCD_INT_HANDLER_GBC_30: LCD_INT_HANDLER_GBC_MACRO 30
LCD_INT_HANDLER_GBC_31: LCD_INT_HANDLER_GBC_MACRO 31
; --------------------------------------------------------------
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
*
* \file kindchecker.cc
*
* \brief Check that types are well formed by applying "kinding rules".
*
* This pass ensures we do not do things that violate the design of the
* type system when writing down types.
*
* For example tensors are not allowed to contain functions in Relay.
*
* We check this by ensuring the `dtype` field of a Tensor always
* contains a data type such as `int`, `float`, `uint`.
*/
#include <tvm/relay/analysis.h>
#include <tvm/relay/error.h>
#include "../ir/type_functor.h"
namespace tvm {
namespace relay {
using namespace tvm::runtime;
struct KindChecker : TypeFunctor<Kind(const Type&)> {
const Module& mod;
ErrorReporter err_reporter;
explicit KindChecker(const Module& mod) : mod(mod), err_reporter() {}
void ReportFatalError(const Error& err) {
this->err_reporter.Report(err);
this->err_reporter.RenderErrors(mod);
}
void CheckKindMatches(const Type& t, const Type& outer,
Kind expected, const std::string& description) {
Kind k = this->VisitType(t);
if (k != expected) {
ReportFatalError(RELAY_ERROR("Incorrect kind for a " << description
<< ". Type " << t << " inside " << outer
<< " is of kind " << k
<< " but was expected to be "
<< expected));
}
}
Kind VisitType_(const IncompleteTypeNode* op) override {
return op->kind;
}
Kind VisitType_(const TypeVarNode* op) override {
return op->kind;
}
Kind VisitType_(const GlobalTypeVarNode* op) override {
return op->kind;
}
Kind VisitType_(const TensorTypeNode* op) override {
return Kind::kType;
}
Kind VisitType_(const TupleTypeNode* op) override {
// tuples should only contain normal types
for (const Type& t : op->fields) {
CheckKindMatches(t, GetRef<TupleType>(op), Kind::kType,
"tuple member");
}
return Kind::kType;
}
Kind VisitType_(const FuncTypeNode* op) override {
// Func types should only take normal types for arguments
// and only return a normal type. They should also have
// well-formed constraints
FuncType ft = GetRef<FuncType>(op);
for (const Type& t : op->arg_types) {
CheckKindMatches(t, ft, Kind::kType, "function type parameter");
}
CheckKindMatches(ft->ret_type, ft, Kind::kType, "function return type");
for (const TypeConstraint& tc : op->type_constraints) {
CheckKindMatches(tc, ft, Kind::kConstraint, "function type constraint");
}
return Kind::kType;
}
Kind VisitType_(const RefTypeNode* op) override {
// ref types should only contain normal types
RefType rt = GetRef<RefType>(op);
CheckKindMatches(op->value, rt, Kind::kType, "ref contents");
return Kind::kType;
}
Kind VisitType_(const TypeRelationNode* op) override {
// arguments to type relation should be normal types
for (const Type& t : op->args) {
CheckKindMatches(t, GetRef<TypeRelation>(op), Kind::kType,
"argument to type relation");
}
return Kind::kConstraint;
}
Kind VisitType_(const TypeCallNode* op) override {
// type call func should be a global type var, args should be type
TypeCall tc = GetRef<TypeCall>(op);
const auto* gtv = op->func.as<GlobalTypeVarNode>();
if (gtv == nullptr) {
ReportFatalError(RELAY_ERROR("The callee in " << tc
<< " is not a global type var, but is " << op->func));
}
CheckKindMatches(op->func, tc, Kind::kAdtHandle, "type call function");
for (const Type& t : op->args) {
CheckKindMatches(t, tc, Kind::kType, "type call argument");
}
// finally we need to check the module to check the number of type params
auto var = GetRef<GlobalTypeVar>(gtv);
auto data = mod->LookupTypeDef(var);
if (data->type_vars.size() != op->args.size()) {
ReportFatalError(RELAY_ERROR("Expected " << data->type_vars.size() << "arguments for " << tc
<< "; got " << op->args.size()));
}
return Kind::kType;
}
Kind VisitType_(const TypeDataNode* op) override {
// Constructors can reference the header var, but no other GlobalTypeVars.
// In theory, a TypeData could be nested, so the header scope
// should be tracked recursively, but it is unclear that we need
// to support it.
TypeData td = GetRef<TypeData>(op);
CheckKindMatches(op->header, td, Kind::kAdtHandle, "type data header");
for (const auto& var : op->type_vars) {
CheckKindMatches(var, td, Kind::kType, "ADT type var");
}
for (const auto& con : op->constructors) {
if (!con->belong_to.same_as(op->header)) {
ReportFatalError(RELAY_ERROR(con << " has header " << con->belong_to
<< " but " << op << " has header " << op->header));
}
for (const Type& t : con->inputs) {
CheckKindMatches(t, td, Kind::kType, "ADT constructor input");
}
}
return Kind::kTypeData;
}
Kind Check(const Type& t) {
return this->VisitType(t);
}
};
Kind KindCheck(const Type& t, const Module& mod) {
KindChecker kc(mod);
return kc.Check(t);
}
TVM_REGISTER_GLOBAL("relay._analysis.check_kind")
.set_body([](TVMArgs args, TVMRetValue* ret) {
if (args.size() == 1) {
*ret = KindCheck(args[0], ModuleNode::make({}, {}));
} else {
*ret = KindCheck(args[0], args[1]);
}
});
} // namespace relay
} // namespace tvm
|
/*****************************************************************************
* metaparse.c
*
* DESCRIPTION
* This file contains the code necessary to initialize the meta data
* structure, and parse the meta data that comes out of the GRIB2 decoder.
*
* HISTORY
* 9/2002 Arthur Taylor (MDL / RSIS): Created.
*
* NOTES
* 1) Need to add support for GS3_ORTHOGRAPHIC = 90,
* GS3_EQUATOR_EQUIDIST = 110, GS3_AZIMUTH_RANGE = 120
* 2) Need to add support for GS4_RADAR = 20
*****************************************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "clock.h"
#include "meta.h"
#include "metaname.h"
#include "myassert.h"
#include "myerror.h"
#include "scan.h"
#include "weather.h"
#include "memendian.h"
#include "myutil.h"
#include "cpl_port.h"
/*****************************************************************************
* MetaInit() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To initialize a grib_metaData structure.
*
* ARGUMENTS
* meta = The structure to fill. (Output)
*
* FILES/DATABASES: None
*
* RETURNS: void
*
* HISTORY
* 9/2002 Arthur Taylor (MDL/RSIS): Created.
*
* NOTES
*****************************************************************************
*/
void MetaInit (grib_MetaData *meta)
{
meta->element = NULL;
meta->comment = NULL;
meta->unitName = NULL;
meta->convert = 0;
meta->shortFstLevel = NULL;
meta->longFstLevel = NULL;
meta->pds2.sect2.ptrType = GS2_NONE;
meta->pds2.sect2.wx.data = NULL;
meta->pds2.sect2.wx.dataLen = 0;
meta->pds2.sect2.wx.maxLen = 0;
meta->pds2.sect2.wx.ugly = NULL;
meta->pds2.sect2.unknown.data = NULL;
meta->pds2.sect2.unknown.dataLen = 0;
meta->pds2.sect4.numInterval = 0;
meta->pds2.sect4.Interval = NULL;
meta->pds2.sect4.numBands = 0;
meta->pds2.sect4.bands = NULL;
return;
}
/*****************************************************************************
* MetaSect2Free() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To free the section 2 data in the grib_metaData structure.
*
* ARGUMENTS
* meta = The structure to free. (Input/Output)
*
* FILES/DATABASES: None
*
* RETURNS: void
*
* HISTORY
* 2/2003 Arthur Taylor (MDL/RSIS): Created.
* 3/2003 AAT: Cleaned up declaration of variable: WxType.
*
* NOTES
*****************************************************************************
*/
void MetaSect2Free (grib_MetaData *meta)
{
size_t i; /* Counter for use when freeing Wx data. */
for (i = 0; i < meta->pds2.sect2.wx.dataLen; i++) {
free (meta->pds2.sect2.wx.data[i]);
FreeUglyString (&(meta->pds2.sect2.wx.ugly[i]));
}
free (meta->pds2.sect2.wx.ugly);
meta->pds2.sect2.wx.ugly = NULL;
free (meta->pds2.sect2.wx.data);
meta->pds2.sect2.wx.data = NULL;
meta->pds2.sect2.wx.dataLen = 0;
meta->pds2.sect2.wx.maxLen = 0;
meta->pds2.sect2.ptrType = GS2_NONE;
free (meta->pds2.sect2.wx.data);
meta->pds2.sect2.unknown.data = NULL;
meta->pds2.sect2.unknown.dataLen = 0;
}
/*****************************************************************************
* MetaFree() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To free a grib_metaData structure.
*
* ARGUMENTS
* meta = The structure to free. (Output)
*
* FILES/DATABASES: None
*
* RETURNS: void
*
* HISTORY
* 9/2002 Arthur Taylor (MDL/RSIS): Created.
*
* NOTES
*****************************************************************************
*/
void MetaFree (grib_MetaData *meta)
{
free (meta->pds2.sect4.bands);
meta->pds2.sect4.bands = NULL;
meta->pds2.sect4.numBands = 0;
free (meta->pds2.sect4.Interval);
meta->pds2.sect4.Interval = NULL;
meta->pds2.sect4.numInterval = 0;
MetaSect2Free (meta);
free (meta->unitName);
meta->unitName = NULL;
meta->convert = 0;
free (meta->comment);
meta->comment = NULL;
free (meta->element);
meta->element = NULL;
free (meta->shortFstLevel);
meta->shortFstLevel = NULL;
free (meta->longFstLevel);
meta->longFstLevel = NULL;
}
/*****************************************************************************
* ParseTime() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To parse the time data from the grib2 integer array to a time_t in
* UTC seconds from the epoch.
*
* ARGUMENTS
* AnsTime = The time_t value to fill with the resulting time. (Output)
* year = The year to parse. (Input)
* mon = The month to parse. (Input)
* day = The day to parse. (Input)
* hour = The hour to parse. (Input)
* min = The minute to parse. (Input)
* sec = The second to parse. (Input)
*
* FILES/DATABASES: None
*
* RETURNS: int (could use errSprintf())
* 0 = OK
* -1 = gribLen is too small.
*
* HISTORY
* 9/2002 Arthur Taylor (MDL/RSIS): Created.
* 4/2003 AAT: Modified to use year/mon/day/hour/min/sec instead of an
* integer array.
* 2/2004 AAT: Added error checks (because of corrupt GRIB1 files)
*
* NOTES
* 1) Couldn't use the default time_zone variable (concern over portability
* issues), so we print the hours, and compare them to the hours we had
* intended. Then subtract the difference from the AnsTime.
* 2) Need error check for times outside of 1902..2037.
*****************************************************************************
*/
int ParseTime (double *AnsTime, int year, uChar mon, uChar day, uChar hour,
uChar min, uChar sec)
{
/* struct tm time; *//* A temporary variable to put the time info into. */
/* char buffer[10]; *//* Used when printing the AnsTime's Hr. */
/* int timeZone; *//* The adjustment in Hr needed to get the right UTC * time. */
if ((year < 1900) || (year > 2100)) {
errSprintf ("ParseTime:: year %d is invalid\n", year);
return -1;
}
/* sec is allowed to be 61 for leap seconds. */
if ((mon > 12) || (day == 0) || (day > 31) || (hour > 24) || (min > 60) ||
(sec > 61)) {
errSprintf ("ParseTime:: Problems with %d/%d %d:%d:%d\n", mon, day,
hour, min, sec);
return -1;
}
Clock_ScanDate (AnsTime, year, mon, day);
*AnsTime += hour * 3600. + min * 60. + sec;
/* *AnsTime -= Clock_GetTimeZone() * 3600;*/
/*
memset (&time, 0, sizeof (struct tm));
time.tm_year = year - 1900;
time.tm_mon = mon - 1;
time.tm_mday = day;
time.tm_hour = hour;
time.tm_min = min;
time.tm_sec = sec;
printf ("%ld\n", mktime (&time));
*AnsTime = mktime (&time) - (Clock_GetTimeZone () * 3600);
*/
/* Cheap method of getting global time_zone variable. */
/*
strftime (buffer, 10, "%H", gmtime (AnsTime));
timeZone = atoi (buffer) - hour;
if (timeZone < 0) {
timeZone += 24;
}
*AnsTime = *AnsTime - (timeZone * 3600);
*/
return 0;
}
/*****************************************************************************
* ParseSect0() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To verify and parse section 0 data.
*
* ARGUMENTS
* is0 = The unpacked section 0 array. (Input)
* ns0 = The size of section 0. (Input)
* grib_len = The length of the entire grib message. (Input)
* meta = The structure to fill. (Output)
*
* FILES/DATABASES: None
*
* RETURNS: int (could use errSprintf())
* 0 = OK
* -1 = ns0 is too small.
* -2 = unexpected values in is0.
*
* HISTORY
* 9/2002 Arthur Taylor (MDL/RSIS): Created.
*
* NOTES
* 1) 1196575042L == ASCII representation of "GRIB"
*****************************************************************************
*/
static int ParseSect0 (sInt4 *is0, sInt4 ns0, sInt4 grib_len,
grib_MetaData *meta)
{
if (ns0 < 9) {
return -1;
}
if ((is0[0] != 1196575042L) || (is0[7] != 2) || (is0[8] != grib_len)) {
errSprintf ("ERROR IS0 has unexpected values: %ld %ld %ld\n",
is0[0], is0[7], is0[8]);
errSprintf ("Should be %ld %d %ld\n", 1196575042L, 2, grib_len);
return -2;
}
meta->pds2.prodType = (uChar) is0[6];
return 0;
}
/*****************************************************************************
* ParseSect1() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To verify and parse section 1 data.
*
* ARGUMENTS
* is1 = The unpacked section 1 array. (Input)
* ns1 = The size of section 1. (Input)
* meta = The structure to fill. (Output)
*
* FILES/DATABASES: None
*
* RETURNS: int (could use errSprintf())
* 0 = OK
* -1 = ns1 is too small.
* -2 = unexpected values in is1.
*
* HISTORY
* 9/2002 Arthur Taylor (MDL/RSIS): Created.
*
* NOTES
*****************************************************************************
*/
static int ParseSect1 (sInt4 *is1, sInt4 ns1, grib_MetaData *meta)
{
if (ns1 < 21) {
return -1;
}
if (is1[4] != 1) {
errSprintf ("ERROR IS1 not labeled correctly. %ld\n", is1[4]);
return -2;
}
meta->center = (unsigned short int) is1[5];
meta->subcenter = (unsigned short int) is1[7];
meta->pds2.mstrVersion = (uChar) is1[9];
meta->pds2.lclVersion = (uChar) is1[10];
if (((meta->pds2.mstrVersion < 1) || (meta->pds2.mstrVersion > 3)) ||
(meta->pds2.lclVersion > 1)) {
if (meta->pds2.mstrVersion == 0) {
printf ("Warning: Master table version == 0, was experimental\n"
"I don't have a copy, and don't know where to get one\n"
"Use meta data at your own risk.\n");
} else {
errSprintf ("Master table version supported (1,2,3) yours is %d... "
"Local table version supported (0,1) yours is %d...\n",
meta->pds2.mstrVersion, meta->pds2.lclVersion);
return -2;
}
}
meta->pds2.sigTime = (uChar) is1[11];
if (ParseTime (&(meta->pds2.refTime), is1[12], is1[14], is1[15], is1[16],
is1[17], is1[18]) != 0) {
preErrSprintf ("Error in call to ParseTime from ParseSect1 (GRIB2)");
return -2;
}
meta->pds2.operStatus = (uChar) is1[19];
meta->pds2.dataType = (uChar) is1[20];
return 0;
}
/*****************************************************************************
* ParseSect2_Wx() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To verify and parse section 2 data when we know the variable is of type
* Wx (Weather).
*
* ARGUMENTS
* rdat = The float data in section 2. (Input)
* nrdat = Length of rdat. (Input)
* idat = The integer data in section 2. (Input)
* nidat = Length of idat. (Input)
* Wx = The weather structure to fill. (Output)
* simpVer = The version of the simple weather code to use when parsing the
* WxString. (Input)
*
* FILES/DATABASES: None
*
* RETURNS: int (could use errSprintf())
* 0 = OK
* -1 = nrdat or nidat is too small.
* -2 = unexpected values in rdat.
*
* HISTORY
* 2/2003 Arthur Taylor (MDL/RSIS): Created.
* 5/2003 AAT: Stopped messing around with the way buffer and data[i]
* were allocated. It was confusing the free routine.
* 5/2003 AAT: Added maxLen to Wx structure.
* 6/2003 AAT: Revisited after Matt (matt@wunderground.com) informed me of
* memory problems.
* 1) I had a memory leak caused by a buffer+= buffLen
* 2) buffLen could have increased out of bounds of buffer.
* 8/2003 AAT: Found an invalid "assertion" when dealing with non-NULL
* terminated weather groups.
*
* NOTES
* 1) May want to rewrite so that we don't need 'meta->sect2NumGroups'
*****************************************************************************
*/
static int ParseSect2_Wx (float *rdat, sInt4 nrdat, sInt4 *idat,
uInt4 nidat, sect2_WxType *Wx, int simpVer)
{
size_t loc; /* Where we currently are in idat. */
size_t groupLen; /* Length of current group in idat. */
size_t j; /* Counter over the length of the current group. */
char *buffer; /* Used to store the current "ugly" string. */
int buffLen; /* Length of current "ugly" string. */
int len; /* length of current english phrases during creation
* of the maxEng[] data. */
int i; /* assists in traversing the maxEng[] array. */
if (nrdat < 1) {
return -1;
}
if (rdat[0] != 0) {
errSprintf ("ERROR: Expected rdat to be empty when dealing with "
"section 2 Weather data\n");
return -2;
}
Wx->dataLen = 0;
Wx->data = NULL;
Wx->maxLen = 0;
for (i = 0; i < NUM_UGLY_WORD; i++) {
Wx->maxEng[i] = 0;
}
loc = 0;
if (nidat <= loc) {
errSprintf ("ERROR: Ran out of idat data\n");
return -1;
}
groupLen = idat[loc++];
loc++; /* Skip the decimal scale factor data. */
/* Note: This also assures that buffLen stays <= nidat. */
if (loc + groupLen >= nidat) {
errSprintf ("ERROR: Ran out of idat data\n");
return -1;
}
buffLen = 0;
buffer = (char *) malloc ((nidat + 1) * sizeof (char));
while (groupLen > 0) {
for (j = 0; j < groupLen; j++) {
buffer[buffLen] = (char) idat[loc];
buffLen++;
loc++;
if (buffer[buffLen - 1] == '\0') {
Wx->dataLen++;
Wx->data = (char **) realloc ((void *) Wx->data,
Wx->dataLen * sizeof (char *));
/* This is done after the realloc, just to make sure we have
* enough memory allocated. */
/* Assert: buffLen is 1 more than strlen(buffer). */
Wx->data[Wx->dataLen - 1] = (char *)
malloc (buffLen * sizeof (char));
strcpy (Wx->data[Wx->dataLen - 1], buffer);
if (Wx->maxLen < buffLen) {
Wx->maxLen = buffLen;
}
buffLen = 0;
}
}
if (loc >= nidat) {
groupLen = 0;
} else {
groupLen = idat[loc];
loc++;
if (groupLen != 0) {
loc++; /* Skip the decimal scale factor data. */
/* Note: This also assures that buffLen stays <= nidat. */
if (loc + groupLen >= nidat) {
errSprintf ("ERROR: Ran out of idat data\n");
free (buffer);
return -1;
}
}
}
}
if (buffLen != 0) {
buffer[buffLen] = '\0';
Wx->dataLen++;
Wx->data = (char **) realloc ((void *) Wx->data,
Wx->dataLen * sizeof (char *));
/* Assert: buffLen is 1 more than strlen(buffer). -- FALSE -- */
buffLen = strlen (buffer) + 1;
Wx->data[Wx->dataLen - 1] = (char *) malloc (buffLen * sizeof (char));
if (Wx->maxLen < buffLen) {
Wx->maxLen = buffLen;
}
strcpy (Wx->data[Wx->dataLen - 1], buffer);
}
free (buffer);
Wx->ugly = (UglyStringType *) malloc (Wx->dataLen *
sizeof (UglyStringType));
for (j = 0; j < Wx->dataLen; j++) {
ParseUglyString (&(Wx->ugly[j]), Wx->data[j], simpVer);
}
/* We want to know how many bytes we need for each english phrase column,
* so we walk through each column calculating that value. */
for (i = 0; i < NUM_UGLY_WORD; i++) {
/* Assert: Already initialized Wx->maxEng[i]. */
for (j = 0; j < Wx->dataLen; j++) {
if (Wx->ugly[j].english[i] != NULL) {
len = strlen (Wx->ugly[j].english[i]);
if (len > Wx->maxEng[i]) {
Wx->maxEng[i] = len;
}
}
}
}
return 0;
}
/*****************************************************************************
* ParseSect2_Unknown() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To verify and parse section 2 data when we don't know anything more
* about the data.
*
* ARGUMENTS
* rdat = The float data in section 2. (Input)
* nrdat = Length of rdat. (Input)
* idat = The integer data in section 2. (Input)
* nidat = Length of idat. (Input)
* meta = The structure to fill. (Output)
*
* FILES/DATABASES: None
*
* RETURNS: int (could use errSprintf())
* 0 = OK
* -1 = nrdat or nidat is too small.
* -2 = unexpected values in rdat.
*
* HISTORY
* 2/2003 Arthur Taylor (MDL/RSIS): Created.
*
* NOTES
* In the extremely improbable case that there is both idat data and rdat
* data, we process the rdat data first.
*****************************************************************************
*/
static int ParseSect2_Unknown (float *rdat, sInt4 nrdat, sInt4 *idat,
sInt4 nidat, grib_MetaData *meta)
{
/* Used for easier access to answer. */
int loc; /* Where we currently are in idat. */
int ansLoc; /* Where we are in the answer data structure. */
sInt4 groupLen; /* Length of current group in idat. */
int j; /* Counter over the length of the current group. */
meta->pds2.sect2.unknown.dataLen = 0;
meta->pds2.sect2.unknown.data = NULL;
ansLoc = 0;
/* Work with rdat data. */
loc = 0;
if (nrdat <= loc) {
errSprintf ("ERROR: Ran out of rdat data\n");
return -1;
}
groupLen = (sInt4) rdat[loc++];
loc++; /* Skip the decimal scale factor data. */
if (nrdat <= loc + groupLen) {
errSprintf ("ERROR: Ran out of rdat data\n");
return -1;
}
while (groupLen > 0) {
meta->pds2.sect2.unknown.dataLen += groupLen;
meta->pds2.sect2.unknown.data = (double *)
realloc ((void *) meta->pds2.sect2.unknown.data,
meta->pds2.sect2.unknown.dataLen * sizeof (double));
for (j = 0; j < groupLen; j++) {
meta->pds2.sect2.unknown.data[ansLoc++] = rdat[loc++];
}
if (nrdat <= loc) {
groupLen = 0;
} else {
groupLen = (sInt4) rdat[loc++];
if (groupLen != 0) {
loc++; /* Skip the decimal scale factor data. */
if (nrdat <= loc + groupLen) {
errSprintf ("ERROR: Ran out of rdat data\n");
return -1;
}
}
}
}
/* Work with idat data. */
loc = 0;
if (nidat <= loc) {
errSprintf ("ERROR: Ran out of idat data\n");
return -1;
}
groupLen = idat[loc++];
loc++; /* Skip the decimal scale factor data. */
if (nidat <= loc + groupLen) {
errSprintf ("ERROR: Ran out of idat data\n");
return -1;
}
while (groupLen > 0) {
meta->pds2.sect2.unknown.dataLen += groupLen;
meta->pds2.sect2.unknown.data = (double *)
realloc ((void *) meta->pds2.sect2.unknown.data,
meta->pds2.sect2.unknown.dataLen * sizeof (double));
for (j = 0; j < groupLen; j++) {
meta->pds2.sect2.unknown.data[ansLoc++] = idat[loc++];
}
if (nidat <= loc) {
groupLen = 0;
} else {
groupLen = idat[loc++];
if (groupLen != 0) {
loc++; /* Skip the decimal scale factor data. */
if (nidat <= loc + groupLen) {
errSprintf ("ERROR: Ran out of idat data\n");
return -1;
}
}
}
}
return 0;
}
/*****************************************************************************
* ParseSect3() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To verify and parse section 3 data.
*
* ARGUMENTS
* is3 = The unpacked section 3 array. (Input)
* ns3 = The size of section 3. (Input)
* meta = The structure to fill. (Output)
*
* FILES/DATABASES: None
*
* RETURNS: int (could use errSprintf())
* 0 = OK
* -1 = ns3 is too small.
* -2 = unexpected values in is3.
* -3 = un-supported map Projection.
*
* HISTORY
* 9/2002 Arthur Taylor (MDL/RSIS): Created.
* 9/2003 AAT: Adjusted Radius Earth case 1,6 to be based on:
* Y * 10^D = R
* Where Y = original value, D is scale factor, R is scale value.
* 1/2004 AAT: Adjusted Radius Earth case 6 to always be 6371.229 km
*
* NOTES
* Need to add support for GS3_ORTHOGRAPHIC = 90,
* GS3_EQUATOR_EQUIDIST = 110, GS3_AZIMUTH_RANGE = 120
*****************************************************************************
*/
static int ParseSect3 (sInt4 *is3, sInt4 ns3, grib_MetaData *meta)
{
double unit; /* Used to convert from stored value to degrees
* lat/lon. See GRIB2 Regulation 92.1.6 */
sInt4 angle; /* For Lat/Lon, 92.1.6 may not hold, in which case,
* angle != 0, and unit = angle/subdivision. */
sInt4 subdivision; /* see angle explaination. */
if (ns3 < 14) {
return -1;
}
if (is3[4] != 3) {
errSprintf ("ERROR IS3 not labeled correctly. %ld\n", is3[4]);
return -2;
}
if (is3[5] != 0) {
errSprintf ("Can not handle 'Source of Grid Definition' = %ld\n",
is3[5]);
errSprintf ("Can only handle grids defined in Code table 3.1\n");
// return -3;
}
meta->gds.numPts = is3[6];
if ((is3[10] != 0) || (is3[11] != 0)) {
errSprintf ("Un-supported Map Projection.\n All Supported "
"projections have 0 bytes following the template.\n");
// return -3;
}
meta->gds.projType = (uChar) is3[12];
// Don't refuse to convert the GRIB file if only the projection is unknown to us
/*
if ((is3[12] != GS3_LATLON) && (is3[12] != GS3_MERCATOR) &&
(is3[12] != GS3_POLAR) && (is3[12] != GS3_LAMBERT)) {
errSprintf ("Un-supported Map Projection %ld\n", is3[12]);
return -3;
}
*/
/*
* Handle variables common to the supported templates.
*/
if (ns3 < 38) {
return -1;
}
/* Assert: is3[14] is the shape of the earth. */
switch (is3[14]) {
case 0:
meta->gds.f_sphere = 1;
meta->gds.majEarth = 6367.47;
meta->gds.minEarth = 6367.47;
break;
case 6:
meta->gds.f_sphere = 1;
meta->gds.majEarth = 6371.229;
meta->gds.minEarth = 6371.229;
break;
case 1:
meta->gds.f_sphere = 1;
/* Following assumes scale factor and scale value refer to
* scientific notation. */
/* Incorrect Assumption (9/8/2003): scale factor / value are based
* on: Y * 10^D = R, where Y = original value, D = scale factor, ___
* R = scale value. */
if ((is3[16] != GRIB2MISSING_s4) && (is3[15] != GRIB2MISSING_s1)) {
/* Assumes data is given in m (not km). */
meta->gds.majEarth = is3[16] / (pow (10.0, is3[15]) * 1000.);
meta->gds.minEarth = meta->gds.majEarth;
} else {
errSprintf ("Missing info on radius of Earth.\n");
return -2;
}
/* Check if our m assumption was valid. If it wasn't, they give us
* 6371 km, which we convert to 6.371 < 6.4 */
if (meta->gds.majEarth < 6.4) {
meta->gds.majEarth = meta->gds.majEarth * 1000.;
meta->gds.minEarth = meta->gds.minEarth * 1000.;
}
break;
case 2:
meta->gds.f_sphere = 0;
meta->gds.majEarth = 6378.160;
meta->gds.minEarth = 6356.775;
break;
case 4:
meta->gds.f_sphere = 0;
meta->gds.majEarth = 6378.137;
meta->gds.minEarth = 6356.752314;
break;
case 5:
meta->gds.f_sphere = 0;
meta->gds.majEarth = 6378.137;
meta->gds.minEarth = 6356.7523;
break;
case 3:
meta->gds.f_sphere = 0;
/* Following assumes scale factor and scale value refer to
* scientific notation. */
/* Incorrect Assumption (9/8/2003): scale factor / value are based
* on: Y * 10^D = R, where Y = original value, D = scale factor, ___
* R = scale value. */
if ((is3[21] != GRIB2MISSING_s4) && (is3[20] != GRIB2MISSING_s1) &&
(is3[26] != GRIB2MISSING_s4) && (is3[25] != GRIB2MISSING_s1)) {
/* Assumes data is given in km (not m). */
meta->gds.majEarth = is3[21] / (pow (10.0, is3[20]));
meta->gds.minEarth = is3[26] / (pow (10.0, is3[25]));
} else {
errSprintf ("Missing info on major / minor axis of Earth.\n");
return -2;
}
/* Check if our km assumption was valid. If it wasn't, they give us
* 6371000 m, which is > 6400. */
if (meta->gds.majEarth > 6400) {
meta->gds.majEarth = meta->gds.majEarth / 1000.;
}
if (meta->gds.minEarth > 6400) {
meta->gds.minEarth = meta->gds.minEarth / 1000.;
}
break;
case 7:
meta->gds.f_sphere = 0;
/* Following assumes scale factor and scale value refer to
* scientific notation. */
/* Incorrect Assumption (9/8/2003): scale factor / value are based
* on: Y * 10^D = R, where Y = original value, D = scale factor, ___
* R = scale value. */
if ((is3[21] != GRIB2MISSING_s4) && (is3[20] != GRIB2MISSING_s1) &&
(is3[26] != GRIB2MISSING_s4) && (is3[25] != GRIB2MISSING_s1)) {
/* Assumes data is given in m (not km). */
meta->gds.majEarth = is3[21] / (pow (10.0, is3[20]) * 1000.);
meta->gds.minEarth = is3[26] / (pow (10.0, is3[25]) * 1000.);
} else {
errSprintf ("Missing info on major / minor axis of Earth.\n");
return -2;
}
/* Check if our m assumption was valid. If it wasn't, they give us
* 6371 km, which we convert to 6.371 < 6.4 */
if (meta->gds.majEarth < 6.4) {
meta->gds.majEarth = meta->gds.majEarth * 1000.;
}
if (meta->gds.minEarth < 6.4) {
meta->gds.minEarth = meta->gds.minEarth * 1000.;
}
break;
default:
errSprintf ("Undefined shape of earth? %ld\n", is3[14]);
return -2;
}
/* Validate the radEarth is reasonable. */
if ((meta->gds.majEarth > 6400) || (meta->gds.majEarth < 6300) ||
(meta->gds.minEarth > 6400) || (meta->gds.minEarth < 6300)) {
errSprintf ("Bad shape of earth? %f %f\n", meta->gds.majEarth,
meta->gds.minEarth);
return -2;
}
meta->gds.Nx = is3[30];
meta->gds.Ny = is3[34];
if (meta->gds.Nx * meta->gds.Ny != meta->gds.numPts) {
errSprintf ("Nx * Ny != number of points?\n");
return -2;
}
/* Initialize variables prior to parsing the specific templates. */
unit = 1e-6;
meta->gds.center = 0;
meta->gds.scaleLat1 = meta->gds.scaleLat2 = 0;
meta->gds.southLat = meta->gds.southLon = 0;
meta->gds.lat2 = meta->gds.lon2 = 0;
switch (is3[12]) {
case GS3_LATLON: /* 0: Regular lat/lon grid. */
case GS3_GAUSSIAN_LATLON: /* 40: Gaussian lat/lon grid. */
if (ns3 < 72) {
return -1;
}
angle = is3[38];
subdivision = is3[42];
if (angle != 0) {
if (subdivision == 0) {
errSprintf ("subdivision of 0? Could not determine unit"
" for latlon grid\n");
return -2;
}
unit = angle / (double) (subdivision);
}
if ((is3[46] == GRIB2MISSING_s4) || (is3[50] == GRIB2MISSING_s4) ||
(is3[55] == GRIB2MISSING_s4) || (is3[59] == GRIB2MISSING_s4) ||
(is3[63] == GRIB2MISSING_s4) || (is3[67] == GRIB2MISSING_s4)) {
errSprintf ("Lat/Lon grid is not defined completely.\n");
return -2;
}
meta->gds.lat1 = is3[46] * unit;
meta->gds.lon1 = is3[50] * unit;
meta->gds.resFlag = (uChar) is3[54];
meta->gds.lat2 = is3[55] * unit;
meta->gds.lon2 = is3[59] * unit;
meta->gds.Dx = is3[63] * unit; /* degrees. */
if (is3[12] == GS3_GAUSSIAN_LATLON) {
int np = is3[67]; /* parallels between a pole and the equator */
meta->gds.Dy = 90.0 / np;
} else
meta->gds.Dy = is3[67] * unit; /* degrees. */
meta->gds.scan = (uChar) is3[71];
meta->gds.meshLat = 0;
meta->gds.orientLon = 0;
/* Resolve resolution flag(bit 3,4). Copy Dx,Dy as appropriate. */
if ((meta->gds.resFlag & GRIB2BIT_3) &&
(!(meta->gds.resFlag & GRIB2BIT_4))) {
meta->gds.Dy = meta->gds.Dx;
} else if ((!(meta->gds.resFlag & GRIB2BIT_3)) &&
(meta->gds.resFlag & GRIB2BIT_4)) {
meta->gds.Dx = meta->gds.Dy;
}
break;
case GS3_MERCATOR: /* 10: Mercator grid. */
if (ns3 < 72) {
return -1;
}
if ((is3[38] == GRIB2MISSING_s4) || (is3[42] == GRIB2MISSING_s4) ||
(is3[47] == GRIB2MISSING_s4) || (is3[51] == GRIB2MISSING_s4) ||
(is3[55] == GRIB2MISSING_s4) || (is3[60] == GRIB2MISSING_s4)) {
errSprintf ("Mercator grid is not defined completely.\n");
return -2;
}
meta->gds.lat1 = is3[38] * unit;
meta->gds.lon1 = is3[42] * unit;
meta->gds.resFlag = (uChar) is3[46];
meta->gds.meshLat = is3[47] * unit;
meta->gds.lat2 = is3[51] * unit;
meta->gds.lon2 = is3[55] * unit;
meta->gds.scan = (uChar) is3[59];
meta->gds.orientLon = is3[60] * unit;
meta->gds.Dx = is3[64] / 1000.; /* mm -> m */
meta->gds.Dy = is3[68] / 1000.; /* mm -> m */
/* Resolve resolution flag(bit 3,4). Copy Dx,Dy as appropriate. */
if ((meta->gds.resFlag & GRIB2BIT_3) &&
(!(meta->gds.resFlag & GRIB2BIT_4))) {
if (is3[64] == GRIB2MISSING_s4) {
errSprintf ("Mercator grid is not defined completely.\n");
return -2;
}
meta->gds.Dy = meta->gds.Dx;
} else if ((!(meta->gds.resFlag & GRIB2BIT_3)) &&
(meta->gds.resFlag & GRIB2BIT_4)) {
if (is3[68] == GRIB2MISSING_s4) {
errSprintf ("Mercator grid is not defined completely.\n");
return -2;
}
meta->gds.Dx = meta->gds.Dy;
}
break;
case GS3_POLAR: /* 20: Polar Stereographic grid. */
if (ns3 < 65) {
return -1;
}
if ((is3[38] == GRIB2MISSING_s4) || (is3[42] == GRIB2MISSING_s4) ||
(is3[47] == GRIB2MISSING_s4) || (is3[51] == GRIB2MISSING_s4)) {
errSprintf ("Polar Stereographic grid is not defined "
"completely.\n");
return -2;
}
meta->gds.lat1 = is3[38] * unit;
meta->gds.lon1 = is3[42] * unit;
meta->gds.resFlag = (uChar) is3[46];
/* Note (1) resFlag (bit 3,4) not applicable. */
meta->gds.meshLat = is3[47] * unit;
meta->gds.orientLon = is3[51] * unit;
meta->gds.Dx = is3[55] / 1000.; /* mm -> m */
meta->gds.Dy = is3[59] / 1000.; /* mm -> m */
meta->gds.center = (uChar) is3[63];
if (meta->gds.center & GRIB2BIT_1) {
/* South polar stereographic. */
meta->gds.scaleLat1 = meta->gds.scaleLat2 = -90;
} else {
/* North polar stereographic. */
meta->gds.scaleLat1 = meta->gds.scaleLat2 = 90;
}
if (meta->gds.center & GRIB2BIT_2) {
errSprintf ("Note (4) specifies no 'bi-polar stereograhic"
" projections'.\n");
return -2;
}
meta->gds.scan = (uChar) is3[64];
break;
case GS3_LAMBERT: /* 30: Lambert Conformal grid. */
if (ns3 < 81) {
return -1;
}
if ((is3[38] == GRIB2MISSING_s4) || (is3[42] == GRIB2MISSING_s4) ||
(is3[47] == GRIB2MISSING_s4) || (is3[51] == GRIB2MISSING_s4) ||
(is3[65] == GRIB2MISSING_s4) || (is3[69] == GRIB2MISSING_s4) ||
(is3[73] == GRIB2MISSING_s4) || (is3[77] == GRIB2MISSING_s4)) {
errSprintf ("Lambert Conformal grid is not defined "
"completely.\n");
return -2;
}
meta->gds.lat1 = is3[38] * unit;
meta->gds.lon1 = is3[42] * unit;
meta->gds.resFlag = (uChar) is3[46];
/* Note (3) resFlag (bit 3,4) not applicable. */
meta->gds.meshLat = is3[47] * unit;
meta->gds.orientLon = is3[51] * unit;
meta->gds.Dx = is3[55] / 1000.; /* mm -> m */
meta->gds.Dy = is3[59] / 1000.; /* mm -> m */
meta->gds.center = (uChar) is3[63];
meta->gds.scan = (uChar) is3[64];
meta->gds.scaleLat1 = is3[65] * unit;
meta->gds.scaleLat2 = is3[69] * unit;
meta->gds.southLat = is3[73] * unit;
meta->gds.southLon = is3[77] * unit;
break;
case GS3_ORTHOGRAPHIC: /* 90: Orthographic grid. */
// Misusing gdsType elements (gdsType needs extension)
meta->gds.lat1 = is3[38];
meta->gds.lon1 = is3[42];
meta->gds.resFlag = (uChar) is3[46];
meta->gds.Dx = is3[47];
meta->gds.Dy = is3[51];
meta->gds.lon2 = is3[55] / 1000.; /* xp - X-coordinateSub-satellite, mm -> m */
meta->gds.lat2 = is3[59] / 1000.; /* yp - Y-coordinateSub-satellite, mm -> m */
meta->gds.scan = (uChar) is3[63];
meta->gds.orientLon = is3[64]; /* angle */
meta->gds.stretchFactor = is3[68] * 1000000.; /* altitude */
meta->gds.southLon = is3[72]; /* x0 - X-coordinateOrigin */
meta->gds.southLat = is3[76]; /* y0 - Y-coordinateOrigin */
break;
default:
errSprintf ("Un-supported Map Projection. %ld\n", is3[12]);
// Don't abandon the conversion only because of an unknown projection
break;
//return -3;
}
if (meta->gds.scan != GRIB2BIT_2) {
#ifdef DEBUG
printf ("Scan mode is expected to be 0100 (ie %d) not %d\n",
GRIB2BIT_2, meta->gds.scan);
printf ("The merged GRIB2 Library should return it in 0100\n");
printf ("The merged library swaps both NCEP and MDL data to scan "
"mode 0100\n");
#endif
/*
errSprintf ("Scan mode is expected to be 0100 (ie %d) not %d",
GRIB2BIT_2, meta->gds.scan);
return -2;
*/
}
return 0;
}
/*****************************************************************************
* ParseSect4Time2secV1() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* Attempt to parse time data in units provided by GRIB1 table 4, to
* seconds.
*
* ARGUMENTS
* time = The delta time to convert. (Input)
* unit = The unit to convert. (Input)
* ans = The converted answer. (Output)
*
* FILES/DATABASES: None
*
* RETURNS: int
* 0 = OK
* -1 = could not determine.
*
* HISTORY
* 9/2002 Arthur Taylor (MDL/RSIS): Created.
* 1/2005 AAT: Fixed unit2sec[] table to have element 10 be 10800 (3 hours)
* instead of 0.
*
* NOTES
*****************************************************************************
*/
int ParseSect4Time2secV1 (sInt4 time, int unit, double *ans)
{
/* Following is a lookup table for unit conversion (see code table 4.4). */
static sInt4 unit2sec[] = {
60, 3600, 86400L, 0, 0,
0, 0, 0, 0, 0,
10800, 21600L, 43200L
};
if ((unit >= 0) && (unit < 13)) {
if (unit2sec[unit] != 0) {
*ans = (double) (time * unit2sec[unit]);
return 0;
}
} else if (unit == 254) {
*ans = (double) (time);
return 0;
}
*ans = 0;
return -1;
}
/*****************************************************************************
* ParseSect4Time2sec() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* Attempt to parse time data in units provided by GRIB2 table 4.4, to
* seconds.
*
* ARGUMENTS
* time = The delta time to convert. (Input)
* unit = The unit to convert. (Input)
* ans = The converted answer. (Output)
*
* FILES/DATABASES: None
*
* RETURNS: int
* 0 = OK
* -1 = could not determine.
*
* HISTORY
* 9/2002 Arthur Taylor (MDL/RSIS): Created.
* 1/2005 AAT: Fixed unit2sec[] table to have element 10 be 10800 (3 hours)
* instead of 0.
*
* NOTES
*****************************************************************************
*/
int ParseSect4Time2sec (sInt4 time, int unit, double *ans)
{
/* Following is a lookup table for unit conversion (see code table 4.4). */
static sInt4 unit2sec[] = {
60, 3600, 86400L, 0, 0,
0, 0, 0, 0, 0,
10800, 21600L, 43200L, 1
};
if ((unit >= 0) && (unit < 14)) {
if (unit2sec[unit] != 0) {
*ans = (double) (time * unit2sec[unit]);
return 0;
}
}
*ans = 0;
return -1;
}
/*****************************************************************************
* ParseSect4() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To verify and parse section 4 data.
*
* ARGUMENTS
* is4 = The unpacked section 4 array. (Input)
* ns4 = The size of section 4. (Input)
* meta = The structure to fill. (Output)
*
* FILES/DATABASES: None
*
* RETURNS: int (could use errSprintf())
* 0 = OK
* -1 = ns4 is too small.
* -2 = unexpected values in is4.
* -4 = un-supported Sect 4 template.
* -5 = unsupported forecast time unit.
* -6 = Ran out of memory.
*
* HISTORY
* 9/2002 Arthur Taylor (MDL/RSIS): Created.
* 3/2003 AAT: Added support for GS4_SATELLITE.
* 3/2003 AAT: Adjusted allocing of sect4.Interval (should be safer now).
* 9/2003 AAT: Adjusted interpretation of scale factor / value.
* 5/2004 AAT: Added some memory checks.
* 3/2005 AAT: Added a cast to (uChar) when comparing to GRIB2MISSING_1
* 3/2005 AAT: Added GS4_PROBABIL_PNT.
*
* NOTES
* Need to add support for GS4_RADAR = 20
*****************************************************************************
*/
static int ParseSect4 (sInt4 *is4, sInt4 ns4, grib_MetaData *meta)
{
int i; /* Counter for time intervals in template 4.8, 4.9
* (typically 1) or counter for satellite band in
* template 4.30. */
void *temp_ptr; /* A temporary pointer when reallocating memory. */
char *msg; /* A pointer to the current error message. */
if (ns4 < 9) {
return -1;
}
if (is4[4] != 4) {
#ifdef DEBUG
printf ("ERROR IS4 not labeled correctly. %d\n", is4[4]);
#endif
errSprintf ("ERROR IS4 not labeled correctly. %d\n", is4[4]);
return -2;
}
if (is4[5] != 0) {
#ifdef DEBUG
printf ("Un-supported template.\n All Supported template "
"have 0 coordinate vertical values after template.");
#endif
errSprintf ("Un-supported template.\n All Supported template "
"have 0 coordinate vertical values after template.");
return -4;
}
if ((is4[7] != GS4_ANALYSIS) && (is4[7] != GS4_ENSEMBLE) &&
(is4[7] != GS4_DERIVED) && (is4[7] != GS4_PROBABIL_PNT) &&
(is4[7] != GS4_STATISTIC) && (is4[7] != GS4_PROBABIL_TIME) &&
(is4[7] != GS4_PERCENTILE) && (is4[7] != GS4_ENSEMBLE_STAT) &&
(is4[7] != GS4_SATELLITE) && (is4[7] != GS4_DERIVED_INTERVAL)) {
#ifdef DEBUG
printf ("Un-supported Template. %d\n", is4[7]);
#endif
errSprintf ("Un-supported Template. %d\n", is4[7]);
return -4;
}
meta->pds2.sect4.templat = (unsigned short int) is4[7];
/*
* Handle variables common to the supported templates.
*/
if (ns4 < 34) {
return -1;
}
meta->pds2.sect4.cat = (uChar) is4[9];
meta->pds2.sect4.subcat = (uChar) is4[10];
meta->pds2.sect4.genProcess = (uChar) is4[11];
/* Initialize variables prior to parsing the specific templates. */
meta->pds2.sect4.typeEnsemble = 0;
meta->pds2.sect4.perturbNum = 0;
meta->pds2.sect4.numberFcsts = 0;
meta->pds2.sect4.derivedFcst = 0;
meta->pds2.sect4.validTime = meta->pds2.refTime;
if (meta->pds2.sect4.templat == GS4_SATELLITE) {
meta->pds2.sect4.genID = (uChar) is4[12];
meta->pds2.sect4.numBands = (uChar) is4[13];
meta->pds2.sect4.bands =
(sect4_BandType *) realloc ((void *) meta->pds2.sect4.bands,
meta->pds2.sect4.numBands *
sizeof (sect4_BandType));
for (i = 0; i < meta->pds2.sect4.numBands; i++) {
meta->pds2.sect4.bands[i].series =
(unsigned short int) is4[14 + 10 * i];
meta->pds2.sect4.bands[i].numbers =
(unsigned short int) is4[16 + 10 * i];
meta->pds2.sect4.bands[i].instType = (uChar) is4[18 + 10 * i];
meta->pds2.sect4.bands[i].centWaveNum.factor =
(uChar) is4[19 + 10 * i];
meta->pds2.sect4.bands[i].centWaveNum.value = is4[20 + 10 * i];
}
meta->pds2.sect4.fstSurfType = GRIB2MISSING_u1;
meta->pds2.sect4.fstSurfScale = GRIB2MISSING_s1;
meta->pds2.sect4.fstSurfValue = 0;
meta->pds2.sect4.sndSurfType = GRIB2MISSING_u1;
meta->pds2.sect4.sndSurfScale = GRIB2MISSING_s1;
meta->pds2.sect4.sndSurfValue = 0;
return 0;
}
meta->pds2.sect4.bgGenID = (uChar) is4[12];
meta->pds2.sect4.genID = (uChar) is4[13];
if ((is4[14] == GRIB2MISSING_u2) || (is4[16] == GRIB2MISSING_u1)) {
meta->pds2.sect4.f_validCutOff = 0;
meta->pds2.sect4.cutOff = 0;
} else {
meta->pds2.sect4.f_validCutOff = 1;
meta->pds2.sect4.cutOff = is4[14] * 3600 + is4[16] * 60;
}
if (is4[18] == GRIB2MISSING_s4) {
errSprintf ("Missing 'forecast' time?\n");
return -5;
}
if (ParseSect4Time2sec (is4[18], is4[17],
&(meta->pds2.sect4.foreSec)) != 0) {
errSprintf ("Unable to convert this TimeUnit: %ld\n", is4[17]);
return -5;
}
meta->pds2.sect4.validTime = (time_t) (meta->pds2.refTime +
meta->pds2.sect4.foreSec);
/*
* Following is based on what was needed to get correct Radius of Earth in
* section 3. (Hopefully they are consistent).
*/
meta->pds2.sect4.fstSurfType = (uChar) is4[22];
if ((is4[24] == GRIB2MISSING_s4) || (is4[23] == GRIB2MISSING_s1) ||
(meta->pds2.sect4.fstSurfType == GRIB2MISSING_u1)) {
meta->pds2.sect4.fstSurfScale = GRIB2MISSING_s1;
meta->pds2.sect4.fstSurfValue = 0;
} else {
meta->pds2.sect4.fstSurfScale = is4[23];
meta->pds2.sect4.fstSurfValue = is4[24] / pow (10.0, is4[23]);
}
meta->pds2.sect4.sndSurfType = (uChar) is4[28];
if ((is4[30] == GRIB2MISSING_s4) || (is4[29] == GRIB2MISSING_s1) ||
(meta->pds2.sect4.sndSurfType == GRIB2MISSING_u1)) {
meta->pds2.sect4.sndSurfScale = GRIB2MISSING_s1;
meta->pds2.sect4.sndSurfValue = 0;
} else {
meta->pds2.sect4.sndSurfScale = is4[29];
meta->pds2.sect4.sndSurfValue = is4[30] / pow (10.0, is4[29]);
}
switch (meta->pds2.sect4.templat) {
case GS4_ANALYSIS: /* 4.0 */
break;
case GS4_ENSEMBLE: /* 4.1 */
meta->pds2.sect4.typeEnsemble = (uChar) is4[34];
meta->pds2.sect4.perturbNum = (uChar) is4[35];
meta->pds2.sect4.numberFcsts = (uChar) is4[36];
break;
case GS4_ENSEMBLE_STAT: /* 4.1 */
meta->pds2.sect4.typeEnsemble = (uChar) is4[34];
meta->pds2.sect4.perturbNum = (uChar) is4[35];
meta->pds2.sect4.numberFcsts = (uChar) is4[36];
if (ParseTime (&(meta->pds2.sect4.validTime), is4[37], is4[39],
is4[40], is4[41], is4[42], is4[43]) != 0) {
msg = errSprintf (NULL);
uChar numInterval = (uChar) is4[44];
if (numInterval != 1) {
errSprintf ("ERROR: in call to ParseTime from ParseSect4\n%s",
msg);
errSprintf ("Most likely they didn't complete bytes 38-44 of "
"Template 4.11\n");
free (msg);
return -1;
}
meta->pds2.sect4.numInterval = numInterval;
printf ("Warning: in call to ParseTime from ParseSect4\n%s", msg);
free (msg);
meta->pds2.sect4.validTime = (time_t) (meta->pds2.refTime +
meta->pds2.sect4.foreSec);
printf ("Most likely they didn't complete bytes 38-44 of "
"Template 4.11\n");
} else {
meta->pds2.sect4.numInterval = (uChar) is4[44];
}
/* Added this check because some MOS grids didn't finish the
* template. */
if (meta->pds2.sect4.numInterval != 0) {
temp_ptr = realloc ((void *) meta->pds2.sect4.Interval,
meta->pds2.sect4.numInterval *
sizeof (sect4_IntervalType));
if (temp_ptr == NULL) {
printf ("Ran out of memory.\n");
return -6;
}
meta->pds2.sect4.Interval = (sect4_IntervalType *) temp_ptr;
meta->pds2.sect4.numMissing = is4[45];
for (i = 0; i < meta->pds2.sect4.numInterval; i++) {
meta->pds2.sect4.Interval[i].processID =
(uChar) is4[49 + i * 12];
meta->pds2.sect4.Interval[i].incrType =
(uChar) is4[50 + i * 12];
meta->pds2.sect4.Interval[i].timeRangeUnit =
(uChar) is4[51 + i * 12];
meta->pds2.sect4.Interval[i].lenTime = is4[52 + i * 12];
meta->pds2.sect4.Interval[i].incrUnit =
(uChar) is4[56 + i * 12];
meta->pds2.sect4.Interval[i].timeIncr =
(uChar) is4[57 + i * 12];
}
} else {
#ifdef DEBUG
printf ("Caution: Template 4.11 had no Intervals.\n");
#endif
meta->pds2.sect4.numMissing = is4[45];
}
break;
case GS4_DERIVED: /* 4.2 */
meta->pds2.sect4.derivedFcst = (uChar) is4[34];
meta->pds2.sect4.numberFcsts = (uChar) is4[35];
break;
case GS4_DERIVED_INTERVAL: /* 4.12 */
meta->pds2.sect4.derivedFcst = (uChar) is4[34];
meta->pds2.sect4.numberFcsts = (uChar) is4[35];
if (ParseTime (&(meta->pds2.sect4.validTime), is4[36], is4[38],
is4[39], is4[40], is4[41], is4[42]) != 0) {
msg = errSprintf (NULL);
uChar numInterval = (uChar) is4[43];
if (numInterval != 1) {
errSprintf ("ERROR: in call to ParseTime from ParseSect4\n%s",
msg);
errSprintf ("Most likely they didn't complete bytes 37-43 of "
"Template 4.12\n");
free (msg);
return -1;
}
meta->pds2.sect4.numInterval = numInterval;
printf ("Warning: in call to ParseTime from ParseSect4\n%s", msg);
free (msg);
meta->pds2.sect4.validTime = (time_t) (meta->pds2.refTime +
meta->pds2.sect4.foreSec);
printf ("Most likely they didn't complete bytes 37-43 of "
"Template 4.12\n");
} else {
meta->pds2.sect4.numInterval = (uChar) is4[43];
}
/* Added this check because some MOS grids didn't finish the
* template. */
if (meta->pds2.sect4.numInterval != 0) {
temp_ptr = realloc ((void *) meta->pds2.sect4.Interval,
meta->pds2.sect4.numInterval *
sizeof (sect4_IntervalType));
if (temp_ptr == NULL) {
printf ("Ran out of memory.\n");
return -6;
}
meta->pds2.sect4.Interval = (sect4_IntervalType *) temp_ptr;
meta->pds2.sect4.numMissing = is4[44];
for (i = 0; i < meta->pds2.sect4.numInterval; i++) {
meta->pds2.sect4.Interval[i].processID =
(uChar) is4[48 + i * 12];
meta->pds2.sect4.Interval[i].incrType =
(uChar) is4[49 + i * 12];
meta->pds2.sect4.Interval[i].timeRangeUnit =
(uChar) is4[50 + i * 12];
meta->pds2.sect4.Interval[i].lenTime = is4[51 + i * 12];
meta->pds2.sect4.Interval[i].incrUnit =
(uChar) is4[55 + i * 12];
meta->pds2.sect4.Interval[i].timeIncr =
(uChar) is4[56 + i * 12];
}
} else {
#ifdef DEBUG
printf ("Caution: Template 4.12 had no Intervals.\n");
#endif
meta->pds2.sect4.numMissing = is4[44];
}
break;
case GS4_STATISTIC: /* 4.8 */
if (ParseTime (&(meta->pds2.sect4.validTime), is4[34], is4[36],
is4[37], is4[38], is4[39], is4[40]) != 0) {
msg = errSprintf (NULL);
uChar numInterval = (uChar) is4[41];
if (numInterval != 1) {
errSprintf ("ERROR: in call to ParseTime from ParseSect4\n%s",
msg);
errSprintf ("Most likely they didn't complete bytes 35-41 of "
"Template 4.8\n");
free (msg);
return -1;
}
meta->pds2.sect4.numInterval = numInterval;
printf ("Warning: in call to ParseTime from ParseSect4\n%s", msg);
free (msg);
meta->pds2.sect4.validTime = (time_t) (meta->pds2.refTime +
meta->pds2.sect4.foreSec);
printf ("Most likely they didn't complete bytes 35-41 of "
"Template 4.8\n");
} else {
meta->pds2.sect4.numInterval = (uChar) is4[41];
}
/* Added this check because some MOS grids didn't finish the
* template. */
if (meta->pds2.sect4.numInterval != 0) {
temp_ptr = realloc ((void *) meta->pds2.sect4.Interval,
meta->pds2.sect4.numInterval *
sizeof (sect4_IntervalType));
if (temp_ptr == NULL) {
printf ("Ran out of memory.\n");
return -6;
}
meta->pds2.sect4.Interval = (sect4_IntervalType *) temp_ptr;
meta->pds2.sect4.numMissing = is4[42];
for (i = 0; i < meta->pds2.sect4.numInterval; i++) {
meta->pds2.sect4.Interval[i].processID =
(uChar) is4[46 + i * 12];
meta->pds2.sect4.Interval[i].incrType =
(uChar) is4[47 + i * 12];
meta->pds2.sect4.Interval[i].timeRangeUnit =
(uChar) is4[48 + i * 12];
meta->pds2.sect4.Interval[i].lenTime = is4[49 + i * 12];
meta->pds2.sect4.Interval[i].incrUnit =
(uChar) is4[53 + i * 12];
meta->pds2.sect4.Interval[i].timeIncr =
(uChar) is4[54 + i * 12];
}
} else {
#ifdef DEBUG
printf ("Caution: Template 4.8 had no Intervals.\n");
#endif
meta->pds2.sect4.numMissing = is4[42];
}
break;
case GS4_PERCENTILE: /* 4.10 */
meta->pds2.sect4.percentile = is4[34];
if (ParseTime (&(meta->pds2.sect4.validTime), is4[35], is4[37],
is4[38], is4[39], is4[40], is4[41]) != 0) {
msg = errSprintf (NULL);
uChar numInterval = (uChar) is4[42];
if (numInterval != 1) {
errSprintf ("ERROR: in call to ParseTime from ParseSect4\n%s",
msg);
errSprintf ("Most likely they didn't complete bytes 35-41 of "
"Template 4.8\n");
free (msg);
return -1;
}
meta->pds2.sect4.numInterval = numInterval;
printf ("Warning: in call to ParseTime from ParseSect4\n%s", msg);
free (msg);
meta->pds2.sect4.validTime = (time_t) (meta->pds2.refTime +
meta->pds2.sect4.foreSec);
printf ("Most likely they didn't complete bytes 35-41 of "
"Template 4.8\n");
} else {
meta->pds2.sect4.numInterval = (uChar) is4[42];
}
/* Added this check because some MOS grids didn't finish the
* template. */
if (meta->pds2.sect4.numInterval != 0) {
temp_ptr = realloc ((void *) meta->pds2.sect4.Interval,
meta->pds2.sect4.numInterval *
sizeof (sect4_IntervalType));
if (temp_ptr == NULL) {
printf ("Ran out of memory.\n");
return -6;
}
meta->pds2.sect4.Interval = (sect4_IntervalType *) temp_ptr;
meta->pds2.sect4.numMissing = is4[43];
for (i = 0; i < meta->pds2.sect4.numInterval; i++) {
meta->pds2.sect4.Interval[i].processID =
(uChar) is4[47 + i * 12];
meta->pds2.sect4.Interval[i].incrType =
(uChar) is4[48 + i * 12];
meta->pds2.sect4.Interval[i].timeRangeUnit =
(uChar) is4[49 + i * 12];
meta->pds2.sect4.Interval[i].lenTime = is4[50 + i * 12];
meta->pds2.sect4.Interval[i].incrUnit =
(uChar) is4[54 + i * 12];
meta->pds2.sect4.Interval[i].timeIncr =
(uChar) is4[55 + i * 12];
}
} else {
#ifdef DEBUG
printf ("Caution: Template 4.10 had no Intervals.\n");
#endif
meta->pds2.sect4.numMissing = is4[43];
}
break;
case GS4_PROBABIL_PNT: /* 4.5 */
meta->pds2.sect4.foreProbNum = (uChar) is4[34];
meta->pds2.sect4.numForeProbs = (uChar) is4[35];
meta->pds2.sect4.probType = (uChar) is4[36];
meta->pds2.sect4.lowerLimit.factor = (sChar) is4[37];
meta->pds2.sect4.lowerLimit.value = is4[38];
meta->pds2.sect4.upperLimit.factor = (sChar) is4[42];
meta->pds2.sect4.upperLimit.value = is4[43];
break;
case GS4_PROBABIL_TIME: /* 4.9 */
meta->pds2.sect4.foreProbNum = (uChar) is4[34];
meta->pds2.sect4.numForeProbs = (uChar) is4[35];
meta->pds2.sect4.probType = (uChar) is4[36];
meta->pds2.sect4.lowerLimit.factor = (sChar) is4[37];
meta->pds2.sect4.lowerLimit.value = is4[38];
meta->pds2.sect4.upperLimit.factor = (sChar) is4[42];
meta->pds2.sect4.upperLimit.value = is4[43];
if (ParseTime (&(meta->pds2.sect4.validTime), is4[47], is4[49],
is4[50], is4[51], is4[52], is4[53]) != 0) {
msg = errSprintf (NULL);
uChar numInterval = (uChar) is4[54];
if (numInterval != 1) {
errSprintf ("ERROR: in call to ParseTime from ParseSect4\n%s",
msg);
errSprintf ("Most likely they didn't complete bytes 48-54 of "
"Template 4.9\n");
free (msg);
return -1;
}
meta->pds2.sect4.numInterval = numInterval;
printf ("Warning: in call to ParseTime from ParseSect4\n%s", msg);
free (msg);
meta->pds2.sect4.validTime = (time_t) (meta->pds2.refTime +
meta->pds2.sect4.foreSec);
printf ("Most likely they didn't complete bytes 48-54 of "
"Template 4.9\n");
} else {
meta->pds2.sect4.numInterval = (uChar) is4[54];
}
temp_ptr = realloc ((void *) meta->pds2.sect4.Interval,
meta->pds2.sect4.numInterval *
sizeof (sect4_IntervalType));
if (temp_ptr == NULL) {
printf ("Ran out of memory.\n");
return -6;
}
meta->pds2.sect4.Interval = (sect4_IntervalType *) temp_ptr;
meta->pds2.sect4.numMissing = is4[55];
for (i = 0; i < meta->pds2.sect4.numInterval; i++) {
meta->pds2.sect4.Interval[i].processID = (uChar) is4[59 + i * 12];
meta->pds2.sect4.Interval[i].incrType = (uChar) is4[60 + i * 12];
meta->pds2.sect4.Interval[i].timeRangeUnit =
(uChar) is4[61 + i * 12];
meta->pds2.sect4.Interval[i].lenTime = is4[62 + i * 12];
meta->pds2.sect4.Interval[i].incrUnit = (uChar) is4[66 + i * 12];
meta->pds2.sect4.Interval[i].timeIncr = (uChar) is4[67 + i * 12];
}
break;
default:
errSprintf ("Un-supported Template. %ld\n", is4[7]);
return -4;
}
return 0;
}
/*****************************************************************************
* ParseSect5() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To verify and parse section 5 data.
*
* ARGUMENTS
* is5 = The unpacked section 5 array. (Input)
* ns5 = The size of section 5. (Input)
* meta = The structure to fill. (Output)
* xmissp = The primary missing value. (Input)
* xmisss = The secondary missing value. (Input)
*
* FILES/DATABASES: None
*
* RETURNS: int (could use errSprintf())
* 0 = OK
* -1 = ns5 is too small.
* -2 = unexpected values in is5.
* -6 = unsupported packing.
*
* HISTORY
* 9/2002 Arthur Taylor (MDL/RSIS): Created.
*
* NOTES
*****************************************************************************
*/
static int ParseSect5 (sInt4 *is5, sInt4 ns5, grib_MetaData *meta,
float xmissp, float xmisss)
{
if (ns5 < 22) {
return -1;
}
if (is5[4] != 5) {
errSprintf ("ERROR IS5 not labeled correctly. %ld\n", is5[5]);
return -2;
}
if ((is5[9] != GS5_SIMPLE) && (is5[9] != GS5_CMPLX) &&
(is5[9] != GS5_CMPLXSEC) && (is5[9] != GS5_SPECTRAL) &&
(is5[9] != GS5_HARMONIC) && (is5[9] != GS5_JPEG2000) &&
(is5[9] != GS5_PNG) && (is5[9] != GS5_JPEG2000_ORG) &&
(is5[9] != GS5_PNG_ORG)) {
errSprintf ("Un-supported Packing? %ld\n", is5[9]);
return -6;
}
meta->gridAttrib.packType = (sInt4) is5[9];
meta->gridAttrib.f_maxmin = 0;
meta->gridAttrib.missPri = xmissp;
meta->gridAttrib.missSec = xmisss;
if ((is5[9] == GS5_SPECTRAL) || (is5[9] == GS5_HARMONIC)) {
meta->gridAttrib.fieldType = 0;
meta->gridAttrib.f_miss = 0;
return 0;
}
if (is5[20] > 1) {
errSprintf ("Invalid field type. %ld\n", is5[20]);
return -2;
}
MEMCPY_BIG (&meta->gridAttrib.refVal, &(is5[11]), 4);
meta->gridAttrib.ESF = is5[15];
meta->gridAttrib.DSF = is5[17];
meta->gridAttrib.fieldType = (uChar) is5[20];
if ((is5[9] == GS5_JPEG2000) || (is5[9] == GS5_JPEG2000_ORG) ||
(is5[9] == GS5_PNG) || (is5[9] == GS5_PNG_ORG)) {
meta->gridAttrib.f_miss = 0;
return 0;
}
if (meta->gridAttrib.packType == 0) {
meta->gridAttrib.f_miss = 0;
} else {
if (ns5 < 23) {
return -1;
}
if (is5[22] > 2) {
errSprintf ("Invalid missing management type, f_miss = %ld\n",
is5[22]);
return -2;
}
meta->gridAttrib.f_miss = (uChar) is5[22];
}
return 0;
}
/*****************************************************************************
* MetaParse() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To parse all the meta data from a grib2 message.
*
* ARGUMENTS
* meta = The structure to fill. (Output)
* is0 = The unpacked section 0 array. (Input)
* ns0 = The size of section 0. (Input)
* is1 = The unpacked section 1 array. (Input)
* ns1 = The size of section 1. (Input)
* is2 = The unpacked section 2 array. (Input)
* ns2 = The size of section 2. (Input)
* rdat = The float data in section 2. (Input)
* nrdat = Length of rdat. (Input)
* idat = The integer data in section 2. (Input)
* nidat = Length of idat. (Input)
* is3 = The unpacked section 3 array. (Input)
* ns3 = The size of section 3. (Input)
* is4 = The unpacked section 4 array. (Input)
* ns4 = The size of section 4. (Input)
* is5 = The unpacked section 5 array. (Input)
* ns5 = The size of section 5. (Input)
* grib_len = The length of the entire grib message. (Input)
* xmissp = The primary missing value. (Input)
* xmisss = The secondary missing value. (Input)
* simpVer = The version of the simple weather code to use when parsing the
* WxString (if applicable). (Input)
*
* FILES/DATABASES: None
*
* RETURNS: int (could use errSprintf())
* 0 = OK
* -1 = A dimension is too small.
* -2 = unexpected values in a grib section.
* -3 = un-supported map Projection.
* -4 = un-supported Sect 4 template.
* -5 = unsupported forecast time unit.
* -6 = unsupported sect 5 packing.
* -10 = Something the driver can't handle yet.
* (prodType != 0, f_sphere != 1, etc)
* -11 = Weather grid without a lookup table.
*
* HISTORY
* 9/2002 Arthur Taylor (MDL/RSIS): Created.
*
* NOTES
*****************************************************************************
*/
int MetaParse (grib_MetaData *meta, sInt4 *is0, sInt4 ns0,
sInt4 *is1, sInt4 ns1, sInt4 *is2, sInt4 ns2,
float *rdat, sInt4 nrdat, sInt4 *idat, sInt4 nidat,
sInt4 *is3, sInt4 ns3, sInt4 *is4, sInt4 ns4,
sInt4 *is5, sInt4 ns5, sInt4 grib_len,
float xmissp, float xmisss, int simpVer)
{
int ierr; /* The error code of a called routine */
/* char *element; *//* Holds the name of the current variable. */
/* char *comment; *//* Holds more comments about current variable. */
/* char *unitName; *//* Holds the name of the unit [K] [%] .. etc */
uChar probType; /* The probability type */
double lowerProb; /* The lower limit on probability forecast if
* template 4.5 or 4.9 */
double upperProb; /* The upper limit on probability forecast if
* template 4.5 or 4.9 */
sInt4 lenTime; /* Length of time for element (see 4.8 and 4.9) */
if ((ierr = ParseSect0 (is0, ns0, grib_len, meta)) != 0) {
preErrSprintf ("Parse error Section 0\n");
//return ierr;
}
if ((ierr = ParseSect1 (is1, ns1, meta)) != 0) {
preErrSprintf ("Parse error Section 1\n");
//return ierr;
}
if (ns2 < 7) {
errSprintf ("ns2 was too small in MetaParse\n");
//return -1;
}
meta->pds2.f_sect2 = (uChar) (is2[0] != 0);
if (meta->pds2.f_sect2) {
meta->pds2.sect2NumGroups = is2[7 - 1];
} else {
meta->pds2.sect2NumGroups = 0;
}
if ((ierr = ParseSect3 (is3, ns3, meta)) != 0) {
preErrSprintf ("Parse error Section 3\n");
//return ierr;
}
if (meta->gds.f_sphere != 1) {
errSprintf ("Driver Filter: Can only handle spheres.\n");
//return -10;
}
if ((ierr = ParseSect4 (is4, ns4, meta)) != 0) {
preErrSprintf ("Parse error Section 4\n");
//return ierr;
}
if ((ierr = ParseSect5 (is5, ns5, meta, xmissp, xmisss)) != 0) {
preErrSprintf ("Parse error Section 5\n");
//return ierr;
}
/* Compute ElementName. */
if (meta->element) {
free (meta->element);
meta->element = NULL;
}
if (meta->unitName) {
free (meta->unitName);
meta->unitName = NULL;
}
if (meta->comment) {
free (meta->comment);
meta->comment = NULL;
}
if ((meta->pds2.sect4.templat == GS4_PROBABIL_TIME) ||
(meta->pds2.sect4.templat == GS4_PROBABIL_PNT)) {
probType = meta->pds2.sect4.probType;
lowerProb = meta->pds2.sect4.lowerLimit.value *
pow (10.0, -1 * meta->pds2.sect4.lowerLimit.factor);
upperProb = meta->pds2.sect4.upperLimit.value *
pow (10.0, -1 * meta->pds2.sect4.upperLimit.factor);
} else {
probType = 0;
lowerProb = 0;
upperProb = 0;
}
if (meta->pds2.sect4.numInterval > 0) {
/* Try to convert lenTime to hourly. */
if (meta->pds2.sect4.Interval[0].timeRangeUnit == 255) {
lenTime = (sInt4) ((meta->pds2.sect4.validTime -
meta->pds2.sect4.foreSec -
meta->pds2.refTime) / 3600);
} else if (meta->pds2.sect4.Interval[0].timeRangeUnit == 0) {
lenTime = (sInt4) (meta->pds2.sect4.Interval[0].lenTime / 60.);
} else if (meta->pds2.sect4.Interval[0].timeRangeUnit == 1) {
lenTime = meta->pds2.sect4.Interval[0].lenTime;
} else if (meta->pds2.sect4.Interval[0].timeRangeUnit == 2) {
lenTime = meta->pds2.sect4.Interval[0].lenTime * 24;
} else if (meta->pds2.sect4.Interval[0].timeRangeUnit == 10) {
lenTime = meta->pds2.sect4.Interval[0].lenTime * 3;
} else if (meta->pds2.sect4.Interval[0].timeRangeUnit == 11) {
lenTime = meta->pds2.sect4.Interval[0].lenTime * 6;
} else if (meta->pds2.sect4.Interval[0].timeRangeUnit == 12) {
lenTime = meta->pds2.sect4.Interval[0].lenTime * 12;
} else if (meta->pds2.sect4.Interval[0].timeRangeUnit == 13) {
lenTime = (sInt4) (meta->pds2.sect4.Interval[0].lenTime / 3600.);
} else {
lenTime = 0;
printf ("Can't handle this timeRangeUnit\n");
myAssert (meta->pds2.sect4.Interval[0].timeRangeUnit == 1);
}
/*
} else {
lenTime = 255;
}
if (lenTime == 255) {
lenTime = (meta->pds2.sect4.validTime - meta->pds2.sect4.foreSec -
meta->pds2.refTime) / 3600;
}
*/
if (lenTime == GRIB2MISSING_s4) {
lenTime = 0;
}
ParseElemName (meta->center, meta->subcenter,
meta->pds2.prodType, meta->pds2.sect4.templat,
meta->pds2.sect4.cat, meta->pds2.sect4.subcat,
lenTime, meta->pds2.sect4.Interval[0].incrType,
meta->pds2.sect4.genID, probType, lowerProb,
upperProb, &(meta->element), &(meta->comment),
&(meta->unitName), &(meta->convert),
meta->pds2.sect4.percentile);
} else {
ParseElemName (meta->center, meta->subcenter,
meta->pds2.prodType, meta->pds2.sect4.templat,
meta->pds2.sect4.cat, meta->pds2.sect4.subcat, 0, 255,
meta->pds2.sect4.genID, probType, lowerProb, upperProb,
&(meta->element), &(meta->comment), &(meta->unitName),
&(meta->convert), meta->pds2.sect4.percentile);
}
#ifdef DEBUG
/*
printf ("Element: %s\nunitName: %s\ncomment: %s\n", meta->element,
meta->comment, meta->unitName);
*/
#endif
/*
if (strcmp (element, "") == 0) {
meta->element = (char *) realloc ((void *) (meta->element),
(1 + strlen ("unknown")) *
sizeof (char));
strcpy (meta->element, "unknown");
} else {
if (IsData_MOS (meta->pds2.center, meta->pds2.subcenter)) {
* See : http://www.nco.ncep.noaa.gov/pmb/docs/on388/tablea.html *
if (meta->pds2.sect4.genID == 96) {
meta->element = (char *) realloc ((void *) (meta->element),
(1 + 7 + strlen (element)) *
sizeof (char));
sprintf (meta->element, "MOSGFS-%s", element);
} else {
meta->element = (char *) realloc ((void *) (meta->element),
(1 + 4 + strlen (element)) *
sizeof (char));
sprintf (meta->element, "MOS-%s", element);
}
} else {
meta->element = (char *) realloc ((void *) (meta->element),
(1 + strlen (element)) *
sizeof (char));
strcpy (meta->element, element);
}
}
meta->unitName = (char *) realloc ((void *) (meta->unitName),
(1 + 2 + strlen (unitName)) *
sizeof (char));
sprintf (meta->unitName, "[%s]", unitName);
meta->comment = (char *) realloc ((void *) (meta->comment),
(1 + strlen (comment) +
strlen (unitName)
+ 2 + 1) * sizeof (char));
sprintf (meta->comment, "%s [%s]", comment, unitName);
*/
if ((meta->pds2.sect4.sndSurfScale == GRIB2MISSING_s1) ||
(meta->pds2.sect4.sndSurfType == GRIB2MISSING_u1)) {
/*
if ((meta->pds2.sect4.fstSurfScale == GRIB2MISSING_s1) ||
(meta->pds2.sect4.fstSurfType == GRIB2MISSING_u1)) {
ParseLevelName (meta->center, meta->subcenter,
meta->pds2.sect4.fstSurfType, 0, 0, 0,
&(meta->shortFstLevel), &(meta->longFstLevel));
} else {
*/
ParseLevelName (meta->center, meta->subcenter,
meta->pds2.sect4.fstSurfType,
meta->pds2.sect4.fstSurfValue, 0, 0,
&(meta->shortFstLevel), &(meta->longFstLevel));
/*
}
*/
} else {
ParseLevelName (meta->center, meta->subcenter,
meta->pds2.sect4.fstSurfType,
meta->pds2.sect4.fstSurfValue, 1,
meta->pds2.sect4.sndSurfValue, &(meta->shortFstLevel),
&(meta->longFstLevel));
}
/* Continue parsing section 2 data. */
if (meta->pds2.f_sect2) {
MetaSect2Free (meta);
if (strcmp (meta->element, "Wx") == 0) {
meta->pds2.sect2.ptrType = GS2_WXTYPE;
if ((ierr = ParseSect2_Wx (rdat, nrdat, idat, nidat,
&(meta->pds2.sect2.wx), simpVer)) != 0) {
preErrSprintf ("Parse error Section 2 : Weather Data\n");
//return ierr;
}
} else {
meta->pds2.sect2.ptrType = GS2_UNKNOWN;
if ((ierr = ParseSect2_Unknown (rdat, nrdat, idat, nidat, meta))
!= 0) {
preErrSprintf ("Parse error Section 2 : Unknown Data type\n");
//return ierr;
}
}
} else {
if (strcmp (meta->element, "Wx") == 0) {
errSprintf ("Weather grid does not have look up table?");
//return -11;
}
}
return 0;
}
/*****************************************************************************
* ParseGridNoMiss() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* A helper function for ParseGrid. In this particular case it is dealing
* with a field that has NO missing value type.
* Walks through either a float or an integer grid, computing the min/max
* values in the grid, and converts the units. It uses gridAttrib info for the
* missing values and it updates gridAttrib with the observed min/max values.
*
* ARGUMENTS
* attrib = Grid Attribute structure already filled in (Input/Output)
* grib_Data = The place to store the grid data. (Output)
* Nx, Ny = The dimensions of the grid (Input)
* iain = Place to find data if it is an Integer (or float). (Input)
* unitM = M in unit conversion equation y(new) = m x(orig) + b (Input)
* unitB = B in unit conversion equation y(new) = m x(orig) + b (Input)
* f_wxType = true if we have a valid wx type. (Input)
* WxType = table to look up values in. (Input)
* startX = The start of the X values. (Input)
* startY = The start of the Y values. (Input)
* subNx = The Nx dimmension of the subgrid (Input)
* subNy = The Ny dimmension of the subgrid (Input)
*
* FILES/DATABASES: None
*
* RETURNS: void
*
* HISTORY
* 12/2002 Arthur Taylor (MDL/RSIS): Created to optimize part of ParseGrid.
* 5/2003 AAT: Added ability to see if wxType occurs. If so sets table
* valid to 2, otherwise leaves it at 1. If table valid is 0 then
* sets value to missing value (if applicable).
* 2/2004 AAT: Added the subgrid capability.
*
* NOTES
* 1) Don't have to check if value became missing value, because we can check
* if missing falls in the range of the min/max converted units. If
* missing does fall in that range we need to move missing.
* (See f_readjust in ParseGrid)
*****************************************************************************
*/
static void ParseGridNoMiss (gridAttribType *attrib, double *grib_Data,
sInt4 Nx, sInt4 Ny, sInt4 *iain,
double unitM, double unitB, uChar f_wxType,
sect2_WxType *WxType, int startX, int startY,
int subNx, int subNy)
{
sInt4 x, y; /* Where we are in the grid. */
double value; /* The data in the new units. */
uChar f_maxmin = 0; /* Flag if max/min is valid yet. */
uInt4 index; /* Current index into Wx table. */
sInt4 *itemp = NULL;
float *ftemp = NULL;
/* Resolve possibility that the data is an integer or a float and find
* max/min values. (see note 1) */
for (y = 0; y < subNy; y++) {
if (((startY + y - 1) < 0) || ((startY + y - 1) >= Ny)) {
for (x = 0; x < subNx; x++) {
*grib_Data++ = 9999;
}
} else {
if (attrib->fieldType) {
itemp = iain + (startY + y - 1) * Nx + (startX - 1);
} else {
ftemp = ((float *) iain) + (startY + y - 1) * Nx + (startX - 1);
}
for (x = 0; x < subNx; x++) {
if (((startX + x - 1) < 0) || ((startX + x - 1) >= Nx)) {
*grib_Data++ = 9999;
} else {
/* Convert the units. */
if (attrib->fieldType) {
if (unitM == -10) {
value = pow (10.0, (*itemp++));
} else {
value = unitM * (*itemp++) + unitB;
}
} else {
if (unitM == -10) {
value = pow (10.0, (double) (*ftemp++));
} else {
value = unitM * (*ftemp++) + unitB;
}
}
if (f_wxType) {
index = (uInt4) value;
if (index < WxType->dataLen) {
if (WxType->ugly[index].f_valid == 1) {
WxType->ugly[index].f_valid = 2;
} else if (WxType->ugly[index].f_valid == 0) {
/* Table is not valid here so set value to missing? */
/* No missing value, so use index = WxType->dataLen? */
/* No... set f_valid to 3 so we know we used this
* invalid element, then handle it in degrib2.c ::
* ReadGrib2Record() where we set it back to 0. */
WxType->ugly[index].f_valid = 3;
}
}
}
if (f_maxmin) {
if (value < attrib->min) {
attrib->min = value;
} else if (value > attrib->max) {
attrib->max = value;
}
} else {
attrib->min = attrib->max = value;
f_maxmin = 1;
}
*grib_Data++ = value;
}
}
}
}
attrib->f_maxmin = f_maxmin;
}
/*****************************************************************************
* ParseGridPrimMiss() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* A helper function for ParseGrid. In this particular case it is dealing
* with a field that has primary missing value type.
* Walks through either a float or an integer grid, computing the min/max
* values in the grid, and converts the units. It uses gridAttrib info for the
* missing values and it updates gridAttrib with the observed min/max values.
*
* ARGUMENTS
* attrib = sect 5 structure already filled in by ParseSect5 (In/Output)
* grib_Data = The place to store the grid data. (Output)
* Nx, Ny = The dimensions of the grid (Input)
* iain = Place to find data if it is an Integer (or float). (Input)
* unitM = M in unit conversion equation y(new) = m x(orig) + b (Input)
* unitB = B in unit conversion equation y(new) = m x(orig) + b (Input)
* f_wxType = true if we have a valid wx type. (Input)
* WxType = table to look up values in. (Input)
* startX = The start of the X values. (Input)
* startY = The start of the Y values. (Input)
* subNx = The Nx dimmension of the subgrid (Input)
* subNy = The Ny dimmension of the subgrid (Input)
*
* FILES/DATABASES: None
*
* RETURNS: void
*
* HISTORY
* 12/2002 Arthur Taylor (MDL/RSIS): Created to optimize part of ParseGrid.
* 5/2003 AAT: Added ability to see if wxType occurs. If so sets table
* valid to 2, otherwise leaves it at 1. If table valid is 0 then
* sets value to missing value (if applicable).
* 2/2004 AAT: Added the subgrid capability.
*
* NOTES
* 1) Don't have to check if value became missing value, because we can check
* if missing falls in the range of the min/max converted units. If
* missing does fall in that range we need to move missing.
* (See f_readjust in ParseGrid)
*****************************************************************************
*/
static void ParseGridPrimMiss (gridAttribType *attrib, double *grib_Data,
sInt4 Nx, sInt4 Ny, sInt4 *iain,
double unitM, double unitB, sInt4 *missCnt,
uChar f_wxType, sect2_WxType *WxType,
int startX, int startY, int subNx, int subNy)
{
sInt4 x, y; /* Where we are in the grid. */
double value; /* The data in the new units. */
uChar f_maxmin = 0; /* Flag if max/min is valid yet. */
uInt4 index; /* Current index into Wx table. */
sInt4 *itemp = NULL;
float *ftemp = NULL;
/* float *ain = (float *) iain;*/
/* Resolve possibility that the data is an integer or a float and find
* max/min values. (see note 1) */
for (y = 0; y < subNy; y++) {
if (((startY + y - 1) < 0) || ((startY + y - 1) >= Ny)) {
for (x = 0; x < subNx; x++) {
*grib_Data++ = attrib->missPri;
(*missCnt)++;
}
} else {
if (attrib->fieldType) {
itemp = iain + (startY + y - 1) * Nx + (startX - 1);
} else {
ftemp = ((float *) iain) + (startY + y - 1) * Nx + (startX - 1);
}
for (x = 0; x < subNx; x++) {
if (((startX + x - 1) < 0) || ((startX + x - 1) >= Nx)) {
*grib_Data++ = attrib->missPri;
(*missCnt)++;
} else {
if (attrib->fieldType) {
value = (*itemp++);
} else {
value = (*ftemp++);
}
/* Make sure value is not a missing value when converting
* units, and while computing max/min. */
if (value == attrib->missPri) {
(*missCnt)++;
} else {
/* Convert the units. */
if (unitM == -10) {
value = pow (10.0, value);
} else {
value = unitM * value + unitB;
}
if (f_wxType) {
index = (uInt4) value;
if (index < WxType->dataLen) {
if (WxType->ugly[index].f_valid) {
WxType->ugly[index].f_valid = 2;
} else {
/* Table is not valid here so set value to missPri
*/
value = attrib->missPri;
(*missCnt)++;
}
}
}
if ((!f_wxType) || (value != attrib->missPri)) {
if (f_maxmin) {
if (value < attrib->min) {
attrib->min = value;
} else if (value > attrib->max) {
attrib->max = value;
}
} else {
attrib->min = attrib->max = value;
f_maxmin = 1;
}
}
}
*grib_Data++ = value;
}
}
}
}
attrib->f_maxmin = f_maxmin;
}
/*****************************************************************************
* ParseGridSecMiss() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* A helper function for ParseGrid. In this particular case it is dealing
* with a field that has NO missing value type.
* Walks through either a float or an integer grid, computing the min/max
* values in the grid, and converts the units. It uses gridAttrib info for the
* missing values and it updates gridAttrib with the observed min/max values.
*
* ARGUMENTS
* attrib = sect 5 structure already filled in by ParseSect5 (In/Output)
* grib_Data = The place to store the grid data. (Output)
* Nx, Ny = The dimensions of the grid (Input)
* iain = Place to find data if it is an Integer (or float). (Input)
* unitM = M in unit conversion equation y(new) = m x(orig) + b (Input)
* unitB = B in unit conversion equation y(new) = m x(orig) + b (Input)
* f_wxType = true if we have a valid wx type. (Input)
* WxType = table to look up values in. (Input)
* startX = The start of the X values. (Input)
* startY = The start of the Y values. (Input)
* subNx = The Nx dimmension of the subgrid (Input)
* subNy = The Ny dimmension of the subgrid (Input)
*
* FILES/DATABASES: None
*
* RETURNS: void
*
* HISTORY
* 12/2002 Arthur Taylor (MDL/RSIS): Created to optimize part of ParseGrid.
* 5/2003 AAT: Added ability to see if wxType occurs. If so sets table
* valid to 2, otherwise leaves it at 1. If table valid is 0 then
* sets value to missing value (if applicable).
* 2/2004 AAT: Added the subgrid capability.
*
* NOTES
* 1) Don't have to check if value became missing value, because we can check
* if missing falls in the range of the min/max converted units. If
* missing does fall in that range we need to move missing.
* (See f_readjust in ParseGrid)
*****************************************************************************
*/
static void ParseGridSecMiss (gridAttribType *attrib, double *grib_Data,
sInt4 Nx, sInt4 Ny, sInt4 *iain,
double unitM, double unitB, sInt4 *missCnt,
uChar f_wxType, sect2_WxType *WxType,
int startX, int startY, int subNx, int subNy)
{
sInt4 x, y; /* Where we are in the grid. */
double value; /* The data in the new units. */
uChar f_maxmin = 0; /* Flag if max/min is valid yet. */
uInt4 index; /* Current index into Wx table. */
sInt4 *itemp = NULL;
float *ftemp = NULL;
/* float *ain = (float *) iain;*/
/* Resolve possibility that the data is an integer or a float and find
* max/min values. (see note 1) */
for (y = 0; y < subNy; y++) {
if (((startY + y - 1) < 0) || ((startY + y - 1) >= Ny)) {
for (x = 0; x < subNx; x++) {
*grib_Data++ = attrib->missPri;
(*missCnt)++;
}
} else {
if (attrib->fieldType) {
itemp = iain + (startY + y - 1) * Nx + (startX - 1);
} else {
ftemp = ((float *) iain) + (startY + y - 1) * Nx + (startX - 1);
}
for (x = 0; x < subNx; x++) {
if (((startX + x - 1) < 0) || ((startX + x - 1) >= Nx)) {
*grib_Data++ = attrib->missPri;
(*missCnt)++;
} else {
if (attrib->fieldType) {
value = (*itemp++);
} else {
value = (*ftemp++);
}
/* Make sure value is not a missing value when converting
* units, and while computing max/min. */
if ((value == attrib->missPri) || (value == attrib->missSec)) {
(*missCnt)++;
} else {
/* Convert the units. */
if (unitM == -10) {
value = pow (10.0, value);
} else {
value = unitM * value + unitB;
}
if (f_wxType) {
index = (uInt4) value;
if (index < WxType->dataLen) {
if (WxType->ugly[index].f_valid) {
WxType->ugly[index].f_valid = 2;
} else {
/* Table is not valid here so set value to missPri
*/
value = attrib->missPri;
(*missCnt)++;
}
}
}
if ((!f_wxType) || (value != attrib->missPri)) {
if (f_maxmin) {
if (value < attrib->min) {
attrib->min = value;
} else if (value > attrib->max) {
attrib->max = value;
}
} else {
attrib->min = attrib->max = value;
f_maxmin = 1;
}
}
}
*grib_Data++ = value;
}
}
}
}
attrib->f_maxmin = f_maxmin;
}
/*****************************************************************************
* ParseGrid() --
*
* Arthur Taylor / MDL
*
* PURPOSE
* To walk through the 2 possible grids (and possible bitmap) created by
* UNPK_GRIB2, and combine the info into 1 grid, at the same time computing
* the min/max values in the grid. It uses gridAttrib info for the missing values
* and it then updates the gridAttrib structure for the min/max values that it
* found.
* It also uses scan, and ScanIndex2XY, to parse the data and organize the
* Grib_Data so that 0,0 is the lower left part of the grid, it then traverses
* the row and then moved up to the next row starting on the left.
*
* ARGUMENTS
* attrib = sect 5 structure already filled in by ParseSect5 (In/Output)
* Grib_Data = The place to store the grid data. (Output)
* grib_DataLen = The current size of Grib_Data (can increase) (Input/Output)
* Nx, Ny = The dimensions of the grid (Input)
* scan = How to walk through the original grid. (Input)
* iain = Place to find data if it is an Integer (or float). (Input)
* ibitmap = Flag stating the data has a bitmap for missing values (In)
* ib = Where to find the bitmap if we have one (Input)
* unitM = M in unit conversion equation y(new) = m x(orig) + b (Input)
* unitB = B in unit conversion equation y(new) = m x(orig) + b (Input)
* f_wxType = true if we have a valid wx type. (Input)
* WxType = table to look up values in. (Input)
* f_subGrid = True if we have a subgrid, false if not. (Input)
* startX stopX = The bounds of the subgrid in X. (0,-1) means full grid (In)
* startY stopY = The bounds of the subgrid in Y. (0,-1) means full grid (In)
*
* FILES/DATABASES: None
*
* RETURNS: void
*
* HISTORY
* 9/2002 Arthur Taylor (MDL/RSIS): Created.
* 11/2002 AAT: Added unit conversion to metaparse.c
* 12/2002 AAT: Optimized first loop to make it assume scan 0100 (64)
* (valid 99.9%), but still have slow loop for generic case.
* 5/2003 AAT: Added ability to see if wxType occurs. If so sets table
* valid to 2, otherwise leaves it at 1. If table valid is 0 then
* sets value to missing value (if applicable).
* 7/2003 AAT: added check if f_maxmin before checking if missing was in
* range of max, min for "readjust" check.
* 2/2004 AAT: Added startX / startY / stopX / stopY
* 5/2004 AAT: Found out that I used the opposite definition for bitmap
* 0 = missing, 1 = valid.
*
* NOTES
*****************************************************************************
*/
void ParseGrid (gridAttribType *attrib, double **Grib_Data,
uInt4 *grib_DataLen, uInt4 Nx, uInt4 Ny, int scan,
sInt4 *iain, sInt4 ibitmap, sInt4 *ib, double unitM,
double unitB, uChar f_wxType, sect2_WxType *WxType,
CPL_UNUSED uChar f_subGrid, int startX, int startY, int stopX, int stopY)
{
double xmissp; /* computed missing value needed for ibitmap = 1,
* Also used if unit conversion causes confusion
* over_ missing values. */
double xmisss; /* Used if unit conversion causes confusion over
* missing values. */
uChar f_readjust; /* True if unit conversion caused confusion over
* missing values. */
uInt4 scanIndex; /* Where we are in the original grid. */
sInt4 x, y; /* Where we are in a grid of scan value 0100 */
sInt4 newIndex; /* x,y in a 1 dimensional array. */
double value; /* The data in the new units. */
double *grib_Data; /* A pointer to Grib_Data for ease of manipulation. */
sInt4 missCnt = 0; /* Number of detected missing values. */
uInt4 index; /* Current index into Wx table. */
float *ain = (float *) iain;
uInt4 subNx; /* The Nx dimmension of the subgrid. */
uInt4 subNy; /* The Ny dimmension of the subgrid. */
subNx = stopX - startX + 1;
subNy = stopY - startY + 1;
myAssert (((!f_subGrid) && (subNx == Nx)) || (f_subGrid));
myAssert (((!f_subGrid) && (subNy == Ny)) || (f_subGrid));
if (subNx * subNy > *grib_DataLen) {
*grib_DataLen = subNx * subNy;
*Grib_Data = (double *) realloc ((void *) (*Grib_Data),
(*grib_DataLen) * sizeof (double));
}
grib_Data = *Grib_Data;
/* Resolve possibility that the data is an integer or a float, find
* max/min values, and do unit conversion. (see note 1) */
if (scan == 64) {
if (attrib->f_miss == 0) {
ParseGridNoMiss (attrib, grib_Data, Nx, Ny, iain, unitM, unitB,
f_wxType, WxType, startX, startY, subNx, subNy);
} else if (attrib->f_miss == 1) {
ParseGridPrimMiss (attrib, grib_Data, Nx, Ny, iain, unitM, unitB,
&missCnt, f_wxType, WxType, startX, startY,
subNx, subNy);
} else if (attrib->f_miss == 2) {
ParseGridSecMiss (attrib, grib_Data, Nx, Ny, iain, unitM, unitB,
&missCnt, f_wxType, WxType, startX, startY, subNx,
subNy);
}
} else {
/* Internally we use scan = 0100. Scan is usually 0100 from the
* unpacker library, but if scan is not, the following code converts
* it. We optimized the previous (scan 0100) case by calling a
* dedicated procedure. Here we don't since for scan != 0100, we
* would_ need a different unpacker library, which is extremely
* unlikely. */
for (scanIndex = 0; scanIndex < Nx * Ny; scanIndex++) {
if (attrib->fieldType) {
value = iain[scanIndex];
} else {
value = ain[scanIndex];
}
/* Make sure value is not a missing value when converting units, and
* while computing max/min. */
if ((attrib->f_miss == 0) ||
((attrib->f_miss == 1) && (value != attrib->missPri)) ||
((attrib->f_miss == 2) && (value != attrib->missPri) &&
(value != attrib->missSec))) {
/* Convert the units. */
if (unitM == -10) {
value = pow (10.0, value);
} else {
value = unitM * value + unitB;
}
/* Don't have to check if value became missing value, because we
* can check if missing falls in the range of min/max. If
* missing does fall in that range we need to move missing. See
* f_readjust */
if (f_wxType) {
index = (uInt4) value;
if (index < WxType->dataLen) {
if (WxType->ugly[index].f_valid == 1) {
WxType->ugly[index].f_valid = 2;
} else if (WxType->ugly[index].f_valid == 0) {
/* Table is not valid here so set value to missPri */
if (attrib->f_miss != 0) {
value = attrib->missPri;
missCnt++;
} else {
/* No missing value, so use index = WxType->dataLen */
/* No... set f_valid to 3 so we know we used this
* invalid element, then handle it in degrib2.c ::
* ReadGrib2Record() where we set it back to 0. */
WxType->ugly[index].f_valid = 3;
}
}
}
}
if ((!f_wxType) ||
((attrib->f_miss == 0) || (value != attrib->missPri))) {
if (attrib->f_maxmin) {
if (value < attrib->min) {
attrib->min = value;
} else if (value > attrib->max) {
attrib->max = value;
}
} else {
attrib->min = attrib->max = value;
attrib->f_maxmin = 1;
}
}
} else {
missCnt++;
}
ScanIndex2XY (scanIndex, &x, &y, scan, Nx, Ny);
/* ScanIndex returns value as if scan was 0100 */
newIndex = (x - 1) + (y - 1) * Nx;
grib_Data[newIndex] = value;
}
}
/* Deal with possibility that unit conversion ended up with valid numbers
* being interpreted as missing. */
f_readjust = 0;
xmissp = attrib->missPri;
xmisss = attrib->missSec;
if (attrib->f_maxmin) {
if ((attrib->f_miss == 1) || (attrib->f_miss == 2)) {
if ((attrib->missPri >= attrib->min) &&
(attrib->missPri <= attrib->max)) {
xmissp = attrib->max + 1;
f_readjust = 1;
}
if (attrib->f_miss == 2) {
if ((attrib->missSec >= attrib->min) &&
(attrib->missSec <= attrib->max)) {
xmisss = attrib->max + 2;
f_readjust = 1;
}
}
}
}
/* Walk through the grid, resetting the missing values, as determined by
* the original grid. */
if (f_readjust) {
for (scanIndex = 0; scanIndex < Nx * Ny; scanIndex++) {
ScanIndex2XY (scanIndex, &x, &y, scan, Nx, Ny);
/* ScanIndex returns value as if scan was 0100 */
newIndex = (x - 1) + (y - 1) * Nx;
if (attrib->fieldType) {
value = iain[scanIndex];
} else {
value = ain[scanIndex];
}
if (value == attrib->missPri) {
grib_Data[newIndex] = xmissp;
} else if ((attrib->f_miss == 2) && (value == attrib->missSec)) {
grib_Data[newIndex] = xmisss;
}
}
attrib->missPri = xmissp;
if (attrib->f_miss == 2) {
attrib->missSec = xmisss;
}
}
/* Resolve bitmap (if there is one) in the data. */
if (ibitmap) {
attrib->f_maxmin = 0;
if ((attrib->f_miss != 1) && (attrib->f_miss != 2)) {
missCnt = 0;
/* Figure out a missing value. */
xmissp = 9999;
if (attrib->f_maxmin) {
if ((xmissp <= attrib->max) && (xmissp >= attrib->min)) {
xmissp = attrib->max + 1;
}
}
/* embed the missing value. */
for (scanIndex = 0; scanIndex < Nx * Ny; scanIndex++) {
ScanIndex2XY (scanIndex, &x, &y, scan, Nx, Ny);
/* ScanIndex returns value as if scan was 0100 */
newIndex = (x - 1) + (y - 1) * Nx;
/* Corrected this on 5/10/2004 */
if (ib[scanIndex] != 1) {
grib_Data[newIndex] = xmissp;
missCnt++;
} else {
if (!attrib->f_maxmin) {
attrib->f_maxmin = 1;
attrib->max = attrib->min = grib_Data[newIndex];
} else {
if (attrib->max < grib_Data[newIndex])
attrib->max = grib_Data[newIndex];
if (attrib->min > grib_Data[newIndex])
attrib->min = grib_Data[newIndex];
}
}
}
attrib->f_miss = 1;
attrib->missPri = xmissp;
}
if (!attrib->f_maxmin) {
attrib->f_maxmin = 1;
attrib->max = attrib->min = xmissp;
}
}
attrib->numMiss = missCnt;
}
typedef struct {
double value;
int cnt;
} freqType;
int freqCompare (const void *A, const void *B)
{
const freqType *a = (freqType *) A;
const freqType *b = (freqType *) B;
if (a->value < b->value)
return -1;
if (a->value > b->value)
return 1;
return 0;
}
void FreqPrint (char **ans, double *Data, sInt4 DataLen, sInt4 Nx,
sInt4 Ny, sChar decimal, char *comment)
{
int x, y, i;
double *ptr;
double value;
freqType *freq = NULL;
int numFreq = 0;
char format[20];
myAssert (*ans == NULL);
if ((Nx < 0) || (Ny < 0) || (Nx * Ny > DataLen)) {
return;
}
ptr = Data;
for (y = 0; y < Ny; y++) {
for (x = 0; x < Nx; x++) {
/* 2/28/2006 Introduced value to round before putting the data in
* the Freq table. */
value = myRound (*ptr, decimal);
for (i = 0; i < numFreq; i++) {
if (value == freq[i].value) {
freq[i].cnt++;
break;
}
}
if (i == numFreq) {
numFreq++;
freq = (freqType *) realloc (freq, numFreq * sizeof (freqType));
freq[i].value = value;
freq[i].cnt = 1;
}
ptr++;
}
}
qsort (freq, numFreq, sizeof (freq[0]), freqCompare);
mallocSprintf (ans, "%s | count\n", comment);
sprintf (format, "%%.%df | %%d\n", decimal);
for (i = 0; i < numFreq; i++) {
reallocSprintf (ans, format, myRound (freq[i].value, decimal),
freq[i].cnt);
}
free (freq);
}
|
.ORIG x1000
ADD R1, R0, 1 ; 1 is an invalid operand (neither a register nor an immediate)
.END
|
; A071412: A002487 mod 3.
; Submitted by Jamie Morken(s4)
; 0,1,1,2,1,0,2,0,1,1,0,2,2,2,0,1,1,2,1,1,0,2,2,1,2,1,2,2,0,1,1,2,1,0,2,0,1,2,1,1,0,2,2,1,2,0,1,0,2,0,1,0,2,1,2,2,0,1,1,2,1,0,2,0,1,1,0,2,2,2,0,1,1,0,2,0,1,2,1,1,0,2,2,1,2,0,1,0,2,2,0,1,1,1,0,2,2,2,0,1
lpb $0
dif $0,2
lpe
seq $0,2487 ; Stern's diatomic series (or Stern-Brocot sequence): a(0) = 0, a(1) = 1; for n > 0: a(2*n) = a(n), a(2*n+1) = a(n) + a(n+1).
mod $0,-3
|
; ============================================================================
; mixer_fpu_ramp_asm.asm
; ---------------------------------------------------------------------------
; MiniFMOD public source code release.
; This source is provided as-is. Firelight Multimedia will not support
; or answer questions about the source provided.
; MiniFMOD Sourcecode is copyright (c) 2000, Firelight Multimedia.
; MiniFMOD Sourcecode is in no way representative of FMOD 3 source.
; Firelight Multimedia is a registered business name.
; This source must not be redistributed without this notice.
; ----------------------------------------------------------------------------
; Some parts of this source file is copyright (c) 2002, Luks <luks@host.sk>
; ===========================================================================
; include file generated by 'genasminc'
%include "mixer_fpu_ramp_asm.inc"
;%define ROLLED ; this would make it smaller but quite slow
%define VOLUMERAMPING ; enable/disable volume ramping
[section .data]
; = GLOBAL DATA DECLARATION ==================================================
%ifdef __WIN32__
%define mix_volumerampsteps _mix_volumerampsteps
%endif
[global mix_volumerampsteps]
%ifdef __WIN32__
%define mix_1overvolumerampsteps _mix_1overvolumerampsteps
%endif
[global mix_1overvolumerampsteps]
; = LOCAL DATA ===============================================================
mix_numsamples dd 0
mix_mixptr dd 0
mix_mixbuffend dd 0
mix_mixbuffptr dd 0
mix_endflag dd 0
mix_sptr dd 0
mix_cptr dd 0
mix_count dd 0
mix_samplebuff dd 0
mix_leftvol dd 0
mix_rightvol dd 0
mix_temp1 dd 0
mix_count_old dd 0
mix_rampleftvol dd 0
mix_ramprightvol dd 0
mix_rampcount dd 0
mix_rampspeedleft dd 0
mix_rampspeedright dd 0
mix_volumerampsteps dd 0
mix_1overvolumerampsteps dd 0
mix_255 dd 255.0
mix_256 dd 256.0
mix_1over255 dd 0.0039215686 ; 1.0 / 255.0
mix_1over256 dd 0.00390625 ; 1.0 / 256.0
mix_1over2gig dd 4.65612e-10 ; 1.0 / 2147483648.0
[section .text]
; = CODE =====================================================================
[global FSOUND_Mixer_FPU_Ramp_ASM]
FSOUND_Mixer_FPU_Ramp_ASM:
push ebp
mov [mix_numsamples], eax
mov [mix_mixptr], ebx
mov [mix_mixbuffend], edx
mov [mix_mixbuffptr], ebx
mov [mix_cptr], ecx
cmp ecx, 0 ; if (!cptr) ...
je near MixExit ; ... then skip this channel!
mov ebx, [ecx+FSOUND_CHANNEL.sptr] ; load the correct SAMPLE pointer for this channel
mov [mix_sptr], ebx ; store sample pointer away
cmp ebx, 0 ; if (!sptr) ...
je near MixExit ; ... then skip this channel!
; get pointer to sample buffer
mov eax, [ebx+FSOUND_SAMPLE.buff]
mov [mix_samplebuff], eax
;==============================================================================================
; LOOP THROUGH CHANNELS
; through setup code:- usually ebx = sample pointer, ecx = channel pointer
;==============================================================================================
;= SUCCESS - SETUP CODE FOR THIS CHANNEL ======================================================
; =========================================================================================
; the following code sets up a mix counter. it sees what will happen first, will the output buffer
; end be reached first? or will the end of the sample be reached first? whatever is smallest will
; be the mixcount.
; first base mixcount on size of OUTPUT BUFFER (in samples not bytes)
mov eax, [mix_numsamples]
CalculateLoopCount:
mov [mix_count], eax
mov esi, [ecx+FSOUND_CHANNEL.mixpos]
mov ebp, FSOUND_OUTPUTBUFF_END
mov [mix_endflag], ebp ; set a flag to say mixing will end when end of output buffer is reached
cmp dword [ecx+FSOUND_CHANNEL.speeddir], FSOUND_MIXDIR_FORWARDS
jne samplesleftbackwards
; work out how many samples left from mixpos to loop end
mov edx, [ebx+FSOUND_SAMPLE.loopstart]
add edx, [ebx+FSOUND_SAMPLE.looplen]
sub edx, esi ; eax = samples left (loopstart+looplen-mixpos)
mov eax, [ecx+FSOUND_CHANNEL.mixposlo]
xor ebp, ebp
sub ebp, eax
sbb edx, 0
mov eax, ebp
jmp samplesleftfinish
samplesleftbackwards:
; work out how many samples left from mixpos to loop start
mov edx, [ecx+FSOUND_CHANNEL.mixpos]
mov eax, [ecx+FSOUND_CHANNEL.mixposlo]
sub eax, 0h
sbb edx, [ebx+FSOUND_SAMPLE.loopstart]
samplesleftfinish:
; edx:eax now contains number of samples left to mix
cmp edx, 1000000h
jae staywithoutputbuffend
shrd eax, edx, 8
shr edx, 8
; now samples left = EDX:EAX -> hhhhhlll
mov ebp, [ecx+FSOUND_CHANNEL.speedhi]
mov edi, [ecx+FSOUND_CHANNEL.speedlo]
shl ebp, 24
shr edi, 8
and edi, 000FFFFFFh
or ebp, edi
div ebp
or edx,edx ; if fractional 16-bit part is zero we must add an extra carry number
jz dontaddbyte ; to the resultant in EDX:EAX.
inc eax
dontaddbyte: ; we must remove the fractional part of the multiply by shifting EDX:EAX
cmp eax, [mix_count]
ja staywithoutputbuffend
mov [mix_count], eax
mov edx, FSOUND_SAMPLEBUFF_END ; set a flag to say mix will end when end of output buffer is reached
mov [mix_endflag], edx
staywithoutputbuffend:
mov ecx, [mix_cptr]
;= VOLUME RAMP SETUP =========================================================
; Reasons to ramp
; 1. volume change
; 2. sample starts (just treat as volume change - 0 to volume)
; 3. sample ends (ramp last n number of samples from volume to 0)
; now if the volume has changed, make end condition equal a volume ramp
mov dword [mix_rampspeedleft], 0 ; clear out volume ramp
mov dword [mix_rampspeedright], 0 ; clear out volume ramp
%ifdef VOLUMERAMPING
mov eax, [mix_count]
mov [mix_count_old], eax ; remember mix count before modifying it
mov dword [mix_rampcount], 0
cmp dword [ecx+FSOUND_CHANNEL.ramp_count], 0
je volumerampstart
; if it tries to continue an old ramp, but the target has changed,
; set up a new ramp
mov eax, [ecx+FSOUND_CHANNEL.leftvolume]
mov edx, [ecx+FSOUND_CHANNEL.ramp_lefttarget]
cmp eax,edx
jne volumerampstart
mov eax, [ecx+FSOUND_CHANNEL.rightvolume]
mov edx, [ecx+FSOUND_CHANNEL.ramp_righttarget]
cmp eax,edx
jne volumerampstart
; restore old ramp
mov eax, [ecx+FSOUND_CHANNEL.ramp_count]
mov [mix_rampcount], eax
mov eax, [ecx+FSOUND_CHANNEL.ramp_leftspeed]
mov [mix_rampspeedleft], eax
mov eax, [ecx+FSOUND_CHANNEL.ramp_rightspeed]
mov [mix_rampspeedright], eax
jmp novolumerampR
volumerampstart:
mov eax, [ecx+FSOUND_CHANNEL.leftvolume]
mov edx, [ecx+FSOUND_CHANNEL.ramp_leftvolume]
shr edx, 8
mov [ecx+FSOUND_CHANNEL.ramp_lefttarget], eax
sub eax, edx
cmp eax, 0
je novolumerampL
mov [mix_temp1], eax
fild dword [mix_temp1]
fmul dword [mix_1over255]
fmul dword [mix_1overvolumerampsteps]
fstp dword [mix_rampspeedleft]
mov eax, [mix_rampspeedleft]
mov [ecx+FSOUND_CHANNEL.ramp_leftspeed], eax
mov eax, [mix_volumerampsteps]
mov [mix_rampcount], eax
novolumerampL:
mov eax, [ecx+FSOUND_CHANNEL.rightvolume]
mov edx, [ecx+FSOUND_CHANNEL.ramp_rightvolume]
shr edx, 8
mov [ecx+FSOUND_CHANNEL.ramp_righttarget], eax
sub eax, edx
cmp eax, 0
je novolumerampR
mov [mix_temp1], eax
fild dword [mix_temp1]
fmul dword [mix_1over255]
fmul dword [mix_1overvolumerampsteps]
fstp dword [mix_rampspeedright]
mov eax, [mix_rampspeedright]
mov [ecx+FSOUND_CHANNEL.ramp_rightspeed], eax
mov eax, [mix_volumerampsteps]
mov [mix_rampcount], eax
novolumerampR:
mov eax, [mix_rampcount]
cmp eax, 0
jle volumerampend
mov [ecx+FSOUND_CHANNEL.ramp_count], eax
cmp [mix_count], eax
jbe volumerampend ; dont clamp mixcount
mov [mix_count], eax
volumerampend:
%endif
;= SET UP VOLUME MULTIPLIERS ==================================================
; set up left/right volumes
mov ecx, [mix_cptr]
; right volume
mov eax, [ecx+FSOUND_CHANNEL.rightvolume]
mov [mix_temp1], eax
fild dword [mix_temp1]
fmul dword [mix_1over255]
fstp dword [mix_rightvol]
; left volume
mov eax, [ecx+FSOUND_CHANNEL.leftvolume]
mov [mix_temp1], eax
fild dword [mix_temp1]
fmul dword [mix_1over255]
fstp dword [mix_leftvol]
; right ramp volume
mov eax, [ecx+FSOUND_CHANNEL.ramp_rightvolume]
mov [mix_temp1], eax
fild dword [mix_temp1]
fmul dword [mix_1over256] ; first convert from 24:8 to 0-255
fmul dword [mix_1over255] ; now make 0-1.0f
fstp dword [mix_ramprightvol]
; left ramp volume
mov eax, [ecx+FSOUND_CHANNEL.ramp_leftvolume]
mov [mix_temp1], eax
fild dword [mix_temp1]
fmul dword [mix_1over256] ; first convert from 24:8 to 0-255
fmul dword [mix_1over255] ; now make 0-1.0f
fstp dword [mix_rampleftvol]
;= SET UP ALL OF THE REGISTERS HERE FOR THE INNER LOOP ====================================
; eax = ---
; ebx = speed low
; ecx = speed high
; edx = counter
; esi = mixpos
; edi = destination pointer
; ebp = mixpos low
mov eax, [mix_cptr]
mov ebx, [eax+FSOUND_CHANNEL.speedlo]
mov ecx, [eax+FSOUND_CHANNEL.speedhi]
; mov edx, mix_count
mov ebp, [eax+FSOUND_CHANNEL.mixposlo]
mov esi, [eax+FSOUND_CHANNEL.mixpos]
mov edi, [mix_mixbuffptr] ; point edi to 16bit output stream
cmp dword [eax+FSOUND_CHANNEL.speeddir], FSOUND_MIXDIR_FORWARDS
je NoChangeSpeed
xor ebx, 0FFFFFFFFh
xor ecx, 0FFFFFFFFh
add ebx, 1
adc ecx, 0
NoChangeSpeed:
;======================================================================================
; ** 16 BIT NORMAL FUNCTIONS **********************************************************
;======================================================================================
mov eax, [mix_samplebuff]
shr eax, 1
add esi, eax
mov edx, [mix_count]
%ifdef VOLUMERAMPING
cmp dword [mix_rampcount], 0
jne near MixLoopStart16_2
%endif
%ifdef ROLLED
jmp MixLoopStart16
%endif
shr edx, 1
or edx, edx
jz near MixLoopStart16 ; no groups of 2 samples to mix!
; START
shr ebp, 1 ; 1 make 31bit coz fpu only loads signed values
add edi, 16 ;
fild word [esi+esi+2] ; 1 [0]samp1+1
mov [mix_temp1], ebp ; 1
; nop
fild word [esi+esi] ; 1 [0]samp1 [1]samp1+1
fild dword [mix_temp1] ; 1 [0]ifrac1 [1]samp1 [2]samp1+1
add ebp, ebp ; 1
; nop
add ebp, ebx ; 1
adc esi, ecx ; 1
fmul dword [mix_1over2gig] ; 1 [0]ffrac1 [1]samp1 [2]samp1+1
fild word [esi+esi+2] ; 1 [0]samp2+1 [1]ffrac1 [2]samp1 [3]samp1+1
shr ebp, 1 ; 1
; nop
mov dword [mix_temp1], ebp ; 1
; nop
fild dword [mix_temp1] ; 1 [0]ifrac2 [1]samp2+1 [2]ffrac1 [3]samp1 [4]samp1+1
fild word [esi+esi] ; 1 [0]samp2 [1]ifrac2 [2]samp2+1 [3]ffrac1 [4]samp1 [5]samp1+1
fxch st5 ; [0]samp1+1 [1]ifrac2 [2]samp2+1 [3]ffrac1 [4]samp1 [5]samp2
fsub st0, st4 ; 1 [0]delta1 [1]ifrac2 [2]samp2+1 [3]ffrac1 [4]samp1 [5]samp2
; fnop ; 1 fsub stall
shl ebp, 1 ; 1
; nop
fmulp st3, st0 ; 1 [0]ifrac2 [1]samp2+1 [2]interp1 [3]samp1 [4]samp2
fmul dword [mix_1over2gig] ; 1 [0]ffrac2 [1]samp2+1 [2]interp1 [3]samp1 [4]samp2
fxch st1 ; [0]samp2+1 [1]ffrac2 [2]interp1 [3]samp1 [4]samp2
fsub st0, st4 ; 1 [0]delta2 [1]ffrac2 [2]interp1 [3]samp1 [4]samp2
add ebp, ebx ; 1
; nop
adc esi, ecx ; 1
; nop
fmulp st1, st0 ; 1 [0]interp2 [1]interp1 [2]samp1 [3]samp2
fxch st1 ; [0]interp1 [1]interp2 [2]samp1 [3]samp2
faddp st2, st0 ; 1 [0]interp2 [1]newsamp1 [2]samp2
; fnop ; 1 fadd stall
; fnop ; 1 fadd stall
fld st1 ; 1 [0]newsamp1 [1]interp2 [2]newsamp1 [3]samp2
fmul dword [mix_leftvol] ; 1 [0]newsampL1 [1]interp2 [2]newsamp1 [3]samp2
fxch st1 ; [0]interp2 [1]newsampL1 [2]newsamp1 [3]samp2
faddp st3, st0 ; 1 [0]newsampL1 [1]newsamp1 [2]newsamp2
fxch st1 ; 1 [0]newsamp1 [1]newsampL1 [2]newsamp2
jmp MixLoopUnroll16CoilEntry ; 1
ALIGN 16
MixLoopUnroll16:
shr ebp, 1 ; 1
; nop
mov [mix_temp1], ebp ; 1
; nop
fild word [esi+esi+2] ; 1 [0]samp1+1 [1]finalR2 [2]finalR1 [3]finalL2
fild word [esi+esi] ; 1 [0]samp1 [1]samp1+1 [2]finalR2 [3]finalR1 [4]finalL2
fild dword [mix_temp1] ; 1 [0]ifrac1 [1]samp1 [2]samp1+1 [3]finalR2 [4]finalR1 [5]finalL2
add ebp, ebp ; 1
; nop
add ebp, ebx ; 1
; nop
adc esi, ecx ; 1
add edi, 16 ;
fmul dword [mix_1over2gig] ; 1 [0]ffrac1 [1]samp1 [2]samp1+1 [3]finalR2 [4]finalR1 [5]finalL2
shr ebp, 1 ; 1
; nop
mov [mix_temp1], ebp ; 1
; nop
fild dword [mix_temp1] ; 1 [0]ifrac2 [1]ffrac1 [2]samp1 [3]samp1+1 [4]finalR2 [5]finalR1 [6]finalL2
fild word [esi+esi+2] ; 1 [0]samp2+1 [1]ifrac2 [2]ffrac1 [3]samp1 [4]samp1+1 [5]finalR2 [6]finalR1 [7]finalL2
fxch st4 ; [0]samp1+1 [1]ifrac2 [2]ffrac1 [3]samp1 [4]samp2+1 [5]finalR2 [6]finalR1 [7]finalL2
fsub st0, st3 ; 1 [0]delta1 [1]ifrac2 [2]ffrac1 [3]samp1 [4]samp2+1 [5]finalR2 [6]finalR1 [7]finalL2
; fnop ; 1 fsub stall
shl ebp, 1 ; 1
; nop
fmulp st2, st0 ; 1 [0]ifrac2 [1]interp1 [2]samp1 [3]samp2+1 [4]finalR2 [5]finalR1 [6]finalL2
fild word [esi+esi] ; 1 [0]samp2 [1]ifrac2 [2]interp1 [3]samp1 [4]samp2+1 [5]finalR2 [6]finalR1 [7]finalL2
fxch st1 ; [0]ifrac2 [1]samp2 [2]interp1 [3]samp1 [4]samp2+1 [5]finalR2 [6]finalR1 [7]finalL2
fmul dword [mix_1over2gig] ; 1 [0]ffrac2 [1]samp2 [2]interp1 [3]samp1 [4]samp2+1 [5]finalR2 [6]finalR1 [7]finalL2
fxch st4 ; [0]samp2+1 [1]samp2 [2]interp1 [3]samp1 [4]ffrac2 [5]finalR2 [6]finalR1 [7]finalL2
fsub st0, st1 ; 1 [0]delta2 [1]samp2 [2]interp1 [3]samp1 [4]ffrac2 [5]finalR2 [6]finalR1 [7]finalL2
add ebp, ebx ; 1
; nop
adc esi, ecx ; 1
; nop
fmulp st4, st0 ; 1 [0]samp2 [1]interp1 [2]samp1 [3]interp2 [4]finalR2 [5]finalR1 [6]finalL2
fxch st2 ; [0]samp1 [1]interp1 [2]samp2 [3]interp2 [4]finalR2 [5]finalR1 [6]finalL2
faddp st1, st0 ; 1 [0]newsamp1 [1]samp2 [2]interp2 [3]finalR2 [4]finalR1 [5]finalL2
fxch st4 ; [0]finalR1 [1]samp2 [2]interp2 [3]finalR2 [4]newsamp1 [5]finalL2
fstp dword [edi-28] ; 2 [0]samp2 [1]interp2 [2]finalR2 [3]newsamp1 [4]finalL2
fxch st4 ; 1 [0]finalL2 [1]interp2 [2]finalR2 [3]newsamp1 [4]samp2
fstp dword [edi-24] ; 2 [0]interp2 [1]finalR2 [2]newsamp1 [3]samp2
fld st2 ; 1 [0]newsamp1 [1]interp2 [2]finalR2 [3]newsamp1 [4]samp2
fmul dword [mix_leftvol] ; 1 [0]newsampL1 [1]interp2 [2]finalR2 [3]newsamp1 [4]samp2
fxch st1 ; [0]interp2 [1]newsampL1 [2]finalR2 [3]newsamp1 [4]samp2
faddp st4, st0 ; 1 [0]newsampL1 [1]finalR2 [2]newsamp1 [3]newsamp2
fxch st1 ; [0]finalR2 [1]newsampL1 [2]newsamp1 [3]newsamp2
fstp dword [edi-20] ; 2 [0]newsampL1 [1]newsamp1 [2]newsamp2
fxch st1 ; 1 [0]newsamp1 [1]newsampL1 [2]newsamp2
MixLoopUnroll16CoilEntry: ; [0]newsamp1 [1]newsampL1 [2]newsamp2
fmul dword [mix_rightvol] ; 1 [0]newsampR1 [1]newsampL1 [2]newsamp2
fxch st2 ; [0]newsamp2 [1]newsampL1 [2]newsampR1
fld st0 ; 1 [0]newsamp2 [1]newsamp2 [2]newsampL1 [3]newsampR1
fmul dword [mix_leftvol] ; 1 [0]newsampL2 [1]newsamp2 [2]newsampL1 [3]newsampR1
fxch st1 ; [0]newsamp2 [1]newsampL2 [2]newsampL1 [3]newsampR1
; fnop ; 1 delay on mul unit
fmul dword [mix_rightvol] ; 1 [0]newsampR2 [1]newsampL2 [2]newsampL1 [3]newsampR1
fxch st2 ; [0]newsampL1 [1]newsampL2 [2]newsampR2 [3]newsampR1
fadd dword [edi-16] ; 1 [0]finalL1 [1]newsampL2 [2]newsampR2 [3]newsampR1
fxch st3 ; [0]newsampR1 [1]newsampL2 [2]newsampR2 [3]finalL1
fadd dword [edi-12] ; 1 [0]finalR1 [1]newsampL2 [2]newsampR2 [3]finalL1
fxch st1 ; [0]newsampL2 [1]finalR1 [2]newsampR2 [3]finalL1
fadd dword [edi-8] ; 1 [0]finalL2 [1]finalR1 [2]newsampR2 [3]finalL1
fxch st3 ; [0]finalL1 [1]finalR1 [2]newsampR2 [3]finalL2
; fnop ; 1 delay on store?
fstp dword [edi-16] ; 2 [0]finalR1 [1]newsampR2 [2]finalL2
fxch st1 ; 1 [0]newsampR2 [1]finalR1 [2]finalL2
fadd dword [edi-4] ; 1 [0]finalR2 [1]finalR1 [2]finalL2
dec edx ; 1
jnz near MixLoopUnroll16 ;
fxch st1 ; 1 [0]finalR1 [1]finalR2 [2]finalL2
fstp dword [edi-12] ; 2 [0]finalR2 [1]finalL2
fxch st1 ; 1 [0]finalL2 [1]finalR2
fstp dword [edi-8] ; 2 [0]finalR2
fstp dword [edi-4] ; 2
;= MIX 16BIT, ROLLED ==================================================================
MixLoopStart16:
mov edx, [mix_count]
%ifndef ROLLED
and edx, 1
%endif
%ifdef VOLUMERAMPING
MixLoopStart16_2:
%endif
or edx, edx ; if count == 0 dont enter the mix loop
jz near MixLoopEnd16
%ifdef VOLUMERAMPING
fld dword [mix_rampspeedleft] ; [0]rampspeedL
fld dword [mix_rampspeedright] ; [0]rampspeedR [1]rampspeedL
fld dword [mix_rampleftvol] ; [0]lvol [1]rampspeedR [2]rampspeedL
fld dword [mix_ramprightvol] ; [0]rvol [1]lvol [2]rampspeedR [3]rampspeedL
%else
fldz ; [0]rampspeedL
fldz ; [0]rampspeedR [1]rampspeedL
fld dword [mix_leftvol] ; [0]lvol [1]rampspeedR [2]rampspeedL
fld dword [mix_rightvol] ; [0]rvol [1]lvol [2]rampspeedR [3]rampspeedL
%endif
jmp MixLoop16
ALIGN 16
MixLoop16:
shr ebp, 1 ; 1 make 31bit coz fpu only loads signed values
add edi, 8 ;
fild word [esi+esi+2] ; 1 [0]samp1+1 [1]rvol [2]lvol [3]rampspeedR [4]rampspeedL
mov [mix_temp1], ebp ; 1
fild word [esi+esi] ; 1 [0]samp1 [2]samp1+1 [3]rvol [4]lvol [5]rampspeedR [6]rampspeedL
fild dword [mix_temp1] ; 1 [0]ifrac [1]samp1 [2]samp1+1 [3]rvol [4]lvol [5]rampspeedR [6]rampspeedL
shl ebp, 1 ; 1 restore mixpos low
add ebp, ebx ; add speed low to mixpos low
adc esi, ecx ; 1 add upper portion of speed plus carry
; nop
fmul dword [mix_1over2gig] ; 1 [0]ifrac [1]samp1 [2]samp1+1 [3]rvol [4]lvol [5]rampspeedR [6]rampspeedL
fxch st2 ; [0]samp1+1 [1]samp1 [2]ffrac [3]rvol [4]lvol [5]rampspeedR [6]rampspeedL
fsub st0, st1 ; 1 [0]delta1 [1]samp1 [2]ffrac [3]rvol [4]lvol [5]rampspeedR [6]rampspeedL
; fnop ; 1
; fnop ; 1
; fnop ; 1
fmulp st2, st0 ; 1 [0]sample [1]interp [2]rvol [3]lvol [4]rampspeedR [5]rampspeedL
; fnop ; 1
; fnop ; 1
; fnop ; 1
; fnop ; 1
faddp st1, st0 ; 1 [0]newsamp [1]rvol [2]lvol [3]rampspeedR [4]rampspeedL
; fnop ; 1
; fnop ; 1
fld st0 ; 1 [0]newsamp [1]newsamp [2]rvol [3]lvol [4]rampspeedR [5]rampspeedL
fmul st0, st3 ; 1 [0]newsampL [1]newsamp [2]rvol [3]lvol [4]rampspeedR [5]rampspeedL
fxch st3 ; [0]lvol [1]newsamp [2]rvol [3]newsampL [4]rampspeedR [5]rampspeedL
fadd st0, st5 ; 1 [0]lvol [1]newsamp [2]rvol [3]newsampL [4]rampspeedR [5]rampspeedL
fxch st1 ; [0]newsamp [1]lvol [2]rvol [3]newsampL [4]rampspeedR [5]rampspeedL
fmul st0, st2 ; 1 [0]newsampR [1]lvol [2]rvol [3]newsampL [4]rampspeedR [5]rampspeedL
fxch st2 ; [0]rvol [1]lvol [2]newsampR [3]newsampL [4]rampspeedR [5]rampspeedL
fadd st0, st4 ; 1 [0]rvol [1]lvol [2]newsampR [3]newsampL [4]rampspeedR [5]rampspeedL
fxch st3 ; [0]newsampL [1]lvol [2]newsampR [3]rvol [4]rampspeedR [5]rampspeedL
; fnop ; 1
; fnop ; 1
fadd dword [edi-8] ; 1 [0]finalL [1]lvol [2]newsampR [3]rvol [4]rampspeedR [5]rampspeedL
fxch st2 ; [0]newsampR [1]lvol [2]finalL [3]rvol [4]rampspeedR [5]rampspeedL
fadd dword [edi-4] ; 1 [0]finalR [1]lvol [2]finalL [3]rvol [4]rampspeedR [5]rampspeedL
fxch st2 ; [0]finalL [1]lvol [2]finalR [3]rvol [4]rampspeedR [5]rampspeedL
; fnop ; 1
fstp dword [edi-8] ; 1 [0]lvol [1]finalR [2]rvol [3]rampspeedR [4]rampspeedL
fxch st1 ; [0]finalR [1]lvol [2]rvol [3]rampspeedR [4]rampspeedL
fstp dword [edi-4] ; 3 [0]lvol [1]rvol [2]rampspeedR [3]rampspeedL
fxch st1 ; [0]rvol [1]lvol [2]rampspeedR [3]rampspeedL
dec edx ; 1
jnz MixLoop16 ;
fxch st2 ; [0]rampspeedR [1]lvol [2]rvol [3]rampspeedL
fstp dword [mix_rampspeedright] ; [0]lvol [1]rvol [2]rampspeedL
fxch st2 ; [0]rampspeedL [1]rvol [2]lvol
fstp dword [mix_rampspeedleft] ; [0]rvol [1]lvol
fmul dword [mix_255] ; [0]rvol*255 [1]lvol
fmul dword [mix_256] ; [0]rvol*255*256 [1]lvol
fxch st1 ; [0]lvol [1]rvol*255*256
fmul dword [mix_255] ; [0]lvol*255 [1]rvol*255*256
fmul dword [mix_256] ; [0]lvol*255*256 [1]rvol*255*256
xor eax, eax
fistp dword [mix_rampleftvol] ; [0]rvol*255*256
fistp dword [mix_ramprightvol] ;
MixLoopEnd16:
mov eax, [mix_samplebuff]
shr eax, 1
sub esi, eax
%ifdef VOLUMERAMPING
;=============================================================================================
; DID A VOLUME RAMP JUST HAPPEN
;=============================================================================================
cmp dword [mix_rampcount], 0
je near DoOutputbuffEnd ; no, no ramp
mov ebx, [mix_sptr] ; load ebx with sample pointer
mov ecx, [mix_cptr] ; load ecx with channel pointer
mov eax, [mix_rampleftvol]
mov [ecx+FSOUND_CHANNEL.ramp_leftvolume], eax
mov eax, [mix_ramprightvol]
mov [ecx+FSOUND_CHANNEL.ramp_rightvolume], eax
mov eax, [mix_count]
mov edx, [mix_rampcount]
sub edx, eax
mov dword [mix_rampspeedleft], 0 ; clear out volume ramp
mov dword [mix_rampspeedright], 0 ; clear out volume ramp
mov dword [mix_rampcount], edx
mov [ecx+FSOUND_CHANNEL.ramp_count], edx
; if rampcount now = 0, a ramp has FINISHED, so finish the rest of the mix
cmp edx, 0
jne DoOutputbuffEnd
; clear out the ramp speeds
mov dword [ecx+FSOUND_CHANNEL.ramp_leftspeed], 0
mov dword [ecx+FSOUND_CHANNEL.ramp_rightspeed], 0
; clamp the 2 volumes together in case the speed wasnt accurate enough!
mov edx, [ecx+FSOUND_CHANNEL.leftvolume]
shl edx, 8
mov [ecx+FSOUND_CHANNEL.ramp_leftvolume], edx
mov edx, [ecx+FSOUND_CHANNEL.rightvolume]
shl edx, 8
mov [ecx+FSOUND_CHANNEL.ramp_rightvolume], edx
; is it 0 because ramp ended only? or both ended together??
; if sample ended together with ramp.. problems .. loop isnt handled
cmp [mix_count_old], eax ; ramp and output mode ended together
je DoOutputbuffEnd
; start again and continue rest of mix
mov [ecx+FSOUND_CHANNEL.mixpos], esi
mov [ecx+FSOUND_CHANNEL.mixposlo], ebp
mov eax, [mix_mixbuffend] ; find out how many OUTPUT samples left to mix
sub eax, edi
shr eax, 3 ; eax now holds # of samples left, go recalculate mix_count!!!
mov [mix_mixbuffptr], edi ; update the new mixbuffer pointer
cmp eax, 0 ; dont start again if nothing left
jne near CalculateLoopCount
DoOutputbuffEnd:
%endif
cmp dword [mix_endflag], FSOUND_OUTPUTBUFF_END
je near FinishUpChannel
;=============================================================================================
; SWITCH ON LOOP MODE TYPE
;=============================================================================================
mov ebx, [mix_sptr] ; load ebx with sample pointer
mov ecx, [mix_cptr] ; load ecx with sample pointer
mov dl, [ebx+FSOUND_SAMPLE.loopmode]
; check for normal loop
test dl, FSOUND_LOOP_NORMAL
jz CheckBidiLoop
mov eax, [ebx+FSOUND_SAMPLE.loopstart]
add eax, [ebx+FSOUND_SAMPLE.looplen]
rewindsample:
sub esi, [ebx+FSOUND_SAMPLE.looplen]
cmp esi, eax
jae rewindsample
mov [ecx+FSOUND_CHANNEL.mixpos], esi
mov [ecx+FSOUND_CHANNEL.mixposlo], ebp
mov eax, [mix_mixbuffend] ; find out how many samples left to mix for the output buffer
sub eax, edi
shr eax, 3 ; eax now holds # of samples left, go recalculate mix_count!!!
mov [mix_mixbuffptr], edi ; update the new mixbuffer pointer
cmp eax, 0
je near FinishUpChannel
jmp CalculateLoopCount
CheckBidiLoop:
test dl, FSOUND_LOOP_BIDI
jz near NoLoop
cmp dword [ecx+FSOUND_CHANNEL.speeddir], FSOUND_MIXDIR_FORWARDS
je BidiForward
BidiBackwards:
mov eax, [ebx+FSOUND_SAMPLE.loopstart]
dec eax
; mov edx, 0ffffff00h
mov edx, 0ffffffffh
sub edx, ebp
sbb eax, esi
mov esi, eax
mov ebp, edx ; esi:ebp = loopstart - mixpos
mov eax, [ebx+FSOUND_SAMPLE.loopstart]
mov edx, 0h
add ebp, edx
adc esi, eax ; esi:ebp += loopstart
mov dword [ecx+FSOUND_CHANNEL.speeddir], FSOUND_MIXDIR_FORWARDS
mov eax, [ebx+FSOUND_SAMPLE.loopstart]
add eax, [ebx+FSOUND_SAMPLE.looplen]
cmp esi, eax
jge BidiForward
jmp BidiFinish
BidiForward:
mov eax, [ebx+FSOUND_SAMPLE.loopstart]
add eax, [ebx+FSOUND_SAMPLE.looplen]
mov edx, 0h
sub edx, ebp
sbb eax, esi
mov esi, eax
mov ebp, edx ; esi:ebp = loopstart+looplen - mixpos
mov eax, [ebx+FSOUND_SAMPLE.loopstart]
add eax, [ebx+FSOUND_SAMPLE.looplen]
dec eax
; mov edx, 0ffffff00h
mov edx, 0ffffffffh
add ebp, edx
adc esi, eax
mov dword [ecx+FSOUND_CHANNEL.speeddir], FSOUND_MIXDIR_BACKWARDS
cmp esi, [ebx+FSOUND_SAMPLE.loopstart]
jl BidiBackwards
BidiFinish:
mov [ecx+FSOUND_CHANNEL.mixpos], esi
mov [ecx+FSOUND_CHANNEL.mixposlo], ebp
mov eax, [mix_mixbuffend] ; find out how many samples left to mix for the output buffer
sub eax, edi
shr eax, 3 ; eax now holds # of samples left, go recalculate mix_count!!!
mov [mix_mixbuffptr], edi ; update the new mixbuffer pointer
cmp eax, 0
je FinishUpChannel
jmp CalculateLoopCount
NoLoop:
xor ebp, ebp
xor esi, esi
mov [ecx+FSOUND_CHANNEL.sptr], esi ; clear the sample pointer out
; LEAVE INNER LOOP
FinishUpChannel:
mov ecx, [mix_cptr]
mov [ecx+FSOUND_CHANNEL.mixposlo], ebp
mov [ecx+FSOUND_CHANNEL.mixpos], esi ; reset mixpos based on esi for next time around
;===================================================================================================
; EXIT
;===================================================================================================
MixExit:
pop ebp ;= RESTORE EBP
ret
|
;
; GSX/GIOS parameter block
;
PUBLIC gios_pb
PUBLIC _gios_pb
PUBLIC gios_ctl
PUBLIC _gios_ctl
PUBLIC gios_intin
PUBLIC _gios_intin
PUBLIC gios_ptsin
PUBLIC _gios_ptsin
PUBLIC gios_intout
PUBLIC _gios_intout
PUBLIC gios_ptsout
PUBLIC _gios_ptsout
SECTION data_clib
; Parameter block
gios_pb:
_gios_pb:
defw gios_ctl ; Addr of control array
defw gios_intin ; Addr of integer input array
defw gios_ptsin ; Addr of pixel input array
defw gios_intout ; Addr of integer input array
defw gios_ptsout ; Addr of pixel input array
SECTION bss_clib
gios_ctl:
_gios_ctl:
defw 0 ; GSX function, 1-33
defw 0 ; number of pts in ptsin
defw 0 ; number of pts in ptsout
defw 0 ; number of values in intin
defw 0 ; number of values in intout
defw 0 ; for special uses
; limited to 200 bytes, e.g. printable text max. 100 characters
gios_intin:
_gios_intin:
defs 200
; limited to 160 bytes, e.g. max 40 corners in graphics objects
gios_ptsin:
_gios_ptsin:
defs 160
; should be max 12 words, thus 24 bytes
gios_ptsout:
_gios_ptsout:
defs 30
; should be max 65 words, thus 130 bytes
gios_intout:
_gios_intout:
defs 140
|
; A158575: a(n) = 32*n^2 + 1.
; 1,33,129,289,513,801,1153,1569,2049,2593,3201,3873,4609,5409,6273,7201,8193,9249,10369,11553,12801,14113,15489,16929,18433,20001,21633,23329,25089,26913,28801,30753,32769,34849,36993,39201,41473,43809,46209,48673,51201,53793,56449,59169,61953,64801,67713,70689,73729,76833,80001,83233,86529,89889,93313,96801,100353,103969,107649,111393,115201,119073,123009,127009,131073,135201,139393,143649,147969,152353,156801,161313,165889,170529,175233,180001,184833,189729,194689,199713,204801,209953,215169,220449,225793,231201,236673,242209,247809,253473,259201,264993,270849,276769,282753,288801,294913,301089,307329,313633,320001,326433,332929,339489,346113,352801,359553,366369,373249,380193,387201,394273,401409,408609,415873,423201,430593,438049,445569,453153,460801,468513,476289,484129,492033,500001,508033,516129,524289,532513,540801,549153,557569,566049,574593,583201,591873,600609,609409,618273,627201,636193,645249,654369,663553,672801,682113,691489,700929,710433,720001,729633,739329,749089,758913,768801,778753,788769,798849,808993,819201,829473,839809,850209,860673,871201,881793,892449,903169,913953,924801,935713,946689,957729,968833,980001,991233,1002529,1013889,1025313,1036801,1048353,1059969,1071649,1083393,1095201,1107073,1119009,1131009,1143073,1155201,1167393,1179649,1191969,1204353,1216801,1229313,1241889,1254529,1267233,1280001,1292833,1305729,1318689,1331713,1344801,1357953,1371169,1384449,1397793,1411201,1424673,1438209,1451809,1465473,1479201,1492993,1506849,1520769,1534753,1548801,1562913,1577089,1591329,1605633,1620001,1634433,1648929,1663489,1678113,1692801,1707553,1722369,1737249,1752193,1767201,1782273,1797409,1812609,1827873,1843201,1858593,1874049,1889569,1905153,1920801,1936513,1952289,1968129,1984033
mov $1,$0
pow $1,2
mul $1,32
add $1,1
|
# 操作系统启动时所需的指令以及字段
#
# 我们在 linker.ld 中将程序入口设置为了 _start,因此在这里我们将填充这个标签
# 它将会执行一些必要操作,然后跳转至我们用 rust 编写的入口函数
#
# 关于 RISC-V 下的汇编语言,可以参考 https://github.com/riscv/riscv-asm-manual/blob/master/riscv-asm.md
# %hi 表示取 [12,32) 位,%lo 表示取 [0,12) 位
.section .text.entry
.globl _start
# 目前 _start 的功能:将预留的栈空间写入 $sp,然后跳转至 rust_main
_start:
# 通过线性映射关系计算 boot_page_table 的物理页号
lui t0, %hi(boot_page_table)
li t1, 0xffffffff00000000
sub t0, t0, t1
srli t0, t0, 12
# 8 << 60 是 satp 中使用 Sv39 模式的记号
li t1, (8 << 60)
or t0, t0, t1
# 写入 satp 并更新 TLB
csrw satp, t0
sfence.vma
# 加载栈的虚拟地址
lui sp, %hi(boot_stack_top)
addi sp, sp, %lo(boot_stack_top)
# 跳转至 rust_main
# 这里同时伴随 hart 和 dtb_pa 两个指针的传入(是 OpenSBI 帮我们完成的)
lui t0, %hi(rust_main)
addi t0, t0, %lo(rust_main)
jr t0
# 回忆:bss 段是 ELF 文件中只记录长度,而全部初始化为 0 的一段内存空间
# 这里声明字段 .bss.stack 作为操作系统启动时的栈
.section .bss.stack
.global boot_stack
boot_stack:
# 16K 启动栈大小
.space 4096 * 16
.global boot_stack_top
boot_stack_top:
# 栈结尾
# 初始内核映射所用的页表
.section .data
.align 12
.global boot_page_table
boot_page_table:
# .8byte表示长度为8个字节的整数
.8byte 0
.8byte 0
# 第 2 项:0x8000_0000 -> 0x8000_0000,0xcf 表示 VRWXAD 均为 1
.8byte (0x80000 << 10) | 0xcf
.zero 505 * 8
# 第 508 项:0xffff_ffff_0000_0000 -> 0x0000_0000,0xcf 表示 VRWXAD 均为 1
.8byte (0x00000 << 10) | 0xcf
.8byte 0
# 第 510 项:0xffff_ffff_8000_0000 -> 0x8000_0000,0xcf 表示 VRWXAD 均为 1
.8byte (0x80000 << 10) | 0xcf
.8byte 0
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %rax
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0x1cf4d, %rbx
nop
nop
nop
xor $48491, %rdx
vmovups (%rbx), %ymm7
vextracti128 $0, %ymm7, %xmm7
vpextrq $0, %xmm7, %rbp
nop
nop
sub $4275, %rax
lea addresses_WT_ht+0x795d, %rsi
lea addresses_UC_ht+0x8a4d, %rdi
nop
nop
nop
nop
nop
add %r11, %r11
mov $112, %rcx
rep movsl
nop
nop
nop
nop
sub %rsi, %rsi
lea addresses_A_ht+0x122ed, %rdx
clflush (%rdx)
xor %rdi, %rdi
movl $0x61626364, (%rdx)
nop
nop
nop
sub %rbp, %rbp
lea addresses_D_ht+0x19627, %rsi
lea addresses_D_ht+0x1a54d, %rdi
nop
nop
nop
nop
nop
cmp $31851, %rbp
mov $8, %rcx
rep movsl
nop
nop
nop
nop
nop
cmp $30957, %rcx
lea addresses_D_ht+0xbd4d, %rsi
nop
nop
nop
nop
nop
add $25919, %rbp
movb (%rsi), %bl
nop
nop
nop
nop
nop
xor %r11, %r11
lea addresses_WC_ht+0x10c4d, %rsi
lea addresses_normal_ht+0x1e14d, %rdi
nop
nop
nop
nop
and %rdx, %rdx
mov $107, %rcx
rep movsw
nop
nop
nop
nop
add $53721, %rax
lea addresses_normal_ht+0x1e14d, %r11
nop
nop
nop
nop
dec %rsi
movb $0x61, (%r11)
nop
nop
nop
nop
lfence
lea addresses_UC_ht+0xd54d, %rax
clflush (%rax)
cmp %rdi, %rdi
vmovups (%rax), %ymm5
vextracti128 $0, %ymm5, %xmm5
vpextrq $0, %xmm5, %rbp
cmp %r11, %r11
lea addresses_WT_ht+0x8e29, %rbx
nop
nop
nop
nop
and %rsi, %rsi
mov $0x6162636465666768, %rcx
movq %rcx, %xmm4
movups %xmm4, (%rbx)
nop
nop
nop
nop
nop
mfence
lea addresses_normal_ht+0x1c45, %rsi
lea addresses_WT_ht+0x1615d, %rdi
nop
nop
nop
sub $9897, %r11
mov $104, %rcx
rep movsw
nop
nop
nop
cmp $56645, %r11
lea addresses_UC_ht+0xa4d, %rdi
nop
nop
nop
nop
add $51357, %rdx
mov (%rdi), %cx
nop
xor %rbx, %rbx
lea addresses_UC_ht+0x1ec8d, %rsi
nop
nop
nop
inc %rbp
movl $0x61626364, (%rsi)
nop
nop
xor $55980, %rbx
lea addresses_D_ht+0x234d, %rbp
nop
nop
nop
nop
and $54297, %rdi
mov $0x6162636465666768, %rcx
movq %rcx, (%rbp)
nop
nop
nop
nop
add %r11, %r11
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r8
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_D+0x18c51, %rcx
nop
nop
nop
nop
inc %r8
movb $0x51, (%rcx)
nop
nop
nop
cmp %r8, %r8
// REPMOV
lea addresses_RW+0x4d4d, %rsi
lea addresses_normal+0x1ad4c, %rdi
nop
nop
nop
cmp %r12, %r12
mov $123, %rcx
rep movsw
nop
nop
nop
sub $57227, %r12
// Store
lea addresses_UC+0x1b7d5, %r12
nop
nop
nop
nop
nop
and %rdi, %rdi
mov $0x5152535455565758, %rsi
movq %rsi, (%r12)
nop
nop
nop
inc %r12
// Store
lea addresses_A+0x5a1d, %r10
nop
nop
nop
inc %r12
mov $0x5152535455565758, %rcx
movq %rcx, %xmm1
movups %xmm1, (%r10)
nop
nop
add $45687, %rcx
// Store
lea addresses_UC+0x10af9, %r8
nop
nop
nop
nop
nop
xor %rdx, %rdx
movl $0x51525354, (%r8)
nop
nop
nop
nop
add $54652, %r12
// Store
lea addresses_normal+0x1044d, %rdi
inc %rcx
mov $0x5152535455565758, %rsi
movq %rsi, (%rdi)
nop
nop
nop
nop
nop
cmp %rdx, %rdx
// Store
lea addresses_WT+0x16d4d, %rdx
dec %r8
movl $0x51525354, (%rdx)
nop
nop
nop
nop
sub $63740, %rcx
// Faulty Load
lea addresses_WC+0x1054d, %rcx
nop
nop
and %rdi, %rdi
mov (%rcx), %r8w
lea oracles, %rdi
and $0xff, %r8
shlq $12, %r8
mov (%rdi,%r8,1), %r8
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r8
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 2}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_RW'}, 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_normal'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC', 'NT': False, 'AVXalign': True, 'size': 4, 'congruent': 1}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 10}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 6}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 3, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_UC_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 5}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_D_ht'}, 'dst': {'same': True, 'congruent': 11, 'type': 'addresses_D_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 11}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 8, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_normal_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 10}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 2}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 3, 'type': 'addresses_normal_ht'}, 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_WT_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 8}}
{'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
*/
|
; ===============================================================
; Jun 2007
; ===============================================================
;
; void *zx_cy2aaddr(uchar row)
;
; Character y coordinate to attribute address.
;
; ===============================================================
SECTION code_clib
SECTION code_arch
PUBLIC asm_zx_cy2aaddr
asm_zx_cy2aaddr:
; enter : hl = valid character y coordinate
;
; exit : hl = attribute address at row = y, x = 0
;
; uses : af, hl
ld a,l
rrca
rrca
rrca
ld h,a
and $e0
ld l,a
ld a,h
and $03
or $58
ld h,a
ret
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r14
push %r8
push %r9
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x1cf9a, %rsi
lea addresses_normal_ht+0x7d1a, %rdi
nop
nop
dec %r10
mov $11, %rcx
rep movsb
nop
nop
add $27694, %r14
lea addresses_WC_ht+0x8972, %rsi
lea addresses_A_ht+0x902a, %rdi
cmp $24983, %rbx
mov $38, %rcx
rep movsq
nop
nop
cmp %rsi, %rsi
lea addresses_WC_ht+0x1819a, %rsi
nop
nop
nop
and $3, %r9
movw $0x6162, (%rsi)
nop
nop
and $53269, %r9
lea addresses_normal_ht+0x1b79a, %r10
nop
add %rdi, %rdi
mov (%r10), %r9
xor %r9, %r9
lea addresses_UC_ht+0x1dada, %r10
nop
nop
cmp %rbx, %rbx
and $0xffffffffffffffc0, %r10
movaps (%r10), %xmm3
vpextrq $0, %xmm3, %rdi
nop
and $21725, %r10
lea addresses_WC_ht+0x1579a, %rsi
lea addresses_UC_ht+0x1ab9a, %rdi
nop
nop
nop
nop
add %r8, %r8
mov $11, %rcx
rep movsw
add %r10, %r10
lea addresses_UC_ht+0x2b9a, %rsi
lea addresses_WT_ht+0xb79a, %rdi
nop
nop
cmp %r8, %r8
mov $45, %rcx
rep movsw
sub %rbx, %rbx
lea addresses_D_ht+0x1e5a, %rsi
lea addresses_D_ht+0x99a, %rdi
nop
inc %r14
mov $40, %rcx
rep movsb
nop
nop
nop
sub %rdi, %rdi
lea addresses_WC_ht+0xbce0, %rcx
nop
xor %r9, %r9
movb (%rcx), %r14b
xor %r14, %r14
lea addresses_D_ht+0x1e6ba, %r14
nop
add %r8, %r8
mov $0x6162636465666768, %r10
movq %r10, %xmm4
movups %xmm4, (%r14)
nop
nop
nop
nop
nop
and %rdi, %rdi
lea addresses_A_ht+0x1346a, %rbx
nop
nop
and $25585, %r14
mov $0x6162636465666768, %rsi
movq %rsi, %xmm0
and $0xffffffffffffffc0, %rbx
vmovntdq %ymm0, (%rbx)
and %rsi, %rsi
lea addresses_D_ht+0x7b9a, %rsi
lea addresses_A_ht+0x1a9ca, %rdi
nop
nop
nop
cmp $56470, %rbx
mov $54, %rcx
rep movsq
nop
nop
nop
nop
nop
xor %r8, %r8
lea addresses_A_ht+0x16b9a, %r8
nop
nop
nop
inc %rsi
mov $0x6162636465666768, %rdi
movq %rdi, %xmm6
movups %xmm6, (%r8)
nop
nop
nop
nop
inc %r14
lea addresses_D_ht+0x4f1a, %rcx
nop
nop
nop
and $41313, %r14
mov $0x6162636465666768, %rdi
movq %rdi, %xmm3
movups %xmm3, (%rcx)
add %rsi, %rsi
lea addresses_A_ht+0xb517, %rsi
lea addresses_normal_ht+0x1101a, %rdi
nop
nop
and $4993, %r9
mov $25, %rcx
rep movsb
xor $4703, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r8
pop %r14
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r14
push %r9
push %rax
push %rbx
// Load
lea addresses_UC+0x1965a, %rax
nop
nop
nop
nop
nop
sub %r9, %r9
mov (%rax), %r14
nop
cmp %r12, %r12
// Faulty Load
lea addresses_WT+0x6f9a, %rbx
clflush (%rbx)
cmp %r11, %r11
movups (%rbx), %xmm6
vpextrq $0, %xmm6, %rax
lea oracles, %r10
and $0xff, %rax
shlq $12, %rax
mov (%r10,%rax,1), %rax
pop %rbx
pop %rax
pop %r9
pop %r14
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
{'src': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 10, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_normal_ht'}}
{'src': {'congruent': 3, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 3, 'same': False, 'type': 'addresses_A_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WC_ht'}}
{'src': {'congruent': 11, 'AVXalign': True, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 6, 'AVXalign': True, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 10, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_UC_ht'}}
{'src': {'congruent': 10, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 11, 'same': False, 'type': 'addresses_WT_ht'}}
{'src': {'congruent': 5, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_D_ht'}}
{'src': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': True, 'size': 32, 'NT': True, 'type': 'addresses_A_ht'}}
{'src': {'congruent': 10, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_A_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_A_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_D_ht'}}
{'src': {'congruent': 0, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_normal_ht'}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; A008767: a(n) = floor(n/7)*ceiling(n/7).
; 0,0,0,0,0,0,0,1,2,2,2,2,2,2,4,6,6,6,6,6,6,9,12,12,12,12,12,12,16,20,20,20,20,20,20,25,30,30,30,30,30,30,36,42,42,42,42,42,42,49,56,56,56,56,56,56,64,72,72,72,72,72,72,81,90,90,90,90,90,90,100,110,110,110,110,110,110,121,132,132,132,132,132,132,144,156,156,156,156,156,156,169,182,182,182,182,182,182,196,210,210,210,210,210,210,225,240,240,240,240,240,240,256,272,272,272,272,272,272,289,306,306,306,306,306,306,324,342,342,342,342,342,342,361,380,380,380,380,380,380,400,420,420,420,420,420,420,441,462,462,462,462,462,462,484,506,506,506,506,506,506,529,552,552,552,552,552,552,576,600,600,600,600,600,600,625,650,650,650,650,650,650,676,702,702,702,702,702,702,729,756,756,756,756,756,756,784,812,812,812,812,812,812,841,870,870,870,870,870,870,900,930,930,930,930,930,930,961,992,992,992,992,992,992,1024,1056,1056,1056,1056,1056,1056,1089,1122,1122,1122,1122,1122,1122,1156,1190,1190,1190,1190,1190,1190,1225,1260,1260,1260,1260
mov $2,$0
div $2,7
lpb $0
trn $0,7
add $1,$2
lpe
|
extern m7_ippsHMACGetTag_rmf:function
extern n8_ippsHMACGetTag_rmf:function
extern y8_ippsHMACGetTag_rmf:function
extern e9_ippsHMACGetTag_rmf:function
extern l9_ippsHMACGetTag_rmf:function
extern n0_ippsHMACGetTag_rmf:function
extern k0_ippsHMACGetTag_rmf:function
extern ippcpJumpIndexForMergedLibs
extern ippcpSafeInit:function
segment .data
align 8
dq .Lin_ippsHMACGetTag_rmf
.Larraddr_ippsHMACGetTag_rmf:
dq m7_ippsHMACGetTag_rmf
dq n8_ippsHMACGetTag_rmf
dq y8_ippsHMACGetTag_rmf
dq e9_ippsHMACGetTag_rmf
dq l9_ippsHMACGetTag_rmf
dq n0_ippsHMACGetTag_rmf
dq k0_ippsHMACGetTag_rmf
segment .text
global ippsHMACGetTag_rmf:function (ippsHMACGetTag_rmf.LEndippsHMACGetTag_rmf - ippsHMACGetTag_rmf)
.Lin_ippsHMACGetTag_rmf:
db 0xf3, 0x0f, 0x1e, 0xfa
call ippcpSafeInit wrt ..plt
align 16
ippsHMACGetTag_rmf:
db 0xf3, 0x0f, 0x1e, 0xfa
mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc]
movsxd rax, dword [rax]
lea r11, [rel .Larraddr_ippsHMACGetTag_rmf]
mov r11, qword [r11+rax*8]
jmp r11
.LEndippsHMACGetTag_rmf:
|
; A269609: Number of length-6 0..n arrays with no repeated value differing from the previous repeated value by one or less.
; 12,376,2878,12570,40288,105892,242226,499798,952180,1702128,2888422,4693426,7351368,11157340,16477018,23757102,33536476,46458088,63281550,84896458,112336432,146793876,189635458,242418310,306906948,385090912,479203126,591738978,725476120,883494988,1069200042,1286341726,1539039148,1831803480,2169562078,2557683322,3002002176,3508846468,4085063890,4738049718,5475775252,6306816976,7240386438,8286360850,9455314408,10758550332,12208133626,13816924558,15598612860,17567752648,19739798062,22131139626,24759141328,27642178420,30799675938,34252147942,38021237476,42129757248,46601731030,51462435778,56738444472,62457669676,68649407818,75344384190,82574798668,90374372152,98778393726,107823768538,117549066400,127994571108,139202330482,151216207126,164081929908,177847146160,192561474598,208276558962,225046122376,242926022428,261974306970,282251270638,303819512092,326743991976,351092091598,376933672330,404341135728,433389484372,464156383426,496722222918,531170180740,567586286368,606059485302,646681704226,689547916888,734756210700,782407854058,832607364382,885462576876,941084714008,999588455710,1061092010298
mov $1,12
mov $2,61
mov $5,$0
mov $6,$0
lpb $2
add $1,$5
sub $2,1
lpe
mov $3,$6
lpb $3
sub $3,1
add $4,$5
lpe
mov $2,118
mov $5,$4
lpb $2
add $1,$5
sub $2,1
lpe
mov $3,$6
mov $4,0
lpb $3
sub $3,1
add $4,$5
lpe
mov $2,116
mov $5,$4
lpb $2
add $1,$5
sub $2,1
lpe
mov $3,$6
mov $4,0
lpb $3
sub $3,1
add $4,$5
lpe
mov $2,56
mov $5,$4
lpb $2
add $1,$5
sub $2,1
lpe
mov $3,$6
mov $4,0
lpb $3
sub $3,1
add $4,$5
lpe
mov $2,12
mov $5,$4
lpb $2
add $1,$5
sub $2,1
lpe
mov $3,$6
mov $4,0
lpb $3
sub $3,1
add $4,$5
lpe
mov $2,1
mov $5,$4
lpb $2
add $1,$5
sub $2,1
lpe
mov $0,$1
|
; A169713: The function W_n(10) (see Borwein et al. reference for definition).
; 1,252,4653,31504,127905,384156,948157,2039808,3965409,7132060,12062061,19407312,29963713,44685564,64699965,91321216,126065217,170663868,227079469,297519120,384449121,490609372,619027773,773034624,956277025,1172733276,1426727277,1722942928,2066438529,2462661180,2917461181,3437106432,4028296833,4698178684,5454359085,6304920336,7258434337,8323976988,9511142589,10830058240,12291398241,13906398492,15686870893,17645217744,19794446145,22148182396,24720686397,27526866048,30582291649,33903210300
mov $8,$0
lpb $0
sub $0,1
add $1,5
lpe
mov $0,4
add $4,$1
sub $1,2
add $3,$1
lpb $3
add $2,5
sub $3,1
lpe
lpb $2
add $0,$4
sub $2,1
lpe
sub $0,3
mov $5,6
mov $9,$8
lpb $5
add $0,$9
sub $5,1
lpe
mov $6,$8
lpb $6
sub $6,1
add $7,$9
lpe
mov $6,$8
mov $9,$7
mov $7,0
lpb $6
sub $6,1
add $7,$9
lpe
mov $5,50
mov $9,$7
lpb $5
add $0,$9
sub $5,1
lpe
mov $6,$8
mov $7,0
lpb $6
sub $6,1
add $7,$9
lpe
mov $6,$8
mov $9,$7
mov $7,0
lpb $6
sub $6,1
add $7,$9
lpe
mov $5,120
mov $9,$7
lpb $5
add $0,$9
sub $5,1
lpe
|
; A176100: Even numbers that are not semiprimes, or, twice the nonprimes.
; Submitted by Jamie Morken(m3a)
; 0,2,8,12,16,18,20,24,28,30,32,36,40,42,44,48,50,52,54,56,60,64,66,68,70,72,76,78,80,84,88,90,92,96,98,100,102,104,108,110,112,114,116,120,124,126,128,130,132,136,138,140,144,148,150,152,154,156,160,162,164
mov $2,$0
mul $0,2
trn $2,2
sub $0,$2
trn $0,1
seq $0,122825 ; a(n) = n + number of previous prime terms, a(1) = 1.
sub $0,1
mul $0,2
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>request_key(type, description, callout_info, keyring) -> str
Invokes the syscall request_key.
See 'man 2 request_key' for more information.
Arguments:
type(char*): type
description(char*): description
callout_info(char*): callout_info
keyring(key_serial_t): keyring
Returns:
key_serial_t
</%docstring>
<%page args="type=0, description=0, callout_info=0, keyring=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = ['type', 'description', 'callout_info']
can_pushstr_array = []
argument_names = ['type', 'description', 'callout_info', 'keyring']
argument_values = [type, description, callout_info, keyring]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%r' % (name, arg))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_request_key']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* request_key(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)} |
db 0 ; species ID placeholder
db 65, 90, 50, 55, 85, 45
; hp atk def spd sat sdf
db GRASS, POISON ; type
db 120 ; catch rate
db 151 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F0 ; gender ratio
db 100 ; unknown 1
db 20 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/weepinbell/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_SLOW ; growth rate
dn EGG_PLANT, EGG_PLANT ; egg groups
; tm/hm learnset
tmhm CURSE, TOXIC, HIDDEN_POWER, SUNNY_DAY, SWEET_SCENT, SNORE, PROTECT, GIGA_DRAIN, ENDURE, FRUSTRATION, SOLARBEAM, RETURN, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SLUDGE_BOMB, REST, ATTRACT, CUT, FLASH
; end
|
; void __CALLEE__ *memcpy_callee(void *s1, void *s2, uint n)
; copy n chars from s2 to s1
; 11.1999 djm
SECTION code_clib
PUBLIC memcpy_callee
PUBLIC _memcpy_callee
PUBLIC ASMDISP_MEMCPY_CALLEE
.memcpy_callee
._memcpy_callee
pop hl
pop bc
pop de
ex (sp),hl
; enter : bc = uint n
; de = void *s2
; hl = void *s1
; exit : hl = void *s1
; uses : af, bc, de
.asmentry
ld a,b
or c
ret z
ex de,hl
push de
ldir
pop hl
ret
DEFC ASMDISP_MEMCPY_CALLEE = # asmentry - memcpy_callee
|
SECTION code_fp_math16
PUBLIC logf16
EXTERN _m16_logf
defc logf16 = _m16_logf
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC _logf16
EXTERN cm16_sdcc_log
defc _logf16 = cm16_sdcc_log
ENDIF
|
<%
from pwnlib.regsort import regsort
from pwnlib.constants import Constant, eval
from pwnlib.shellcraft import registers
from pwnlib.shellcraft.arm import mov
%>
<%page args="reg_context, stack_allowed = True"/>
<%docstring>
Sets multiple registers, taking any register dependencies into account
(i.e., given eax=1,ebx=eax, set ebx first).
Args:
reg_context (dict): Desired register context
stack_allowed (bool): Can the stack be used?
Example:
>>> print shellcraft.setregs({'r0':1, 'r2':'r3'}).rstrip()
mov r0, #1
mov r2, r3
>>> print shellcraft.setregs({'r0':'r1', 'r1':'r0', 'r2':'r3'}).rstrip()
mov r2, r3
eor r0, r0, r1 /* xchg r0, r1 */
eor r1, r0, r1
eor r0, r0, r1
</%docstring>
<%
reg_context = {k:v for k,v in reg_context.items() if v is not None}
sorted_regs = regsort(reg_context, registers.arm)
%>
% if not sorted_regs:
/* setregs noop */
% else:
% for how, dst, src in regsort(reg_context, registers.arm):
% if how == 'xchg':
eor ${dst}, ${dst}, ${src} /* xchg ${dst}, ${src} */
eor ${src}, ${dst}, ${src}
eor ${dst}, ${dst}, ${src}
% else:
${mov(dst, src)}
% endif
% endfor
% endif
|
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2020 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "CufflinksSupportTask.h"
#include <QCoreApplication>
#include <QDir>
#include <U2Core/AnnotationTableObject.h>
#include <U2Core/AppContext.h>
#include <U2Core/AppSettings.h>
#include <U2Core/AssemblyObject.h>
#include <U2Core/BaseDocumentFormats.h>
#include <U2Core/Counter.h>
#include <U2Core/GUrl.h>
#include <U2Core/GUrlUtils.h>
#include <U2Core/IOAdapter.h>
#include <U2Core/IOAdapterUtils.h>
#include <U2Core/L10n.h>
#include <U2Core/LoadDocumentTask.h>
#include <U2Core/U2OpStatusUtils.h>
#include <U2Core/U2SafePoints.h>
#include <U2Core/UserApplicationsSettings.h>
#include <U2Formats/DifferentialFormat.h>
#include <U2Formats/FpkmTrackingFormat.h>
#include <U2Formats/GTFFormat.h>
#include "../ExternalToolSupportL10N.h"
#include "CufflinksSupport.h"
#include "tophat/TopHatSettings.h"
namespace U2 {
const QString CufflinksSupportTask::outSubDirBaseName("cufflinks_out");
CufflinksSupportTask::CufflinksSupportTask(const CufflinksSettings &_settings)
: ExternalToolSupportTask(tr("Running Cufflinks task"), TaskFlags_NR_FOSE_COSC),
settings(_settings),
tmpDoc(NULL),
convertAssToSamTask(NULL),
cufflinksExtToolTask(NULL),
loadIsoformAnnotationsTask(NULL) {
GCOUNTER(cvar, tvar, "NGS:CufflinksTask");
}
CufflinksSupportTask::~CufflinksSupportTask() {
delete tmpDoc;
}
QString CufflinksSupportTask::initTmpDir() {
// Add a new subdirectory for temporary files
QString tmpDirName = "Cufflinks_" + QString::number(this->getTaskId()) + "_" +
QDate::currentDate().toString("dd.MM.yyyy") + "_" +
QTime::currentTime().toString("hh.mm.ss.zzz") + "_" +
QString::number(QCoreApplication::applicationPid()) + "/";
QString cufflinksTmpDirName =
AppContext::getAppSettings()->getUserAppsSettings()->getCurrentProcessTemporaryDirPath(CufflinksSupport::CUFFLINKS_TMP_DIR);
QDir tmpDir(cufflinksTmpDirName + "/" + tmpDirName);
if (tmpDir.exists()) {
foreach (const QString &file, tmpDir.entryList()) {
tmpDir.remove(file);
}
if (!tmpDir.rmdir(tmpDir.absolutePath())) {
stateInfo.setError(ExternalToolSupportL10N::errorRemovingTmpSubdir(tmpDir.absolutePath()));
return "";
}
}
if (!tmpDir.mkpath(tmpDir.absolutePath())) {
stateInfo.setError(ExternalToolSupportL10N::errorCreatingTmpSubrir(tmpDir.absolutePath()));
return "";
}
return tmpDir.absolutePath();
}
void CufflinksSupportTask::prepare() {
settings.outDir = GUrlUtils::createDirectory(
settings.outDir + "/" + outSubDirBaseName,
"_",
stateInfo);
CHECK_OP(stateInfo, );
workingDirectory = initTmpDir();
CHECK_OP(stateInfo, );
if (settings.fromFile) {
cufflinksExtToolTask = runCufflinks();
addSubTask(cufflinksExtToolTask);
return;
}
settings.url = workingDirectory + "/tmp.sam";
DocumentFormat *docFormat = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::SAM);
tmpDoc = docFormat->createNewLoadedDocument(IOAdapterUtils::get(BaseIOAdapters::LOCAL_FILE), GUrl(settings.url), stateInfo);
CHECK_OP(stateInfo, );
QScopedPointer<AssemblyObject> assObj(
Workflow::StorageUtils::getAssemblyObject(settings.storage, settings.assemblyId));
if (assObj.isNull()) {
stateInfo.setError(tr("Unable to get an assembly object."));
return;
}
convertAssToSamTask = new ConvertAssemblyToSamTask(assObj->getEntityRef(), settings.url);
addSubTask(convertAssToSamTask);
}
ExternalToolRunTask *CufflinksSupportTask::runCufflinks() {
// Init the arguments list
QStringList arguments;
arguments << "--no-update-check";
arguments << "-p" << QString::number(TopHatSettings::getThreadsCount());
arguments << "--output-dir" << settings.outDir;
if (!settings.referenceAnnotation.isEmpty()) {
arguments << "-G" << settings.referenceAnnotation;
}
if (!settings.rabtAnnotation.isEmpty()) {
arguments << "-g" << settings.rabtAnnotation;
}
arguments << "--library-type" << settings.libraryType.getLibraryTypeAsStr();
if (!settings.maskFile.isEmpty()) {
arguments << "-M" << settings.maskFile;
}
if (true == settings.multiReadCorrect) {
arguments << "--multi-read-correct";
}
arguments << "--min-isoform-fraction" << QString::number(settings.minIsoformFraction);
if (!settings.fragBiasCorrect.isEmpty()) {
arguments << "--frag-bias-correct" << settings.fragBiasCorrect;
}
arguments << "--pre-mrna-fraction" << QString::number(settings.preMrnaFraction);
arguments << settings.url;
// Create the Cufflinks task
ExternalToolRunTask *runTask = new ExternalToolRunTask(CufflinksSupport::ET_CUFFLINKS_ID,
arguments,
new ExternalToolLogParser(),
workingDirectory);
setListenerForTask(runTask);
return runTask;
}
QList<Task *> CufflinksSupportTask::onSubTaskFinished(Task *subTask) {
QList<Task *> result;
if (subTask->hasError()) {
stateInfo.setError(subTask->getError());
return result;
}
if (hasError() || isCanceled()) {
return result;
}
if (subTask == convertAssToSamTask) {
cufflinksExtToolTask = runCufflinks();
result.append(cufflinksExtToolTask);
}
else if (subTask == cufflinksExtToolTask) {
ExternalToolSupportUtils::appendExistingFile(settings.outDir + "/transcripts.gtf", outputFiles);
ExternalToolSupportUtils::appendExistingFile(settings.outDir + "/isoforms.fpkm_tracking", outputFiles);
ExternalToolSupportUtils::appendExistingFile(settings.outDir + "/genes.fpkm_tracking", outputFiles);
initLoadIsoformAnnotationsTask("transcripts.gtf", CufflinksOutputGtf);
CHECK(NULL != loadIsoformAnnotationsTask, result);
result << loadIsoformAnnotationsTask;
}
else if (subTask == loadIsoformAnnotationsTask) {
QScopedPointer<Document> doc(loadIsoformAnnotationsTask->takeDocument());
SAFE_POINT_EXT(NULL != doc, setError(L10N::nullPointerError("document with annotations")), result);
doc->setDocumentOwnsDbiResources(false);
foreach (GObject *object, doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE)) {
doc->removeObject(object, DocumentObjectRemovalMode_Release);
isoformLevelAnnotationTables << qobject_cast<AnnotationTableObject *>(object);
}
}
return result;
}
DocumentFormatId CufflinksSupportTask::getFormatId(CufflinksOutputFormat format) {
switch (format) {
case CufflinksOutputFpkm:
return BaseDocumentFormats::FPKM_TRACKING_FORMAT;
case CufflinksOutputGtf:
return BaseDocumentFormats::GTF;
default:
FAIL("Internal error: unexpected format of the Cufflinks output!", "");
}
}
void CufflinksSupportTask::initLoadIsoformAnnotationsTask(const QString &fileName, CufflinksOutputFormat format) {
const QString filePath = settings.outDir + "/" + fileName;
IOAdapterFactory *iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE);
SAFE_POINT_EXT(NULL != iof, setError(tr("An internal error occurred during getting annotations from a %1 output file!").arg(CufflinksSupport::ET_CUFFLINKS)), );
QVariantMap hints;
hints[DocumentFormat::DBI_REF_HINT] = QVariant::fromValue(settings.storage->getDbiRef());
loadIsoformAnnotationsTask = new LoadDocumentTask(getFormatId(format), filePath, iof, hints);
}
Task::ReportResult CufflinksSupportTask::report() {
if (settings.url.isEmpty()) {
return ReportResult_Finished;
}
GUrlUtils::removeDir(workingDirectory, stateInfo);
return ReportResult_Finished;
}
QList<AnnotationTableObject *> CufflinksSupportTask::getIsoformAnnotationTables() const {
return isoformLevelAnnotationTables;
}
const QStringList &CufflinksSupportTask::getOutputFiles() const {
return outputFiles;
}
} // namespace U2
|
Route22GateScript:
call EnableAutoTextBoxDrawing
ld hl, Route22GateScriptPointers
ld a, [wRoute22GateCurScript]
call CallFunctionInTable
ld a, [wYCoord]
cp $4
ld a, ROUTE_23
jr c, .asm_1e69a
ld a, ROUTE_22
.asm_1e69a
ld [wLastMap], a
ret
Route22GateScriptPointers:
dw Route22GateScript0
dw Route22GateScript1
dw Route22GateScript2
Route22GateScript0:
ld hl, Route22GateScriptCoords
call ArePlayerCoordsInArray
ret nc
xor a
ld [hJoyHeld], a
ld a, $1
ld [hSpriteIndexOrTextID], a
jp DisplayTextID
Route22GateScriptCoords:
db 2,4
db 2,5
db $ff
Route22GateScript_1e6ba:
ld a, $1
ld [wSimulatedJoypadStatesIndex], a
ld a, D_DOWN
ld [wSimulatedJoypadStatesEnd], a
ld [wSpriteStateData1 + 9], a
ld [wJoyIgnore], a
jp StartSimulatingJoypadStates
Route22GateScript1:
ld a, [wSimulatedJoypadStatesIndex]
and a
ret nz
xor a
ld [wJoyIgnore], a
call Delay3
ld a, $0
ld [wRoute22GateCurScript], a
Route22GateScript2:
ret
Route22GateTextPointers:
dw Route22GateText1
Route22GateText1:
TX_ASM
ld a, [wObtainedBadges]
bit 0, a
jr nz, .asm_1e6f6
ld hl, Route22GateText_1e704
call PrintText
call Route22GateScript_1e6ba
ld a, $1
jr .asm_1e6fe
.asm_1e6f6
ld hl, Route22GateText_1e71a
call PrintText
ld a, $2
.asm_1e6fe
ld [wRoute22GateCurScript], a
jp TextScriptEnd
Route22GateText_1e704:
TX_FAR _Route22GateText_1e704
TX_ASM
ld a, SFX_DENIED
call PlaySoundWaitForCurrent
call WaitForSoundToFinish
ld hl, Route22GateText_1e715
ret
Route22GateText_1e715:
TX_FAR _Route22GateText_1e715
db "@"
Route22GateText_1e71a:
TX_FAR _Route22GateText_1e71a
TX_SFX_ITEM_1
db "@"
|
(lp1
(ccopy_reg
_reconstructor
p2
(cpygments.token
_TokenType
p3
c__builtin__
tuple
p4
(S'Comment'
p5
S'Single'
p6
ttRp7
(dp8
S'subtypes'
p9
c__builtin__
set
p10
((ltRp11
sS'parent'
p12
g2
(g3
g4
(g5
ttRp13
(dp14
g12
g2
(g3
g4
(ttRp15
(dp16
g5
g13
sS'Name'
p17
g2
(g3
g4
(g17
ttRp18
(dp19
S'Function'
p20
g2
(g3
g4
(g17
g20
ttRp21
(dp22
g9
g10
((ltRp23
sg12
g18
sbsS'Exception'
p24
g2
(g3
g4
(g17
g24
ttRp25
(dp26
g9
g10
((ltRp27
sg12
g18
sbsS'Tag'
p28
g2
(g3
g4
(g17
g28
ttRp29
(dp30
g9
g10
((ltRp31
sg12
g18
sbsS'Constant'
p32
g2
(g3
g4
(g17
g32
ttRp33
(dp34
g9
g10
((ltRp35
sg12
g18
sbsg12
g15
sS'Pseudo'
p36
g2
(g3
g4
(g17
g36
ttRp37
(dp38
g9
g10
((ltRp39
sg12
g18
sbsS'Attribute'
p40
g2
(g3
g4
(g17
g40
ttRp41
(dp42
g9
g10
((ltRp43
sg12
g18
sbsS'Label'
p44
g2
(g3
g4
(g17
g44
ttRp45
(dp46
g9
g10
((ltRp47
sg12
g18
sbsS'Blubb'
p48
g2
(g3
g4
(g17
g48
ttRp49
(dp50
g9
g10
((ltRp51
sg12
g18
sbsS'Entity'
p52
g2
(g3
g4
(g17
g52
ttRp53
(dp54
g9
g10
((ltRp55
sg12
g18
sbsS'Builtin'
p56
g2
(g3
g4
(g17
g56
ttRp57
(dp58
g9
g10
((lp59
g2
(g3
g4
(g17
g56
g36
ttRp60
(dp61
g9
g10
((ltRp62
sg12
g57
sbatRp63
sg36
g60
sg12
g18
sbsS'Other'
p64
g2
(g3
g4
(g17
g64
ttRp65
(dp66
g9
g10
((ltRp67
sg12
g18
sbsS'Identifier'
p68
g2
(g3
g4
(g17
g68
ttRp69
(dp70
g9
g10
((ltRp71
sg12
g18
sbsS'Variable'
p72
g2
(g3
g4
(g17
g72
ttRp73
(dp74
g12
g18
sS'Global'
p75
g2
(g3
g4
(g17
g72
g75
ttRp76
(dp77
g9
g10
((ltRp78
sg12
g73
sbsS'Instance'
p79
g2
(g3
g4
(g17
g72
g79
ttRp80
(dp81
g9
g10
((ltRp82
sg12
g73
sbsS'Anonymous'
p83
g2
(g3
g4
(g17
g72
g83
ttRp84
(dp85
g9
g10
((ltRp86
sg12
g73
sbsg9
g10
((lp87
g84
ag80
ag76
ag2
(g3
g4
(g17
g72
S'Class'
p88
ttRp89
(dp90
g9
g10
((ltRp91
sg12
g73
sbatRp92
sg88
g89
sbsg9
g10
((lp93
g2
(g3
g4
(g17
S'Decorator'
p94
ttRp95
(dp96
g9
g10
((ltRp97
sg12
g18
sbag41
ag33
ag37
ag2
(g3
g4
(g17
S'Namespace'
p98
ttRp99
(dp100
g9
g10
((ltRp101
sg12
g18
sbag69
ag57
ag73
ag65
ag49
ag53
ag21
ag2
(g3
g4
(g17
S'Property'
p102
ttRp103
(dp104
g9
g10
((ltRp105
sg12
g18
sbag45
ag29
ag25
ag2
(g3
g4
(g17
g88
ttRp106
(dp107
g9
g10
((ltRp108
sg12
g18
sbatRp109
sg102
g103
sg88
g106
sg94
g95
sg98
g99
sbsS'Keyword'
p110
g2
(g3
g4
(g110
ttRp111
(dp112
S'Pervasive'
p113
g2
(g3
g4
(g110
g113
ttRp114
(dp115
g9
g10
((ltRp116
sg12
g111
sbsg32
g2
(g3
g4
(g110
g32
ttRp117
(dp118
g9
g10
((ltRp119
sg12
g111
sbsg12
g15
sg98
g2
(g3
g4
(g110
g98
ttRp120
(dp121
g9
g10
((ltRp122
sg12
g111
sbsg36
g2
(g3
g4
(g110
g36
ttRp123
(dp124
g9
g10
((ltRp125
sg12
g111
sbsS'Reserved'
p126
g2
(g3
g4
(g110
g126
ttRp127
(dp128
g9
g10
((ltRp129
sg12
g111
sbsS'Declaration'
p130
g2
(g3
g4
(g110
g130
ttRp131
(dp132
g9
g10
((ltRp133
sg12
g111
sbsg72
g2
(g3
g4
(g110
g72
ttRp134
(dp135
g9
g10
((ltRp136
sg12
g111
sbsg9
g10
((lp137
g117
ag127
ag2
(g3
g4
(g110
S'Type'
p138
ttRp139
(dp140
g9
g10
((ltRp141
sg12
g111
sbag114
ag131
ag134
ag120
ag123
atRp142
sg138
g139
sbsS'Generic'
p143
g2
(g3
g4
(g143
ttRp144
(dp145
S'Prompt'
p146
g2
(g3
g4
(g143
g146
ttRp147
(dp148
g9
g10
((ltRp149
sg12
g144
sbsg12
g15
sS'Deleted'
p150
g2
(g3
g4
(g143
g150
ttRp151
(dp152
g9
g10
((ltRp153
sg12
g144
sbsS'Traceback'
p154
g2
(g3
g4
(g143
g154
ttRp155
(dp156
g9
g10
((ltRp157
sg12
g144
sbsS'Emph'
p158
g2
(g3
g4
(g143
g158
ttRp159
(dp160
g9
g10
((ltRp161
sg12
g144
sbsS'Output'
p162
g2
(g3
g4
(g143
g162
ttRp163
(dp164
g9
g10
((ltRp165
sg12
g144
sbsS'Subheading'
p166
g2
(g3
g4
(g143
g166
ttRp167
(dp168
g9
g10
((ltRp169
sg12
g144
sbsS'Error'
p170
g2
(g3
g4
(g143
g170
ttRp171
(dp172
g9
g10
((ltRp173
sg12
g144
sbsg9
g10
((lp174
g163
ag159
ag171
ag167
ag155
ag151
ag2
(g3
g4
(g143
S'Heading'
p175
ttRp176
(dp177
g9
g10
((ltRp178
sg12
g144
sbag2
(g3
g4
(g143
S'Inserted'
p179
ttRp180
(dp181
g9
g10
((ltRp182
sg12
g144
sbag2
(g3
g4
(g143
S'Strong'
p183
ttRp184
(dp185
g9
g10
((ltRp186
sg12
g144
sbag147
atRp187
sg183
g184
sg179
g180
sg175
g176
sbsS'Text'
p188
g2
(g3
g4
(g188
ttRp189
(dp190
g9
g10
((lp191
g2
(g3
g4
(g188
S'Symbol'
p192
ttRp193
(dp194
g9
g10
((ltRp195
sg12
g189
sbag2
(g3
g4
(g188
S'Whitespace'
p196
ttRp197
(dp198
g9
g10
((ltRp199
sg12
g189
sbatRp200
sg192
g193
sg196
g197
sg12
g15
sbsS'Punctuation'
p201
g2
(g3
g4
(g201
ttRp202
(dp203
g9
g10
((lp204
g2
(g3
g4
(g201
S'Indicator'
p205
ttRp206
(dp207
g9
g10
((ltRp208
sg12
g202
sbatRp209
sg205
g206
sg12
g15
sbsS'Token'
p210
g15
sS'Number'
p211
g2
(g3
g4
(S'Literal'
p212
g211
ttRp213
(dp214
S'Bin'
p215
g2
(g3
g4
(g212
g211
g215
ttRp216
(dp217
g9
g10
((ltRp218
sg12
g213
sbsS'Binary'
p219
g2
(g3
g4
(g212
g211
g219
ttRp220
(dp221
g9
g10
((ltRp222
sg12
g213
sbsg12
g2
(g3
g4
(g212
ttRp223
(dp224
S'String'
p225
g2
(g3
g4
(g212
g225
ttRp226
(dp227
S'Regex'
p228
g2
(g3
g4
(g212
g225
g228
ttRp229
(dp230
g9
g10
((ltRp231
sg12
g226
sbsS'Interpol'
p232
g2
(g3
g4
(g212
g225
g232
ttRp233
(dp234
g9
g10
((ltRp235
sg12
g226
sbsS'Regexp'
p236
g2
(g3
g4
(g212
g225
g236
ttRp237
(dp238
g9
g10
((ltRp239
sg12
g226
sbsg12
g223
sS'Heredoc'
p240
g2
(g3
g4
(g212
g225
g240
ttRp241
(dp242
g9
g10
((ltRp243
sg12
g226
sbsS'Double'
p244
g2
(g3
g4
(g212
g225
g244
ttRp245
(dp246
g9
g10
((ltRp247
sg12
g226
sbsg192
g2
(g3
g4
(g212
g225
g192
ttRp248
(dp249
g9
g10
((ltRp250
sg12
g226
sbsS'Escape'
p251
g2
(g3
g4
(g212
g225
g251
ttRp252
(dp253
g9
g10
((ltRp254
sg12
g226
sbsS'Character'
p255
g2
(g3
g4
(g212
g225
g255
ttRp256
(dp257
g9
g10
((ltRp258
sg12
g226
sbsS'Interp'
p259
g2
(g3
g4
(g212
g225
g259
ttRp260
(dp261
g9
g10
((ltRp262
sg12
g226
sbsS'Backtick'
p263
g2
(g3
g4
(g212
g225
g263
ttRp264
(dp265
g9
g10
((ltRp266
sg12
g226
sbsS'Char'
p267
g2
(g3
g4
(g212
g225
g267
ttRp268
(dp269
g9
g10
((ltRp270
sg12
g226
sbsg6
g2
(g3
g4
(g212
g225
g6
ttRp271
(dp272
g9
g10
((ltRp273
sg12
g226
sbsg64
g2
(g3
g4
(g212
g225
g64
ttRp274
(dp275
g9
g10
((ltRp276
sg12
g226
sbsS'Doc'
p277
g2
(g3
g4
(g212
g225
g277
ttRp278
(dp279
g9
g10
((ltRp280
sg12
g226
sbsg9
g10
((lp281
g274
ag2
(g3
g4
(g212
g225
S'Atom'
p282
ttRp283
(dp284
g9
g10
((ltRp285
sg12
g226
sbag245
ag268
ag260
ag278
ag241
ag264
ag233
ag248
ag237
ag229
ag271
ag256
ag252
atRp286
sg282
g283
sbsg12
g15
sg211
g213
sS'Scalar'
p287
g2
(g3
g4
(g212
g287
ttRp288
(dp289
g9
g10
((lp290
g2
(g3
g4
(g212
g287
S'Plain'
p291
ttRp292
(dp293
g9
g10
((ltRp294
sg12
g288
sbatRp295
sg12
g223
sg291
g292
sbsg64
g2
(g3
g4
(g212
g64
ttRp296
(dp297
g9
g10
((ltRp298
sg12
g223
sbsS'Date'
p299
g2
(g3
g4
(g212
g299
ttRp300
(dp301
g9
g10
((ltRp302
sg12
g223
sbsg9
g10
((lp303
g300
ag226
ag296
ag213
ag288
atRp304
sbsS'Decimal'
p305
g2
(g3
g4
(g212
g211
g305
ttRp306
(dp307
g9
g10
((ltRp308
sg12
g213
sbsS'Float'
p309
g2
(g3
g4
(g212
g211
g309
ttRp310
(dp311
g9
g10
((ltRp312
sg12
g213
sbsS'Hex'
p313
g2
(g3
g4
(g212
g211
g313
ttRp314
(dp315
g9
g10
((ltRp316
sg12
g213
sbsS'Integer'
p317
g2
(g3
g4
(g212
g211
g317
ttRp318
(dp319
g9
g10
((lp320
g2
(g3
g4
(g212
g211
g317
S'Long'
p321
ttRp322
(dp323
g9
g10
((ltRp324
sg12
g318
sbatRp325
sg321
g322
sg12
g213
sbsS'Octal'
p326
g2
(g3
g4
(g212
g211
g326
ttRp327
(dp328
g9
g10
((ltRp329
sg12
g213
sbsg9
g10
((lp330
g216
ag220
ag327
ag306
ag2
(g3
g4
(g212
g211
S'Oct'
p331
ttRp332
(dp333
g9
g10
((ltRp334
sg12
g213
sbag318
ag310
ag314
atRp335
sg331
g332
sbsg212
g223
sg64
g2
(g3
g4
(g64
ttRp336
(dp337
g9
g10
((ltRp338
sg12
g15
sbsg170
g2
(g3
g4
(g170
ttRp339
(dp340
g9
g10
((ltRp341
sg12
g15
sbsS'Operator'
p342
g2
(g3
g4
(g342
ttRp343
(dp344
g9
g10
((lp345
g2
(g3
g4
(g342
S'Word'
p346
ttRp347
(dp348
g9
g10
((ltRp349
sg12
g343
sbatRp350
sg346
g347
sg12
g15
sbsg9
g10
((lp351
g13
ag339
ag144
ag189
ag18
ag202
ag111
ag223
ag343
ag336
atRp352
sg225
g226
sbsS'Preproc'
p353
g2
(g3
g4
(g5
g353
ttRp354
(dp355
g9
g10
((ltRp356
sg12
g13
sbsg6
g7
sS'Multiline'
p357
g2
(g3
g4
(g5
g357
ttRp358
(dp359
g9
g10
((ltRp360
sg12
g13
sbsg9
g10
((lp361
g2
(g3
g4
(g5
S'Special'
p362
ttRp363
(dp364
g9
g10
((ltRp365
sg12
g13
sbag354
ag7
ag358
atRp366
sg362
g363
sbsbV; test source file for assembling to NetBSD/FreeBSD a.out shared library
p367
tp368
a(g189
V\u000a
tp369
a(g7
V; build with:
p370
tp371
a(g189
V\u000a
tp372
a(g7
V; nasm -f aoutb aoutso.asm
p373
tp374
a(g189
V\u000a
tp375
a(g7
V; ld -Bshareable -o aoutso.so aoutso.o
p376
tp377
a(g189
V\u000a
tp378
a(g7
V; test with:
p379
tp380
a(g189
V\u000a
tp381
a(g7
V; cc -o aoutso aouttest.c aoutso.so
p382
tp383
a(g189
V\u000a
tp384
a(g7
V; ./aoutso
p385
tp386
a(g189
V\u000a
tp387
a(g189
V\u000a
tp388
a(g7
V; This file should test the following:
p389
tp390
a(g189
V\u000a
tp391
a(g7
V; [1] Define and export a global text-section symbol
p392
tp393
a(g189
V\u000a
tp394
a(g7
V; [2] Define and export a global data-section symbol
p395
tp396
a(g189
V\u000a
tp397
a(g7
V; [3] Define and export a global BSS-section symbol
p398
tp399
a(g189
V\u000a
tp400
a(g7
V; [4] Define a non-global text-section symbol
p401
tp402
a(g189
V\u000a
tp403
a(g7
V; [5] Define a non-global data-section symbol
p404
tp405
a(g189
V\u000a
tp406
a(g7
V; [6] Define a non-global BSS-section symbol
p407
tp408
a(g189
V\u000a
tp409
a(g7
V; [7] Define a COMMON symbol
p410
tp411
a(g189
V\u000a
tp412
a(g7
V; [8] Define a NASM local label
p413
tp414
a(g189
V\u000a
tp415
a(g7
V; [9] Reference a NASM local label
p416
tp417
a(g189
V\u000a
tp418
a(g7
V; [10] Import an external symbol
p419
tp420
a(g189
V\u000a
tp421
a(g7
V; [11] Make a PC-relative call to an external symbol
p422
tp423
a(g189
V\u000a
tp424
a(g7
V; [12] Reference a text-section symbol in the text section
p425
tp426
a(g189
V\u000a
tp427
a(g7
V; [13] Reference a data-section symbol in the text section
p428
tp429
a(g189
V\u000a
tp430
a(g7
V; [14] Reference a BSS-section symbol in the text section
p431
tp432
a(g189
V\u000a
tp433
a(g7
V; [15] Reference a text-section symbol in the data section
p434
tp435
a(g189
V\u000a
tp436
a(g7
V; [16] Reference a data-section symbol in the data section
p437
tp438
a(g189
V\u000a
tp439
a(g7
V; [17] Reference a BSS-section symbol in the data section
p440
tp441
a(g189
V\u000a
tp442
a(g189
V\u000a
tp443
a(g189
V
p444
tp445
a(g111
VBITS
p446
tp447
a(g189
V
tp448
a(g318
V32
p449
tp450
a(g189
V\u000a
tp451
a(g189
V
p452
tp453
a(g111
VEXTERN
p454
tp455
a(g189
V
tp456
a(g73
V__GLOBAL_OFFSET_TABLE_
p457
tp458
a(g189
V\u000a
tp459
a(g189
V
p460
tp461
a(g111
VGLOBAL
p462
tp463
a(g189
V
tp464
a(g73
V_lrotate
p465
tp466
a(g202
V:
tp467
a(g73
Vfunction
p468
tp469
a(g189
V
tp470
a(g7
V; [1]
p471
tp472
a(g189
V\u000a
tp473
a(g189
V
p474
tp475
a(g111
VGLOBAL
p476
tp477
a(g189
V
tp478
a(g73
V_greet
p479
tp480
a(g202
V:
tp481
a(g73
Vfunction
p482
tp483
a(g189
V
tp484
a(g7
V; [1]
p485
tp486
a(g189
V\u000a
tp487
a(g189
V
p488
tp489
a(g111
VGLOBAL
p490
tp491
a(g189
V
tp492
a(g73
V_asmstr
p493
tp494
a(g202
V:
tp495
a(g73
Vdata
p496
tp497
a(g189
V
tp498
a(g73
V_asmstr.end
p499
tp500
a(g343
V-
tp501
a(g73
V_asmstr
p502
tp503
a(g189
V
tp504
a(g7
V; [2]
p505
tp506
a(g189
V\u000a
tp507
a(g189
V
p508
tp509
a(g111
VGLOBAL
p510
tp511
a(g189
V
tp512
a(g73
V_textptr
p513
tp514
a(g202
V:
tp515
a(g73
Vdata
p516
tp517
a(g189
V
tp518
a(g318
V4
tp519
a(g189
V
tp520
a(g7
V; [2]
p521
tp522
a(g189
V\u000a
tp523
a(g189
V
p524
tp525
a(g111
VGLOBAL
p526
tp527
a(g189
V
tp528
a(g73
V_selfptr
p529
tp530
a(g202
V:
tp531
a(g73
Vdata
p532
tp533
a(g189
V
tp534
a(g318
V4
tp535
a(g189
V
tp536
a(g7
V; [2]
p537
tp538
a(g189
V\u000a
tp539
a(g189
V
p540
tp541
a(g111
VGLOBAL
p542
tp543
a(g189
V
tp544
a(g73
V_integer
p545
tp546
a(g202
V:
tp547
a(g73
Vdata
p548
tp549
a(g189
V
tp550
a(g318
V4
tp551
a(g189
V
tp552
a(g7
V; [3]
p553
tp554
a(g189
V\u000a
tp555
a(g189
V
p556
tp557
a(g111
VEXTERN
p558
tp559
a(g189
V
tp560
a(g73
V_printf
p561
tp562
a(g189
V
tp563
a(g7
V; [10]
p564
tp565
a(g189
V\u000a
tp566
a(g189
V
p567
tp568
a(g111
VCOMMON
p569
tp570
a(g189
V
tp571
a(g73
V_commvar
p572
tp573
a(g189
V
tp574
a(g318
V4
tp575
a(g189
V
tp576
a(g7
V; [7]
p577
tp578
a(g189
V\u000a\u000a
p579
tp580
a(g189
V
p581
tp582
a(g111
VSECTION
p583
tp584
a(g189
V
tp585
a(g73
V.text
p586
tp587
a(g189
V\u000a\u000a
p588
tp589
a(g7
V; prototype: long lrotate(long x, int num);
p590
tp591
a(g189
V\u000a
tp592
a(g45
V_lrotate:
p593
tp594
a(g189
V
p595
tp596
a(g7
V; [1]
p597
tp598
a(g189
V\u000a
tp599
a(g189
V
p600
tp601
a(g21
Vpush
p602
tp603
a(g189
V
tp604
a(g57
Vebp
p605
tp606
a(g189
V\u000a
tp607
a(g189
V
p608
tp609
a(g21
Vmov
p610
tp611
a(g189
V
tp612
a(g57
Vebp
p613
tp614
a(g202
V,
tp615
a(g57
Vesp
p616
tp617
a(g189
V\u000a
tp618
a(g189
V
p619
tp620
a(g21
Vmov
p621
tp622
a(g189
V
tp623
a(g57
Veax
p624
tp625
a(g202
V,[
p626
tp627
a(g57
Vebp
p628
tp629
a(g343
V+
tp630
a(g318
V8
tp631
a(g202
V]
tp632
a(g189
V\u000a
tp633
a(g189
V
p634
tp635
a(g21
Vmov
p636
tp637
a(g189
V
tp638
a(g57
Vecx
p639
tp640
a(g202
V,[
p641
tp642
a(g57
Vebp
p643
tp644
a(g343
V+
tp645
a(g318
V12
p646
tp647
a(g202
V]
tp648
a(g189
V\u000a
tp649
a(g21
V.label
p650
tp651
a(g189
V
p652
tp653
a(g73
Vrol
p654
tp655
a(g189
V
tp656
a(g57
Veax
p657
tp658
a(g202
V,
tp659
a(g318
V1
tp660
a(g189
V
p661
tp662
a(g7
V; [4] [8]
p663
tp664
a(g189
V\u000a
tp665
a(g189
V
p666
tp667
a(g21
Vloop
p668
tp669
a(g189
V
tp670
a(g73
V.label
p671
tp672
a(g189
V
p673
tp674
a(g7
V; [9] [12]
p675
tp676
a(g189
V\u000a
tp677
a(g189
V
p678
tp679
a(g21
Vmov
p680
tp681
a(g189
V
tp682
a(g57
Vesp
p683
tp684
a(g202
V,
tp685
a(g57
Vebp
p686
tp687
a(g189
V\u000a
tp688
a(g189
V
p689
tp690
a(g21
Vpop
p691
tp692
a(g189
V
tp693
a(g57
Vebp
p694
tp695
a(g189
V\u000a
tp696
a(g189
V
p697
tp698
a(g21
Vret
p699
tp700
a(g189
V\u000a\u000a
p701
tp702
a(g7
V; prototype: void greet(void);
p703
tp704
a(g189
V\u000a
tp705
a(g21
V_greet
p706
tp707
a(g189
V
p708
tp709
a(g73
Vpush
p710
tp711
a(g189
V
tp712
a(g57
Vebx
p713
tp714
a(g189
V
p715
tp716
a(g7
V; we'll use EBX for GOT, so save it
p717
tp718
a(g189
V\u000a
tp719
a(g189
V
p720
tp721
a(g21
Vcall
p722
tp723
a(g189
V
tp724
a(g73
V.getgot
p725
tp726
a(g189
V\u000a
tp727
a(g45
V.getgot:
p728
tp729
a(g189
V
p730
tp731
a(g21
Vpop
p732
tp733
a(g189
V
tp734
a(g57
Vebx
p735
tp736
a(g189
V\u000a
tp737
a(g189
V
p738
tp739
a(g21
Vadd
p740
tp741
a(g189
V
tp742
a(g57
Vebx
p743
tp744
a(g202
V,
tp745
a(g73
V__GLOBAL_OFFSET_TABLE_
p746
tp747
a(g189
V
tp748
a(g343
V+
tp749
a(g189
V
tp750
a(g117
V$$
p751
tp752
a(g189
V
tp753
a(g343
V-
tp754
a(g189
V
tp755
a(g73
V.getgot
p756
tp757
a(g189
V
tp758
a(g347
Vwrt
p759
tp760
a(g189
V
tp761
a(g73
V..gotpc
p762
tp763
a(g189
V\u000a
tp764
a(g189
V
p765
tp766
a(g21
Vmov
p767
tp768
a(g189
V
tp769
a(g57
Veax
p770
tp771
a(g202
V,[
p772
tp773
a(g57
Vebx
p774
tp775
a(g343
V+
tp776
a(g73
V_integer
p777
tp778
a(g189
V
tp779
a(g347
Vwrt
p780
tp781
a(g189
V
tp782
a(g73
V..got
p783
tp784
a(g202
V]
tp785
a(g189
V
tp786
a(g7
V; [14]
p787
tp788
a(g189
V\u000a
tp789
a(g189
V
p790
tp791
a(g21
Vmov
p792
tp793
a(g189
V
tp794
a(g57
Veax
p795
tp796
a(g202
V,[
p797
tp798
a(g57
Veax
p799
tp800
a(g202
V]
tp801
a(g189
V\u000a
tp802
a(g189
V
p803
tp804
a(g21
Vinc
p805
tp806
a(g189
V
tp807
a(g57
Veax
p808
tp809
a(g189
V\u000a
tp810
a(g189
V
p811
tp812
a(g21
Vmov
p813
tp814
a(g189
V
tp815
a(g202
V[
tp816
a(g57
Vebx
p817
tp818
a(g343
V+
tp819
a(g73
Vlocalint
p820
tp821
a(g189
V
tp822
a(g347
Vwrt
p823
tp824
a(g189
V
tp825
a(g73
V..gotoff
p826
tp827
a(g202
V],
p828
tp829
a(g57
Veax
p830
tp831
a(g189
V
tp832
a(g7
V; [14]
p833
tp834
a(g189
V\u000a
tp835
a(g189
V
p836
tp837
a(g21
Vmov
p838
tp839
a(g189
V
tp840
a(g57
Veax
p841
tp842
a(g202
V,[
p843
tp844
a(g57
Vebx
p845
tp846
a(g343
V+
tp847
a(g73
V_commvar
p848
tp849
a(g189
V
tp850
a(g347
Vwrt
p851
tp852
a(g189
V
tp853
a(g73
V..got
p854
tp855
a(g202
V]
tp856
a(g189
V\u000a
tp857
a(g189
V
p858
tp859
a(g21
Vpush
p860
tp861
a(g189
V
tp862
a(g139
Vdword
p863
tp864
a(g189
V
tp865
a(g202
V[
tp866
a(g57
Veax
p867
tp868
a(g202
V]
tp869
a(g189
V\u000a
tp870
a(g189
V
p871
tp872
a(g21
Vmov
p873
tp874
a(g189
V
tp875
a(g57
Veax
p876
tp877
a(g202
V,[
p878
tp879
a(g57
Vebx
p880
tp881
a(g343
V+
tp882
a(g73
Vlocalptr
p883
tp884
a(g189
V
tp885
a(g347
Vwrt
p886
tp887
a(g189
V
tp888
a(g73
V..gotoff
p889
tp890
a(g202
V]
tp891
a(g189
V
tp892
a(g7
V; [13]
p893
tp894
a(g189
V\u000a
tp895
a(g189
V
p896
tp897
a(g21
Vpush
p898
tp899
a(g189
V
tp900
a(g139
Vdword
p901
tp902
a(g189
V
tp903
a(g202
V[
tp904
a(g57
Veax
p905
tp906
a(g202
V]
tp907
a(g189
V\u000a
tp908
a(g189
V
p909
tp910
a(g21
Vmov
p911
tp912
a(g189
V
tp913
a(g57
Veax
p914
tp915
a(g202
V,[
p916
tp917
a(g57
Vebx
p918
tp919
a(g343
V+
tp920
a(g73
V_integer
p921
tp922
a(g189
V
tp923
a(g347
Vwrt
p924
tp925
a(g189
V
tp926
a(g73
V..got
p927
tp928
a(g202
V]
tp929
a(g189
V
tp930
a(g7
V; [1] [14]
p931
tp932
a(g189
V\u000a
tp933
a(g189
V
p934
tp935
a(g21
Vpush
p936
tp937
a(g189
V
tp938
a(g139
Vdword
p939
tp940
a(g189
V
tp941
a(g202
V[
tp942
a(g57
Veax
p943
tp944
a(g202
V]
tp945
a(g189
V\u000a
tp946
a(g189
V
p947
tp948
a(g21
Vlea
p949
tp950
a(g189
V
tp951
a(g57
Veax
p952
tp953
a(g202
V,[
p954
tp955
a(g57
Vebx
p956
tp957
a(g343
V+
tp958
a(g73
V_printfstr
p959
tp960
a(g189
V
tp961
a(g347
Vwrt
p962
tp963
a(g189
V
tp964
a(g73
V..gotoff
p965
tp966
a(g202
V]
tp967
a(g189
V\u000a
tp968
a(g189
V
p969
tp970
a(g21
Vpush
p971
tp972
a(g189
V
tp973
a(g57
Veax
p974
tp975
a(g189
V
p976
tp977
a(g7
V; [13]
p978
tp979
a(g189
V\u000a
tp980
a(g189
V
p981
tp982
a(g21
Vcall
p983
tp984
a(g189
V
tp985
a(g73
V_printf
p986
tp987
a(g189
V
tp988
a(g347
Vwrt
p989
tp990
a(g189
V
tp991
a(g73
V..plt
p992
tp993
a(g189
V
tp994
a(g7
V; [11]
p995
tp996
a(g189
V\u000a
tp997
a(g189
V
p998
tp999
a(g21
Vadd
p1000
tp1001
a(g189
V
tp1002
a(g57
Vesp
p1003
tp1004
a(g202
V,
tp1005
a(g318
V16
p1006
tp1007
a(g189
V\u000a
tp1008
a(g189
V
p1009
tp1010
a(g21
Vpop
p1011
tp1012
a(g189
V
tp1013
a(g57
Vebx
p1014
tp1015
a(g189
V\u000a
tp1016
a(g189
V
p1017
tp1018
a(g21
Vret
p1019
tp1020
a(g189
V\u000a\u000a
p1021
tp1022
a(g189
V
p1023
tp1024
a(g111
VSECTION
p1025
tp1026
a(g189
V
tp1027
a(g73
V.data
p1028
tp1029
a(g189
V\u000a\u000a
p1030
tp1031
a(g7
V; a string
p1032
tp1033
a(g189
V\u000a
tp1034
a(g21
V_asmstr
p1035
tp1036
a(g189
V
p1037
tp1038
a(g73
Vdb
p1039
tp1040
a(g189
V
tp1041
a(g226
V'hello, world'
p1042
tp1043
a(g202
V,
tp1044
a(g189
V
tp1045
a(g318
V0
tp1046
a(g189
V
tp1047
a(g7
V; [2]
p1048
tp1049
a(g189
V\u000a
tp1050
a(g21
V.end
p1051
tp1052
a(g189
V\u000a\u000a
p1053
tp1054
a(g7
V; a string for Printf
p1055
tp1056
a(g189
V\u000a
tp1057
a(g21
V_printfstr
p1058
tp1059
a(g189
V
tp1060
a(g73
Vdb
p1061
tp1062
a(g189
V
tp1063
a(g226
V"integer==%d, localint==%d, commvar=%d"
p1064
tp1065
a(g189
V\u000a
tp1066
a(g189
V
p1067
tp1068
a(g131
Vdb
p1069
tp1070
a(g189
V
tp1071
a(g318
V10
p1072
tp1073
a(g202
V,
tp1074
a(g189
V
tp1075
a(g318
V0
tp1076
a(g189
V\u000a\u000a
p1077
tp1078
a(g7
V; some pointers
p1079
tp1080
a(g189
V\u000a
tp1081
a(g21
Vlocalptr
p1082
tp1083
a(g189
V
p1084
tp1085
a(g73
Vdd
p1086
tp1087
a(g189
V
tp1088
a(g73
Vlocalint
p1089
tp1090
a(g189
V
p1091
tp1092
a(g7
V; [5] [17]
p1093
tp1094
a(g189
V\u000a
tp1095
a(g21
V_textptr
p1096
tp1097
a(g189
V
p1098
tp1099
a(g73
Vdd
p1100
tp1101
a(g189
V
tp1102
a(g73
V_greet
p1103
tp1104
a(g189
V
tp1105
a(g347
Vwrt
p1106
tp1107
a(g189
V
tp1108
a(g73
V..sym
p1109
tp1110
a(g189
V
tp1111
a(g7
V; [15]
p1112
tp1113
a(g189
V\u000a
tp1114
a(g21
V_selfptr
p1115
tp1116
a(g189
V
p1117
tp1118
a(g73
Vdd
p1119
tp1120
a(g189
V
tp1121
a(g73
V_selfptr
p1122
tp1123
a(g189
V
tp1124
a(g347
Vwrt
p1125
tp1126
a(g189
V
tp1127
a(g73
V..sym
p1128
tp1129
a(g189
V
tp1130
a(g7
V; [16]
p1131
tp1132
a(g189
V\u000a\u000a
p1133
tp1134
a(g189
V
p1135
tp1136
a(g111
VSECTION
p1137
tp1138
a(g189
V
tp1139
a(g73
V.bss
p1140
tp1141
a(g189
V\u000a\u000a
p1142
tp1143
a(g7
V; an integer
p1144
tp1145
a(g189
V\u000a
tp1146
a(g21
V_integer
p1147
tp1148
a(g189
V
p1149
tp1150
a(g73
Vresd
p1151
tp1152
a(g189
V
tp1153
a(g318
V1
tp1154
a(g189
V
p1155
tp1156
a(g7
V; [3]
p1157
tp1158
a(g189
V\u000a\u000a
p1159
tp1160
a(g7
V; a local integer
p1161
tp1162
a(g189
V\u000a
tp1163
a(g21
Vlocalint
p1164
tp1165
a(g189
V
p1166
tp1167
a(g73
Vresd
p1168
tp1169
a(g189
V
tp1170
a(g318
V1
tp1171
a(g189
V
p1172
tp1173
a(g7
V; [6]
p1174
tp1175
a(g189
V\u000a
tp1176
a. |
; DV3 Q68 FAT16 Find Partition V1.00 2017 W. Lenerz
;
section dv3
xdef hfp_fat
include 'dev8_keys_err'
include 'dev8_dv3_keys'
include 'dev8_dv3_hd_keys'
include 'dev8_keys_dos'
include 'dev8_mac_xword'
;+++
; DV3 FAT16 find partition.
;
; ******* !!!!
;
; It is presumed here that the FAT16 partition one is looking for
; - either is the first and only partition on a FAT16 formatted medium
; - or is one of the primary (!!!!) partitions on a FAT32 formatted medium.
; If not, the partition won't be found.
;
; For the Q68, I need to card on which the parition can be found, and the
; partition nbr. They can be found at hdl_unit(a3) and hdl_part(a3) respectively.
; The hdl_part is used here, the hdl_unit in the read/write routines.
; ******* !!!!
;
; d1 r as d3 but in ths format if required
; d2 r size of partition, -1 no partition table
; d3 r sector number with partition root
; d4 r partition ID
; d7 c p drive ID / number
; a3 c p pointer to linkage block
; a4 c p pointer to physical definition
;
; error return 0 or error
;---
hfp.reg reg a1
hfp_fat
movem.l hfp.reg,-(a7) ;
lea hdl_part-1(a3),a1 ; table stating which drive on what arition
moveq #0,d4
move.b (a1,d7.w),d4 ; partition required
prt_chk ble.s hfp_mchk ; neither 0 nor negatives!
cmp.b #4,d4
bgt.s hfp_mchk ; no more than 4 partitions, please
clr.l d3 ; start by reading root sector
hfp_chk move.l d3,d0 ; root sect or start sect of partition
lea hdl_buff(a3),a1 ; sector buffer
moveq #1,d2
jsr hdl_rsint(a3) ; read this sector
bne.s hfp_npart ; oops, say no partition
cmp.l #'FAT1',dos_f16s(a1) ; (direct) fat 16 partition?
bne.s hfp_f32 ; no, could be fat32
cmp.b #'6',4+dos_f16s(a1) ; still fat16 ?
bne.s hfp_mchk ; no
hfp_got moveq #0,d2
move.w dos_sect+1(a1),d2
move.b dos_sect(a1),d2 ; total sectors (small numbers)
tst.w d2 ; will be 0 if big number
mck_badl
blt.s hfp_mchk ; no negative values!
bgt.s hfp_ok1 ; small numbers ok
move.l dos_bnos(a1),d2 ; get big sectors number
xlong d2
move.l d3,d1 ; got a FAT16 partition
move.l #dos.fflg,d4 ; for FAT disk
hfp_ok1 moveq #0,d0
move.b d0,hdl_npart(a3) ; partition found
hfp_exit
movem.l (sp)+,hfp.reg
rts
hfp_mchk
moveq #err.mchk,d0
hfp_npart
st hdl_npart(a3) ; set no partition found
bra.s hfp_exit
; Check whether this is a FAT32 MBR, if yes, try to get the FAT16 partition.
; If d3<>0 then we alread checked the MBR, it was a FaT32 MBR and we tried to
; get the FAT16 partition from there - but this failed since we're back here.
; This means that we can't find the FAT16 partition.
hfp_f32 tst.l d3 ; will be 0 if root sector read
bne.s hfp_mchk ; we read a part. and it wasn't fat16
; cmp.l #'FAT3',dos_f32s(a1) ; fat32?
; bne.s hfp_mchk ; no
; cmp.b #'2',4+dos_f32s(a1) ; still fat32 ?
; bne.s hfp_mchk ; no
cmp.w #$55aa,$1fe(a1) ; could this be a partition table?
bne.s hfp_mchk : definitely not
lea dos_ptbl+dos_pstt(a1),a1; point to parition table start
moveq #dos.plen,d0 ; length of one partition table entry
hfp_lp subq.b #1,d4 ; this partition?
beq.s hfp_fnd ; yes
blt.s hfp_mchk ; too far (should have been caught at trp_chk)
add.l d0,a1 ; point next entry in table
bra.s hfp_lp ; try again
hfp_fnd move.l (a1)+,d3 ; start of partition sector nbr
xlong d3
bra hfp_chk ; check for FAT16 partition
end
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) Geoworks 1994 -- All Rights Reserved
GEOWORKS CONFIDENTIAL
PROJECT: Network extensions
MODULE: socket library
FILE: socketControl.asm
AUTHOR: Eric Weber, Apr 8, 1994
ROUTINES:
Name Description
---- -----------
INT ControlAttach Initialize control-block related data
EXT SocketGetDeliveryType Get the delivery type for a socket
INT WakeUpSocket Wake up the thread which is blocked on a
socket, if any
INT WakeUpExcept Wake up the thread which is blocked on a
socket, if any
EXT SocketFindPort Locate a given port in the portmap
EXT SocketFindFirstQueuedListen
Find the first PortInfo for the same port
as that passed in that has anything on its
listen queue.
EXT SocketClearSemaphore Free the wait semaphore from a socket, if
present.
EXT SocketClearExcept Free the except semaphore from a socket, if
present.
EXT SetupPacketInfo Copy information about a packet onto the
stack
INT SocketCreateLow Low level function for allocating sockets
EXT SocketFindOrCreatePort Find or create a port
EXT SocketImplicitBind Choose a port and bind the socket to it
INT SocketBindLow low-level function to bind a socket to a
port
INT SocketAllocatePort Create a port
INT SocketConnectDatagram Connect a datagram socket
INT SocketRegisterConnection
Register the connection for a socket and
add it to port's connection array
INT RemoveSocketFromPort Remove a socket from port's chunk array
INT SocketClearConnection Remove failed connection indication from a
socket
EXT SocketCreateListenQueue Create a listen queue chunk
INT SocketListenLow Set a socket to a listening state
INT SocketCheckOpenState Determine the outcome of an open operation
INT SocketPreAccept Initiate acceptance of a connection
INT SocketPostLinkAccept Clean up after accepting
INT FreeListenQueue Free a listen queue
EXT FreePortListenQueue Free the listen queue associated with a
port, canceling all connections pending for
it.
EXT FreeListenQueueCallback callback for FreeListenQueue sends
CCO_REFUSE and decrements link ref count
INT SocketFreeLow Free a socket chunk and possibly the port
chunk
EXT SocketFreePort Free a port, if it is not in use
INT SocketCheckReadySetup Setup to wait on sockets
INT SocketCheckReadyHere See if a particular socket is ready
INT SocketCheckReadyCleanup remove semaphore from all sockets currently
containing it
INT SocketPostDataAccept Accept a connection from a data driver
INT SetupDatagramInfo Copy information about a packet onto the
stack
INT SocketGetLink Get the domain and link a socket is using
INT SocketGetAddress Get default address for a datagram socket
INT SocketGetDomainName Get the domain name a socket is connect
over
INT SocketQueryAddress Query a driver for either the local or
remote name
INT SocketGetRemotePort Get remote port number
INT SocketGetLocalPort Get port this socket is bound to
INT SocketPassOption Pass an option through to the driver
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 4/ 8/94 Initial revision
DESCRIPTION:
Code for managing ports and sockets
$Id: socketControl.asm,v 1.44 97/10/28 00:12:30 brianc Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketControl segment lmem LMEM_TYPE_GENERAL, mask LMF_RETURN_ERRORS
SocketSocketArray chunk SocketArray
ChunkArrayHeader <0, size word, 0, size SocketArray>
EC < ControlChunkType CCT_SOCKET_ARRAY >
SocketSocketArray endc
SocketPortArray chunk PortArray
ChunkArrayHeader <0, size PortArrayEntry, 0, size PortArray>
EC < ControlChunkType CCT_PORT_ARRAY >
SocketPortArray endc
SocketDomainArray chunk DomainArray
ChunkArrayHeader <0, size word, 0, size DomainArray>
EC < ControlChunkType CCT_DOMAIN_ARRAY >
SocketDomainArray endc
SocketControl ends
idata segment
;
; where to read the implicit port range from the init file
;
minImplicitKey char "minImplicitPort",0
maxImplicitKey char "maxImplicitPort",0
idata ends
udata segment
;
; any implicitly bound ports will have port numbers between
; minImplicitPort+1 and maxImplicitPort inclusively.
;
minImplicitPort word
maxImplicitPort word
;
; this is the last implicit port which was assigned
;
curImplicitPort word
udata ends
UtilCode segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ControlAttach
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Initialize control-block related data
CALLED BY: (INTERNAL) SocketEntry
PASS: ds = dgroup
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 10/ 3/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
ControlAttach proc far
uses ax,cx,dx,si
.enter
;
; read the min implicit port
;
Assert dgroup, ds
mov si, offset ds:[socketCategory]
mov cx, ds
mov dx, offset ds:[minImplicitKey]
mov ax, IMPLICIT_PORT_MIN
call InitFileReadInteger
;
; the min port must be in the range 0..65534
;
cmp ax, -1
jne minOK
WARNING INVALID_MIN_IMPLICIT_PORT
mov ax, -2
minOK:
mov ds:[minImplicitPort], ax
mov ds:[curImplicitPort], ax
;
; read the max implicit port
;
mov dx, offset ds:[maxImplicitKey]
mov ax, IMPLICIT_PORT_MAX
call InitFileReadInteger
;
; the max port must be in the range min+1..65535
;
cmp ax, ds:[minImplicitPort]
ja maxOK
WARNING INVALID_MAX_IMPLICIT_PORT
mov ax, ds:[minImplicitPort]
inc ax
maxOK:
mov ds:[maxImplicitPort], ax
.leave
ret
ControlAttach endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketGetDeliveryType
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get the delivery type for a socket
CALLED BY: (EXTERNAL) SocketConnect, SocketSend
PASS: *ds:bx - Socket
RETURN: cx - SocketDeliveryType
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 6/ 7/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketGetDeliveryType proc far
uses si
.enter
mov si, ds:[bx]
mov cl, ds:[si].SI_delivery
clr ch
.leave
ret
SocketGetDeliveryType endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
WakeUpSocket
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Wake up the thread which is blocked on a socket, if any
CALLED BY: (INTERNAL) ConnectionAccept, ConnectionBegin,
ConnectionCancel, ConnectionClose, ConnectionOpen,
ConnectionRefuse, ReceiveDatagramDataPacket,
ReceiveLinkDataPacket, ReceiveSequencedDataPacket,
SocketConnectRequest, SocketConnectionClosed,
SocketInterrupt, SocketRemoveConnection
PASS: *ds:bx - SocketInfo
RETURN: z set if nobody waiting
DESTROYED: nothing
SIDE EFFECTS: none
PSEUDO CODE/STRATEGY:
use SI_semSem to control access to waitSem, to ensure that
no other thread is in the middle of SocketClearSemaphore
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 6/ 8/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
WakeUpSocket proc far
uses bx,si,di
.enter
mov si,bx
EC < call ECCheckSocketLow >
mov di, ds:[bx]
;
; lock semSem
;
mov bx, ds:[di].SI_semSem
call ThreadPSem
;
; wake up waiter
;
call WakeUpSocketLow
;
; unlock semSem
;
mov bx, ds:[di].SI_semSem
call ThreadVSem
.leave
ret
WakeUpSocket endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
WakeUpExcept
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Wake up the thread which is blocked on a socket, if any
CALLED BY: (INTERNAL) ReceiveUrgentDataPacket
PASS: *ds:bx - SocketInfo
RETURN: z flag set if nobody waiting
DESTROYED: nothing
SIDE EFFECTS: none
PSEUDO CODE/STRATEGY:
use SI_semSem to control access to exceptSem, to ensure that
no other thread is in the middle of SocketClearExcept
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 6/ 8/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
WakeUpExcept proc far
uses bx,si,di
.enter
mov si,bx
EC < call ECCheckSocketLow >
mov di, ds:[bx]
;
; lock semSem
;
mov bx, ds:[di].SI_semSem
call ThreadPSem
;
; wake up anyone waiting explicitly for exception/urgent
;
call WakeUpExceptLow
;
; if nobody is waiting on exceptSem, set SF_EXCEPT and
; wake up the waitSem instead
;
checkWait::
or ds:[di].SI_flags, mask SF_EXCEPT
call WakeUpSocketLow
done::
mov bx, ds:[di].SI_semSem
call ThreadVSem
.leave
ret
WakeUpExcept endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
WakeUpForClose
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Wake everyone up, because receive just got disabled
CALLED BY:
PASS: *ds:bx - socket
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 3/ 7/96 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
WakeUpForClose proc far
uses bx,si,di
.enter
;
; validate socket
;
mov si,bx
EC < call ECCheckSocketLow >
mov di, ds:[bx]
EC < test ds:[di].SI_flags, mask SF_RECV_ENABLE >
EC < ERROR_NZ RECEIVE_STILL_ENABLED >
;
; grab semSem
;
mov bx, ds:[di].SI_semSem
call ThreadPSem
;
; wake everyone up
;
call WakeUpExceptLow
call WakeUpSocketLow
;
; release semSem
;
call ThreadVSem
.leave
ret
WakeUpForClose endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
WakeUpSocketLow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Wake up whomever is on the waitSem
CALLED BY: WakeUpSocket, WakeUpExcept
PASS: ds:di - SocketInfo
ds:di.SI_semSem locked if control block is shared
RETURN: z set if nobody waiting
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 3/ 7/96 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
WakeUpSocketLow proc far
uses bx, es
.enter
;
; unlock waitSem
;
mov bx, ds:[di].SI_waitSem
tst bx
jz done
call ThreadVSem
;
; write socket handle to waitPtr, if necessary
;
tst ds:[di].SI_waitPtr.segment ; ptr exists?
jz done
writePtr::
push di
movdw esdi, ds:[di].SI_waitPtr
mov es:[di], si ; write socket han
pop di
done:
.leave
ret
WakeUpSocketLow endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
WakeUpExceptLow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Wake up the thread on exceptSem
CALLED BY: WakeUpExcept
PASS: ds:di - socket
ds:di.SI_semSem locked if control block locked shared
RETURN: z flag - set if nobody waiting
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 3/ 7/96 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
WakeUpExceptLow proc far
uses ax,bx,cx,dx,si,di,bp
.enter
;
; unlock exceptSem
;
mov bx, ds:[di].SI_exceptSem
tst bx
jz done
call ThreadVSem
;
; write socket handle to exceptPtr, if necessary
;
tst ds:[di].SI_exceptPtr.segment ; ptr exists?
jz done
push di
movdw esdi, ds:[di].SI_exceptPtr
mov es:[di], si ; write socket han
pop di
done:
.leave
ret
WakeUpExceptLow endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketFindPort
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Locate a given port in the portmap
CALLED BY: (EXTERNAL) ConnectionAccept, ConnectionBegin,
ConnectionCancel, ConnectionClose, ConnectionOpen,
ConnectionRefuse, ECCheckPortLow,
ReceiveDatagramDataPacket, ReceiveLinkDataPacket,
SocketCheckListen, SocketConnectRequest,
SocketFindOrCreatePort, SocketFreePort, SocketImplicitBind,
SocketRemoveLoadOnMsgMem
PASS: ds - control block
axbx - SocketPort
dx - domain handle
RETURN: *ds:si - port array
if found:
carry clear
ds:di - PortArrayEntry
if not found:
carry set
ds:di - element before which to insert new port
di = 0 if new port should be appended
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
This routine is used as part of the process of looking up
a socket for every incoming packet. Therefore it must be fast.
This is why it does it's own chunk array computations instead of
using the ChunkArray functions in the kernel
It doesn't really need to be that fast, but it works now so I'm
not changing it
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 4/25/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketFindPort proc far
uses ax,bx,cx,dx,bp,es
.enter
;
; save domain handle
;
push dx
;
; locate the portmap and get a count of active ports
;
mov si, offset SocketPortArray
mov di, ds:[si]
mov cx, ds:[di].CAH_count
;
; set up for loop
;
jcxz append ; handle empty array
clr bp ; bp = lower bound = 0
dec cx ; cx = upper bound = count-1
mov dx,cx
shr dx ; dx = cx/2 = first element to check
;
; main loop:
; bp = lower bound of element range (inclusive)
; dx = element to check next
; cx = upper bound of element range (inclusive)
; axbx = SocketPort to search for
; *ds:si = portmap
; (on stack) = domain handle
;
top:
;
; if we have a negative region, we didn't find it
;
cmp bp,cx
jg notFound
;
; get a pointer to the element
;
push ax,dx
mov ax, size PortArrayEntry ; ax = size of element
mul dx ; dxax = offset to element
mov di, ds:[si] ; ds:di = array header
add di, ds:[di].CAH_offset ; ds:di = first element
add di, ax ; ds:di = desired element
pop ax,dx
;
; is this the one?
;
cmpdw axbx, ds:[di].PAE_id
jb lower
je found
;
; we need to search higher in the array
;
higher:
inc dx ; dx = new lower bound
mov bp,dx ; bp = new lower bound
add dx,cx ; dx = sum of bounds
shr dx ; dx = median of bounds
jmp top
;
; we need to search lower in the array
;
lower:
dec dx ; dx = new upper bound
mov cx,dx ; cx = new upper bound
add dx,bp ; dx = sum of bounds
shr dx ; dx = median of bounds
jmp top
;
; the element wasn't found
; bp = index at which to add new element
;
notFound:
mov ax,bp
call ChunkArrayElementToPtr ; ds:di=elt, cf=out of bounds
cmc
jc done ; jmp if not out of bounds
;
; the element is larger then the last element of the array
;
append:
clr di
stc
jmp done
;
; we found something with the right port number
; ds:di = element, dx = index
; compare the domains
;
found:
pop ax ; domain to check
push ax
tst_clc ax
jz done ; unrestricted search
mov bx, ds:[di].PAE_info
mov bx, ds:[bx] ; ds:bx = PortInfo
tst_clc ds:[bx].PI_restriction
jz done ; port ok for all domains
cmp ax, ds:[bx].PI_restriction
movdw axbx, ds:[di].PAE_id ; restore port number
ja higher
jb lower
;
; Eureka! this port matches in all regards
;
done:
pop ax ; discard domain handle
.leave
ret
SocketFindPort endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketFindFirstQueuedListen
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Find the first PortInfo for the same port as that passed in
that has anything on its listen queue.
CALLED BY: (EXTERNAL) SocketCheckListen
PASS: ds:di = PortArrayEntry found (may not be the first one
in the array, though)
*ds:si = port array
RETURN: carry set if no port is actually listening:
ax = SE_NOT_LISTENING
si = destroyed
carry clear if found a listening port:
ds:di = PortInfo
*ds:si = listen queue
ax = destroyed
DESTROYED:
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/27/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketFindFirstQueuedListen proc far
uses bx, dx, bp, cx
.enter
;
; Load the port number into bxdx for convenience
;
movdw bxdx, ds:[di].PAE_id
;
; Back up to the first entry for the port, in case the unrestricted
; binary search landed us in the middle of the port range.
;
call ChunkArrayPtrToElement
call ChunkArrayGetCount
xchg cx, ax
sub ax, cx
entryLoop:
jcxz haveFirst
;
; Check the previous entry to see if it's for the same port.
;
lea si, ds:[di-size PortArrayEntry]
cmpdw ds:[si].PAE_id, bxdx
jne haveFirst ; => no, so ds:di is first
dec cx ; one fewer to look at before
; this one
inc ax ; one more to look at after
mov di, si ; ds:di <- prev
jmp entryLoop
haveFirst:
;
; ds:di = entry to look at first
; ax = # entries left in the array following (and including) ds:di
; bxdx = port #
;
; Now look at the listen queue for each one for this port until we
; find one that has something in it.
;
; At the end of the loop, when nothing found that's listening:
; ax = SE_PORT_NOT_LISTENING if nothing was listening
; ds:bp = PortArrayEntry for first port that was listening,
; if ax is 0
;
mov_tr cx, ax ; cx <- # to examine
mov ax, SE_PORT_NOT_LISTENING
clr bp
findQueueLoop:
cmpdw ds:[di].PAE_id, bxdx
jne noneFound
mov si, ds:[di].PAE_info
mov si, ds:[si] ; ds:si <- PortInfo
mov si, ds:[si].PI_listenQueue
tst si
jz findQueueNext
clr ax ; found at least one that's
; listening
tst bp
jnz checkCount
mov bp, di
checkCount:
mov si, ds:[si]
tst ds:[si].CAH_count
jnz foundIt
findQueueNext:
add di, size PortArrayEntry
loop findQueueLoop
noneFound:
tst ax ; none listening?
stc ; assume so
jnz done ; => so
mov di, bp ; ds:di <- first listener,
; though queue is empty
foundIt:
mov di, ds:[di].PAE_info
mov di, ds:[di]
mov si, ds:[di].PI_listenQueue
clc
done:
.leave
ret
SocketFindFirstQueuedListen endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketClearSemaphore
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Free the wait semaphore from a socket, if present.
CALLED BY: (EXTERNAL) SocketAccept, SocketClose, SocketConnect,
SocketPreAccept, SocketRecvLow
PASS: *ds:bx - SocketInfo
RETURN: nothing
DESTROYED: nothing (flags preserved)
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
use SI_semSem to control access to waitSem, to ensure that
no other thread is in the middle of WakeUpSocket
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 7/26/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketClearSemaphore proc far
uses ax,bx,si
pushf
.enter
mov si, ds:[bx]
mov bx, ds:[si].SI_semSem
call ThreadPSem
clrdw ds:[si].SI_waitPtr ; clear pointer
clr bx
xchg bx, ds:[si].SI_waitSem ; clear semaphore
tst bx
jz done
call ThreadFreeSem ; free semaphore
done:
mov bx, ds:[si].SI_semSem
call ThreadVSem
.leave
popf
ret
SocketClearSemaphore endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketClearExcept
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Free the except semaphore from a socket, if present.
CALLED BY: (EXTERNAL) SocketRecvLow
PASS: *ds:bx - SocketInfo
RETURN: nothing
DESTROYED: nothing (flags preserved)
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
use SI_semSem to control access to exceptSem, to ensure that
no other thread is in the middle of WakeUpExcept
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 6/15/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketClearExcept proc far
uses ax,bx,si
pushf
.enter
mov si, ds:[bx]
mov bx, ds:[si].SI_semSem
call ThreadPSem
clrdw ds:[si].SI_exceptPtr ; clear pointer
clr bx
xchg bx, ds:[si].SI_exceptSem ; clear semaphore
tst bx
jz done
call ThreadFreeSem ; free semaphore
done:
mov bx, ds:[si].SI_semSem
call ThreadVSem
.leave
popf
ret
SocketClearExcept endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SetupPacketInfo
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Copy information about a packet onto the stack
CALLED BY: (EXTERNAL) SocketAccept, SocketClearConnection,
SocketConnect, SocketSend, SocketSendClose
PASS: *ds:bx - SocketInfo
*ds:cx - DomainInfo
dx - link offset
ON STACK
uninitialized PacketInfo
RETURN: PacketInfo filled in (args not popped)
bx - waitSem from socket
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 6/ 5/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SetupPacketInfo proc far info:PacketInfo
uses ax,si,di
.enter
;
; get information from the socket
;
getSocket::
mov si, ds:[bx] ; ds:si = SocketInfo
movdw ss:[info].PI_destPort,ds:[si].SSI_connection.CE_port,ax
mov bx, ds:[si].SI_waitSem
;
; get information from the port
;
mov di, ds:[si].SI_port
mov di, ds:[di] ; ds:di = PortInfo
movdw ss:[info].PI_srcPort, ds:[di].PI_number, ax
;
; get information from the domain
;
mov di, cx
mov di, ds:[di]
segmov ss:[info].PI_driverType,ds:[di].DI_driverType, al
segmov ss:[info].PI_client, ds:[di].DI_client, ax
movdw ss:[info].PI_entry, ds:[di].DI_entry, ax
mov al, ds:[di].DI_seqHeaderSize
clr ah
mov ss:[info].PI_headerSize, ax
;
; get information from the link
;
add di, dx ; ds:di = LinkInfo
segmov ss:[info].PI_link, ds:[di].LI_handle, ax
;
; make sure socket and link agree
;
EC < cmp ds:[si].SSI_connection.CE_domain, cx >
EC < ERROR_NE SOCKET_LINK_MISMATCH >
EC < mov ax, ds:[di].LI_handle >
EC < cmp ds:[si].SSI_connection.CE_link, ax >
EC < ERROR_NE SOCKET_LINK_MISMATCH >
.leave
ret ; DO NOT POP ARGS
SetupPacketInfo endp
UtilCode ends
ApiCode segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketCreateLow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Low level function for allocating sockets
CALLED BY: (INTERNAL) SocketCreate, SocketPreAccept
PASS: ds - control block
ax - SocketDeliveryType
RETURN: ax - Socket
ds - control block (possibly moved)
carry set if out of memory
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 4/27/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketCreateLow proc near
uses bx,cx,si,di
.enter
;
; allocate a socket
;
mov bx,ax ; save delivery type
clr al ; no object flags
mov cx, size SequencedSocketInfo ; chunk size
cmp bl, SDT_DATAGRAM
jne alloc
mov cx, size DatagramSocketInfo
alloc:
call LMemAlloc ; ax = chunk
jc done
;
; add it to the socket array
;
mov si, offset SocketSocketArray
call ChunkArrayAppend
jnc appendOK
call LMemFree ; discard socket
stc
jmp done
appendOK:
mov ds:[di], ax
;
; set the delivery type
;
mov si, ax
mov si, ds:[si] ; ds:si = SocketInfo
mov ds:[si].SI_delivery, bl
;
; set the owner
;
call GeodeGetProcessHandle ; bx = owner of this thread
mov ds:[si].SI_owner, bx
;
; allocate a semaphore
;
mov bx, 1
call ThreadAllocSem ; bx = semaphore
push ax
mov ax, handle 0
call HandleModifyOwner
pop ax
mov ds:[si].SI_semSem, bx
;
; initialize the rest of the common fields
;
EC < mov ds:[si].SI_type, CCT_SOCKET_INFO >
mov ds:[si].SI_state, ISS_UNCONNECTED
clr bx ; bx <- 0 for initializing
; everything that needs to
; be zero
mov ds:[si].SI_flags, mask SF_INTERRUPTIBLE
mov ds:[si].SI_port, bx
mov ds:[si].SI_dataQueue, bx
movdw ds:[si].SI_curQueueSize, bxbx
mov ds:[si].SI_maxQueueSize.low, DEFAULT_MAX_RECV_QUEUE_SIZE
mov ds:[si].SI_maxQueueSize.high, bx
mov ds:[si].SI_maxSendSize, DEFAULT_MAX_SEND_QUEUE_SIZE
mov ds:[si].SI_queueToken, bx
mov ds:[si].SI_dataOffset, bx
mov ds:[si].SI_waitSem, bx
movdw ds:[si].SI_waitPtr, bxbx
mov ds:[si].SI_exceptSem, bx
movdw ds:[si].SI_exceptPtr, bxbx
;
; initialize sequenced or datagram specific fields
;
CheckHack <SDT_DATAGRAM eq 0> ; so that CF always
; clear after CMP.
cmp ds:[si].SI_delivery, SDT_DATAGRAM ; CF clear
je datagram
movdw ds:[si].SSI_urgent, bxbx
mov ds:[si].SSI_urgentSize, bx
;
; these fields don't strictly need to be initialized, but it makes
; things cleaner while debugging
;
EC < mov ds:[si].SSI_error, bx >
EC < mov ds:[si].SSI_connection.CE_domain, bx >
EC < mov ds:[si].SSI_connection.CE_link, bx >
EC < movdw ds:[si].SSI_connection.CE_port, bxbx >
jmp done
;
; initialize datagram fields
;
datagram:
mov ds:[si].DSI_domain, bx
mov ds:[si].DSI_addressSize, bx
mov ds:[si].DSI_exception, bl
done:
.leave
ret
SocketCreateLow endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketFindOrCreatePort
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Find or create a port
CALLED BY: (EXTERNAL) SocketAddLoadOnMsgMem, SocketBindLow
PASS: axbx - SocketPort
dx:di - domain to bind in (dx = 0 if none)
ds - control segment locked for writing
RETURN: bx - port handle
ax - SocketError (carry set on error)
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 11/20/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketFindOrCreatePort proc far
uses cx,dx,si,di,bp
portNum local SocketPort push ax,bx
.enter
;
; was a domain passed?
;
clr bx ; assume it doesn't
tst dx
je domainOK
;
; it was, but does it exist?
; note that it doesn't matter what state the domain is in
;
push bp
mov bp,di
call SocketFindDomainLow ; bx = domain
jnc updateDomain
;
; it doesn't, so create it
;
call SocketCreateDomain ; bx = domain
mov ax, SE_OUT_OF_MEMORY
;
; check for errors
;
updateDomain:
pop bp
jc done ; (carry from SocketCreate,
; when taken)
;
; got the domain, now locate the port
;
domainOK:
mov dx,bx
movdw axbx, ss:[portNum]
call SocketFindPort ; locate the entry
jnc located
call SocketAllocatePort ; or create it if needed
mov ax, SE_OUT_OF_MEMORY
jc done
;
; we may have found a restricted port on an unrestricted search
; or vice versa
;
located:
mov bx, ds:[di].PAE_info ; *ds:bx = PortInfo
mov di, ds:[bx]
cmp dx, ds:[di].PI_restriction
je done ; carry clear if equal
mov ax, SE_BIND_CONFLICT
stc
done:
.leave
ret
SocketFindOrCreatePort endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketImplicitBind
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Choose a port and bind the socket to it
CALLED BY: (EXTERNAL) SocketConnect, SocketSend
PASS: bx - socket
cx - domain
ds - control segment
RETURN: carry - set if error
ax - SocketError if error, preserved if no error
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 11/29/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketImplicitBind proc far
uses bx,cx,dx,si,di,bp,es
socketHan local word push bx
domainHan local word push cx
passedAX local word push ax
.enter
;
; get dgroup pointer
;
push bx
mov bx, handle dgroup
call MemDerefES
pop bx
;
; validate socket
;
EC < mov si, bx >
EC < call ECCheckSocketLow >
;
; check for an existing binding
;
mov si, ds:[bx]
tst_clc ds:[si].SI_port
jnz done
;
; choose the manufacturer id
;
mov si, cx
mov si, ds:[si]
mov ax, MANUFACTURER_ID_GEOWORKS
cmp ds:[si].DI_driverType, SDT_DATA
jne gotID
mov ax, MANUFACTURER_ID_SOCKET_16BIT_PORT
gotID:
;
; locate the start of that id in the port array
;
mov bx, es:[curImplicitPort]
cmp bx, es:[maxImplicitPort]
jb startOK
mov bx, es:[minImplicitPort]
startOK:
inc bx
clr dx ; unrestricted search
call SocketFindPort
jc gotPort
;
; compute the upper bound of the array
;
push ax,di
mov ax, CA_LAST_ELEMENT
call ChunkArrayElementToPtr ; ds:di = last element
mov dx,di
pop ax,di
;
; skip any entries with the same portnum
;
skip:
cmp di, dx
je append
add di, size PortArrayEntry
cmpdw axbx, ds:[di].PAE_id
je skip
;
; try the next port number
;
cmp bx, es:[curImplicitPort]
je busy
cmp bx, es:[maxImplicitPort]
jne nextPort
mov bx, es:[minImplicitPort]
nextPort:
inc bx
cmpdw axbx, ds:[di].PAE_id
je skip ; next port is busy too
;
; axbx is not in use
; create a port for it
;
gotPort:
mov es:[curImplicitPort], bx
mov dx, ss:[domainHan]
call SocketAllocatePort
jnc initSocket
mov ax, SE_OUT_OF_MEMORY
jmp done
append:
clr di
jmp gotPort
;
; bind the socket
;
initSocket:
mov di, ds:[di].PAE_info ; port handle
mov bx, ss:[socketHan]
mov si, ds:[bx] ; ds:si = SocketInfo
mov ds:[si].SI_port, di
mov di, ds:[di] ; ds:di = PortInfo
mov ds:[di].PI_numActive, 1
;
; normal exit
;
clc
mov ax, ss:[passedAX]
done:
.leave
ret
;
; all portnums are in use
; this can never happen, since we'd run out of memory first
;
busy:
mov ax, SE_ALL_PORTS_BUSY
stc
jmp done
SocketImplicitBind endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketBindLow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: low-level function to bind a socket to a port
CALLED BY: (INTERNAL) SocketBind, SocketBindInDomain
PASS: ds - control block
*ds:si - SocketInfo
axbx - SocketPort
cx - SocketBindFlags
dx:di - domain name (dx = 0 if none)
RETURN: carry - set on error
ax - SocketError
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 4/25/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketBindLow proc near
uses bx,cx,dx,si,di,bp
.enter
;
; find or create a port
;
call SocketFindOrCreatePort ; bx = port
jc abort
;
; socket can't be bound already
;
mov di, ds:[si] ; ds:di = socket info
tst ds:[di].SI_port
jnz alreadyBound
;
; treat datagrams differently
;
cmp ds:[di].SI_delivery, SDT_DATAGRAM
mov di, ds:[bx] ; ds:di = port info
je datagram
;
; check for existing binds
;
tst ds:[di].PI_numActive
jz activeOK
test cx, mask SBF_REUSE_PORT
jz portInUse
activeOK:
inc ds:[di].PI_numActive
;
; we've updated the port, now update the socket
;
mov di, ds:[si] ; ds:di = SocketInfo
mov ds:[di].SI_port, bx ; pointer to PortInfo
jmp done
;
; the socket is already bound
;
alreadyBound:
mov ax, SE_SOCKET_ALREADY_BOUND
stc
jmp abort
;
; another socket is already bound to the port
;
portInUse:
stc
mov ax, SE_PORT_IN_USE
jmp abort
;
; check for other datagram users
;
datagram:
tst ds:[di].PI_dgram
jnz portInUse
;
; create a data queue
;
push bx
mov bx, si
call SocketAllocQueue
pop bx
mov ax, SE_OUT_OF_MEMORY
jc abort
;
; update port and socket
;
mov ds:[di].PI_dgram, si
mov di, ds:[si] ; ds:di = SocketInfo
mov ds:[di].SI_port, bx
done::
mov ax, SE_NORMAL
clc
abort:
.leave
ret
SocketBindLow endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketAllocatePort
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Create a port
CALLED BY: (INTERNAL) SocketFindOrCreatePort, SocketImplicitBind
PASS: ds - control block
*ds:si - port array
ds:di - PortArrayElement to precede
axbx - SocketPort
dx - domain handle
RETURN: ds:di - PortArrayEntry
carry - set if couldn't allocate memory
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
allocating the PAE will destroy the offset in di, so convert
it to an index during the allocation and convert it back after
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 4/25/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketAllocatePort proc near
uses ax,bx,cx,dx,bp,si
portArray local nptr push si
portNum local dword push ax,bx
index local word
.enter
;
; get the index of the PortArrayEntry
;
mov ss:[index], CA_NULL_ELEMENT
tst di
jz alloc
call ChunkArrayPtrToElement
mov ss:[index], ax
;
; allocate the PortInfo
;
alloc:
mov bx, size Socket ; element size
mov cx, size PortInfo ; header size
clr si ; new chunk
call ChunkArrayCreate ; *ds:si = array
jc done ; out of memory
;
; initialize the port
;
push di
mov di, ds:[si]
EC < mov ds:[di].PI_type, CCT_PORT_INFO >
movdw ds:[di].PI_number, ss:[portNum], ax
mov ds:[di].PI_restriction, dx
pop di
;
; insert or append a PortArrayEntry
;
mov dx,si ; *ds:dx PortInfo
mov si, ss:[portArray]
mov ax, ss:[index]
cmp ax, CA_NULL_ELEMENT
jne insert
;
; append the new entry
;
call ChunkArrayAppend ; ds:di = new element
jnc init
;
; if we couldn't allocate the PortArrayEntry, get rid of the PortInfo
;
extendFailed:
call LMemFree ; free PortInfo
stc
jmp done
;
; insert a new PortArrayEntry at ds:di
;
insert:
call ChunkArrayElementToPtr ; ds:di = elt to insert before
call ChunkArrayInsertAt ; ds:di = new element
jc extendFailed
;
; initialize the PortArrayEntry
;
init:
movdw ds:[di].PAE_id, ss:[portNum], bx
mov ds:[di].PAE_info, dx
clc
done:
.leave
ret
SocketAllocatePort endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketConnectDatagram
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Connect a datagram socket
CALLED BY: (INTERNAL) SocketConnect
PASS: *ds:bx = SocketInfo
es:di = SocketAddress
RETURN: carry set on error
ax = SocketError
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 12/14/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketConnectDatagram proc near
uses bx,cx,dx,si,di,bp
.enter
;
; validate the socket
;
mov si, bx
EC < call ECCheckSocketLow >
;
; locate and lock the domain
;
call SocketAddressToDomain ; dx = domain
jc done
;
; resize socket
;
mov ax,si
mov cx, es:[di].SA_addressSize
add cx, size DatagramSocketInfo
call LMemReAlloc
mov ax, SE_OUT_OF_MEMORY
jc done
;
; now store the address in the socket
;
push si, dx
mov bx, ds:[si] ; ds:bx = SocketInfo
mov ds:[bx].SI_state, ISS_CONNECTED
xchg ds:[bx].DSI_domain, dx ; store domain handle
movdw ds:[bx].DSI_port, es:[di].SA_port, ax
mov cx, es:[di].SA_addressSize
mov ds:[bx].DSI_addressSize, cx
segxchg ds,es
lea si, ds:[di].SA_address
lea di, es:[bx].DSI_address
EC < call ECCheckMovsb >
rep movsb
segxchg ds,es ; restore for return
; edwdig - time to kill the evil evil damn stupid udp bug!
; die bug die!
;
pop bx, cx
mov si, ds:[bx]
tst ds:[si].SI_port
jnz release
call SocketImplicitBind
jc release
mov di, ds:[si].SI_port
mov di, ds:[di]
mov ds:[di].PI_dgram, bx
call SocketAllocQueue
mov ax, SE_OUT_OF_MEMORY
;
; if there was a domain before, release our misc lock
;
release:
pushf
tst dx
jz cleanup
mov si, dx ; *ds:si = old domain
call SocketReleaseMiscLock
;
; clean up and exit
;
cleanup:
popf
jc done
mov ax, SE_NORMAL
clc
done:
.leave
ret
SocketConnectDatagram endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketRegisterConnection
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Register the connection for a socket and add it to port's
connection array
CALLED BY: (INTERNAL) SocketConnect
PASS: ds - control block
bx - Socket
cx - domain
dx - link offset
es:di - address
RETURN: carry set on error
ax - SocketError
carry clear if no error
ax - driver type
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 4/25/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketRegisterConnection proc near
uses bx,cx,dx,si,di,bp
.enter
movdw axdi, es:[di].SA_port
pushdw axdi ; save SocketPort
;
; verify the socket
;
mov si,bx ; si = Socket
EC < call ECCheckSocketLow >
;
; verify the delivery type
;
mov si, ds:[si]
EC < cmp ds:[si].SI_delivery, SDT_DATAGRAM >
EC < ERROR_E ILLEGAL_OPERATION_ON_DATAGRAM_SOCKET >
;
; verify 16-bit ports, if needed
;
mov di, cx
mov di, ds:[di]
cmp ds:[di].DI_driverType, SDT_DATA
jne portOK
cmp ax, MANUFACTURER_ID_SOCKET_16BIT_PORT
mov ax, SE_DOMAIN_REQUIRES_16BIT_PORTS
jne error
;
; verify state
;
portOK:
cmp ds:[si].SI_state, ISS_UNCONNECTED
je stateOK
mov ax, SE_SOCKET_IN_USE
jmp error
;
; allocate the data queue
;
stateOK:
call SocketAllocQueue
mov ax, SE_OUT_OF_MEMORY
jc error
;
; store pointer to socket in port's array
;
mov si, ds:[si].SI_port
EC < call ECCheckPortLow >
call ChunkArrayAppend ; ds:di = entry
mov ax, SE_OUT_OF_MEMORY
jc portError
mov ds:[di], bx ; store socket
;
; update the state
;
mov si, ds:[bx] ; ds:si = SocketInfo
mov ds:[si].SI_state, ISS_CONNECTING
;
; store the domain and remote port
;
mov ds:[si].SSI_connection.CE_domain, cx
popdw ds:[si].SSI_connection.CE_port
;
; allocate a semaphore
;
push bx
clr bx
call ThreadAllocSem
mov ds:[si].SI_waitSem, bx
pop bx
;
; check driver type
;
mov di, cx ; *ds:di = dom
mov di, ds:[di]
mov al, ds:[di].DI_driverType
cmp al, SDT_DATA
push ax
je data
;
; update the link reference count and get link handle
;
call LinkIncRefCount ; ax=link hdl
mov ds:[si].SSI_connection.CE_link, ax
jmp done
data:
;
; store socket into ConnectionInfo
;
add di, dx
mov ds:[di].CI_socket, bx
done:
pop ax ; ax = drv type
clc
abort:
.leave
ret
;
; handle errors
;
portError:
call SocketFreeQueue
error:
popdw bxbx ; discard SocketPort on stack
stc
jmp abort
SocketRegisterConnection endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
RemoveSocketFromPort
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Remove a socket from port's chunk array
CALLED BY: (INTERNAL) SocketClearConnection, SocketClose,
SocketPostDataAccept, SocketPostLinkAccept, SocketDataConnect
PASS: *ds:bx - SocketInfo
RETURN: ds:di - PortInfo
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 6/ 7/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
RemoveSocketFromPort proc far
uses ax,bx,cx,dx,si,di,bp,es
.enter
EC < mov si, bx >
EC < call ECCheckSocketLow >
;
; remove us from the port's array
;
mov si, ds:[bx]
mov si, ds:[si].SI_port ; *ds:di = PortInfo
mov di, ds:[si] ; ds:di = PortInfo
push di
mov cx, ds:[di].CAH_count ; # of connected skts
add di, ds:[di].CAH_offset ; first socket
mov ax, bx ; handle to locate
segmov es,ds
repne scasw ; search array
EC < ERROR_NE SOCKET_NOT_IN_PORT_ARRAY >
sub di,2 ; ds:di = elt to delete
call ChunkArrayDelete
done::
pop di ; ds:di = PortInfo
.leave
ret
RemoveSocketFromPort endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketClearConnection
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Remove failed connection indication from a socket
CALLED BY: (INTERNAL) SocketConnect
PASS: bx - socket
ds - control segment
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 5/23/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketClearConnection proc near
uses ax,bx,cx,dx,si,di,bp
.enter
;
; see if we need to send a cancel message
;
mov si, ds:[bx] ; ds:si = socket
cmp ds:[si].SI_state, ISS_CONNECTING
jne clear
;
; setup parameters for cancel
;
mov cx, ds:[si].SSI_connection.CE_domain
mov dx, ds:[si].SSI_connection.CE_link
call SocketFindLinkByHandle ; dx = link offset
sub sp, size PacketInfo
mov ax, bx ; save socket
call SetupPacketInfo
mov bx, ax ; restore socket
;
; send the packet
;
call SocketControlEndWrite
mov ax, CCO_CANCEL
call SendConnectionControl
call SocketControlStartWrite
mov si, ds:[bx] ; ds:si = SocketInfo
;
; remove reference to link
;
update::
mov si, ds:[bx] ; ds:si = socket
mov cx, ds:[si].SSI_connection.CE_domain
mov dx, ds:[si].SSI_connection.CE_link
call SocketFindLinkByHandle ; dx = link offset
call LinkDecRefCount
;
; remove data queue
;
call SocketFreeQueue
;
; clear the connection related fields
;
clear::
mov ds:[si].SI_state, ISS_UNCONNECTED
clr ds:[si].SSI_connection.CE_domain
clr ds:[si].SSI_connection.CE_link
clrdw ds:[si].SSI_connection.CE_port
;
; remove socket from port's array
;
call RemoveSocketFromPort
done::
.leave
ret
SocketClearConnection endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketCreateListenQueue
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Create a listen queue chunk
CALLED BY: (EXTERNAL) FreePortListenQueue, SocketAddLoadOnMsgMem,
SocketListenLow
PASS: *ds:si - PortInfo
cx - size of listen queue
RETURN: carry - set if error
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 11/21/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketCreateListenQueue proc far
uses ax,bx,cx,dx,si,di,bp
.enter
;
; allocate a listen queue
;
mov di, si ; *ds:di = PortInfo
mov bp, cx ; bp = queue length
mov bx, size ConnectionEndpoint ; element size
mov cx, size ListenQueue ; header size
clr si ; alloc new chunk
clr al ; no flags
call ChunkArrayCreate ; *ds:si = array
;
; record it in the port
;
mov di, ds:[di] ; ds:di = PortInfo
mov ds:[di].PI_listenQueue, si
;
; initialize the queue
;
mov si, ds:[si] ; ds:si = ListenQueue
EC < mov ds:[si].LQ_type, CCT_LISTEN_QUEUE
mov ds:[si].LQ_maxEntries, bp
.leave
ret
SocketCreateListenQueue endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketListenLow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set a socket to a listening state
CALLED BY: (INTERNAL) SocketListen
PASS: ds - control segment
es - dgroup
bx - Socket
cx - # of pending connections to permit
RETURN: carry set on error
ax - SocketError
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 5/10/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketListenLow proc near
uses bx,cx,dx,si,di,bp
.enter
;
; validate the socket handle
;
mov si, bx ; *ds:si = SocketInfo
EC < call ECCheckSocketLow >
;
; check delivery type
;
mov si, ds:[si] ; ds:si = SocketInfo
EC < cmp ds:[si].SI_delivery, SDT_DATAGRAM >
EC < ERROR_E ILLEGAL_OPERATION_ON_DATAGRAM_SOCKET >
;
; verify that the socket is bound
;
EC < tst ds:[si].SI_port >
EC < ERROR_Z SOCKET_NOT_BOUND >
;
; make sure the socket isn't busy
;
checkState::
cmp ds:[si].SI_state, ISS_UNCONNECTED
je derefPort
mov ax, SE_SOCKET_BUSY
stc
jmp done
;
; locate the port descriptor
;
derefPort:
mov si, ds:[si].SI_port ; *ds:si = PortInfo
EC < call ECCheckPortLow >
mov di, ds:[si] ; ds:di = PortInfo
;
; check for existing listeners
;
tst ds:[di].PI_listener
jz doListen
mov ax, SE_PORT_ALREADY_LISTENING
stc
jmp done
;
; create a listen queue
;
doListen:
tst ds:[di].PI_listenQueue
jnz queueExists
call SocketCreateListenQueue
mov ax, SE_OUT_OF_MEMORY
jc done
;
; register with the port
;
register:
mov di, ds:[si] ; ds:di = PortInfo
mov ds:[di].PI_listener, bx
;
; change the socket state and turn on interrupts
;
mov si, ds:[bx]
mov ds:[si].SI_state, ISS_LISTENING
ornf ds:[si].SI_flags, mask SF_INTERRUPTIBLE
;
; everything's ok
;
mov ax, SE_NO_ERROR
clc
done:
.leave
ret
;
; A listen queue already exists, presumably from
; LoadOnMsg. Put the new size into it.
;
queueExists:
mov di, ds:[di].PI_listenQueue
mov di, ds:[di]
mov ds:[di].LQ_maxEntries, cx
jmp register
SocketListenLow endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketCheckOpenState
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Determine the outcome of an open operation
CALLED BY: (INTERNAL) SocketConnect
PASS: *ds:bx = SocketInfo
RETURN: carry = set if error
ax = error code
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 6/ 7/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketCheckOpenState proc near
uses bx,cx,dx,si,di,bp
.enter
mov si, ds:[bx] ; ds:si = SocketInfo
;
; test for successful connection
;
mov ax, SE_NORMAL
cmp ds:[si].SI_state, ISS_CONNECTED
je success
;
; test for time out
;
mov ax, SE_TIMED_OUT
cmp ds:[si].SI_state, ISS_CONNECTING
stc
je done
;
; test for miscellaneous errors
;
mov ax, ds:[si].SSI_error
cmp ds:[si].SI_state, ISS_ERROR
stc
je done
;
; state is UNCONNECTED, LISTENING, ACCEPTING, or CLOSED
;
ERROR UNEXPECTED_SOCKET_STATE
success:
clc
done:
.leave
ret
SocketCheckOpenState endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketPreAccept
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Initiate acceptance of a connection
CALLED BY: (INTERNAL) SocketAccept
PASS: *ds:bx = SocketInfo
ss:bp = timeout info
RETURN: if error
carry set
ax = SocketError
else
carry clear
bx = new socket
cx = domain of connection
dx = link handle of connection
DESTROYED: nothing
SIDE EFFECTS:
allocates a wait sem in the socket
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 6/ 7/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketPreAccept proc near
uses si,di
origAX local word push ax
newSocket local lptr.SocketInfo
domain local lptr.DomainInfo
linkHan local word
.enter
;
; verify the delivery type
;
mov di, ds:[bx] ; ds:di = SocketInfo
EC < cmp ds:[di].SI_delivery, SDT_DATAGRAM >
EC < ERROR_E ILLEGAL_OPERATION_ON_DATAGRAM_SOCKET >
;
; verify that the socket is listening
;
cmp ds:[di].SI_state, ISS_LISTENING
mov ax, SE_SOCKET_NOT_LISTENING
stc
jne done ; check result of cmp
;
; make sure nobody else is accepting on the socket
;
tst ds:[di].SI_waitSem
mov ax, SE_SOCKET_BUSY
stc
jnz done ; check result of tst
;
; find the listen queue
;
mov si, ds:[di].SI_port ; *ds:si = PortInfo
mov si, ds:[si]
mov si, ds:[si].PI_listenQueue ; *ds:si = ListenQueue
;
; retrieve the first element
;
dequeue:
mov di, ds:[bx] ; ds:di = SocketInfo
test ds:[di].SI_flags, mask SF_INTERRUPT
jnz gotInterrupt
clr ax ; first element
call ChunkArrayElementToPtr ; di=ConnectionEndpoint
jnc accept
;
; allocate a semaphore
;
allocSem::
mov di, ds:[bx] ; ds:di = SocketInfo
EC < tst ds:[di].SI_waitSem >
EC < ERROR_NZ UNEXPECTED_SOCKET_STATE >
push bx ; save socket chunk
clr bx ; initial count 0
call ThreadAllocSem ; bx = semaphore
mov ds:[di].SI_waitSem, bx
;
; wait for a connection
;
semWait::
mov cx, ss:[bp]
call SocketControlEndWrite
call SocketPTimedSem
call SocketControlStartWrite
pastWait::
;
; check result of wait
;
pop bx ; *ds:bx = socket
call SocketClearSemaphore
jnc dequeue
mov ax, SE_TIMED_OUT
done:
;
; Preserve AX if not returning an error.
;
jc reallyDone
mov ax, ss:[origAX]
reallyDone:
.leave
ret
;
; the operation was interrupted
;
gotInterrupt:
and ds:[di].SI_flags, not mask SF_INTERRUPT
mov ax, SE_INTERRUPT
stc
jmp done
;
; couldn't get enough memory to complete the accept
;
queueFailed:
mov bx, si
call SocketFreeLow
createFailed:
pop si, bx
acceptFailed:
mov ax, SE_OUT_OF_MEMORY
stc
jmp done
;
; We have a connection to accept
;
; *ds:bx = old socket
; *ds:si = listen queue
; ds:di = ConnectionElement in queue
;
; Start by extending the port's array, so we can get out easily
; if that fails.
;
accept:
EC < call ECCheckConnectionEndpoint >
sub di, ds:[si] ; get offset to CE
push si, di
mov si, ds:[bx] ; ds:si = SocketInfo
mov si, ds:[si].SI_port
call ChunkArrayAppend ; ds:di = new element
pop si, di
jc acceptFailed
create::
push si, bx
mov bx, ds:[bx]
mov al, ds:[bx].SI_delivery
call SocketCreateLow
jc createFailed
mov ss:[newSocket], ax
add di, ds:[si] ; ds:di = CE from queue
mov si, ax
;
; create a data queue for the new socket
;
mov bx, si
call SocketAllocQueue
jc queueFailed
;
; copy ConnectionEndpoint from listen queue and pop the queue
;
EC < call ECCheckConnectionEndpoint >
mov si, ds:[si] ; ds:si= new SocketInfo
add si, offset SSI_connection ; si=ConnectionEndpoint
mov dx, ds:[di].CE_domain
mov ds:[si].CE_domain, dx
mov ss:[domain], dx
mov dx, ds:[di].CE_link ; dx=link
mov ds:[si].CE_link, dx
mov ss:[linkHan], dx
movdw ds:[si].CE_port, ds:[di].CE_port, cx
EC < push di >
EC < mov di,si >
EC < call ECCheckConnectionEndpoint >
EC < pop di >
pop si,bx ; bx=old skt, si=queue
call ChunkArrayDelete
;
; initialize the other fields of the new socket
;
mov si, ss:[newSocket]
mov si, ds:[si] ; ds:si= new SocketInfo
mov di, ds:[bx] ; ds:di= old SocketInfo
mov ds:[si].SI_state, ISS_ACCEPTING
segmov ds:[si].SI_port, ds:[di].SI_port, cx
;
; allocate a semaphore for new socket
; will be used to wait for the BEGIN packet
;
clr bx
call ThreadAllocSem ; bx = semaphore
mov ds:[si].SI_waitSem, bx
;
; insert socket in port array slot we allocated above
;
mov si, cx ; *ds:si = PortInfo
mov cx, CA_LAST_ELEMENT
call ChunkArrayElementToPtr ; ds:di = element
segmov ds:[di], ss:[newSocket], ax ; nptr to new socket
;
; update socket count in port
;
mov di, ds:[si]
inc ds:[di].PI_numActive
;
; return new socket to user
;
mov bx,ss:[newSocket] ; bx = socket
mov cx,ss:[domain] ; cx = domain
mov dx,ss:[linkHan]
;
; validate the socket one more time
;
EC < call ECCheckDomainLow >
EC < mov di, ds:[bx] >
EC < add di, offset SSI_connection >
EC < call ECCheckConnectionEndpoint >
clc
jmp done
SocketPreAccept endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketPostLinkAccept
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Clean up after accepting
CALLED BY: (INTERNAL) SocketAccept
PASS: *ds:bx - SocketInfo
RETURN: carry - set to retry accept
if connection established
carry clear
ax - SE_NORMAL
if the connection was canceled
carry set
bx - master socket
if we aren't connected for some other reason
carry clear
ax - SocketError
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 6/ 7/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketPostLinkAccept proc near
uses bx,cx,dx,si,di,bp
.enter
;
; see if we connected
;
mov si, ds:[bx]
cmp ds:[si].SI_state, ISS_CONNECTED
je success
;
; states NOT_CONNECTED, LISTENING, ACCEPTING, OPENING,
; SEND_CLOSED, and CLOSED are all illegal here
;
EC < cmp ds:[si].SI_state, ISS_ERROR >
EC < ERROR_NE UNEXPECTED_SOCKET_STATE >
;
; we didn't get a connection, so delete the temporary socket
;
mov cx, ds:[si].SSI_error ; remember error code
call RemoveSocketFromPort ; ds:di = PortInfo
mov ax, bx ; *ds:ax = socket
call SocketFreeLow
;
; if the error isn't a cancelation, abort the accept
;
mov ax,cx ; ax = SocketError
cmp ax, SE_CONNECTION_CANCELED
clc
jne done
;
; if it was a cancelation, tell Accept to try again
;
stc
jmp done
;
; we have a connection
;
success:
mov ax, SE_NORMAL
clc
done:
.leave
ret
SocketPostLinkAccept endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FreeListenQueue
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Free a listen queue
CALLED BY: (INTERNAL) SocketClose
PASS: *ds:bx = SocketInfo of listening socket
RETURN: ds = control segment (possibly moved)
DESTROYED: nothing
SIDE EFFECTS: sends CCO_CANCEL for all entries in queue
PSEUDO CODE/STRATEGY:
The listen related state of the port is cleared before we start
canceling connections. This prevents somebody from seeing and
being confused by the partially closed listen queue and socket.
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 8/18/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
FreeListenQueue proc near
uses si
.enter
;
; get pointer to socket and port
;
mov si, ds:[bx]
mov di, ds:[si].SI_port
;
; validate stuff
;
EC < cmp ds:[si].SI_state, ISS_LISTENING >
EC < ERROR_NE UNEXPECTED_SOCKET_STATE >
EC < mov si, ds:[di] >
EC < cmp ds:[si].PI_listener, bx >
EC < ERROR_NE CORRUPT_PORT >
EC < tst ds:[si].PI_listenQueue >
EC < ERROR_Z CORRUPT_PORT >
call FreePortListenQueue
.leave
ret
FreeListenQueue endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FreePortListenQueue
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Free the listen queue associated with a port, canceling
all connections pending for it.
CALLED BY: (EXTERNAL) ConnectionOpen, FreeListenQueue,
SocketRemoveLoadOnMsgMem
PASS: *ds:di = PortInfo (write access)
RETURN: ds = fixed up
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/27/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
FreePortListenQueue proc far
uses ax,bx,cx,dx,si,di,bp
.enter
Assert writeControl, ds
;
; stop listening
;
; This will prevent anyone else from messing with the listen
; queue while we are shutting it down.
;
mov si, di ; *ds:si <- PortInfo, for
; SocketCreateListenQueue...
mov di, ds:[si]
clr ds:[di].PI_listener
clr bx
xchg bx, ds:[di].PI_listenQueue
;
; if there is load info, create a new listen queue now
;
tst ds:[di].PI_loadInfo
jz doEnum
mov cx, LOM_LISTEN_QUEUE_SIZE
call SocketCreateListenQueue
;
; enumerate the listen queue to refuse the connections
;
doEnum:
mov di, ds:[si]
movdw axdx, ds:[di].PI_number
mov si, bx ; *ds:si <- listen queue
mov bx,cs
mov di,offset FreeListenQueueCallback
call ChunkArrayEnum
;
; free the listen queue
;
mov ax, si
call LMemFree
.leave
ret
FreePortListenQueue endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FreeListenQueueCallback
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: callback for FreeListenQueue
sends CCO_REFUSE and decrements link ref count
CALLED BY: (EXTERNAL) FreePortListenQueue via ChunkArrayEnum
PASS: ds:di - ConnectionEndpoint
axdx - source port
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
send CCO_CLOSE
dec link count
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 8/22/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
FreeListenQueueCallback proc far
uses ax,dx,bp
.enter
;
; get information from ConnectionEndpoint
;
sub sp, size PacketInfo
mov bp,sp
movdw ss:[bp].PI_srcPort, axdx
movdw ss:[bp].PI_destPort, ds:[di].CE_port, ax
segmov ss:[bp].PI_link, ds:[di].CE_link, dx
;
; get information from domain
;
mov bx, ds:[di].CE_domain
mov di, ds:[bx]
segmov ss:[bp].PI_driverType, ds:[di].DI_driverType, al
segmov ss:[bp].PI_client, ds:[di].DI_client,ax
movdw ss:[bp].PI_entry, ds:[di].DI_entry, ax
mov al, ds:[di].DI_seqHeaderSize
clr ah
mov ss:[bp].PI_headerSize, ax
;
; check driver type
;
cmp ss:[bp].PI_driverType, SDT_DATA
je data
;
; update link but don't close it yet
;
link::
mov cx,bx ; cx = domain handle
call SocketFindLinkByHandle ; dx = link offset
jc abort
call LinkDecRefCountNoClose
;
; send a REFUSE packet
;
; this should prompt the other side to close the link
;
call SocketControlEndWrite
mov ax, CCO_REFUSE
call SendConnectionControl
call SocketControlStartWrite
jmp done
;
; if the link is gone, clean up and exit
;
abort:
EC < WARNING REDUNDENT_CLOSE >
add sp, size PacketInfo
jmp done
;
; notify driver that we don't want this connection
;
data:
call SocketControlEndWrite
mov di, DR_SOCKET_REJECT
mov ax, ss:[bp].PI_link
lea bp, ss:[bp].PI_entry
call {fptr}ss:[bp]
;
; delete connection
;
call SocketControlStartWrite
mov ax, ss:[bp].PI_link
add sp, size PacketInfo
clr dx
call SocketRemoveConnection
;
; continue enumeration
;
done:
clc
.leave
ret
FreeListenQueueCallback endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketFreeLow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Free a socket chunk and possibly the port chunk
CALLED BY: (INTERNAL) SocketClose, SocketPostLinkAccept
PASS: *ds:bx - SocketInfo
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 8/22/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketFreeLow proc far
uses ax,bx,cx,dx,si,di,bp,es
.enter
;
; free the permanent semaphore
;
mov si, ds:[bx]
push bx
mov bx, ds:[si].SI_semSem
call ThreadFreeSem
pop bx
;
; free data queue if needed
;
call SocketFreeQueue
;
; remember the port
;
savePort::
mov dl, ds:[si].SI_delivery
mov si, ds:[si].SI_port
;
; free the socket
;
mov ax,bx
call LMemFree
;
; remove it from the socket array
;
push si
segmov es, ds
mov si, offset SocketSocketArray
mov di, ds:[si]
mov cx, ds:[di].CAH_count
add di, ds:[di].CAH_offset
repne scasw
EC < ERROR_NE SOCKET_NOT_IN_SOCKET_ARRAY >
dec di
dec di
call ChunkArrayDelete
pop si
;
; unbind the socket
;
unbind::
tst si
jz done ; jump if not bound
mov di, ds:[si] ; ds:di = PortInfo
cmp dl, SDT_DATAGRAM
je datagram
;
; decrement socket count in port
;
dec ds:[di].PI_numActive
EC < ERROR_S CORRUPT_PORT >
jmp freePort
;
; clear PI_dgram
;
datagram:
EC < cmp ds:[di].PI_dgram, ax >
EC < ERROR_NE CORRUPT_SOCKET >
clr ds:[di].PI_dgram
freePort:
call SocketFreePort
done:
.leave
ret
SocketFreeLow endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketFreePort
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Free a port, if it is not in use
CALLED BY: (EXTERNAL) SocketAddLoadOnMsgMem, SocketFreeLow,
SocketRemoveLoadOnMsgMem
PASS: *ds:si - PortInfo
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 11/21/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketFreePort proc far
uses ax,bx,dx,si,di
.enter
;
; check counters in port
;
mov di, ds:[si] ; ds:di = PortInfo
tst ds:[di].PI_numActive
jnz done ; sequenced sockets exist
tst ds:[di].PI_dgram
jnz done ; datagram socket exists
tst ds:[di].PI_loadInfo
jnz done ; LoadOnMsg exists
;
; find port array entry for this port
;
push si
mov si, offset SocketPortArray
movdw axbx, ds:[di].PI_number
mov dx, ds:[di].PI_restriction
call SocketFindPort ; ds:di = PortArrayEntry
EC < ERROR_C CORRUPT_PORT >
pop ax ; *ds:ax = PortInfo
;
; free the PortArrayEntry and the PortInfo
;
call ChunkArrayDelete
call LMemFree
;
; clean up the domain, if any
;
tst dx
jz done
mov si, dx
;
; we no longer free domain chunks, so the bind count is
; irrelevant, and doing a SocketRemoveDomain is dangerous
;
if 0
mov di, ds:[si]
dec ds:[di].DI_bindCount
jnz done
call SocketRemoveDomain
endif
done:
.leave
ret
SocketFreePort endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketCheckReadySetup
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Setup to wait on sockets
CALLED BY: (INTERNAL) SocketCheckReady
PASS: es:di - array of SocketCheckRequest
es - control segment
cx - number of sockets to check
dx - segment of control block
bx - semaphore
ss:si - address where sem handle will be written
RETURN: carry - set on error
if carry set:
ax - SocketError
cx - socket causing error
if carry clear:
cx - socket meeting condition (0 if none)
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 8/31/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketCheckReadySetup proc near
uses bx,dx,si,di,bp
sem local hptr push bx
whichPtr local word push si
busy local word
error local word
ForceRef sem
ForceRef whichPtr
.enter
;
; note any busy or error conditions
; see if any socket is already in desired condition
;
clr ss:[busy]
clr ss:[error]
pass1:
mov si, es:[di].SCR_socket
mov bl, es:[di].SCR_condition
add di, size SocketCheckRequest
call SocketCheckReadyHere
jc ready ; socket is ready
loop pass1
;
; no socket was discovered to be ready
; return busy or error if appropriate, otherwise on to pass 2
;
mov cx,ss:[error]
jcxz notError
mov ax, SE_IMPROPER_CONDITION
stc
jmp done
notError:
mov cx, ss:[busy]
jcxz notBusy
mov ax, SE_SOCKET_BUSY
stc
jmp done
;
; we didn't find a ready socket, but didn't find any errors
; either
;
notBusy:
clc
jmp done
;
; if we found a ready socket, return it now
;
ready:
mov cx, si
clc
done:
.leave
ret
SocketCheckReadySetup endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketCheckReadyHere
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: See if a particular socket is ready
CALLED BY: (INTERNAL) SocketCheckReadySetup
PASS: ds - control segment
si - socket
bl - SocketCondition
RETURN:
carry - set if socket meets condition
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 9/ 1/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketCheckReadyHere proc near
uses ax,bx,cx,dx,si,di,bp
.enter inherit SocketCheckReadySetup
;
; validate
;
EC < Assert etype, bl, SocketCondition >
EC < call ECCheckSocketLow >
;
; setup loop
;
mov di, ds:[si] ; ds:di = SocketInfo
clr ax
clr bh
shl bl
jmp cs:[jumpTable][bx]
;
; see if there is urgent data
;
checkUrgent:
cmp ds:[di].SI_state, ISS_CONNECTED
jne invalidState
tst ds:[di].SSI_urgentSize
jnz socketOK
jmp checkExceptBusy
;
; see if we can wait for an exception
;
checkException:
;
; see if the exception semaphore is busy
;
checkExceptBusy:
tst_clc ds:[di].SI_exceptSem
jz exceptNotBusy
mov ss:[busy], si
jmp done
exceptNotBusy:
segmov ds:[di].SI_exceptSem, ss:[sem], ax
segmov ds:[di].SI_exceptPtr.offset, ss:[whichPtr], ax
mov ds:[di].SI_exceptPtr.segment, ss
jmp done
;
; see if an accept operation would block
;
checkAccept:
cmp ds:[di].SI_state, ISS_LISTENING
jne invalidState
mov bx, ds:[di].SI_port
mov bx, ds:[bx]
mov bx, ds:[bx].PI_listenQueue
mov bx, ds:[bx]
tst_clc ds:[bx].CAH_count
jz checkBusy
jmp socketOK
;
; see if a write operation would block
;
checkWrite:
cmp ds:[di].SI_state, ISS_CONNECTED
je socketOK
;
; the requested operation is not valid given the socket state
;
invalidState:
mov ss:[error], si
clc
jmp done
;
; see if a read operation would block
;
checkRead:
cmp ds:[di].SI_state, ISS_CONNECTED
jne invalidState
test ds:[di].SI_flags, mask SF_RECV_ENABLE
jz socketOK
test ds:[di].SI_flags, mask SF_FAILED
jnz socketOK
;
; the read operation will block if there is no data
;
readStateOK::
call SocketCheckQueue
jc checkBusy
;
; the socket meets the requested condition
;
socketOK:
stc
jmp done
;
; the condition is valid, but the socket does not yet meet
; the specified condition, so see if it's busy
;
checkBusy:
tst_clc ds:[di].SI_waitSem
jz notBusy
mov ss:[busy], si
jmp done
notBusy:
segmov ds:[di].SI_waitSem, ss:[sem], ax
segmov ds:[di].SI_waitPtr.offset, ss:[whichPtr], ax
mov ds:[di].SI_waitPtr.segment, ss
done:
.leave
ret
jumpTable nptr \
checkRead,
checkWrite,
checkAccept,
checkException,
checkUrgent
SocketCheckReadyHere endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketCheckReadyCleanup
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: remove semaphore from all sockets currently containing it
CALLED BY: (INTERNAL) SocketCheckReady
PASS: es:di - array of SocketCheckRequest
ax - length of array
bx - semaphore
cx - socket to look for
RETURN: cx - index of socket
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
don't both looking at the SocketCondition, just check both
semaphores
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 12/ 3/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketCheckReadyCleanup proc near
uses ax,bx,dx,si,di
.enter
;
; setup for loop
;
xchg ax,cx
mov dx,-1
jcxz done
push cx,di
;
; compare next socket to target of search
; remember index in dx if it matches
;
top:
mov si, es:[di].SCR_socket
cmp ax,si
jne checkWait
mov dx,cx
;
; see if we need to clear wait sem
;
checkWait:
mov si, ds:[si]
cmp ds:[si].SI_waitSem, bx
jne checkExcept
clr ds:[si].SI_waitSem
clrdw ds:[si].SI_waitPtr
;
; see if we need to clear except sem
;
checkExcept:
cmp ds:[si].SI_exceptSem, bx
jne next
clr ds:[si].SI_exceptSem
clrdw ds:[si].SI_exceptPtr
;
; go to next socket
;
next:
add di, size SocketCheckRequest
loop top
;
; convert loop index to array index
;
pop cx,di ; cx = original loop bound
cmp dx,-1 ; see if dx still has original value
je noMatch
sub cx,dx ; cx = index of matching socket
;
; make sure we really have the match we think we have
;
.assert (size SocketCheckRequest eq 4)
EC < mov bx,cx >
EC < shl bx >
EC < shl bx >
EC < cmp ax, es:[di][bx] >
EC < ERROR_NE SOCKET_NOT_IN_CHECK_ARRAY >
done:
.leave
ret
;
; we didn't find the socket we were looking for
; this is permissible only if we weren't really looking
;
noMatch:
EC < tst ax >
EC < ERROR_NZ SOCKET_NOT_IN_CHECK_ARRAY >
mov cx,-1
jmp done
SocketCheckReadyCleanup endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketPostDataAccept
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Accept a connection from a data driver
CALLED BY: (INTERNAL) SocketAccept
PASS: bx = socket
cx = domain of connection
dx = connection handle of connection
ss:ax = timeout
ds = control segment
RETURN: if connection timed out:
carry set
if connection succeeds:
carry clear
ax = SE_NORMAL
if connection failed for some other reason:
carry clear
ax = SocketError
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 11/ 8/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketPostDataAccept proc near
uses bx,cx,dx,si,di,bp
entry local fptr.far
.enter
;
; get the driver entry point
;
push ax
mov si, cx ; *ds:si = domain
mov di, ds:[si]
movdw ss:[entry], ds:[di].DI_entry, ax
;
; update the domain with the socket handle NOW so we're prepared in
; case the driver sends us some data before we come back from calling
; the driver.
;
mov ax, dx ; ax = conn handle
call SocketFindLinkByHandle ; dx = offset
add di, dx ; ds:di = ConnectionInfo
mov ds:[di].CI_socket, bx
mov dx, ax ; dx = conn handle
;
; compute timeout
;
pop cx
call SocketGetTimeout ; cx = timeout
;
; call the driver
;
callDriver::
push bx
call SocketControlEndWrite
mov di, DR_SOCKET_ATTACH
mov ax, dx ; ax = conn handle
lea bx, ss:[entry]
call {fptr}ss:[bx]
call SocketControlStartWrite
pop bx ; *ds:bx = socket
jnc success
;
; we didn't get a connection, so delete the temporary socket
;
failed::
push ax ; remember error
call RemoveSocketFromPort ; ds:di = PortInfo
mov ax, bx ; *ds:ax = socket
call LMemFree
pop ax
;
; for some errors, we simply try again
;
cmp al, SDE_CONNECTION_TIMEOUT
jne notTimeout
stc
jmp done
notTimeout:
;
; for everything else, abort the accept
; (note that if operands to cmp are equal, carry will be clear)
;
cmp al, SDE_CONNECTION_REFUSED
jne notRefused
mov al, SE_CONNECTION_REFUSED
jmp done
notRefused:
cmp al, SDE_INSUFFICIENT_MEMORY
jne notMemory
mov al, SE_OUT_OF_MEMORY
jmp done
;
; If it's an error we didn't know about when this code was written,
; return the misc error code. Otherwise, anything not listed
; above is not supposed to be possible.
;
notMemory:
mov ah,al
cmp al, SocketDrError
jae miscError ; jae=jnc
mov al, SE_INTERNAL_ERROR
clc
jmp done
miscError:
mov al, SE_CONNECTION_ERROR
jmp done
;
; we have a connection, so update connection info
;
; bx = socket
; si = domain
;
success:
mov cx,si ; cx = domain
mov di, ds:[bx] ; ds:di=socket
mov ds:[di].SI_state, ISS_CONNECTED
ornf ds:[di].SI_flags, mask SF_SEND_ENABLE or mask SF_RECV_ENABLE or mask SF_INTERRUPTIBLE
mov dx, ds:[di].SSI_connection.CE_link ; dx = con hdl
;
; got a connection
;
mov ax, SE_NORMAL
clc
done:
.leave
ret
SocketPostDataAccept endp
ApiCode ends
ExtraApiCode segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SetupDatagramInfo
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Copy information about a packet onto the stack
CALLED BY: (INTERNAL) SocketSend
PASS: *ds:bx - SocketInfo
es:di - SocketAddress
dx - domain handle
ON STACK
uninitialized PacketInfo
RETURN: PacketInfo filled in (args not popped)
es:di - address to use
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 6/ 5/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SetupDatagramInfo proc near info:PacketInfo
uses ax,si,di
.enter
;
; get information from the port
;
mov si, ds:[bx] ; ds:si = SocketInfo
mov di, ds:[si].SI_port
mov di, ds:[di] ; ds:di = PortInfo
movdw ss:[info].PI_srcPort, ds:[di].PI_number, ax
;
; get information from the domain
;
mov di, dx
mov di, ds:[di]
segmov ss:[info].PI_driverType,ds:[di].DI_driverType, al
segmov ss:[info].PI_client, ds:[di].DI_client, ax
movdw ss:[info].PI_entry, ds:[di].DI_entry, ax
mov al, ds:[di].DI_dgramHeaderSize
clr ah
mov ss:[info].PI_headerSize, ax
.leave
ret ; DO NOT POP ARGS
SetupDatagramInfo endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketSetSendFlag
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set the SF_SENDING flag
CALLED BY: SocketSend
PASS: *ds:bx - SocketInfo
RETURN: carry set if error
ax - SocketError (SE_SOCKET_BUSY)
carry clear otherwise
ax - preserved
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 7/18/96 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketSetSendFlag proc near
uses dx, si
.enter
EC < mov si, bx >
EC < call ECCheckSocketLow >
EC < call ECEnsureSocketNotClosing >
;
; check for interrupt
;
mov si, ds:[bx]
mov dx, ds:[si].SI_flags
and ds:[si].SI_flags, not mask SF_SINTERRUPT
test dx, mask SF_SINTERRUPT
jnz interrupt
;
; check for busy
;
or ds:[si].SI_flags, mask SF_SENDING
test dx, mask SF_SENDING
jz done
mov ax, SE_SOCKET_BUSY
jmp gotError
interrupt:
mov ax, SE_INTERRUPT
gotError:
stc
done:
.leave
ret
SocketSetSendFlag endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketClearSendFlag
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Clear the SF_SENDING flag
CALLED BY: SocketSend
PASS: bx - socket
control block unlocked
RETURN: nothing
DESTROYED: nothing (flags preserved)
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 7/18/96 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketClearSendFlag proc near
uses ds, si
pushf
.enter
call SocketControlStartWrite
mov si, ds:[bx]
and ds:[si].SI_flags, not mask SF_SENDING
call SocketControlEndWrite
.leave
popf
ret
SocketClearSendFlag endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketGetLink
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get the domain and link a socket is using
CALLED BY: (INTERNAL) SocketSend
PASS: *ds:bx - SocketInfo
RETURN: cx - domain
dx - offset to link
carry - set on error
ax - SocketError if error, preserved otherwise
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 6/ 7/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketGetLink proc near
uses si
.enter
;
; socket must be connected
;
mov si, ds:[bx]
cmp ds:[si].SI_state, ISS_CONNECTED
jne notConnected
mov ax, ds:[si].SI_flags
test ax, mask SF_FAILED
jnz failed
test ax, mask SF_SEND_ENABLE
jz closed
;
; search for the link
;
mov cx, ds:[si].SSI_connection.CE_domain
mov dx, ds:[si].SSI_connection.CE_link
call SocketFindLinkByHandle
jc linkNotFound
done:
.leave
ret
notConnected:
mov ax, SE_SOCKET_NOT_CONNECTED
stc
jmp done
failed:
mov ax, ds:[si].SSI_error
stc
jmp done
closed:
mov ax, SE_CONNECTION_CLOSED
stc
jmp done
linkNotFound:
ornf ds:[si].SI_flags, mask SF_FAILED
mov ax, SE_LINK_FAILED
stc
jmp done
SocketGetLink endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketGetAddress
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get default address for a datagram socket
CALLED BY: (INTERNAL) SocketSend
PASS: *ds:bx - SocketInfo
RETURN: es:di - SocketAddress (port and adress initialized)
dx - domain
carry set if error
ax - SocketError
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 6/ 7/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketGetAddress proc near
uses bx,cx,si
.enter
;
; verify that socket is connected
;
EC < mov si,bx >
EC < call ECCheckSocketLow >
mov si, ds:[bx]
cmp ds:[si].SI_state, ISS_CONNECTED
jne notConnected
;
; get domain handle
;
mov dx, ds:[si].DSI_domain
;
; compute size of output
;
mov ax, size SocketAddress+2
add ax, ds:[si].DSI_addressSize
mov cx, ALLOC_DYNAMIC_LOCK
;
; allocate a block and store handle in block
;
call MemAlloc
jc allocFailed
mov es,ax
mov es:0, bx
;
; initialize the address
;
; since the address starts at offset 2, we need to add 2 to
; all of the SA field offsets
;
clrdw es:[SA_domain+2]
movdw es:[SA_port+2], ds:[si].DSI_port, ax
segmov es:[SA_addressSize+2], ds:[si].DSI_addressSize, cx
lea di, es:[SA_address+2]
add si, offset DSI_address
EC < call ECCheckMovsb >
rep movsb
;
; return pointer to address
;
mov di,2
clc
done:
.leave
ret
notConnected:
mov ax, SE_SOCKET_NOT_CONNECTED
stc
jmp done
allocFailed:
mov ax, SE_OUT_OF_MEMORY
stc
jmp done
SocketGetAddress endp
ExtraApiCode ends
InfoApiCode segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketGetDomainName
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get the domain name a socket is connect over
CALLED BY: (INTERNAL) SocketGetPeerName, SocketGetSocketName
PASS: *ds:si - SocketInfo
es:di - SocketAddress
RETURN: ax = SocketError (carry set if error)
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 12/18/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketGetDomainName proc near
uses bx,cx,dx,si,di,bp
.enter
;
; verify that we are connected
;
mov si, ds:[si]
mov ax, SE_SOCKET_NOT_CONNECTED
cmp ds:[si].SI_state, ISS_CONNECTED
stc
jne done
;
; find the domain and check name size
;
mov bx, ds:[si].SSI_connection.CE_domain
mov si, ds:[bx]
mov cx, es:[di].SA_domainSize
jcxz pastCopy
dec cx ; because DI_nameSize doesn't include
; null
cmp cx, ds:[si].DI_nameSize
jbe gotSize
mov cx, ds:[si].DI_nameSize
gotSize:
inc cx ; restore space for null
;
; copy the name
;
push es,di,si
lea si, ds:[si].DI_name
movdw esdi, es:[di].SA_domain
EC < call ECCheckMovsb >
rep movsb
pop es,di,si
pastCopy:
;
; get the size to return
;
mov cx, ds:[si].DI_nameSize
inc cx ; include null
mov es:[di].SA_domainSize, cx
clc
mov ax, SE_NORMAL
done:
.leave
ret
SocketGetDomainName endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketQueryAddress
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Query a driver for either the local or remote name
CALLED BY: (INTERNAL) SocketGetPeerName, SocketGetSocketName
PASS: *ds:si - SocketInfo (locked shared)
es:di - SocketAddress
ax - SGIT_LOCAL_ADDR or SGIT_REMOTE_ADDR
RETURN: carry set on error
ax - SocketError
ds - control segment (locked exclusive)
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 12/18/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketQueryAddress proc near
uses bx,cx,dx,si,di,bp,es
.enter
;
; verify that we are connected
;
mov si, ds:[si]
cmp ds:[si].SI_state, ISS_CONNECTED
jne notConnected
test ds:[si].SI_flags, mask SF_SEND_ENABLE
jz closed
;
; find the domain and link
;
mov cx, ds:[si].SSI_connection.CE_link
mov si, ds:[si].SSI_connection.CE_domain
push si ; save domain handle
call SocketGrabMiscLock
;
; get the entry point
;
getEntry::
push es,di ; save address buf
segxchg ds,es
mov si, es:[si] ; es:si = DomainInfo
pushdw es:[si].DI_entry
mov bp, sp ; ss:[bp] = entry point (fptr)
;
; call the driver
;
lea bx, ds:[di].SA_address ; ds:bx = addr buffer
mov dx, ds:[di].SA_addressSize ; dx = size of buffer
mov di, DR_SOCKET_GET_INFO
call SocketControlEndRead
call {fptr}ss:[bp] ; ax = address size
popdw bpbp ; pop entry point fptr
;
; release the misc lock
; do not disturb the flags
;
pastDriver::
call SocketControlStartWrite
pop es,di ; es:di = SocketAddress
pop si
call SocketReleaseMiscLock
;
; handle any errors from the driver call above
;
jnc checkSize
mov ax, SE_INFO_NOT_AVAILABLE
jmp done
checkSize:
xchg es:[di].SA_addressSize, ax
cmp ax, es:[di].SA_addressSize
mov ax, SE_BUFFER_TOO_SMALL
jc done ; jc=jb
mov ax, SE_NORMAL
done:
.leave
ret
notConnected:
mov ax, SE_SOCKET_NOT_CONNECTED
stc
jmp done
closed:
mov ax, SE_SOCKET_CLOSED
stc
jmp done
SocketQueryAddress endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketQueryMediumAddress
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Common code for SocketCheckMediumConnection and
SocketGetMediumAddress
CALLED BY: SocketCheckMediumConnection, SocketGetMediumAddress
PASS: ds:si = domain name (null-terminated string)
es:di = buffer for address, large enough to accomodate
the expected address.
cx = size of address buffer, in bytes.
dx:ax = MediumAndUnit
bx = SocketGetInfoType
RETURN: carry set on error (no connection exists over the unit
of the medium):
ax = SocketError
SE_CONNECTION_ERROR
carry clear if connection exists:
es:di = filled in with the address. If the address
is larger than the size of the buffer,
then only the beginning of the address, up
to the buffer size, will be copied in.
cx = number of bytes in address returned. Caller
should check if value returned in cx is
greater than the value passed in. If so,
it may be necessary to call this function
again, with a larger address buffer.
ax = SE_NORMAL
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
CL 1/18/95 Initial version
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 11/ 7/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketQueryMediumAddress proc near
domainName local fptr.char push ds, si
addrBuffer local fptr push es, di
addrBufferSize local word push cx
mediumAndUnit local fptr.MediumAndUnit push dx, ax
queryType local word push bx
domain local lptr
driverEntry local fptr.far
uses bx,dx,ds,si,di,ds
.enter
;
; find and lock driver
;
push bp
call SocketControlStartRead ;ds = control segment
movdw dxbp, domainName ;dx:bp = domain name
call SocketFindDomain ;bx = domain handle
pop bp
jc noConnection1 ;return "no connection"
mov ss:[domain], bx
mov si, bx ;*ds:si = DomainInfo
call SocketGrabMiscLock
;
; Get driver entry point
;
mov di, ds:[si] ;ds:di = DomainInfo
movdw ss:[driverEntry], ds:[di].DI_entry, ax
call SocketControlEndRead
;
; query the driver
;
mov di, DR_SOCKET_GET_INFO
mov cx, ss:[addrBufferSize]
movdw dssi, ss:[addrBuffer]
movdw dxbx, ss:[mediumAndUnit]
mov ax, ss:[queryType]
call ss:[driverEntry] ;cx = actual size of address
;
; release the driver. Flags preserved throughout.
;
call SocketControlStartWrite ;ds = control segment
mov si, ss:[domain] ;*ds:si = DomainInfo
call SocketReleaseMiscLock
call SocketControlEndWrite
;
; return answer
;
jc noConnection2
mov ax, SE_NORMAL
exit:
.leave
ret
noConnection1:
WARNING DOMAIN_NOT_FOUND
call SocketControlEndRead ; unlock SocketControl
noConnection2:
mov ax, SE_CONNECTION_ERROR
jmp exit
SocketQueryMediumAddress endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketGetRemotePort
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get remote port number
CALLED BY: (INTERNAL) SocketGetPeerName
PASS: *ds:si - SocketInfo must be connected
es:di - SocketAddress
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 12/18/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketGetRemotePort proc near
uses ax,si
.enter
mov si, ds:[si]
movdw es:[di].SA_port, ds:[si].SSI_connection.CE_port, ax
.leave
ret
SocketGetRemotePort endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketGetLocalPort
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get port this socket is bound to
CALLED BY: (INTERNAL) SocketGetSocketName
PASS: *ds:si - SocketInfo must be bound
es:di - SocketAddress
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 12/18/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketGetLocalPort proc near
uses ax,si
.enter
mov si, ds:[si]
mov si, ds:[si].SI_port
mov si, ds:[si]
movdw es:[di].SA_port, ds:[si].PI_number, ax
.leave
ret
SocketGetLocalPort endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SocketPassOption
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Pass an option through to the driver
CALLED BY: (INTERNAL) SocketSetSocketOption
PASS: ds:si - SocketInfo
ax,cx - parameters to DR_SOCKET_SET_OPTION
RETURN: ds - socket control segment (possibly moved)
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
No attempt is made to ensure that the socket will still be open
when the request is passed to the driver. The driver, however,
will disregard
REVISION HISTORY:
Name Date Description
---- ---- -----------
EW 7/20/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SocketPassOption proc near
uses bx,si,di,bp
.enter
;
; verify that we are connected
;
cmp ds:[si].SI_state, ISS_CONNECTED
jne skip
;
; find the domain and link
;
mov bx, ds:[si].SSI_connection.CE_link
mov si, ds:[si].SSI_connection.CE_domain
tst si
jz skip
mov di, ds:[si]
cmp ds:[di].DI_driverType, SDT_DATA
jne skip
call SocketGrabMiscLock
;
; get the entry point
;
getEntry::
pushdw ds:[di].DI_entry
mov bp, sp ; ss:[bp] = entry point (fptr)
;
; call the driver
;
mov di, DR_SOCKET_SET_OPTION
call SocketControlEndRead
call {fptr}ss:[bp]
popdw bpbp ; pop entry point fptr
;
; release the misc lock
;
pastDriver::
call SocketControlStartWrite
call SocketReleaseMiscLock
skip:
.leave
ret
SocketPassOption endp
InfoApiCode ends
|
; A027940: a(n) = T(2*n, n+4), T given by A027935.
; Submitted by Christian Krause
; 1,46,551,3785,18955,77533,276408,895103,2708322,7811510,21791338,59419294,159571139,424302452,1121168305,2951121095,7749900701,20324325571,53259796514,139506540045,365330860180,956582678652,2504546934692,6557230277964,17167369784405,44945172450762,117668525005579,308060883894229,806514735473151,2111484086661305,5527938476757852,14472332522305195,37889060539925910,99194850870040146,259695494225254830,679891634411892234,1779979412146269367,4660046605782095152,12200160409676474933
mul $0,2
seq $0,53308 ; Partial sums of A053296.
|
;=================================================
;=================================================
;
; Math lib tables
;
;-------------------------------------------------
; Load into $A000
;
.define SquaresOverFour_0_512 0, 0, 1, 2, 4, 6, 9, 12, 16, 20, 25, 30, 36, 42, 49, 56, 64, 72, 81, 90, 100, 110, 121, 132, 144, 156, 169, 182, 196, 210, 225, 240, 256, 272, 289, 306, 324, 342, 361, 380, 400, 420, 441, 462, 484, 506, 529, 552, 576, 600, 625, 650, 676, 702, 729, 756, 784, 812, 841, 870, 900, 930, 961, 992, 1024, 1056, 1089, 1122, 1156, 1190, 1225, 1260, 1296, 1332, 1369, 1406, 1444, 1482, 1521, 1560, 1600, 1640, 1681, 1722, 1764, 1806, 1849, 1892, 1936, 1980, 2025, 2070, 2116, 2162, 2209, 2256, 2304, 2352, 2401, 2450, 2500, 2550, 2601, 2652, 2704, 2756, 2809, 2862, 2916, 2970, 3025, 3080, 3136, 3192, 3249, 3306, 3364, 3422, 3481, 3540, 3600, 3660, 3721, 3782, 3844, 3906, 3969, 4032, 4096, 4160, 4225, 4290, 4356, 4422, 4489, 4556, 4624, 4692, 4761, 4830, 4900, 4970, 5041, 5112, 5184, 5256, 5329, 5402, 5476, 5550, 5625, 5700, 5776, 5852, 5929, 6006, 6084, 6162, 6241, 6320, 6400, 6480, 6561, 6642, 6724, 6806, 6889, 6972, 7056, 7140, 7225, 7310, 7396, 7482, 7569, 7656, 7744, 7832, 7921, 8010, 8100, 8190, 8281, 8372, 8464, 8556, 8649, 8742, 8836, 8930, 9025, 9120, 9216, 9312, 9409, 9506, 9604, 9702, 9801, 9900, 10000, 10100, 10201, 10302, 10404, 10506, 10609, 10712, 10816, 10920, 11025, 11130, 11236, 11342, 11449, 11556, 11664, 11772, 11881, 11990, 12100, 12210, 12321, 12432, 12544, 12656, 12769, 12882, 12996, 13110, 13225, 13340, 13456, 13572, 13689, 13806, 13924, 14042, 14161, 14280, 14400, 14520, 14641, 14762, 14884, 15006, 15129, 15252, 15376, 15500, 15625, 15750, 15876, 16002, 16129, 16256, 16384, 16512, 16641, 16770, 16900, 17030, 17161, 17292, 17424, 17556, 17689, 17822, 17956, 18090, 18225, 18360, 18496, 18632, 18769, 18906, 19044, 19182, 19321, 19460, 19600, 19740, 19881, 20022, 20164, 20306, 20449, 20592, 20736, 20880, 21025, 21170, 21316, 21462, 21609, 21756, 21904, 22052, 22201, 22350, 22500, 22650, 22801, 22952, 23104, 23256, 23409, 23562, 23716, 23870, 24025, 24180, 24336, 24492, 24649, 24806, 24964, 25122, 25281, 25440, 25600, 25760, 25921, 26082, 26244, 26406, 26569, 26732, 26896, 27060, 27225, 27390, 27556, 27722, 27889, 28056, 28224, 28392, 28561, 28730, 28900, 29070, 29241, 29412, 29584, 29756, 29929, 30102, 30276, 30450, 30625, 30800, 30976, 31152, 31329, 31506, 31684, 31862, 32041, 32220, 32400, 32580, 32761, 32942, 33124, 33306, 33489, 33672, 33856, 34040, 34225, 34410, 34596, 34782, 34969, 35156, 35344, 35532, 35721, 35910, 36100, 36290, 36481, 36672, 36864, 37056, 37249, 37442, 37636, 37830, 38025, 38220, 38416, 38612, 38809, 39006, 39204, 39402, 39601, 39800, 40000, 40200, 40401, 40602, 40804, 41006, 41209, 41412, 41616, 41820, 42025, 42230, 42436, 42642, 42849, 43056, 43264, 43472, 43681, 43890, 44100, 44310, 44521, 44732, 44944, 45156, 45369, 45582, 45796, 46010, 46225, 46440, 46656, 46872, 47089, 47306, 47524, 47742, 47961, 48180, 48400, 48620, 48841, 49062, 49284, 49506, 49729, 49952, 50176, 50400, 50625, 50850, 51076, 51302, 51529, 51756, 51984, 52212, 52441, 52670, 52900, 53130, 53361, 53592, 53824, 54056, 54289, 54522, 54756, 54990, 55225, 55460, 55696, 55932, 56169, 56406, 56644, 56882, 57121, 57360, 57600, 57840, 58081, 58322, 58564, 58806, 59049, 59292, 59536, 59780, 60025, 60270, 60516, 60762, 61009, 61256, 61504, 61752, 62001, 62250, 62500, 62750, 63001, 63252, 63504, 63756, 64009, 64262, 64516, 64770, 65025, 65280
.define Squares_0_255 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500, 2601, 2704, 2809, 2916, 3025, 3136, 3249, 3364, 3481, 3600, 3721, 3844, 3969, 4096, 4225, 4356, 4489, 4624, 4761, 4900, 5041, 5184, 5329, 5476, 5625, 5776, 5929, 6084, 6241, 6400, 6561, 6724, 6889, 7056, 7225, 7396, 7569, 7744, 7921, 8100, 8281, 8464, 8649, 8836, 9025, 9216, 9409, 9604, 9801, 10000, 10201, 10404, 10609, 10816, 11025, 11236, 11449, 11664, 11881, 12100, 12321, 12544, 12769, 12996, 13225, 13456, 13689, 13924, 14161, 14400, 14641, 14884, 15129, 15376, 15625, 15876, 16129, 16384, 16641, 16900, 17161, 17424, 17689, 17956, 18225, 18496, 18769, 19044, 19321, 19600, 19881, 20164, 20449, 20736, 21025, 21316, 21609, 21904, 22201, 22500, 22801, 23104, 23409, 23716, 24025, 24336, 24649, 24964, 25281, 25600, 25921, 26244, 26569, 26896, 27225, 27556, 27889, 28224, 28561, 28900, 29241, 29584, 29929, 30276, 30625, 30976, 31329, 31684, 32041, 32400, 32761, 33124, 33489, 33856, 34225, 34596, 34969, 35344, 35721, 36100, 36481, 36864, 37249, 37636, 38025, 38416, 38809, 39204, 39601, 40000, 40401, 40804, 41209, 41616, 42025, 42436, 42849, 43264, 43681, 44100, 44521, 44944, 45369, 45796, 46225, 46656, 47089, 47524, 47961, 48400, 48841, 49284, 49729, 50176, 50625, 51076, 51529, 51984, 52441, 52900, 53361, 53824, 54289, 54756, 55225, 55696, 56169, 56644, 57121, 57600, 58081, 58564, 59049, 59536, 60025, 60516, 61009, 61504, 62001, 62500, 63001, 63504, 64009, 64516, 65025
.define Squares_256_512 65536, 66049, 66564, 67081, 67600, 68121, 68644, 69169, 69696, 70225, 70756, 71289, 71824, 72361, 72900, 73441, 73984, 74529, 75076, 75625, 76176, 76729, 77284, 77841, 78400, 78961, 79524, 80089, 80656, 81225, 81796, 82369, 82944, 83521, 84100, 84681, 85264, 85849, 86436, 87025, 87616, 88209, 88804, 89401, 90000, 90601, 91204, 91809, 92416, 93025, 93636, 94249, 94864, 95481, 96100, 96721, 97344, 97969, 98596, 99225, 99856, 100489, 101124, 101761, 102400, 103041, 103684, 104329, 104976, 105625, 106276, 106929, 107584, 108241, 108900, 109561, 110224, 110889, 111556, 112225, 112896, 113569, 114244, 114921, 115600, 116281, 116964, 117649, 118336, 119025, 119716, 120409, 121104, 121801, 122500, 123201, 123904, 124609, 125316, 126025, 126736, 127449, 128164, 128881, 129600, 130321, 131044, 131769, 132496, 133225, 133956, 134689, 135424, 136161, 136900, 137641, 138384, 139129, 139876, 140625, 141376, 142129, 142884, 143641, 144400, 145161, 145924, 146689, 147456, 148225, 148996, 149769, 150544, 151321, 152100, 152881, 153664, 154449, 155236, 156025, 156816, 157609, 158404, 159201, 160000, 160801, 161604, 162409, 163216, 164025, 164836, 165649, 166464, 167281, 168100, 168921, 169744, 170569, 171396, 172225, 173056, 173889, 174724, 175561, 176400, 177241, 178084, 178929, 179776, 180625, 181476, 182329, 183184, 184041, 184900, 185761, 186624, 187489, 188356, 189225, 190096, 190969, 191844, 192721, 193600, 194481, 195364, 196249, 197136, 198025, 198916, 199809, 200704, 201601, 202500, 203401, 204304, 205209, 206116, 207025, 207936, 208849, 209764, 210681, 211600, 212521, 213444, 214369, 215296, 216225, 217156, 218089, 219024, 219961, 220900, 221841, 222784, 223729, 224676, 225625, 226576, 227529, 228484, 229441, 230400, 231361, 232324, 233289, 234256, 235225, 236196, 237169, 238144, 239121, 240100, 241081, 242064, 243049, 244036, 245025, 246016, 247009, 248004, 249001, 250000, 251001, 252004, 253009, 254016, 255025, 256036, 257049, 258064, 259081, 260100, 261121
.define Sin_0_45 0, 0, 1, 2, 3, 3, 4, 5, 6, 7, 7, 8, 9, 10, 10, 11, 12, 13, 14, 14, 15, 16, 17, 18, 18, 19, 20, 21, 21, 22, 23, 24, 25, 25, 26, 27, 28, 28, 29, 30, 31, 32, 32, 33, 34, 35, 36, 36, 37, 38, 39, 39, 40, 41, 42, 42, 43, 44, 45, 46, 46, 47, 48, 49, 49, 50, 51, 52, 53, 53, 54, 55, 56, 56, 57, 58, 59, 59, 60, 61, 62, 62, 63, 64, 65, 66, 66, 67, 68, 69, 69, 70, 71, 72, 72, 73, 74, 75, 75, 76, 77, 78, 78, 79, 80, 81, 81, 82, 83, 84, 84, 85, 86, 86, 87, 88, 89, 89, 90, 91, 92, 92, 93, 94, 95, 95, 96, 97, 97, 98, 99, 100, 100, 101, 102, 103, 103, 104, 105, 105, 106, 107, 108, 108, 109, 110, 110, 111, 112, 112, 113, 114, 115, 115, 116, 117, 117, 118, 119, 119, 120, 121, 122, 122, 123, 124, 124, 125, 126, 126, 127, 128, 128, 129, 130, 130, 131, 132, 132, 133, 134, 134, 135, 136, 136, 137, 138, 138, 139, 140, 140, 141, 142, 142, 143, 144, 144, 145, 146, 146, 147, 148, 148, 149, 149, 150, 151, 151, 152, 153, 153, 154, 155, 155, 156, 156, 157, 158, 158, 159, 159, 160, 161, 161, 162, 163, 163, 164, 164, 165, 166, 166, 167, 167, 168, 168, 169, 170, 170, 171, 171, 172, 173, 173, 174, 174, 175, 175, 176, 177, 177, 178, 178, 179, 179, 180
.define Cos_0_45 256, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 253, 253, 253, 253, 253, 253, 253, 253, 253, 252, 252, 252, 252, 252, 252, 252, 252, 251, 251, 251, 251, 251, 251, 251, 250, 250, 250, 250, 250, 250, 249, 249, 249, 249, 249, 249, 248, 248, 248, 248, 248, 247, 247, 247, 247, 247, 246, 246, 246, 246, 246, 245, 245, 245, 245, 244, 244, 244, 244, 244, 243, 243, 243, 243, 242, 242, 242, 242, 241, 241, 241, 241, 240, 240, 240, 239, 239, 239, 239, 238, 238, 238, 237, 237, 237, 237, 236, 236, 236, 235, 235, 235, 234, 234, 234, 234, 233, 233, 233, 232, 232, 232, 231, 231, 231, 230, 230, 230, 229, 229, 229, 228, 228, 227, 227, 227, 226, 226, 226, 225, 225, 225, 224, 224, 223, 223, 223, 222, 222, 221, 221, 221, 220, 220, 219, 219, 219, 218, 218, 217, 217, 217, 216, 216, 215, 215, 215, 214, 214, 213, 213, 212, 212, 211, 211, 211, 210, 210, 209, 209, 208, 208, 207, 207, 207, 206, 206, 205, 205, 204, 204, 203, 203, 202, 202, 201, 201, 200, 200, 199, 199, 198, 198, 197, 197, 196, 196, 195, 195, 194, 194, 193, 193, 192, 192, 191, 191, 190, 190, 189, 189, 188, 188, 187, 187, 186, 185, 185, 184, 184, 183, 183, 182, 182, 181
.byte 0, 0
SQUARES_OVER_FOUR_LO:
.lobytes SquaresOverFour_0_512
SQUARES_OVER_FOUR_HI:
.hibytes SquaresOverFour_0_512
SIN45_TABLE_LO:
.lobytes Sin_0_45
SIN45_TABLE_HI:
.hibytes Sin_0_45
COS45_TABLE_LO:
.lobytes Cos_0_45
COS45_TABLE_HI:
.hibytes Cos_0_45 |
/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2008-2017 Imperial College London
* Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
* Copyright 2013-2017 Andreas Schuh
*
* 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 "mirtk/GradientImageFilter.h"
#include "mirtk/Math.h"
#include "mirtk/Parallel.h"
#include "mirtk/VoxelFunction.h"
#include <limits>
#include <utility>
namespace mirtk {
// =============================================================================
// Auxiliary functors
// =============================================================================
namespace GradientImageFilterUtils {
// -----------------------------------------------------------------------------
/// Evaluate image gradient at a specific voxel using finite differences
template <class TIn, class TOut = TIn>
class EvaluateImageGradient : public VoxelFunction
{
typedef typename GradientImageFilter<TIn>::GradientType GradientType;
GradientType _Type;
const GenericImage<TIn> *_Input;
double _PaddingValue;
bool _UseVoxelSize;
const Matrix *_Orientation;
int _MaxI, _MaxJ, _MaxK;
int _NumberOfVoxels;
public:
EvaluateImageGradient(GradientType type,
const GenericImage<TIn> *input, double padding,
bool use_voxel_size, const Matrix *orientation)
:
_Type(type),
_Input(input),
_PaddingValue(padding),
_UseVoxelSize(use_voxel_size),
_Orientation(orientation),
_MaxI(input->X() - 1),
_MaxJ(input->Y() - 1),
_MaxK(input->Z() - 1),
_NumberOfVoxels(input->NumberOfSpatialVoxels())
{}
void operator ()(int i, int j, int k, int l, TOut *g)
{
double dx = .0, dy = .0, dz = .0, v1, v2;
const bool nan_bg = IsNaN(_PaddingValue);
int i1 = (i == 0 ? 0 : i - 1);
int i2 = (i == _MaxI ? _MaxI : i + 1);
int j1 = (j == 0 ? 0 : j - 1);
int j2 = (j == _MaxJ ? _MaxJ : j + 1);
int k1 = (k == 0 ? 0 : k - 1);
int k2 = (k == _MaxK ? _MaxK : k + 1);
if (i1 < i2) {
v1 = static_cast<double>(_Input->Get(i1, j, k, l));
v2 = static_cast<double>(_Input->Get(i2, j, k, l));
if (IsNaN(v1) || (!nan_bg && v1 <= _PaddingValue)) {
if (i1 < i) {
i1 = i;
v1 = static_cast<double>(_Input->Get(i1, j, k, l));
if (IsNaN(v1) || (!nan_bg && v1 <= _PaddingValue)) {
i1 = i2;
}
} else {
i1 = i2;
}
}
if (IsNaN(v2) || (!nan_bg && v2 <= _PaddingValue)) {
if (i2 > i) {
i2 = i;
v2 = static_cast<double>(_Input->Get(i1, j, k, l));
if (IsNaN(v2) || (!nan_bg && v2 <= _PaddingValue)) {
i2 = i1;
}
} else {
i2 = i1;
}
}
if (i1 < i2) dx = (v2 - v1) / (i2 - i1);
}
if (j1 < j2) {
v1 = static_cast<double>(_Input->Get(i, j1, k, l));
v2 = static_cast<double>(_Input->Get(i, j2, k, l));
if (IsNaN(v1) || (!nan_bg && v1 <= _PaddingValue)) {
if (j1 < j) {
j1 = j;
v1 = static_cast<double>(_Input->Get(i, j1, k, l));
if (IsNaN(v1) || (!nan_bg && v1 <= _PaddingValue)) {
j1 = j2;
}
} else {
j1 = j2;
}
}
if (IsNaN(v2) || (!nan_bg && v2 <= _PaddingValue)) {
if (j2 > j) {
j2 = j;
v2 = static_cast<double>(_Input->Get(i, j2, k, l));
if (IsNaN(v2) || (!nan_bg && v2 <= _PaddingValue)) {
j2 = j1;
}
} else {
j2 = j1;
}
}
if (j1 < j2) dy = (v2 - v1) / (j2 - j1);
}
if (k1 < k2) {
v1 = static_cast<double>(_Input->Get(i, j, k1, l));
v2 = static_cast<double>(_Input->Get(i, j, k2, l));
if (IsNaN(v1) || (!nan_bg && v1 <= _PaddingValue)) {
if (k1 < k) {
k1 = k;
v1 = static_cast<double>(_Input->Get(i, j, k1, l));
if (IsNaN(v1) || (!nan_bg && v1 <= _PaddingValue)) {
k1 = k2;
}
} else {
k1 = k2;
}
}
if (IsNaN(v2) || (!nan_bg && v2 <= _PaddingValue)) {
if (k2 > k) {
k2 = k;
v2 = static_cast<double>(_Input->Get(i, j, k2, l));
if (IsNaN(v2) || (!nan_bg && v2 <= _PaddingValue)) {
k2 = k1;
}
} else {
k2 = k1;
}
}
if (k1 < k2) dz = (v2 - v1) / (k2 - k1);
}
if (_UseVoxelSize) {
if (_Input->GetXSize() > .0) dx /= _Input->GetXSize();
if (_Input->GetYSize() > .0) dy /= _Input->GetYSize();
if (_Input->GetZSize() > .0) dz /= _Input->GetZSize();
}
if (_Orientation) {
// Using numerator-layout for matrix calculus.
// http://en.wikipedia.org/wiki/Matrix_calculus#Numerator-layout_notation
const double di = dx, dj = dy, dk = dz;
const Matrix &R = *_Orientation;
dx = di * R(0, 0) + dj * R(1, 0) + dk * R(2, 0);
dy = di * R(0, 1) + dj * R(1, 1) + dk * R(2, 1);
dz = di * R(0, 2) + dj * R(1, 2) + dk * R(2, 2);
}
switch (_Type) {
case GradientType::GRADIENT_X: {
*g = static_cast<TOut>(dx);
} break;
case GradientType::GRADIENT_Y: {
*g = static_cast<TOut>(dx);
} break;
case GradientType::GRADIENT_Z: {
*g = static_cast<TOut>(dz);
} break;
case GradientType::GRADIENT_DOT_PRODUCT: {
*g = static_cast<TOut>(dx*dx + dy*dy + dz*dz);
} break;
case GradientType::GRADIENT_MAGNITUDE: {
*g = static_cast<TOut>(sqrt(dx*dx + dy*dy + dz*dz));
} break;
case GradientType::GRADIENT_VECTOR: {
g += 2 * l * _NumberOfVoxels;
*g = static_cast<TOut>(dx), g += _NumberOfVoxels;
*g = static_cast<TOut>(dy), g += _NumberOfVoxels;
*g = static_cast<TOut>(dz);
} break;
case GradientType::NORMALISED_GRADIENT_VECTOR: {
const double norm = sqrt(dx*dx + dy*dy + dz*dz) + 1e-10;
g += 2 * l * _NumberOfVoxels;
*g = static_cast<TOut>(dx / norm), g += _NumberOfVoxels;
*g = static_cast<TOut>(dy / norm), g += _NumberOfVoxels;
*g = static_cast<TOut>(dz / norm);
} break;
default: {
*g = TOut(0);
} break;
}
}
};
} // namespace GradientImageFilterUtils
using namespace GradientImageFilterUtils;
// =============================================================================
// Construction/Destruction
// =============================================================================
// -----------------------------------------------------------------------------
template <class VoxelType>
GradientImageFilter<VoxelType>::GradientImageFilter(GradientType type)
:
_Type(type),
_UseVoxelSize(true),
_UseOrientation(false),
_PaddingValue(-inf)
{
}
// =============================================================================
// Execution
// =============================================================================
// -----------------------------------------------------------------------------
template <class VoxelType>
void GradientImageFilter<VoxelType>::Initialize()
{
// Check inputs and outputs
if (this->Input() == nullptr) {
cerr << this->NameOfClass() << "::Initialize: Filter has no input" << endl;
exit(1);
}
if (this->Output() == nullptr) {
cerr << this->NameOfClass() << "::Initialize: Filter has no output" << endl;
exit(1);
}
if (this->Input()->IsEmpty()) {
cerr << this->NameOfClass() << "::Initialize: Input is empty" << endl;
exit(1);
}
if (_Type < 0 || _Type >= NUM_GRADIENT_TYPES) {
cerr << this->NameOfClass() << "::Initialize: Invalid gradient type: " << _Type << endl;
exit(1);
}
// Instantiate temporary output image if necessary
if (this->Input() == this->Output()) {
this->Buffer(this->Output());
this->Output(new GenericImage<VoxelType>());
} else {
this->Buffer(nullptr);
}
// Initialize output image
if (_Type == GRADIENT_VECTOR || _Type == NORMALISED_GRADIENT_VECTOR) {
this->Output()->Initialize(this->Input()->Attributes(), 3 * this->Input()->T());
} else {
this->Output()->Initialize(this->Input()->Attributes(), this->Input()->T());
}
}
// -----------------------------------------------------------------------------
template <class VoxelType>
void GradientImageFilter<VoxelType>::Run()
{
this->Initialize();
ImageAttributes attr = this->Input()->Attributes();
if (attr._dt == .0) attr._dt = 1.0; // Call voxel function for each scalar input
Matrix R;
if (_UseOrientation) R = attr.GetWorldToImageOrientation();
EvaluateImageGradient<VoxelType> eval(
_Type, this->Input(), _PaddingValue, _UseVoxelSize, _UseOrientation ? &R : nullptr
);
ParallelForEachVoxel(attr, this->Output(), eval);
this->Finalize();
}
// -----------------------------------------------------------------------------
template <class VoxelType>
void GradientImageFilter<VoxelType>::Finalize()
{
if (this->Buffer()) {
this->Buffer()->CopyFrom(this->Output()->Data());
delete this->Output();
this->Output(this->Buffer());
this->Buffer(nullptr);
}
}
// =============================================================================
// Explicit template instantiations
// =============================================================================
// -----------------------------------------------------------------------------
template class GradientImageFilter<unsigned char>;
template class GradientImageFilter<short>;
template class GradientImageFilter<float>;
template class GradientImageFilter<double>;
} // namespace mirtk
|
<%
from pwnlib.shellcraft.mips.linux import syscall
%>
<%page args="pid, param"/>
<%docstring>
Invokes the syscall sched_getparam. See 'man 2 sched_getparam' for more information.
Arguments:
pid(pid_t): pid
param(sched_param): param
</%docstring>
${syscall('SYS_sched_getparam', pid, param)}
|
/* Copyright 2018 Ignacio Torroba (ignaciotb@kth.se)
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef EKF_LOCALIZATION_HPP
#define EKF_LOCALIZATION_HPP
#include <ros/timer.h>
#include <ros/ros.h>
#include "gazebo_msgs/GetWorldProperties.h"
#include "gazebo_msgs/GetModelState.h"
#include "utils_matrices/utils_matrices.hpp"
#include "correspondence_class/correspondence_class.hpp"
#include "noise_oneD_kf/noise_oneD_kf.hpp"
#include <queue>
#include <math.h>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/assign.hpp>
#include <boost/bind.hpp>
#include <ros/transport_hints.h>
#include <boost/scoped_ptr.hpp>
#include <boost/math/distributions/chi_squared.hpp>
#include <boost/math/distributions/inverse_chi_squared.hpp>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
#include <std_msgs/UInt32.h>
#include <sensor_msgs/Image.h>
#include <message_filters/subscriber.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <geometry_msgs/TwistWithCovarianceStamped.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/TransformStamped.h>
#include <visualization_msgs/MarkerArray.h>
#include <visualization_msgs/Marker.h>
#include <geometry_msgs/PoseArray.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>
#include <tf/transform_broadcaster.h>
typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Imu,
geometry_msgs::TwistWithCovarianceStamped> MsgTimingPolicy;
/**
* @brief The EKFLocalization class
* EKF-based localization node for LoLo
* Inputs:
* IMU, DVL and landmarks positions from measurements
* Map as a collection of landmarks with respect to world frame
* Outputs:
* nav_msgs/Odometry with an estimate of the 6DOF pose of LoLo
* updated tf transform odom --> base_link
*/
class EKFLocalization{
public:
EKFLocalization(std::string node_name, ros::NodeHandle &nh);
void ekfLocalize(const ros::TimerEvent& e);
~EKFLocalization();
void init(std::vector<double> sigma_diag, std::vector<double> r_diag, std::vector<double> q_diag, double delta);
private:
// ROS variables
ros::NodeHandle *nh_;
std::string node_name_;
message_filters::Synchronizer<MsgTimingPolicy>* msg_synch_ptr_;
message_filters::Subscriber<sensor_msgs::Imu>* imu_subs_;
message_filters::Subscriber<geometry_msgs::TwistWithCovarianceStamped>* dvl_subs_;
ros::Timer timer_;
// Comms
ros::Subscriber fast_imu_sub_;
ros::Subscriber fast_dvl_sub_;
ros::Subscriber tf_gt_subs_;
ros::Subscriber observs_subs_;
ros::Subscriber rpt_subs_;
ros::Publisher odom_pub_;
ros::Publisher odom_inertial_pub_;
ros::Publisher vis_pub_;
visualization_msgs::MarkerArray markers_;
ros::ServiceClient gazebo_client_;
ros::ServiceClient landmarks_client_;
// Handlers for sensors
std::deque<sensor_msgs::ImuPtr> imu_readings_; // TODO: add limit size to queues
std::deque<geometry_msgs::TwistWithCovarianceStampedPtr> dvl_readings_;
std::deque<nav_msgs::OdometryPtr> gt_readings_;
std::deque<geometry_msgs::PoseArrayPtr> measurements_t_;
boost::mutex msg_lock_;
std::vector<boost::numeric::ublas::vector<double>> map_odom_;
bool init_filter_;
// System state variables
boost::numeric::ublas::vector<double> mu_;
boost::numeric::ublas::vector<double> mu_hat_;
boost::numeric::ublas::vector<double> mu_pred_;
boost::numeric::ublas::matrix<double> Sigma_;
boost::numeric::ublas::matrix<double> Sigma_hat_;
boost::numeric::ublas::matrix<double> G_t_;
double delta_m_;
double lambda_M_;
// Noise models
boost::numeric::ublas::matrix<double> R_;
boost::numeric::ublas::matrix<double> Q_;
// Aux
double t_prev_;
bool coord_;
unsigned int size_imu_q_;
unsigned int size_dvl_q_;
OneDKF* dvl_x_kf;
OneDKF* dvl_y_kf;
OneDKF* dvl_z_kf;
// tf
tf::TransformBroadcaster odom_bc_;
tf::StampedTransform transf_dvl_base_;
tf::StampedTransform transf_world_odom_;
tf::Transform transf_odom_world_;
tf::StampedTransform transf_base_sssr_;
std::string odom_frame_;
std::string world_frame_;
std::string base_frame_;
std::string dvl_frame_;
std::string sssr_frame_;
std::string map_srv_name_;
std::string lm_srv_name_;
// Input callbacks
void gtCB(const nav_msgs::OdometryPtr &pose_msg);
void synchSensorsCB(const sensor_msgs::ImuConstPtr &imu_msg,
const geometry_msgs::TwistWithCovarianceStampedConstPtr &dvl_msg);
void fastIMUCB(const sensor_msgs::ImuPtr &imu_msg);
void fastDVLCB(const geometry_msgs::TwistWithCovarianceStampedPtr &dvl_msg);
void observationsCB(const geometry_msgs::PoseArrayPtr &observ_msg);
/**
* @brief EKFLocalization::computeOdom
* @param dvl_msg
* @param gt_pose
* @param q_auv
* @param u_t
* Integrates IMU and DVL to predict an estimate of the pose
*/
void computeOdom(const geometry_msgs::TwistWithCovarianceStampedPtr &dvl_msg, const tf::Quaternion &q_auv,
boost::numeric::ublas::vector<double> &u_t);
/**
* @brief EKFLocalization::predictMotion
* @param u_t
* Prediction step for the EKF
*/
void predictMotion(boost::numeric::ublas::vector<double> &u_t);
/**
* @brief predictMeasurement
* @param landmark_j
* @param z_i
* @param ml_i_list
* Measurement prediction for a given pair measurement-landmark at time t
*/
void predictMeasurement(const boost::numeric::ublas::vector<double> &landmark_j,
boost::numeric::ublas::vector<double> &z_i,
std::vector<CorrespondenceClass *> &ml_i_list);
/**
* @brief dataAssociation
* Maximum likelihood data association with outlier rejection
*/
void dataAssociation();
/**
* @brief sequentialUpdate
* @param c_i_j
* Sequential update for a given match observation-landmark
*/
void sequentialUpdate(CorrespondenceClass *c_i_j);
/**
* @brief createMapMarkers
* Publishes the map as an array of markers for visualization in RVIZ
*/
void createMapMarkers(std::vector<boost::numeric::ublas::vector<double> > map_world);
/**
* @brief EKFLocalization::sendOutput
* @param t
* @return
* Publishes AUV odometry info and tf odom --> base_link
*/
bool sendOutput(ros::Time t);
/**
* @brief EKFLocalization::interpolateDVL
* @param t_now
* @param dvl_msg_ptr
* Interpolates DVL (slower) inputs through Bezier curves to synch to faster sensors
*/
void interpolateDVL(ros::Time t_now, geometry_msgs::TwistWithCovarianceStampedPtr &dvl_msg_ptr);
};
#endif // EKF_LOCALIZATION_HPP
|
_main:
;LCD.c,18 :: void main() {
;LCD.c,19 :: Lcd_Init(); // Initialize LCD
CALL _Lcd_Init+0
;LCD.c,21 :: Lcd_Cmd(_LCD_CLEAR); // Clear display
MOVLW 1
MOVWF FARG_Lcd_Cmd_out_char+0
CALL _Lcd_Cmd+0
;LCD.c,22 :: Lcd_Cmd(_LCD_CURSOR_OFF); // Cursor off
MOVLW 12
MOVWF FARG_Lcd_Cmd_out_char+0
CALL _Lcd_Cmd+0
;LCD.c,23 :: Lcd_Out(1,1,"HELLO EVERY BODY"); // Write text in first row
MOVLW 1
MOVWF FARG_Lcd_Out_row+0
MOVLW 1
MOVWF FARG_Lcd_Out_column+0
MOVLW ?lstr1_LCD+0
MOVWF FARG_Lcd_Out_text+0
CALL _Lcd_Out+0
;LCD.c,24 :: Delay_ms(2000);
MOVLW 21
MOVWF R11+0
MOVLW 75
MOVWF R12+0
MOVLW 190
MOVWF R13+0
L_main0:
DECFSZ R13+0, 1
GOTO L_main0
DECFSZ R12+0, 1
GOTO L_main0
DECFSZ R11+0, 1
GOTO L_main0
NOP
;LCD.c,25 :: Lcd_Cmd(_LCD_CLEAR); // Clear display
MOVLW 1
MOVWF FARG_Lcd_Cmd_out_char+0
CALL _Lcd_Cmd+0
;LCD.c,26 :: Lcd_Out(2,1,"ENG AHMED NAGUIB"); // Write text in first row
MOVLW 2
MOVWF FARG_Lcd_Out_row+0
MOVLW 1
MOVWF FARG_Lcd_Out_column+0
MOVLW ?lstr2_LCD+0
MOVWF FARG_Lcd_Out_text+0
CALL _Lcd_Out+0
;LCD.c,28 :: }
L_end_main:
GOTO $+0
; end of _main
|
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#define NT2_BENCH_MODULE "nt2 operator toolbox - multiplies/scalar Mode"
//////////////////////////////////////////////////////////////////////////////
// timing Test behavior of operator components in scalar mode
//////////////////////////////////////////////////////////////////////////////
#include <nt2/operator/include/functions/multiplies.hpp>
#include <nt2/sdk/bench/benchmark.hpp>
#include <nt2/sdk/bench/timing.hpp>
#include <nt2/include/constants/valmax.hpp>
#include <nt2/include/constants/valmin.hpp>
#include <boost/dispatch/meta/as_integer.hpp>
#include <cmath>
//////////////////////////////////////////////////////////////////////////////
// scalar runtime benchmark for functor<multiplies_> from operator
//////////////////////////////////////////////////////////////////////////////
using nt2::tag::multiplies_;
//////////////////////////////////////////////////////////////////////////////
// range macro
//////////////////////////////////////////////////////////////////////////////
#define RS(T,V1,V2) (T, T(V1) ,T(V2))
namespace n1 {
typedef float T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
NT2_TIMING(multiplies_,(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2))(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2)))
}
namespace n2 {
typedef double T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
NT2_TIMING(multiplies_,(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2))(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2)))
}
namespace n3 {
typedef nt2::int8_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
NT2_TIMING(multiplies_,(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2))(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2)))
}
namespace n4 {
typedef nt2::int16_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
NT2_TIMING(multiplies_,(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2))(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2)))
}
namespace n5 {
typedef nt2::int32_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
NT2_TIMING(multiplies_,(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2))(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2)))
}
namespace n6 {
typedef nt2::int64_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
NT2_TIMING(multiplies_,(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2))(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2)))
}
namespace n7 {
typedef nt2::uint8_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
NT2_TIMING(multiplies_,(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2))(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2)))
}
namespace n8 {
typedef nt2::uint16_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
NT2_TIMING(multiplies_,(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2))(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2)))
}
namespace n9 {
typedef nt2::uint32_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
NT2_TIMING(multiplies_,(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2))(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2)))
}
namespace n10 {
typedef nt2::uint64_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
NT2_TIMING(multiplies_,(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2))(RS(T,nt2::Valmin<T>()/2,nt2::Valmax<T>()/2)))
}
#undef RS
|
/* Copyright 2016 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/tools/tfprof/internal/tfprof_stats.h"
#include <utility>
#include "tensorflow/c/checkpoint_reader.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/protobuf/config.pb.h"
#include "tensorflow/tools/tfprof/internal/tfprof_constants.h"
#include "tensorflow/tools/tfprof/internal/tfprof_options.h"
#include "tensorflow/tools/tfprof/internal/tfprof_utils.h"
#include "tensorflow/tools/tfprof/tfprof_log.pb.h"
#include "tensorflow/tools/tfprof/tfprof_output.pb.h"
namespace tensorflow {
namespace tfprof {
class TFProfShowTest : public ::testing::Test {
protected:
TFProfShowTest() {
string graph_path =
io::JoinPath(testing::TensorFlowSrcRoot(),
"tools/tfprof/internal/testdata/graph.pbtxt");
std::unique_ptr<tensorflow::GraphDef> graph_pb(new tensorflow::GraphDef());
TF_CHECK_OK(ReadGraphDef(Env::Default(), graph_path, graph_pb.get()));
std::unique_ptr<tensorflow::RunMetadata> run_meta_pb(
new tensorflow::RunMetadata());
string run_meta_path =
io::JoinPath(testing::TensorFlowSrcRoot(),
"tools/tfprof/internal/testdata/run_meta");
TF_CHECK_OK(
ReadBinaryProto(Env::Default(), run_meta_path, run_meta_pb.get()));
std::unique_ptr<OpLog> op_log_pb(new OpLog());
string op_log_path =
io::JoinPath(testing::TensorFlowSrcRoot(),
"tools/tfprof/internal/testdata/tfprof_log");
TF_CHECK_OK(ReadBinaryProto(Env::Default(), op_log_path, op_log_pb.get()));
string ckpt_path = io::JoinPath(testing::TensorFlowSrcRoot(),
"tools/tfprof/internal/testdata/ckpt");
TF_Status* status = TF_NewStatus();
std::unique_ptr<checkpoint::CheckpointReader> ckpt_reader(
new checkpoint::CheckpointReader(ckpt_path, status));
CHECK(TF_GetCode(status) == TF_OK);
TF_DeleteStatus(status);
tf_stats_.reset(new TFStats(std::move(graph_pb), std::move(run_meta_pb),
std::move(op_log_pb), std::move(ckpt_reader)));
}
std::unique_ptr<TFStats> tf_stats_;
};
TEST_F(TFProfShowTest, DumpScopeMode) {
string dump_file = io::JoinPath(testing::TmpDir(), "dump");
Options opts(5, 0, 0, 0, 0, {".*"}, "name",
{"VariableV2"}, // accout_type_regexes
{".*"}, {""}, {".*"}, {""}, false,
{"params", "bytes", "micros", "float_ops", "num_hidden_ops"},
false, dump_file);
tf_stats_->PrintGraph("scope", opts);
string dump_str;
TF_CHECK_OK(ReadFileToString(Env::Default(), dump_file, &dump_str));
EXPECT_EQ(
"_TFProfRoot (--/370 params, --/0 flops, --/1.48KB, --/5us)\n "
"conv2d/bias (5, 5/5 params, 0/0 flops, 20B/20B, 1us/1us)\n "
"conv2d/kernel (3x3x3x5, 135/135 params, 0/0 flops, 540B/540B, "
"1us/1us)\n conv2d_1/bias (5, 5/5 params, 0/0 flops, 20B/20B, "
"1us/1us)\n conv2d_1/kernel (3x3x5x5, 225/225 params, 0/0 flops, "
"900B/900B, 2us/2us)\n",
dump_str);
}
} // namespace tfprof
} // namespace tensorflow
|
/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2018, Southwest Research Institute
*
* 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 "descartes_core/path_planner_base.h"
using namespace descartes_core;
const std::map<int, std::string> PathPlannerBase::error_map_{
{ PlannerError::OK, "OK" },
{ PlannerError::EMPTY_PATH, "No path plan has been generated" },
{ PlannerError::INVALID_ID, "ID is nil or isn't part of the path" },
{ PlannerError::IK_NOT_AVAILABLE, "One or more ik solutions could not be found" },
{ PlannerError::UNINITIALIZED, "Planner has not been initialized with a robot model" },
{ PlannerError::INCOMPLETE_PATH, "Input trajectory and output path point cound differ" }
};
|
; A126935: Define an array by d(m, 0) = 1, d(m, 1) = m; d(m, k) = (m - k + 1) d(m+1, k-1) - (k-1) (m+1) d(m+2, k-2). Sequence gives d(n,3).
; 0,-12,-24,-30,-24,0,48,126,240,396,600,858,1176,1560,2016,2550,3168,3876,4680,5586,6600,7728,8976,10350,11856,13500,15288,17226,19320,21576,24000,26598,29376,32340,35496,38850,42408,46176,50160,54366,58800,63468,68376,73530,78936,84600,90528,96726,103200,109956,117000,124338,131976,139920,148176,156750,165648,174876,184440,194346,204600,215208,226176,237510,249216,261300,273768,286626,299880,313536,327600,342078,356976,372300,388056,404250,420888,437976,455520,473526,492000,510948,530376,550290
mov $1,$0
bin $0,3
mul $1,2
sub $0,$1
mul $0,6
|
#include "GameScene.h"
USING_NS_CC;
Scene* GameScene::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = GameScene::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool GameScene::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
return true;
}
|
Name: zel_gover.asm
Type: file
Size: 21921
Last-Modified: '2016-05-13T04:36:32Z'
SHA-1: 209880FAA32D94EAA6AAC1D02267A661A0797A69
Description: null
|
BITS 32
;TEST_FILE_META_BEGIN
;TEST_TYPE=TEST_F
;TEST_IGNOREFLAGS=
;TEST_FILE_META_END
; XADD8rr
mov al, 0x45
mov bl, 0x56
;TEST_BEGIN_RECORDING
xadd al, bl
;TEST_END_RECORDING
|
# /* **************************************************************************
# * *
# * (C) Copyright Paul Mensonides 2002.
# * Distributed under the Boost Software License, Version 1.0. (See
# * accompanying file LICENSE_1_0.txt or copy at
# * http://www.boost.org/LICENSE_1_0.txt)
# * *
# ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# include <qsboost/preprocessor/slot/detail/shared.hpp>
#
# undef QSBOOST_PP_ITERATION_FINISH_4
#
# undef QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1
# undef QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2
# undef QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3
# undef QSBOOST_PP_ITERATION_FINISH_4_DIGIT_4
# undef QSBOOST_PP_ITERATION_FINISH_4_DIGIT_5
# undef QSBOOST_PP_ITERATION_FINISH_4_DIGIT_6
# undef QSBOOST_PP_ITERATION_FINISH_4_DIGIT_7
# undef QSBOOST_PP_ITERATION_FINISH_4_DIGIT_8
# undef QSBOOST_PP_ITERATION_FINISH_4_DIGIT_9
# undef QSBOOST_PP_ITERATION_FINISH_4_DIGIT_10
#
# if QSBOOST_PP_SLOT_TEMP_3 == 0
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3 0
# elif QSBOOST_PP_SLOT_TEMP_3 == 1
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3 1
# elif QSBOOST_PP_SLOT_TEMP_3 == 2
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3 2
# elif QSBOOST_PP_SLOT_TEMP_3 == 3
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3 3
# elif QSBOOST_PP_SLOT_TEMP_3 == 4
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3 4
# elif QSBOOST_PP_SLOT_TEMP_3 == 5
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3 5
# elif QSBOOST_PP_SLOT_TEMP_3 == 6
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3 6
# elif QSBOOST_PP_SLOT_TEMP_3 == 7
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3 7
# elif QSBOOST_PP_SLOT_TEMP_3 == 8
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3 8
# elif QSBOOST_PP_SLOT_TEMP_3 == 9
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3 9
# endif
#
# if QSBOOST_PP_SLOT_TEMP_2 == 0
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2 0
# elif QSBOOST_PP_SLOT_TEMP_2 == 1
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2 1
# elif QSBOOST_PP_SLOT_TEMP_2 == 2
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2 2
# elif QSBOOST_PP_SLOT_TEMP_2 == 3
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2 3
# elif QSBOOST_PP_SLOT_TEMP_2 == 4
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2 4
# elif QSBOOST_PP_SLOT_TEMP_2 == 5
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2 5
# elif QSBOOST_PP_SLOT_TEMP_2 == 6
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2 6
# elif QSBOOST_PP_SLOT_TEMP_2 == 7
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2 7
# elif QSBOOST_PP_SLOT_TEMP_2 == 8
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2 8
# elif QSBOOST_PP_SLOT_TEMP_2 == 9
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2 9
# endif
#
# if QSBOOST_PP_SLOT_TEMP_1 == 0
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1 0
# elif QSBOOST_PP_SLOT_TEMP_1 == 1
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1 1
# elif QSBOOST_PP_SLOT_TEMP_1 == 2
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1 2
# elif QSBOOST_PP_SLOT_TEMP_1 == 3
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1 3
# elif QSBOOST_PP_SLOT_TEMP_1 == 4
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1 4
# elif QSBOOST_PP_SLOT_TEMP_1 == 5
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1 5
# elif QSBOOST_PP_SLOT_TEMP_1 == 6
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1 6
# elif QSBOOST_PP_SLOT_TEMP_1 == 7
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1 7
# elif QSBOOST_PP_SLOT_TEMP_1 == 8
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1 8
# elif QSBOOST_PP_SLOT_TEMP_1 == 9
# define QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1 9
# endif
#
# if QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3
# define QSBOOST_PP_ITERATION_FINISH_4 QSBOOST_PP_SLOT_CC_3(QSBOOST_PP_ITERATION_FINISH_4_DIGIT_3, QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2, QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1)
# elif QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2
# define QSBOOST_PP_ITERATION_FINISH_4 QSBOOST_PP_SLOT_CC_2(QSBOOST_PP_ITERATION_FINISH_4_DIGIT_2, QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1)
# else
# define QSBOOST_PP_ITERATION_FINISH_4 QSBOOST_PP_ITERATION_FINISH_4_DIGIT_1
# endif
|
.include "m1-ntsc.asm"
//Changes Mother 1+2 Screen
.org 0x8705F94 :: .incbin "data/m12-705f94.bin"
.org 0x86fd794 :: .incbin "data/m12-6fd794.bin"
.org 0x8709190 :: .incbin "data/m12-709190.bin"
////////////////////
//////Graphics//////
////////////////////
//Town Map Hacks
.org 0x87ad4dc :: .incbin "data/m2-7ad4dc.bin" //Town Map - To Threed (Good)
.org 0x87e1ffc :: .incbin "data/m2-7e1ffc.bin" //Town Map - Threek->Threed (Good)
.org 0x87f00fc :: .incbin "data/m2-7f00fc.bin" //Town Map - Scarabi->Scaraba (Good)
.org 0x87ac15c :: .incbin "data/m2-7ac15c.bin" //Town Map - Hospital (Good, but need to change sprite size ffs)
.org 0x87ac9fc :: .incbin "data/m2-7ac9fc.bin" //Town Map - Food (Good)
.org 0x87A0D7C :: .incbin "data/m2-7a0d7c.bin"
.org 0x88bb098 :: .incbin "data/m2-8bb098.bin" //Insane Cultist (Good...?)
.org 0x830d3a4 :: .incbin "data/m2-30d3a4.bin"
.org 0x876c1fc :: .incbin "data/m2-76c1fc.bin" //Door - Don->! (Good)
.org 0x877ee3c :: .incbin "data/m2-77ee3c.bin" //Soda truck and Runaway Five van (Good...?)
.org 0x8764e3c :: .incbin "data/m2-764e3c.bin" //Eraser Statue (+Pencil Statue?) (Preliminary)
.org 0x8787fbc :: .incbin "data/m2-787fbc.bin" //Nusutto->Burglin Park (Good)
.org 0x87099fc :: .incbin "data/m2-7099fc.bin" //THE WAR AGAINST GIYGAS! (Preliminary)
.org 0x87acb7c :: .incbin "data/m2-7acb7c.bin"
.org 0x87ac87c :: .incbin "data/m2-7ac87c.bin"
.org 0x8b01804 :: .incbin "data/m2-b01804.bin"
.org 0x8b03d84 :: .incbin "data/m2-b03d84.bin"
.org 0x8675528 :: .incbin "data/m2-675528.bin"
.org 0x8B01D84 :: .incbin "data/m2-b01d84.bin"
.org 0x874d4bc :: .incbin "data/m2-74d4bc.bin"
.org 0x869ff28 :: .incbin "data/m2-69ff28.bin"
////////////////////
////////Maps////////
////////////////////
////////////////////
////////Audio///////
////////////////////
.org 0x8C917D0
.align 4
brass_stop_organ:
.incbin "data/brass_stop_organ.bin"
//This is the sound data
.include "ArmipsMusicPlayDef.asm"
.include "./sound/song002restored.asm" //File Select
.include "./sound/song003restored.asm" //Your name, please (Imperfect, note)
.include "./sound/song007restored.asm" //A Bad Dream
.include "./sound/song008restored.asm" //Enemy Encounter (Blue/Green) (Imperfect, causes a vblanking issue)
.include "./sound/song013restored.asm" //Teleportation
.include "./sound/song016restored.asm" //Dr. Andonuts' Lab (Imperfect, loop)
.include "./sound/song029restored.asm" //Onett Night 1
.include "./sound/song041restored.asm" //Alien Invasion
.include "./sound/song044restored.asm" //Threed, Zombie Central (Imperfect...?, loop)
.include "./sound/song050restored.asm" //Moonside
.include "./sound/song055restored.asm" //Cavern of Winters
.include "./sound/song057restored.asm" //Jackie's Cafe
.include "./sound/song072restored.asm" //Giygas' Intro (Imperfect, loop)
.include "./sound/song073restored.asm" //Giygas' Intimidation (Imperfect, loop)
.include "./sound/song074restored.asm" //Giygas is Fatally Wounded!
.include "./sound/song087restored.asm" //Get On The Bus
.include "./sound/song097restored.asm" //Battle Against a Machine
.include "./sound/song100restored.asm" //Franky
.include "./sound/song101restored.asm" //Weak Opponent
.include "./sound/song104restored.asm" //Kraken of The Sea
.include "./sound/song105restored.asm" //Pokey Means Business!
.include "./sound/song121restored.asm" //Onett (No Sunrise) (preliminary, crash)
.include "./sound/song125restored.asm" //Snowman (Imperfect, loop, some notes.)
.include "./sound/song148restored.asm" //Otherworldly Foe
.include "./sound/song175restored.asm" //Title Screen
.include "./sound/song176restored.asm" //Boss Swirl
.include "./sound/song185restored.asm" //Giygas is Wounded!
.include "./sound/song186restored.asm" //Giygas Stirs
.include "./sound/song204restored.asm" //Title Screen (Short)
.include "./sound/song324restored.asm" //Player Attack (Imperfect)
.include "./sound/song326restored.asm" //S w i s h (Unable to hear fwr)
.include "./sound/song329restored.asm" //Player Use PSI
.include "./sound/song330restored.asm" //Hit
.include "./sound/song331restored.asm" //SMAAAASHH!
.include "./sound/song332restored.asm" //ded
.include "./sound/song336restored.asm" //Lifeup noise
.include "./sound/song337restored.asm" //Cure noise
.include "./sound/song348restored.asm" //PSI Rockin (A) (Imperfect, instrumentation)
.include "./sound/song349restored.asm" //PSI Rockin (B)
.include "./sound/song350restored.asm" //PSI Rockin (C)
.include "./sound/song356restored.asm" //PSI Freeze (A)
.include "./sound/song357restored.asm" //PSI Freeze (B)
.include "./sound/song358restored.asm" //PSI Freeze (C)
.include "./sound/song364restored.asm" //PSI Starstorm
.include "./sound/song365restored.asm" //PSI Flash (A)
.include "./sound/song366restored.asm" //PSI Flash (B)
.include "./sound/song395restored.asm" //Magic Butterfly
//This repoints the sound bytes to their new locations
.org 0x810B540 :: .word song002restored
.org 0x810B548 :: .word song003restored
.org 0x810B568 :: .word song007restored
.org 0x810B570 :: .word song008restored
.org 0x810B598 :: .word song013restored
.org 0x810B5B0 :: .word song016restored
.org 0x810B618 :: .word song029restored
.org 0x810B678 :: .word song041restored
.org 0x810B690 :: .word song044restored
.org 0x810B6C0 :: .word song050restored
.org 0x810B6E8 :: .word song055restored
.org 0x810B6F8 :: .word song057restored
.org 0x810B770 :: .word song072restored
.org 0x810B778 :: .word song073restored
.org 0x810B780 :: .word song074restored
.org 0x810B7E8 :: .word song087restored
.org 0x810B838 :: .word song097restored
.org 0x810B850 :: .word song100restored
.org 0x810B858 :: .word song101restored
.org 0x810B870 :: .word song104restored
.org 0x810B878 :: .word song105restored
//.org 0x810B8F8 :: .word song121restored
.org 0x810B918 :: .word song125restored
.org 0x810B9D0 :: .word song148restored
.org 0x810B9E8 :: .word song041restored
.org 0x810BAA8 :: .word song175restored
.org 0x810BAB0 :: .word song176restored
.org 0x810BAF8 :: .word song185restored
.org 0x810BB00 :: .word song186restored
.org 0x810BB90 :: .word song204restored //Replace the shorter title screen
.org 0x810BF50 :: .word song324restored
.org 0x810BF60 :: .word song326restored
.org 0x810BF78 :: .word song329restored
.org 0x810BF80 :: .word song330restored
.org 0x810BF88 :: .word song331restored
.org 0x810BF90 :: .word song332restored
.org 0x810BFB0 :: .word song336restored
.org 0x810BFB8 :: .word song337restored
.org 0x810C010 :: .word song348restored
.org 0x810C018 :: .word song349restored
.org 0x810C020 :: .word song350restored
.org 0x810C050 :: .word song356restored
.org 0x810C058 :: .word song357restored
.org 0x810C060 :: .word song358restored
.org 0x810C090 :: .word song364restored
.org 0x810C098 :: .word song365restored
.org 0x810C0A0 :: .word song366restored
.org 0x810C188 :: .word song395restored
//Songs that Only need Minor changes
.org 0x82ADD23 :: .byte 0x1D //Speed up Song 169 (Eight Melodies [Giygas])
//Samples
.org 0x810A788 :: dw brass_stop_organ
.org 0x810A78C :: .byte 0xE7 //Better attack
.org 0x81081DD :: .byte 0xFC,0x00 //Fix decay+sustain for Weird Opponent melody
.org 0x810AE1D :: .byte 0xFA,0x00 //Make the guitar instrument fade out
//Notes about sound restoration
//003: Your name, please
//005: enemy defeated!
//007: A Bad Dream
//008: Enemy Encounter (Green/Blue)
//009: Enemy Encounter (Red)
//010: Eight Melodies
//011: Joined your Party!
//012: All Healed up!
//014: Teleport Crash
//015: Fall
//017: Ominous Neighbor
//018: Apple Kid's Theme
//020: Onett Arcade (wtf happened here)
//021: Pokey's Theme
//022: Hospital
//023: Home Sweet Home
//024: Paula's Theme
//026: Enjoy Your Stay
//027: Waking up from a rest in the hotel
//028: Buy Sumtin Will Ya!?
//042: Fire Spring
//043: Master Belch's Factory
//047: Fourside
//048: Saturn Valley
//049: Monkey Caves
//051: Dusty Dunes Desert
//052: Peaceful Rest Valley
//053: Happy Happy Village
//054: Winters
//056: Summers
//059: Dalaam
//060: Mu
//061: Scaraba
//062: The Unforgiving Desert
//063: Pyramid
//064: Deep Darkness
//065: Tenda Village
//334: Miss
//335: Dodge
//333: Enemy Death
//328: Pray
//327: Enemy S w i s h
//325: Robot Walk (holy frick the missed hard)
//311: Pick up/Hang up phone
//316: Item from preset
//338: Shield 1
//339: Shield 2
//341: Stat Down
//343: PSI Magnet
//344: PSI Paralysis (A)
//345: PSI Brainshock (A)
//346: Player gets hit
//347: Mortal Damage
//354: a cool noise that i dont know wtf it goes to
//359: HP Sucker
//368: Consume food
//372: Help
//379: PSI Paralysis (B)
//380: PSI Brainshock (B)
//382: Spores
//383: Status Ailment
//384: Y e l l
//390: Giygas gets fatally wounded
//399: Shield Killer
//402: Key Item
//403: Learn PSI
//404: chicken
//405-410: Sphinx Dance
//414: Spooky
//416: Place Item In Invetory
//429: Warp Guy
//
//Songs that are extremely difficult to do:
//148: Otherworldly foe
//
|
; A139277: a(n) = n*(8*n+5).
; 0,13,42,87,148,225,318,427,552,693,850,1023,1212,1417,1638,1875,2128,2397,2682,2983,3300,3633,3982,4347,4728,5125,5538,5967,6412,6873,7350,7843,8352,8877,9418,9975,10548,11137,11742,12363,13000
mov $1,8
mul $1,$0
add $1,5
mul $1,$0
mov $0,$1
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Quick Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet/wallet.h"
#include "base58.h"
#include "checkpoints.h"
#include "chain.h"
#include "coincontrol.h"
#include "consensus/consensus.h"
#include "consensus/validation.h"
#include "key.h"
#include "keystore.h"
#include "main.h"
#include "net.h"
#include "policy/policy.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/sign.h"
#include "timedata.h"
#include "txmempool.h"
#include "util.h"
#include "utilmoneystr.h"
#include "darksend.h"
#include "governance.h"
#include "instantx.h"
#include "keepass.h"
#include "spork.h"
#include <assert.h>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
using namespace std;
/** Transaction fee set by the user */
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
bool fSendFreeTransactions = DEFAULT_SEND_FREE_TRANSACTIONS;
/**
* Fees smaller than this (in duffs) are considered zero fee (for transaction creation)
* Override with -mintxfee
*/
CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
/**
* If fee estimation does not have enough data to provide estimates, use this fee instead.
* Has no effect if not using fee estimation
* Override with -fallbackfee
*/
CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
/** @defgroup mapWallet
*
* @{
*/
struct CompareValueOnly
{
bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
{
return t1.first < t2.first;
}
};
std::string COutput::ToString() const
{
return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
}
int COutput::Priority() const
{
BOOST_FOREACH(CAmount d, vecPrivateSendDenominations)
if(tx->vout[i].nValue == d) return 10000;
if(tx->vout[i].nValue < 1*COIN) return 20000;
//nondenom return largest first
return -(tx->vout[i].nValue/COIN);
}
const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
if (it == mapWallet.end())
return NULL;
return &(it->second);
}
CPubKey CWallet::GenerateNewKey()
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
CKey secret;
secret.MakeNewKey(fCompressed);
// Compressed public keys were introduced in version 0.6.0
if (fCompressed)
SetMinVersion(FEATURE_COMPRPUBKEY);
CPubKey pubkey = secret.GetPubKey();
assert(secret.VerifyPubKey(pubkey));
// Create new metadata
int64_t nCreationTime = GetTime();
mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
nTimeFirstKey = nCreationTime;
if (!AddKeyPubKey(secret, pubkey))
throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
return pubkey;
}
bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
return false;
// check if we need to remove from watch-only
CScript script;
script = GetScriptForDestination(pubkey.GetID());
if (HaveWatchOnly(script))
RemoveWatchOnly(script);
script = GetScriptForRawPubKey(pubkey);
if (HaveWatchOnly(script))
RemoveWatchOnly(script);
if (!fFileBacked)
return true;
if (!IsCrypted()) {
return CWalletDB(strWalletFile).WriteKey(pubkey,
secret.GetPrivKey(),
mapKeyMetadata[pubkey.GetID()]);
}
return true;
}
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
const vector<unsigned char> &vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
if (!fFileBacked)
return true;
{
LOCK(cs_wallet);
if (pwalletdbEncryption)
return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
else
return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
}
return false;
}
bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
nTimeFirstKey = meta.nCreateTime;
mapKeyMetadata[pubkey.GetID()] = meta;
return true;
}
bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
}
bool CWallet::AddCScript(const CScript& redeemScript)
{
if (!CCryptoKeyStore::AddCScript(redeemScript))
return false;
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
}
bool CWallet::LoadCScript(const CScript& redeemScript)
{
/* A sanity check was added in pull #3843 to avoid adding redeemScripts
* that never can be redeemed. However, old wallets may still contain
* these. Do not add them to the wallet and warn. */
if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
{
std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
__func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
return true;
}
return CCryptoKeyStore::AddCScript(redeemScript);
}
bool CWallet::AddWatchOnly(const CScript &dest)
{
if (!CCryptoKeyStore::AddWatchOnly(dest))
return false;
nTimeFirstKey = 1; // No birthday information for watch-only keys.
NotifyWatchonlyChanged(true);
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteWatchOnly(dest);
}
bool CWallet::RemoveWatchOnly(const CScript &dest)
{
AssertLockHeld(cs_wallet);
if (!CCryptoKeyStore::RemoveWatchOnly(dest))
return false;
if (!HaveWatchOnly())
NotifyWatchonlyChanged(false);
if (fFileBacked)
if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
return false;
return true;
}
bool CWallet::LoadWatchOnly(const CScript &dest)
{
return CCryptoKeyStore::AddWatchOnly(dest);
}
bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool fForMixingOnly)
{
SecureString strWalletPassphraseFinal;
if (!IsLocked()) // was already fully unlocked, not only for mixing
return true;
// Verify KeePassIntegration
if (strWalletPassphrase == "keepass" && GetBoolArg("-keepass", false)) {
try {
strWalletPassphraseFinal = keePassInt.retrievePassphrase();
} catch (std::exception& e) {
LogPrintf("CWallet::Unlock could not retrieve passphrase from KeePass: Error: %s\n", e.what());
return false;
}
} else {
strWalletPassphraseFinal = strWalletPassphrase;
}
CCrypter crypter;
CKeyingMaterial vMasterKey;
{
LOCK(cs_wallet);
BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
{
if (!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
continue; // try another master key
if (CCryptoKeyStore::Unlock(vMasterKey, fForMixingOnly)) {
if(nWalletBackups == -2) {
TopUpKeyPool();
LogPrintf("Keypool replenished, re-initializing automatic backups.\n");
nWalletBackups = GetArg("-createwalletbackups", 10);
}
return true;
}
}
}
return false;
}
bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
{
bool fWasLocked = IsLocked(true);
bool bUseKeePass = false;
SecureString strOldWalletPassphraseFinal;
// Verify KeePassIntegration
if(strOldWalletPassphrase == "keepass" && GetBoolArg("-keepass", false)) {
bUseKeePass = true;
try {
strOldWalletPassphraseFinal = keePassInt.retrievePassphrase();
} catch (std::exception& e) {
LogPrintf("CWallet::ChangeWalletPassphrase -- could not retrieve passphrase from KeePass: Error: %s\n", e.what());
return false;
}
} else {
strOldWalletPassphraseFinal = strOldWalletPassphrase;
}
{
LOCK(cs_wallet);
Lock();
CCrypter crypter;
CKeyingMaterial vMasterKey;
BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
return false;
if (CCryptoKeyStore::Unlock(vMasterKey))
{
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (pMasterKey.second.nDeriveIterations < 25000)
pMasterKey.second.nDeriveIterations = 25000;
LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
return false;
CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked)
Lock();
// Update KeePass if necessary
if(bUseKeePass) {
LogPrintf("CWallet::ChangeWalletPassphrase -- Updating KeePass with new passphrase");
try {
keePassInt.updatePassphrase(strNewWalletPassphrase);
} catch (std::exception& e) {
LogPrintf("CWallet::ChangeWalletPassphrase -- could not update passphrase in KeePass: Error: %s\n", e.what());
return false;
}
}
return true;
}
}
}
return false;
}
void CWallet::SetBestChain(const CBlockLocator& loc)
{
CWalletDB walletdb(strWalletFile);
walletdb.WriteBestBlock(loc);
}
bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
{
LOCK(cs_wallet); // nWalletVersion
if (nWalletVersion >= nVersion)
return true;
// when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
if (fExplicit && nVersion > nWalletMaxVersion)
nVersion = FEATURE_LATEST;
nWalletVersion = nVersion;
if (nVersion > nWalletMaxVersion)
nWalletMaxVersion = nVersion;
if (fFileBacked)
{
CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
if (nWalletVersion > 40000)
pwalletdb->WriteMinVersion(nWalletVersion);
if (!pwalletdbIn)
delete pwalletdb;
}
return true;
}
bool CWallet::SetMaxVersion(int nVersion)
{
LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
// cannot downgrade below current version
if (nWalletVersion > nVersion)
return false;
nWalletMaxVersion = nVersion;
return true;
}
set<uint256> CWallet::GetConflicts(const uint256& txid) const
{
set<uint256> result;
AssertLockHeld(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
if (it == mapWallet.end())
return result;
const CWalletTx& wtx = it->second;
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
if (mapTxSpends.count(txin.prevout) <= 1)
continue; // No conflict if zero or one spends
range = mapTxSpends.equal_range(txin.prevout);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
result.insert(it->second);
}
return result;
}
void CWallet::Flush(bool shutdown)
{
bitdb.Flush(shutdown);
}
bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
{
if (!bitdb.Open(GetDataDir()))
{
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
} catch (const boost::filesystem::filesystem_error&) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
errorString += msg;
return true;
}
}
if (GetBoolArg("-salvagewallet", false))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, walletFile, true))
return false;
}
if (boost::filesystem::exists(GetDataDir() / walletFile))
{
CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), GetDataDir());
}
if (r == CDBEnv::RECOVER_FAIL)
errorString += _("wallet.dat corrupt, salvage failed");
}
return true;
}
void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
{
// We want all the wallet transactions in range to have the same metadata as
// the oldest (smallest nOrderPos).
// So: find smallest nOrderPos:
int nMinOrderPos = std::numeric_limits<int>::max();
const CWalletTx* copyFrom = NULL;
for (TxSpends::iterator it = range.first; it != range.second; ++it)
{
const uint256& hash = it->second;
int n = mapWallet[hash].nOrderPos;
if (n < nMinOrderPos)
{
nMinOrderPos = n;
copyFrom = &mapWallet[hash];
}
}
// Now copy data from copyFrom to rest:
for (TxSpends::iterator it = range.first; it != range.second; ++it)
{
const uint256& hash = it->second;
CWalletTx* copyTo = &mapWallet[hash];
if (copyFrom == copyTo) continue;
if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
// fTimeReceivedIsTxTime not copied on purpose
// nTimeReceived not copied on purpose
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
// nOrderPos not copied on purpose
// cached members not copied on purpose
}
}
/**
* Outpoint is spent if any non-conflicted transaction
* spends it:
*/
bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
{
const COutPoint outpoint(hash, n);
pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
range = mapTxSpends.equal_range(outpoint);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
{
const uint256& wtxid = it->second;
std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
if (mit != mapWallet.end()) {
int depth = mit->second.GetDepthInMainChain();
if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
return true; // Spent
}
}
return false;
}
void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
{
mapTxSpends.insert(make_pair(outpoint, wtxid));
pair<TxSpends::iterator, TxSpends::iterator> range;
range = mapTxSpends.equal_range(outpoint);
SyncMetaData(range);
}
void CWallet::AddToSpends(const uint256& wtxid)
{
assert(mapWallet.count(wtxid));
CWalletTx& thisTx = mapWallet[wtxid];
if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
return;
BOOST_FOREACH(const CTxIn& txin, thisTx.vin)
AddToSpends(txin.prevout, wtxid);
}
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{
if (IsCrypted())
return false;
CKeyingMaterial vMasterKey;
RandAddSeedPerfmon();
vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
CMasterKey kMasterKey;
RandAddSeedPerfmon();
kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
CCrypter crypter;
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (kMasterKey.nDeriveIterations < 25000)
kMasterKey.nDeriveIterations = 25000;
LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
return false;
{
LOCK(cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
if (fFileBacked)
{
assert(!pwalletdbEncryption);
pwalletdbEncryption = new CWalletDB(strWalletFile);
if (!pwalletdbEncryption->TxnBegin()) {
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
return false;
}
pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
}
if (!EncryptKeys(vMasterKey))
{
if (fFileBacked) {
pwalletdbEncryption->TxnAbort();
delete pwalletdbEncryption;
}
// We now probably have half of our keys encrypted in memory, and half not...
// die and let the user reload the unencrypted wallet.
assert(false);
}
// Encryption was introduced in version 0.4.0
SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
if (fFileBacked)
{
if (!pwalletdbEncryption->TxnCommit()) {
delete pwalletdbEncryption;
// We now have keys encrypted in memory, but not on disk...
// die to avoid confusion and let the user reload the unencrypted wallet.
assert(false);
}
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
}
Lock();
Unlock(strWalletPassphrase);
NewKeyPool();
Lock();
// Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file.
CDB::Rewrite(strWalletFile);
// Update KeePass if necessary
if(GetBoolArg("-keepass", false)) {
LogPrintf("CWallet::EncryptWallet -- Updating KeePass with new passphrase");
try {
keePassInt.updatePassphrase(strWalletPassphrase);
} catch (std::exception& e) {
LogPrintf("CWallet::EncryptWallet -- could not update passphrase in KeePass: Error: %s\n", e.what());
}
}
}
NotifyStatusChanged(this);
return true;
}
int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
{
AssertLockHeld(cs_wallet); // nOrderPosNext
int64_t nRet = nOrderPosNext++;
if (pwalletdb) {
pwalletdb->WriteOrderPosNext(nOrderPosNext);
} else {
CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
}
return nRet;
}
void CWallet::MarkDirty()
{
{
LOCK(cs_wallet);
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
item.second.MarkDirty();
}
fAnonymizableTallyCached = false;
fAnonymizableTallyCachedNonDenom = false;
}
bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
{
uint256 hash = wtxIn.GetHash();
if (fFromLoadWallet)
{
mapWallet[hash] = wtxIn;
CWalletTx& wtx = mapWallet[hash];
wtx.BindWallet(this);
wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
AddToSpends(hash);
BOOST_FOREACH(const CTxIn& txin, wtx.vin) {
if (mapWallet.count(txin.prevout.hash)) {
CWalletTx& prevtx = mapWallet[txin.prevout.hash];
if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
MarkConflicted(prevtx.hashBlock, wtx.GetHash());
}
}
}
}
else
{
LOCK(cs_wallet);
// Inserts only if not already there, returns tx inserted or tx found
pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this);
bool fInsertedNew = ret.second;
if (fInsertedNew)
{
wtx.nTimeReceived = GetAdjustedTime();
wtx.nOrderPos = IncOrderPosNext(pwalletdb);
wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
wtx.nTimeSmart = wtx.nTimeReceived;
if (!wtxIn.hashUnset())
{
if (mapBlockIndex.count(wtxIn.hashBlock))
{
int64_t latestNow = wtx.nTimeReceived;
int64_t latestEntry = 0;
{
// Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
int64_t latestTolerated = latestNow + 300;
const TxItems & txOrdered = wtxOrdered;
for (TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx == &wtx)
continue;
CAccountingEntry *const pacentry = (*it).second.second;
int64_t nSmartTime;
if (pwtx)
{
nSmartTime = pwtx->nTimeSmart;
if (!nSmartTime)
nSmartTime = pwtx->nTimeReceived;
}
else
nSmartTime = pacentry->nTime;
if (nSmartTime <= latestTolerated)
{
latestEntry = nSmartTime;
if (nSmartTime > latestNow)
latestNow = nSmartTime;
break;
}
}
}
int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
}
else
LogPrintf("AddToWallet(): found %s in block %s not in index\n",
wtxIn.GetHash().ToString(),
wtxIn.hashBlock.ToString());
}
AddToSpends(hash);
}
bool fUpdated = false;
if (!fInsertedNew)
{
// Merge
if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
// If no longer abandoned, update
if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
{
wtx.nIndex = wtxIn.nIndex;
fUpdated = true;
}
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
{
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
}
}
//// debug print
LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
if (!wtx.WriteToDisk(pwalletdb))
return false;
// Break debit/credit balance caches:
wtx.MarkDirty();
// Notify UI of new or updated transaction
NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
// notify an external script when a wallet transaction comes in or is updated
std::string strCmd = GetArg("-walletnotify", "");
if ( !strCmd.empty())
{
boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
fAnonymizableTallyCached = false;
fAnonymizableTallyCachedNonDenom = false;
}
return true;
}
/**
* Add a transaction to the wallet, or update it.
* pblock is optional, but should be provided if the transaction is known to be in a block.
* If fUpdate is true, existing transactions will be updated.
*/
bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
{
{
AssertLockHeld(cs_wallet);
if (pblock) {
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
while (range.first != range.second) {
if (range.first->second != tx.GetHash()) {
LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pblock->GetHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
MarkConflicted(pblock->GetHash(), range.first->second);
}
range.first++;
}
}
}
bool fExisted = mapWallet.count(tx.GetHash()) != 0;
if (fExisted && !fUpdate) return false;
if (fExisted || IsMine(tx) || IsFromMe(tx))
{
CWalletTx wtx(this,tx);
// Get merkle branch if transaction was found in a block
if (pblock)
wtx.SetMerkleBranch(*pblock);
// Do not flush the wallet here for performance reasons
// this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
CWalletDB walletdb(strWalletFile, "r+", false);
return AddToWallet(wtx, false, &walletdb);
}
}
return false;
}
bool CWallet::AbandonTransaction(const uint256& hashTx)
{
LOCK2(cs_main, cs_wallet);
// Do not flush the wallet here for performance reasons
CWalletDB walletdb(strWalletFile, "r+", false);
std::set<uint256> todo;
std::set<uint256> done;
// Can't mark abandoned if confirmed or in mempool
assert(mapWallet.count(hashTx));
CWalletTx& origtx = mapWallet[hashTx];
if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
return false;
}
todo.insert(hashTx);
while (!todo.empty()) {
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
assert(mapWallet.count(now));
CWalletTx& wtx = mapWallet[now];
int currentconfirm = wtx.GetDepthInMainChain();
// If the orig tx was not in block, none of its spends can be
assert(currentconfirm <= 0);
// if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
if (currentconfirm == 0 && !wtx.isAbandoned()) {
// If the orig tx was not in block/mempool, none of its spends can be in mempool
assert(!wtx.InMempool());
wtx.nIndex = -1;
wtx.setAbandoned();
wtx.MarkDirty();
wtx.WriteToDisk(&walletdb);
NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
// Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
if (!done.count(iter->second)) {
todo.insert(iter->second);
}
iter++;
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
if (mapWallet.count(txin.prevout.hash))
mapWallet[txin.prevout.hash].MarkDirty();
}
}
}
fAnonymizableTallyCached = false;
fAnonymizableTallyCachedNonDenom = false;
return true;
}
void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
{
LOCK2(cs_main, cs_wallet);
int conflictconfirms = 0;
if (mapBlockIndex.count(hashBlock)) {
CBlockIndex* pindex = mapBlockIndex[hashBlock];
if (chainActive.Contains(pindex)) {
conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
}
}
// If number of conflict confirms cannot be determined, this means
// that the block is still unknown or not yet part of the main chain,
// for example when loading the wallet during a reindex. Do nothing in that
// case.
if (conflictconfirms >= 0)
return;
// Do not flush the wallet here for performance reasons
CWalletDB walletdb(strWalletFile, "r+", false);
std::set<uint256> todo;
std::set<uint256> done;
todo.insert(hashTx);
while (!todo.empty()) {
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
assert(mapWallet.count(now));
CWalletTx& wtx = mapWallet[now];
int currentconfirm = wtx.GetDepthInMainChain();
if (conflictconfirms < currentconfirm) {
// Block is 'more conflicted' than current confirm; update.
// Mark transaction as conflicted with this block.
wtx.nIndex = -1;
wtx.hashBlock = hashBlock;
wtx.MarkDirty();
wtx.WriteToDisk(&walletdb);
// Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
if (!done.count(iter->second)) {
todo.insert(iter->second);
}
iter++;
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
if (mapWallet.count(txin.prevout.hash))
mapWallet[txin.prevout.hash].MarkDirty();
}
}
}
fAnonymizableTallyCached = false;
fAnonymizableTallyCachedNonDenom = false;
}
void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
{
LOCK2(cs_main, cs_wallet);
if (!AddToWalletIfInvolvingMe(tx, pblock, true))
return; // Not one of ours
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be
// recomputed, also:
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
if (mapWallet.count(txin.prevout.hash))
mapWallet[txin.prevout.hash].MarkDirty();
}
fAnonymizableTallyCached = false;
fAnonymizableTallyCachedNonDenom = false;
}
isminetype CWallet::IsMine(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
return IsMine(prev.vout[txin.prevout.n]);
}
}
return ISMINE_NO;
}
CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]) & filter)
return prev.vout[txin.prevout.n].nValue;
}
}
return 0;
}
// Recursively determine the rounds of a given input (How deep is the PrivateSend chain for a given input)
int CWallet::GetRealInputPrivateSendRounds(CTxIn txin, int nRounds) const
{
static std::map<uint256, CMutableTransaction> mDenomWtxes;
if(nRounds >= 16) return 15; // 16 rounds max
uint256 hash = txin.prevout.hash;
unsigned int nout = txin.prevout.n;
const CWalletTx* wtx = GetWalletTx(hash);
if(wtx != NULL)
{
std::map<uint256, CMutableTransaction>::const_iterator mdwi = mDenomWtxes.find(hash);
if (mdwi == mDenomWtxes.end()) {
// not known yet, let's add it
LogPrint("privatesend", "GetRealInputPrivateSendRounds INSERTING %s\n", hash.ToString());
mDenomWtxes[hash] = CMutableTransaction(*wtx);
} else if(mDenomWtxes[hash].vout[nout].nRounds != -10) {
// found and it's not an initial value, just return it
return mDenomWtxes[hash].vout[nout].nRounds;
}
// bounds check
if (nout >= wtx->vout.size()) {
// should never actually hit this
LogPrint("privatesend", "GetRealInputPrivateSendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, -4);
return -4;
}
if (IsCollateralAmount(wtx->vout[nout].nValue)) {
mDenomWtxes[hash].vout[nout].nRounds = -3;
LogPrint("privatesend", "GetRealInputPrivateSendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds);
return mDenomWtxes[hash].vout[nout].nRounds;
}
//make sure the final output is non-denominate
if (!IsDenominatedAmount(wtx->vout[nout].nValue)) { //NOT DENOM
mDenomWtxes[hash].vout[nout].nRounds = -2;
LogPrint("privatesend", "GetRealInputPrivateSendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds);
return mDenomWtxes[hash].vout[nout].nRounds;
}
bool fAllDenoms = true;
BOOST_FOREACH(CTxOut out, wtx->vout) {
fAllDenoms = fAllDenoms && IsDenominatedAmount(out.nValue);
}
// this one is denominated but there is another non-denominated output found in the same tx
if (!fAllDenoms) {
mDenomWtxes[hash].vout[nout].nRounds = 0;
LogPrint("privatesend", "GetRealInputPrivateSendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds);
return mDenomWtxes[hash].vout[nout].nRounds;
}
int nShortest = -10; // an initial value, should be no way to get this by calculations
bool fDenomFound = false;
// only denoms here so let's look up
BOOST_FOREACH(CTxIn txinNext, wtx->vin) {
if (IsMine(txinNext)) {
int n = GetRealInputPrivateSendRounds(txinNext, nRounds + 1);
// denom found, find the shortest chain or initially assign nShortest with the first found value
if(n >= 0 && (n < nShortest || nShortest == -10)) {
nShortest = n;
fDenomFound = true;
}
}
}
mDenomWtxes[hash].vout[nout].nRounds = fDenomFound
? (nShortest >= 15 ? 16 : nShortest + 1) // good, we a +1 to the shortest one but only 16 rounds max allowed
: 0; // too bad, we are the fist one in that chain
LogPrint("privatesend", "GetRealInputPrivateSendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds);
return mDenomWtxes[hash].vout[nout].nRounds;
}
return nRounds - 1;
}
// respect current settings
int CWallet::GetInputPrivateSendRounds(CTxIn txin) const
{
LOCK(cs_wallet);
int realPrivateSendRounds = GetRealInputPrivateSendRounds(txin, 0);
return realPrivateSendRounds > nPrivateSendRounds ? nPrivateSendRounds : realPrivateSendRounds;
}
bool CWallet::IsDenominated(const CTxIn &txin) const
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end()) {
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size()) {
return IsDenominatedAmount(prev.vout[txin.prevout.n].nValue);
}
}
return false;
}
bool CWallet::IsDenominatedAmount(CAmount nInputAmount) const
{
BOOST_FOREACH(CAmount d, vecPrivateSendDenominations)
if(nInputAmount == d)
return true;
return false;
}
isminetype CWallet::IsMine(const CTxOut& txout) const
{
return ::IsMine(*this, txout.scriptPubKey);
}
CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error("CWallet::GetCredit(): value out of range");
return ((IsMine(txout) & filter) ? txout.nValue : 0);
}
bool CWallet::IsChange(const CTxOut& txout) const
{
// TODO: fix handling of 'change' outputs. The assumption is that any
// payment to a script that is ours, but is not in the address book
// is change. That assumption is likely to break when we implement multisignature
// wallets that return change back into a multi-signature-protected address;
// a better way of identifying which outputs are 'the send' and which are
// 'the change' will need to be implemented (maybe extend CWalletTx to remember
// which output, if any, was change).
if (::IsMine(*this, txout.scriptPubKey))
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
return true;
LOCK(cs_wallet);
if (!mapAddressBook.count(address))
return true;
}
return false;
}
CAmount CWallet::GetChange(const CTxOut& txout) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error("CWallet::GetChange(): value out of range");
return (IsChange(txout) ? txout.nValue : 0);
}
bool CWallet::IsMine(const CTransaction& tx) const
{
BOOST_FOREACH(const CTxOut& txout, tx.vout)
if (IsMine(txout))
return true;
return false;
}
bool CWallet::IsFromMe(const CTransaction& tx) const
{
return (GetDebit(tx, ISMINE_ALL) > 0);
}
CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nDebit = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
nDebit += GetDebit(txin, filter);
if (!MoneyRange(nDebit))
throw std::runtime_error("CWallet::GetDebit(): value out of range");
}
return nDebit;
}
CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nCredit = 0;
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nCredit += GetCredit(txout, filter);
if (!MoneyRange(nCredit))
throw std::runtime_error("CWallet::GetCredit(): value out of range");
}
return nCredit;
}
CAmount CWallet::GetChange(const CTransaction& tx) const
{
CAmount nChange = 0;
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nChange += GetChange(txout);
if (!MoneyRange(nChange))
throw std::runtime_error("CWallet::GetChange(): value out of range");
}
return nChange;
}
int64_t CWalletTx::GetTxTime() const
{
int64_t n = nTimeSmart;
return n ? n : nTimeReceived;
}
int CWalletTx::GetRequestCount() const
{
// Returns -1 if it wasn't being tracked
int nRequests = -1;
{
LOCK(pwallet->cs_wallet);
if (IsCoinBase())
{
// Generated block
if (!hashUnset())
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
}
}
else
{
// Did anyone request this transaction?
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
if (mi != pwallet->mapRequestCount.end())
{
nRequests = (*mi).second;
// How about the block it's in?
if (nRequests == 0 && !hashUnset())
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
else
nRequests = 1; // If it's in someone else's block it must have got out
}
}
}
}
return nRequests;
}
void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
{
nFee = 0;
listReceived.clear();
listSent.clear();
strSentAccount = strFromAccount;
// Compute fee:
CAmount nDebit = GetDebit(filter);
if (nDebit > 0) // debit>0 means we signed/sent this transaction
{
CAmount nValueOut = GetValueOut();
nFee = nDebit - nValueOut;
}
// Sent/received.
for (unsigned int i = 0; i < vout.size(); ++i)
{
const CTxOut& txout = vout[i];
isminetype fIsMine = pwallet->IsMine(txout);
// Only need to handle txouts if AT LEAST one of these is true:
// 1) they debit from us (sent)
// 2) the output is to us (received)
if (nDebit > 0)
{
// Don't report 'change' txouts
if (pwallet->IsChange(txout))
continue;
}
else if (!(fIsMine & filter))
continue;
// In either case, we need to get the destination address
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
{
LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
this->GetHash().ToString());
address = CNoDestination();
}
COutputEntry output = {address, txout.nValue, (int)i};
// If we are debited by the transaction, add the output as a "sent" entry
if (nDebit > 0)
listSent.push_back(output);
// If we are receiving the output, add it as a "received" entry
if (fIsMine & filter)
listReceived.push_back(output);
}
}
void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
{
nReceived = nSent = nFee = 0;
CAmount allFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (strAccount == strSentAccount)
{
BOOST_FOREACH(const COutputEntry& s, listSent)
nSent += s.amount;
nFee = allFee;
}
{
LOCK(pwallet->cs_wallet);
BOOST_FOREACH(const COutputEntry& r, listReceived)
{
if (pwallet->mapAddressBook.count(r.destination))
{
map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
nReceived += r.amount;
}
else if (strAccount.empty())
{
nReceived += r.amount;
}
}
}
}
bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
{
return pwalletdb->WriteTx(GetHash(), *this);
}
/**
* Scan the block chain (starting in pindexStart) for transactions
* from or to us. If fUpdate is true, found transactions that already
* exist in the wallet will be updated.
*/
int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
{
int ret = 0;
int64_t nNow = GetTime();
const CChainParams& chainParams = Params();
CBlockIndex* pindex = pindexStart;
{
LOCK2(cs_main, cs_wallet);
// no need to read and scan block, if block was created before
// our wallet birthday (as adjusted for block time variability)
while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
pindex = chainActive.Next(pindex);
ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
while (pindex)
{
if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
CBlock block;
ReadBlockFromDisk(block, pindex, Params().GetConsensus());
BOOST_FOREACH(CTransaction& tx, block.vtx)
{
if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
ret++;
}
pindex = chainActive.Next(pindex);
if (GetTime() >= nNow + 60) {
nNow = GetTime();
LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
}
}
ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
}
return ret;
}
void CWallet::ReacceptWalletTransactions()
{
// If transactions aren't being broadcasted, don't let them into local mempool either
if (!fBroadcastTransactions)
return;
LOCK2(cs_main, cs_wallet);
std::map<int64_t, CWalletTx*> mapSorted;
// Sort pending wallet transactions based on their initial wallet insertion order
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
const uint256& wtxid = item.first;
CWalletTx& wtx = item.second;
assert(wtx.GetHash() == wtxid);
int nDepth = wtx.GetDepthInMainChain();
if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
}
}
// Try to add wallet transactions to memory pool
BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
{
CWalletTx& wtx = *(item.second);
LOCK(mempool.cs);
wtx.AcceptToMemoryPool(false);
}
}
bool CWalletTx::RelayWalletTransaction(std::string strCommand)
{
assert(pwallet->GetBroadcastTransactions());
if (!IsCoinBase())
{
if (GetDepthInMainChain() == 0 && !isAbandoned() && InMempool()) {
uint256 hash = GetHash();
LogPrintf("Relaying wtx %s\n", hash.ToString());
if(strCommand == NetMsgType::TXLOCKREQUEST) {
instantsend.ProcessTxLockRequest(((CTxLockRequest)*this));
}
RelayTransaction((CTransaction)*this);
return true;
}
}
return false;
}
set<uint256> CWalletTx::GetConflicts() const
{
set<uint256> result;
if (pwallet != NULL)
{
uint256 myHash = GetHash();
result = pwallet->GetConflicts(myHash);
result.erase(myHash);
}
return result;
}
CAmount CWalletTx::GetDebit(const isminefilter& filter) const
{
if (vin.empty())
return 0;
CAmount debit = 0;
if(filter & ISMINE_SPENDABLE)
{
if (fDebitCached)
debit += nDebitCached;
else
{
nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
fDebitCached = true;
debit += nDebitCached;
}
}
if(filter & ISMINE_WATCH_ONLY)
{
if(fWatchDebitCached)
debit += nWatchDebitCached;
else
{
nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
fWatchDebitCached = true;
debit += nWatchDebitCached;
}
}
return debit;
}
CAmount CWalletTx::GetCredit(const isminefilter& filter) const
{
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
int64_t credit = 0;
if (filter & ISMINE_SPENDABLE)
{
// GetBalance can assume transactions in mapWallet won't change
if (fCreditCached)
credit += nCreditCached;
else
{
nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
fCreditCached = true;
credit += nCreditCached;
}
}
if (filter & ISMINE_WATCH_ONLY)
{
if (fWatchCreditCached)
credit += nWatchCreditCached;
else
{
nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
fWatchCreditCached = true;
credit += nWatchCreditCached;
}
}
return credit;
}
CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
{
if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
{
if (fUseCache && fImmatureCreditCached)
return nImmatureCreditCached;
nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
fImmatureCreditCached = true;
return nImmatureCreditCached;
}
return 0;
}
CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
{
if (pwallet == 0)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && fAvailableCreditCached)
return nAvailableCreditCached;
CAmount nCredit = 0;
uint256 hashTx = GetHash();
for (unsigned int i = 0; i < vout.size(); i++)
{
if (!pwallet->IsSpent(hashTx, i))
{
const CTxOut &txout = vout[i];
nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
if (!MoneyRange(nCredit))
throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
}
}
nAvailableCreditCached = nCredit;
fAvailableCreditCached = true;
return nCredit;
}
CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
{
if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
{
if (fUseCache && fImmatureWatchCreditCached)
return nImmatureWatchCreditCached;
nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
fImmatureWatchCreditCached = true;
return nImmatureWatchCreditCached;
}
return 0;
}
CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
{
if (pwallet == 0)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && fAvailableWatchCreditCached)
return nAvailableWatchCreditCached;
CAmount nCredit = 0;
for (unsigned int i = 0; i < vout.size(); i++)
{
if (!pwallet->IsSpent(GetHash(), i))
{
const CTxOut &txout = vout[i];
nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
if (!MoneyRange(nCredit))
throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
}
}
nAvailableWatchCreditCached = nCredit;
fAvailableWatchCreditCached = true;
return nCredit;
}
CAmount CWalletTx::GetAnonymizedCredit(bool fUseCache) const
{
if (pwallet == 0)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && fAnonymizedCreditCached)
return nAnonymizedCreditCached;
CAmount nCredit = 0;
uint256 hashTx = GetHash();
for (unsigned int i = 0; i < vout.size(); i++)
{
const CTxOut &txout = vout[i];
const CTxIn txin = CTxIn(hashTx, i);
if(pwallet->IsSpent(hashTx, i) || !pwallet->IsDenominated(txin)) continue;
const int nRounds = pwallet->GetInputPrivateSendRounds(txin);
if(nRounds >= nPrivateSendRounds){
nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
if (!MoneyRange(nCredit))
throw std::runtime_error("CWalletTx::GetAnonymizedCredit() : value out of range");
}
}
nAnonymizedCreditCached = nCredit;
fAnonymizedCreditCached = true;
return nCredit;
}
CAmount CWalletTx::GetDenominatedCredit(bool unconfirmed, bool fUseCache) const
{
if (pwallet == 0)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
int nDepth = GetDepthInMainChain(false);
if(nDepth < 0) return 0;
bool isUnconfirmed = IsTrusted() && nDepth == 0;
if(unconfirmed != isUnconfirmed) return 0;
if (fUseCache) {
if(unconfirmed && fDenomUnconfCreditCached)
return nDenomUnconfCreditCached;
else if (!unconfirmed && fDenomConfCreditCached)
return nDenomConfCreditCached;
}
CAmount nCredit = 0;
uint256 hashTx = GetHash();
for (unsigned int i = 0; i < vout.size(); i++)
{
const CTxOut &txout = vout[i];
if(pwallet->IsSpent(hashTx, i) || !pwallet->IsDenominatedAmount(vout[i].nValue)) continue;
nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
if (!MoneyRange(nCredit))
throw std::runtime_error("CWalletTx::GetDenominatedCredit() : value out of range");
}
if(unconfirmed) {
nDenomUnconfCreditCached = nCredit;
fDenomUnconfCreditCached = true;
} else {
nDenomConfCreditCached = nCredit;
fDenomConfCreditCached = true;
}
return nCredit;
}
CAmount CWalletTx::GetChange() const
{
if (fChangeCached)
return nChangeCached;
nChangeCached = pwallet->GetChange(*this);
fChangeCached = true;
return nChangeCached;
}
bool CWalletTx::InMempool() const
{
LOCK(mempool.cs);
if (mempool.exists(GetHash())) {
return true;
}
return false;
}
bool CWalletTx::IsTrusted() const
{
// Quick answer in most cases
if (!CheckFinalTx(*this))
return false;
int nDepth = GetDepthInMainChain();
if (nDepth >= 1)
return true;
if (nDepth < 0)
return false;
if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
return false;
// Don't trust unconfirmed transactions from us unless they are in the mempool.
if (!InMempool())
return false;
// Trusted if all inputs are from us and are in the mempool:
BOOST_FOREACH(const CTxIn& txin, vin)
{
// Transactions not sent by us: not trusted
const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
if (parent == NULL)
return false;
const CTxOut& parentOut = parent->vout[txin.prevout.n];
if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
return false;
}
return true;
}
bool CWalletTx::IsEquivalentTo(const CWalletTx& tx) const
{
CMutableTransaction tx1 = *this;
CMutableTransaction tx2 = tx;
for (unsigned int i = 0; i < tx1.vin.size(); i++) tx1.vin[i].scriptSig = CScript();
for (unsigned int i = 0; i < tx2.vin.size(); i++) tx2.vin[i].scriptSig = CScript();
return CTransaction(tx1) == CTransaction(tx2);
}
std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
{
std::vector<uint256> result;
LOCK(cs_wallet);
// Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
// Don't rebroadcast if newer than nTime:
if (wtx.nTimeReceived > nTime)
continue;
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
}
BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
{
CWalletTx& wtx = *item.second;
if (wtx.RelayWalletTransaction())
result.push_back(wtx.GetHash());
}
return result;
}
void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
{
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
if (GetTime() < nNextResend || !fBroadcastTransactions)
return;
bool fFirst = (nNextResend == 0);
nNextResend = GetTime() + GetRand(30 * 60);
if (fFirst)
return;
// Only do it if there's been a new block since last time
if (nBestBlockTime < nLastResend)
return;
nLastResend = GetTime();
// Rebroadcast unconfirmed txes older than 5 minutes before the last
// block was found:
std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
if (!relayed.empty())
LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
}
/** @} */ // end of mapWallet
/** @defgroup Actions
*
* @{
*/
CAmount CWallet::GetBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetAnonymizableBalance(bool fSkipDenominated) const
{
if(fLiteMode) return 0;
std::vector<CompactTallyItem> vecTally;
if(!SelectCoinsGrouppedByAddresses(vecTally, fSkipDenominated)) return 0;
CAmount nTotal = 0;
BOOST_FOREACH(CompactTallyItem& item, vecTally) {
bool fIsDenominated = IsDenominatedAmount(item.nAmount);
if(fSkipDenominated && fIsDenominated) continue;
// assume that the fee to create denoms be PRIVATESEND_COLLATERAL at max
if(item.nAmount >= vecPrivateSendDenominations.back() + (fIsDenominated ? 0 : PRIVATESEND_COLLATERAL))
nTotal += item.nAmount;
}
return nTotal;
}
CAmount CWallet::GetAnonymizedBalance() const
{
if(fLiteMode) return 0;
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAnonymizedCredit();
}
}
return nTotal;
}
// Note: calculated including unconfirmed,
// that's ok as long as we use it for informational purposes only
double CWallet::GetAverageAnonymizedRounds() const
{
if(fLiteMode) return 0;
double fTotal = 0;
double fCount = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
uint256 hash = (*it).first;
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
CTxIn vin = CTxIn(hash, i);
if(IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue;
int rounds = GetInputPrivateSendRounds(vin);
fTotal += (float)rounds;
fCount += 1;
}
}
}
if(fCount == 0) return 0;
return fTotal/fCount;
}
// Note: calculated including unconfirmed,
// that's ok as long as we use it for informational purposes only
CAmount CWallet::GetNormalizedAnonymizedBalance() const
{
if(fLiteMode) return 0;
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
uint256 hash = (*it).first;
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
CTxIn txin = CTxIn(hash, i);
if(IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(txin)) continue;
if (pcoin->GetDepthInMainChain() < 0) continue;
int nRounds = GetInputPrivateSendRounds(txin);
nTotal += pcoin->vout[i].nValue * nRounds / nPrivateSendRounds;
}
}
}
return nTotal;
}
CAmount CWallet::GetNeedsToBeAnonymizedBalance(CAmount nMinBalance) const
{
if(fLiteMode) return 0;
CAmount nAnonymizedBalance = GetAnonymizedBalance();
CAmount nNeedsToAnonymizeBalance = nPrivateSendAmount*COIN - nAnonymizedBalance;
// try to overshoot target DS balance up to nMinBalance
nNeedsToAnonymizeBalance += nMinBalance;
CAmount nAnonymizableBalance = GetAnonymizableBalance();
// anonymizable balance is way too small
if(nAnonymizableBalance < nMinBalance) return 0;
// not enough funds to anonymze amount we want, try the max we can
if(nNeedsToAnonymizeBalance > nAnonymizableBalance) nNeedsToAnonymizeBalance = nAnonymizableBalance;
// we should never exceed the pool max
if (nNeedsToAnonymizeBalance > PRIVATESEND_POOL_MAX) nNeedsToAnonymizeBalance = PRIVATESEND_POOL_MAX;
return nNeedsToAnonymizeBalance;
}
CAmount CWallet::GetDenominatedBalance(bool unconfirmed) const
{
if(fLiteMode) return 0;
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetDenominatedCredit(unconfirmed);
}
}
return nTotal;
}
CAmount CWallet::GetUnconfirmedBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureCredit();
}
}
return nTotal;
}
CAmount CWallet::GetWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableWatchOnlyCredit();
}
}
return nTotal;
}
CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
nTotal += pcoin->GetAvailableWatchOnlyCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureWatchOnlyCredit();
}
}
return nTotal;
}
void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue, AvailableCoinsType nCoinType, bool fUseInstantSend) const
{
vCoins.clear();
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const uint256& wtxid = it->first;
const CWalletTx* pcoin = &(*it).second;
if (!CheckFinalTx(*pcoin))
continue;
if (fOnlyConfirmed && !pcoin->IsTrusted())
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain(false);
// do not use IX for inputs that have less then INSTANTSEND_CONFIRMATIONS_REQUIRED blockchain confirmations
if (fUseInstantSend && nDepth < INSTANTSEND_CONFIRMATIONS_REQUIRED)
continue;
// We should not consider coins which aren't at least in our mempool
// It's possible for these to be conflicted via ancestors which we may never be able to detect
if (nDepth == 0 && !pcoin->InMempool())
continue;
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
bool found = false;
if(nCoinType == ONLY_DENOMINATED) {
found = IsDenominatedAmount(pcoin->vout[i].nValue);
} else if(nCoinType == ONLY_NOT1000IFMN) {
found = !(fMasterNode && pcoin->vout[i].nValue == 1000*COIN);
} else if(nCoinType == ONLY_NONDENOMINATED_NOT1000IFMN) {
if (IsCollateralAmount(pcoin->vout[i].nValue)) continue; // do not use collateral amounts
found = !IsDenominatedAmount(pcoin->vout[i].nValue);
if(found && fMasterNode) found = pcoin->vout[i].nValue != 1000*COIN; // do not use Hot MN funds
} else if(nCoinType == ONLY_1000) {
found = pcoin->vout[i].nValue == 1000*COIN;
} else if(nCoinType == ONLY_PRIVATESEND_COLLATERAL) {
found = IsCollateralAmount(pcoin->vout[i].nValue);
} else {
found = true;
}
if(!found) continue;
isminetype mine = IsMine(pcoin->vout[i]);
if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
(!IsLockedCoin((*it).first, i) || nCoinType == ONLY_1000) &&
(pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
(!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
vCoins.push_back(COutput(pcoin, i, nDepth,
((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
(coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO)));
}
}
}
}
static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{
vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
seed_insecure_rand();
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(vValue.size(), false);
CAmount nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (unsigned int i = 0; i < vValue.size(); i++)
{
//The solver here uses a randomized algorithm,
//the randomness serves no real security purpose but is just
//needed to prevent degenerate behavior and it is important
//that the rng is fast. We do not use a constant random sequence,
//because there may be some privacy improvement by making
//the selection random.
if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
{
nTotal += vValue[i].first;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].first;
vfIncluded[i] = false;
}
}
}
}
}
//Reduces the approximate best subset by removing any inputs that are smaller than the surplus of nTotal beyond nTargetValue.
for (unsigned int i = 0; i < vValue.size(); i++)
{
if (vfBest[i] && (nBest - vValue[i].first) >= nTargetValue )
{
vfBest[i] = false;
nBest -= vValue[i].first;
}
}
}
// move denoms down
bool less_then_denom (const COutput& out1, const COutput& out2)
{
const CWalletTx *pcoin1 = out1.tx;
const CWalletTx *pcoin2 = out2.tx;
bool found1 = false;
bool found2 = false;
BOOST_FOREACH(CAmount d, vecPrivateSendDenominations) // loop through predefined denoms
{
if(pcoin1->vout[out1.i].nValue == d) found1 = true;
if(pcoin2->vout[out2.i].nValue == d) found2 = true;
}
return (!found1 && found2);
}
bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
coinLowestLarger.first = std::numeric_limits<CAmount>::max();
coinLowestLarger.second.first = NULL;
vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
CAmount nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
// move denoms down on the list
sort(vCoins.begin(), vCoins.end(), less_then_denom);
// try to find nondenom first to prevent unneeded spending of mixed coins
for (unsigned int tryDenom = 0; tryDenom < 2; tryDenom++)
{
LogPrint("selectcoins", "tryDenom: %d\n", tryDenom);
vValue.clear();
nTotalLower = 0;
BOOST_FOREACH(const COutput &output, vCoins)
{
if (!output.fSpendable)
continue;
const CWalletTx *pcoin = output.tx;
// if (fDebug) LogPrint("selectcoins", "value %s confirms %d\n", FormatMoney(pcoin->vout[output.i].nValue), output.nDepth);
if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
continue;
int i = output.i;
CAmount n = pcoin->vout[i].nValue;
if (tryDenom == 0 && IsDenominatedAmount(n)) continue; // we don't want denom values on first run
pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
if (n == nTargetValue)
{
setCoinsRet.insert(coin.second);
nValueRet += coin.first;
return true;
}
else if (n < nTargetValue + MIN_CHANGE)
{
vValue.push_back(coin);
nTotalLower += n;
}
else if (n < coinLowestLarger.first)
{
coinLowestLarger = coin;
}
}
if (nTotalLower == nTargetValue)
{
for (unsigned int i = 0; i < vValue.size(); ++i)
{
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
return true;
}
if (nTotalLower < nTargetValue)
{
if (coinLowestLarger.second.first == NULL) // there is no input larger than nTargetValue
{
if (tryDenom == 0)
// we didn't look at denom yet, let's do it
continue;
else
// we looked at everything possible and didn't find anything, no luck
return false;
}
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
return true;
}
// nTotalLower > nTargetValue
break;
}
// Solve subset sum by stochastic approximation
sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
vector<char> vfBest;
CAmount nBest;
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (coinLowestLarger.second.first &&
((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger.first <= nBest))
{
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
}
else {
string s = "CWallet::SelectCoinsMinConf best subset: ";
for (unsigned int i = 0; i < vValue.size(); i++)
{
if (vfBest[i])
{
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
s += FormatMoney(vValue[i].first) + " ";
}
}
LogPrint("selectcoins", "%s - total %s\n", s, FormatMoney(nBest));
}
return true;
}
bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl, AvailableCoinsType nCoinType, bool fUseInstantSend) const
{
// Note: this function should never be used for "always free" tx types like dstx
vector<COutput> vCoins;
AvailableCoins(vCoins, true, coinControl, false, nCoinType, fUseInstantSend);
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
{
BOOST_FOREACH(const COutput& out, vCoins)
{
if(!out.fSpendable)
continue;
if(nCoinType == ONLY_DENOMINATED) {
CTxIn txin = CTxIn(out.tx->GetHash(),out.i);
int nRounds = GetInputPrivateSendRounds(txin);
// make sure it's actually anonymized
if(nRounds < nPrivateSendRounds) continue;
}
nValueRet += out.tx->vout[out.i].nValue;
setCoinsRet.insert(make_pair(out.tx, out.i));
}
return (nValueRet >= nTargetValue);
}
//if we're doing only denominated, we need to round up to the nearest smallest denomination
if(nCoinType == ONLY_DENOMINATED) {
CAmount nSmallestDenom = vecPrivateSendDenominations.back();
// Make outputs by looping through denominations, from large to small
BOOST_FOREACH(CAmount nDenom, vecPrivateSendDenominations)
{
BOOST_FOREACH(const COutput& out, vCoins)
{
//make sure it's the denom we're looking for, round the amount up to smallest denom
if(out.tx->vout[out.i].nValue == nDenom && nValueRet + nDenom < nTargetValue + nSmallestDenom) {
CTxIn txin = CTxIn(out.tx->GetHash(),out.i);
int nRounds = GetInputPrivateSendRounds(txin);
// make sure it's actually anonymized
if(nRounds < nPrivateSendRounds) continue;
nValueRet += nDenom;
setCoinsRet.insert(make_pair(out.tx, out.i));
}
}
}
return (nValueRet >= nTargetValue);
}
// calculate value from preset inputs and store them
set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
CAmount nValueFromPresetInputs = 0;
std::vector<COutPoint> vPresetInputs;
if (coinControl)
coinControl->ListSelected(vPresetInputs);
BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
{
map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
if (it != mapWallet.end())
{
const CWalletTx* pcoin = &it->second;
// Clearly invalid input, fail
if (pcoin->vout.size() <= outpoint.n)
return false;
nValueFromPresetInputs += pcoin->vout[outpoint.n].nValue;
setPresetCoins.insert(make_pair(pcoin, outpoint.n));
} else
return false; // TODO: Allow non-wallet inputs
}
// remove preset inputs from vCoins
for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
{
if (setPresetCoins.count(make_pair(it->tx, it->i)))
it = vCoins.erase(it);
else
++it;
}
bool res = nTargetValue <= nValueFromPresetInputs ||
SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, vCoins, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, vCoins, setCoinsRet, nValueRet) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, vCoins, setCoinsRet, nValueRet));
// because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
// add preset inputs to the total value selected
nValueRet += nValueFromPresetInputs;
return res;
}
struct CompareByPriority
{
bool operator()(const COutput& t1,
const COutput& t2) const
{
return t1.Priority() > t2.Priority();
}
};
bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nChangePosRet, std::string& strFailReason, bool includeWatching)
{
vector<CRecipient> vecSend;
// Turn the txout set into a CRecipient vector
BOOST_FOREACH(const CTxOut& txOut, tx.vout)
{
CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
vecSend.push_back(recipient);
}
CCoinControl coinControl;
coinControl.fAllowOtherInputs = true;
coinControl.fAllowWatchOnly = includeWatching;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
coinControl.Select(txin.prevout);
CReserveKey reservekey(this);
CWalletTx wtx;
if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosRet, strFailReason, &coinControl, false))
return false;
if (nChangePosRet != -1)
tx.vout.insert(tx.vout.begin() + nChangePosRet, wtx.vout[nChangePosRet]);
// Add new txins (keeping original txin scriptSig/order)
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
bool found = false;
BOOST_FOREACH(const CTxIn& origTxIn, tx.vin)
{
if (txin.prevout.hash == origTxIn.prevout.hash && txin.prevout.n == origTxIn.prevout.n)
{
found = true;
break;
}
}
if (!found)
tx.vin.push_back(txin);
}
return true;
}
bool CWallet::SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vecTxInRet, std::vector<COutput>& vCoinsRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax)
{
vecTxInRet.clear();
vCoinsRet.clear();
nValueRet = 0;
vector<COutput> vCoins;
AvailableCoins(vCoins, true, NULL, false, ONLY_DENOMINATED);
std::random_shuffle(vCoins.rbegin(), vCoins.rend(), GetRandInt);
// ( bit on if present )
// bit 0 - 100Q+1
// bit 1 - 10Q+1
// bit 2 - 1Q+1
// bit 3 - .1Q+1
std::vector<int> vecBits;
if (!darkSendPool.GetDenominationsBits(nDenom, vecBits)) {
return false;
}
int nDenomResult = 0;
InsecureRand insecureRand;
BOOST_FOREACH(const COutput& out, vCoins)
{
// masternode-like input should not be selected by AvailableCoins now anyway
//if(out.tx->vout[out.i].nValue == 1000*COIN) continue;
if(nValueRet + out.tx->vout[out.i].nValue <= nValueMax){
CTxIn txin = CTxIn(out.tx->GetHash(), out.i);
int nRounds = GetInputPrivateSendRounds(txin);
if(nRounds >= nPrivateSendRoundsMax) continue;
if(nRounds < nPrivateSendRoundsMin) continue;
BOOST_FOREACH(int nBit, vecBits) {
if(out.tx->vout[out.i].nValue == vecPrivateSendDenominations[nBit]) {
if(nValueRet >= nValueMin) {
//randomly reduce the max amount we'll submit (for anonymity)
nValueMax -= insecureRand(nValueMax/5);
//on average use 50% of the inputs or less
int r = insecureRand(vCoins.size());
if((int)vecTxInRet.size() > r) return true;
}
txin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
nValueRet += out.tx->vout[out.i].nValue;
vecTxInRet.push_back(txin);
vCoinsRet.push_back(out);
nDenomResult |= 1 << nBit;
}
}
}
}
return nValueRet >= nValueMin && nDenom == nDenomResult;
}
struct CompareByAmount
{
bool operator()(const CompactTallyItem& t1,
const CompactTallyItem& t2) const
{
return t1.nAmount > t2.nAmount;
}
};
bool CWallet::SelectCoinsGrouppedByAddresses(std::vector<CompactTallyItem>& vecTallyRet, bool fSkipDenominated, bool fAnonymizable) const
{
LOCK2(cs_main, cs_wallet);
isminefilter filter = ISMINE_SPENDABLE;
// try to use cache
if(fAnonymizable) {
if(fSkipDenominated && fAnonymizableTallyCachedNonDenom) {
vecTallyRet = vecAnonymizableTallyCachedNonDenom;
LogPrint("selectcoins", "SelectCoinsGrouppedByAddresses - using cache for non-denom inputs\n");
return vecTallyRet.size() > 0;
}
if(!fSkipDenominated && fAnonymizableTallyCached) {
vecTallyRet = vecAnonymizableTallyCached;
LogPrint("selectcoins", "SelectCoinsGrouppedByAddresses - using cache for all inputs\n");
return vecTallyRet.size() > 0;
}
}
// Tally
map<CBitcoinAddress, CompactTallyItem> mapTally;
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if(wtx.IsCoinBase() && wtx.GetBlocksToMaturity() > 0) continue;
if(!fAnonymizable && !wtx.IsTrusted()) continue;
for (unsigned int i = 0; i < wtx.vout.size(); i++) {
CTxDestination address;
if (!ExtractDestination(wtx.vout[i].scriptPubKey, address)) continue;
isminefilter mine = ::IsMine(*this, address);
if(!(mine & filter)) continue;
if(IsSpent(wtx.GetHash(), i) || IsLockedCoin(wtx.GetHash(), i)) continue;
if(fSkipDenominated && IsDenominatedAmount(wtx.vout[i].nValue)) continue;
if(fAnonymizable) {
// ignore collaterals
if(IsCollateralAmount(wtx.vout[i].nValue)) continue;
if(fMasterNode && wtx.vout[i].nValue == 1000*COIN) continue;
// ignore outputs that are 10 times smaller then the smallest denomination
// otherwise they will just lead to higher fee / lower priority
if(wtx.vout[i].nValue <= vecPrivateSendDenominations.back()/10) continue;
// ignore anonymized
if(GetInputPrivateSendRounds(CTxIn(wtx.GetHash(), i)) >= nPrivateSendRounds) continue;
}
CompactTallyItem& item = mapTally[address];
item.address = address;
item.nAmount += wtx.vout[i].nValue;
item.vecTxIn.push_back(CTxIn(wtx.GetHash(), i));
}
}
// construct resulting vector
vecTallyRet.clear();
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CompactTallyItem)& item, mapTally) {
if(fAnonymizable && item.second.nAmount < vecPrivateSendDenominations.back()) continue;
vecTallyRet.push_back(item.second);
}
// order by amounts per address, from smallest to largest
sort(vecTallyRet.rbegin(), vecTallyRet.rend(), CompareByAmount());
// cache anonymizable for later use
if(fAnonymizable) {
if(fSkipDenominated) {
vecAnonymizableTallyCachedNonDenom = vecTallyRet;
fAnonymizableTallyCachedNonDenom = true;
} else {
vecAnonymizableTallyCached = vecTallyRet;
fAnonymizableTallyCached = true;
}
}
// debug
std::string strMessage = "SelectCoinsGrouppedByAddresses - vecTallyRet:\n";
BOOST_FOREACH(CompactTallyItem& item, vecTallyRet)
strMessage += strprintf(" %s %f\n", item.address.ToString().c_str(), float(item.nAmount)/COIN);
LogPrint("selectcoins", "%s", strMessage);
return vecTallyRet.size() > 0;
}
bool CWallet::SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vecTxInRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax) const
{
CCoinControl *coinControl=NULL;
vecTxInRet.clear();
nValueRet = 0;
vector<COutput> vCoins;
AvailableCoins(vCoins, true, coinControl, false, nPrivateSendRoundsMin < 0 ? ONLY_NONDENOMINATED_NOT1000IFMN : ONLY_DENOMINATED);
//order the array so largest nondenom are first, then denominations, then very small inputs.
sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority());
BOOST_FOREACH(const COutput& out, vCoins)
{
//do not allow inputs less than 1/10th of minimum value
if(out.tx->vout[out.i].nValue < nValueMin/10) continue;
//do not allow collaterals to be selected
if(IsCollateralAmount(out.tx->vout[out.i].nValue)) continue;
if(fMasterNode && out.tx->vout[out.i].nValue == 1000*COIN) continue; //masternode input
if(nValueRet + out.tx->vout[out.i].nValue <= nValueMax){
CTxIn txin = CTxIn(out.tx->GetHash(),out.i);
int nRounds = GetInputPrivateSendRounds(txin);
if(nRounds >= nPrivateSendRoundsMax) continue;
if(nRounds < nPrivateSendRoundsMin) continue;
txin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
nValueRet += out.tx->vout[out.i].nValue;
vecTxInRet.push_back(txin);
}
}
return nValueRet >= nValueMin;
}
bool CWallet::GetCollateralTxIn(CTxIn& txinRet, CAmount& nValueRet) const
{
vector<COutput> vCoins;
AvailableCoins(vCoins);
BOOST_FOREACH(const COutput& out, vCoins)
{
if(IsCollateralAmount(out.tx->vout[out.i].nValue))
{
txinRet = CTxIn(out.tx->GetHash(), out.i);
txinRet.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
nValueRet = out.tx->vout[out.i].nValue;
return true;
}
}
return false;
}
bool CWallet::GetMasternodeVinAndKeys(CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash, std::string strOutputIndex)
{
// wait for reindex and/or import to finish
if (fImporting || fReindex) return false;
// Find possible candidates
std::vector<COutput> vPossibleCoins;
AvailableCoins(vPossibleCoins, true, NULL, false, ONLY_1000);
if(vPossibleCoins.empty()) {
LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate any valid masternode vin\n");
return false;
}
if(strTxHash.empty()) // No output specified, select the first one
return GetVinAndKeysFromOutput(vPossibleCoins[0], txinRet, pubKeyRet, keyRet);
// Find specific vin
uint256 txHash = uint256S(strTxHash);
int nOutputIndex = atoi(strOutputIndex.c_str());
BOOST_FOREACH(COutput& out, vPossibleCoins)
if(out.tx->GetHash() == txHash && out.i == nOutputIndex) // found it!
return GetVinAndKeysFromOutput(out, txinRet, pubKeyRet, keyRet);
LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate specified masternode vin\n");
return false;
}
bool CWallet::GetVinAndKeysFromOutput(COutput out, CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet)
{
// wait for reindex and/or import to finish
if (fImporting || fReindex) return false;
CScript pubScript;
txinRet = CTxIn(out.tx->GetHash(), out.i);
pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
CTxDestination address1;
ExtractDestination(pubScript, address1);
CBitcoinAddress address2(address1);
CKeyID keyID;
if (!address2.GetKeyID(keyID)) {
LogPrintf("CWallet::GetVinAndKeysFromOutput -- Address does not refer to a key\n");
return false;
}
if (!GetKey(keyID, keyRet)) {
LogPrintf ("CWallet::GetVinAndKeysFromOutput -- Private key for address is not known\n");
return false;
}
pubKeyRet = keyRet.GetPubKey();
return true;
}
int CWallet::CountInputsWithAmount(CAmount nInputAmount)
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted()){
int nDepth = pcoin->GetDepthInMainChain(false);
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
COutput out = COutput(pcoin, i, nDepth, true);
CTxIn txin = CTxIn(out.tx->GetHash(), out.i);
if(out.tx->vout[out.i].nValue != nInputAmount) continue;
if(!IsDenominatedAmount(pcoin->vout[i].nValue)) continue;
if(IsSpent(out.tx->GetHash(), i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(txin)) continue;
nTotal++;
}
}
}
}
return nTotal;
}
bool CWallet::HasCollateralInputs(bool fOnlyConfirmed) const
{
vector<COutput> vCoins;
AvailableCoins(vCoins, fOnlyConfirmed, NULL, false, ONLY_PRIVATESEND_COLLATERAL);
return !vCoins.empty();
}
bool CWallet::IsCollateralAmount(CAmount nInputAmount) const
{
// collateral inputs should always be a 2x..4x of PRIVATESEND_COLLATERAL
return nInputAmount >= PRIVATESEND_COLLATERAL * 2 &&
nInputAmount <= PRIVATESEND_COLLATERAL * 4 &&
nInputAmount % PRIVATESEND_COLLATERAL == 0;
}
bool CWallet::CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason)
{
txCollateral.vin.clear();
txCollateral.vout.clear();
CReserveKey reservekey(this);
CAmount nValue = 0;
CTxIn txinCollateral;
if (!GetCollateralTxIn(txinCollateral, nValue)) {
strReason = "PrivateSend requires a collateral transaction and could not locate an acceptable input!";
return false;
}
// make our change address
CScript scriptChange;
CPubKey vchPubKey;
assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked
scriptChange = GetScriptForDestination(vchPubKey.GetID());
reservekey.KeepKey();
txCollateral.vin.push_back(txinCollateral);
//pay collateral charge in fees
CTxOut txout = CTxOut(nValue - PRIVATESEND_COLLATERAL, scriptChange);
txCollateral.vout.push_back(txout);
if(!SignSignature(*this, txinCollateral.prevPubKey, txCollateral, 0, int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))) {
strReason = "Unable to sign collateral transaction!";
return false;
}
return true;
}
bool CWallet::GetBudgetSystemCollateralTX(CTransaction& tx, uint256 hash, CAmount amount, bool fUseInstantSend)
{
CWalletTx wtx;
if(GetBudgetSystemCollateralTX(wtx, hash, amount, fUseInstantSend)){
tx = (CTransaction)wtx;
return true;
}
return false;
}
bool CWallet::GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, CAmount amount, bool fUseInstantSend)
{
// make our change address
CReserveKey reservekey(this);
CScript scriptChange;
scriptChange << OP_RETURN << ToByteVector(hash);
CAmount nFeeRet = 0;
int nChangePosRet = -1;
std::string strFail = "";
vector< CRecipient > vecSend;
vecSend.push_back((CRecipient){scriptChange, amount, false});
CCoinControl *coinControl=NULL;
bool success = CreateTransaction(vecSend, tx, reservekey, nFeeRet, nChangePosRet, strFail, coinControl, true, ALL_COINS, fUseInstantSend);
if(!success){
LogPrintf("CWallet::GetBudgetSystemCollateralTX -- Error: %s\n", strFail);
return false;
}
return true;
}
bool CWallet::ConvertList(std::vector<CTxIn> vecTxIn, std::vector<CAmount>& vecAmounts)
{
BOOST_FOREACH(CTxIn txin, vecTxIn) {
if (mapWallet.count(txin.prevout.hash)) {
CWalletTx& wtx = mapWallet[txin.prevout.hash];
if(txin.prevout.n < wtx.vout.size()){
vecAmounts.push_back(wtx.vout[txin.prevout.n].nValue);
}
} else {
LogPrintf("CWallet::ConvertList -- Couldn't find transaction\n");
}
}
return true;
}
bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign, AvailableCoinsType nCoinType, bool fUseInstantSend)
{
CAmount nFeePay = fUseInstantSend ? CTxLockRequest().GetMinFee() : 0;
CAmount nValue = 0;
unsigned int nSubtractFeeFromAmount = 0;
BOOST_FOREACH (const CRecipient& recipient, vecSend)
{
if (nValue < 0 || recipient.nAmount < 0)
{
strFailReason = _("Transaction amounts must be positive");
return false;
}
nValue += recipient.nAmount;
if (recipient.fSubtractFeeFromAmount)
nSubtractFeeFromAmount++;
}
if (vecSend.empty() || nValue < 0)
{
strFailReason = _("Transaction amounts must be positive");
return false;
}
wtxNew.fTimeReceivedIsTxTime = true;
wtxNew.BindWallet(this);
CMutableTransaction txNew;
// Discourage fee sniping.
//
// For a large miner the value of the transactions in the best block and
// the mempool can exceed the cost of deliberately attempting to mine two
// blocks to orphan the current best block. By setting nLockTime such that
// only the next block can include the transaction, we discourage this
// practice as the height restricted and limited blocksize gives miners
// considering fee sniping fewer options for pulling off this attack.
//
// A simple way to think about this is from the wallet's point of view we
// always want the blockchain to move forward. By setting nLockTime this
// way we're basically making the statement that we only want this
// transaction to appear in the next block; we don't want to potentially
// encourage reorgs by allowing transactions to appear at lower heights
// than the next block in forks of the best chain.
//
// Of course, the subsidy is high enough, and transaction volume low
// enough, that fee sniping isn't a problem yet, but by implementing a fix
// now we ensure code won't be written that makes assumptions about
// nLockTime that preclude a fix later.
txNew.nLockTime = chainActive.Height();
// Secondly occasionally randomly pick a nLockTime even further back, so
// that transactions that are delayed after signing for whatever reason,
// e.g. high-latency mix networks and some CoinJoin implementations, have
// better privacy.
if (GetRandInt(10) == 0)
txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
{
LOCK2(cs_main, cs_wallet);
{
nFeeRet = 0;
if(nFeePay > 0) nFeeRet = nFeePay;
// Start with no fee and loop until there is enough fee
while (true)
{
txNew.vin.clear();
txNew.vout.clear();
wtxNew.fFromMe = true;
nChangePosRet = -1;
bool fFirst = true;
CAmount nValueToSelect = nValue;
if (nSubtractFeeFromAmount == 0)
nValueToSelect += nFeeRet;
double dPriority = 0;
// vouts to the payees
BOOST_FOREACH (const CRecipient& recipient, vecSend)
{
CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
if (recipient.fSubtractFeeFromAmount)
{
txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
if (fFirst) // first receiver pays the remainder not divisible by output count
{
fFirst = false;
txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
}
}
if (txout.IsDust(::minRelayTxFee))
{
if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
{
if (txout.nValue < 0)
strFailReason = _("The transaction amount is too small to pay the fee");
else
strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
}
else
strFailReason = _("Transaction amount too small");
return false;
}
txNew.vout.push_back(txout);
}
// Choose coins to use
set<pair<const CWalletTx*,unsigned int> > setCoins;
CAmount nValueIn = 0;
if (!SelectCoins(nValueToSelect, setCoins, nValueIn, coinControl, nCoinType, fUseInstantSend))
{
if (nCoinType == ONLY_NOT1000IFMN) {
strFailReason = _("Unable to locate enough funds for this transaction that are not equal 1000 Q.");
} else if (nCoinType == ONLY_NONDENOMINATED_NOT1000IFMN) {
strFailReason = _("Unable to locate enough PrivateSend non-denominated funds for this transaction that are not equal 1000 Q.");
} else if (nCoinType == ONLY_DENOMINATED) {
strFailReason = _("Unable to locate enough PrivateSend denominated funds for this transaction.");
strFailReason += " " + _("PrivateSend uses exact denominated amounts to send funds, you might simply need to anonymize some more coins.");
} else if (nValueIn < nValueToSelect) {
strFailReason = _("Insufficient funds.");
}
if (fUseInstantSend) {
if (nValueIn > sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE)*COIN) {
strFailReason += " " + strprintf(_("InstantSend doesn't support sending values that high yet. Transactions are currently limited to %1 Q."), sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE));
} else {
// could be not true but most likely that's the reason
strFailReason += " " + strprintf(_("InstantSend requires inputs with at least %d confirmations, you might need to wait a few minutes and try again."), INSTANTSEND_CONFIRMATIONS_REQUIRED);
}
}
return false;
}
BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
{
CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
//The coin age after the next block (depth+1) is used instead of the current,
//reflecting an assumption the user would accept a bit more delay for
//a chance at a free transaction.
//But mempool inputs might still be in the mempool, so their age stays 0
int age = pcoin.first->GetDepthInMainChain();
assert(age >= 0);
if (age != 0)
age += 1;
dPriority += (double)nCredit * age;
}
const CAmount nChange = nValueIn - nValueToSelect;
CTxOut newTxOut;
if (nChange > 0)
{
//over pay for denominated transactions
if (nCoinType == ONLY_DENOMINATED) {
nFeeRet += nChange;
wtxNew.mapValue["DS"] = "1";
// recheck skipped denominations during next mixing
darkSendPool.ClearSkippedDenominations();
} else {
// Fill a vout to ourself
// TODO: pass in scriptChange instead of reservekey so
// change transaction isn't always pay-to-quick-address
CScript scriptChange;
// coin control: send change to custom address
if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
scriptChange = GetScriptForDestination(coinControl->destChange);
// no coin control: send change to newly generated address
else
{
// Note: We use a new key here to keep it from being obvious which side is the change.
// The drawback is that by not reusing a previous key, the change may be lost if a
// backup is restored, if the backup doesn't have the new private key for the change.
// If we reused the old key, it would be possible to add code to look for and
// rediscover unknown transactions that were written with keys of ours to recover
// post-backup change.
// Reserve a new key pair from key pool
CPubKey vchPubKey;
bool ret;
ret = reservekey.GetReservedKey(vchPubKey);
assert(ret); // should never fail, as we just unlocked
scriptChange = GetScriptForDestination(vchPubKey.GetID());
}
newTxOut = CTxOut(nChange, scriptChange);
// We do not move dust-change to fees, because the sender would end up paying more than requested.
// This would be against the purpose of the all-inclusive feature.
// So instead we raise the change and deduct from the recipient.
if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
{
CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
newTxOut.nValue += nDust; // raise change until no more dust
for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
{
if (vecSend[i].fSubtractFeeFromAmount)
{
txNew.vout[i].nValue -= nDust;
if (txNew.vout[i].IsDust(::minRelayTxFee))
{
strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
return false;
}
break;
}
}
}
// Never create dust outputs; if we would, just
// add the dust to the fee.
if (newTxOut.IsDust(::minRelayTxFee))
{
nFeeRet += nChange;
reservekey.ReturnKey();
}
else
{
// Insert change txn at random position:
nChangePosRet = GetRandInt(txNew.vout.size()+1);
vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
txNew.vout.insert(position, newTxOut);
}
}
}
else
reservekey.ReturnKey();
// Fill vin
//
// Note how the sequence number is set to max()-1 so that the
// nLockTime set above actually works.
BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins){
CTxIn txin = CTxIn(coin.first->GetHash(),coin.second,CScript(),
std::numeric_limits<unsigned int>::max()-1);
txin.prevPubKey = coin.first->vout[coin.second].scriptPubKey;
txNew.vin.push_back(txin);
}
// BIP69 https://github.com/kristovatlas/bips/blob/master/bip-0069.mediawiki
sort(txNew.vin.begin(), txNew.vin.end());
sort(txNew.vout.begin(), txNew.vout.end());
// If there was change output added before, we must update its position now
if (nChangePosRet != -1) {
int i = 0;
BOOST_FOREACH(const CTxOut& txOut, txNew.vout)
{
if (txOut == newTxOut)
{
nChangePosRet = i;
break;
}
i++;
}
}
// Sign
int nIn = 0;
CTransaction txNewConst(txNew);
BOOST_FOREACH(const CTxIn& txin, txNew.vin)
{
bool signSuccess;
const CScript& scriptPubKey = txin.prevPubKey;
CScript& scriptSigRes = txNew.vin[nIn].scriptSig;
if (sign)
signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, SIGHASH_ALL), scriptPubKey, scriptSigRes);
else
signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, scriptSigRes);
if (!signSuccess)
{
strFailReason = _("Signing transaction failed");
return false;
}
nIn++;
}
unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
// Remove scriptSigs if we used dummy signatures for fee calculation
if (!sign) {
BOOST_FOREACH (CTxIn& txin, txNew.vin)
txin.scriptSig = CScript();
}
// Embed the constructed transaction data in wtxNew.
*static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
// Limit size
if (nBytes >= MAX_STANDARD_TX_SIZE)
{
strFailReason = _("Transaction too large");
return false;
}
dPriority = wtxNew.ComputePriority(dPriority, nBytes);
// Can we complete this as a free transaction?
if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
{
// Not enough fee: enough priority?
double dPriorityNeeded = mempool.estimateSmartPriority(nTxConfirmTarget);
// Require at least hard-coded AllowFree.
if (dPriority >= dPriorityNeeded && AllowFree(dPriority))
break;
// Small enough, and priority high enough, to send for free
// if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
// break;
}
CAmount nFeeNeeded = max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool));
if (coinControl && nFeeNeeded > 0 && coinControl->nMinimumTotalFee > nFeeNeeded) {
nFeeNeeded = coinControl->nMinimumTotalFee;
}
if(fUseInstantSend) {
nFeeNeeded = std::max(nFeeNeeded, CTxLockRequest(txNew).GetMinFee());
}
// If we made it here and we aren't even able to meet the relay fee on the next pass, give up
// because we must be at the maximum allowed fee.
if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
{
strFailReason = _("Transaction too large for fee policy");
return false;
}
if (nFeeRet >= nFeeNeeded)
break; // Done, enough fee included.
// Include more fee and try again.
nFeeRet = nFeeNeeded;
continue;
}
}
}
return true;
}
/**
* Call after CreateTransaction unless you want to abort
*/
bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std::string strCommand)
{
{
LOCK2(cs_main, cs_wallet);
LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
{
// This is only to keep the database open to defeat the auto-flush for the
// duration of this scope. This is the only place where this optimization
// maybe makes sense; please don't do it anywhere else.
CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
// Take key pair from key pool so it won't be used again
reservekey.KeepKey();
// Add tx to wallet, because if it has change it's also ours,
// otherwise just for transaction history.
AddToWallet(wtxNew, false, pwalletdb);
// Notify that old coins are spent
set<uint256> updated_hahes;
BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
{
// notify only once
if(updated_hahes.find(txin.prevout.hash) != updated_hahes.end()) continue;
CWalletTx &coin = mapWallet[txin.prevout.hash];
coin.BindWallet(this);
NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
updated_hahes.insert(txin.prevout.hash);
}
if (fFileBacked)
delete pwalletdb;
}
// Track how many getdata requests our transaction gets
mapRequestCount[wtxNew.GetHash()] = 0;
if (fBroadcastTransactions)
{
// Broadcast
if (!wtxNew.AcceptToMemoryPool(false))
{
// This must not fail. The transaction has already been signed and recorded.
LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
return false;
}
wtxNew.RelayWalletTransaction(strCommand);
}
}
return true;
}
bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB & pwalletdb)
{
if (!pwalletdb.WriteAccountingEntry_Backend(acentry))
return false;
laccentries.push_back(acentry);
CAccountingEntry & entry = laccentries.back();
wtxOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
return true;
}
CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
{
return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
}
CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
{
// payTxFee is user-set "I want to pay this much"
CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
// User didn't set: use -txconfirmtarget to estimate...
if (nFeeNeeded == 0) {
int estimateFoundTarget = nConfirmTarget;
nFeeNeeded = pool.estimateSmartFee(nConfirmTarget, &estimateFoundTarget).GetFee(nTxBytes);
// ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
if (nFeeNeeded == 0)
nFeeNeeded = fallbackFee.GetFee(nTxBytes);
}
// prevent user from paying a fee below minRelayTxFee or minTxFee
nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
// But always obey the maximum
if (nFeeNeeded > maxTxFee)
nFeeNeeded = maxTxFee;
return nFeeNeeded;
}
DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
{
if (!fFileBacked)
return DB_LOAD_OK;
fFirstRunRet = false;
DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
if (nLoadWalletRet == DB_NEED_REWRITE)
{
if (CDB::Rewrite(strWalletFile, "\x04pool"))
{
LOCK(cs_wallet);
setKeyPool.clear();
nKeysLeftSinceAutoBackup = 0;
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nLoadWalletRet != DB_LOAD_OK)
return nLoadWalletRet;
fFirstRunRet = !vchDefaultKey.IsValid();
uiInterface.LoadWallet(this);
return DB_LOAD_OK;
}
DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
if (!fFileBacked)
return DB_LOAD_OK;
DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
if (nZapWalletTxRet == DB_NEED_REWRITE)
{
if (CDB::Rewrite(strWalletFile, "\x04pool"))
{
LOCK(cs_wallet);
setKeyPool.clear();
nKeysLeftSinceAutoBackup = 0;
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nZapWalletTxRet != DB_LOAD_OK)
return nZapWalletTxRet;
return DB_LOAD_OK;
}
bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
{
bool fUpdated = false;
{
LOCK(cs_wallet); // mapAddressBook
std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
fUpdated = mi != mapAddressBook.end();
mapAddressBook[address].name = strName;
if (!strPurpose.empty()) /* update purpose only if requested */
mapAddressBook[address].purpose = strPurpose;
}
NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
if (!fFileBacked)
return false;
if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
return false;
return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
}
bool CWallet::DelAddressBook(const CTxDestination& address)
{
{
LOCK(cs_wallet); // mapAddressBook
if(fFileBacked)
{
// Delete destdata tuples associated with address
std::string strAddress = CBitcoinAddress(address).ToString();
BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
{
CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
}
}
mapAddressBook.erase(address);
}
NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
if (!fFileBacked)
return false;
CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
}
bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
{
if (fFileBacked)
{
if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
return false;
}
vchDefaultKey = vchPubKey;
return true;
}
/**
* Mark old keypool keys as used,
* and generate all new keys
*/
bool CWallet::NewKeyPool()
{
{
LOCK(cs_wallet);
CWalletDB walletdb(strWalletFile);
BOOST_FOREACH(int64_t nIndex, setKeyPool)
walletdb.ErasePool(nIndex);
setKeyPool.clear();
fEnablePrivateSend = false;
nKeysLeftSinceAutoBackup = 0;
if (IsLocked(true))
return false;
int64_t nKeys = max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t)0);
for (int i = 0; i < nKeys; i++)
{
int64_t nIndex = i+1;
walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
setKeyPool.insert(nIndex);
}
LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
}
return true;
}
bool CWallet::TopUpKeyPool(unsigned int kpSize)
{
{
LOCK(cs_wallet);
if (IsLocked(true))
return false;
CWalletDB walletdb(strWalletFile);
// Top up key pool
unsigned int nTargetSize;
if (kpSize > 0)
nTargetSize = kpSize;
else
nTargetSize = max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
while (setKeyPool.size() < (nTargetSize + 1))
{
int64_t nEnd = 1;
if (!setKeyPool.empty())
nEnd = *(--setKeyPool.end()) + 1;
if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
throw runtime_error("TopUpKeyPool(): writing generated key failed");
setKeyPool.insert(nEnd);
LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
double dProgress = 100.f * nEnd / (nTargetSize + 1);
std::string strMsg = strprintf(_("Loading wallet... (%3.2f %%)"), dProgress);
uiInterface.InitMessage(strMsg);
}
}
return true;
}
void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
{
nIndex = -1;
keypool.vchPubKey = CPubKey();
{
LOCK(cs_wallet);
if (!IsLocked(true))
TopUpKeyPool();
// Get the oldest key
if(setKeyPool.empty())
return;
CWalletDB walletdb(strWalletFile);
nIndex = *(setKeyPool.begin());
setKeyPool.erase(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool))
throw runtime_error("ReserveKeyFromKeyPool(): read failed");
if (!HaveKey(keypool.vchPubKey.GetID()))
throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool");
assert(keypool.vchPubKey.IsValid());
LogPrintf("keypool reserve %d\n", nIndex);
}
}
void CWallet::KeepKey(int64_t nIndex)
{
// Remove from key pool
if (fFileBacked)
{
CWalletDB walletdb(strWalletFile);
walletdb.ErasePool(nIndex);
nKeysLeftSinceAutoBackup = nWalletBackups ? nKeysLeftSinceAutoBackup - 1 : 0;
}
LogPrintf("keypool keep %d\n", nIndex);
}
void CWallet::ReturnKey(int64_t nIndex)
{
// Return to key pool
{
LOCK(cs_wallet);
setKeyPool.insert(nIndex);
}
LogPrintf("keypool return %d\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey& result)
{
int64_t nIndex = 0;
CKeyPool keypool;
{
LOCK(cs_wallet);
ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex == -1)
{
if (IsLocked(true)) return false;
result = GenerateNewKey();
return true;
}
KeepKey(nIndex);
result = keypool.vchPubKey;
}
return true;
}
int64_t CWallet::GetOldestKeyPoolTime()
{
int64_t nIndex = 0;
CKeyPool keypool;
ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex == -1)
return GetTime();
ReturnKey(nIndex);
return keypool.nTime;
}
std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
{
map<CTxDestination, CAmount> balances;
{
LOCK(cs_wallet);
BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
{
CWalletTx *pcoin = &walletEntry.second;
if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
continue;
for (unsigned int i = 0; i < pcoin->vout.size(); i++)
{
CTxDestination addr;
if (!IsMine(pcoin->vout[i]))
continue;
if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
continue;
CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
if (!balances.count(addr))
balances[addr] = 0;
balances[addr] += n;
}
}
}
return balances;
}
set< set<CTxDestination> > CWallet::GetAddressGroupings()
{
AssertLockHeld(cs_wallet); // mapWallet
set< set<CTxDestination> > groupings;
set<CTxDestination> grouping;
BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
{
CWalletTx *pcoin = &walletEntry.second;
if (pcoin->vin.size() > 0)
{
bool any_mine = false;
// group all input addresses with each other
BOOST_FOREACH(CTxIn txin, pcoin->vin)
{
CTxDestination address;
if(!IsMine(txin)) /* If this input isn't mine, ignore it */
continue;
if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
continue;
grouping.insert(address);
any_mine = true;
}
// group change with input addresses
if (any_mine)
{
BOOST_FOREACH(CTxOut txout, pcoin->vout)
if (IsChange(txout))
{
CTxDestination txoutAddr;
if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
continue;
grouping.insert(txoutAddr);
}
}
if (grouping.size() > 0)
{
groupings.insert(grouping);
grouping.clear();
}
}
// group lone addrs by themselves
for (unsigned int i = 0; i < pcoin->vout.size(); i++)
if (IsMine(pcoin->vout[i]))
{
CTxDestination address;
if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
continue;
grouping.insert(address);
groupings.insert(grouping);
grouping.clear();
}
}
set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
BOOST_FOREACH(set<CTxDestination> grouping, groupings)
{
// make a set of all the groups hit by this new group
set< set<CTxDestination>* > hits;
map< CTxDestination, set<CTxDestination>* >::iterator it;
BOOST_FOREACH(CTxDestination address, grouping)
if ((it = setmap.find(address)) != setmap.end())
hits.insert((*it).second);
// merge all hit groups into a new single group and delete old groups
set<CTxDestination>* merged = new set<CTxDestination>(grouping);
BOOST_FOREACH(set<CTxDestination>* hit, hits)
{
merged->insert(hit->begin(), hit->end());
uniqueGroupings.erase(hit);
delete hit;
}
uniqueGroupings.insert(merged);
// update setmap
BOOST_FOREACH(CTxDestination element, *merged)
setmap[element] = merged;
}
set< set<CTxDestination> > ret;
BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
{
ret.insert(*uniqueGrouping);
delete uniqueGrouping;
}
return ret;
}
std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
{
LOCK(cs_wallet);
set<CTxDestination> result;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second.name;
if (strName == strAccount)
result.insert(address);
}
return result;
}
bool CReserveKey::GetReservedKey(CPubKey& pubkey)
{
if (nIndex == -1)
{
CKeyPool keypool;
pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex != -1)
vchPubKey = keypool.vchPubKey;
else {
return false;
}
}
assert(vchPubKey.IsValid());
pubkey = vchPubKey;
return true;
}
void CReserveKey::KeepKey()
{
if (nIndex != -1)
pwallet->KeepKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CReserveKey::ReturnKey()
{
if (nIndex != -1)
pwallet->ReturnKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
{
setAddress.clear();
CWalletDB walletdb(strWalletFile);
LOCK2(cs_main, cs_wallet);
BOOST_FOREACH(const int64_t& id, setKeyPool)
{
CKeyPool keypool;
if (!walletdb.ReadPool(id, keypool))
throw runtime_error("GetAllReserveKeyHashes(): read failed");
assert(keypool.vchPubKey.IsValid());
CKeyID keyID = keypool.vchPubKey.GetID();
if (!HaveKey(keyID))
throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool");
setAddress.insert(keyID);
}
}
bool CWallet::UpdatedTransaction(const uint256 &hashTx)
{
{
LOCK(cs_wallet);
// Only notify UI if this transaction is in this wallet
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end()){
NotifyTransactionChanged(this, hashTx, CT_UPDATED);
return true;
}
}
return false;
}
void CWallet::GetScriptForMining(boost::shared_ptr<CReserveScript> &script)
{
boost::shared_ptr<CReserveKey> rKey(new CReserveKey(this));
CPubKey pubkey;
if (!rKey->GetReservedKey(pubkey))
return;
script = rKey;
script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
}
void CWallet::LockCoin(COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.insert(output);
std::map<uint256, CWalletTx>::iterator it = mapWallet.find(output.hash);
if (it != mapWallet.end()) it->second.MarkDirty(); // recalculate all credits for this tx
fAnonymizableTallyCached = false;
fAnonymizableTallyCachedNonDenom = false;
}
void CWallet::UnlockCoin(COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.erase(output);
std::map<uint256, CWalletTx>::iterator it = mapWallet.find(output.hash);
if (it != mapWallet.end()) it->second.MarkDirty(); // recalculate all credits for this tx
fAnonymizableTallyCached = false;
fAnonymizableTallyCachedNonDenom = false;
}
void CWallet::UnlockAllCoins()
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.clear();
}
bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
{
AssertLockHeld(cs_wallet); // setLockedCoins
COutPoint outpt(hash, n);
return (setLockedCoins.count(outpt) > 0);
}
void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
{
AssertLockHeld(cs_wallet); // setLockedCoins
for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
it != setLockedCoins.end(); it++) {
COutPoint outpt = (*it);
vOutpts.push_back(outpt);
}
}
/** @} */ // end of Actions
class CAffectedKeysVisitor : public boost::static_visitor<void> {
private:
const CKeyStore &keystore;
std::vector<CKeyID> &vKeys;
public:
CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
void Process(const CScript &script) {
txnouttype type;
std::vector<CTxDestination> vDest;
int nRequired;
if (ExtractDestinations(script, type, vDest, nRequired)) {
BOOST_FOREACH(const CTxDestination &dest, vDest)
boost::apply_visitor(*this, dest);
}
}
void operator()(const CKeyID &keyId) {
if (keystore.HaveKey(keyId))
vKeys.push_back(keyId);
}
void operator()(const CScriptID &scriptId) {
CScript script;
if (keystore.GetCScript(scriptId, script))
Process(script);
}
void operator()(const CNoDestination &none) {}
};
void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
AssertLockHeld(cs_wallet); // mapKeyMetadata
mapKeyBirth.clear();
// get birth times for keys with metadata
for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
if (it->second.nCreateTime)
mapKeyBirth[it->first] = it->second.nCreateTime;
// map in which we'll infer heights of other keys
CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
std::set<CKeyID> setKeys;
GetKeys(setKeys);
BOOST_FOREACH(const CKeyID &keyid, setKeys) {
if (mapKeyBirth.count(keyid) == 0)
mapKeyFirstBlock[keyid] = pindexMax;
}
setKeys.clear();
// if there are no such keys, we're done
if (mapKeyFirstBlock.empty())
return;
// find first block that affects those keys, if there are any left
std::vector<CKeyID> vAffected;
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
// iterate over all wallet transactions...
const CWalletTx &wtx = (*it).second;
BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
// ... which are already in a block
int nHeight = blit->second->nHeight;
BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
// iterate over all their outputs
CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
BOOST_FOREACH(const CKeyID &keyid, vAffected) {
// ... and all their affected keys
std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
rit->second = blit->second;
}
vAffected.clear();
}
}
}
// Extract block timestamps for those keys
for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
}
bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
{
if (boost::get<CNoDestination>(&dest))
return false;
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
}
bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
{
if (!mapAddressBook[dest].destdata.erase(key))
return false;
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
}
bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
{
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
return true;
}
bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
{
std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
if(i != mapAddressBook.end())
{
CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
if(j != i->second.destdata.end())
{
if(value)
*value = j->second;
return true;
}
}
return false;
}
CKeyPool::CKeyPool()
{
nTime = GetTime();
}
CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
{
nTime = GetTime();
vchPubKey = vchPubKeyIn;
}
CWalletKey::CWalletKey(int64_t nExpires)
{
nTimeCreated = (nExpires ? GetTime() : 0);
nTimeExpires = nExpires;
}
int CMerkleTx::SetMerkleBranch(const CBlock& block)
{
AssertLockHeld(cs_main);
CBlock blockTmp;
// Update the tx's hashBlock
hashBlock = block.GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
if (block.vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)block.vtx.size())
{
nIndex = -1;
LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
return 0;
}
// Is the tx in a block that's in the main chain
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
const CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
return 0;
return chainActive.Height() - pindex->nHeight + 1;
}
int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet, bool enableIX) const
{
int nResult;
if (hashUnset())
nResult = 0;
else {
AssertLockHeld(cs_main);
// Find the block it claims to be in
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
nResult = 0;
else {
CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
nResult = 0;
else {
pindexRet = pindex;
nResult = ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
if (nResult == 0 && !mempool.exists(GetHash()))
return -1; // Not in chain, not in mempool
}
}
}
if(enableIX && nResult < 6 && instantsend.IsLockedInstantSendTransaction(GetHash()))
return nInstantSendDepth + nResult;
return nResult;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!IsCoinBase())
return 0;
return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
{
CValidationState state;
return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, false, fRejectAbsurdFee);
}
|
//---------------------------------------------------------------------------
//
// Copyright (c) 2008-2010 AlazarTech, Inc.
//
// AlazarTech, Inc. licenses this software under specific terms and
// conditions. Use of any of the software or derviatives thereof in any
// product without an AlazarTech digitizer board is strictly prohibited.
//
// AlazarTech, Inc. provides this software AS IS, WITHOUT ANY WARRANTY,
// EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. AlazarTech makes no
// guarantee or representations regarding the use of, or the results of the
// use of, the software and documentation in terms of correctness, accuracy,
// reliability, currentness, or otherwise; and you rely on the software,
// documentation and results solely at your own risk.
//
// IN NO EVENT SHALL ALAZARTECH BE LIABLE FOR ANY LOSS OF USE, LOSS OF
// BUSINESS, LOSS OF PROFITS, INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL
// DAMAGES OF ANY KIND. IN NO EVENT SHALL ALAZARTECH'S TOTAL LIABILITY EXCEED
// THE SUM PAID TO ALAZARTECH FOR THE PRODUCT LICENSED HEREUNDER.
//
//---------------------------------------------------------------------------
// AcqToDisk.cpp :
//
// This program demonstrates how to configure an ATS310 to capture to on-board
// memory, and use AlazarHyperDisp to transfer records from on-board to host
// memory.
//
#include <stdio.h>
#include <conio.h>
#include "AlazarError.h"
#include "AlazarApi.h"
#include "AlazarCmd.h"
// Forward declarations
BOOL ConfigureBoard(HANDLE boardHandle);
BOOL AcquireData(HANDLE boardHandle);
//----------------------------------------------------------------------------
//
// Function : main
//
// Description : Program entry point
//
//----------------------------------------------------------------------------
int main(int argc, char* argv[])
{
// TODO: Select a board
U32 systemId = 1;
U32 boardId = 1;
// Get a handle to the board
HANDLE boardHandle = AlazarGetBoardBySystemID(systemId, boardId);
if (boardHandle == NULL)
{
printf("Error: Unable to open board system ID %u board ID %u\n", systemId, boardId);
return 1;
}
// Configure the board's sample rate, input, and trigger settings
if (!ConfigureBoard(boardHandle))
{
printf("Error: Board configuration failed\n");
return 1;
}
// Make an acquisition, optionally saving sample data to a file
if (!AcquireData(boardHandle))
{
printf("Error: Acquisition failed\n");
return 1;
}
return 0;
}
//----------------------------------------------------------------------------
//
// Function : ConfigureBoard
//
// Description : Configure sample rate, input, and trigger settings
//
//----------------------------------------------------------------------------
BOOL ConfigureBoard(HANDLE boardHandle)
{
RETURN_CODE retCode;
// TODO: Specify the sample rate (see sample rate id below)
double samplesPerSec = 20.e6;
// TODO: Select clock parameters as required to generate this sample rate.
//
// For example: if samplesPerSec is 100.e6 (100 MS/s), then:
// - select clock source INTERNAL_CLOCK and sample rate SAMPLE_RATE_100MSPS
// - select clock source FAST_EXTERNAL_CLOCK, sample rate SAMPLE_RATE_USER_DEF,
// and connect a 100 MHz signalto the EXT CLK BNC connector.
retCode =
AlazarSetCaptureClock(
boardHandle, // HANDLE -- board handle
INTERNAL_CLOCK, // U32 -- clock source id
SAMPLE_RATE_20MSPS, // U32 -- sample rate id
CLOCK_EDGE_RISING, // U32 -- clock edge id
0 // U32 -- clock decimation
);
if (retCode != ApiSuccess)
{
printf("Error: AlazarSetCaptureClock failed -- %s\n", AlazarErrorToText(retCode));
return FALSE;
}
// TODO: Select CHA input parameters as required
retCode =
AlazarInputControl(
boardHandle, // HANDLE -- board handle
CHANNEL_A, // U8 -- input channel
DC_COUPLING, // U32 -- input coupling id
INPUT_RANGE_PM_800_MV, // U32 -- input range id
IMPEDANCE_50_OHM // U32 -- input impedance id
);
if (retCode != ApiSuccess)
{
printf("Error: AlazarInputControl failed -- %s\n", AlazarErrorToText(retCode));
return FALSE;
}
// TODO: Select CHB input parameters as required
retCode =
AlazarInputControl(
boardHandle, // HANDLE -- board handle
CHANNEL_B, // U8 -- channel identifier
DC_COUPLING, // U32 -- input coupling id
INPUT_RANGE_PM_800_MV, // U32 -- input range id
IMPEDANCE_50_OHM // U32 -- input impedance id
);
if (retCode != ApiSuccess)
{
printf("Error: AlazarInputControl failed -- %s\n", AlazarErrorToText(retCode));
return FALSE;
}
// TODO: Select trigger inputs and levels as required
retCode =
AlazarSetTriggerOperation(
boardHandle, // HANDLE -- board handle
TRIG_ENGINE_OP_J, // U32 -- trigger operation
TRIG_ENGINE_J, // U32 -- trigger engine id
TRIG_CHAN_A, // U32 -- trigger source id
TRIGGER_SLOPE_POSITIVE, // U32 -- trigger slope id
128, // U32 -- trigger level from 0 (-range) to 255 (+range)
TRIG_ENGINE_K, // U32 -- trigger engine id
TRIG_DISABLE, // U32 -- trigger source id for engine K
TRIGGER_SLOPE_POSITIVE, // U32 -- trigger slope id
128 // U32 -- trigger level from 0 (-range) to 255 (+range)
);
if (retCode != ApiSuccess)
{
printf("Error: AlazarSetTriggerOperation failed -- %s\n", AlazarErrorToText(retCode));
return FALSE;
}
// TODO: Select external trigger parameters as required
retCode =
AlazarSetExternalTrigger(
boardHandle, // HANDLE -- board handle
DC_COUPLING, // U32 -- external trigger coupling id
ETR_5V // U32 -- external trigger range id
);
// TODO: Set trigger delay as required.
double triggerDelay_sec = 0.;
U32 triggerDelay_samples = (U32) (triggerDelay_sec * samplesPerSec + 0.5);
retCode = AlazarSetTriggerDelay(boardHandle, triggerDelay_samples);
if (retCode != ApiSuccess)
{
printf("Error: AlazarSetTriggerDelay failed -- %s\n", AlazarErrorToText(retCode));
return FALSE;
}
// TODO: Set trigger timeout as required.
// NOTE:
// The board will wait for a for this amount of time for a trigger event.
// If a trigger event does not arrive, then the board will automatically
// trigger. Set the trigger timeout value to 0 to force the board to wait
// forever for a trigger event.
//
// IMPORTANT:
// The trigger timeout value should be set to zero after appropriate
// trigger parameters have been determined, otherwise the
// board may trigger if the timeout interval expires before a
// hardware trigger event arrives.
double triggerTimeout_sec = 0.;
U32 triggerTimeout_clocks = (U32) (triggerTimeout_sec / 10.e-6 + 0.5);
retCode =
AlazarSetTriggerTimeOut(
boardHandle, // HANDLE -- board handle
triggerTimeout_clocks // U32 -- timeout_sec / 10.e-6 (0 == wait forever)
);
if (retCode != ApiSuccess)
{
printf("Error: AlazarSetTriggerTimeOut failed -- %s\n", AlazarErrorToText(retCode));
return FALSE;
}
return TRUE;
}
//----------------------------------------------------------------------------
//
// Function : AcquireData
//
// Description : Make acquisition and optionally save samples to a file
//
//----------------------------------------------------------------------------
BOOL AcquireData(HANDLE boardHandle)
{
// TODO: Select the number of pre-trigger samples per record
U32 preTriggerSamples = 63 * 1024;
// TODO: Select the number of post-trigger samples per record
U32 postTriggerSamples = 63 * 1024;
// TODO: Select the number of records in the acquisition
U32 recordsPerCapture = 1;
// TODO: Select the amount of time, in seconds, to wait for the
// acquisiton to complete to on-board memory.
DWORD timeout_ms = 10000;
// TODO: Select the number of HyperDisp points per record
U32 pointsPerRecord = 1024;
// TODO: Select if you wish to save the sample data to a file
BOOL saveData = TRUE;
// TODO: Select which channels read from on-board memory (A, B, or both)
U32 channelMask = CHANNEL_A | CHANNEL_B;
// Calculate the number of enabled channels from the channel mask
int channelCount = 0;
switch (channelMask)
{
case CHANNEL_A:
case CHANNEL_B:
channelCount = 1;
break;
case CHANNEL_A | CHANNEL_B:
channelCount = 2;
break;
default:
printf("Error: Invalid channel mask %08X\n", channelMask);
return FALSE;
}
// Get the sample and memory size
U8 bitsPerSample;
U32 maxSamplesPerChannel;
RETURN_CODE retCode = AlazarGetChannelInfo(boardHandle, &maxSamplesPerChannel, &bitsPerSample);
if (retCode != ApiSuccess)
{
printf("Error: AlazarGetChannelInfo failed -- %s\n", AlazarErrorToText(retCode));
return FALSE;
}
// Calculate the size of each record in bytes
U32 bytesPerSample = (bitsPerSample + 7) / 8;
U32 samplesPerRecord = preTriggerSamples + postTriggerSamples;
U32 bytesPerRecord = bytesPerSample * samplesPerRecord;
// Calculate the size of the HyperDisp buffer
U32 inSamplesPerPoint = samplesPerRecord / pointsPerRecord;
if (inSamplesPerPoint < 1)
{
printf("Error: Samples per record must be greater than HyperDisp points per record.\n");
return FALSE;
}
U32 outSamplesPerPoint = 2; // 1 for min sample + 1 for max sample
U32 bytesPerBuffer = bytesPerSample * outSamplesPerPoint * pointsPerRecord;
// Configure the number of samples per record
retCode =
AlazarSetRecordSize (
boardHandle, // HANDLE -- board handle
preTriggerSamples, // U32 -- pre-trigger samples
postTriggerSamples // U32 -- post-trigger samples
);
if (retCode != ApiSuccess)
{
printf("Error: AlazarSetRecordSize failed -- %s\n", AlazarErrorToText(retCode));
return FALSE;
}
// Configure the number of records in the acquisition
retCode = AlazarSetRecordCount(boardHandle, recordsPerCapture);
if (retCode != ApiSuccess)
{
printf("Error: AlazarSetRecordCount failed -- %s\n", AlazarErrorToText(retCode));
return FALSE;
}
// Arm the board to wait for a trigger event to begin the acquisition
retCode = AlazarStartCapture(boardHandle);
if (retCode != ApiSuccess)
{
printf("Error: AlazarStartCapture failed -- %s\n", AlazarErrorToText(retCode));
return FALSE;
}
// Wait for the board to capture all records to on-board memory
DWORD startTickCount = GetTickCount();
DWORD timeoutTickCount = startTickCount + timeout_ms;
BOOL success = TRUE;
printf("Capturing %d records ... press any key to abort\n", recordsPerCapture);
while (AlazarBusy (boardHandle) && (success == TRUE))
{
if (GetTickCount() > timeoutTickCount)
{
printf("Error: Capture timeout after %lu ms\n", timeout_ms);
success = FALSE;
}
else if (_kbhit())
{
printf("Error: Acquisition aborted\n");
success = FALSE;
}
else
{
Sleep(10);
}
}
if (!success)
{
retCode = AlazarAbortCapture(boardHandle);
if (retCode != ApiSuccess)
{
printf("Error: AlazarAbortCapture failed -- %s\n", AlazarErrorToText(retCode));
}
return FALSE;
}
// The board has captured all records to on-board memory
double captureTime_sec = (GetTickCount() - startTickCount) / 1000.;
double recordsPerSec;
if (captureTime_sec > 0.)
recordsPerSec = recordsPerCapture / captureTime_sec;
else
recordsPerSec = 0.;
printf("Captured %u records in %g sec (%.4g records / sec)\n", recordsPerCapture, captureTime_sec, recordsPerSec);
// Allocate a buffer to store one record
U16* buffer = (U16 *) malloc(bytesPerBuffer);
if (buffer == NULL)
{
printf("Error: alloc %d bytes failed\n", bytesPerBuffer);
return FALSE;
}
// Create a data file if required
FILE *fpData = NULL;
if (saveData)
{
fpData = fopen("data.txt", "w");
if (fpData == NULL)
{
printf("Error: Unable to create data file -- %u\n", GetLastError());
free(buffer);
return FALSE;
}
}
// Transfer the records from on-board memory to our buffer
printf("Transferring %u records ... press any key to cancel\n", recordsPerCapture);
startTickCount = GetTickCount();
INT64 bytesTransferred = 0;
U32 record;
for (record = 0; (record < recordsPerCapture) && (success == TRUE); record++)
{
for (int channel = 0; (channel < channelCount) && (success == TRUE); channel++)
{
// Find the current channel Id
char channelId;
if (channelCount == 1)
{
if (channelMask & CHANNEL_A)
channelId = CHANNEL_A;
else
channelId = CHANNEL_B;
}
else
{
if (channel == 0)
channelId = CHANNEL_A;
else
channelId = CHANNEL_B;
}
// The FPGA will calculate the minimum and maximum sample values
// during each interval, and transfer min-max points to our buffer.
U32 hdError;
retCode =
AlazarHyperDisp (
boardHandle, // HANDLE -- board handle
NULL, // void* -- reserved
samplesPerRecord, // U32 -- BufferSize
(U8*) buffer, // U8* -- ViewBuffer
bytesPerRecord, // U32 -- ViewBufferSize
pointsPerRecord, // U32 -- NumOfPixels
1, // U32 -- Option (1 = calculate HyperDisp of record)
channelId, // U32 -- ChannelSelect
record + 1, // U32 -- record (1 indexed)
-(long)preTriggerSamples, // long -- TransferOffset
&hdError // U32* -- error
);
if (retCode != ApiSuccess)
{
printf("Error: AlazarHyperDisp failed -- %s error %u\n", AlazarErrorToText(retCode), hdError);
success = FALSE;
}
else
{
bytesTransferred += bytesPerBuffer;
// TODO: Process record here.
//
// The HyperDisp samples are arranged in the buffer as follows:
// (Min0, Max0), (Min1, Max1) ... (Min[N-1], Max[N-1])
//
// 12-bit sample codes occupy the most significant bits of each 16-bit
// sample value.
//
// Sample codes are unsigned by default. As a result:
// - a sample code of 0x000 represents a negative full scale input signal.
// - a sample code of 0x800 represents a ~0V signal.
// - a sample code of 0xFFF represents a positive full scale input signal.
if (saveData)
{
// Find the current channel name from the channel Id
char channelName;
if (channelId == CHANNEL_A)
channelName = 'A';
else
channelName = 'B';
// Write the HyperDisp interval index, and the minimum, maximum, and average samples value to file
if (fprintf(fpData, "--> CH%c record %u begin\n\n", channelName, record + 1) < 0)
{
printf("Error: Write CH%c record %u header failed -- %u\n", channelName, record, GetLastError());
success = FALSE;
}
if (success)
{
if (fprintf(fpData, "Sample \tMin \tMax \tAve\n") < 0)
{
printf("Error: Write CH%c record %u column labels failed -- %u\n", channelName, record, GetLastError());
success = FALSE;
break;
}
}
// Sample codes are stored in the most significant bits of each
// sample value.
int bitShift = 8 * bytesPerSample - bitsPerSample;
U16 *pMinMaxSamples = (U16*) buffer;
for (U32 point = 0; (point < pointsPerRecord) && (success == TRUE); point++)
{
U16 minCode = (*pMinMaxSamples) >> bitShift;
pMinMaxSamples++;
U16 maxCode = (*pMinMaxSamples) >> bitShift;
pMinMaxSamples++;
U16 aveCode = (U16) (((U32) minCode + (U32) maxCode) / 2);
if (fprintf(fpData, "%u \t%u \t%u \t%u\n", point, minCode, maxCode, aveCode) < 0)
{
printf("Error: Write CH%c record %u samples failed -- %u\n", channelName, record, GetLastError());
success = FALSE;
}
}
if (success)
{
if (fprintf(fpData, "\n<-- CH%c record %u end\n\n", channelName, record + 1) < 0)
{
printf("Error: Write CH%c record %u footer failed -- %u\n", channelName, record, GetLastError());
success = FALSE;
}
}
}
}
}
// If a key was pressed, then stop processing records.
if (_kbhit())
{
printf("Error: Transfer aborted ...\n");
success = FALSE;
}
}
// Display results
double transferTime_sec = (GetTickCount() - startTickCount) / 1000.;
double bytesPerSec;
if (transferTime_sec > 0.)
bytesPerSec = bytesTransferred / transferTime_sec;
else
bytesPerSec = 0.;
printf("Transferred %I64d bytes in %g sec (%.4g bytes per sec)\n", bytesTransferred, transferTime_sec, bytesPerSec);
// Free the DMA buffer
free(buffer);
// Close the data file
if (fpData != NULL)
fclose(fpData);
return success;
}
|
; A132774: A natural number operator.
; Submitted by Christian Krause
; 1,2,3,0,4,5,0,0,6,7,0,0,0,8,9,0,0,0,0,10,11,0,0,0,0,0,12,13,0,0,0,0,0,0,14,15
mov $4,2
lpb $4
trn $2,$0
add $0,$4
sub $0,1
lpb $0
sub $0,1
add $3,1
sub $0,$3
add $2,2
lpe
add $2,$0
mov $4,$0
lpe
mov $0,$2
|
/**
* 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 <time.h>
#include <arpa/inet.h>
#include <gmock/gmock.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <string>
#include <sstream>
#include <tuple>
#include <vector>
#include <process/async.hpp>
#include <process/clock.hpp>
#include <process/defer.hpp>
#include <process/delay.hpp>
#include <process/dispatch.hpp>
#include <process/executor.hpp>
#include <process/filter.hpp>
#include <process/future.hpp>
#include <process/gc.hpp>
#include <process/gmock.hpp>
#include <process/gtest.hpp>
#include <process/network.hpp>
#include <process/owned.hpp>
#include <process/process.hpp>
#include <process/run.hpp>
#include <process/socket.hpp>
#include <process/time.hpp>
#include <stout/duration.hpp>
#include <stout/gtest.hpp>
#include <stout/hashmap.hpp>
#include <stout/hashset.hpp>
#include <stout/lambda.hpp>
#include <stout/nothing.hpp>
#include <stout/os.hpp>
#include <stout/stringify.hpp>
#include <stout/stopwatch.hpp>
#include <stout/try.hpp>
#include "encoder.hpp"
using namespace process;
using process::firewall::DisabledEndpointsFirewallRule;
using process::firewall::FirewallRule;
using process::network::Address;
using process::network::Socket;
using std::move;
using std::string;
using std::vector;
using testing::_;
using testing::Assign;
using testing::DoAll;
using testing::Return;
using testing::ReturnArg;
// TODO(bmahler): Move tests into their own files as appropriate.
TEST(ProcessTest, Event)
{
Event* event = new TerminateEvent(UPID());
EXPECT_FALSE(event->is<MessageEvent>());
EXPECT_FALSE(event->is<ExitedEvent>());
EXPECT_TRUE(event->is<TerminateEvent>());
delete event;
}
TEST(ProcessTest, Future)
{
Promise<bool> promise;
promise.set(true);
ASSERT_TRUE(promise.future().isReady());
EXPECT_TRUE(promise.future().get());
}
TEST(ProcessTest, Associate)
{
Promise<bool> promise1;
Future<bool> future1(true);
promise1.associate(future1);
ASSERT_TRUE(promise1.future().isReady());
EXPECT_TRUE(promise1.future().get());
Promise<bool> promise2;
Promise<bool> promise2_;
Future<bool> future2 = promise2_.future();
promise2.associate(future2);
promise2_.discard();
ASSERT_TRUE(promise2.future().isDiscarded());
Promise<bool> promise3;
Promise<bool> promise4;
promise3.associate(promise4.future());
promise4.fail("associate");
ASSERT_TRUE(promise3.future().isFailed());
EXPECT_EQ("associate", promise3.future().failure());
// Test 'discard' versus 'discarded' after association.
Promise<bool> promise5;
Future<bool> future3;
promise5.associate(future3);
EXPECT_FALSE(future3.isDiscarded());
promise5.future().discard();
EXPECT_TRUE(future3.hasDiscard());
Promise<bool> promise6;
Promise<bool> promise7;
promise6.associate(promise7.future());
promise7.discard();
EXPECT_TRUE(promise6.future().isDiscarded());
}
void onAny(const Future<bool>& future, bool* b)
{
ASSERT_TRUE(future.isReady());
*b = future.get();
}
TEST(ProcessTest, OnAny)
{
bool b = false;
Future<bool>(true)
.onAny(lambda::bind(&onAny, lambda::_1, &b));
EXPECT_TRUE(b);
}
Future<string> itoa1(int* const& i)
{
std::ostringstream out;
out << *i;
return out.str();
}
string itoa2(int* const& i)
{
std::ostringstream out;
out << *i;
return out.str();
}
TEST(ProcessTest, Then)
{
Promise<int*> promise;
int i = 42;
promise.set(&i);
Future<string> future = promise.future()
.then(lambda::bind(&itoa1, lambda::_1));
ASSERT_TRUE(future.isReady());
EXPECT_EQ("42", future.get());
future = promise.future()
.then(lambda::bind(&itoa2, lambda::_1));
ASSERT_TRUE(future.isReady());
EXPECT_EQ("42", future.get());
}
Future<int> repair(const Future<int>& future)
{
EXPECT_TRUE(future.isFailed());
EXPECT_EQ("Failure", future.failure());
return 43;
}
// Checks that 'repair' callback gets executed if the future failed
// and not executed if the future is completed successfully.
TEST(ProcessTest, Repair)
{
// Check that the 'repair' callback _does not_ get executed by
// making sure that when we complete the promise with a value that's
// the value that we get back.
Promise<int> promise1;
Future<int> future1 = promise1.future()
.repair(lambda::bind(&repair, lambda::_1));
EXPECT_TRUE(future1.isPending());
promise1.set(42); // So this means 'repair' should not get executed.
AWAIT_EXPECT_EQ(42, future1);
// Check that the 'repair' callback gets executed by failing the
// promise which should invoke the 'repair' callback.
Promise<int> promise2;
Future<int> future2 = promise2.future()
.repair(lambda::bind(&repair, lambda::_1));
EXPECT_TRUE(future2.isPending());
promise2.fail("Failure"); // So 'repair' should get called returning '43'.
AWAIT_EXPECT_EQ(43, future2);
}
Future<Nothing> after(volatile bool* executed, const Future<Nothing>& future)
{
EXPECT_TRUE(future.hasDiscard());
*executed = true;
return Failure("Failure");
}
// Checks that the 'after' callback gets executed if the future is not
// completed.
TEST(ProcessTest, After1)
{
Clock::pause();
volatile bool executed = false;
Future<Nothing> future = Future<Nothing>()
.after(Hours(42), lambda::bind(&after, &executed, lambda::_1));
// A pending future should stay pending until 'after' is executed.
EXPECT_TRUE(future.isPending());
// Only advanced halfway, future should remain pending.
Clock::advance(Hours(21));
EXPECT_TRUE(future.isPending());
// Even doing a discard on the future should keep it pending.
future.discard();
EXPECT_TRUE(future.isPending());
// After advancing all the way the future should now fail because
// the 'after' callback gets executed.
Clock::advance(Hours(21));
AWAIT_FAILED(future);
EXPECT_TRUE(executed);
Clock::resume();
}
// Checks that completing a promise will keep the 'after' callback
// from executing.
TEST(ProcessTest, After2)
{
Clock::pause();
volatile bool executed = false;
Promise<Nothing> promise;
Future<Nothing> future = promise.future()
.after(Hours(42), lambda::bind(&after, &executed, lambda::_1));
EXPECT_TRUE(future.isPending());
// Only advanced halfway, future should remain pending.
Clock::advance(Hours(21));
EXPECT_TRUE(future.isPending());
// Even doing a discard on the future should keep it pending.
future.discard();
EXPECT_TRUE(future.isPending());
// Now set the promise, the 'after' timer should be cancelled and
// the pending future should be completed.
promise.set(Nothing());
AWAIT_READY(future);
// Advancing time the rest of the way should not cause the 'after'
// callback to execute.
Clock::advance(Hours(21));
EXPECT_FALSE(executed);
Clock::resume();
}
Future<bool> readyFuture()
{
return true;
}
Future<bool> failedFuture()
{
return Failure("The value is not positive (or zero)");
}
Future<bool> pendingFuture(const Future<bool>& future)
{
return future; // Keep it pending.
}
Future<string> second(const bool& b)
{
return b ? string("true") : string("false");
}
Future<string> third(const string& s)
{
return s;
}
TEST(ProcessTest, Chain)
{
Future<string> s = readyFuture()
.then(lambda::bind(&second, lambda::_1))
.then(lambda::bind(&third, lambda::_1));
s.await();
ASSERT_TRUE(s.isReady());
EXPECT_EQ("true", s.get());
s = failedFuture()
.then(lambda::bind(&second, lambda::_1))
.then(lambda::bind(&third, lambda::_1));
s.await();
ASSERT_TRUE(s.isFailed());
Promise<bool> promise;
s = pendingFuture(promise.future())
.then(lambda::bind(&second, lambda::_1))
.then(lambda::bind(&third, lambda::_1));
ASSERT_TRUE(s.isPending());
promise.discard();
AWAIT_DISCARDED(s);
}
Future<bool> inner1(const Future<bool>& future)
{
return future;
}
Future<int> inner2(volatile bool* executed, const Future<int>& future)
{
*executed = true;
return future;
}
// Tests that Future::discard does not complete the future unless
// Promise::discard is invoked.
TEST(ProcessTest, Discard1)
{
Promise<bool> promise1;
Promise<int> promise2;
volatile bool executed = false;
Future<int> future = Future<string>("hello world")
.then(lambda::bind(&inner1, promise1.future()))
.then(lambda::bind(&inner2, &executed, promise2.future()));
ASSERT_TRUE(future.isPending());
future.discard();
// The future should remain pending, even though we discarded it.
ASSERT_TRUE(future.hasDiscard());
ASSERT_TRUE(future.isPending());
// The future associated with the lambda already executed in the
// first 'then' should have the discard propagated to it.
ASSERT_TRUE(promise1.future().hasDiscard());
// But the future assocaited with the lambda that hasn't yet been
// executed should not have the discard propagated to it.
ASSERT_FALSE(promise2.future().hasDiscard());
// Now discarding the promise should cause the outer future to be
// discarded also.
ASSERT_TRUE(promise1.discard());
AWAIT_DISCARDED(future);
// And the final lambda should never have executed.
ASSERT_FALSE(executed);
ASSERT_TRUE(promise2.future().isPending());
}
// Tests that Future::discard does not complete the future and
// Promise::set can still be invoked to complete the future.
TEST(ProcessTest, Discard2)
{
Promise<bool> promise1;
Promise<int> promise2;
volatile bool executed = false;
Future<int> future = Future<string>("hello world")
.then(lambda::bind(&inner1, promise1.future()))
.then(lambda::bind(&inner2, &executed, promise2.future()));
ASSERT_TRUE(future.isPending());
future.discard();
// The future should remain pending, even though we discarded it.
ASSERT_TRUE(future.hasDiscard());
ASSERT_TRUE(future.isPending());
// The future associated with the lambda already executed in the
// first 'then' should have the discard propagated to it.
ASSERT_TRUE(promise1.future().hasDiscard());
// But the future assocaited with the lambda that hasn't yet been
// executed should not have the discard propagated to it.
ASSERT_FALSE(promise2.future().hasDiscard());
// Now setting the promise should cause the outer future to be
// discarded rather than executing the last lambda because the
// implementation of Future::then does not continue the chain once a
// discard occurs.
ASSERT_TRUE(promise1.set(true));
AWAIT_DISCARDED(future);
// And the final lambda should never have executed.
ASSERT_FALSE(executed);
ASSERT_TRUE(promise2.future().isPending());
}
// Tests that Future::discard does not complete the future and
// Promise::fail can still be invoked to complete the future.
TEST(ProcessTest, Discard3)
{
Promise<bool> promise1;
Promise<int> promise2;
volatile bool executed = false;
Future<int> future = Future<string>("hello world")
.then(lambda::bind(&inner1, promise1.future()))
.then(lambda::bind(&inner2, &executed, promise2.future()));
ASSERT_TRUE(future.isPending());
future.discard();
// The future should remain pending, even though we discarded it.
ASSERT_TRUE(future.hasDiscard());
ASSERT_TRUE(future.isPending());
// The future associated with the lambda already executed in the
// first 'then' should have the discard propagated to it.
ASSERT_TRUE(promise1.future().hasDiscard());
// But the future assocaited with the lambda that hasn't yet been
// executed should not have the discard propagated to it.
ASSERT_FALSE(promise2.future().hasDiscard());
// Now failing the promise should cause the outer future to be
// failed also.
ASSERT_TRUE(promise1.fail("failure message"));
AWAIT_FAILED(future);
// And the final lambda should never have executed.
ASSERT_FALSE(executed);
ASSERT_TRUE(promise2.future().isPending());
}
class SpawnProcess : public Process<SpawnProcess>
{
public:
MOCK_METHOD0(initialize, void(void));
MOCK_METHOD0(finalize, void(void));
};
TEST(ProcessTest, Spawn)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
SpawnProcess process;
EXPECT_CALL(process, initialize())
.Times(1);
EXPECT_CALL(process, finalize())
.Times(1);
PID<SpawnProcess> pid = spawn(process);
ASSERT_FALSE(!pid);
ASSERT_FALSE(wait(pid, Seconds(0)));
terminate(pid);
wait(pid);
}
class DispatchProcess : public Process<DispatchProcess>
{
public:
MOCK_METHOD0(func0, void(void));
MOCK_METHOD1(func1, bool(bool));
MOCK_METHOD1(func2, Future<bool>(bool));
MOCK_METHOD1(func3, int(int));
MOCK_METHOD2(func4, Future<bool>(bool, int));
};
TEST(ProcessTest, Dispatch)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
DispatchProcess process;
EXPECT_CALL(process, func0())
.Times(1);
EXPECT_CALL(process, func1(_))
.WillOnce(ReturnArg<0>());
EXPECT_CALL(process, func2(_))
.WillOnce(ReturnArg<0>());
PID<DispatchProcess> pid = spawn(&process);
ASSERT_FALSE(!pid);
dispatch(pid, &DispatchProcess::func0);
Future<bool> future;
future = dispatch(pid, &DispatchProcess::func1, true);
EXPECT_TRUE(future.get());
future = dispatch(pid, &DispatchProcess::func2, true);
EXPECT_TRUE(future.get());
terminate(pid);
wait(pid);
}
TEST(ProcessTest, Defer1)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
DispatchProcess process;
EXPECT_CALL(process, func0())
.Times(1);
EXPECT_CALL(process, func1(_))
.WillOnce(ReturnArg<0>());
EXPECT_CALL(process, func2(_))
.WillOnce(ReturnArg<0>());
EXPECT_CALL(process, func4(_, _))
.WillRepeatedly(ReturnArg<0>());
PID<DispatchProcess> pid = spawn(&process);
ASSERT_FALSE(!pid);
{
Deferred<void(void)> func0 =
defer(pid, &DispatchProcess::func0);
func0();
}
Future<bool> future;
{
Deferred<Future<bool>(void)> func1 =
defer(pid, &DispatchProcess::func1, true);
future = func1();
EXPECT_TRUE(future.get());
}
{
Deferred<Future<bool>(void)> func2 =
defer(pid, &DispatchProcess::func2, true);
future = func2();
EXPECT_TRUE(future.get());
}
{
Deferred<Future<bool>(void)> func4 =
defer(pid, &DispatchProcess::func4, true, 42);
future = func4();
EXPECT_TRUE(future.get());
}
{
Deferred<Future<bool>(bool)> func4 =
defer(pid, &DispatchProcess::func4, lambda::_1, 42);
future = func4(false);
EXPECT_FALSE(future.get());
}
{
Deferred<Future<bool>(int)> func4 =
defer(pid, &DispatchProcess::func4, true, lambda::_1);
future = func4(42);
EXPECT_TRUE(future.get());
}
// Only take const &!
terminate(pid);
wait(pid);
}
class DeferProcess : public Process<DeferProcess>
{
public:
Future<string> func1(const Future<int>& f)
{
return f.then(defer(self(), &Self::_func1, lambda::_1));
}
Future<string> func2(const Future<int>& f)
{
return f.then(defer(self(), &Self::_func2));
}
private:
Future<string> _func1(int i)
{
return stringify(i);
}
Future<string> _func2()
{
return string("42");
}
};
TEST(ProcessTest, Defer2)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
DeferProcess process;
PID<DeferProcess> pid = spawn(process);
Future<string> f = dispatch(pid, &DeferProcess::func1, 41);
f.await();
ASSERT_TRUE(f.isReady());
EXPECT_EQ("41", f.get());
f = dispatch(pid, &DeferProcess::func2, 41);
f.await();
ASSERT_TRUE(f.isReady());
EXPECT_EQ("42", f.get());
terminate(pid);
wait(pid);
}
template <typename T>
void set(T* t1, const T& t2)
{
*t1 = t2;
}
TEST(ProcessTest, Defer3)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
volatile bool bool1 = false;
volatile bool bool2 = false;
Deferred<void(bool)> set1 =
defer([&bool1](bool b) { bool1 = b; });
set1(true);
Deferred<void(bool)> set2 =
defer([&bool2](bool b) { bool2 = b; });
set2(true);
while (!bool1);
while (!bool2);
}
class HandlersProcess : public Process<HandlersProcess>
{
public:
HandlersProcess()
{
install("func", &HandlersProcess::func);
}
MOCK_METHOD2(func, void(const UPID&, const string&));
};
TEST(ProcessTest, Handlers)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
HandlersProcess process;
EXPECT_CALL(process, func(_, _))
.Times(1);
PID<HandlersProcess> pid = spawn(&process);
ASSERT_FALSE(!pid);
post(pid, "func");
terminate(pid, false);
wait(pid);
}
// Tests DROP_MESSAGE and DROP_DISPATCH and in particular that an
// event can get dropped before being processed.
TEST(ProcessTest, Expect)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
HandlersProcess process;
EXPECT_CALL(process, func(_, _))
.Times(0);
PID<HandlersProcess> pid = spawn(&process);
ASSERT_FALSE(!pid);
Future<Message> message = DROP_MESSAGE("func", _, _);
post(pid, "func");
AWAIT_EXPECT_READY(message);
Future<Nothing> func = DROP_DISPATCH(pid, &HandlersProcess::func);
dispatch(pid, &HandlersProcess::func, pid, "");
AWAIT_EXPECT_READY(func);
terminate(pid, false);
wait(pid);
}
// Tests the FutureArg<N> action.
TEST(ProcessTest, Action)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
HandlersProcess process;
PID<HandlersProcess> pid = spawn(&process);
ASSERT_FALSE(!pid);
Future<string> future1;
Future<Nothing> future2;
EXPECT_CALL(process, func(_, _))
.WillOnce(FutureArg<1>(&future1))
.WillOnce(FutureSatisfy(&future2));
dispatch(pid, &HandlersProcess::func, pid, "hello world");
AWAIT_EXPECT_EQ("hello world", future1);
EXPECT_TRUE(future2.isPending());
dispatch(pid, &HandlersProcess::func, pid, "hello world");
AWAIT_EXPECT_READY(future2);
terminate(pid, false);
wait(pid);
}
class BaseProcess : public Process<BaseProcess>
{
public:
virtual void func() = 0;
MOCK_METHOD0(foo, void());
};
class DerivedProcess : public BaseProcess
{
public:
DerivedProcess() {}
MOCK_METHOD0(func, void());
};
TEST(ProcessTest, Inheritance)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
DerivedProcess process;
EXPECT_CALL(process, func())
.Times(2);
EXPECT_CALL(process, foo())
.Times(1);
PID<DerivedProcess> pid1 = spawn(&process);
ASSERT_FALSE(!pid1);
dispatch(pid1, &DerivedProcess::func);
PID<BaseProcess> pid2(process);
PID<BaseProcess> pid3 = pid1;
ASSERT_EQ(pid2, pid3);
dispatch(pid3, &BaseProcess::func);
dispatch(pid3, &BaseProcess::foo);
terminate(pid1, false);
wait(pid1);
}
TEST(ProcessTest, Thunk)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
struct Thunk
{
static int run(int i)
{
return i;
}
static int run(int i, int j)
{
return run(i + j);
}
};
int result = run(&Thunk::run, 21, 21).get();
EXPECT_EQ(42, result);
}
class DelegatorProcess : public Process<DelegatorProcess>
{
public:
explicit DelegatorProcess(const UPID& delegatee)
{
delegate("func", delegatee);
}
};
class DelegateeProcess : public Process<DelegateeProcess>
{
public:
DelegateeProcess()
{
install("func", &DelegateeProcess::func);
}
MOCK_METHOD2(func, void(const UPID&, const string&));
};
TEST(ProcessTest, Delegate)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
DelegateeProcess delegatee;
DelegatorProcess delegator(delegatee.self());
EXPECT_CALL(delegatee, func(_, _))
.Times(1);
spawn(&delegator);
spawn(&delegatee);
post(delegator.self(), "func");
terminate(delegator, false);
wait(delegator);
terminate(delegatee, false);
wait(delegatee);
}
class TimeoutProcess : public Process<TimeoutProcess>
{
public:
MOCK_METHOD0(timeout, void());
};
TEST(ProcessTest, Delay)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
Clock::pause();
volatile bool timeoutCalled = false;
TimeoutProcess process;
EXPECT_CALL(process, timeout())
.WillOnce(Assign(&timeoutCalled, true));
spawn(process);
delay(Seconds(5), process.self(), &TimeoutProcess::timeout);
Clock::advance(Seconds(5));
while (!timeoutCalled);
terminate(process);
wait(process);
Clock::resume();
}
class OrderProcess : public Process<OrderProcess>
{
public:
void order(const PID<TimeoutProcess>& pid)
{
// TODO(benh): Add a test which uses 'send' instead of dispatch.
dispatch(pid, &TimeoutProcess::timeout);
}
};
TEST(ProcessTest, Order)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
Clock::pause();
TimeoutProcess process1;
volatile bool timeoutCalled = false;
EXPECT_CALL(process1, timeout())
.WillOnce(Assign(&timeoutCalled, true));
spawn(process1);
Time now = Clock::now(&process1);
Seconds seconds(1);
Clock::advance(Seconds(1));
EXPECT_EQ(now, Clock::now(&process1));
OrderProcess process2;
spawn(process2);
dispatch(process2, &OrderProcess::order, process1.self());
while (!timeoutCalled);
EXPECT_EQ(now + seconds, Clock::now(&process1));
terminate(process1);
wait(process1);
terminate(process2);
wait(process2);
Clock::resume();
}
class DonateProcess : public Process<DonateProcess>
{
public:
void donate()
{
DonateProcess process;
spawn(process);
terminate(process);
wait(process);
}
};
TEST(ProcessTest, Donate)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
DonateProcess process;
spawn(process);
dispatch(process, &DonateProcess::donate);
terminate(process, false);
wait(process);
}
class ExitedProcess : public Process<ExitedProcess>
{
public:
explicit ExitedProcess(const UPID& pid) { link(pid); }
MOCK_METHOD1(exited, void(const UPID&));
};
TEST(ProcessTest, Exited)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
UPID pid = spawn(new ProcessBase(), true);
ExitedProcess process(pid);
volatile bool exitedCalled = false;
EXPECT_CALL(process, exited(pid))
.WillOnce(Assign(&exitedCalled, true));
spawn(process);
terminate(pid);
while (!exitedCalled);
terminate(process);
wait(process);
}
TEST(ProcessTest, InjectExited)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
UPID pid = spawn(new ProcessBase(), true);
ExitedProcess process(pid);
volatile bool exitedCalled = false;
EXPECT_CALL(process, exited(pid))
.WillOnce(Assign(&exitedCalled, true));
spawn(process);
inject::exited(pid, process.self());
while (!exitedCalled);
terminate(process);
wait(process);
}
TEST(ProcessTest, Select)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
Promise<int> promise1;
Promise<int> promise2;
Promise<int> promise3;
Promise<int> promise4;
std::set<Future<int>> futures;
futures.insert(promise1.future());
futures.insert(promise2.future());
futures.insert(promise3.future());
futures.insert(promise4.future());
promise1.set(42);
Future<Future<int>> future = select(futures);
AWAIT_READY(future);
AWAIT_READY(future.get());
EXPECT_EQ(42, future.get().get());
futures.erase(promise1.future());
future = select(futures);
EXPECT_TRUE(future.isPending());
future.discard();
AWAIT_DISCARDED(future);
}
class SettleProcess : public Process<SettleProcess>
{
public:
SettleProcess() : calledDispatch(false) {}
virtual void initialize()
{
os::sleep(Milliseconds(10));
delay(Seconds(0), self(), &SettleProcess::afterDelay);
}
void afterDelay()
{
dispatch(self(), &SettleProcess::afterDispatch);
os::sleep(Milliseconds(10));
TimeoutProcess timeoutProcess;
spawn(timeoutProcess);
terminate(timeoutProcess);
wait(timeoutProcess);
}
void afterDispatch()
{
os::sleep(Milliseconds(10));
calledDispatch = true;
}
volatile bool calledDispatch;
};
TEST(ProcessTest, Settle)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
Clock::pause();
SettleProcess process;
spawn(process);
Clock::settle();
ASSERT_TRUE(process.calledDispatch);
terminate(process);
wait(process);
Clock::resume();
}
TEST(ProcessTest, Pid)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
TimeoutProcess process;
PID<TimeoutProcess> pid = process;
}
class Listener1 : public Process<Listener1>
{
public:
virtual void event1() = 0;
};
class Listener2 : public Process<Listener2>
{
public:
virtual void event2() = 0;
};
class MultipleListenerProcess
: public Process<MultipleListenerProcess>,
public Listener1,
public Listener2
{
public:
MOCK_METHOD0(event1, void());
MOCK_METHOD0(event2, void());
};
TEST(ProcessTest, Listener)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
MultipleListenerProcess process;
EXPECT_CALL(process, event1())
.Times(1);
EXPECT_CALL(process, event2())
.Times(1);
spawn(process);
dispatch(PID<Listener1>(process), &Listener1::event1);
dispatch(PID<Listener2>(process), &Listener2::event2);
terminate(process, false);
wait(process);
}
class EventReceiver
{
public:
MOCK_METHOD1(event1, void(int));
MOCK_METHOD1(event2, void(const string&));
};
TEST(ProcessTest, Executor)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
volatile bool event1Called = false;
volatile bool event2Called = false;
EventReceiver receiver;
EXPECT_CALL(receiver, event1(42))
.WillOnce(Assign(&event1Called, true));
EXPECT_CALL(receiver, event2("event2"))
.WillOnce(Assign(&event2Called, true));
Executor executor;
Deferred<void(int)> event1 =
executor.defer([&receiver](int i) {
return receiver.event1(i);
});
event1(42);
Deferred<void(const string&)> event2 =
executor.defer([&receiver](const string& s) {
return receiver.event2(s);
});
event2("event2");
while (!event1Called);
while (!event2Called);
}
class RemoteProcess : public Process<RemoteProcess>
{
public:
RemoteProcess()
{
install("handler", &RemoteProcess::handler);
}
MOCK_METHOD2(handler, void(const UPID&, const string&));
};
TEST(ProcessTest, Remote)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
RemoteProcess process;
spawn(process);
Future<Nothing> handler;
EXPECT_CALL(process, handler(_, _))
.WillOnce(FutureSatisfy(&handler));
Try<Socket> create = Socket::create();
ASSERT_SOME(create);
Socket socket = create.get();
AWAIT_READY(socket.connect(process.self().address));
Message message;
message.name = "handler";
message.from = UPID();
message.to = process.self();
const string data = MessageEncoder::encode(&message);
AWAIT_READY(socket.send(data));
AWAIT_READY(handler);
terminate(process);
wait(process);
}
// Like the 'remote' test but uses http::post.
TEST(ProcessTest, Http1)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
RemoteProcess process;
spawn(process);
Future<UPID> pid;
Future<string> body;
EXPECT_CALL(process, handler(_, _))
.WillOnce(DoAll(FutureArg<0>(&pid),
FutureArg<1>(&body)));
http::Headers headers;
headers["User-Agent"] = "libprocess/";
Future<http::Response> response =
http::post(process.self(), "handler", headers, "hello world");
AWAIT_READY(body);
ASSERT_EQ("hello world", body.get());
AWAIT_READY(pid);
ASSERT_EQ(UPID(), pid.get());
terminate(process);
wait(process);
}
// Like 'http1' but using a 'Libprocess-From' header.
TEST(ProcessTest, Http2)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
RemoteProcess process;
spawn(process);
// Create a receiving socket so we can get messages back.
Try<Socket> create = Socket::create();
ASSERT_SOME(create);
Socket socket = create.get();
ASSERT_SOME(socket.bind(Address()));
// Create a UPID for 'Libprocess-From' based on the IP and port we
// got assigned.
Try<Address> address = socket.address();
ASSERT_SOME(address);
UPID from("", address.get());
ASSERT_SOME(socket.listen(1));
Future<UPID> pid;
Future<string> body;
EXPECT_CALL(process, handler(_, _))
.WillOnce(DoAll(FutureArg<0>(&pid),
FutureArg<1>(&body)));
http::Headers headers;
headers["Libprocess-From"] = stringify(from);
Future<http::Response> response =
http::post(process.self(), "handler", headers, "hello world");
AWAIT_READY(response);
ASSERT_EQ(http::statuses[202], response.get().status);
AWAIT_READY(body);
ASSERT_EQ("hello world", body.get());
AWAIT_READY(pid);
ASSERT_EQ(from, pid.get());
// Now post a message as though it came from the process.
const string name = "reply";
post(process.self(), from, name);
// Accept the incoming connection.
Future<Socket> accept = socket.accept();
AWAIT_READY(accept);
Socket client = accept.get();
const string data = "POST /" + name + " HTTP/1.1";
AWAIT_EXPECT_EQ(data, client.recv(data.size()));
terminate(process);
wait(process);
}
int foo()
{
return 1;
}
int foo1(int a)
{
return a;
}
int foo2(int a, int b)
{
return a + b;
}
int foo3(int a, int b, int c)
{
return a + b + c;
}
int foo4(int a, int b, int c, int d)
{
return a + b + c + d;
}
void bar(int a)
{
return;
}
TEST(ProcessTest, Async)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
// Non-void functions with different no.of args.
EXPECT_EQ(1, async(&foo).get());
EXPECT_EQ(10, async(&foo1, 10).get());
EXPECT_EQ(30, async(&foo2, 10, 20).get());
EXPECT_EQ(60, async(&foo3, 10, 20, 30).get());
EXPECT_EQ(100, async(&foo4, 10, 20, 30, 40).get());
// Non-void function with a complex arg.
int i = 42;
EXPECT_EQ("42", async(&itoa2, &i).get());
// Non-void function that returns a future.
EXPECT_EQ("42", async(&itoa1, &i).get().get());
}
class FileServer : public Process<FileServer>
{
public:
explicit FileServer(const string& _path)
: path(_path) {}
virtual void initialize()
{
provide("", path);
}
const string path;
};
TEST(ProcessTest, Provide)
{
const Try<string> mkdtemp = os::mkdtemp();
ASSERT_SOME(mkdtemp);
const string LOREM_IPSUM =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do "
"eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad "
"minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip "
"ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur "
"sint occaecat cupidatat non proident, sunt in culpa qui officia "
"deserunt mollit anim id est laborum.";
const string path = path::join(mkdtemp.get(), "lorem.txt");
ASSERT_SOME(os::write(path, LOREM_IPSUM));
FileServer server(path);
PID<FileServer> pid = spawn(server);
Future<http::Response> response = http::get(pid);
AWAIT_READY(response);
ASSERT_EQ(LOREM_IPSUM, response.get().body);
terminate(server);
wait(server);
ASSERT_SOME(os::rmdir(path));
}
int baz(string s) { return 42; }
Future<int> bam(string s) { return 42; }
TEST(ProcessTest, Defers)
{
{
std::function<Future<int>(string)> f =
defer(std::bind(baz, std::placeholders::_1));
Deferred<Future<int>(string)> d =
defer(std::bind(baz, std::placeholders::_1));
Future<int> future = Future<string>().then(
defer(std::bind(baz, std::placeholders::_1)));
Future<int> future3 = Future<string>().then(
std::bind(baz, std::placeholders::_1));
Future<string>().then(std::function<int(string)>());
Future<string>().then(std::function<int(void)>());
Future<int> future11 = Future<string>().then(
defer(std::bind(bam, std::placeholders::_1)));
Future<int> future12 = Future<string>().then(
std::bind(bam, std::placeholders::_1));
std::function<Future<int>(string)> f2 =
defer([](string s) { return baz(s); });
Deferred<Future<int>(string)> d2 =
defer([](string s) { return baz(s); });
Future<int> future2 = Future<string>().then(
defer([](string s) { return baz(s); }));
Future<int> future4 = Future<string>().then(
[](string s) { return baz(s); });
Future<int> future5 = Future<string>().then(
defer([](string s) -> Future<int> { return baz(s); }));
Future<int> future6 = Future<string>().then(
defer([](string s) { return Future<int>(baz(s)); }));
Future<int> future7 = Future<string>().then(
defer([](string s) { return bam(s); }));
Future<int> future8 = Future<string>().then(
[](string s) { return Future<int>(baz(s)); });
Future<int> future9 = Future<string>().then(
[](string s) -> Future<int> { return baz(s); });
Future<int> future10 = Future<string>().then(
[](string s) { return bam(s); });
}
// {
// // CAN NOT DO IN CLANG!
// std::function<void(string)> f =
// defer(std::bind(baz, std::placeholders::_1));
// std::function<int(string)> blah;
// std::function<void(string)> blam = blah;
// std::function<void(string)> f2 =
// defer([](string s) { return baz(s); });
// }
// {
// // CAN NOT DO WITH GCC OR CLANG!
// std::function<int(int)> f =
// defer(std::bind(baz, std::placeholders::_1));
// }
{
std::function<Future<int>(void)> f =
defer(std::bind(baz, "42"));
std::function<Future<int>(void)> f2 =
defer([]() { return baz("42"); });
}
{
std::function<Future<int>(int)> f =
defer(std::bind(baz, "42"));
std::function<Future<int>(int)> f2 =
defer([](int i) { return baz("42"); });
}
// Don't care about value passed from Future::then.
{
Future<int> future = Future<string>().then(
defer(std::bind(baz, "42")));
Future<int> future3 = Future<string>().then(
std::bind(baz, "42"));
Future<int> future11 = Future<string>().then(
defer(std::bind(bam, "42")));
Future<int> future12 = Future<string>().then(
std::bind(bam, "42"));
Future<int> future2 = Future<string>().then(
defer([]() { return baz("42"); }));
Future<int> future4 = Future<string>().then(
[]() { return baz("42"); });
Future<int> future5 = Future<string>().then(
defer([]() -> Future<int> { return baz("42"); }));
Future<int> future6 = Future<string>().then(
defer([]() { return Future<int>(baz("42")); }));
Future<int> future7 = Future<string>().then(
defer([]() { return bam("42"); }));
Future<int> future8 = Future<string>().then(
[]() { return Future<int>(baz("42")); });
Future<int> future9 = Future<string>().then(
[]() -> Future<int> { return baz("42"); });
Future<int> future10 = Future<string>().then(
[]() { return bam("42"); });
}
struct Functor
{
int operator()(string) const { return 42; }
int operator()() const { return 42; }
} functor;
Future<int> future13 = Future<string>().then(
defer(functor));
}
TEST(ProcessTest, FromTry)
{
Try<int> t = 1;
Future<int> future = t;
ASSERT_TRUE(future.isReady());
EXPECT_EQ(1, future.get());
t = Error("error");
future = t;
ASSERT_TRUE(future.isFailed());
}
class PercentEncodedIDProcess : public Process<PercentEncodedIDProcess>
{
public:
PercentEncodedIDProcess()
: ProcessBase("id(42)") {}
virtual void initialize()
{
install("handler1", &Self::handler1);
route("/handler2", None(), &Self::handler2);
}
MOCK_METHOD2(handler1, void(const UPID&, const string&));
MOCK_METHOD1(handler2, Future<http::Response>(const http::Request&));
};
TEST(ProcessTest, PercentEncodedURLs)
{
PercentEncodedIDProcess process;
spawn(process);
// Construct the PID using percent-encoding.
UPID pid("id%2842%29", process.self().address);
// Mimic a libprocess message sent to an installed handler.
Future<Nothing> handler1;
EXPECT_CALL(process, handler1(_, _))
.WillOnce(FutureSatisfy(&handler1));
http::Headers headers;
headers["User-Agent"] = "libprocess/";
Future<http::Response> response = http::post(pid, "handler1", headers);
AWAIT_READY(handler1);
// Now an HTTP request.
EXPECT_CALL(process, handler2(_))
.WillOnce(Return(http::OK()));
response = http::get(pid, "handler2");
AWAIT_READY(response);
EXPECT_EQ(http::statuses[200], response.get().status);
terminate(process);
wait(process);
}
class HTTPEndpointProcess : public Process<HTTPEndpointProcess>
{
public:
explicit HTTPEndpointProcess(const std::string& id)
: ProcessBase(id) {}
virtual void initialize()
{
route(
"/handler1",
None(),
&HTTPEndpointProcess::handler1);
route(
"/handler2",
None(),
&HTTPEndpointProcess::handler2);
route(
"/handler3",
None(),
&HTTPEndpointProcess::handler3);
}
MOCK_METHOD1(handler1, Future<http::Response>(const http::Request&));
MOCK_METHOD1(handler2, Future<http::Response>(const http::Request&));
MOCK_METHOD1(handler3, Future<http::Response>(const http::Request&));
};
// Sets firewall rules which disable endpoints on a process and then
// attempts to connect to those endpoints.
TEST(ProcessTest, FirewallDisablePaths)
{
const string id = "testprocess";
// TODO(arojas): Add initilization list construction when available.
hashset<string> endpoints;
endpoints.insert(path::join("", id, "handler1"));
endpoints.insert(path::join("", id, "handler2/nested"));
// Patterns are not supported, so this should do nothing.
endpoints.insert(path::join("", id, "handler3/*"));
process::firewall::install(
{Owned<FirewallRule>(new DisabledEndpointsFirewallRule(endpoints))});
HTTPEndpointProcess process(id);
PID<HTTPEndpointProcess> pid = spawn(process);
// Test call to a disabled endpoint.
Future<http::Response> response = http::get(pid, "handler1");
AWAIT_READY(response);
EXPECT_EQ(http::statuses[403], response.get().status);
// Test call to a non disabled endpoint.
// Substrings should not match.
EXPECT_CALL(process, handler2(_))
.WillOnce(Return(http::OK()));
response = http::get(pid, "handler2");
AWAIT_READY(response);
EXPECT_EQ(http::statuses[200], response.get().status);
// Test nested endpoints. Full paths needed for match.
response = http::get(pid, "handler2/nested");
AWAIT_READY(response);
EXPECT_EQ(http::statuses[403], response.get().status);
EXPECT_CALL(process, handler2(_))
.WillOnce(Return(http::OK()));
response = http::get(pid, "handler2/nested/path");
AWAIT_READY(response);
EXPECT_EQ(http::statuses[200], response.get().status);
EXPECT_CALL(process, handler3(_))
.WillOnce(Return(http::OK()));
// Test a wildcard rule. Since they are not supported, it must have
// no effect at all.
response = http::get(pid, "handler3");
AWAIT_READY(response);
EXPECT_EQ(http::statuses[200], response.get().status);
EXPECT_CALL(process, handler3(_))
.WillOnce(Return(http::OK()));
response = http::get(pid, "handler3/nested");
AWAIT_READY(response);
EXPECT_EQ(http::statuses[200], response.get().status);
terminate(process);
wait(process);
}
// Test that firewall rules can be changed by changing the vector.
// An empty vector should allow all paths.
TEST(ProcessTest, FirewallUninstall)
{
const string id = "testprocess";
// TODO(arojas): Add initilization list construction when available.
hashset<string> endpoints;
endpoints.insert(path::join("", id, "handler1"));
endpoints.insert(path::join("", id, "handler2"));
process::firewall::install(
{Owned<FirewallRule>(new DisabledEndpointsFirewallRule(endpoints))});
HTTPEndpointProcess process(id);
PID<HTTPEndpointProcess> pid = spawn(process);
Future<http::Response> response = http::get(pid, "handler1");
AWAIT_READY(response);
EXPECT_EQ(http::statuses[403], response.get().status);
response = http::get(pid, "handler2");
AWAIT_READY(response);
EXPECT_EQ(http::statuses[403], response.get().status);
process::firewall::install({});
EXPECT_CALL(process, handler1(_))
.WillOnce(Return(http::OK()));
response = http::get(pid, "handler1");
AWAIT_READY(response);
EXPECT_EQ(http::statuses[200], response.get().status);
EXPECT_CALL(process, handler2(_))
.WillOnce(Return(http::OK()));
response = http::get(pid, "handler2");
AWAIT_READY(response);
EXPECT_EQ(http::statuses[200], response.get().status);
terminate(process);
wait(process);
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r8
push %r9
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_D_ht+0xbf0, %rdx
nop
add $65109, %rdi
movb (%rdx), %r8b
nop
nop
nop
nop
and %r11, %r11
lea addresses_WC_ht+0xbbb0, %rsi
lea addresses_D_ht+0x1bdf0, %rdi
clflush (%rsi)
clflush (%rdi)
nop
nop
and $24148, %r9
mov $105, %rcx
rep movsw
nop
nop
nop
nop
add %r8, %r8
lea addresses_D_ht+0xddf0, %rsi
lea addresses_WC_ht+0xbbfc, %rdi
xor $3043, %r8
mov $87, %rcx
rep movsw
nop
nop
nop
nop
xor %rdi, %rdi
lea addresses_D_ht+0x1ad58, %r11
nop
and %rdx, %rdx
movb (%r11), %r9b
nop
inc %r11
lea addresses_A_ht+0x1a3f0, %rdi
and %r8, %r8
vmovups (%rdi), %ymm7
vextracti128 $1, %ymm7, %xmm7
vpextrq $0, %xmm7, %r11
nop
nop
nop
xor $42030, %r9
lea addresses_UC_ht+0xa7ac, %rsi
lea addresses_normal_ht+0xb34d, %rdi
nop
nop
nop
nop
add $3407, %rdx
mov $28, %rcx
rep movsl
nop
nop
nop
sub %r11, %r11
lea addresses_A_ht+0x1e9f0, %rsi
lea addresses_D_ht+0x149f0, %rdi
nop
nop
cmp %r10, %r10
mov $7, %rcx
rep movsw
nop
nop
nop
add $54072, %rcx
lea addresses_normal_ht+0x9f0, %r10
nop
nop
sub $60790, %r11
movb $0x61, (%r10)
nop
nop
nop
xor $42545, %r10
lea addresses_A_ht+0x8bf0, %rsi
lea addresses_WC_ht+0x76c, %rdi
nop
nop
nop
nop
xor %rdx, %rdx
mov $30, %rcx
rep movsw
nop
nop
nop
nop
dec %rdi
lea addresses_normal_ht+0x11c30, %r9
nop
nop
nop
nop
nop
and $36804, %r8
movb (%r9), %dl
nop
nop
nop
mfence
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r9
pop %r8
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r14
push %r15
push %r8
push %rcx
push %rsi
// Store
lea addresses_normal+0x18c10, %r15
nop
nop
sub $33424, %r11
movl $0x51525354, (%r15)
nop
nop
nop
and %r11, %r11
// Store
lea addresses_D+0xdaa8, %rcx
nop
nop
nop
nop
sub $20175, %r8
mov $0x5152535455565758, %r13
movq %r13, (%rcx)
add $29021, %r8
// Store
lea addresses_normal+0x21e8, %r11
sub %r14, %r14
movb $0x51, (%r11)
nop
nop
nop
nop
sub %r8, %r8
// Faulty Load
lea addresses_D+0x185f0, %rsi
nop
dec %r13
movups (%rsi), %xmm1
vpextrq $1, %xmm1, %rcx
lea oracles, %r8
and $0xff, %rcx
shlq $12, %rcx
mov (%r8,%rcx,1), %rcx
pop %rsi
pop %rcx
pop %r8
pop %r15
pop %r14
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_D', 'same': True, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_normal', 'same': False, 'size': 4, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_D', 'same': True, 'size': 8, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_normal', 'same': False, 'size': 1, 'congruent': 1, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_D', 'same': True, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_D_ht', 'same': False, 'size': 1, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_A_ht', 'same': False, 'size': 32, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 1, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 1, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'36': 21829}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
|
db DEX_PERSIAN ; pokedex id
db 65 ; base hp
db 70 ; base attack
db 60 ; base defense
db 115 ; base speed
db 65 ; base special
db NORMAL ; species type 1
db NORMAL ; species type 2
db 90 ; catch rate
db 148 ; base exp yield
INCBIN "pic/ymon/persian.pic",0,1 ; 77, sprite dimensions
dw PersianPicFront
dw PersianPicBack
; attacks known at lvl 0
db SCRATCH
db GROWL
db BITE
db SCREECH
db 0 ; growth rate
; learnset
tmlearn 6,8
tmlearn 9,10,11,12,15,16
tmlearn 20,24
tmlearn 25,31,32
tmlearn 34,39,40
tmlearn 44
tmlearn 50
db BANK(PersianPicFront)
|
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.24.28117.0
TITLE C:\Users\libit\source\repos\L037\L037\L037.cpp
.686P
.XMM
include listing.inc
.model flat
INCLUDELIB LIBCMT
INCLUDELIB OLDNAMES
CONST SEGMENT
$SG5561 DB 'Hello World!', 0aH, 00H
ORG $+2
$SG5562 DB 'a[%d]=%d', 0aH, 00H
CONST ENDS
PUBLIC ___local_stdio_printf_options
PUBLIC __vfprintf_l
PUBLIC _printf
PUBLIC _main
PUBLIC ?_OptionsStorage@?1??__local_stdio_printf_options@@9@4_KA ; `__local_stdio_printf_options'::`2'::_OptionsStorage
PUBLIC __xmm@00000006000000040000000200000000
PUBLIC __xmm@0000000e0000000c0000000a00000008
PUBLIC __xmm@00000016000000140000001200000010
PUBLIC __xmm@0000001e0000001c0000001a00000018
EXTRN ___acrt_iob_func:PROC
EXTRN ___stdio_common_vfprintf:PROC
EXTRN @__security_check_cookie@4:PROC
EXTRN ___security_cookie:DWORD
; COMDAT ?_OptionsStorage@?1??__local_stdio_printf_options@@9@4_KA
_BSS SEGMENT
?_OptionsStorage@?1??__local_stdio_printf_options@@9@4_KA DQ 01H DUP (?) ; `__local_stdio_printf_options'::`2'::_OptionsStorage
_BSS ENDS
; COMDAT __xmm@0000001e0000001c0000001a00000018
CONST SEGMENT
__xmm@0000001e0000001c0000001a00000018 DB 018H, 00H, 00H, 00H, 01aH, 00H, 00H
DB 00H, 01cH, 00H, 00H, 00H, 01eH, 00H, 00H, 00H
CONST ENDS
; COMDAT __xmm@00000016000000140000001200000010
CONST SEGMENT
__xmm@00000016000000140000001200000010 DB 010H, 00H, 00H, 00H, 012H, 00H, 00H
DB 00H, 014H, 00H, 00H, 00H, 016H, 00H, 00H, 00H
CONST ENDS
; COMDAT __xmm@0000000e0000000c0000000a00000008
CONST SEGMENT
__xmm@0000000e0000000c0000000a00000008 DB 08H, 00H, 00H, 00H, 0aH, 00H, 00H
DB 00H, 0cH, 00H, 00H, 00H, 0eH, 00H, 00H, 00H
CONST ENDS
; COMDAT __xmm@00000006000000040000000200000000
CONST SEGMENT
__xmm@00000006000000040000000200000000 DB 00H, 00H, 00H, 00H, 02H, 00H, 00H
DB 00H, 04H, 00H, 00H, 00H, 06H, 00H, 00H, 00H
CONST ENDS
; Function compile flags: /Ogtpy
_TEXT SEGMENT
_a$ = -84 ; size = 80
__$ArrayPad$ = -4 ; size = 4
_main PROC
; File C:\Users\libit\source\repos\L037\L037\L037.cpp
; Line 7
sub esp, 84 ; 00000054H
mov eax, DWORD PTR ___security_cookie
xor eax, esp
mov DWORD PTR __$ArrayPad$[esp+84], eax
; Line 8
push OFFSET $SG5561
call _printf
; Line 15
movaps xmm0, XMMWORD PTR __xmm@00000006000000040000000200000000
lea ecx, DWORD PTR _a$[esp+152]
movups XMMWORD PTR _a$[esp+88], xmm0
add esp, 4
mov eax, 32 ; 00000020H
movaps xmm0, XMMWORD PTR __xmm@0000000e0000000c0000000a00000008
movups XMMWORD PTR _a$[esp+100], xmm0
movaps xmm0, XMMWORD PTR __xmm@00000016000000140000001200000010
movups XMMWORD PTR _a$[esp+116], xmm0
movaps xmm0, XMMWORD PTR __xmm@0000001e0000001c0000001a00000018
movups XMMWORD PTR _a$[esp+132], xmm0
$LL13@main:
mov DWORD PTR [ecx], eax
lea ecx, DWORD PTR [ecx+4]
add eax, 2
cmp eax, 40 ; 00000028H
jl SHORT $LL13@main
; Line 18
push esi
xor esi, esi
$LL7@main:
; Line 20
push DWORD PTR _a$[esp+esi*4+88]
push esi
push OFFSET $SG5562
call _printf
inc esi
add esp, 12 ; 0000000cH
cmp esi, 20 ; 00000014H
jl SHORT $LL7@main
; Line 22
mov ecx, DWORD PTR __$ArrayPad$[esp+88]
xor eax, eax
pop esi
xor ecx, esp
call @__security_check_cookie@4
add esp, 84 ; 00000054H
ret 0
_main ENDP
_TEXT ENDS
; Function compile flags: /Ogtpy
; COMDAT _printf
_TEXT SEGMENT
__Format$ = 8 ; size = 4
_printf PROC ; COMDAT
; File C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\stdio.h
; Line 954
push esi
; Line 958
mov esi, DWORD PTR __Format$[esp]
push 1
call ___acrt_iob_func
add esp, 4
; Line 643
lea ecx, DWORD PTR __Format$[esp+4]
push ecx
push 0
push esi
push eax
call ___local_stdio_printf_options
push DWORD PTR [eax+4]
push DWORD PTR [eax]
call ___stdio_common_vfprintf
add esp, 24 ; 00000018H
; Line 960
pop esi
; Line 961
ret 0
_printf ENDP
_TEXT ENDS
; Function compile flags: /Ogtpy
; COMDAT __vfprintf_l
_TEXT SEGMENT
__Stream$ = 8 ; size = 4
__Format$ = 12 ; size = 4
__Locale$ = 16 ; size = 4
__ArgList$ = 20 ; size = 4
__vfprintf_l PROC ; COMDAT
; File C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\stdio.h
; Line 643
push DWORD PTR __ArgList$[esp-4]
push DWORD PTR __Locale$[esp]
push DWORD PTR __Format$[esp+4]
push DWORD PTR __Stream$[esp+8]
call ___local_stdio_printf_options
push DWORD PTR [eax+4]
push DWORD PTR [eax]
call ___stdio_common_vfprintf
add esp, 24 ; 00000018H
; Line 644
ret 0
__vfprintf_l ENDP
_TEXT ENDS
; Function compile flags: /Ogtpy
; COMDAT ___local_stdio_printf_options
_TEXT SEGMENT
___local_stdio_printf_options PROC ; COMDAT
; File C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\corecrt_stdio_config.h
; Line 88
mov eax, OFFSET ?_OptionsStorage@?1??__local_stdio_printf_options@@9@4_KA ; `__local_stdio_printf_options'::`2'::_OptionsStorage
; Line 89
ret 0
___local_stdio_printf_options ENDP
_TEXT ENDS
END
|
; A088378: (Smallest prime-factor of n)^3.
; 1,8,27,8,125,8,343,8,27,8,1331,8,2197,8,27,8,4913,8,6859,8,27,8,12167,8,125,8,27,8,24389,8,29791,8,27,8,125,8,50653,8,27,8,68921,8,79507,8,27,8,103823,8,343,8,27,8,148877,8,125,8,27,8,205379,8,226981,8,27,8,125,8,300763,8,27,8,357911,8,389017,8,27,8,343,8,493039,8,27,8,571787,8,125,8,27,8,704969,8,343,8,27,8,125,8,912673,8,27,8,1030301,8,1092727,8,27,8,1225043,8,1295029,8,27,8,1442897,8,125,8,27,8,343,8,1331,8,27,8,125,8,2048383,8,27,8,2248091,8,343,8,27,8,2571353,8,2685619,8,27,8,1331,8,125,8,27,8,3307949,8,3442951,8,27,8,125,8,3869893,8,27,8,343,8,4330747,8,27,8,4657463,8,2197,8,27,8,5177717,8,125,8,27,8,5735339,8,5929741,8,27,8,125,8,1331,8,27,8,6967871,8,7189057,8,27,8,7645373,8,7880599,8,27,8,343,8,125,8,27,8,1331,8,9393931,8,27,8,125,8,343,8,27,8,2197,8,11089567,8,27,8,11697083,8,12008989,8,27,8,12649337,8,125,8,27,8,13651919,8,13997521,8,27,8,125,8,2197,8,27,8
cal $0,20639 ; Lpf(n): least prime dividing n (when n > 1); a(1) = 1. Or, smallest prime factor of n, or smallest prime divisor of n.
pow $0,3
mov $1,$0
|
; A034132: Decimal part of cube root of a(n) starts with 6: first term of runs.
; 18,47,98,176,288,439,637,885,1192,1561,2001,2516,3113,3797,4575,5452,6435,7530,8742,10078,11544,13145,14887,16778,18822,21025,23394,25935,28653,31555,34646,37934,41422,45119,49028,53158,57513,62100,66924
mov $5,$0
mul $0,10
mov $3,$0
mov $0,43071
mov $1,$3
sub $1,4
mov $6,$1
mov $1,3
add $6,54
lpb $0
mov $0,6
sub $6,4
bin $6,2
mul $6,2
add $1,$6
div $1,125
lpe
add $1,2
mov $2,$5
mul $2,13
add $1,$2
mov $4,$5
mul $4,$5
mov $2,$4
mul $2,7
add $1,$2
mul $4,$5
add $1,$4
|
;;
;; Copyright (c) 2021, Intel Corporation
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice,
;; this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;; * Neither the name of Intel Corporation nor the names of its contributors
;; may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;
%include "include/os.asm"
%include "include/reg_sizes.asm"
%include "include/memcpy.asm"
%include "include/imb_job.asm"
%include "include/clear_regs.asm"
%include "include/cet.inc"
[bits 64]
default rel
align 64
mask_44:
dq 0xfffffffffff, 0xfffffffffff, 0xfffffffffff, 0xfffffffffff,
dq 0xfffffffffff, 0xfffffffffff, 0xfffffffffff, 0xfffffffffff
align 64
mask_42:
dq 0x3ffffffffff, 0x3ffffffffff, 0x3ffffffffff, 0x3ffffffffff,
dq 0x3ffffffffff, 0x3ffffffffff, 0x3ffffffffff, 0x3ffffffffff
align 64
high_bit:
dq 0x10000000000, 0x10000000000, 0x10000000000, 0x10000000000,
dq 0x10000000000, 0x10000000000, 0x10000000000, 0x10000000000
align 64
byte_len_to_mask_table:
dw 0x0000, 0x0001, 0x0003, 0x0007,
dw 0x000f, 0x001f, 0x003f, 0x007f,
dw 0x00ff, 0x01ff, 0x03ff, 0x07ff,
dw 0x0fff, 0x1fff, 0x3fff, 0x7fff,
dw 0xffff
align 16
pad16_bit:
dq 0x01, 0x0
dq 0x0100, 0x0
dq 0x010000, 0x0
dq 0x01000000, 0x0
dq 0x0100000000, 0x0
dq 0x010000000000, 0x0
dq 0x01000000000000, 0x0
dq 0x0100000000000000, 0x0
dq 0x0, 0x01
dq 0x0, 0x0100
dq 0x0, 0x010000
dq 0x0, 0x01000000
dq 0x0, 0x0100000000
dq 0x0, 0x010000000000
dq 0x0, 0x01000000000000
dq 0x0, 0x0100000000000000
align 64
pad64_bit:
dq 0, 0, 0, 0, 0, 0, 0, 0
dq 0x0100, 0, 0, 0, 0, 0, 0, 0
dq 0x010000, 0, 0, 0, 0, 0, 0, 0
dq 0x01000000, 0, 0, 0, 0, 0, 0, 0
dq 0x0100000000, 0, 0, 0, 0, 0, 0, 0
dq 0x010000000000, 0, 0, 0, 0, 0, 0, 0
dq 0x01000000000000, 0, 0, 0, 0, 0, 0, 0
dq 0x0100000000000000, 0, 0, 0, 0, 0, 0, 0
dq 0, 0x01, 0, 0, 0, 0, 0, 0
dq 0, 0x0100, 0, 0, 0, 0, 0, 0
dq 0, 0x010000, 0, 0, 0, 0, 0, 0
dq 0, 0x01000000, 0, 0, 0, 0, 0, 0
dq 0, 0x0100000000, 0, 0, 0, 0, 0, 0
dq 0, 0x010000000000, 0, 0, 0, 0, 0, 0
dq 0, 0x01000000000000, 0, 0, 0, 0, 0, 0
dq 0, 0x0100000000000000, 0, 0, 0, 0, 0, 0
dq 0, 0, 0, 0, 0, 0, 0, 0
dq 0, 0, 0x0100, 0, 0, 0, 0, 0
dq 0, 0, 0x010000, 0, 0, 0, 0, 0
dq 0, 0, 0x01000000, 0, 0, 0, 0, 0
dq 0, 0, 0x0100000000, 0, 0, 0, 0, 0
dq 0, 0, 0x010000000000, 0, 0, 0, 0, 0
dq 0, 0, 0x01000000000000, 0, 0, 0, 0, 0
dq 0, 0, 0x0100000000000000, 0, 0, 0, 0, 0
dq 0, 0, 0, 0x01, 0, 0, 0, 0
dq 0, 0, 0, 0x0100, 0, 0, 0, 0
dq 0, 0, 0, 0x010000, 0, 0, 0, 0
dq 0, 0, 0, 0x01000000, 0, 0, 0, 0
dq 0, 0, 0, 0x0100000000, 0, 0, 0, 0
dq 0, 0, 0, 0x010000000000, 0, 0, 0, 0
dq 0, 0, 0, 0x01000000000000, 0, 0, 0, 0
dq 0, 0, 0, 0x0100000000000000, 0, 0, 0, 0
dq 0, 0, 0, 0, 0, 0, 0, 0
dq 0, 0, 0, 0, 0x0100, 0, 0, 0
dq 0, 0, 0, 0, 0x010000, 0, 0, 0
dq 0, 0, 0, 0, 0x01000000, 0, 0, 0
dq 0, 0, 0, 0, 0x0100000000, 0, 0, 0
dq 0, 0, 0, 0, 0x010000000000, 0, 0, 0
dq 0, 0, 0, 0, 0x01000000000000, 0, 0, 0
dq 0, 0, 0, 0, 0x0100000000000000, 0, 0, 0
dq 0, 0, 0, 0, 0, 0x01, 0, 0
dq 0, 0, 0, 0, 0, 0x0100, 0, 0
dq 0, 0, 0, 0, 0, 0x010000, 0, 0
dq 0, 0, 0, 0, 0, 0x01000000, 0, 0
dq 0, 0, 0, 0, 0, 0x0100000000, 0, 0
dq 0, 0, 0, 0, 0, 0x010000000000, 0, 0
dq 0, 0, 0, 0, 0, 0x01000000000000, 0, 0
dq 0, 0, 0, 0, 0, 0x0100000000000000, 0, 0
dq 0, 0, 0, 0, 0, 0, 0, 0
dq 0, 0, 0, 0, 0, 0, 0x0100, 0
dq 0, 0, 0, 0, 0, 0, 0x010000, 0
dq 0, 0, 0, 0, 0, 0, 0x01000000, 0
dq 0, 0, 0, 0, 0, 0, 0x0100000000, 0
dq 0, 0, 0, 0, 0, 0, 0x010000000000, 0
dq 0, 0, 0, 0, 0, 0, 0x01000000000000, 0
dq 0, 0, 0, 0, 0, 0, 0x0100000000000000, 0
dq 0, 0, 0, 0, 0, 0, 0, 0x01
dq 0, 0, 0, 0, 0, 0, 0, 0x0100
dq 0, 0, 0, 0, 0, 0, 0, 0x010000
dq 0, 0, 0, 0, 0, 0, 0, 0x01000000
dq 0, 0, 0, 0, 0, 0, 0, 0x0100000000
dq 0, 0, 0, 0, 0, 0, 0, 0x010000000000
dq 0, 0, 0, 0, 0, 0, 0, 0x01000000000000
dq 0, 0, 0, 0, 0, 0, 0, 0x0100000000000000
align 64
byte64_len_to_mask_table:
dq 0x0000000000000000, 0x0000000000000001
dq 0x0000000000000003, 0x0000000000000007
dq 0x000000000000000f, 0x000000000000001f
dq 0x000000000000003f, 0x000000000000007f
dq 0x00000000000000ff, 0x00000000000001ff
dq 0x00000000000003ff, 0x00000000000007ff
dq 0x0000000000000fff, 0x0000000000001fff
dq 0x0000000000003fff, 0x0000000000007fff
dq 0x000000000000ffff, 0x000000000001ffff
dq 0x000000000003ffff, 0x000000000007ffff
dq 0x00000000000fffff, 0x00000000001fffff
dq 0x00000000003fffff, 0x00000000007fffff
dq 0x0000000000ffffff, 0x0000000001ffffff
dq 0x0000000003ffffff, 0x0000000007ffffff
dq 0x000000000fffffff, 0x000000001fffffff
dq 0x000000003fffffff, 0x000000007fffffff
dq 0x00000000ffffffff, 0x00000001ffffffff
dq 0x00000003ffffffff, 0x00000007ffffffff
dq 0x0000000fffffffff, 0x0000001fffffffff
dq 0x0000003fffffffff, 0x0000007fffffffff
dq 0x000000ffffffffff, 0x000001ffffffffff
dq 0x000003ffffffffff, 0x000007ffffffffff
dq 0x00000fffffffffff, 0x00001fffffffffff
dq 0x00003fffffffffff, 0x00007fffffffffff
dq 0x0000ffffffffffff, 0x0001ffffffffffff
dq 0x0003ffffffffffff, 0x0007ffffffffffff
dq 0x000fffffffffffff, 0x001fffffffffffff
dq 0x003fffffffffffff, 0x007fffffffffffff
dq 0x00ffffffffffffff, 0x01ffffffffffffff
dq 0x03ffffffffffffff, 0x07ffffffffffffff
dq 0x0fffffffffffffff, 0x1fffffffffffffff
dq 0x3fffffffffffffff, 0x7fffffffffffffff
dq 0xffffffffffffffff
qword_high_bit_mask:
dw 0, 0x1, 0x5, 0x15, 0x55, 0x57, 0x5f, 0x7f, 0xff
%ifdef LINUX
%define arg1 rdi
%define arg2 rsi
%define arg3 rdx
%define arg4 rcx
%define job arg1
%define gp1 rsi
%define gp2 rcx
%else
%define arg1 rcx
%define arg2 rdx
%define arg3 r8
%define arg4 r9
%define job rdi
%define gp1 rcx ;; 'arg1' copied to 'job' at start
%define gp2 rsi
%endif
;; don't use rdx and rax - they are needed for multiply operation
%define gp3 rbp
%define gp4 r8
%define gp5 r9
%define gp6 r10
%define gp7 r11
%define gp8 r12
%define gp9 r13
%define gp10 r14
%define gp11 r15
%xdefine len gp11
%xdefine msg gp10
%define POLY1305_BLOCK_SIZE 16
%define APPEND(a,b) a %+ b
struc STACKFRAME
_r_save: resq 16 ; Memory to save limbs of powers of R
_rp_save: resq 8 ; Memory to save limbs of powers of R'
_gpr_save: resq 8 ; Memory to save GP registers
_rsp_save: resq 1 ; Memory to save RSP
endstruc
section .text
;; =============================================================================
;; =============================================================================
;; Initializes POLY1305 context structure
;; =============================================================================
%macro POLY1305_INIT 6
%define %%KEY %1 ; [in] pointer to 32-byte key
%define %%A0 %2 ; [out] GPR with accumulator bits 63..0
%define %%A1 %3 ; [out] GPR with accumulator bits 127..64
%define %%A2 %4 ; [out] GPR with accumulator bits 195..128
%define %%R0 %5 ; [out] GPR with R constant bits 63..0
%define %%R1 %6 ; [out] GPR with R constant bits 127..64
;; R = KEY[0..15] & 0xffffffc0ffffffc0ffffffc0fffffff
mov %%R0, 0x0ffffffc0fffffff
and %%R0, [%%KEY + (0 * 8)]
mov %%R1, 0x0ffffffc0ffffffc
and %%R1, [%%KEY + (1 * 8)]
;; set accumulator to 0
xor %%A0, %%A0
xor %%A1, %%A1
xor %%A2, %%A2
%endmacro
;; =============================================================================
;; =============================================================================
;; Computes hash for message length being multiple of block size
;; =============================================================================
%macro POLY1305_MUL_REDUCE 11-12
%define %%A0 %1 ; [in/out] GPR with accumulator bits 63:0
%define %%A1 %2 ; [in/out] GPR with accumulator bits 127:64
%define %%A2 %3 ; [in/out] GPR with accumulator bits 195:128
%define %%R0 %4 ; [in] GPR with R constant bits 63:0
%define %%R1 %5 ; [in] GPR with R constant bits 127:64
%define %%C1 %6 ; [in] C1 = R1 + (R1 >> 2)
%define %%T1 %7 ; [clobbered] GPR register
%define %%T2 %8 ; [clobbered] GPR register
%define %%T3 %9 ; [clobbered] GPR register
%define %%GP_RAX %10 ; [clobbered] RAX register
%define %%GP_RDX %11 ; [clobbered] RDX register
%define %%ONLY128 %12 ; [in] Used if input A2 is 0
;; Combining 64-bit x 64-bit multiplication with reduction steps
;;
;; NOTES:
;; 1) A2 here is only two bits so anything above is subject of reduction.
;; Constant C1 = R1 + (R1 >> 2) simplifies multiply with less operations
;; 2) Magic 5x comes from mod 2^130-5 property and incorporating
;; reduction into multiply phase.
;; See "Cheating at modular arithmetic" and "Poly1305's prime: 2^130 - 5"
;; paragraphs at https://loup-vaillant.fr/tutorials/poly1305-design for more details.
;;
;; Flow of the code below is as follows:
;;
;; A2 A1 A0
;; x R1 R0
;; -----------------------------
;; A2×R0 A1×R0 A0×R0
;; + A0×R1
;; + 5xA2xR1 5xA1xR1
;; -----------------------------
;; [0|L2L] [L1H|L1L] [L0H|L0L]
;;
;; Registers: T3:T2 T1:A0
;;
;; Completing the multiply and adding (with carry) 3x128-bit limbs into
;; 192-bits again (3x64-bits):
;; A0 = L0L
;; A1 = L0H + L1L
;; T3 = L1H + L2L
;; T3:T2 = (A0 * R1)
mov %%GP_RAX, %%R1
mul %%A0
mov %%T2, %%GP_RAX
mov %%GP_RAX, %%R0
mov %%T3, %%GP_RDX
;; T1:A0 = (A0 * R0)
mul %%A0
mov %%A0, %%GP_RAX ;; A0 not used in other operations
mov %%GP_RAX, %%R0
mov %%T1, %%GP_RDX
;; T3:T2 += (A1 * R0)
mul %%A1
add %%T2, %%GP_RAX
mov %%GP_RAX, %%C1
adc %%T3, %%GP_RDX
;; T1:A0 += (A1 * R1x5)
mul %%A1
%if %0 == 11
mov %%A1, %%A2 ;; use A1 for A2
%endif
add %%A0, %%GP_RAX
adc %%T1, %%GP_RDX
;; NOTE: A2 is clamped to 2-bits,
;; R1/R0 is clamped to 60-bits,
;; their product is less than 2^64.
%if %0 == 11
;; T3:T2 += (A2 * R1x5)
imul %%A1, %%C1
add %%T2, %%A1
mov %%A1, %%T1 ;; T1:A0 => A1:A0
adc %%T3, 0
;; T3:A1 += (A2 * R0)
imul %%A2, %%R0
add %%A1, %%T2
adc %%T3, %%A2
;; If A2 == 0, just move and add T1-T2 to A1
%else
mov %%A1, %%T1
add %%A1, %%T2
adc %%T3, 0
%endif
;; At this point, 3 64-bit limbs are in T3:A1:A0
;; T3 can span over more than 2 bits so final partial reduction step is needed.
;;
;; Partial reduction (just to fit into 130 bits)
;; A2 = T3 & 3
;; k = (T3 & ~3) + (T3 >> 2)
;; Y x4 + Y x1
;; A2:A1:A0 += k
;;
;; Result will be in A2:A1:A0
mov %%T1, %%T3
mov DWORD(%%A2), DWORD(%%T3)
and %%T1, ~3
shr %%T3, 2
and DWORD(%%A2), 3
add %%T1, %%T3
;; A2:A1:A0 += k (kept in T1)
add %%A0, %%T1
adc %%A1, 0
adc DWORD(%%A2), 0
%endmacro
;; =============================================================================
;; =============================================================================
;; Computes hash for 8 16-byte message blocks,
;; and adds new message blocks to accumulator.
;;
;; It first multiplies all 8 blocks with powers of R:
;;
;; a2 a1 a0
;; × b2 b1 b0
;; ---------------------------------------
;; a2×b0 a1×b0 a0×b0
;; + a1×b1 a0×b1 5×a2×b1
;; + a0×b2 5×a2×b2 5×a1×b2
;; ---------------------------------------
;; p2 p1 p0
;;
;; Then, it propagates the carry (higher bits after bit 43) from lower limbs into higher limbs,
;; multiplying by 5 in case of the carry of p2.
;;
;; =============================================================================
%macro POLY1305_MUL_REDUCE_VEC 17-24
%define %%A0 %1 ; [in/out] ZMM register containing 1st 44-bit limb of the 8 blocks
%define %%A1 %2 ; [in/out] ZMM register containing 2nd 44-bit limb of the 8 blocks
%define %%A2 %3 ; [in/out] ZMM register containing 3rd 44-bit limb of the 8 blocks
%define %%R0 %4 ; [in] ZMM register (R0) to include the 1st limb in IDX
%define %%R1 %5 ; [in] ZMM register (R1) to include the 2nd limb in IDX
%define %%R2 %6 ; [in] ZMM register (R2) to include the 3rd limb in IDX
%define %%R1P %7 ; [in] ZMM register (R1') to include the 2nd limb (multiplied by 5) in IDX
%define %%R2P %8 ; [in] ZMM register (R2') to include the 3rd limb (multiplied by 5) in IDX
%define %%P0_L %9 ; [clobbered] ZMM register to contain p[0] of the 8 blocks
%define %%P0_H %10 ; [clobbered] ZMM register to contain p[0] of the 8 blocks
%define %%P1_L %11 ; [clobbered] ZMM register to contain p[1] of the 8 blocks
%define %%P1_H %12 ; [clobbered] ZMM register to contain p[1] of the 8 blocks
%define %%P2_L %13 ; [clobbered] ZMM register to contain p[2] of the 8 blocks
%define %%P2_H %14 ; [clobbered] ZMM register to contain p[2] of the 8 blocks
%define %%MASK_42 %15 ; [in] ZMM register containing 42-bit mask
%define %%MASK_44 %16 ; [in] ZMM register containing 44-bit mask
%define %%ZTMP1 %17 ; [clobbered] Temporary ZMM register
%define %%ZTMP2 %18 ; [clobbered] Temporary ZMM register
%define %%ZTMP3 %19 ; [clobbered] Temporary ZMM register
%define %%ZTMP4 %20 ; [clobbered] Temporary ZMM register
%define %%ZTMP5 %21 ; [clobbered] Temporary ZMM register
%define %%ZTMP6 %22 ; [clobbered] Temporary ZMM register
%define %%MSG %23 ; [in/out] Pointer to message
%define %%LEN %24 ; [in/out] Length left of message
;; Reset accumulator
vpxorq %%P0_L, %%P0_L
vpxorq %%P0_H, %%P0_H
vpxorq %%P1_L, %%P1_L
vpxorq %%P1_H, %%P1_H
vpxorq %%P2_L, %%P2_L
vpxorq %%P2_H, %%P2_H
%if %0 == 17
; Reset accumulator and calculate products
vpmadd52luq %%P0_L, %%A2, %%R1P
vpmadd52huq %%P0_H, %%A2, %%R1P
vpmadd52luq %%P1_L, %%A2, %%R2P
vpmadd52huq %%P1_H, %%A2, %%R2P
vpmadd52luq %%P2_L, %%A2, %%R0
vpmadd52huq %%P2_H, %%A2, %%R0
vpmadd52luq %%P1_L, %%A0, %%R1
vpmadd52huq %%P1_H, %%A0, %%R1
vpmadd52luq %%P2_L, %%A0, %%R2
vpmadd52huq %%P2_H, %%A0, %%R2
vpmadd52luq %%P0_L, %%A0, %%R0
vpmadd52huq %%P0_H, %%A0, %%R0
vpmadd52luq %%P0_L, %%A1, %%R2P
vpmadd52huq %%P0_H, %%A1, %%R2P
vpmadd52luq %%P1_L, %%A1, %%R0
vpmadd52huq %%P1_H, %%A1, %%R0
vpmadd52luq %%P2_L, %%A1, %%R1
vpmadd52huq %%P2_H, %%A1, %%R1
; Carry propagation (first pass)
vpsrlq %%ZTMP1, %%P0_L, 44
vpandq %%A0, %%P0_L, %%MASK_44 ; Clear top 20 bits
vpsllq %%P0_H, 8
vpaddq %%P0_H, %%ZTMP1
vpaddq %%P1_L, %%P0_H
vpandq %%A1, %%P1_L, %%MASK_44 ; Clear top 20 bits
vpsrlq %%ZTMP1, %%P1_L, 44
vpsllq %%P1_H, 8
vpaddq %%P1_H, %%ZTMP1
vpaddq %%P2_L, %%P1_H
vpandq %%A2, %%P2_L, %%MASK_42 ; Clear top 22 bits
vpsrlq %%ZTMP1, %%P2_L, 42
vpsllq %%P2_H, 10
vpaddq %%P2_H, %%ZTMP1
; Carry propagation (second pass)
; Multiply by 5 the highest bits (above 130 bits)
vpaddq %%A0, %%P2_H
vpsllq %%P2_H, 2
vpaddq %%A0, %%P2_H
vpsrlq %%ZTMP1, %%A0, 44
vpandq %%A0, %%MASK_44
vpaddq %%A1, %%ZTMP1
%else
;; This code interleaves hash computation with input loading/splatting
; Calculate products
vpmadd52luq %%P0_L, %%A2, %%R1P
vpmadd52huq %%P0_H, %%A2, %%R1P
;; input loading of new blocks
add %%MSG, POLY1305_BLOCK_SIZE*8
sub %%LEN, POLY1305_BLOCK_SIZE*8
vpmadd52luq %%P1_L, %%A2, %%R2P
vpmadd52huq %%P1_H, %%A2, %%R2P
; Load next block of data (128 bytes)
vmovdqu64 %%ZTMP5, [%%MSG]
vmovdqu64 %%ZTMP2, [%%MSG + 64]
vpmadd52luq %%P0_L, %%A0, %%R0
vpmadd52huq %%P0_H, %%A0, %%R0
; Interleave new blocks of data
vpunpckhqdq %%ZTMP3, %%ZTMP5, %%ZTMP2
vpunpcklqdq %%ZTMP5, %%ZTMP5, %%ZTMP2
vpmadd52luq %%P2_L, %%A2, %%R0
vpmadd52huq %%P2_H, %%A2, %%R0
; Highest 42-bit limbs of new blocks
vpsrlq %%ZTMP6, %%ZTMP3, 24
vporq %%ZTMP6, [rel high_bit] ; Add 2^128 to all 8 final qwords of the message
vpmadd52luq %%P1_L, %%A0, %%R1
vpmadd52huq %%P1_H, %%A0, %%R1
; Middle 44-bit limbs of new blocks
vpsrlq %%ZTMP2, %%ZTMP5, 44
vpsllq %%ZTMP4, %%ZTMP3, 20
vpmadd52luq %%P0_L, %%A1, %%R2P
vpmadd52huq %%P0_H, %%A1, %%R2P
vpternlogq %%ZTMP2, %%ZTMP4, %%MASK_44, 0xA8 ; (A OR B AND C)
; Lowest 44-bit limbs of new blocks
vpandq %%ZTMP5, %%MASK_44
vpmadd52luq %%P2_L, %%A0, %%R2
vpmadd52huq %%P2_H, %%A0, %%R2
; Carry propagation (first pass)
vpsrlq %%ZTMP1, %%P0_L, 44
vpsllq %%P0_H, 8
vpmadd52luq %%P1_L, %%A1, %%R0
vpmadd52huq %%P1_H, %%A1, %%R0
; Carry propagation (first pass) - continue
vpandq %%A0, %%P0_L, %%MASK_44 ; Clear top 20 bits
vpaddq %%P0_H, %%ZTMP1
vpmadd52luq %%P2_L, %%A1, %%R1
vpmadd52huq %%P2_H, %%A1, %%R1
; Carry propagation (first pass) - continue
vpaddq %%P1_L, %%P0_H
vpsllq %%P1_H, 8
vpsrlq %%ZTMP1, %%P1_L, 44
vpandq %%A1, %%P1_L, %%MASK_44 ; Clear top 20 bits
vpaddq %%P2_L, %%P1_H ; P2_L += P1_H + P1_L[63:44]
vpaddq %%P2_L, %%ZTMP1
vpandq %%A2, %%P2_L, %%MASK_42 ; Clear top 22 bits
vpaddq %%A2, %%ZTMP6 ; Add highest bits from new blocks to accumulator
vpsrlq %%ZTMP1, %%P2_L, 42
vpsllq %%P2_H, 10
vpaddq %%P2_H, %%ZTMP1
; Carry propagation (second pass)
; Multiply by 5 the highest bits (above 130 bits)
vpaddq %%A0, %%P2_H
vpsllq %%P2_H, 2
vpaddq %%A0, %%P2_H
vpsrlq %%ZTMP1, %%A0, 44
vpandq %%A0, %%MASK_44
vpaddq %%A0, %%ZTMP5 ; Add low 42-bit bits from new blocks to accumulator
vpaddq %%A1, %%ZTMP2 ; Add medium 42-bit bits from new blocks to accumulator
vpaddq %%A1, %%ZTMP1
%endif
%endmacro
;; =============================================================================
;; =============================================================================
;; Shuffle data blocks, so they match the right power of R.
;; Powers of R are in this order: R^8 R^4 R^7 R^3 R^6 R^2 R^5 R
;; Data blocks are coming in this order: A0 A4 A1 A5 A2 A6 A3 A7
;; Generally the computation is: A0*R^8 + A1*R^7 + A2*R^6 + A3*R^5 +
;; A4*R^4 + A5*R^3 + A6*R^2 + A7*R
;; When there are less data blocks, less powers of R are used, so data needs to
;; be shuffled. Example: if 4 blocks are left, only A0-A3 are available and only
;; R-R^4 are used (A0*R^4 + A1*R^3 + A2*R^2 + A3*R), so A0-A3 need to be shifted
;; =============================================================================
%macro SHUFFLE_DATA_BLOCKS 5
%define %%A_L %1 ; [in/out] 0-43 bits of input data
%define %%A_M %2 ; [in/out] 44-87 bits of input data
%define %%A_H %3 ; [in/out] 88-129 bits of input data
%define %%TMP %4 ; [clobbered] Temporary GP register
%define %%N_BLOCKS %5 ; [in] Number of remaining input blocks
%if %%N_BLOCKS == 1
%define %%SHUF_MASK 0x39
%define %%KMASK 0xffff
%elif %%N_BLOCKS == 2
%define %%SHUF_MASK 0x4E
%define %%KMASK 0xffff
%elif %%N_BLOCKS == 3
%define %%SHUF_MASK 0x93
%define %%KMASK 0xffff
%elif %%N_BLOCKS == 4
%define %%KMASK 0xffff
%elif %%N_BLOCKS == 5
%define %%SHUF_MASK 0x39
%define %%KMASK 0xfff0
%elif %%N_BLOCKS == 6
%define %%SHUF_MASK 0x4E
%define %%KMASK 0xff00
%elif %%N_BLOCKS == 7
%define %%SHUF_MASK 0x93
%define %%KMASK 0xf000
%endif
mov %%TMP, %%KMASK
kmovq k1, %%TMP
vpshufd %%A_L{k1}, %%A_L, 0x4E
vpshufd %%A_M{k1}, %%A_M, 0x4E
vpshufd %%A_H{k1}, %%A_H, 0x4E
%if %%N_BLOCKS != 4
vshufi64x2 %%A_L, %%A_L, %%SHUF_MASK
vshufi64x2 %%A_M, %%A_M, %%SHUF_MASK
vshufi64x2 %%A_H, %%A_H, %%SHUF_MASK
%endif
%endmacro
;; =============================================================================
;; =============================================================================
;; Computes hash for message length being multiple of block size
;; =============================================================================
%macro POLY1305_BLOCKS 14
%define %%MSG %1 ; [in/out] GPR pointer to input message (updated)
%define %%LEN %2 ; [in/out] GPR in: length in bytes / out: length mod 16
%define %%A0 %3 ; [in/out] accumulator bits 63..0
%define %%A1 %4 ; [in/out] accumulator bits 127..64
%define %%A2 %5 ; [in/out] accumulator bits 195..128
%define %%R0 %6 ; [in] R constant bits 63..0
%define %%R1 %7 ; [in] R constant bits 127..64
%define %%T0 %8 ; [clobbered] GPR register
%define %%T1 %9 ; [clobbered] GPR register
%define %%T2 %10 ; [clobbered] GPR register
%define %%T3 %11 ; [clobbered] GPR register
%define %%GP_RAX %12 ; [clobbered] RAX register
%define %%GP_RDX %13 ; [clobbered] RDX register
%define %%PAD_16 %14 ; [in] text "pad_to_16" or "no_padding"
%define %%MASK_42 zmm30
%define %%MASK_44 zmm31
; Minimum of 256 bytes to run vectorized code
cmp %%LEN, POLY1305_BLOCK_SIZE*16
jb %%_final_loop
vmovdqa64 %%MASK_42, [rel mask_42]
vmovdqa64 %%MASK_44, [rel mask_44]
; Spread accumulator into 44-bit limbs in quadwords
mov %%T0, %%A0
and %%T0, [rel mask_44] ;; First limb (A[43:0])
vmovq xmm5, %%T0
mov %%T0, %%A1
shrd %%A0, %%T0, 44
and %%A0, [rel mask_44] ;; Second limb (A[77:52])
vmovq xmm6, %%A0
shrd %%A1, %%A2, 24
and %%A1, [rel mask_42] ;; Third limb (A[129:88])
vmovq xmm7, %%A1
; Load first block of data (128 bytes)
vmovdqu64 zmm0, [%%MSG]
vmovdqu64 zmm1, [%%MSG + 64]
; Interleave the data to form 44-bit limbs
;
; zmm13 to have bits 0-43 of all 8 blocks in 8 qwords
; zmm14 to have bits 87-44 of all 8 blocks in 8 qwords
; zmm15 to have bits 127-88 of all 8 blocks in 8 qwords
vpunpckhqdq zmm15, zmm0, zmm1
vpunpcklqdq zmm13, zmm0, zmm1
vpsrlq zmm14, zmm13, 44
vpsllq zmm18, zmm15, 20
vpternlogq zmm14, zmm18, %%MASK_44, 0xA8 ; (A OR B AND C)
vpandq zmm13, %%MASK_44
vpsrlq zmm15, 24
; Add 2^128 to all 8 final qwords of the message
vporq zmm15, [rel high_bit]
vpaddq zmm13, zmm5
vpaddq zmm14, zmm6
vpaddq zmm15, zmm7
; Use memory in stack to save powers of R, before loading them into ZMM registers
; The first 16*8 bytes will contain the 16 bytes of the 8 powers of R
; The last 64 bytes will contain the last 2 bits of powers of R, spread in 8 qwords,
; to be OR'd with the highest qwords (in zmm26)
mov [rsp + _r_save + 16*7], %%R0
mov [rsp + _r_save + 16*7 + 8], %%R1
xor %%T0, %%T0
mov [rsp + _rp_save + 8*7], %%T0
; Calculate R^2
mov %%T0, %%R1
shr %%T0, 2
add %%T0, %%R1 ;; T0 = R1 + (R1 >> 2)
mov %%A0, %%R0
mov %%A1, %%R1
POLY1305_MUL_REDUCE %%A0, %%A1, %%A2, %%R0, %%R1, %%T0, %%T1, %%T2, %%T3, %%GP_RAX, %%GP_RDX, no_A2
mov [rsp + _r_save + 16*6], %%A0
mov [rsp + _r_save + 16*6 + 8], %%A1
mov %%T3, %%A2
shl %%T3, 40
mov [rsp + _rp_save + 8*5], %%T3
; Calculate R^3
POLY1305_MUL_REDUCE %%A0, %%A1, %%A2, %%R0, %%R1, %%T0, %%T1, %%T2, %%T3, %%GP_RAX, %%GP_RDX
mov [rsp + _r_save + 16*5], %%A0
mov [rsp + _r_save + 16*5 + 8], %%A1
mov %%T3, %%A2
shl %%T3, 40
mov [rsp + _rp_save + 8*3], %%T3
; Calculate R^4
POLY1305_MUL_REDUCE %%A0, %%A1, %%A2, %%R0, %%R1, %%T0, %%T1, %%T2, %%T3, %%GP_RAX, %%GP_RDX
mov [rsp + _r_save + 16*4], %%A0
mov [rsp + _r_save + 16*4 + 8], %%A1
mov %%T3, %%A2
shl %%T3, 40
mov [rsp + _rp_save + 8], %%T3
; Calculate R^5
POLY1305_MUL_REDUCE %%A0, %%A1, %%A2, %%R0, %%R1, %%T0, %%T1, %%T2, %%T3, %%GP_RAX, %%GP_RDX
mov [rsp + _r_save + 16*3], %%A0
mov [rsp + _r_save + 16*3 + 8], %%A1
mov %%T3, %%A2
shl %%T3, 40
mov [rsp + _rp_save + 8*6], %%T3
; Calculate R^6
POLY1305_MUL_REDUCE %%A0, %%A1, %%A2, %%R0, %%R1, %%T0, %%T1, %%T2, %%T3, %%GP_RAX, %%GP_RDX
mov [rsp + _r_save + 16*2], %%A0
mov [rsp + _r_save + 16*2 + 8], %%A1
mov %%T3, %%A2
shl %%T3, 40
mov [rsp + _rp_save + 8*4], %%T3
; Calculate R^7
POLY1305_MUL_REDUCE %%A0, %%A1, %%A2, %%R0, %%R1, %%T0, %%T1, %%T2, %%T3, %%GP_RAX, %%GP_RDX
mov [rsp + _r_save + 16], %%A0
mov [rsp + _r_save + 16 + 8], %%A1
mov %%T3, %%A2
shl %%T3, 40
mov [rsp + _rp_save + 8*2], %%T3
; Calculate R^8
POLY1305_MUL_REDUCE %%A0, %%A1, %%A2, %%R0, %%R1, %%T0, %%T1, %%T2, %%T3, %%GP_RAX, %%GP_RDX
mov [rsp + _r_save], %%A0
mov [rsp + _r_save + 8], %%A1
mov %%T3, %%A2
shl %%T3, 40
mov [rsp + _rp_save], %%T3
; Broadcast 44-bit limbs of R^8
mov %%T0, %%A0
and %%T0, [rel mask_44] ;; First limb (R^8[43:0])
vpbroadcastq zmm22, %%T0
mov %%T0, %%A1
shrd %%A0, %%T0, 44
and %%A0, [rel mask_44] ;; Second limb (R^8[87:44])
vpbroadcastq zmm23, %%A0
shrd %%A1, %%A2, 24
and %%A1, [rel mask_42] ;; Third limb (R^8[129:88])
vpbroadcastq zmm24, %%A1
; Generate 4*5*R^8
vpsllq zmm25, zmm23, 2
vpsllq zmm26, zmm24, 2
; 5*R^8
vpaddq zmm25, zmm23
vpaddq zmm26, zmm24
; 4*5*R^8
vpsllq zmm25, 2
vpsllq zmm26, 2
mov %%T0, %%LEN
and %%T0, 0xffffffffffffff80 ; multiple of 128 bytes
%%_poly1305_blocks_loop:
cmp %%T0, POLY1305_BLOCK_SIZE*8
jbe %%_poly1305_blocks_loop_end
; zmm13-zmm15 contain the 8 blocks of message plus the previous accumulator
; zmm22-24 contain the 5x44-bit limbs of the powers of R
; zmm25-26 contain the 5x44-bit limbs of the powers of R' (5*4*R)
POLY1305_MUL_REDUCE_VEC zmm13, zmm14, zmm15, \
zmm22, zmm23, zmm24, \
zmm25, zmm26, \
zmm5, zmm6, zmm7, zmm8, zmm9, zmm10, \
%%MASK_42, %%MASK_44, zmm11, zmm0, zmm1, \
zmm2, zmm3, zmm4, %%MSG, %%T0
jmp %%_poly1305_blocks_loop
%%_poly1305_blocks_loop_end:
;; Need to multiply by r^8,r^7... r
; Interleave the powers of R to form 44-bit limbs
;
; zmm22 to have bits 0-43 of all 8 powers of R in 8 qwords
; zmm23 to have bits 87-44 of all 8 powers of R in 8 qwords
; zmm24 to have bits 129-88 of all 8 powers of R in 8 qwords
vmovdqa64 zmm0, [rsp + _r_save]
vmovdqa64 zmm1, [rsp + _r_save + 64]
vpunpckhqdq zmm24, zmm0, zmm1
vpunpcklqdq zmm22, zmm0, zmm1
vpsrlq zmm23, zmm22, 44
vpsllq zmm25, zmm24, 20
vpternlogq zmm23, zmm25, %%MASK_44, 0xA8 ; (A OR B AND C)
vpandq zmm22, %%MASK_44
vpsrlq zmm24, 24
; rsp + _rp_save contains the 2 highest bits of the powers of R
vporq zmm24, [rsp + _rp_save] ; R4
; zmm25 to have bits 87-44 of all 8 powers of R' in 8 qwords
; zmm26 to have bits 129-88 of all 8 powers of R' in 8 qwords
vpsllq zmm0, zmm23, 2
vpaddq zmm25, zmm23, zmm0 ; R1' (R1*5)
vpsllq zmm1, zmm24, 2
vpaddq zmm26, zmm24, zmm1 ; R2' (R2*5)
; 4*5*R^8
vpsllq zmm25, 2
vpsllq zmm26, 2
; zmm13-zmm15 contain the 8 blocks of message plus the previous accumulator
; zmm22-24 contain the 3x44-bit limbs of the powers of R
; zmm25-26 contain the 3x44-bit limbs of the powers of R' (5*4*R)
POLY1305_MUL_REDUCE_VEC zmm13, zmm14, zmm15, \
zmm22, zmm23, zmm24, \
zmm25, zmm26, \
zmm5, zmm6, zmm7, zmm8, zmm9, zmm10, \
%%MASK_42, %%MASK_44, zmm11
;; Add all blocks (horizontally)
vextracti64x4 ymm0, zmm13, 1
vextracti64x4 ymm1, zmm14, 1
vextracti64x4 ymm2, zmm15, 1
vpaddq ymm13, ymm0
vpaddq ymm14, ymm1
vpaddq ymm15, ymm2
vextracti32x4 xmm10, ymm13, 1
vextracti32x4 xmm11, ymm14, 1
vextracti32x4 xmm12, ymm15, 1
vpaddq xmm13, xmm10
vpaddq xmm14, xmm11
vpaddq xmm15, xmm12
vpsrldq xmm10, xmm13, 8
vpsrldq xmm11, xmm14, 8
vpsrldq xmm12, xmm15, 8
; Finish folding and clear second qword
mov %%T0, 0xfd
kmovq k1, %%T0
vpaddq xmm13{k1}{z}, xmm10
vpaddq xmm14{k1}{z}, xmm11
vpaddq xmm15{k1}{z}, xmm12
add %%MSG, POLY1305_BLOCK_SIZE*8
and %%LEN, (POLY1305_BLOCK_SIZE*8 - 1) ; Get remaining lengths (LEN < 128 bytes)
cmp %%LEN, 32 ; If remaining bytes is <= 32, perform last blocks in scalar
jbe %%_simd_to_gp
mov %%T0, %%LEN
and %%T0, 0x3f
lea %%T1, [rel byte64_len_to_mask_table]
mov %%T1, [%%T1 + 8*%%T0]
; Load default byte masks
mov %%T2, 0xffffffffffffffff
xor %%T3, %%T3
cmp %%LEN, 64
cmovb %%T2, %%T1 ; Load mask for first 64 bytes
cmovg %%T3, %%T1 ; Load mask for second 64 bytes
kmovq k1, %%T2
kmovq k2, %%T3
vmovdqu8 zmm0{k1}{z}, [%%MSG]
vmovdqu8 zmm1{k2}{z}, [%%MSG + 64]
; Pad last block message, if partial
%ifnidn %%PAD_16,pad_to_16
lea %%T1, [rel pad64_bit]
shl %%T0, 6
cmp %%LEN, 64
ja %%_pad_second_64b
vporq zmm0, [%%T1 + %%T0]
jmp %%_end_pad
%%_pad_second_64b:
vporq zmm1, [%%T1 + %%T0]
%%_end_pad:
%endif
mov %%T0, %%LEN
and %%T0, 0x70 ; Multiple of 16 bytes
; Load last block of data (up to 112 bytes)
shr %%T0, 3 ; Get number of full qwords
; Interleave the data to form 44-bit limbs
;
; zmm13 to have bits 0-43 of all 8 blocks in 8 qwords
; zmm14 to have bits 87-44 of all 8 blocks in 8 qwords
; zmm15 to have bits 127-88 of all 8 blocks in 8 qwords
vpunpckhqdq zmm4, zmm0, zmm1
vpunpcklqdq zmm2, zmm0, zmm1
vpsrlq zmm3, zmm2, 44
vpsllq zmm28, zmm4, 20
vpternlogq zmm3, zmm28, %%MASK_44, 0xA8 ; (A OR B AND C)
vpandq zmm2, %%MASK_44
vpsrlq zmm4, 24
lea %%T1, [rel qword_high_bit_mask]
%ifnidn %%PAD_16,pad_to_16
kmovb k1, [%%T1 + %%T0]
%else
mov %%T3, %%LEN
mov %%T2, %%T0
add %%T2, 2
and %%T3, 0xf
cmovnz %%T0, %%T2
kmovb k1, [%%T1 + %%T0]
%endif
; Add 2^128 to final qwords of the message (all full blocks and partial block,
; if "pad_to_16" is selected)
vporq zmm4{k1}, [rel high_bit]
vpaddq zmm13, zmm2
vpaddq zmm14, zmm3
vpaddq zmm15, zmm4
mov %%T0, %%LEN
add %%T0, 15
shr %%T0, 4 ; Get number of 16-byte blocks (including partial blocks)
xor %%LEN, %%LEN ; All length will be consumed
; No need to shuffle data blocks (data is in the right order)
cmp %%T0, 8
je %%_end_shuffle
cmp %%T0, 4
je %%_shuffle_blocks_4
jb %%_shuffle_blocks_3
; Number of 16-byte blocks > 4
cmp %%T0, 6
je %%_shuffle_blocks_6
ja %%_shuffle_blocks_7
jmp %%_shuffle_blocks_5
%assign i 3
%rep 5
APPEND(%%_shuffle_blocks_, i):
SHUFFLE_DATA_BLOCKS zmm13, zmm14, zmm15, %%T1, i
jmp %%_end_shuffle
%assign i (i + 1)
%endrep
%%_end_shuffle:
; zmm13-zmm15 contain the 8 blocks of message plus the previous accumulator
; zmm22-24 contain the 3x44-bit limbs of the powers of R
; zmm25-26 contain the 3x44-bit limbs of the powers of R' (5*4*R)
POLY1305_MUL_REDUCE_VEC zmm13, zmm14, zmm15, \
zmm22, zmm23, zmm24, \
zmm25, zmm26, \
zmm5, zmm6, zmm7, zmm8, zmm9, zmm10, \
%%MASK_42, %%MASK_44, zmm11
;; Add all blocks (horizontally)
vextracti64x4 ymm0, zmm13, 1
vextracti64x4 ymm1, zmm14, 1
vextracti64x4 ymm2, zmm15, 1
vpaddq ymm13, ymm0
vpaddq ymm14, ymm1
vpaddq ymm15, ymm2
vextracti32x4 xmm10, ymm13, 1
vextracti32x4 xmm11, ymm14, 1
vextracti32x4 xmm12, ymm15, 1
vpaddq xmm13, xmm10
vpaddq xmm14, xmm11
vpaddq xmm15, xmm12
vpsrldq xmm10, xmm13, 8
vpsrldq xmm11, xmm14, 8
vpsrldq xmm12, xmm15, 8
vpaddq xmm13, xmm10
vpaddq xmm14, xmm11
vpaddq xmm15, xmm12
%%_simd_to_gp:
; Carry propagation
vpsrlq xmm0, xmm13, 44
vpandq xmm13, XWORD(%%MASK_44) ; Clear top 20 bits
vpaddq xmm14, xmm0
vpsrlq xmm0, xmm14, 44
vpandq xmm14, XWORD(%%MASK_44) ; Clear top 20 bits
vpaddq xmm15, xmm0
vpsrlq xmm0, xmm15, 42
vpandq xmm15, XWORD(%%MASK_42) ; Clear top 22 bits
vpsllq xmm1, xmm0, 2
vpaddq xmm0, xmm1
vpaddq xmm13, xmm0
; Put together A
vmovq %%A0, xmm13
vmovq %%T0, xmm14
mov %%T1, %%T0
shl %%T1, 44
or %%A0, %%T1
shr %%T0, 20
vmovq %%A2, xmm15
mov %%A1, %%A2
shl %%A1, 24
or %%A1, %%T0
shr %%A2, 40
; Clear powers of R
%ifdef SAFE_DATA
vpxorq zmm0, zmm0
vmovdqa64 [rsp + _r_save], zmm0
vmovdqa64 [rsp + _r_save + 64], zmm0
vmovdqa64 [rsp + _rp_save], zmm0
%endif
vzeroupper
%%_final_loop:
cmp %%LEN, POLY1305_BLOCK_SIZE
jb %%_poly1305_blocks_partial
;; A += MSG[i]
add %%A0, [%%MSG + 0]
adc %%A1, [%%MSG + 8]
adc %%A2, 1 ;; no padding bit
mov %%T0, %%R1
shr %%T0, 2
add %%T0, %%R1 ;; T0 = R1 + (R1 >> 2)
POLY1305_MUL_REDUCE %%A0, %%A1, %%A2, %%R0, %%R1, \
%%T0, %%T1, %%T2, %%T3, %%GP_RAX, %%GP_RDX
add %%MSG, POLY1305_BLOCK_SIZE
sub %%LEN, POLY1305_BLOCK_SIZE
jmp %%_final_loop
%%_poly1305_blocks_partial:
or %%LEN, %%LEN
jz %%_poly1305_blocks_exit
lea %%T1, [rel byte_len_to_mask_table]
kmovw k1, [%%T1 + %%LEN*2]
vmovdqu8 xmm0{k1}{z}, [%%MSG]
%ifnidn %%PAD_16,pad_to_16
;; pad the message
lea %%T2, [rel pad16_bit]
shl %%LEN, 4
vporq xmm0, [%%T2 + %%LEN]
%endif
vmovq %%T0, xmm0
vpextrq %%T1, xmm0, 1
;; A += MSG[i]
add %%A0, %%T0
adc %%A1, %%T1
%ifnidn %%PAD_16,pad_to_16
adc %%A2, 0 ;; no padding bit
%else
adc %%A2, 1 ;; padding bit please
%endif
mov %%T0, %%R1
shr %%T0, 2
add %%T0, %%R1 ;; T0 = R1 + (R1 >> 2)
POLY1305_MUL_REDUCE %%A0, %%A1, %%A2, %%R0, %%R1, \
%%T0, %%T1, %%T2, %%T3, %%GP_RAX, %%GP_RDX
%%_poly1305_blocks_exit:
%endmacro
;; =============================================================================
;; =============================================================================
;; Finalizes Poly1305 hash calculation on a message
;; =============================================================================
%macro POLY1305_FINALIZE 8
%define %%KEY %1 ; [in] pointer to 32 byte key
%define %%MAC %2 ; [in/out] pointer to store MAC value into (16 bytes)
%define %%A0 %3 ; [in/out] accumulator bits 63..0
%define %%A1 %4 ; [in/out] accumulator bits 127..64
%define %%A2 %5 ; [in/out] accumulator bits 195..128
%define %%T0 %6 ; [clobbered] GPR register
%define %%T1 %7 ; [clobbered] GPR register
%define %%T2 %8 ; [clobbered] GPR register
;; T = A - P, where P = 2^130 - 5
;; P[63..0] = 0xFFFFFFFFFFFFFFFB
;; P[127..64] = 0xFFFFFFFFFFFFFFFF
;; P[195..128] = 0x0000000000000003
mov %%T0, %%A0
mov %%T1, %%A1
mov %%T2, %%A2
sub %%T0, -5 ;; 0xFFFFFFFFFFFFFFFB
sbb %%T1, -1 ;; 0xFFFFFFFFFFFFFFFF
sbb %%T2, 0x3
;; if A > (2^130 - 5) then A = T
;; - here, if borrow/CF == false then A = T
cmovnc %%A0, %%T0
cmovnc %%A1, %%T1
;; MAC = (A + S) mod 2^128 (S = key[16..31])
add %%A0, [%%KEY + (2 * 8)]
adc %%A1, [%%KEY + (3 * 8)]
;; store MAC
mov [%%MAC + (0 * 8)], %%A0
mov [%%MAC + (1 * 8)], %%A1
%endmacro
;; =============================================================================
;; =============================================================================
;; Creates stack frame and saves registers
;; =============================================================================
%macro FUNC_ENTRY 0
mov rax, rsp
sub rsp, STACKFRAME_size
and rsp, -64
mov [rsp + _gpr_save + 8*0], rbx
mov [rsp + _gpr_save + 8*1], rbp
mov [rsp + _gpr_save + 8*2], r12
mov [rsp + _gpr_save + 8*3], r13
mov [rsp + _gpr_save + 8*4], r14
mov [rsp + _gpr_save + 8*5], r15
%ifndef LINUX
mov [rsp + _gpr_save + 8*6], rsi
mov [rsp + _gpr_save + 8*7], rdi
%endif
mov [rsp + _rsp_save], rax
%endmacro ; FUNC_ENTRY
;; =============================================================================
;; =============================================================================
;; Restores registers and removes the stack frame
;; =============================================================================
%macro FUNC_EXIT 0
mov rbx, [rsp + _gpr_save + 8*0]
mov rbp, [rsp + _gpr_save + 8*1]
mov r12, [rsp + _gpr_save + 8*2]
mov r13, [rsp + _gpr_save + 8*3]
mov r14, [rsp + _gpr_save + 8*4]
mov r15, [rsp + _gpr_save + 8*5]
%ifndef LINUX
mov rsi, [rsp + _gpr_save + 8*6]
mov rdi, [rsp + _gpr_save + 8*7]
%endif
mov rsp, [rsp + _rsp_save]
%ifdef SAFE_DATA
clear_scratch_gps_asm
%endif ;; SAFE_DATA
%endmacro
;; =============================================================================
;; =============================================================================
;; void poly1305_aead_update_fma_avx512(const void *msg, const uint64_t msg_len,
;; void *hash, const void *key)
;; arg1 - Input message
;; arg2 - Message length
;; arg3 - Input/output hash
;; arg4 - Poly1305 key
align 32
MKGLOBAL(poly1305_aead_update_fma_avx512,function,internal)
poly1305_aead_update_fma_avx512:
%ifdef SAFE_PARAM
or arg1, arg1
jz .poly1305_update_exit
or arg3, arg3
jz .poly1305_update_exit
or arg4, arg4
jz .poly1305_update_exit
%endif
FUNC_ENTRY
%ifdef LINUX
%xdefine _a0 gp3
%xdefine _a1 gp4
%xdefine _a2 gp5
%xdefine _r0 gp6
%xdefine _r1 gp7
%xdefine _len arg2
%xdefine _arg3 arg4 ; use rcx, arg3 = rdx
%else
%xdefine _a0 gp3
%xdefine _a1 rdi
%xdefine _a2 gp5 ; = arg4 / r9
%xdefine _r0 gp6
%xdefine _r1 gp7
%xdefine _len gp2 ; rsi
%xdefine _arg3 arg3 ; arg
%endif
;; load R
mov _r0, [arg4 + 0 * 8]
mov _r1, [arg4 + 1 * 8]
;; load accumulator / current hash value
;; note: arg4 can't be used beyond this point
%ifdef LINUX
mov _arg3, arg3 ; note: _arg3 = arg4 (linux)
%endif
mov _a0, [_arg3 + 0 * 8]
mov _a1, [_arg3 + 1 * 8]
mov _a2, [_arg3 + 2 * 8] ; note: _a2 = arg4 (win)
%ifndef LINUX
mov _len, arg2 ;; arg2 = rdx on Windows
%endif
POLY1305_BLOCKS arg1, _len, _a0, _a1, _a2, _r0, _r1, \
gp10, gp11, gp8, gp9, rax, rdx, pad_to_16
;; save accumulator back
mov [_arg3 + 0 * 8], _a0
mov [_arg3 + 1 * 8], _a1
mov [_arg3 + 2 * 8], _a2
FUNC_EXIT
.poly1305_update_exit:
ret
;; =============================================================================
;; =============================================================================
;; void poly1305_aead_complete_fma_avx512(const void *hash, const void *key,
;; void *tag)
;; arg1 - Input hash
;; arg2 - Poly1305 key
;; arg3 - Output tag
align 32
MKGLOBAL(poly1305_aead_complete_fma_avx512,function,internal)
poly1305_aead_complete_fma_avx512:
%ifdef SAFE_PARAM
or arg1, arg1
jz .poly1305_complete_exit
or arg2, arg2
jz .poly1305_complete_exit
or arg3, arg3
jz .poly1305_complete_exit
%endif
FUNC_ENTRY
%xdefine _a0 gp6
%xdefine _a1 gp7
%xdefine _a2 gp8
;; load accumulator / current hash value
mov _a0, [arg1 + 0 * 8]
mov _a1, [arg1 + 1 * 8]
mov _a2, [arg1 + 2 * 8]
POLY1305_FINALIZE arg2, arg3, _a0, _a1, _a2, gp9, gp10, gp11
;; clear Poly key
%ifdef SAFE_DATA
vpxorq ymm0, ymm0
vmovdqu64 [arg2], ymm0
%endif
FUNC_EXIT
.poly1305_complete_exit:
ret
;; =============================================================================
;; =============================================================================
;; void poly1305_mac_fma_avx512(IMB_JOB *job)
;; arg1 - job structure
align 32
MKGLOBAL(poly1305_mac_fma_avx512,function,internal)
poly1305_mac_fma_avx512:
endbranch64
FUNC_ENTRY
%ifndef LINUX
mov job, arg1
%endif
%ifdef SAFE_PARAM
or job, job
jz .poly1305_mac_exit
%endif
%xdefine _a0 gp1
%xdefine _a1 gp2
%xdefine _a2 gp3
%xdefine _r0 gp4
%xdefine _r1 gp5
mov gp6, [job + _poly1305_key]
POLY1305_INIT gp6, _a0, _a1, _a2, _r0, _r1
mov msg, [job + _src]
add msg, [job + _hash_start_src_offset_in_bytes]
mov len, [job + _msg_len_to_hash]
POLY1305_BLOCKS msg, len, _a0, _a1, _a2, _r0, _r1, \
gp6, gp7, gp8, gp9, rax, rdx, no_padding
mov rax, [job + _poly1305_key]
mov rdx, [job + _auth_tag_output]
POLY1305_FINALIZE rax, rdx, _a0, _a1, _a2, gp6, gp7, gp8
.poly1305_mac_exit:
FUNC_EXIT
ret
%ifdef LINUX
section .note.GNU-stack noalloc noexec nowrite progbits
%endif
|
/*
Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the License.
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, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <my_global.h>
#include "Suma.hpp"
#include <ndb_version.h>
#include <NdbTCP.h>
#include <Bitmask.hpp>
#include <SimpleProperties.hpp>
#include <signaldata/NodeFailRep.hpp>
#include <signaldata/ReadNodesConf.hpp>
#include <signaldata/ListTables.hpp>
#include <signaldata/GetTabInfo.hpp>
#include <signaldata/GetTableId.hpp>
#include <signaldata/DictTabInfo.hpp>
#include <signaldata/SumaImpl.hpp>
#include <signaldata/ScanFrag.hpp>
#include <signaldata/TransIdAI.hpp>
#include <signaldata/CreateTrigImpl.hpp>
#include <signaldata/DropTrigImpl.hpp>
#include <signaldata/FireTrigOrd.hpp>
#include <signaldata/TrigAttrInfo.hpp>
#include <signaldata/CheckNodeGroups.hpp>
#include <signaldata/CreateTab.hpp>
#include <signaldata/DropTab.hpp>
#include <signaldata/AlterTable.hpp>
#include <signaldata/AlterTab.hpp>
#include <signaldata/DihScanTab.hpp>
#include <signaldata/SystemError.hpp>
#include <signaldata/GCP.hpp>
#include <signaldata/StopMe.hpp>
#include <signaldata/DictLock.hpp>
#include <ndbapi/NdbDictionary.hpp>
#include <DebuggerNames.hpp>
#include "../dbtup/Dbtup.hpp"
#include "../dbdih/Dbdih.hpp"
#include <signaldata/CreateNodegroup.hpp>
#include <signaldata/CreateNodegroupImpl.hpp>
#include <signaldata/DropNodegroup.hpp>
#include <signaldata/DropNodegroupImpl.hpp>
#include <signaldata/DbinfoScan.hpp>
#include <signaldata/TransIdAI.hpp>
#include <EventLogger.hpp>
extern EventLogger * g_eventLogger;
//#define HANDOVER_DEBUG
//#define NODEFAIL_DEBUG
//#define NODEFAIL_DEBUG2
//#define DEBUG_SUMA_SEQUENCE
//#define EVENT_DEBUG
//#define EVENT_PH3_DEBUG
//#define EVENT_DEBUG2
#if 1
#undef DBUG_ENTER
#undef DBUG_PRINT
#undef DBUG_RETURN
#undef DBUG_VOID_RETURN
#if 0
#define DBUG_ENTER(a) {ndbout_c("%s:%d >%s", __FILE__, __LINE__, a);}
#define DBUG_PRINT(a,b) {ndbout << __FILE__ << ":" << __LINE__ << " " << a << ": "; ndbout_c b ;}
#define DBUG_RETURN(a) { ndbout_c("%s:%d <", __FILE__, __LINE__); return(a); }
#define DBUG_VOID_RETURN { ndbout_c("%s:%d <", __FILE__, __LINE__); return; }
#else
#define DBUG_ENTER(a)
#define DBUG_PRINT(a,b)
#define DBUG_RETURN(a) return a
#define DBUG_VOID_RETURN return
#endif
#endif
#define DBG_3R 0
/**
* @todo:
* SUMA crashes if an index is created at the same time as
* global replication. Very easy to reproduce using testIndex.
* Note: This only happens occasionally, but is quite easy to reprod.
*/
Uint32 g_subPtrI = RNIL;
static const Uint32 SUMA_SEQUENCE = 0xBABEBABE;
static const Uint32 MAX_CONCURRENT_GCP = 2;
/**************************************************************
*
* Start of suma
*
*/
#define PRINT_ONLY 0
void
Suma::execREAD_CONFIG_REQ(Signal* signal)
{
jamEntry();
const ReadConfigReq * req = (ReadConfigReq*)signal->getDataPtr();
Uint32 ref = req->senderRef;
Uint32 senderData = req->senderData;
const ndb_mgm_configuration_iterator * p =
m_ctx.m_config.getOwnConfigIterator();
ndbrequire(p != 0);
// SumaParticipant
Uint32 noTables, noAttrs, maxBufferedEpochs;
ndb_mgm_get_int_parameter(p, CFG_DICT_TABLE,
&noTables);
ndb_mgm_get_int_parameter(p, CFG_DICT_ATTRIBUTE,
&noAttrs);
ndb_mgm_get_int_parameter(p, CFG_DB_MAX_BUFFERED_EPOCHS,
&maxBufferedEpochs);
c_tablePool.setSize(noTables);
c_tables.setSize(noTables);
c_subscriptions.setSize(noTables);
Uint32 cnt = 0;
cnt = 0;
ndb_mgm_get_int_parameter(p, CFG_DB_SUBSCRIPTIONS, &cnt);
if (cnt == 0)
{
jam();
cnt = noTables;
}
c_subscriptionPool.setSize(cnt);
cnt *= 2;
{
Uint32 val = 0;
ndb_mgm_get_int_parameter(p, CFG_DB_SUBSCRIBERS, &val);
if (val)
{
jam();
cnt = val;
}
}
c_subscriberPool.setSize(cnt);
cnt = 0;
ndb_mgm_get_int_parameter(p, CFG_DB_SUB_OPERATIONS, &cnt);
if (cnt)
c_subOpPool.setSize(cnt);
else
c_subOpPool.setSize(256);
c_syncPool.setSize(2);
// Trix: max 5 concurrent index stats ops with max 9 words bounds
Uint32 noOfBoundWords = 5 * 9;
// XXX multiplies number of words by 15 ???
c_dataBufferPool.setSize(noAttrs + noOfBoundWords);
c_maxBufferedEpochs = maxBufferedEpochs;
// Calculate needed gcp pool as 10 records + the ones needed
// during a possible api timeout
Uint32 dbApiHbInterval, gcpInterval, microGcpInterval = 0;
ndb_mgm_get_int_parameter(p, CFG_DB_API_HEARTBEAT_INTERVAL,
&dbApiHbInterval);
ndb_mgm_get_int_parameter(p, CFG_DB_GCP_INTERVAL,
&gcpInterval);
ndb_mgm_get_int_parameter(p, CFG_DB_MICRO_GCP_INTERVAL,
µGcpInterval);
if (microGcpInterval)
{
gcpInterval = microGcpInterval;
}
c_gcp_pool.setSize(10 + (4*dbApiHbInterval+gcpInterval-1)/gcpInterval);
c_page_chunk_pool.setSize(50);
{
SLList<SyncRecord> tmp(c_syncPool);
Ptr<SyncRecord> ptr;
while(tmp.seize(ptr))
new (ptr.p) SyncRecord(* this, c_dataBufferPool);
tmp.release();
}
// Suma
c_masterNodeId = getOwnNodeId();
c_nodeGroup = c_noNodesInGroup = 0;
for (int i = 0; i < MAX_REPLICAS; i++) {
c_nodesInGroup[i] = 0;
}
m_first_free_page= RNIL;
c_no_of_buckets = 0;
memset(c_buckets, 0, sizeof(c_buckets));
for(Uint32 i = 0; i<NO_OF_BUCKETS; i++)
{
Bucket* bucket= c_buckets+i;
bucket->m_buffer_tail = RNIL;
bucket->m_buffer_head.m_page_id = RNIL;
bucket->m_buffer_head.m_page_pos = Buffer_page::DATA_WORDS;
}
m_max_seen_gci = 0; // FIRE_TRIG_ORD
m_max_sent_gci = 0; // FIRE_TRIG_ORD -> send
m_last_complete_gci = 0; // SUB_GCP_COMPLETE_REP
m_gcp_complete_rep_count = 0;
m_out_of_buffer_gci = 0;
m_missing_data = false;
c_startup.m_wait_handover= false;
c_failedApiNodes.clear();
ReadConfigConf * conf = (ReadConfigConf*)signal->getDataPtrSend();
conf->senderRef = reference();
conf->senderData = senderData;
sendSignal(ref, GSN_READ_CONFIG_CONF, signal,
ReadConfigConf::SignalLength, JBB);
}
void
Suma::execSTTOR(Signal* signal) {
jamEntry();
DBUG_ENTER("Suma::execSTTOR");
m_startphase = signal->theData[1];
m_typeOfStart = signal->theData[7];
DBUG_PRINT("info",("startphase = %u, typeOfStart = %u",
m_startphase, m_typeOfStart));
if(m_startphase == 3)
{
jam();
void* ptr = m_ctx.m_mm.get_memroot();
c_page_pool.set((Buffer_page*)ptr, (Uint32)~0);
}
if(m_startphase == 5)
{
jam();
if (ERROR_INSERTED(13029)) /* Hold startphase 5 */
{
sendSignalWithDelay(SUMA_REF, GSN_STTOR, signal,
30, signal->getLength());
DBUG_VOID_RETURN;
}
signal->theData[0] = reference();
sendSignal(NDBCNTR_REF, GSN_READ_NODESREQ, signal, 1, JBB);
DBUG_VOID_RETURN;
}
if(m_startphase == 7)
{
if (m_typeOfStart != NodeState::ST_NODE_RESTART &&
m_typeOfStart != NodeState::ST_INITIAL_NODE_RESTART)
{
for( Uint32 i = 0; i < c_no_of_buckets; i++)
{
if (get_responsible_node(i) == getOwnNodeId())
{
// I'm running this bucket
DBUG_PRINT("info",("bucket %u set to true", i));
m_active_buckets.set(i);
ndbout_c("m_active_buckets.set(%d)", i);
}
}
}
if(!m_active_buckets.isclear())
{
NdbNodeBitmask tmp;
Uint32 bucket = 0;
while ((bucket = m_active_buckets.find(bucket)) != Bucket_mask::NotFound)
{
tmp.set(get_responsible_node(bucket, c_nodes_in_nodegroup_mask));
bucket++;
}
ndbassert(tmp.get(getOwnNodeId()));
m_gcp_complete_rep_count = m_active_buckets.count();
}
else
m_gcp_complete_rep_count = 0; // I contribute 1 gcp complete rep
if(m_typeOfStart == NodeState::ST_INITIAL_START &&
c_masterNodeId == getOwnNodeId())
{
jam();
createSequence(signal);
DBUG_VOID_RETURN;
}//if
if (ERROR_INSERTED(13030))
{
ndbout_c("Dont start handover");
DBUG_VOID_RETURN;
}
}//if
if(m_startphase == 100)
{
/**
* Allow API's to connect
*/
sendSTTORRY(signal);
DBUG_VOID_RETURN;
}
if(m_startphase == 101)
{
if (m_typeOfStart == NodeState::ST_NODE_RESTART ||
m_typeOfStart == NodeState::ST_INITIAL_NODE_RESTART)
{
/**
* Handover code here
*/
c_startup.m_wait_handover= true;
check_start_handover(signal);
DBUG_VOID_RETURN;
}
}
sendSTTORRY(signal);
DBUG_VOID_RETURN;
}
#include <ndb_version.h>
void
Suma::send_dict_lock_req(Signal* signal, Uint32 state)
{
if (state == DictLockReq::SumaStartMe &&
!ndbd_suma_dictlock_startme(getNodeInfo(c_masterNodeId).m_version))
{
jam();
goto notsupported;
}
else if (state == DictLockReq::SumaHandOver &&
!ndbd_suma_dictlock_handover(getNodeInfo(c_masterNodeId).m_version))
{
jam();
goto notsupported;
}
{
jam();
DictLockReq* req = (DictLockReq*)signal->getDataPtrSend();
req->lockType = state;
req->userPtr = state;
req->userRef = reference();
sendSignal(calcDictBlockRef(c_masterNodeId),
GSN_DICT_LOCK_REQ, signal, DictLockReq::SignalLength, JBB);
}
return;
notsupported:
DictLockConf* conf = (DictLockConf*)signal->getDataPtrSend();
conf->userPtr = state;
execDICT_LOCK_CONF(signal);
}
void
Suma::execDICT_LOCK_CONF(Signal* signal)
{
jamEntry();
DictLockConf* conf = (DictLockConf*)signal->getDataPtr();
Uint32 state = conf->userPtr;
switch(state){
case DictLockReq::SumaStartMe:
jam();
c_startup.m_restart_server_node_id = 0;
CRASH_INSERTION(13039);
send_start_me_req(signal);
return;
case DictLockReq::SumaHandOver:
jam();
send_handover_req(signal, SumaHandoverReq::RT_START_NODE);
return;
default:
jam();
jamLine(state);
ndbrequire(false);
}
}
void
Suma::execDICT_LOCK_REF(Signal* signal)
{
jamEntry();
DictLockRef* ref = (DictLockRef*)signal->getDataPtr();
Uint32 state = ref->userPtr;
ndbrequire(ref->errorCode == DictLockRef::TooManyRequests);
signal->theData[0] = SumaContinueB::RETRY_DICT_LOCK;
signal->theData[1] = state;
sendSignalWithDelay(reference(), GSN_CONTINUEB, signal, 300, 2);
}
void
Suma::send_dict_unlock_ord(Signal* signal, Uint32 state)
{
if (state == DictLockReq::SumaStartMe &&
!ndbd_suma_dictlock_startme(getNodeInfo(c_masterNodeId).m_version))
{
jam();
return;
}
else if (state == DictLockReq::SumaHandOver &&
!ndbd_suma_dictlock_handover(getNodeInfo(c_masterNodeId).m_version))
{
jam();
return;
}
jam();
DictUnlockOrd* ord = (DictUnlockOrd*)signal->getDataPtrSend();
ord->lockPtr = 0;
ord->lockType = state;
ord->senderData = state;
ord->senderRef = reference();
sendSignal(calcDictBlockRef(c_masterNodeId),
GSN_DICT_UNLOCK_ORD, signal, DictUnlockOrd::SignalLength, JBB);
}
void
Suma::send_start_me_req(Signal* signal)
{
Uint32 nodeId= c_startup.m_restart_server_node_id;
do {
nodeId = c_alive_nodes.find(nodeId + 1);
if(nodeId == getOwnNodeId())
continue;
if(nodeId == NdbNodeBitmask::NotFound)
{
nodeId = 0;
continue;
}
break;
} while(true);
infoEvent("Suma: asking node %d to recreate subscriptions on me", nodeId);
c_startup.m_restart_server_node_id= nodeId;
sendSignal(calcSumaBlockRef(nodeId),
GSN_SUMA_START_ME_REQ, signal, 1, JBB);
}
void
Suma::execSUMA_START_ME_REF(Signal* signal)
{
const SumaStartMeRef* ref= (SumaStartMeRef*)signal->getDataPtr();
Uint32 error = ref->errorCode;
if (error != SumaStartMeRef::Busy && error != SumaStartMeRef::NotStarted)
{
jam();
// for some reason we did not manage to create a subscription
// on the starting node
SystemError * const sysErr = (SystemError*)&signal->theData[0];
sysErr->errorCode = SystemError::CopySubscriptionRef;
sysErr->errorRef = reference();
sysErr->data[0] = error;
sysErr->data[1] = 0;
sendSignal(NDBCNTR_REF, GSN_SYSTEM_ERROR, signal,
SystemError::SignalLength, JBB);
return;
}
infoEvent("Suma: node %d refused %d",
c_startup.m_restart_server_node_id, ref->errorCode);
send_start_me_req(signal);
}
void
Suma::execSUMA_START_ME_CONF(Signal* signal)
{
infoEvent("Suma: node %d has completed restoring me",
c_startup.m_restart_server_node_id);
sendSTTORRY(signal);
send_dict_unlock_ord(signal, DictLockReq::SumaStartMe);
c_startup.m_restart_server_node_id= 0;
}
void
Suma::createSequence(Signal* signal)
{
jam();
DBUG_ENTER("Suma::createSequence");
UtilSequenceReq * req = (UtilSequenceReq*)signal->getDataPtrSend();
req->senderData = RNIL;
req->sequenceId = SUMA_SEQUENCE;
req->requestType = UtilSequenceReq::Create;
sendSignal(DBUTIL_REF, GSN_UTIL_SEQUENCE_REQ,
signal, UtilSequenceReq::SignalLength, JBB);
// execUTIL_SEQUENCE_CONF will call createSequenceReply()
DBUG_VOID_RETURN;
}
void
Suma::createSequenceReply(Signal* signal,
UtilSequenceConf * conf,
UtilSequenceRef * ref)
{
jam();
if (ref != NULL)
{
switch ((UtilSequenceRef::ErrorCode)ref->errorCode)
{
case UtilSequenceRef::NoSuchSequence:
ndbrequire(false);
case UtilSequenceRef::TCError:
{
char buf[128];
BaseString::snprintf(buf, sizeof(buf),
"Startup failed during sequence creation. TC error %d",
ref->TCErrorCode);
progError(__LINE__, NDBD_EXIT_RESOURCE_ALLOC_ERROR, buf);
}
}
ndbrequire(false);
}
sendSTTORRY(signal);
}
void
Suma::execREAD_NODESCONF(Signal* signal){
jamEntry();
ReadNodesConf * const conf = (ReadNodesConf *)signal->getDataPtr();
if(getNodeState().getNodeRestartInProgress())
{
c_alive_nodes.assign(NdbNodeBitmask::Size, conf->startedNodes);
c_alive_nodes.set(getOwnNodeId());
}
else
{
c_alive_nodes.assign(NdbNodeBitmask::Size, conf->startingNodes);
NdbNodeBitmask tmp;
tmp.assign(NdbNodeBitmask::Size, conf->startedNodes);
ndbrequire(tmp.isclear()); // No nodes can be started during SR
}
if (DBG_3R)
{
for (Uint32 i = 0; i<MAX_NDB_NODES; i++)
{
if (c_alive_nodes.get(i))
ndbout_c("%u c_alive_nodes.set(%u)", __LINE__, i);
}
}
c_masterNodeId = conf->masterNodeId;
getNodeGroupMembers(signal);
}
void
Suma::getNodeGroupMembers(Signal* signal)
{
jam();
DBUG_ENTER("Suma::getNodeGroupMembers");
/**
* Ask DIH for nodeGroupMembers
*/
CheckNodeGroups * sd = (CheckNodeGroups*)signal->getDataPtrSend();
sd->blockRef = reference();
sd->requestType = CheckNodeGroups::GetNodeGroupMembers;
sd->nodeId = getOwnNodeId();
sd->senderData = RNIL;
sendSignal(DBDIH_REF, GSN_CHECKNODEGROUPSREQ, signal,
CheckNodeGroups::SignalLength, JBB);
DBUG_VOID_RETURN;
}
static
bool
valid_seq(Uint32 n, Uint32 r, Uint16 dst[])
{
Uint16 tmp[MAX_REPLICAS];
for (Uint32 i = 0; i<r; i++)
{
tmp[i] = n % r;
for (Uint32 j = 0; j<i; j++)
if (tmp[j] == tmp[i])
return false;
n /= r;
}
/**
* reverse order for backward compatibility (with 2 replica)
*/
for (Uint32 i = 0; i<r; i++)
dst[i] = tmp[r-i-1];
return true;
}
void
Suma::fix_nodegroup()
{
Uint32 i, pos= 0;
for (i = 0; i < MAX_NDB_NODES; i++)
{
if (c_nodes_in_nodegroup_mask.get(i))
{
c_nodesInGroup[pos++] = i;
}
}
const Uint32 replicas= c_noNodesInGroup = pos;
if (replicas)
{
Uint32 buckets= 1;
for(i = 1; i <= replicas; i++)
buckets *= i;
Uint32 tot = 0;
switch(replicas){
case 1:
tot = 1;
break;
case 2:
tot = 4; // 2^2
break;
case 3:
tot = 27; // 3^3
break;
case 4:
tot = 256; // 4^4
break;
ndbrequire(false);
}
Uint32 cnt = 0;
for (i = 0; i<tot; i++)
{
Bucket* ptr= c_buckets + cnt;
if (valid_seq(i, replicas, ptr->m_nodes))
{
jam();
if (DBG_3R) printf("bucket %u : ", cnt);
for (Uint32 j = 0; j<replicas; j++)
{
ptr->m_nodes[j] = c_nodesInGroup[ptr->m_nodes[j]];
if (DBG_3R) printf("%u ", ptr->m_nodes[j]);
}
if (DBG_3R) printf("\n");
cnt++;
}
}
ndbrequire(cnt == buckets);
c_no_of_buckets= buckets;
}
else
{
jam();
c_no_of_buckets = 0;
}
}
void
Suma::execCHECKNODEGROUPSCONF(Signal *signal)
{
const CheckNodeGroups *sd = (const CheckNodeGroups *)signal->getDataPtrSend();
DBUG_ENTER("Suma::execCHECKNODEGROUPSCONF");
jamEntry();
c_nodeGroup = sd->output;
c_nodes_in_nodegroup_mask.assign(sd->mask);
c_noNodesInGroup = c_nodes_in_nodegroup_mask.count();
fix_nodegroup();
#ifndef DBUG_OFF
for (Uint32 i = 0; i < c_noNodesInGroup; i++) {
DBUG_PRINT("exit",("Suma: NodeGroup %u, me %u, "
"member[%u] %u",
c_nodeGroup, getOwnNodeId(),
i, c_nodesInGroup[i]));
}
#endif
c_startup.m_restart_server_node_id = 0;
if (m_typeOfStart == NodeState::ST_NODE_RESTART ||
m_typeOfStart == NodeState::ST_INITIAL_NODE_RESTART)
{
jam();
send_dict_lock_req(signal, DictLockReq::SumaStartMe);
return;
}
c_startup.m_restart_server_node_id = 0;
sendSTTORRY(signal);
DBUG_VOID_RETURN;
}
void
Suma::execAPI_START_REP(Signal* signal)
{
Uint32 nodeId = signal->theData[0];
c_connected_nodes.set(nodeId);
check_start_handover(signal);
}
void
Suma::check_start_handover(Signal* signal)
{
if(c_startup.m_wait_handover)
{
NodeBitmask tmp;
tmp.assign(c_connected_nodes);
tmp.bitAND(c_subscriber_nodes);
if(!c_subscriber_nodes.equal(tmp))
{
return;
}
c_startup.m_wait_handover= false;
if (c_no_of_buckets)
{
jam();
send_dict_lock_req(signal, DictLockReq::SumaHandOver);
}
else
{
jam();
sendSTTORRY(signal);
}
}
}
void
Suma::send_handover_req(Signal* signal, Uint32 type)
{
jam();
c_startup.m_handover_nodes.assign(c_alive_nodes);
c_startup.m_handover_nodes.bitAND(c_nodes_in_nodegroup_mask);
c_startup.m_handover_nodes.clear(getOwnNodeId());
Uint32 gci= Uint32(m_last_complete_gci >> 32) + 3;
SumaHandoverReq* req= (SumaHandoverReq*)signal->getDataPtrSend();
char buf[255];
c_startup.m_handover_nodes.getText(buf);
infoEvent("Suma: initiate handover for %s with nodes %s GCI: %u",
(type == SumaHandoverReq::RT_START_NODE ? "startup" : "shutdown"),
buf,
gci);
req->gci = gci;
req->nodeId = getOwnNodeId();
req->requestType = type;
NodeReceiverGroup rg(SUMA, c_startup.m_handover_nodes);
sendSignal(rg, GSN_SUMA_HANDOVER_REQ, signal,
SumaHandoverReq::SignalLength, JBB);
}
void
Suma::sendSTTORRY(Signal* signal){
signal->theData[0] = 0;
signal->theData[3] = 1;
signal->theData[4] = 3;
signal->theData[5] = 5;
signal->theData[6] = 7;
signal->theData[7] = 100;
signal->theData[8] = 101;
signal->theData[9] = 255; // No more start phases from missra
sendSignal(NDBCNTR_REF, GSN_STTORRY, signal, 10, JBB);
}
void
Suma::execNDB_STTOR(Signal* signal)
{
jamEntry();
}
void
Suma::execCONTINUEB(Signal* signal){
jamEntry();
Uint32 type= signal->theData[0];
switch(type){
case SumaContinueB::RELEASE_GCI:
{
Uint32 gci_hi = signal->theData[2];
Uint32 gci_lo = signal->theData[3];
Uint64 gci = gci_lo | (Uint64(gci_hi) << 32);
release_gci(signal, signal->theData[1], gci);
return;
}
case SumaContinueB::RESEND_BUCKET:
{
Uint32 min_gci_hi = signal->theData[2];
Uint32 min_gci_lo = signal->theData[5];
Uint32 last_gci_hi = signal->theData[4];
Uint32 last_gci_lo = signal->theData[6];
Uint64 min_gci = min_gci_lo | (Uint64(min_gci_hi) << 32);
Uint64 last_gci = last_gci_lo | (Uint64(last_gci_hi) << 32);
resend_bucket(signal,
signal->theData[1],
min_gci,
signal->theData[3],
last_gci);
return;
}
case SumaContinueB::OUT_OF_BUFFER_RELEASE:
out_of_buffer_release(signal, signal->theData[1]);
return;
case SumaContinueB::API_FAIL_GCI_LIST:
api_fail_gci_list(signal, signal->theData[1]);
return;
case SumaContinueB::API_FAIL_SUBSCRIBER_LIST:
api_fail_subscriber_list(signal,
signal->theData[1]);
return;
case SumaContinueB::API_FAIL_SUBSCRIPTION:
api_fail_subscription(signal);
return;
case SumaContinueB::SUB_STOP_REQ:
sub_stop_req(signal);
return;
case SumaContinueB::RETRY_DICT_LOCK:
jam();
send_dict_lock_req(signal, signal->theData[1]);
return;
}
}
/*****************************************************************************
*
* Node state handling
*
*****************************************************************************/
void Suma::execAPI_FAILREQ(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execAPI_FAILREQ");
Uint32 failedApiNode = signal->theData[0];
ndbrequire(signal->theData[1] == QMGR_REF); // As callback hard-codes QMGR
c_connected_nodes.clear(failedApiNode);
if (c_failedApiNodes.get(failedApiNode))
{
jam();
/* Being handled already, just conf */
goto CONF;
}
if (!c_subscriber_nodes.get(failedApiNode))
{
jam();
/* No Subscribers on that node, no SUMA
* specific work to do
*/
goto BLOCK_CLEANUP;
}
c_failedApiNodes.set(failedApiNode);
c_subscriber_nodes.clear(failedApiNode);
c_subscriber_per_node[failedApiNode] = 0;
c_failedApiNodesState[failedApiNode] = __LINE__;
check_start_handover(signal);
signal->theData[0] = SumaContinueB::API_FAIL_GCI_LIST;
signal->theData[1] = failedApiNode;
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 2, JBB);
return;
BLOCK_CLEANUP:
jam();
api_fail_block_cleanup(signal, failedApiNode);
DBUG_VOID_RETURN;
CONF:
jam();
signal->theData[0] = failedApiNode;
signal->theData[1] = reference();
sendSignal(QMGR_REF, GSN_API_FAILCONF, signal, 2, JBB);
c_failedApiNodesState[failedApiNode] = 0;
DBUG_VOID_RETURN;
}//execAPI_FAILREQ()
void
Suma::api_fail_block_cleanup_callback(Signal* signal,
Uint32 failedNodeId,
Uint32 elementsCleaned)
{
jamEntry();
/* Suma should not have any block level elements
* to be cleaned (Fragmented send/receive structures etc.)
* As it only uses Fragmented send/receive locally
*/
ndbassert(elementsCleaned == 0);
/* Node failure handling is complete */
signal->theData[0] = failedNodeId;
signal->theData[1] = reference();
sendSignal(QMGR_REF, GSN_API_FAILCONF, signal, 2, JBB);
c_failedApiNodes.clear(failedNodeId);
c_failedApiNodesState[failedNodeId] = 0;
}
void
Suma::api_fail_block_cleanup(Signal* signal, Uint32 failedNode)
{
jam();
c_failedApiNodesState[failedNode] = __LINE__;
Callback cb = {safe_cast(&Suma::api_fail_block_cleanup_callback),
failedNode};
simBlockNodeFailure(signal, failedNode, cb);
}
void
Suma::api_fail_gci_list(Signal* signal, Uint32 nodeId)
{
jam();
Ptr<Gcp_record> gcp;
if (c_gcp_list.first(gcp))
{
jam();
gcp.p->m_subscribers.bitAND(c_subscriber_nodes);
if (gcp.p->m_subscribers.isclear())
{
jam();
SubGcpCompleteAck* ack = (SubGcpCompleteAck*)signal->getDataPtrSend();
ack->rep.gci_hi = Uint32(gcp.p->m_gci >> 32);
ack->rep.gci_lo = Uint32(gcp.p->m_gci);
ack->rep.senderRef = reference();
NodeReceiverGroup rg(SUMA, c_nodes_in_nodegroup_mask);
sendSignal(rg, GSN_SUB_GCP_COMPLETE_ACK, signal,
SubGcpCompleteAck::SignalLength, JBB);
c_gcp_list.release(gcp);
c_failedApiNodesState[nodeId] = __LINE__;
signal->theData[0] = SumaContinueB::API_FAIL_GCI_LIST;
signal->theData[1] = nodeId;
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 2, JBB);
return;
}
}
if (ERROR_INSERTED(13023))
{
CLEAR_ERROR_INSERT_VALUE;
}
signal->theData[0] = SumaContinueB::API_FAIL_SUBSCRIBER_LIST;
signal->theData[1] = nodeId;
signal->theData[2] = RNIL; // SubOpPtr
signal->theData[3] = RNIL; // c_subscribers bucket
signal->theData[4] = RNIL; // subscriptionId
signal->theData[5] = RNIL; // SubscriptionKey
Ptr<SubOpRecord> subOpPtr;
if (c_subOpPool.seize(subOpPtr))
{
c_failedApiNodesState[nodeId] = __LINE__;
signal->theData[2] = subOpPtr.i;
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 6, JBB);
}
else
{
c_failedApiNodesState[nodeId] = __LINE__;
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 3, JBB);
}
return;
}
void
Suma::api_fail_subscriber_list(Signal* signal, Uint32 nodeId)
{
jam();
Ptr<SubOpRecord> subOpPtr;
if (c_outstanding_drop_trig_req > 9)
{
jam();
/**
* Make sure not to overflow DbtupProxy with too many GSN_DROP_TRIG_IMPL_REQ
* 9 is arbitrary number...
*/
sendSignalWithDelay(reference(), GSN_CONTINUEB, signal, 100,
signal->getLength());
return;
}
subOpPtr.i = signal->theData[2];
if (subOpPtr.i == RNIL)
{
if (c_subOpPool.seize(subOpPtr))
{
signal->theData[3] = RNIL;
}
else
{
jam();
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 3, JBB);
c_failedApiNodesState[nodeId] = __LINE__;
return;
}
}
else
{
jam();
c_subOpPool.getPtr(subOpPtr);
}
Uint32 bucket = signal->theData[3];
Uint32 subscriptionId = signal->theData[4];
Uint32 subscriptionKey = signal->theData[5];
DLHashTable<Subscription>::Iterator iter;
if (bucket == RNIL)
{
jam();
c_subscriptions.first(iter);
c_failedApiNodesState[nodeId] = __LINE__;
}
else
{
jam();
Subscription key;
key.m_subscriptionId = subscriptionId;
key.m_subscriptionKey = subscriptionKey;
if (c_subscriptions.find(iter.curr, key) == false)
{
jam();
/**
* We restart from this bucket :-(
*/
c_subscriptions.next(bucket, iter);
c_failedApiNodesState[nodeId] = __LINE__;
}
else
{
iter.bucket = bucket;
}
}
if (iter.curr.isNull())
{
jam();
api_fail_block_cleanup(signal, nodeId);
c_failedApiNodesState[nodeId] = __LINE__;
return;
}
subOpPtr.p->m_opType = SubOpRecord::R_API_FAIL_REQ;
subOpPtr.p->m_subPtrI = iter.curr.i;
subOpPtr.p->m_senderRef = nodeId;
subOpPtr.p->m_senderData = iter.bucket;
LocalDLFifoList<SubOpRecord> list(c_subOpPool, iter.curr.p->m_stop_req);
bool empty = list.isEmpty();
list.add(subOpPtr);
if (empty)
{
jam();
c_failedApiNodesState[nodeId] = __LINE__;
signal->theData[0] = SumaContinueB::API_FAIL_SUBSCRIPTION;
signal->theData[1] = subOpPtr.i;
signal->theData[2] = RNIL;
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 3, JBB);
}
else
{
jam();
c_failedApiNodesState[nodeId] = __LINE__;
}
}
void
Suma::api_fail_subscription(Signal* signal)
{
jam();
Ptr<SubOpRecord> subOpPtr;
c_subOpPool.getPtr(subOpPtr, signal->theData[1]);
Uint32 nodeId = subOpPtr.p->m_senderRef;
Ptr<Subscription> subPtr;
c_subscriptionPool.getPtr(subPtr, subOpPtr.p->m_subPtrI);
Ptr<Subscriber> ptr;
{
LocalDLList<Subscriber> list(c_subscriberPool, subPtr.p->m_subscribers);
if (signal->theData[2] == RNIL)
{
jam();
list.first(ptr);
}
else
{
jam();
list.getPtr(ptr, signal->theData[2]);
}
for (Uint32 i = 0; i<32 && !ptr.isNull(); i++)
{
jam();
if (refToNode(ptr.p->m_senderRef) == nodeId)
{
jam();
Ptr<Subscriber> tmp = ptr;
list.next(ptr);
list.remove(tmp);
/**
* NOTE: remove before...so we done send UNSUBSCRIBE to self (yuck)
*/
bool report = subPtr.p->m_options & Subscription::REPORT_SUBSCRIBE;
send_sub_start_stop_event(signal, tmp, NdbDictionary::Event::_TE_STOP,
report, list);
c_subscriberPool.release(tmp);
}
else
{
jam();
list.next(ptr);
}
}
}
if (!ptr.isNull())
{
jam();
c_failedApiNodesState[nodeId] = __LINE__;
signal->theData[0] = SumaContinueB::API_FAIL_SUBSCRIPTION;
signal->theData[1] = subOpPtr.i;
signal->theData[2] = ptr.i;
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 3, JBB);
return;
}
// Start potential waiter(s)
check_remove_queue(signal, subPtr, subOpPtr, true, false);
check_release_subscription(signal, subPtr);
// Continue iterating through subscriptions
DLHashTable<Subscription>::Iterator iter;
iter.bucket = subOpPtr.p->m_senderData;
iter.curr = subPtr;
if (c_subscriptions.next(iter))
{
jam();
c_failedApiNodesState[nodeId] = __LINE__;
signal->theData[0] = SumaContinueB::API_FAIL_SUBSCRIBER_LIST;
signal->theData[1] = nodeId;
signal->theData[2] = subOpPtr.i;
signal->theData[3] = iter.bucket;
signal->theData[4] = iter.curr.p->m_subscriptionId; // subscriptionId
signal->theData[5] = iter.curr.p->m_subscriptionKey; // SubscriptionKey
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 6, JBB);
return;
}
c_subOpPool.release(subOpPtr);
/* Now do block level cleanup */
api_fail_block_cleanup(signal, nodeId);
}
void
Suma::execNODE_FAILREP(Signal* signal){
jamEntry();
DBUG_ENTER("Suma::execNODE_FAILREP");
ndbassert(signal->getNoOfSections() == 0);
const NodeFailRep * rep = (NodeFailRep*)signal->getDataPtr();
NdbNodeBitmask failed; failed.assign(NdbNodeBitmask::Size, rep->theNodes);
if(c_restart.m_ref && failed.get(refToNode(c_restart.m_ref)))
{
jam();
if (c_restart.m_waiting_on_self)
{
jam();
c_restart.m_abort = 1;
}
else
{
jam();
Ptr<Subscription> subPtr;
c_subscriptionPool.getPtr(subPtr, c_restart.m_subPtrI);
abort_start_me(signal, subPtr, false);
}
}
if (ERROR_INSERTED(13032))
{
Uint32 node = c_subscriber_nodes.find(0);
if (node != NodeBitmask::NotFound)
{
ndbout_c("Inserting API_FAILREQ node: %u", node);
signal->theData[0] = node;
sendSignal(QMGR_REF, GSN_API_FAILREQ, signal, 1, JBA);
}
}
NdbNodeBitmask tmp;
tmp.assign(c_alive_nodes);
tmp.bitANDC(failed);
NdbNodeBitmask takeover_nodes;
if(c_nodes_in_nodegroup_mask.overlaps(failed))
{
for( Uint32 i = 0; i < c_no_of_buckets; i++)
{
if(m_active_buckets.get(i))
continue;
else if(m_switchover_buckets.get(i))
{
Uint32 state= c_buckets[i].m_state;
if((state & Bucket::BUCKET_HANDOVER) &&
failed.get(get_responsible_node(i)))
{
m_active_buckets.set(i);
m_switchover_buckets.clear(i);
ndbout_c("aborting handover");
}
else if(state & Bucket::BUCKET_STARTING)
{
progError(__LINE__, NDBD_EXIT_SYSTEM_ERROR,
"Nodefailure during SUMA takeover");
}
else if (state & Bucket::BUCKET_SHUTDOWN_TO)
{
jam();
c_buckets[i].m_state &= ~Uint32(Bucket::BUCKET_SHUTDOWN_TO);
m_switchover_buckets.clear(i);
ndbrequire(get_responsible_node(i, tmp) == getOwnNodeId());
start_resend(signal, i);
}
}
else if(get_responsible_node(i, tmp) == getOwnNodeId())
{
start_resend(signal, i);
}
}
}
/* Block level cleanup */
for(unsigned i = 1; i < MAX_NDB_NODES; i++) {
jam();
if(failed.get(i)) {
jam();
Uint32 elementsCleaned = simBlockNodeFailure(signal, i); // No callback
ndbassert(elementsCleaned == 0); // As Suma has no remote fragmented signals
(void) elementsCleaned; // Avoid compiler error
}//if
}//for
c_alive_nodes.assign(tmp);
DBUG_VOID_RETURN;
}
void
Suma::execINCL_NODEREQ(Signal* signal){
jamEntry();
const Uint32 senderRef = signal->theData[0];
const Uint32 nodeId = signal->theData[1];
ndbrequire(!c_alive_nodes.get(nodeId));
if (c_nodes_in_nodegroup_mask.get(nodeId))
{
/**
*
* XXX TODO: This should be removed
* But, other nodes are (incorrectly) reported as started
* even if they're not "started", but only INCL_NODEREQ'ed
*/
c_alive_nodes.set(nodeId);
/**
*
* Nodes in nodegroup will be "alive" when
* sending SUMA_HANDOVER_REQ
*/
}
else
{
jam();
c_alive_nodes.set(nodeId);
}
signal->theData[0] = nodeId;
signal->theData[1] = reference();
sendSignal(senderRef, GSN_INCL_NODECONF, signal, 2, JBB);
}
void
Suma::execSIGNAL_DROPPED_REP(Signal* signal){
jamEntry();
ndbrequire(false);
}
/********************************************************************
*
* Dump state
*
*/
static
const char*
cstr(Suma::Subscription::State s)
{
switch(s){
case Suma::Subscription::UNDEFINED:
return "undefined";
case Suma::Subscription::DEFINED:
return "defined";
case Suma::Subscription::DEFINING:
return "defining";
}
return "<unknown>";
}
static
const char*
cstr(Suma::Subscription::TriggerState s)
{
switch(s){
case Suma::Subscription::T_UNDEFINED:
return "undefined";
case Suma::Subscription::T_CREATING:
return "creating";
case Suma::Subscription::T_DEFINED:
return "defined";
case Suma::Subscription::T_DROPPING:
return "dropping";
case Suma::Subscription::T_ERROR:
return "error";
}
return "<uknown>";
}
static
const char*
cstr(Suma::Subscription::Options s)
{
static char buf[256];
buf[0] = 0;
strcat(buf, "[");
if (s & Suma::Subscription::REPORT_ALL)
strcat(buf, " reportall");
if (s & Suma::Subscription::REPORT_SUBSCRIBE)
strcat(buf, " reportsubscribe");
if (s & Suma::Subscription::MARKED_DROPPED)
strcat(buf, " dropped");
if (s & Suma::Subscription::NO_REPORT_DDL)
strcat(buf, " noreportddl");
strcat(buf, " ]");
return buf;
}
static
const char*
cstr(Suma::Table::State s)
{
switch(s){
case Suma::Table::UNDEFINED:
return "undefined";
case Suma::Table::DEFINING:
return "defining";
case Suma::Table::DEFINED:
return "defined";
case Suma::Table::DROPPED:
return "dropped";
}
return "<unknown>";
}
void
Suma::execDUMP_STATE_ORD(Signal* signal){
jamEntry();
Uint32 tCase = signal->theData[0];
#if 0
if(tCase >= 8000 && tCase <= 8003){
SubscriptionPtr subPtr;
c_subscriptions.getPtr(subPtr, g_subPtrI);
Ptr<SyncRecord> syncPtr;
c_syncPool.getPtr(syncPtr, subPtr.p->m_syncPtrI);
if(tCase == 8000){
syncPtr.p->startMeta(signal);
}
if(tCase == 8001){
syncPtr.p->startScan(signal);
}
if(tCase == 8002){
syncPtr.p->startTrigger(signal);
}
if(tCase == 8003){
subPtr.p->m_subscriptionType = SubCreateReq::SingleTableScan;
LocalDataBuffer<15> attrs(c_dataBufferPool, syncPtr.p->m_attributeList);
Uint32 tab = 0;
Uint32 att[] = { 0, 1, 1 };
syncPtr.p->m_tableList.append(&tab, 1);
attrs.append(att, 3);
}
}
#endif
if(tCase == 8004){
infoEvent("Suma: c_subscriberPool size: %d free: %d",
c_subscriberPool.getSize(),
c_subscriberPool.getNoOfFree());
infoEvent("Suma: c_tablePool size: %d free: %d",
c_tablePool.getSize(),
c_tablePool.getNoOfFree());
infoEvent("Suma: c_subscriptionPool size: %d free: %d",
c_subscriptionPool.getSize(),
c_subscriptionPool.getNoOfFree());
infoEvent("Suma: c_syncPool size: %d free: %d",
c_syncPool.getSize(),
c_syncPool.getNoOfFree());
infoEvent("Suma: c_dataBufferPool size: %d free: %d",
c_dataBufferPool.getSize(),
c_dataBufferPool.getNoOfFree());
infoEvent("Suma: c_subOpPool size: %d free: %d",
c_subOpPool.getSize(),
c_subOpPool.getNoOfFree());
#if 0
infoEvent("Suma: c_dataSubscribers count: %d",
count_subscribers(c_dataSubscribers));
infoEvent("Suma: c_prepDataSubscribers count: %d",
count_subscribers(c_prepDataSubscribers));
#endif
}
if(tCase == 8005)
{
for(Uint32 i = 0; i<c_no_of_buckets; i++)
{
Bucket* ptr= c_buckets + i;
infoEvent("Bucket %d %d%d-%x switch gci: %llu max_acked_gci: %llu max_gci: %llu tail: %d head: %d",
i,
m_active_buckets.get(i),
m_switchover_buckets.get(i),
ptr->m_state,
ptr->m_switchover_gci,
ptr->m_max_acked_gci,
ptr->m_buffer_head.m_max_gci,
ptr->m_buffer_tail,
ptr->m_buffer_head.m_page_id);
}
}
if (tCase == 8006)
{
SET_ERROR_INSERT_VALUE(13029);
}
if (tCase == 8007)
{
c_startup.m_restart_server_node_id = MAX_NDB_NODES + 1;
SET_ERROR_INSERT_VALUE(13029);
}
if (tCase == 8008)
{
CLEAR_ERROR_INSERT_VALUE;
}
if (tCase == 8010)
{
char buf1[255], buf2[255];
c_subscriber_nodes.getText(buf1);
c_connected_nodes.getText(buf2);
infoEvent("c_subscriber_nodes: %s", buf1);
infoEvent("c_connected_nodes: %s", buf2);
}
if (tCase == 8009)
{
if (ERROR_INSERTED(13030))
{
CLEAR_ERROR_INSERT_VALUE;
sendSTTORRY(signal);
}
else
{
SET_ERROR_INSERT_VALUE(13030);
}
return;
}
if (tCase == 8011)
{
jam();
Uint32 bucket = signal->theData[1];
KeyTable<Table>::Iterator it;
if (signal->getLength() == 1)
{
jam();
bucket = 0;
infoEvent("-- Starting dump of subscribers --");
}
c_tables.next(bucket, it);
const Uint32 RT_BREAK = 16;
for(Uint32 i = 0; i<RT_BREAK || it.bucket == bucket; i++)
{
jam();
if(it.curr.i == RNIL)
{
jam();
infoEvent("-- Ending dump of subscribers --");
return;
}
infoEvent("Table %u ver %u",
it.curr.p->m_tableId,
it.curr.p->m_schemaVersion);
Uint32 cnt = 0;
Ptr<Subscription> subPtr;
LocalDLList<Subscription> subList(c_subscriptionPool,
it.curr.p->m_subscriptions);
for(subList.first(subPtr); !subPtr.isNull(); subList.next(subPtr))
{
infoEvent(" Subcription %u", subPtr.i);
{
Ptr<Subscriber> ptr;
LocalDLList<Subscriber> list(c_subscriberPool,
subPtr.p->m_subscribers);
for (list.first(ptr); !ptr.isNull(); list.next(ptr), i++)
{
jam();
cnt++;
infoEvent(" Subscriber [ %x %u %u ]",
ptr.p->m_senderRef,
ptr.p->m_senderData,
subPtr.i);
}
}
{
Ptr<SubOpRecord> ptr;
LocalDLFifoList<SubOpRecord> list(c_subOpPool,
subPtr.p->m_create_req);
for (list.first(ptr); !ptr.isNull(); list.next(ptr), i++)
{
jam();
infoEvent(" create [ %x %u ]",
ptr.p->m_senderRef,
ptr.p->m_senderData);
}
}
{
Ptr<SubOpRecord> ptr;
LocalDLFifoList<SubOpRecord> list(c_subOpPool,
subPtr.p->m_start_req);
for (list.first(ptr); !ptr.isNull(); list.next(ptr), i++)
{
jam();
infoEvent(" start [ %x %u ]",
ptr.p->m_senderRef,
ptr.p->m_senderData);
}
}
{
Ptr<SubOpRecord> ptr;
LocalDLFifoList<SubOpRecord> list(c_subOpPool,
subPtr.p->m_stop_req);
for (list.first(ptr); !ptr.isNull(); list.next(ptr), i++)
{
jam();
infoEvent(" stop [ %u %x %u ]",
ptr.p->m_opType,
ptr.p->m_senderRef,
ptr.p->m_senderData);
}
}
}
infoEvent("Table %u #subscribers %u", it.curr.p->m_tableId, cnt);
c_tables.next(it);
}
signal->theData[0] = tCase;
signal->theData[1] = it.bucket;
sendSignalWithDelay(reference(), GSN_DUMP_STATE_ORD, signal, 100, 2);
return;
}
if (tCase == 8012)
{
jam();
Uint32 bucket = signal->theData[1];
KeyTable<Subscription>::Iterator it;
if (signal->getLength() == 1)
{
jam();
bucket = 0;
infoEvent("-- Starting dump of subscribers --");
}
c_subscriptions.next(bucket, it);
const Uint32 RT_BREAK = 16;
for(Uint32 i = 0; i<RT_BREAK || it.bucket == bucket; i++)
{
jam();
if(it.curr.i == RNIL)
{
jam();
infoEvent("-- Ending dump of subscribers --");
return;
}
Ptr<Subscription> subPtr = it.curr;
Ptr<Table> tabPtr;
c_tablePool.getPtr(tabPtr, subPtr.p->m_table_ptrI);
infoEvent("Subcription %u id: 0x%.8x key: 0x%.8x state: %s",
subPtr.i,
subPtr.p->m_subscriptionId,
subPtr.p->m_subscriptionKey,
cstr(subPtr.p->m_state));
infoEvent(" trigger state: %s options: %s",
cstr(subPtr.p->m_trigger_state),
cstr((Suma::Subscription::Options)subPtr.p->m_options));
infoEvent(" tablePtr: %u tableId: %u schemaVersion: 0x%.8x state: %s",
tabPtr.i,
subPtr.p->m_tableId,
tabPtr.p->m_schemaVersion,
cstr(tabPtr.p->m_state));
{
Ptr<Subscriber> ptr;
LocalDLList<Subscriber> list(c_subscriberPool,
subPtr.p->m_subscribers);
for (list.first(ptr); !ptr.isNull(); list.next(ptr), i++)
{
jam();
infoEvent(" Subscriber [ %x %u %u ]",
ptr.p->m_senderRef,
ptr.p->m_senderData,
subPtr.i);
}
}
{
Ptr<SubOpRecord> ptr;
LocalDLFifoList<SubOpRecord> list(c_subOpPool,
subPtr.p->m_create_req);
for (list.first(ptr); !ptr.isNull(); list.next(ptr), i++)
{
jam();
infoEvent(" create [ %x %u ]",
ptr.p->m_senderRef,
ptr.p->m_senderData);
}
}
{
Ptr<SubOpRecord> ptr;
LocalDLFifoList<SubOpRecord> list(c_subOpPool,
subPtr.p->m_start_req);
for (list.first(ptr); !ptr.isNull(); list.next(ptr), i++)
{
jam();
infoEvent(" start [ %x %u ]",
ptr.p->m_senderRef,
ptr.p->m_senderData);
}
}
{
Ptr<SubOpRecord> ptr;
LocalDLFifoList<SubOpRecord> list(c_subOpPool,
subPtr.p->m_stop_req);
for (list.first(ptr); !ptr.isNull(); list.next(ptr), i++)
{
jam();
infoEvent(" stop [ %u %x %u ]",
ptr.p->m_opType,
ptr.p->m_senderRef,
ptr.p->m_senderData);
}
}
c_subscriptions.next(it);
}
signal->theData[0] = tCase;
signal->theData[1] = it.bucket;
sendSignalWithDelay(reference(), GSN_DUMP_STATE_ORD, signal, 100, 2);
return;
}
if (tCase == 7019 && signal->getLength() == 2)
{
jam();
Uint32 nodeId = signal->theData[1];
if (nodeId < MAX_NODES)
{
warningEvent(" Suma 7019 %u line: %u", nodeId,
c_failedApiNodesState[nodeId]);
warningEvent(" c_connected_nodes.get(): %u",
c_connected_nodes.get(nodeId));
warningEvent(" c_failedApiNodes.get(): %u",
c_failedApiNodes.get(nodeId));
warningEvent(" c_subscriber_nodes.get(): %u",
c_subscriber_nodes.get(nodeId));
warningEvent(" c_subscriber_per_node[%u]: %u",
nodeId, c_subscriber_per_node[nodeId]);
}
else
{
warningEvent(" SUMP: dump-7019 to unknown node: %u", nodeId);
}
}
}
void Suma::execDBINFO_SCANREQ(Signal *signal)
{
DbinfoScanReq req= *(DbinfoScanReq*)signal->theData;
const Ndbinfo::ScanCursor* cursor =
CAST_CONSTPTR(Ndbinfo::ScanCursor, DbinfoScan::getCursorPtr(&req));
Ndbinfo::Ratelimit rl;
jamEntry();
switch(req.tableId){
case Ndbinfo::POOLS_TABLEID:
{
Ndbinfo::pool_entry pools[] =
{
{ "Subscriber",
c_subscriberPool.getUsed(),
c_subscriberPool.getSize(),
c_subscriberPool.getEntrySize(),
c_subscriberPool.getUsedHi(),
{ CFG_DB_SUBSCRIBERS,
CFG_DB_SUBSCRIPTIONS,
CFG_DB_NO_TABLES,0 }},
{ "Table",
c_tablePool.getUsed(),
c_tablePool.getSize(),
c_tablePool.getEntrySize(),
c_tablePool.getUsedHi(),
{ CFG_DB_NO_TABLES,0,0,0 }},
{ "Subscription",
c_subscriptionPool.getUsed(),
c_subscriptionPool.getSize(),
c_subscriptionPool.getEntrySize(),
c_subscriptionPool.getUsedHi(),
{ CFG_DB_SUBSCRIPTIONS,
CFG_DB_NO_TABLES,0,0 }},
{ "Sync",
c_syncPool.getUsed(),
c_syncPool.getSize(),
c_syncPool.getEntrySize(),
c_syncPool.getUsedHi(),
{ 0,0,0,0 }},
{ "Data Buffer",
c_dataBufferPool.getUsed(),
c_dataBufferPool.getSize(),
c_dataBufferPool.getEntrySize(),
c_dataBufferPool.getUsedHi(),
{ CFG_DB_NO_ATTRIBUTES,0,0,0 }},
{ "SubOp",
c_subOpPool.getUsed(),
c_subOpPool.getSize(),
c_subOpPool.getEntrySize(),
c_subOpPool.getUsedHi(),
{ CFG_DB_SUB_OPERATIONS,0,0,0 }},
{ "Page Chunk",
c_page_chunk_pool.getUsed(),
c_page_chunk_pool.getSize(),
c_page_chunk_pool.getEntrySize(),
c_page_chunk_pool.getUsedHi(),
{ 0,0,0,0 }},
{ "GCP",
c_gcp_pool.getUsed(),
c_gcp_pool.getSize(),
c_gcp_pool.getEntrySize(),
c_gcp_pool.getUsedHi(),
{ CFG_DB_API_HEARTBEAT_INTERVAL,
CFG_DB_GCP_INTERVAL,0,0 }},
{ NULL, 0,0,0,0, { 0,0,0,0 }}
};
const size_t num_config_params =
sizeof(pools[0].config_params) / sizeof(pools[0].config_params[0]);
Uint32 pool = cursor->data[0];
BlockNumber bn = blockToMain(number());
while(pools[pool].poolname)
{
jam();
Ndbinfo::Row row(signal, req);
row.write_uint32(getOwnNodeId());
row.write_uint32(bn); // block number
row.write_uint32(instance()); // block instance
row.write_string(pools[pool].poolname);
row.write_uint64(pools[pool].used);
row.write_uint64(pools[pool].total);
row.write_uint64(pools[pool].used_hi);
row.write_uint64(pools[pool].entry_size);
for (size_t i = 0; i < num_config_params; i++)
row.write_uint32(pools[pool].config_params[i]);
ndbinfo_send_row(signal, req, row, rl);
pool++;
if (rl.need_break(req))
{
jam();
ndbinfo_send_scan_break(signal, req, rl, pool);
return;
}
}
break;
}
default:
break;
}
ndbinfo_send_scan_conf(signal, req, rl);
}
/*************************************************************
*
* Creation of subscription id's
*
************************************************************/
void
Suma::execCREATE_SUBID_REQ(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execCREATE_SUBID_REQ");
ndbassert(signal->getNoOfSections() == 0);
CRASH_INSERTION(13001);
CreateSubscriptionIdReq const * req =
(CreateSubscriptionIdReq*)signal->getDataPtr();
SubscriberPtr subbPtr;
if(!c_subscriberPool.seize(subbPtr)){
jam();
sendSubIdRef(signal, req->senderRef, req->senderData, 1412);
DBUG_VOID_RETURN;
}
DBUG_PRINT("info",("c_subscriberPool size: %d free: %d",
c_subscriberPool.getSize(),
c_subscriberPool.getNoOfFree()));
subbPtr.p->m_senderRef = req->senderRef;
subbPtr.p->m_senderData = req->senderData;
UtilSequenceReq * utilReq = (UtilSequenceReq*)signal->getDataPtrSend();
utilReq->senderData = subbPtr.i;
utilReq->sequenceId = SUMA_SEQUENCE;
utilReq->requestType = UtilSequenceReq::NextVal;
sendSignal(DBUTIL_REF, GSN_UTIL_SEQUENCE_REQ,
signal, UtilSequenceReq::SignalLength, JBB);
DBUG_VOID_RETURN;
}
void
Suma::execUTIL_SEQUENCE_CONF(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execUTIL_SEQUENCE_CONF");
ndbassert(signal->getNoOfSections() == 0);
CRASH_INSERTION(13002);
UtilSequenceConf * conf = (UtilSequenceConf*)signal->getDataPtr();
if(conf->requestType == UtilSequenceReq::Create) {
jam();
createSequenceReply(signal, conf, NULL);
DBUG_VOID_RETURN;
}
Uint64 subId;
memcpy(&subId,conf->sequenceValue,8);
SubscriberPtr subbPtr;
c_subscriberPool.getPtr(subbPtr,conf->senderData);
CreateSubscriptionIdConf * subconf = (CreateSubscriptionIdConf*)conf;
subconf->senderRef = reference();
subconf->senderData = subbPtr.p->m_senderData;
subconf->subscriptionId = (Uint32)subId;
subconf->subscriptionKey =(getOwnNodeId() << 16) | (Uint32)(subId & 0xFFFF);
sendSignal(subbPtr.p->m_senderRef, GSN_CREATE_SUBID_CONF, signal,
CreateSubscriptionIdConf::SignalLength, JBB);
c_subscriberPool.release(subbPtr);
DBUG_PRINT("info",("c_subscriberPool size: %d free: %d",
c_subscriberPool.getSize(),
c_subscriberPool.getNoOfFree()));
DBUG_VOID_RETURN;
}
void
Suma::execUTIL_SEQUENCE_REF(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execUTIL_SEQUENCE_REF");
ndbassert(signal->getNoOfSections() == 0);
UtilSequenceRef * ref = (UtilSequenceRef*)signal->getDataPtr();
Uint32 err= ref->errorCode;
if(ref->requestType == UtilSequenceReq::Create) {
jam();
createSequenceReply(signal, NULL, ref);
DBUG_VOID_RETURN;
}
Uint32 subData = ref->senderData;
SubscriberPtr subbPtr;
c_subscriberPool.getPtr(subbPtr,subData);
if (err == UtilSequenceRef::TCError)
{
jam();
err = ref->TCErrorCode;
}
sendSubIdRef(signal, subbPtr.p->m_senderRef, subbPtr.p->m_senderData, err);
c_subscriberPool.release(subbPtr);
DBUG_PRINT("info",("c_subscriberPool size: %d free: %d",
c_subscriberPool.getSize(),
c_subscriberPool.getNoOfFree()));
DBUG_VOID_RETURN;
}//execUTIL_SEQUENCE_REF()
void
Suma::sendSubIdRef(Signal* signal,
Uint32 senderRef, Uint32 senderData, Uint32 errCode)
{
jam();
DBUG_ENTER("Suma::sendSubIdRef");
CreateSubscriptionIdRef * ref =
(CreateSubscriptionIdRef *)signal->getDataPtrSend();
ref->senderRef = reference();
ref->senderData = senderData;
ref->errorCode = errCode;
sendSignal(senderRef,
GSN_CREATE_SUBID_REF,
signal,
CreateSubscriptionIdRef::SignalLength,
JBB);
DBUG_VOID_RETURN;
}
/**********************************************************
* Suma participant interface
*
* Creation of subscriptions
*/
void
Suma::execSUB_CREATE_REQ(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execSUB_CREATE_REQ");
ndbassert(signal->getNoOfSections() == 0);
CRASH_INSERTION(13003);
const SubCreateReq req = *(SubCreateReq*)signal->getDataPtr();
const Uint32 senderRef = req.senderRef;
const Uint32 senderData = req.senderData;
const Uint32 subId = req.subscriptionId;
const Uint32 subKey = req.subscriptionKey;
const Uint32 type = req.subscriptionType & SubCreateReq::RemoveFlags;
const Uint32 flags = req.subscriptionType & SubCreateReq::GetFlags;
const Uint32 reportAll = (flags & SubCreateReq::ReportAll) ?
Subscription::REPORT_ALL : 0;
const Uint32 reportSubscribe = (flags & SubCreateReq::ReportSubscribe) ?
Subscription::REPORT_SUBSCRIBE : 0;
const Uint32 noReportDDL = (flags & SubCreateReq::NoReportDDL) ?
Subscription::NO_REPORT_DDL : 0;
const Uint32 tableId = req.tableId;
const Uint32 schemaTransId = req.schemaTransId;
bool subDropped = req.subscriptionType & SubCreateReq::NR_Sub_Dropped;
/**
* This 2 options are only allowed during NR
*/
if (subDropped)
{
ndbrequire(refToNode(senderRef) == c_startup.m_restart_server_node_id);
}
Subscription key;
key.m_subscriptionId = subId;
key.m_subscriptionKey = subKey;
DBUG_PRINT("enter",("key.m_subscriptionId: %u, key.m_subscriptionKey: %u",
key.m_subscriptionId, key.m_subscriptionKey));
SubscriptionPtr subPtr;
bool found = c_subscriptions.find(subPtr, key);
if (c_startup.m_restart_server_node_id == RNIL)
{
jam();
/**
* We havent started syncing yet
*/
sendSubCreateRef(signal, senderRef, senderData,
SubCreateRef::NotStarted);
return;
}
CRASH_INSERTION2(13040, c_startup.m_restart_server_node_id != RNIL);
CRASH_INSERTION(13041);
bool allowDup = true; //c_startup.m_restart_server_node_id;
if (found && !allowDup)
{
jam();
sendSubCreateRef(signal, senderRef, senderData,
SubCreateRef::SubscriptionAlreadyExist);
return;
}
if (found == false)
{
jam();
if(!c_subscriptions.seize(subPtr))
{
jam();
sendSubCreateRef(signal, senderRef, senderData,
SubCreateRef::OutOfSubscriptionRecords);
return;
}
new (subPtr.p) Subscription();
subPtr.p->m_seq_no = c_current_seq;
subPtr.p->m_subscriptionId = subId;
subPtr.p->m_subscriptionKey = subKey;
subPtr.p->m_subscriptionType = type;
subPtr.p->m_tableId = tableId;
subPtr.p->m_table_ptrI = RNIL;
subPtr.p->m_state = Subscription::UNDEFINED;
subPtr.p->m_trigger_state = Subscription::T_UNDEFINED;
subPtr.p->m_triggers[0] = ILLEGAL_TRIGGER_ID;
subPtr.p->m_triggers[1] = ILLEGAL_TRIGGER_ID;
subPtr.p->m_triggers[2] = ILLEGAL_TRIGGER_ID;
subPtr.p->m_errorCode = 0;
subPtr.p->m_options = reportSubscribe | reportAll | noReportDDL;
subPtr.p->m_schemaTransId = schemaTransId;
}
Ptr<SubOpRecord> subOpPtr;
LocalDLFifoList<SubOpRecord> subOpList(c_subOpPool, subPtr.p->m_create_req);
if ((ERROR_INSERTED(13044) && found == false) ||
subOpList.seize(subOpPtr) == false)
{
jam();
if (found == false)
{
jam();
if (ERROR_INSERTED(13044))
{
CLEAR_ERROR_INSERT_VALUE;
}
c_subscriptionPool.release(subPtr); // not yet in hash
}
sendSubCreateRef(signal, senderRef, senderData,
SubCreateRef::OutOfTableRecords);
return;
}
subOpPtr.p->m_senderRef = senderRef;
subOpPtr.p->m_senderData = senderData;
if (subDropped)
{
jam();
subPtr.p->m_options |= Subscription::MARKED_DROPPED;
}
TablePtr tabPtr;
if (found)
{
jam();
c_tablePool.getPtr(tabPtr, subPtr.p->m_table_ptrI);
}
else if (c_tables.find(tabPtr, tableId))
{
jam();
}
else
{
jam();
if (ERROR_INSERTED(13045) || c_tablePool.seize(tabPtr) == false)
{
jam();
if (ERROR_INSERTED(13045))
{
CLEAR_ERROR_INSERT_VALUE;
}
subOpList.release(subOpPtr);
c_subscriptionPool.release(subPtr); // not yet in hash
sendSubCreateRef(signal, senderRef, senderData,
SubCreateRef::OutOfTableRecords);
return;
}
new (tabPtr.p) Table;
tabPtr.p->m_tableId= tableId;
tabPtr.p->m_ptrI= tabPtr.i;
tabPtr.p->m_error = 0;
tabPtr.p->m_schemaVersion = RNIL;
tabPtr.p->m_state = Table::UNDEFINED;
tabPtr.p->m_schemaTransId = schemaTransId;
c_tables.add(tabPtr);
}
if (found == false)
{
jam();
c_subscriptions.add(subPtr);
LocalDLList<Subscription> list(c_subscriptionPool,
tabPtr.p->m_subscriptions);
list.add(subPtr);
subPtr.p->m_table_ptrI = tabPtr.i;
}
switch(tabPtr.p->m_state){
case Table::DEFINED:{
jam();
// Send conf
subOpList.release(subOpPtr);
subPtr.p->m_state = Subscription::DEFINED;
SubCreateConf * const conf = (SubCreateConf*)signal->getDataPtrSend();
conf->senderRef = reference();
conf->senderData = senderData;
sendSignal(senderRef, GSN_SUB_CREATE_CONF, signal,
SubCreateConf::SignalLength, JBB);
return;
}
case Table::UNDEFINED:{
jam();
tabPtr.p->m_state = Table::DEFINING;
subPtr.p->m_state = Subscription::DEFINING;
if (ERROR_INSERTED(13031))
{
jam();
CLEAR_ERROR_INSERT_VALUE;
GetTabInfoRef* ref = (GetTabInfoRef*)signal->getDataPtrSend();
ref->tableId = tableId;
ref->senderData = tabPtr.i;
ref->errorCode = GetTabInfoRef::TableNotDefined;
sendSignal(reference(), GSN_GET_TABINFOREF, signal,
GetTabInfoRef::SignalLength, JBB);
return;
}
GetTabInfoReq * req = (GetTabInfoReq *)signal->getDataPtrSend();
req->senderRef = reference();
req->senderData = tabPtr.i;
req->requestType =
GetTabInfoReq::RequestById | GetTabInfoReq::LongSignalConf;
req->tableId = tableId;
req->schemaTransId = schemaTransId;
sendSignal(DBDICT_REF, GSN_GET_TABINFOREQ, signal,
GetTabInfoReq::SignalLength, JBB);
return;
}
case Table::DEFINING:
{
jam();
/**
* just wait for completion
*/
subPtr.p->m_state = Subscription::DEFINING;
return;
}
case Table::DROPPED:
{
subOpList.release(subOpPtr);
{
LocalDLList<Subscription> list(c_subscriptionPool,
tabPtr.p->m_subscriptions);
list.remove(subPtr);
}
c_subscriptions.release(subPtr);
sendSubCreateRef(signal, senderRef, senderData,
SubCreateRef::TableDropped);
return;
}
}
ndbrequire(false);
}
void
Suma::sendSubCreateRef(Signal* signal, Uint32 retRef, Uint32 data,
Uint32 errCode)
{
jam();
SubCreateRef * ref = (SubCreateRef *)signal->getDataPtrSend();
ref->errorCode = errCode;
ref->senderData = data;
sendSignal(retRef, GSN_SUB_CREATE_REF, signal,
SubCreateRef::SignalLength, JBB);
return;
}
/**********************************************************
*
* Setting upp trigger for subscription
*
*/
void
Suma::execSUB_SYNC_REQ(Signal* signal)
{
jamEntry();
CRASH_INSERTION(13004);
SubSyncReq * const req = (SubSyncReq*)signal->getDataPtr();
SubscriptionPtr subPtr;
Subscription key;
key.m_subscriptionId = req->subscriptionId;
key.m_subscriptionKey = req->subscriptionKey;
SectionHandle handle(this, signal);
if(!c_subscriptions.find(subPtr, key))
{
jam();
releaseSections(handle);
sendSubSyncRef(signal, 1407);
return;
}
Ptr<SyncRecord> syncPtr;
LocalDLList<SyncRecord> list(c_syncPool, subPtr.p->m_syncRecords);
if(!list.seize(syncPtr))
{
jam();
releaseSections(handle);
sendSubSyncRef(signal, 1416);
return;
}
new (syncPtr.p) Ptr<SyncRecord>;
syncPtr.p->m_senderRef = req->senderRef;
syncPtr.p->m_senderData = req->senderData;
syncPtr.p->m_subscriptionPtrI = subPtr.i;
syncPtr.p->ptrI = syncPtr.i;
syncPtr.p->m_error = 0;
syncPtr.p->m_requestInfo = req->requestInfo;
syncPtr.p->m_frag_cnt = req->fragCount;
syncPtr.p->m_frag_id = req->fragId;
syncPtr.p->m_tableId = subPtr.p->m_tableId;
{
jam();
if(handle.m_cnt > 0)
{
SegmentedSectionPtr ptr;
handle.getSection(ptr, SubSyncReq::ATTRIBUTE_LIST);
LocalDataBuffer<15> attrBuf(c_dataBufferPool, syncPtr.p->m_attributeList);
append(attrBuf, ptr, getSectionSegmentPool());
}
if (req->requestInfo & SubSyncReq::RangeScan)
{
jam();
ndbrequire(handle.m_cnt > 1)
SegmentedSectionPtr ptr;
handle.getSection(ptr, SubSyncReq::TUX_BOUND_INFO);
LocalDataBuffer<15> boundBuf(c_dataBufferPool, syncPtr.p->m_boundInfo);
append(boundBuf, ptr, getSectionSegmentPool());
}
releaseSections(handle);
}
/**
* We need to gather fragment info
*/
{
jam();
DihScanTabReq* req = (DihScanTabReq*)signal->getDataPtrSend();
req->senderRef = reference();
req->senderData = syncPtr.i;
req->tableId = subPtr.p->m_tableId;
req->schemaTransId = subPtr.p->m_schemaTransId;
sendSignal(DBDIH_REF, GSN_DIH_SCAN_TAB_REQ, signal,
DihScanTabReq::SignalLength, JBB);
}
}
void
Suma::sendSubSyncRef(Signal* signal, Uint32 errCode){
jam();
SubSyncRef * ref= (SubSyncRef *)signal->getDataPtrSend();
ref->errorCode = errCode;
sendSignal(signal->getSendersBlockRef(),
GSN_SUB_SYNC_REF,
signal,
SubSyncRef::SignalLength,
JBB);
return;
}
void
Suma::execDIH_SCAN_TAB_REF(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execDI_FCOUNTREF");
DihScanTabRef * ref = (DihScanTabRef*)signal->getDataPtr();
switch ((DihScanTabRef::ErrorCode) ref->error)
{
case DihScanTabRef::ErroneousTableState:
jam();
if (ref->tableStatus == Dbdih::TabRecord::TS_CREATING)
{
const Uint32 tableId = ref->tableId;
const Uint32 synPtrI = ref->senderData;
const Uint32 schemaTransId = ref->schemaTransId;
DihScanTabReq * req = (DihScanTabReq*)signal->getDataPtrSend();
req->senderData = synPtrI;
req->senderRef = reference();
req->tableId = tableId;
req->schemaTransId = schemaTransId;
sendSignalWithDelay(DBDIH_REF, GSN_DIH_SCAN_TAB_REQ, signal,
DihScanTabReq::SignalLength,
DihScanTabReq::RetryInterval);
DBUG_VOID_RETURN;
}
ndbrequire(false);
default:
ndbrequire(false);
}
DBUG_VOID_RETURN;
}
void
Suma::execDIH_SCAN_TAB_CONF(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execDI_FCOUNTCONF");
ndbassert(signal->getNoOfSections() == 0);
DihScanTabConf * conf = (DihScanTabConf*)signal->getDataPtr();
const Uint32 tableId = conf->tableId;
const Uint32 fragCount = conf->fragmentCount;
const Uint32 scanCookie = conf->scanCookie;
Ptr<SyncRecord> ptr;
c_syncPool.getPtr(ptr, conf->senderData);
LocalDataBuffer<15> fragBuf(c_dataBufferPool, ptr.p->m_fragments);
ndbrequire(fragBuf.getSize() == 0);
ndbassert(fragCount >= ptr.p->m_frag_cnt);
if (ptr.p->m_frag_cnt == 0)
{
jam();
ptr.p->m_frag_cnt = fragCount;
}
ptr.p->m_scan_cookie = scanCookie;
DihScanGetNodesReq* req = (DihScanGetNodesReq*)signal->getDataPtrSend();
req->senderRef = reference();
req->senderData = ptr.i;
req->tableId = tableId;
req->fragId = 0;
req->scanCookie = scanCookie;
sendSignal(DBDIH_REF, GSN_DIH_SCAN_GET_NODES_REQ, signal,
DihScanGetNodesReq::SignalLength, JBB);
DBUG_VOID_RETURN;
}
void
Suma::execDIH_SCAN_GET_NODES_CONF(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execDIGETPRIMCONF");
ndbassert(signal->getNoOfSections() == 0);
DihScanGetNodesConf* conf = (DihScanGetNodesConf*)signal->getDataPtr();
const Uint32 nodeCount = conf->count;
const Uint32 tableId = conf->tableId;
const Uint32 fragNo = conf->fragId;
ndbrequire(nodeCount > 0 && nodeCount <= MAX_REPLICAS);
Ptr<SyncRecord> ptr;
c_syncPool.getPtr(ptr, conf->senderData);
{
LocalDataBuffer<15> fragBuf(c_dataBufferPool, ptr.p->m_fragments);
/**
* Add primary node for fragment to list
*/
FragmentDescriptor fd;
fd.m_fragDesc.m_nodeId = conf->nodes[0];
fd.m_fragDesc.m_fragmentNo = fragNo;
fd.m_fragDesc.m_lqhInstanceKey = conf->instanceKey;
if (ptr.p->m_frag_id == ZNIL)
{
signal->theData[2] = fd.m_dummy;
fragBuf.append(&signal->theData[2], 1);
}
else if (ptr.p->m_frag_id == fragNo)
{
/*
* Given fragment must have a replica on this node.
*/
const Uint32 ownNodeId = getOwnNodeId();
Uint32 i = 0;
for (i = 0; i < nodeCount; i++)
if (conf->nodes[i] == ownNodeId)
break;
if (i == nodeCount)
{
sendSubSyncRef(signal, 1428);
return;
}
fd.m_fragDesc.m_nodeId = ownNodeId;
signal->theData[2] = fd.m_dummy;
fragBuf.append(&signal->theData[2], 1);
}
}
const Uint32 nextFrag = fragNo + 1;
if(nextFrag == ptr.p->m_frag_cnt)
{
jam();
ptr.p->startScan(signal);
return;
}
DihScanGetNodesReq* req = (DihScanGetNodesReq*)signal->getDataPtrSend();
req->senderRef = reference();
req->senderData = ptr.i;
req->tableId = tableId;
req->fragId = nextFrag;
req->scanCookie = ptr.p->m_scan_cookie;
sendSignal(DBDIH_REF, GSN_DIH_SCAN_GET_NODES_REQ, signal,
DihScanGetNodesReq::SignalLength, JBB);
DBUG_VOID_RETURN;
}
/**********************************************************
* Dict interface
*/
/*************************************************************************
*
*
*/
void
Suma::execGET_TABINFOREF(Signal* signal){
jamEntry();
GetTabInfoRef* ref = (GetTabInfoRef*)signal->getDataPtr();
Uint32 tableId = ref->tableId;
Uint32 senderData = ref->senderData;
Uint32 schemaTransId = ref->schemaTransId;
GetTabInfoRef::ErrorCode errorCode =
(GetTabInfoRef::ErrorCode) ref->errorCode;
int do_resend_request = 0;
TablePtr tabPtr;
c_tablePool.getPtr(tabPtr, senderData);
switch (errorCode)
{
case GetTabInfoRef::TableNotDefined:
// wrong state
break;
case GetTabInfoRef::InvalidTableId:
// no such table
break;
case GetTabInfoRef::Busy:
do_resend_request = 1;
break;
case GetTabInfoRef::NoFetchByName:
jam();
case GetTabInfoRef::TableNameTooLong:
jam();
ndbrequire(false);
}
if (tabPtr.p->m_state == Table::DROPPED)
{
jam();
do_resend_request = 0;
}
if (do_resend_request)
{
GetTabInfoReq * req = (GetTabInfoReq *)signal->getDataPtrSend();
req->senderRef = reference();
req->senderData = senderData;
req->requestType =
GetTabInfoReq::RequestById | GetTabInfoReq::LongSignalConf;
req->tableId = tableId;
req->schemaTransId = schemaTransId;
sendSignalWithDelay(DBDICT_REF, GSN_GET_TABINFOREQ, signal,
30, GetTabInfoReq::SignalLength);
return;
}
get_tabinfo_ref_release(signal, tabPtr);
}
void
Suma::get_tabinfo_ref_release(Signal* signal, Ptr<Table> tabPtr)
{
LocalDLList<Subscription> subList(c_subscriptionPool,
tabPtr.p->m_subscriptions);
Ptr<Subscription> subPtr;
bool empty = subList.isEmpty();
for(subList.first(subPtr); !subPtr.isNull();)
{
jam();
Ptr<SubOpRecord> ptr;
ndbassert(subPtr.p->m_start_req.isEmpty());
ndbassert(subPtr.p->m_stop_req.isEmpty());
LocalDLFifoList<SubOpRecord> list(c_subOpPool, subPtr.p->m_create_req);
for (list.first(ptr); !ptr.isNull(); )
{
jam();
sendSubCreateRef(signal,
ptr.p->m_senderRef,
ptr.p->m_senderData,
SubCreateRef::TableDropped);
Ptr<SubOpRecord> tmp0 = ptr;
list.next(ptr);
list.release(tmp0);
}
Ptr<Subscription> tmp1 = subPtr;
subList.next(subPtr);
c_subscriptions.remove(tmp1);
subList.release(tmp1);
}
c_tables.release(tabPtr);
ndbassert(!empty);
}
void
Suma::execGET_TABINFO_CONF(Signal* signal){
jamEntry();
CRASH_INSERTION(13006);
if(!assembleFragments(signal)){
return;
}
SectionHandle handle(this, signal);
GetTabInfoConf* conf = (GetTabInfoConf*)signal->getDataPtr();
TablePtr tabPtr;
c_tablePool.getPtr(tabPtr, conf->senderData);
SegmentedSectionPtr ptr;
handle.getSection(ptr, GetTabInfoConf::DICT_TAB_INFO);
ndbrequire(tabPtr.p->parseTable(ptr, *this));
releaseSections(handle);
if (tabPtr.p->m_state == Table::DROPPED)
{
jam();
get_tabinfo_ref_release(signal, tabPtr);
return;
}
tabPtr.p->m_state = Table::DEFINED;
LocalDLList<Subscription> subList(c_subscriptionPool,
tabPtr.p->m_subscriptions);
Ptr<Subscription> subPtr;
bool empty = subList.isEmpty();
for(subList.first(subPtr); !subPtr.isNull(); subList.next(subPtr))
{
jam();
subPtr.p->m_state = Subscription::DEFINED;
Ptr<SubOpRecord> ptr;
LocalDLFifoList<SubOpRecord> list(c_subOpPool, subPtr.p->m_create_req);
for (list.first(ptr); !ptr.isNull();)
{
jam();
SubCreateConf * const conf = (SubCreateConf*)signal->getDataPtrSend();
conf->senderRef = reference();
conf->senderData = ptr.p->m_senderData;
sendSignal(ptr.p->m_senderRef, GSN_SUB_CREATE_CONF, signal,
SubCreateConf::SignalLength, JBB);
Ptr<SubOpRecord> tmp = ptr;
list.next(ptr);
list.release(tmp);
}
}
ndbassert(!empty);
}
bool
Suma::Table::parseTable(SegmentedSectionPtr ptr,
Suma &suma)
{
DBUG_ENTER("Suma::Table::parseTable");
SimplePropertiesSectionReader it(ptr, suma.getSectionSegmentPool());
SimpleProperties::UnpackStatus s;
DictTabInfo::Table tableDesc; tableDesc.init();
s = SimpleProperties::unpack(it, &tableDesc,
DictTabInfo::TableMapping,
DictTabInfo::TableMappingSize,
true, true);
jamBlock(&suma);
suma.suma_ndbrequire(s == SimpleProperties::Break);
/**
* Initialize table object
*/
m_noOfAttributes = tableDesc.NoOfAttributes;
m_schemaVersion = tableDesc.TableVersion;
DBUG_RETURN(true);
}
/**********************************************************
*
* Scan interface
*
*/
void
Suma::SyncRecord::startScan(Signal* signal)
{
jam();
DBUG_ENTER("Suma::SyncRecord::startScan");
/**
* Get fraginfo
*/
m_currentFragment = 0;
nextScan(signal);
DBUG_VOID_RETURN;
}
bool
Suma::SyncRecord::getNextFragment(TablePtr * tab,
FragmentDescriptor * fd)
{
jam();
SubscriptionPtr subPtr;
suma.c_subscriptions.getPtr(subPtr, m_subscriptionPtrI);
DataBuffer<15>::DataBufferIterator fragIt;
TablePtr tabPtr;
suma.c_tablePool.getPtr(tabPtr, subPtr.p->m_table_ptrI);
LocalDataBuffer<15> fragBuf(suma.c_dataBufferPool, m_fragments);
fragBuf.position(fragIt, m_currentFragment);
for(; !fragIt.curr.isNull(); fragBuf.next(fragIt), m_currentFragment++)
{
FragmentDescriptor tmp;
tmp.m_dummy = * fragIt.data;
if(tmp.m_fragDesc.m_nodeId == suma.getOwnNodeId()){
* fd = tmp;
* tab = tabPtr;
return true;
}
}
m_currentFragment = 0;
return false;
}
void
Suma::SyncRecord::nextScan(Signal* signal)
{
jam();
DBUG_ENTER("Suma::SyncRecord::nextScan");
TablePtr tabPtr;
FragmentDescriptor fd;
SubscriptionPtr subPtr;
if(!getNextFragment(&tabPtr, &fd)){
jam();
completeScan(signal);
DBUG_VOID_RETURN;
}
suma.c_subscriptions.getPtr(subPtr, m_subscriptionPtrI);
DataBuffer<15>::Head head = m_attributeList;
LocalDataBuffer<15> attrBuf(suma.c_dataBufferPool, head);
Uint32 instanceKey = fd.m_fragDesc.m_lqhInstanceKey;
BlockReference lqhRef = numberToRef(DBLQH, instanceKey, suma.getOwnNodeId());
ScanFragReq * req = (ScanFragReq *)signal->getDataPtrSend();
const Uint32 parallelism = 16;
//const Uint32 attrLen = 5 + attrBuf.getSize();
req->senderData = ptrI;
req->resultRef = suma.reference();
req->tableId = tabPtr.p->m_tableId;
req->requestInfo = 0;
req->savePointId = 0;
ScanFragReq::setLockMode(req->requestInfo, 0);
ScanFragReq::setHoldLockFlag(req->requestInfo, 1);
ScanFragReq::setKeyinfoFlag(req->requestInfo, 0);
if (m_requestInfo & SubSyncReq::NoDisk)
{
ScanFragReq::setNoDiskFlag(req->requestInfo, 1);
}
if (m_requestInfo & SubSyncReq::LM_Exclusive)
{
ScanFragReq::setLockMode(req->requestInfo, 1);
ScanFragReq::setHoldLockFlag(req->requestInfo, 1);
ScanFragReq::setKeyinfoFlag(req->requestInfo, 1);
}
if (m_requestInfo & SubSyncReq::Reorg)
{
ScanFragReq::setReorgFlag(req->requestInfo, ScanFragReq::REORG_MOVED);
}
if (m_requestInfo & SubSyncReq::TupOrder)
{
ScanFragReq::setTupScanFlag(req->requestInfo, 1);
}
if (m_requestInfo & SubSyncReq::LM_CommittedRead)
{
ScanFragReq::setReadCommittedFlag(req->requestInfo, 1);
}
if (m_requestInfo & SubSyncReq::RangeScan)
{
ScanFragReq::setRangeScanFlag(req->requestInfo, 1);
}
if (m_requestInfo & SubSyncReq::StatScan)
{
ScanFragReq::setStatScanFlag(req->requestInfo, 1);
}
req->fragmentNoKeyLen = fd.m_fragDesc.m_fragmentNo;
req->schemaVersion = tabPtr.p->m_schemaVersion;
req->transId1 = 0;
req->transId2 = (SUMA << 20) + (suma.getOwnNodeId() << 8);
req->clientOpPtr = (ptrI << 16);
req->batch_size_rows= parallelism;
req->batch_size_bytes= 0;
Uint32 * attrInfo = signal->theData + 25;
attrInfo[0] = attrBuf.getSize();
attrInfo[1] = 0;
attrInfo[2] = 0;
attrInfo[3] = 0;
attrInfo[4] = 0;
Uint32 pos = 5;
DataBuffer<15>::DataBufferIterator it;
for(attrBuf.first(it); !it.curr.isNull(); attrBuf.next(it))
{
AttributeHeader::init(&attrInfo[pos++], * it.data, 0);
}
LinearSectionPtr ptr[3];
Uint32 noOfSections;
ptr[0].p = attrInfo;
ptr[0].sz = pos;
noOfSections = 1;
if (m_requestInfo & SubSyncReq::RangeScan)
{
jam();
Uint32 oldpos = pos; // after attrInfo
LocalDataBuffer<15> boundBuf(suma.c_dataBufferPool, m_boundInfo);
for (boundBuf.first(it); !it.curr.isNull(); boundBuf.next(it))
{
attrInfo[pos++] = *it.data;
}
ptr[1].p = &attrInfo[oldpos];
ptr[1].sz = pos - oldpos;
noOfSections = 2;
}
suma.sendSignal(lqhRef, GSN_SCAN_FRAGREQ, signal,
ScanFragReq::SignalLength, JBB, ptr, noOfSections);
m_currentNoOfAttributes = attrBuf.getSize();
DBUG_VOID_RETURN;
}
void
Suma::execSCAN_FRAGREF(Signal* signal){
jamEntry();
// ScanFragRef * const ref = (ScanFragRef*)signal->getDataPtr();
ndbrequire(false);
}
void
Suma::execSCAN_FRAGCONF(Signal* signal){
jamEntry();
DBUG_ENTER("Suma::execSCAN_FRAGCONF");
ndbassert(signal->getNoOfSections() == 0);
CRASH_INSERTION(13011);
ScanFragConf * const conf = (ScanFragConf*)signal->getDataPtr();
const Uint32 completed = conf->fragmentCompleted;
const Uint32 senderData = conf->senderData;
const Uint32 completedOps = conf->completedOps;
Ptr<SyncRecord> syncPtr;
c_syncPool.getPtr(syncPtr, senderData);
if(completed != 2){ // 2==ZSCAN_FRAG_CLOSED
jam();
#if PRINT_ONLY
SubSyncContinueConf * const conf =
(SubSyncContinueConf*)signal->getDataPtrSend();
conf->subscriptionId = subPtr.p->m_subscriptionId;
conf->subscriptionKey = subPtr.p->m_subscriptionKey;
execSUB_SYNC_CONTINUE_CONF(signal);
#else
SubSyncContinueReq * const req = (SubSyncContinueReq*)signal->getDataPtrSend();
req->subscriberData = syncPtr.p->m_senderData;
req->noOfRowsSent = completedOps;
req->senderData = senderData;
sendSignal(syncPtr.p->m_senderRef, GSN_SUB_SYNC_CONTINUE_REQ, signal,
SubSyncContinueReq::SignalLength, JBB);
#endif
DBUG_VOID_RETURN;
}
ndbrequire(completedOps == 0);
syncPtr.p->m_currentFragment++;
syncPtr.p->nextScan(signal);
DBUG_VOID_RETURN;
}
void
Suma::execSUB_SYNC_CONTINUE_CONF(Signal* signal){
jamEntry();
ndbassert(signal->getNoOfSections() == 0);
CRASH_INSERTION(13012);
SubSyncContinueConf * const conf =
(SubSyncContinueConf*)signal->getDataPtr();
SubscriptionPtr subPtr;
Subscription key;
key.m_subscriptionId = conf->subscriptionId;
key.m_subscriptionKey = conf->subscriptionKey;
Uint32 syncPtrI = conf->senderData;
ndbrequire(c_subscriptions.find(subPtr, key));
Uint32 instanceKey;
{
Ptr<SyncRecord> syncPtr;
c_syncPool.getPtr(syncPtr, syncPtrI);
LocalDataBuffer<15> fragBuf(c_dataBufferPool, syncPtr.p->m_fragments);
DataBuffer<15>::DataBufferIterator fragIt;
bool ok = fragBuf.position(fragIt, syncPtr.p->m_currentFragment);
ndbrequire(ok);
FragmentDescriptor tmp;
tmp.m_dummy = * fragIt.data;
instanceKey = tmp.m_fragDesc.m_lqhInstanceKey;
}
BlockReference lqhRef = numberToRef(DBLQH, instanceKey, getOwnNodeId());
ScanFragNextReq * req = (ScanFragNextReq *)signal->getDataPtrSend();
req->senderData = syncPtrI;
req->requestInfo = 0;
req->transId1 = 0;
req->transId2 = (SUMA << 20) + (getOwnNodeId() << 8);
req->batch_size_rows = 16;
req->batch_size_bytes = 0;
sendSignal(lqhRef, GSN_SCAN_NEXTREQ, signal,
ScanFragNextReq::SignalLength, JBB);
}
void
Suma::SyncRecord::completeScan(Signal* signal, int error)
{
jam();
DBUG_ENTER("Suma::SyncRecord::completeScan");
SubscriptionPtr subPtr;
suma.c_subscriptionPool.getPtr(subPtr, m_subscriptionPtrI);
DihScanTabCompleteRep* rep = (DihScanTabCompleteRep*)signal->getDataPtr();
rep->tableId = subPtr.p->m_tableId;
rep->scanCookie = m_scan_cookie;
suma.sendSignal(DBDIH_REF, GSN_DIH_SCAN_TAB_COMPLETE_REP, signal,
DihScanTabCompleteRep::SignalLength, JBB);
#if PRINT_ONLY
ndbout_c("GSN_SUB_SYNC_CONF (data)");
#else
if (error == 0)
{
SubSyncConf * const conf = (SubSyncConf*)signal->getDataPtrSend();
conf->senderRef = suma.reference();
conf->senderData = m_senderData;
suma.sendSignal(m_senderRef, GSN_SUB_SYNC_CONF, signal,
SubSyncConf::SignalLength, JBB);
}
else
{
SubSyncRef * const ref = (SubSyncRef*)signal->getDataPtrSend();
ref->senderRef = suma.reference();
ref->senderData = m_senderData;
suma.sendSignal(m_senderRef, GSN_SUB_SYNC_REF, signal,
SubSyncRef::SignalLength, JBB);
}
#endif
release();
LocalDLList<SyncRecord> list(suma.c_syncPool, subPtr.p->m_syncRecords);
Ptr<SyncRecord> tmp;
tmp.i = ptrI;
tmp.p = this;
list.release(tmp);
DBUG_VOID_RETURN;
}
void
Suma::execSCAN_HBREP(Signal* signal){
jamEntry();
#if 0
ndbout << "execSCAN_HBREP" << endl << hex;
for(int i = 0; i<signal->length(); i++){
ndbout << signal->theData[i] << " ";
if(((i + 1) % 8) == 0)
ndbout << endl << hex;
}
ndbout << endl;
#endif
}
/**********************************************************
*
* Suma participant interface
*
* Creation of subscriber
*
*/
void
Suma::execSUB_START_REQ(Signal* signal){
jamEntry();
ndbassert(signal->getNoOfSections() == 0);
DBUG_ENTER("Suma::execSUB_START_REQ");
SubStartReq * const req = (SubStartReq*)signal->getDataPtr();
CRASH_INSERTION(13013);
Uint32 senderRef = req->senderRef;
Uint32 senderData = req->senderData;
Uint32 subscriberData = req->subscriberData;
Uint32 subscriberRef = req->subscriberRef;
SubscriptionData::Part part = (SubscriptionData::Part)req->part;
(void)part; // TODO validate part
Subscription key;
key.m_subscriptionId = req->subscriptionId;
key.m_subscriptionKey = req->subscriptionKey;
SubscriptionPtr subPtr;
CRASH_INSERTION2(13042, getNodeState().startLevel == NodeState::SL_STARTING);
if (c_startup.m_restart_server_node_id == RNIL)
{
jam();
/**
* We havent started syncing yet
*/
sendSubStartRef(signal,
senderRef, senderData, SubStartRef::NotStarted);
return;
}
bool found = c_subscriptions.find(subPtr, key);
if (!found)
{
jam();
sendSubStartRef(signal,
senderRef, senderData, SubStartRef::NoSuchSubscription);
return;
}
if (ERROR_INSERTED(13046))
{
jam();
CLEAR_ERROR_INSERT_VALUE;
sendSubStartRef(signal,
senderRef, senderData, SubStartRef::NoSuchSubscription);
return;
}
switch(subPtr.p->m_state){
case Subscription::UNDEFINED:
jam();
ndbrequire(false);
case Subscription::DEFINING:
jam();
sendSubStartRef(signal,
senderRef, senderData, SubStartRef::Defining);
return;
case Subscription::DEFINED:
break;
}
if (subPtr.p->m_options & Subscription::MARKED_DROPPED)
{
jam();
if (c_startup.m_restart_server_node_id == 0)
{
sendSubStartRef(signal,
senderRef, senderData, SubStartRef::Dropped);
return;
}
else
{
/**
* Allow SUB_START_REQ from peer node
*/
}
}
if (subPtr.p->m_trigger_state == Subscription::T_ERROR)
{
jam();
sendSubStartRef(signal,
senderRef, senderData, subPtr.p->m_errorCode);
return;
}
SubscriberPtr subbPtr;
if(!c_subscriberPool.seize(subbPtr))
{
jam();
sendSubStartRef(signal,
senderRef, senderData, SubStartRef::OutOfSubscriberRecords);
return;
}
Ptr<SubOpRecord> subOpPtr;
if (!c_subOpPool.seize(subOpPtr))
{
jam();
c_subscriberPool.release(subbPtr);
sendSubStartRef(signal,
senderRef, senderData, SubStartRef::OutOfSubOpRecords);
return;
}
if (! check_sub_start(subscriberRef))
{
jam();
c_subscriberPool.release(subbPtr);
c_subOpPool.release(subOpPtr);
sendSubStartRef(signal,
senderRef, senderData, SubStartRef::NodeDied);
return;
}
// setup subscriber record
subbPtr.p->m_senderRef = subscriberRef;
subbPtr.p->m_senderData = subscriberData;
subOpPtr.p->m_opType = SubOpRecord::R_SUB_START_REQ;
subOpPtr.p->m_subPtrI = subPtr.i;
subOpPtr.p->m_senderRef = senderRef;
subOpPtr.p->m_senderData = senderData;
subOpPtr.p->m_subscriberRef = subbPtr.i;
{
LocalDLFifoList<SubOpRecord> subOpList(c_subOpPool, subPtr.p->m_start_req);
subOpList.add(subOpPtr);
}
/**
* Check triggers
*/
switch(subPtr.p->m_trigger_state){
case Subscription::T_UNDEFINED:
jam();
/**
* create triggers
*/
create_triggers(signal, subPtr);
break;
case Subscription::T_CREATING:
jam();
/**
* Triggers are already being created...wait for completion
*/
return;
case Subscription::T_DROPPING:
jam();
/**
* Trigger(s) are being dropped...wait for completion
* (and recreate them when done)
*/
break;
case Subscription::T_DEFINED:{
jam();
report_sub_start_conf(signal, subPtr);
return;
}
case Subscription::T_ERROR:
jam();
ndbrequire(false); // Checked above
break;
}
}
void
Suma::sendSubStartRef(Signal* signal, Uint32 dstref, Uint32 data, Uint32 err)
{
jam();
SubStartRef * ref = (SubStartRef *)signal->getDataPtrSend();
ref->senderRef = reference();
ref->senderData = data;
ref->errorCode = err;
sendSignal(dstref, GSN_SUB_START_REF, signal,
SubStartRef::SignalLength, JBB);
}
void
Suma::create_triggers(Signal* signal, SubscriptionPtr subPtr)
{
jam();
ndbrequire(subPtr.p->m_trigger_state == Subscription::T_UNDEFINED);
subPtr.p->m_trigger_state = Subscription::T_CREATING;
TablePtr tabPtr;
c_tablePool.getPtr(tabPtr, subPtr.p->m_table_ptrI);
AttributeMask attrMask;
tabPtr.p->createAttributeMask(attrMask, *this);
subPtr.p->m_outstanding_trigger = 3;
for(Uint32 j = 0; j<3; j++)
{
Uint32 triggerId = (tabPtr.p->m_schemaVersion << 18) | (j << 16) | subPtr.i;
ndbrequire(subPtr.p->m_triggers[j] == ILLEGAL_TRIGGER_ID);
CreateTrigImplReq * const req =
(CreateTrigImplReq*)signal->getDataPtrSend();
req->senderRef = SUMA_REF;
req->senderData = subPtr.i;
req->requestType = 0;
Uint32 ti = 0;
TriggerInfo::setTriggerType(ti, TriggerType::SUBSCRIPTION_BEFORE);
TriggerInfo::setTriggerActionTime(ti, TriggerActionTime::TA_DETACHED);
TriggerInfo::setTriggerEvent(ti, (TriggerEvent::Value)j);
TriggerInfo::setMonitorReplicas(ti, true);
//TriggerInfo::setMonitorAllAttributes(ti, j == TriggerEvent::TE_DELETE);
TriggerInfo::setMonitorAllAttributes(ti, true);
TriggerInfo::setReportAllMonitoredAttributes(ti,
subPtr.p->m_options & Subscription::REPORT_ALL);
req->triggerInfo = ti;
req->receiverRef = SUMA_REF;
req->triggerId = triggerId;
req->tableId = subPtr.p->m_tableId;
req->tableVersion = 0; // not used
req->indexId = ~(Uint32)0;
req->indexVersion = 0;
LinearSectionPtr ptr[3];
ptr[0].p = attrMask.rep.data;
ptr[0].sz = attrMask.getSizeInWords();
sendSignal(DBTUP_REF, GSN_CREATE_TRIG_IMPL_REQ,
signal, CreateTrigImplReq::SignalLength, JBB, ptr, 1);
}
}
void
Suma::execCREATE_TRIG_IMPL_CONF(Signal* signal)
{
jamEntry();
CreateTrigImplConf * conf = (CreateTrigImplConf*)signal->getDataPtr();
const Uint32 triggerId = conf->triggerId;
Uint32 type = (triggerId >> 16) & 0x3;
Uint32 tableId = conf->tableId;
TablePtr tabPtr;
SubscriptionPtr subPtr;
c_subscriptions.getPtr(subPtr, conf->senderData);
c_tables.getPtr(tabPtr, subPtr.p->m_table_ptrI);
ndbrequire(tabPtr.p->m_tableId == tableId);
ndbrequire(subPtr.p->m_trigger_state == Subscription::T_CREATING);
ndbrequire(type < 3);
ndbrequire(subPtr.p->m_triggers[type] == ILLEGAL_TRIGGER_ID);
subPtr.p->m_triggers[type] = triggerId;
ndbrequire(subPtr.p->m_outstanding_trigger);
subPtr.p->m_outstanding_trigger--;
if (subPtr.p->m_outstanding_trigger)
{
jam();
/**
* Wait for more
*/
return;
}
if (subPtr.p->m_errorCode == 0)
{
jam();
subPtr.p->m_trigger_state = Subscription::T_DEFINED;
report_sub_start_conf(signal, subPtr);
}
else
{
jam();
subPtr.p->m_trigger_state = Subscription::T_ERROR;
drop_triggers(signal, subPtr);
}
}
void
Suma::execCREATE_TRIG_IMPL_REF(Signal* signal)
{
jamEntry();
CreateTrigImplRef * const ref = (CreateTrigImplRef*)signal->getDataPtr();
const Uint32 triggerId = ref->triggerId;
Uint32 type = (triggerId >> 16) & 0x3;
Uint32 tableId = ref->tableId;
TablePtr tabPtr;
SubscriptionPtr subPtr;
c_subscriptions.getPtr(subPtr, ref->senderData);
c_tables.getPtr(tabPtr, subPtr.p->m_table_ptrI);
ndbrequire(tabPtr.p->m_tableId == tableId);
ndbrequire(subPtr.p->m_trigger_state == Subscription::T_CREATING);
ndbrequire(type < 3);
ndbrequire(subPtr.p->m_triggers[type] == ILLEGAL_TRIGGER_ID);
subPtr.p->m_errorCode = ref->errorCode;
ndbrequire(subPtr.p->m_outstanding_trigger);
subPtr.p->m_outstanding_trigger--;
if (subPtr.p->m_outstanding_trigger)
{
jam();
/**
* Wait for more
*/
return;
}
subPtr.p->m_trigger_state = Subscription::T_ERROR;
drop_triggers(signal, subPtr);
}
bool
Suma::check_sub_start(Uint32 subscriberRef)
{
Uint32 nodeId = refToNode(subscriberRef);
bool startme = c_startup.m_restart_server_node_id;
bool handover = c_startup.m_wait_handover;
bool connected =
c_failedApiNodes.get(nodeId) == false &&
c_connected_nodes.get(nodeId);
return (startme || handover || connected);
}
void
Suma::report_sub_start_conf(Signal* signal, Ptr<Subscription> subPtr)
{
const Uint64 gci = get_current_gci(signal);
{
LocalDLList<Subscriber> list(c_subscriberPool,
subPtr.p->m_subscribers);
LocalDLFifoList<SubOpRecord> subOpList(c_subOpPool, subPtr.p->m_start_req);
Ptr<Subscriber> ptr;
Ptr<SubOpRecord> subOpPtr;
for (subOpList.first(subOpPtr); !subOpPtr.isNull(); )
{
jam();
Uint32 senderRef = subOpPtr.p->m_senderRef;
Uint32 senderData = subOpPtr.p->m_senderData;
c_subscriberPool.getPtr(ptr, subOpPtr.p->m_subscriberRef);
if (check_sub_start(ptr.p->m_senderRef))
{
SubStartConf* conf = (SubStartConf*)signal->getDataPtrSend();
conf->senderRef = reference();
conf->senderData = senderData;
conf->subscriptionId = subPtr.p->m_subscriptionId;
conf->subscriptionKey = subPtr.p->m_subscriptionKey;
conf->firstGCI = Uint32(gci >> 32);
conf->part = SubscriptionData::TableData;
conf->bucketCount = c_no_of_buckets;
conf->nodegroup = c_nodeGroup;
sendSignal(senderRef, GSN_SUB_START_CONF, signal,
SubStartConf::SignalLength, JBB);
/**
* Call before adding to list...
* cause method will (maybe) iterate thought list
*/
bool report = subPtr.p->m_options & Subscription::REPORT_SUBSCRIBE;
send_sub_start_stop_event(signal, ptr,NdbDictionary::Event::_TE_ACTIVE,
report, list);
list.add(ptr);
c_subscriber_nodes.set(refToNode(ptr.p->m_senderRef));
c_subscriber_per_node[refToNode(ptr.p->m_senderRef)]++;
}
else
{
jam();
sendSubStartRef(signal,
senderRef, senderData, SubStartRef::NodeDied);
c_subscriberPool.release(ptr);
}
Ptr<SubOpRecord> tmp = subOpPtr;
subOpList.next(subOpPtr);
subOpList.release(tmp);
}
}
check_release_subscription(signal, subPtr);
}
void
Suma::report_sub_start_ref(Signal* signal,
Ptr<Subscription> subPtr,
Uint32 errCode)
{
LocalDLList<Subscriber> list(c_subscriberPool,
subPtr.p->m_subscribers);
LocalDLFifoList<SubOpRecord> subOpList(c_subOpPool, subPtr.p->m_start_req);
Ptr<Subscriber> ptr;
Ptr<SubOpRecord> subOpPtr;
for (subOpList.first(subOpPtr); !subOpPtr.isNull(); )
{
jam();
Uint32 senderRef = subOpPtr.p->m_senderRef;
Uint32 senderData = subOpPtr.p->m_senderData;
c_subscriberPool.getPtr(ptr, subOpPtr.p->m_subscriberRef);
SubStartRef* ref = (SubStartRef*)signal->getDataPtrSend();
ref->senderRef = reference();
ref->senderData = senderData;
ref->errorCode = errCode;
sendSignal(senderRef, GSN_SUB_START_REF, signal,
SubStartConf::SignalLength, JBB);
Ptr<SubOpRecord> tmp = subOpPtr;
subOpList.next(subOpPtr);
subOpList.release(tmp);
c_subscriberPool.release(ptr);
}
}
void
Suma::drop_triggers(Signal* signal, SubscriptionPtr subPtr)
{
jam();
subPtr.p->m_outstanding_trigger = 0;
Ptr<Table> tabPtr;
c_tablePool.getPtr(tabPtr, subPtr.p->m_table_ptrI);
if (tabPtr.p->m_state == Table::DROPPED)
{
jam();
subPtr.p->m_triggers[0] = ILLEGAL_TRIGGER_ID;
subPtr.p->m_triggers[1] = ILLEGAL_TRIGGER_ID;
subPtr.p->m_triggers[2] = ILLEGAL_TRIGGER_ID;
}
else
{
for(Uint32 j = 0; j<3; j++)
{
jam();
Uint32 triggerId = subPtr.p->m_triggers[j];
if (triggerId != ILLEGAL_TRIGGER_ID)
{
subPtr.p->m_outstanding_trigger++;
DropTrigImplReq * const req =
(DropTrigImplReq*)signal->getDataPtrSend();
req->senderRef = SUMA_REF; // Sending to myself
req->senderData = subPtr.i;
req->requestType = 0;
// TUP needs some triggerInfo to find right list
Uint32 ti = 0;
TriggerInfo::setTriggerType(ti, TriggerType::SUBSCRIPTION_BEFORE);
TriggerInfo::setTriggerActionTime(ti, TriggerActionTime::TA_DETACHED);
TriggerInfo::setTriggerEvent(ti, (TriggerEvent::Value)j);
TriggerInfo::setMonitorReplicas(ti, true);
//TriggerInfo::setMonitorAllAttributes(ti, j ==TriggerEvent::TE_DELETE);
TriggerInfo::setMonitorAllAttributes(ti, true);
TriggerInfo::setReportAllMonitoredAttributes(ti,
subPtr.p->m_options & Subscription::REPORT_ALL);
req->triggerInfo = ti;
req->tableId = subPtr.p->m_tableId;
req->tableVersion = 0; // not used
req->indexId = RNIL;
req->indexVersion = 0;
req->triggerId = triggerId;
req->receiverRef = SUMA_REF;
c_outstanding_drop_trig_req++;
sendSignal(DBTUP_REF, GSN_DROP_TRIG_IMPL_REQ,
signal, DropTrigImplReq::SignalLength, JBB);
}
}
}
if (subPtr.p->m_outstanding_trigger == 0)
{
jam();
drop_triggers_complete(signal, subPtr);
}
}
void
Suma::execDROP_TRIG_IMPL_REF(Signal* signal)
{
jamEntry();
DropTrigImplRef * const ref = (DropTrigImplRef*)signal->getDataPtr();
Ptr<Table> tabPtr;
Ptr<Subscription> subPtr;
const Uint32 triggerId = ref->triggerId;
const Uint32 type = (triggerId >> 16) & 0x3;
c_subscriptionPool.getPtr(subPtr, ref->senderData);
c_tables.getPtr(tabPtr, subPtr.p->m_table_ptrI);
ndbrequire(tabPtr.p->m_tableId == ref->tableId);
ndbrequire(type < 3);
ndbrequire(subPtr.p->m_triggers[type] != ILLEGAL_TRIGGER_ID);
subPtr.p->m_triggers[type] = ILLEGAL_TRIGGER_ID;
ndbrequire(subPtr.p->m_outstanding_trigger);
subPtr.p->m_outstanding_trigger--;
ndbrequire(c_outstanding_drop_trig_req);
c_outstanding_drop_trig_req--;
if (subPtr.p->m_outstanding_trigger)
{
jam();
/**
* Wait for more
*/
return;
}
drop_triggers_complete(signal, subPtr);
}
void
Suma::execDROP_TRIG_IMPL_CONF(Signal* signal)
{
jamEntry();
DropTrigImplConf * const conf = (DropTrigImplConf*)signal->getDataPtr();
Ptr<Table> tabPtr;
Ptr<Subscription> subPtr;
const Uint32 triggerId = conf->triggerId;
const Uint32 type = (triggerId >> 16) & 0x3;
c_subscriptionPool.getPtr(subPtr, conf->senderData);
c_tables.getPtr(tabPtr, subPtr.p->m_table_ptrI);
ndbrequire(tabPtr.p->m_tableId == conf->tableId);
ndbrequire(type < 3);
ndbrequire(subPtr.p->m_triggers[type] != ILLEGAL_TRIGGER_ID);
subPtr.p->m_triggers[type] = ILLEGAL_TRIGGER_ID;
ndbrequire(subPtr.p->m_outstanding_trigger);
subPtr.p->m_outstanding_trigger--;
ndbrequire(c_outstanding_drop_trig_req);
c_outstanding_drop_trig_req--;
if (subPtr.p->m_outstanding_trigger)
{
jam();
/**
* Wait for more
*/
return;
}
drop_triggers_complete(signal, subPtr);
}
void
Suma::drop_triggers_complete(Signal* signal, Ptr<Subscription> subPtr)
{
switch(subPtr.p->m_trigger_state){
case Subscription::T_UNDEFINED:
case Subscription::T_CREATING:
case Subscription::T_DEFINED:
jam();
ndbrequire(false);
break;
case Subscription::T_DROPPING:
jam();
/**
*/
subPtr.p->m_trigger_state = Subscription::T_UNDEFINED;
if (!subPtr.p->m_start_req.isEmpty())
{
jam();
create_triggers(signal, subPtr);
return;
}
break;
case Subscription::T_ERROR:
jam();
Uint32 err = subPtr.p->m_errorCode;
subPtr.p->m_trigger_state = Subscription::T_UNDEFINED;
subPtr.p->m_errorCode = 0;
report_sub_start_ref(signal, subPtr, err);
break;
}
check_release_subscription(signal, subPtr);
}
/**********************************************************
* Suma participant interface
*
* Stopping and removing of subscriber
*
*/
void
Suma::execSUB_STOP_REQ(Signal* signal){
jamEntry();
ndbassert(signal->getNoOfSections() == 0);
DBUG_ENTER("Suma::execSUB_STOP_REQ");
CRASH_INSERTION(13019);
SubStopReq * const req = (SubStopReq*)signal->getDataPtr();
Uint32 senderRef = req->senderRef;
Uint32 senderData = req->senderData;
Uint32 subscriberRef = req->subscriberRef;
Uint32 subscriberData = req->subscriberData;
SubscriptionPtr subPtr;
Subscription key;
key.m_subscriptionId = req->subscriptionId;
key.m_subscriptionKey = req->subscriptionKey;
bool abortStart = (req->requestInfo & SubStopReq::RI_ABORT_START);
if (c_startup.m_restart_server_node_id == RNIL)
{
jam();
/**
* We havent started syncing yet
*/
sendSubStopRef(signal,
senderRef, senderData, SubStopRef::NotStarted);
return;
}
bool found = c_subscriptions.find(subPtr, key);
if (!found)
{
jam();
sendSubStopRef(signal,
senderRef, senderData, SubStopRef::NoSuchSubscription);
return;
}
switch(subPtr.p->m_state){
case Subscription::UNDEFINED:
jam();
ndbrequire(false);
case Subscription::DEFINING:
jam();
sendSubStopRef(signal,
senderRef, senderData, SubStopRef::Defining);
return;
case Subscription::DEFINED:
jam();
break;
}
Ptr<SubOpRecord> subOpPtr;
LocalDLFifoList<SubOpRecord> list(c_subOpPool, subPtr.p->m_stop_req);
bool empty = list.isEmpty();
if (list.seize(subOpPtr) == false)
{
jam();
sendSubStopRef(signal,
senderRef, senderData, SubStopRef::OutOfSubOpRecords);
return;
}
if (abortStart)
{
jam();
subOpPtr.p->m_opType = SubOpRecord::R_SUB_ABORT_START_REQ;
}
else
{
jam();
subOpPtr.p->m_opType = SubOpRecord::R_SUB_STOP_REQ;
}
subOpPtr.p->m_subPtrI = subPtr.i;
subOpPtr.p->m_senderRef = senderRef;
subOpPtr.p->m_senderData = senderData;
subOpPtr.p->m_subscriberRef = subscriberRef;
subOpPtr.p->m_subscriberData = subscriberData;
if (empty)
{
jam();
signal->theData[0] = SumaContinueB::SUB_STOP_REQ;
signal->theData[1] = subOpPtr.i;
signal->theData[2] = RNIL;
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 3, JBB);
}
}
void
Suma::sub_stop_req(Signal* signal)
{
jam();
Ptr<SubOpRecord> subOpPtr;
c_subOpPool.getPtr(subOpPtr, signal->theData[1]);
Ptr<Subscription> subPtr;
c_subscriptionPool.getPtr(subPtr, subOpPtr.p->m_subPtrI);
Ptr<Subscriber> ptr;
{
LocalDLList<Subscriber> list(c_subscriberPool, subPtr.p->m_subscribers);
if (signal->theData[2] == RNIL)
{
jam();
list.first(ptr);
}
else
{
jam();
list.getPtr(ptr, signal->theData[2]);
}
for (Uint32 i = 0; i<32 && !ptr.isNull(); i++, list.next(ptr))
{
if (ptr.p->m_senderRef == subOpPtr.p->m_subscriberRef &&
ptr.p->m_senderData == subOpPtr.p->m_subscriberData)
{
jam();
goto found;
}
}
}
if (ptr.isNull())
{
jam();
sendSubStopRef(signal,
subOpPtr.p->m_senderRef,
subOpPtr.p->m_senderData,
SubStopRef::NoSuchSubscriber);
check_remove_queue(signal, subPtr, subOpPtr, true, true);
return;
}
signal->theData[0] = SumaContinueB::SUB_STOP_REQ;
signal->theData[1] = subOpPtr.i;
signal->theData[2] = ptr.i;
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 3, JBB);
return;
found:
{
LocalDLList<Subscriber> list(c_subscriberPool, subPtr.p->m_subscribers);
list.remove(ptr);
/**
* NOTE: remove before...so we done send UNSUBSCRIBE to self (yuck)
*/
bool report = subPtr.p->m_options & Subscription::REPORT_SUBSCRIBE;
report_sub_stop_conf(signal, subOpPtr, ptr, report, list);
c_subscriberPool.release(ptr);
}
check_remove_queue(signal, subPtr, subOpPtr, true, true);
check_release_subscription(signal, subPtr);
}
void
Suma::check_remove_queue(Signal* signal,
Ptr<Subscription> subPtr,
Ptr<SubOpRecord> subOpPtr,
bool ishead,
bool dorelease)
{
LocalDLFifoList<SubOpRecord> list(c_subOpPool, subPtr.p->m_stop_req);
{
Ptr<SubOpRecord> tmp;
list.first(tmp);
if (ishead)
{
jam();
ndbrequire(tmp.i == subOpPtr.i);
}
else
{
jam();
ishead = (tmp.i == subOpPtr.i);
}
}
if (dorelease)
{
jam();
list.release(subOpPtr);
}
else
{
jam();
list.remove(subOpPtr);
}
if (ishead)
{
jam();
if (list.first(subOpPtr) == false)
{
jam();
c_restart.m_waiting_on_self = 1;
return;
}
// Fall through
}
else
{
jam();
return;
}
switch(subOpPtr.p->m_opType){
case SubOpRecord::R_SUB_ABORT_START_REQ:
case SubOpRecord::R_SUB_STOP_REQ:
jam();
signal->theData[0] = SumaContinueB::SUB_STOP_REQ;
signal->theData[1] = subOpPtr.i;
signal->theData[2] = RNIL;
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 3, JBB);
return;
case SubOpRecord::R_API_FAIL_REQ:
jam();
signal->theData[0] = SumaContinueB::API_FAIL_SUBSCRIPTION;
signal->theData[1] = subOpPtr.i;
signal->theData[2] = RNIL;
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 3, JBB);
return;
case SubOpRecord::R_START_ME_REQ:
jam();
sendSubCreateReq(signal, subPtr);
return;
}
}
void
Suma::report_sub_stop_conf(Signal* signal,
Ptr<SubOpRecord> subOpPtr,
Ptr<Subscriber> ptr,
bool report,
LocalDLList<Subscriber>& list)
{
jam();
CRASH_INSERTION(13020);
Uint32 senderRef = subOpPtr.p->m_senderRef;
Uint32 senderData = subOpPtr.p->m_senderData;
bool abortStart = subOpPtr.p->m_opType == SubOpRecord::R_SUB_ABORT_START_REQ;
// let subscriber know that subscrber is stopped
if (!abortStart)
{
jam();
send_sub_start_stop_event(signal, ptr, NdbDictionary::Event::_TE_STOP,
report, list);
}
SubStopConf * const conf = (SubStopConf*)signal->getDataPtrSend();
const Uint64 gci = m_max_seen_gci;
conf->senderRef= reference();
conf->senderData= senderData;
conf->gci_hi= Uint32(gci>>32);
conf->gci_lo= Uint32(gci);
sendSignal(senderRef, GSN_SUB_STOP_CONF, signal,
SubStopConf::SignalLength, JBB);
Uint32 nodeId = refToNode(ptr.p->m_senderRef);
if (c_subscriber_per_node[nodeId])
{
c_subscriber_per_node[nodeId]--;
if (c_subscriber_per_node[nodeId] == 0)
{
jam();
c_subscriber_nodes.clear(nodeId);
}
}
}
void
Suma::sendSubStopRef(Signal* signal,
Uint32 retref,
Uint32 data,
Uint32 errCode)
{
jam();
SubStopRef * ref = (SubStopRef *)signal->getDataPtrSend();
ref->senderRef = reference();
ref->errorCode = errCode;
ref->senderData = data;
sendSignal(retref, GSN_SUB_STOP_REF, signal, SubStopRef::SignalLength, JBB);
}
// report new started subscriber to all other subscribers
void
Suma::send_sub_start_stop_event(Signal *signal,
Ptr<Subscriber> ptr,
NdbDictionary::Event::_TableEvent event,
bool report,
LocalDLList<Subscriber>& list)
{
const Uint64 gci = get_current_gci(signal);
SubTableData * data = (SubTableData*)signal->getDataPtrSend();
Uint32 nodeId = refToNode(ptr.p->m_senderRef);
NdbDictionary::Event::_TableEvent other;
if (event == NdbDictionary::Event::_TE_STOP)
{
other = NdbDictionary::Event::_TE_UNSUBSCRIBE;
}
else if (event == NdbDictionary::Event::_TE_ACTIVE)
{
other = NdbDictionary::Event::_TE_SUBSCRIBE;
}
else
{
jamLine(event);
ndbrequire(false);
}
data->gci_hi = Uint32(gci >> 32);
data->gci_lo = Uint32(gci);
data->tableId = 0;
data->requestInfo = 0;
SubTableData::setOperation(data->requestInfo, event);
SubTableData::setNdbdNodeId(data->requestInfo, getOwnNodeId());
SubTableData::setReqNodeId(data->requestInfo, nodeId);
data->changeMask = 0;
data->totalLen = 0;
data->senderData = ptr.p->m_senderData;
sendSignal(ptr.p->m_senderRef, GSN_SUB_TABLE_DATA, signal,
SubTableData::SignalLength, JBB);
if (report == false)
{
return;
}
data->requestInfo = 0;
SubTableData::setOperation(data->requestInfo, other);
SubTableData::setNdbdNodeId(data->requestInfo, getOwnNodeId());
Ptr<Subscriber> tmp;
for(list.first(tmp); !tmp.isNull(); list.next(tmp))
{
jam();
SubTableData::setReqNodeId(data->requestInfo, nodeId);
data->senderData = tmp.p->m_senderData;
sendSignal(tmp.p->m_senderRef, GSN_SUB_TABLE_DATA, signal,
SubTableData::SignalLength, JBB);
ndbassert(tmp.i != ptr.i); // ptr should *NOT* be in list now
if (other != NdbDictionary::Event::_TE_UNSUBSCRIBE)
{
jam();
SubTableData::setReqNodeId(data->requestInfo,
refToNode(tmp.p->m_senderRef));
data->senderData = ptr.p->m_senderData;
sendSignal(ptr.p->m_senderRef, GSN_SUB_TABLE_DATA, signal,
SubTableData::SignalLength, JBB);
}
}
}
void
Suma::Table::createAttributeMask(AttributeMask& mask,
Suma &suma)
{
mask.clear();
for(Uint32 i = 0; i<m_noOfAttributes; i++)
mask.set(i);
}
void Suma::suma_ndbrequire(bool v) { ndbrequire(v); }
/**********************************************************
* Scan data interface
*
* Assumption: one execTRANSID_AI contains all attr info
*
*/
#define SUMA_BUF_SZ1 MAX_KEY_SIZE_IN_WORDS + MAX_TUPLE_SIZE_IN_WORDS
#define SUMA_BUF_SZ MAX_ATTRIBUTES_IN_TABLE + SUMA_BUF_SZ1
static Uint32 f_bufferLock = 0;
static Uint32 f_buffer[SUMA_BUF_SZ];
static Uint32 f_trigBufferSize = 0;
static Uint32 b_bufferLock = 0;
static Uint32 b_buffer[SUMA_BUF_SZ];
static Uint32 b_trigBufferSize = 0;
void
Suma::execTRANSID_AI(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execTRANSID_AI");
CRASH_INSERTION(13015);
TransIdAI * const data = (TransIdAI*)signal->getDataPtr();
const Uint32 opPtrI = data->connectPtr;
Uint32 length = signal->length() - 3;
if(f_bufferLock == 0){
f_bufferLock = opPtrI;
} else {
ndbrequire(f_bufferLock == opPtrI);
}
if (signal->getNoOfSections())
{
SectionHandle handle(this, signal);
SegmentedSectionPtr dataPtr;
handle.getSection(dataPtr, 0);
length = dataPtr.sz;
copy(data->attrData, dataPtr);
releaseSections(handle);
}
Ptr<SyncRecord> syncPtr;
c_syncPool.getPtr(syncPtr, (opPtrI >> 16));
Uint32 sum = 0;
Uint32 * dst = f_buffer + MAX_ATTRIBUTES_IN_TABLE;
Uint32 * headers = f_buffer;
const Uint32 * src = &data->attrData[0];
const Uint32 * const end = &src[length];
const Uint32 attribs = syncPtr.p->m_currentNoOfAttributes;
for(Uint32 i = 0; i<attribs; i++){
Uint32 tmp = * src++;
* headers++ = tmp;
Uint32 len = AttributeHeader::getDataSize(tmp);
memcpy(dst, src, 4 * len);
dst += len;
src += len;
sum += len;
}
f_trigBufferSize = sum;
ndbrequire(src == end);
if ((syncPtr.p->m_requestInfo & SubSyncReq::LM_Exclusive) == 0)
{
sendScanSubTableData(signal, syncPtr, 0);
}
DBUG_VOID_RETURN;
}
void
Suma::execKEYINFO20(Signal* signal)
{
jamEntry();
KeyInfo20* data = (KeyInfo20*)signal->getDataPtr();
const Uint32 opPtrI = data->clientOpPtr;
const Uint32 takeOver = data->scanInfo_Node;
ndbrequire(f_bufferLock == opPtrI);
Ptr<SyncRecord> syncPtr;
c_syncPool.getPtr(syncPtr, (opPtrI >> 16));
sendScanSubTableData(signal, syncPtr, takeOver);
}
void
Suma::sendScanSubTableData(Signal* signal,
Ptr<SyncRecord> syncPtr, Uint32 takeOver)
{
const Uint32 attribs = syncPtr.p->m_currentNoOfAttributes;
const Uint32 sum = f_trigBufferSize;
/**
* Send data to subscriber
*/
LinearSectionPtr ptr[3];
ptr[0].p = f_buffer;
ptr[0].sz = attribs;
ptr[1].p = f_buffer + MAX_ATTRIBUTES_IN_TABLE;
ptr[1].sz = sum;
SubscriptionPtr subPtr;
c_subscriptions.getPtr(subPtr, syncPtr.p->m_subscriptionPtrI);
/**
* Initialize signal
*/
SubTableData * sdata = (SubTableData*)signal->getDataPtrSend();
Uint32 ref = syncPtr.p->m_senderRef;
sdata->tableId = syncPtr.p->m_tableId;
sdata->senderData = syncPtr.p->m_senderData;
sdata->requestInfo = 0;
SubTableData::setOperation(sdata->requestInfo,
NdbDictionary::Event::_TE_SCAN); // Scan
sdata->gci_hi = 0; // Undefined
sdata->gci_lo = 0;
sdata->takeOver = takeOver;
#if PRINT_ONLY
ndbout_c("GSN_SUB_TABLE_DATA (scan) #attr: %d len: %d", attribs, sum);
#else
sendSignal(ref,
GSN_SUB_TABLE_DATA,
signal,
SubTableData::SignalLength, JBB,
ptr, 2);
#endif
/**
* Reset f_bufferLock
*/
f_bufferLock = 0;
}
/**********************************************************
*
* Trigger data interface
*
*/
void
Suma::execTRIG_ATTRINFO(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execTRIG_ATTRINFO");
CRASH_INSERTION(13016);
TrigAttrInfo* const trg = (TrigAttrInfo*)signal->getDataPtr();
const Uint32 trigId = trg->getTriggerId();
const Uint32 dataLen = signal->length() - TrigAttrInfo::StaticLength;
if(trg->getAttrInfoType() == TrigAttrInfo::BEFORE_VALUES){
jam();
ndbrequire(b_bufferLock == trigId);
memcpy(b_buffer + b_trigBufferSize, trg->getData(), 4 * dataLen);
b_trigBufferSize += dataLen;
// printf("before values %u %u %u\n",trigId, dataLen, b_trigBufferSize);
} else {
jam();
if(f_bufferLock == 0){
f_bufferLock = trigId;
f_trigBufferSize = 0;
b_bufferLock = trigId;
b_trigBufferSize = 0;
} else {
ndbrequire(f_bufferLock == trigId);
}
memcpy(f_buffer + f_trigBufferSize, trg->getData(), 4 * dataLen);
f_trigBufferSize += dataLen;
}
DBUG_VOID_RETURN;
}
#ifdef NODEFAIL_DEBUG2
static int theCounts[64] = {0};
#endif
Uint32
Suma::get_responsible_node(Uint32 bucket) const
{
// id will contain id to responsible suma or
// RNIL if we don't have nodegroup info yet
jam();
Uint32 node;
const Bucket* ptr= c_buckets + bucket;
for(Uint32 i = 0; i<MAX_REPLICAS; i++)
{
node= ptr->m_nodes[i];
if(c_alive_nodes.get(node))
{
#ifdef NODEFAIL_DEBUG2
theCounts[node]++;
ndbout_c("Suma:responsible n=%u, D=%u, id = %u, count=%u",
n,D, id, theCounts[node]);
#endif
return node;
}
}
return 0;
}
Uint32
Suma::get_responsible_node(Uint32 bucket, const NdbNodeBitmask& mask) const
{
jam();
Uint32 node;
const Bucket* ptr= c_buckets + bucket;
for(Uint32 i = 0; i<MAX_REPLICAS; i++)
{
node= ptr->m_nodes[i];
if(mask.get(node))
{
return node;
}
}
return 0;
}
bool
Suma::check_switchover(Uint32 bucket, Uint64 gci)
{
const Uint32 send_mask =
Bucket::BUCKET_STARTING |
Bucket::BUCKET_TAKEOVER |
Bucket::BUCKET_SHUTDOWN_TO;
bool send = c_buckets[bucket].m_state & send_mask;
ndbassert(m_switchover_buckets.get(bucket));
if(unlikely(gci > c_buckets[bucket].m_switchover_gci))
{
return send;
}
return !send;
}
static
Uint32
reformat(Signal* signal, LinearSectionPtr ptr[3],
Uint32 * src_1, Uint32 sz_1,
Uint32 * src_2, Uint32 sz_2)
{
Uint32 noOfAttrs = 0, dataLen = 0;
Uint32 * headers = signal->theData + 25;
Uint32 * dst = signal->theData + 25 + MAX_ATTRIBUTES_IN_TABLE;
ptr[0].p = headers;
ptr[1].p = dst;
while(sz_1 > 0){
Uint32 tmp = * src_1 ++;
* headers ++ = tmp;
Uint32 len = AttributeHeader::getDataSize(tmp);
memcpy(dst, src_1, 4 * len);
dst += len;
src_1 += len;
noOfAttrs++;
dataLen += len;
sz_1 -= (1 + len);
}
assert(sz_1 == 0);
ptr[0].sz = noOfAttrs;
ptr[1].sz = dataLen;
ptr[2].p = src_2;
ptr[2].sz = sz_2;
return sz_2 > 0 ? 3 : 2;
}
/**
* Pass entire pages with SUMA-trigger-data from
* TUP to SUMA to avoid extensive LongSignalMessage buffer contention
*/
void
Suma::execFIRE_TRIG_ORD_L(Signal* signal)
{
jamEntry();
ndbassert(signal->getNoOfSections() == 0);
Uint32 pageId = signal->theData[0];
Uint32 len = signal->theData[1];
if (pageId == RNIL && len == 0)
{
jam();
/**
* Out of memory
*/
out_of_buffer(signal);
return;
}
Uint32 * ptr = reinterpret_cast<Uint32*>(c_page_pool.getPtr(pageId));
while (len)
{
Uint32 * save = ptr;
Uint32 msglen = * ptr++;
Uint32 siglen = * ptr++;
Uint32 sec0len = * ptr++;
Uint32 sec1len = * ptr++;
Uint32 sec2len = * ptr++;
/**
* Copy value directly into local buffers
*/
Uint32 trigId = ((FireTrigOrd*)ptr)->getTriggerId();
memcpy(signal->theData, ptr, 4 * siglen); // signal
ptr += siglen;
memcpy(f_buffer, ptr, 4*sec0len);
ptr += sec0len;
memcpy(b_buffer, ptr, 4*sec1len);
ptr += sec1len;
memcpy(f_buffer + sec0len, ptr, 4*sec2len);
ptr += sec2len;
f_trigBufferSize = sec0len + sec2len;
b_trigBufferSize = sec1len;
f_bufferLock = trigId;
b_bufferLock = trigId;
execFIRE_TRIG_ORD(signal);
ndbrequire(ptr == save + msglen);
ndbrequire(len >= msglen);
len -= msglen;
}
m_ctx.m_mm.release_page(RT_DBTUP_PAGE, pageId);
}
void
Suma::execFIRE_TRIG_ORD(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execFIRE_TRIG_ORD");
CRASH_INSERTION(13016);
FireTrigOrd* const trg = (FireTrigOrd*)signal->getDataPtr();
const Uint32 trigId = trg->getTriggerId();
const Uint32 hashValue = trg->getHashValue();
const Uint32 gci_hi = trg->getGCI();
const Uint32 gci_lo = trg->m_gci_lo;
const Uint64 gci = gci_lo | (Uint64(gci_hi) << 32);
const Uint32 event = trg->getTriggerEvent();
const Uint32 any_value = trg->getAnyValue();
const Uint32 transId1 = trg->m_transId1;
const Uint32 transId2 = trg->m_transId2;
Ptr<Subscription> subPtr;
c_subscriptionPool.getPtr(subPtr, trigId & 0xFFFF);
ndbassert(gci > m_last_complete_gci);
if (signal->getNoOfSections())
{
jam();
ndbassert(isNdbMtLqh());
SectionHandle handle(this, signal);
ndbrequire(b_bufferLock == 0);
ndbrequire(f_bufferLock == 0);
f_bufferLock = trigId;
b_bufferLock = trigId;
SegmentedSectionPtr ptr;
handle.getSection(ptr, 0); // Keys
Uint32 sz = ptr.sz;
copy(f_buffer, ptr);
handle.getSection(ptr, 2); // After values
copy(f_buffer + sz, ptr);
f_trigBufferSize = sz + ptr.sz;
handle.getSection(ptr, 1); // Before values
copy(b_buffer, ptr);
b_trigBufferSize = ptr.sz;
releaseSections(handle);
}
jam();
ndbrequire(f_bufferLock == trigId);
/**
* Reset f_bufferLock
*/
f_bufferLock = 0;
b_bufferLock = 0;
Uint32 tableId = subPtr.p->m_tableId;
Uint32 schemaVersion =
c_tablePool.getPtr(subPtr.p->m_table_ptrI)->m_schemaVersion;
Uint32 bucket= hashValue % c_no_of_buckets;
m_max_seen_gci = (gci > m_max_seen_gci ? gci : m_max_seen_gci);
if(m_active_buckets.get(bucket) ||
(m_switchover_buckets.get(bucket) && (check_switchover(bucket, gci))))
{
m_max_sent_gci = (gci > m_max_sent_gci ? gci : m_max_sent_gci);
Uint32 sz = trg->getNoOfPrimaryKeyWords()+trg->getNoOfAfterValueWords();
ndbrequire(sz == f_trigBufferSize);
LinearSectionPtr ptr[3];
const Uint32 nptr= reformat(signal, ptr,
f_buffer, f_trigBufferSize,
b_buffer, b_trigBufferSize);
Uint32 ptrLen= 0;
for(Uint32 i =0; i < nptr; i++)
ptrLen+= ptr[i].sz;
/**
* Signal to subscriber(s)
*/
SubTableData * data = (SubTableData*)signal->getDataPtrSend();//trg;
data->gci_hi = gci_hi;
data->gci_lo = gci_lo;
data->tableId = tableId;
data->requestInfo = 0;
SubTableData::setOperation(data->requestInfo, event);
data->flags = 0;
data->anyValue = any_value;
data->totalLen = ptrLen;
data->transId1 = transId1;
data->transId2 = transId2;
{
LocalDLList<Subscriber> list(c_subscriberPool, subPtr.p->m_subscribers);
SubscriberPtr subbPtr;
for(list.first(subbPtr); !subbPtr.isNull(); list.next(subbPtr))
{
data->senderData = subbPtr.p->m_senderData;
sendSignal(subbPtr.p->m_senderRef, GSN_SUB_TABLE_DATA, signal,
SubTableData::SignalLengthWithTransId, JBB, ptr, nptr);
}
}
}
else
{
const uint buffer_header_sz = 6;
Uint32* dst;
Uint32 sz = f_trigBufferSize + b_trigBufferSize + buffer_header_sz;
if((dst = get_buffer_ptr(signal, bucket, gci, sz)))
{
* dst++ = subPtr.i;
* dst++ = schemaVersion;
* dst++ = (event << 16) | f_trigBufferSize;
* dst++ = any_value;
* dst++ = transId1;
* dst++ = transId2;
memcpy(dst, f_buffer, f_trigBufferSize << 2);
dst += f_trigBufferSize;
memcpy(dst, b_buffer, b_trigBufferSize << 2);
}
}
DBUG_VOID_RETURN;
}
void
Suma::checkMaxBufferedEpochs(Signal *signal)
{
/*
* Check if any subscribers are exceeding the MaxBufferedEpochs
*/
Ptr<Gcp_record> gcp;
jamEntry();
if (c_gcp_list.isEmpty())
{
jam();
return;
}
c_gcp_list.first(gcp);
if (ERROR_INSERTED(13037))
{
jam();
CLEAR_ERROR_INSERT_VALUE;
ndbout_c("Simulating exceeding the MaxBufferedEpochs %u(%llu,%llu,%llu)",
c_maxBufferedEpochs, m_max_seen_gci,
m_last_complete_gci, gcp.p->m_gci);
}
else if (c_gcp_list.count() < c_maxBufferedEpochs)
{
return;
}
NodeBitmask subs = gcp.p->m_subscribers;
jam();
// Disconnect lagging subscribers waiting for oldest epoch
ndbout_c("Found lagging epoch %llu", gcp.p->m_gci);
for(Uint32 nodeId = 0; nodeId < MAX_NODES; nodeId++)
{
if (subs.get(nodeId))
{
jam();
subs.clear(nodeId);
// Disconnecting node
signal->theData[0] = NDB_LE_SubscriptionStatus;
signal->theData[1] = 1; // DISCONNECTED;
signal->theData[2] = nodeId;
signal->theData[3] = (Uint32) gcp.p->m_gci;
signal->theData[4] = (Uint32) (gcp.p->m_gci >> 32);
signal->theData[5] = (Uint32) c_gcp_list.count();
signal->theData[6] = c_maxBufferedEpochs;
sendSignal(CMVMI_REF, GSN_EVENT_REP, signal, 8, JBB);
/**
* Force API_FAILREQ
*/
signal->theData[0] = nodeId;
sendSignal(QMGR_REF, GSN_API_FAILREQ, signal, 1, JBA);
}
}
}
void
Suma::execSUB_GCP_COMPLETE_REP(Signal* signal)
{
jamEntry();
ndbassert(signal->getNoOfSections() == 0);
SubGcpCompleteRep * rep = (SubGcpCompleteRep*)signal->getDataPtrSend();
Uint32 gci_hi = rep->gci_hi;
Uint32 gci_lo = rep->gci_lo;
Uint64 gci = gci_lo | (Uint64(gci_hi) << 32);
if (isNdbMtLqh() && m_gcp_rep_cnt > 1)
{
#define SSPP 0
if (SSPP)
printf("execSUB_GCP_COMPLETE_REP(%u/%u)", gci_hi, gci_lo);
jam();
Uint32 min = m_min_gcp_rep_counter_index;
Uint32 sz = NDB_ARRAY_SIZE(m_gcp_rep_counter);
for (Uint32 i = min; i != m_max_gcp_rep_counter_index; i = (i + 1) % sz)
{
jam();
if (m_gcp_rep_counter[i].m_gci == gci)
{
jam();
m_gcp_rep_counter[i].m_cnt ++;
if (m_gcp_rep_counter[i].m_cnt == m_gcp_rep_cnt)
{
jam();
/**
* Release this entry...
*/
if (i != min)
{
jam();
m_gcp_rep_counter[i] = m_gcp_rep_counter[min];
}
m_min_gcp_rep_counter_index = (min + 1) % sz;
if (SSPP)
ndbout_c(" found - complete after: (min: %u max: %u)",
m_min_gcp_rep_counter_index,
m_max_gcp_rep_counter_index);
goto found;
}
else
{
jam();
if (SSPP)
ndbout_c(" found - wait unchanged: (min: %u max: %u)",
m_min_gcp_rep_counter_index,
m_max_gcp_rep_counter_index);
return; // Wait for more...
}
}
}
/**
* Not found...
*/
Uint32 next = (m_max_gcp_rep_counter_index + 1) % sz;
ndbrequire(next != min); // ring buffer full
m_gcp_rep_counter[m_max_gcp_rep_counter_index].m_gci = gci;
m_gcp_rep_counter[m_max_gcp_rep_counter_index].m_cnt = 1;
m_max_gcp_rep_counter_index = next;
if (SSPP)
ndbout_c(" new - after: (min: %u max: %u)",
m_min_gcp_rep_counter_index,
m_max_gcp_rep_counter_index);
return;
}
found:
bool drop = false;
Uint32 flags = (m_missing_data)
? rep->flags | SubGcpCompleteRep::MISSING_DATA
: rep->flags;
if (ERROR_INSERTED(13036))
{
jam();
CLEAR_ERROR_INSERT_VALUE;
ndbout_c("Simulating out of event buffer at node failure");
flags |= SubGcpCompleteRep::MISSING_DATA;
}
#ifdef VM_TRACE
if (m_gcp_monitor == 0)
{
}
else if (gci_hi == Uint32(m_gcp_monitor >> 32))
{
ndbrequire(gci_lo == Uint32(m_gcp_monitor) + 1);
}
else
{
ndbrequire(gci_hi == Uint32(m_gcp_monitor >> 32) + 1);
ndbrequire(gci_lo == 0);
}
m_gcp_monitor = gci;
#endif
m_last_complete_gci = gci;
checkMaxBufferedEpochs(signal);
m_max_seen_gci = (gci > m_max_seen_gci ? gci : m_max_seen_gci);
/**
*
*/
if(!m_switchover_buckets.isclear())
{
bool unlock = false;
Uint32 i = m_switchover_buckets.find(0);
for(; i != Bucket_mask::NotFound; i = m_switchover_buckets.find(i + 1))
{
if(gci > c_buckets[i].m_switchover_gci)
{
Uint32 state = c_buckets[i].m_state;
m_switchover_buckets.clear(i);
printf("%u/%u (%u/%u) switchover complete bucket %d state: %x",
Uint32(gci >> 32),
Uint32(gci),
Uint32(c_buckets[i].m_switchover_gci >> 32),
Uint32(c_buckets[i].m_switchover_gci),
i, state);
if(state & Bucket::BUCKET_STARTING)
{
/**
* NR case
*/
jam();
m_active_buckets.set(i);
c_buckets[i].m_state &= ~(Uint32)Bucket::BUCKET_STARTING;
ndbout_c("starting");
m_gcp_complete_rep_count++;
unlock = true;
}
else if(state & Bucket::BUCKET_TAKEOVER)
{
/**
* NF case
*/
jam();
Bucket* bucket= c_buckets + i;
Page_pos pos= bucket->m_buffer_head;
ndbrequire(pos.m_max_gci < gci);
Buffer_page* page= c_page_pool.getPtr(pos.m_page_id);
ndbout_c("takeover %d", pos.m_page_id);
page->m_max_gci_hi = (Uint32)(pos.m_max_gci >> 32);
page->m_max_gci_lo = (Uint32)(pos.m_max_gci & 0xFFFFFFFF);
ndbassert(pos.m_max_gci != 0);
page->m_words_used = pos.m_page_pos;
page->m_next_page = RNIL;
memset(&bucket->m_buffer_head, 0, sizeof(bucket->m_buffer_head));
bucket->m_buffer_head.m_page_id = RNIL;
bucket->m_buffer_head.m_page_pos = Buffer_page::DATA_WORDS + 1;
m_active_buckets.set(i);
m_gcp_complete_rep_count++;
c_buckets[i].m_state &= ~(Uint32)Bucket::BUCKET_TAKEOVER;
}
else if (state & Bucket::BUCKET_HANDOVER)
{
/**
* NR, living node
*/
jam();
c_buckets[i].m_state &= ~(Uint32)Bucket::BUCKET_HANDOVER;
m_gcp_complete_rep_count--;
ndbout_c("handover");
}
else if (state & Bucket::BUCKET_CREATED_MASK)
{
jam();
Uint32 cnt = state >> 8;
Uint32 mask = Uint32(Bucket::BUCKET_CREATED_MASK) | (cnt << 8);
c_buckets[i].m_state &= ~mask;
flags |= SubGcpCompleteRep::ADD_CNT;
flags |= (cnt << 16);
ndbout_c("add %u %s", cnt,
state & Bucket::BUCKET_CREATED_SELF ? "self" : "other");
if (state & Bucket::BUCKET_CREATED_SELF &&
get_responsible_node(i) == getOwnNodeId())
{
jam();
m_active_buckets.set(i);
m_gcp_complete_rep_count++;
}
}
else if (state & Bucket::BUCKET_DROPPED_MASK)
{
jam();
Uint32 cnt = state >> 8;
Uint32 mask = Uint32(Bucket::BUCKET_DROPPED_MASK) | (cnt << 8);
c_buckets[i].m_state &= ~mask;
flags |= SubGcpCompleteRep::SUB_CNT;
flags |= (cnt << 16);
ndbout_c("sub %u %s", cnt,
state & Bucket::BUCKET_DROPPED_SELF ? "self" : "other");
if (state & Bucket::BUCKET_DROPPED_SELF)
{
m_active_buckets.clear(i);
drop = true;
}
}
else if (state & Bucket::BUCKET_SHUTDOWN)
{
jam();
Uint32 nodeId = c_buckets[i].m_switchover_node;
ndbrequire(nodeId == getOwnNodeId());
m_active_buckets.clear(i);
m_gcp_complete_rep_count--;
ndbout_c("shutdown handover");
c_buckets[i].m_state &= ~(Uint32)Bucket::BUCKET_SHUTDOWN;
}
else if (state & Bucket::BUCKET_SHUTDOWN_TO)
{
jam();
Uint32 nodeId = c_buckets[i].m_switchover_node;
NdbNodeBitmask nodegroup = c_nodes_in_nodegroup_mask;
nodegroup.clear(nodeId);
ndbrequire(get_responsible_node(i) == nodeId &&
get_responsible_node(i, nodegroup) == getOwnNodeId());
m_active_buckets.set(i);
m_gcp_complete_rep_count++;
ndbout_c("shutdown takover");
c_buckets[i].m_state &= ~(Uint32)Bucket::BUCKET_SHUTDOWN_TO;
}
}
}
if (m_switchover_buckets.isclear())
{
jam();
if(getNodeState().startLevel == NodeState::SL_STARTING &&
c_startup.m_handover_nodes.isclear())
{
jam();
sendSTTORRY(signal);
}
else if (getNodeState().startLevel >= NodeState::SL_STOPPING_1)
{
jam();
ndbrequire(c_shutdown.m_wait_handover);
StopMeConf * conf = CAST_PTR(StopMeConf, signal->getDataPtrSend());
conf->senderData = c_shutdown.m_senderData;
conf->senderRef = reference();
sendSignal(c_shutdown.m_senderRef, GSN_STOP_ME_CONF, signal,
StopMeConf::SignalLength, JBB);
c_shutdown.m_wait_handover = false;
infoEvent("Suma: handover complete");
}
}
if (unlock)
{
jam();
send_dict_unlock_ord(signal, DictLockReq::SumaHandOver);
}
}
if(ERROR_INSERTED(13010))
{
CLEAR_ERROR_INSERT_VALUE;
ndbout_c("Don't send GCP_COMPLETE_REP(%llu)", gci);
return;
}
/**
* Signal to subscribers
*/
rep->gci_hi = gci_hi;
rep->gci_lo = gci_lo;
rep->flags = flags;
rep->senderRef = reference();
rep->gcp_complete_rep_count = m_gcp_complete_rep_count;
if(m_gcp_complete_rep_count && !c_subscriber_nodes.isclear())
{
CRASH_INSERTION(13033);
NodeReceiverGroup rg(API_CLUSTERMGR, c_subscriber_nodes);
sendSignal(rg, GSN_SUB_GCP_COMPLETE_REP, signal,
SubGcpCompleteRep::SignalLength, JBB);
Ptr<Gcp_record> gcp;
if(c_gcp_list.seize(gcp))
{
gcp.p->m_gci = gci;
gcp.p->m_subscribers = c_subscriber_nodes;
}
else
{
char buf[100];
c_subscriber_nodes.getText(buf);
g_eventLogger->error("c_gcp_list.seize() failed: gci: %llu nodes: %s",
gci, buf);
}
}
/**
* Add GCP COMPLETE REP to buffer
*/
bool subscribers = !c_subscriber_nodes.isclear();
for(Uint32 i = 0; i<c_no_of_buckets; i++)
{
if(m_active_buckets.get(i))
continue;
if (subscribers || (c_buckets[i].m_state & Bucket::BUCKET_RESEND))
{
//Uint32* dst;
get_buffer_ptr(signal, i, gci, 0);
}
}
if(m_out_of_buffer_gci && gci > m_out_of_buffer_gci)
{
jam();
infoEvent("Reenable event buffer");
m_out_of_buffer_gci = 0;
m_missing_data = false;
}
if (unlikely(drop))
{
jam();
m_gcp_complete_rep_count = 0;
c_nodeGroup = RNIL;
c_nodes_in_nodegroup_mask.clear();
fix_nodegroup();
}
}
void
Suma::execCREATE_TAB_CONF(Signal *signal)
{
jamEntry();
DBUG_ENTER("Suma::execCREATE_TAB_CONF");
DBUG_VOID_RETURN;
}
void
Suma::execDROP_TAB_CONF(Signal *signal)
{
jamEntry();
ndbassert(signal->getNoOfSections() == 0);
DropTabConf * const conf = (DropTabConf*)signal->getDataPtr();
Uint32 senderRef= conf->senderRef;
Uint32 tableId= conf->tableId;
TablePtr tabPtr;
if (!c_tables.find(tabPtr, tableId))
{
jam();
return;
}
DBUG_PRINT("info",("drop table id: %d[i=%u]", tableId, tabPtr.i));
const Table::State old_state = tabPtr.p->m_state;
tabPtr.p->m_state = Table::DROPPED;
c_tables.remove(tabPtr);
if (senderRef != 0)
{
jam();
// dict coordinator sends info to API
const Uint64 gci = get_current_gci(signal);
SubTableData * data = (SubTableData*)signal->getDataPtrSend();
data->gci_hi = Uint32(gci >> 32);
data->gci_lo = Uint32(gci);
data->tableId = tableId;
data->requestInfo = 0;
SubTableData::setOperation(data->requestInfo,
NdbDictionary::Event::_TE_DROP);
SubTableData::setReqNodeId(data->requestInfo, refToNode(senderRef));
Ptr<Subscription> subPtr;
LocalDLList<Subscription> subList(c_subscriptionPool,
tabPtr.p->m_subscriptions);
for (subList.first(subPtr); !subPtr.isNull(); subList.next(subPtr))
{
jam();
if(subPtr.p->m_subscriptionType != SubCreateReq::TableEvent)
{
jam();
continue;
//continue in for-loop if the table is not part of
//the subscription. Otherwise, send data to subscriber.
}
if (subPtr.p->m_options & Subscription::NO_REPORT_DDL)
{
jam();
continue;
}
Ptr<Subscriber> ptr;
LocalDLList<Subscriber> list(c_subscriberPool, subPtr.p->m_subscribers);
for(list.first(ptr); !ptr.isNull(); list.next(ptr))
{
jam();
data->senderData= ptr.p->m_senderData;
sendSignal(ptr.p->m_senderRef, GSN_SUB_TABLE_DATA, signal,
SubTableData::SignalLength, JBB);
}
}
}
if (old_state == Table::DEFINING)
{
jam();
return;
}
if (tabPtr.p->m_subscriptions.isEmpty())
{
jam();
tabPtr.p->release(* this);
c_tablePool.release(tabPtr);
return;
}
else
{
/**
* check_release_subscription create a subList...
* weirdness below is to make sure that it's not created twice
*/
Ptr<Subscription> subPtr;
{
LocalDLList<Subscription> subList(c_subscriptionPool,
tabPtr.p->m_subscriptions);
subList.first(subPtr);
}
while (!subPtr.isNull())
{
Ptr<Subscription> tmp = subPtr;
{
LocalDLList<Subscription> subList(c_subscriptionPool,
tabPtr.p->m_subscriptions);
subList.next(subPtr);
}
check_release_subscription(signal, tmp);
}
}
}
/**
* This receives DICT_TAB_INFO in long signal section 1, and releases the data
* after use.
*/
void
Suma::execALTER_TAB_REQ(Signal *signal)
{
jamEntry();
AlterTabReq * const req = (AlterTabReq*)signal->getDataPtr();
Uint32 senderRef= req->senderRef;
Uint32 tableId= req->tableId;
Uint32 changeMask= req->changeMask;
TablePtr tabPtr;
// Copy DICT_TAB_INFO to local linear buffer
SectionHandle handle(this, signal);
SegmentedSectionPtr tabInfoPtr;
handle.getSection(tabInfoPtr, 0);
if (!c_tables.find(tabPtr, tableId))
{
jam();
releaseSections(handle);
return;
}
if (senderRef == 0)
{
jam();
releaseSections(handle);
return;
}
// dict coordinator sends info to API
#ifndef DBUG_OFF
ndbout_c("DICT_TAB_INFO in SUMA, tabInfoPtr.sz = %d", tabInfoPtr.sz);
SimplePropertiesSectionReader reader(handle.m_ptr[0],
getSectionSegmentPool());
reader.printAll(ndbout);
#endif
copy(b_dti_buf, tabInfoPtr);
releaseSections(handle);
LinearSectionPtr lptr[3];
lptr[0].p = b_dti_buf;
lptr[0].sz = tabInfoPtr.sz;
const Uint64 gci = get_current_gci(signal);
SubTableData * data = (SubTableData*)signal->getDataPtrSend();
data->gci_hi = Uint32(gci >> 32);
data->gci_lo = Uint32(gci);
data->tableId = tableId;
data->requestInfo = 0;
SubTableData::setOperation(data->requestInfo,
NdbDictionary::Event::_TE_ALTER);
SubTableData::setReqNodeId(data->requestInfo, refToNode(senderRef));
data->flags = 0;
data->changeMask = changeMask;
data->totalLen = tabInfoPtr.sz;
Ptr<Subscription> subPtr;
LocalDLList<Subscription> subList(c_subscriptionPool,
tabPtr.p->m_subscriptions);
for (subList.first(subPtr); !subPtr.isNull(); subList.next(subPtr))
{
if(subPtr.p->m_subscriptionType != SubCreateReq::TableEvent)
{
jam();
continue;
//continue in for-loop if the table is not part of
//the subscription. Otherwise, send data to subscriber.
}
if (subPtr.p->m_options & Subscription::NO_REPORT_DDL)
{
jam();
continue;
}
Ptr<Subscriber> ptr;
LocalDLList<Subscriber> list(c_subscriberPool, subPtr.p->m_subscribers);
for(list.first(ptr); !ptr.isNull(); list.next(ptr))
{
jam();
data->senderData= ptr.p->m_senderData;
Callback c = { 0, 0 };
sendFragmentedSignal(ptr.p->m_senderRef, GSN_SUB_TABLE_DATA, signal,
SubTableData::SignalLength, JBB, lptr, 1, c);
}
}
}
void
Suma::execSUB_GCP_COMPLETE_ACK(Signal* signal)
{
jamEntry();
ndbassert(signal->getNoOfSections() == 0);
SubGcpCompleteAck * const ack = (SubGcpCompleteAck*)signal->getDataPtr();
Uint32 gci_hi = ack->rep.gci_hi;
Uint32 gci_lo = ack->rep.gci_lo;
Uint32 senderRef = ack->rep.senderRef;
if (unlikely(signal->getLength() < SubGcpCompleteAck::SignalLength))
{
jam();
ndbassert(!ndb_check_micro_gcp(getNodeInfo(refToNode(senderRef)).m_version));
gci_lo = 0;
}
Uint64 gci = gci_lo | (Uint64(gci_hi) << 32);
m_max_seen_gci = (gci > m_max_seen_gci ? gci : m_max_seen_gci);
if (ERROR_INSERTED(13037))
{
jam();
ndbout_c("Simulating exceeding the MaxBufferedEpochs, ignoring ack");
return;
}
if (refToBlock(senderRef) == SUMA)
{
jam();
// Ack from other SUMA
Uint32 nodeId= refToNode(senderRef);
for(Uint32 i = 0; i<c_no_of_buckets; i++)
{
if(m_active_buckets.get(i) ||
(m_switchover_buckets.get(i) && (check_switchover(i, gci))) ||
(!m_switchover_buckets.get(i) && get_responsible_node(i) == nodeId))
{
release_gci(signal, i, gci);
}
}
return;
}
// Ack from User and not an ack from other SUMA, redistribute in nodegroup
Uint32 nodeId = refToNode(senderRef);
if (ERROR_INSERTED(13023))
{
ndbout_c("Throwing SUB_GCP_COMPLETE_ACK gci: %u/%u from %u",
Uint32(gci>>32), Uint32(gci), nodeId);
return;
}
jam();
Ptr<Gcp_record> gcp;
for(c_gcp_list.first(gcp); !gcp.isNull(); c_gcp_list.next(gcp))
{
if(gcp.p->m_gci == gci)
{
gcp.p->m_subscribers.clear(nodeId);
gcp.p->m_subscribers.bitAND(c_subscriber_nodes);
if(!gcp.p->m_subscribers.isclear())
{
jam();
return;
}
break;
}
}
if(gcp.isNull())
{
g_eventLogger->warning("ACK wo/ gcp record (gci: %u/%u) ref: %.8x from: %.8x",
Uint32(gci >> 32), Uint32(gci),
senderRef, signal->getSendersBlockRef());
}
else
{
c_gcp_list.release(gcp);
}
CRASH_INSERTION(13011);
if(ERROR_INSERTED(13012))
{
CLEAR_ERROR_INSERT_VALUE;
ndbout_c("Don't redistribute SUB_GCP_COMPLETE_ACK");
return;
}
ack->rep.senderRef = reference();
NodeReceiverGroup rg(SUMA, c_nodes_in_nodegroup_mask);
sendSignal(rg, GSN_SUB_GCP_COMPLETE_ACK, signal,
SubGcpCompleteAck::SignalLength, JBB);
}
/**************************************************************
*
* Removing subscription
*
*/
void
Suma::execSUB_REMOVE_REQ(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execSUB_REMOVE_REQ");
CRASH_INSERTION(13021);
const SubRemoveReq req = *(SubRemoveReq*)signal->getDataPtr();
SubscriptionPtr subPtr;
Subscription key;
key.m_subscriptionId = req.subscriptionId;
key.m_subscriptionKey = req.subscriptionKey;
if (c_startup.m_restart_server_node_id == RNIL)
{
jam();
/**
* We havent started syncing yet
*/
sendSubRemoveRef(signal, req, SubRemoveRef::NotStarted);
return;
}
bool found = c_subscriptions.find(subPtr, key);
if(!found)
{
jam();
sendSubRemoveRef(signal, req, SubRemoveRef::NoSuchSubscription);
return;
}
switch(subPtr.p->m_state){
case Subscription::UNDEFINED:
jam();
ndbrequire(false);
case Subscription::DEFINING:
jam();
sendSubRemoveRef(signal, req, SubRemoveRef::Defining);
return;
case Subscription::DEFINED:
if (subPtr.p->m_options & Subscription::MARKED_DROPPED)
{
/**
* already dropped
*/
jam();
sendSubRemoveRef(signal, req, SubRemoveRef::AlreadyDropped);
return;
}
break;
}
subPtr.p->m_options |= Subscription::MARKED_DROPPED;
check_release_subscription(signal, subPtr);
SubRemoveConf * const conf = (SubRemoveConf*)signal->getDataPtrSend();
conf->senderRef = reference();
conf->senderData = req.senderData;
conf->subscriptionId = req.subscriptionId;
conf->subscriptionKey = req.subscriptionKey;
sendSignal(req.senderRef, GSN_SUB_REMOVE_CONF, signal,
SubRemoveConf::SignalLength, JBB);
return;
}
void
Suma::check_release_subscription(Signal* signal, Ptr<Subscription> subPtr)
{
if (!subPtr.p->m_subscribers.isEmpty())
{
jam();
return;
}
if (!subPtr.p->m_start_req.isEmpty())
{
jam();
return;
}
if (!subPtr.p->m_stop_req.isEmpty())
{
jam();
return;
}
switch(subPtr.p->m_trigger_state){
case Subscription::T_UNDEFINED:
jam();
goto do_release;
case Subscription::T_CREATING:
jam();
/**
* Wait for completion
*/
return;
case Subscription::T_DEFINED:
jam();
subPtr.p->m_trigger_state = Subscription::T_DROPPING;
drop_triggers(signal, subPtr);
return;
case Subscription::T_DROPPING:
jam();
/**
* Wait for completion
*/
return;
case Subscription::T_ERROR:
jam();
/**
* Wait for completion
*/
return;
}
ndbrequire(false);
do_release:
TablePtr tabPtr;
c_tables.getPtr(tabPtr, subPtr.p->m_table_ptrI);
if (tabPtr.p->m_state == Table::DROPPED)
{
jam();
subPtr.p->m_options |= Subscription::MARKED_DROPPED;
}
if ((subPtr.p->m_options & Subscription::MARKED_DROPPED) == 0)
{
jam();
return;
}
{
LocalDLList<Subscription> list(c_subscriptionPool,
tabPtr.p->m_subscriptions);
list.remove(subPtr);
}
if (tabPtr.p->m_subscriptions.isEmpty())
{
jam();
switch(tabPtr.p->m_state){
case Table::UNDEFINED:
ndbrequire(false);
case Table::DEFINING:
break;
case Table::DEFINED:
jam();
c_tables.remove(tabPtr);
// Fall through
case Table::DROPPED:
jam();
tabPtr.p->release(* this);
c_tablePool.release(tabPtr);
};
}
c_subscriptions.release(subPtr);
}
void
Suma::sendSubRemoveRef(Signal* signal,
const SubRemoveReq& req,
Uint32 errCode)
{
jam();
DBUG_ENTER("Suma::sendSubRemoveRef");
SubRemoveRef * ref = (SubRemoveRef *)signal->getDataPtrSend();
ref->senderRef = reference();
ref->senderData = req.senderData;
ref->subscriptionId = req.subscriptionId;
ref->subscriptionKey = req.subscriptionKey;
ref->errorCode = errCode;
sendSignal(signal->getSendersBlockRef(), GSN_SUB_REMOVE_REF,
signal, SubRemoveRef::SignalLength, JBB);
DBUG_VOID_RETURN;
}
void
Suma::Table::release(Suma & suma){
jamBlock(&suma);
m_state = UNDEFINED;
}
void
Suma::SyncRecord::release(){
jam();
LocalDataBuffer<15> fragBuf(suma.c_dataBufferPool, m_fragments);
fragBuf.release();
LocalDataBuffer<15> attrBuf(suma.c_dataBufferPool, m_attributeList);
attrBuf.release();
LocalDataBuffer<15> boundBuf(suma.c_dataBufferPool, m_boundInfo);
boundBuf.release();
}
/**************************************************************
*
* Restarting remote node functions, master functionality
* (slave does nothing special)
* - triggered on INCL_NODEREQ calling startNode
* - included node will issue START_ME when it's ready to start
* the subscribers
*
*/
void
Suma::execSUMA_START_ME_REQ(Signal* signal) {
jamEntry();
Uint32 retref = signal->getSendersBlockRef();
if (c_restart.m_ref)
{
jam();
SumaStartMeRef* ref= (SumaStartMeRef*)signal->getDataPtrSend();
ref->errorCode = SumaStartMeRef::Busy;
sendSignal(retref, GSN_SUMA_START_ME_REF, signal,
SumaStartMeRef::SignalLength, JBB);
return;
}
if (getNodeState().getStarted() == false)
{
jam();
SumaStartMeRef* ref= (SumaStartMeRef*)signal->getDataPtrSend();
ref->errorCode = SumaStartMeRef::NotStarted;
sendSignal(retref, GSN_SUMA_START_ME_REF, signal,
SumaStartMeRef::SignalLength, JBB);
return;
}
Ptr<SubOpRecord> subOpPtr;
if (c_subOpPool.seize(subOpPtr) == false)
{
jam();
SumaStartMeRef* ref= (SumaStartMeRef*)signal->getDataPtrSend();
ref->errorCode = SumaStartMeRef::Busy;
sendSignal(retref, GSN_SUMA_START_ME_REF, signal,
SumaStartMeRef::SignalLength, JBB);
return;
}
subOpPtr.p->m_opType = SubOpRecord::R_START_ME_REQ;
c_restart.m_abort = 0;
c_restart.m_waiting_on_self = 0;
c_restart.m_ref = retref;
c_restart.m_max_seq = c_current_seq;
c_restart.m_subOpPtrI = subOpPtr.i;
DLHashTable<Subscription>::Iterator it;
if (c_subscriptions.first(it))
{
jam();
/**
* We only need to handle subscriptions with seq <= c_current_seq
* all subscriptions(s) created after this, will be handled by
* starting suma directly
*/
c_current_seq++;
}
copySubscription(signal, it);
}
void
Suma::copySubscription(Signal* signal, DLHashTable<Subscription>::Iterator it)
{
jam();
Ptr<SubOpRecord> subOpPtr;
c_subOpPool.getPtr(subOpPtr, c_restart.m_subOpPtrI);
Ptr<Subscription> subPtr = it.curr;
if (!subPtr.isNull())
{
jam();
c_restart.m_subPtrI = subPtr.i;
c_restart.m_bucket = it.bucket;
LocalDLFifoList<SubOpRecord> list(c_subOpPool, subPtr.p->m_stop_req);
bool empty = list.isEmpty();
list.add(subOpPtr);
if (!empty)
{
/**
* Wait for lock
*/
jam();
c_restart.m_waiting_on_self = 1;
return;
}
sendSubCreateReq(signal, subPtr);
}
else
{
jam();
SumaStartMeConf* conf = (SumaStartMeConf*)signal->getDataPtrSend();
conf->unused = 0;
sendSignal(c_restart.m_ref, GSN_SUMA_START_ME_CONF, signal,
SumaStartMeConf::SignalLength, JBB);
c_subOpPool.release(subOpPtr);
c_restart.m_ref = 0;
return;
}
}
void
Suma::sendSubCreateReq(Signal* signal, Ptr<Subscription> subPtr)
{
jam();
if (c_restart.m_abort)
{
jam();
abort_start_me(signal, subPtr, true);
return;
}
c_restart.m_waiting_on_self = 0;
SubCreateReq * req = (SubCreateReq *)signal->getDataPtrSend();
req->senderRef = reference();
req->senderData = subPtr.i;
req->subscriptionId = subPtr.p->m_subscriptionId;
req->subscriptionKey = subPtr.p->m_subscriptionKey;
req->subscriptionType = subPtr.p->m_subscriptionType;
req->tableId = subPtr.p->m_tableId;
req->schemaTransId = 0;
if (subPtr.p->m_options & Subscription::REPORT_ALL)
{
req->subscriptionType |= SubCreateReq::ReportAll;
}
if (subPtr.p->m_options & Subscription::REPORT_SUBSCRIBE)
{
req->subscriptionType |= SubCreateReq::ReportSubscribe;
}
if (subPtr.p->m_options & Subscription::NO_REPORT_DDL)
{
req->subscriptionType |= SubCreateReq::NoReportDDL;
}
if (subPtr.p->m_options & Subscription::MARKED_DROPPED)
{
req->subscriptionType |= SubCreateReq::NR_Sub_Dropped;
ndbout_c("copying dropped sub: %u", subPtr.i);
}
Ptr<Table> tabPtr;
c_tablePool.getPtr(tabPtr, subPtr.p->m_table_ptrI);
if (tabPtr.p->m_state != Table::DROPPED)
{
jam();
c_restart.m_waiting_on_self = 0;
if (!ndbd_suma_dictlock_startme(getNodeInfo(refToNode(c_restart.m_ref)).m_version))
{
jam();
/**
* Downgrade
*
* In pre suma v2, SUB_CREATE_REQ::SignalLength is one greater
* but code checks length and set a default value...
* so we dont need to do anything...
* Thank you Ms. Fortuna
*/
}
sendSignal(c_restart.m_ref, GSN_SUB_CREATE_REQ, signal,
SubCreateReq::SignalLength, JBB);
}
else
{
jam();
ndbout_c("not copying sub %u with dropped table: %u/%u",
subPtr.i,
tabPtr.p->m_tableId, tabPtr.i);
c_restart.m_waiting_on_self = 1;
SubCreateConf * conf = (SubCreateConf *)signal->getDataPtrSend();
conf->senderRef = reference();
conf->senderData = subPtr.i;
sendSignal(reference(), GSN_SUB_CREATE_CONF, signal,
SubCreateConf::SignalLength, JBB);
}
}
void
Suma::execSUB_CREATE_REF(Signal* signal)
{
jamEntry();
SubCreateRef *const ref= (SubCreateRef *)signal->getDataPtr();
Uint32 error= ref->errorCode;
{
SumaStartMeRef* ref= (SumaStartMeRef*)signal->getDataPtrSend();
ref->errorCode = error;
sendSignal(c_restart.m_ref, GSN_SUMA_START_ME_REF, signal,
SumaStartMeRef::SignalLength, JBB);
}
Ptr<Subscription> subPtr;
c_subscriptionPool.getPtr(subPtr, c_restart.m_subPtrI);
abort_start_me(signal, subPtr, true);
}
void
Suma::execSUB_CREATE_CONF(Signal* signal)
{
jamEntry();
/**
* We have lock...start all subscriber(s)
*/
Ptr<Subscription> subPtr;
c_subscriptionPool.getPtr(subPtr, c_restart.m_subPtrI);
c_restart.m_waiting_on_self = 0;
/**
* Check if we were aborted...
* this signal is sent to self in case of DROPPED subscription...
*/
if (c_restart.m_abort)
{
jam();
abort_start_me(signal, subPtr, true);
return;
}
Ptr<Table> tabPtr;
c_tablePool.getPtr(tabPtr, subPtr.p->m_table_ptrI);
Ptr<Subscriber> ptr;
if (tabPtr.p->m_state != Table::DROPPED)
{
jam();
LocalDLList<Subscriber> list(c_subscriberPool, subPtr.p->m_subscribers);
list.first(ptr);
}
else
{
jam();
ptr.setNull();
ndbout_c("not copying subscribers on sub: %u with dropped table %u/%u",
subPtr.i, tabPtr.p->m_tableId, tabPtr.i);
}
copySubscriber(signal, subPtr, ptr);
}
void
Suma::copySubscriber(Signal* signal,
Ptr<Subscription> subPtr,
Ptr<Subscriber> ptr)
{
if (!ptr.isNull())
{
jam();
SubStartReq* req = (SubStartReq*)signal->getDataPtrSend();
req->senderRef = reference();
req->senderData = ptr.i;
req->subscriptionId = subPtr.p->m_subscriptionId;
req->subscriptionKey = subPtr.p->m_subscriptionKey;
req->part = SubscriptionData::TableData;
req->subscriberData = ptr.p->m_senderData;
req->subscriberRef = ptr.p->m_senderRef;
sendSignal(c_restart.m_ref, GSN_SUB_START_REQ,
signal, SubStartReq::SignalLength, JBB);
return;
}
else
{
// remove lock from this subscription
Ptr<SubOpRecord> subOpPtr;
c_subOpPool.getPtr(subOpPtr, c_restart.m_subOpPtrI);
check_remove_queue(signal, subPtr, subOpPtr, true, false);
check_release_subscription(signal, subPtr);
DLHashTable<Subscription>::Iterator it;
it.curr = subPtr;
it.bucket = c_restart.m_bucket;
c_subscriptions.next(it);
copySubscription(signal, it);
}
}
void
Suma::execSUB_START_CONF(Signal* signal)
{
jamEntry();
SubStartConf * const conf = (SubStartConf*)signal->getDataPtr();
Ptr<Subscription> subPtr;
c_subscriptionPool.getPtr(subPtr, c_restart.m_subPtrI);
Ptr<Subscriber> ptr;
c_subscriberPool.getPtr(ptr, conf->senderData);
LocalDLList<Subscriber> list(c_subscriberPool, subPtr.p->m_subscribers);
list.next(ptr);
copySubscriber(signal, subPtr, ptr);
}
void
Suma::execSUB_START_REF(Signal* signal)
{
jamEntry();
SubStartRef * sig = (SubStartRef*)signal->getDataPtr();
Uint32 errorCode = sig->errorCode;
{
SumaStartMeRef* ref= (SumaStartMeRef*)signal->getDataPtrSend();
ref->errorCode = errorCode;
sendSignal(c_restart.m_ref, GSN_SUMA_START_ME_REF, signal,
SumaStartMeRef::SignalLength, JBB);
}
Ptr<Subscription> subPtr;
c_subscriptionPool.getPtr(subPtr, c_restart.m_subPtrI);
abort_start_me(signal, subPtr, true);
}
void
Suma::abort_start_me(Signal* signal, Ptr<Subscription> subPtr,
bool lockowner)
{
Ptr<SubOpRecord> subOpPtr;
c_subOpPool.getPtr(subOpPtr, c_restart.m_subOpPtrI);
check_remove_queue(signal, subPtr, subOpPtr, lockowner, true);
check_release_subscription(signal, subPtr);
c_restart.m_ref = 0;
}
void
Suma::execSUMA_HANDOVER_REQ(Signal* signal)
{
jamEntry();
DBUG_ENTER("Suma::execSUMA_HANDOVER_REQ");
// Uint32 sumaRef = signal->getSendersBlockRef();
const SumaHandoverReq * req = CAST_CONSTPTR(SumaHandoverReq,
signal->getDataPtr());
Uint32 gci = req->gci;
Uint32 nodeId = req->nodeId;
Uint32 new_gci = Uint32(m_last_complete_gci >> 32) + MAX_CONCURRENT_GCP + 1;
Uint32 requestType = req->requestType;
if (!ndbd_suma_stop_me(getNodeInfo(nodeId).m_version))
{
jam();
requestType = SumaHandoverReq::RT_START_NODE;
}
Uint32 start_gci = (gci > new_gci ? gci : new_gci);
// mark all active buckets really belonging to restarting SUMA
Bucket_mask tmp;
if (requestType == SumaHandoverReq::RT_START_NODE)
{
jam();
c_alive_nodes.set(nodeId);
if (DBG_3R)
ndbout_c("%u c_alive_nodes.set(%u)", __LINE__, nodeId);
for( Uint32 i = 0; i < c_no_of_buckets; i++)
{
if(get_responsible_node(i) == nodeId)
{
if (m_active_buckets.get(i))
{
// I'm running this bucket but it should really be the restarted node
tmp.set(i);
m_active_buckets.clear(i);
m_switchover_buckets.set(i);
c_buckets[i].m_switchover_gci = (Uint64(start_gci) << 32) - 1;
c_buckets[i].m_state |= Bucket::BUCKET_HANDOVER;
c_buckets[i].m_switchover_node = nodeId;
ndbout_c("prepare to handover bucket: %d", i);
}
else if(m_switchover_buckets.get(i))
{
ndbout_c("dont handover bucket: %d %d", i, nodeId);
}
}
}
}
else if (requestType == SumaHandoverReq::RT_STOP_NODE)
{
jam();
for( Uint32 i = 0; i < c_no_of_buckets; i++)
{
NdbNodeBitmask nodegroup = c_nodes_in_nodegroup_mask;
nodegroup.clear(nodeId);
if(get_responsible_node(i) == nodeId &&
get_responsible_node(i, nodegroup) == getOwnNodeId())
{
// I'm will be running this bucket when nodeId shutdown
jam();
tmp.set(i);
m_switchover_buckets.set(i);
c_buckets[i].m_switchover_gci = (Uint64(start_gci) << 32) - 1;
c_buckets[i].m_state |= Bucket::BUCKET_SHUTDOWN_TO;
c_buckets[i].m_switchover_node = nodeId;
ndbout_c("prepare to takeover bucket: %d", i);
}
}
}
else
{
jam();
goto ref;
}
{
SumaHandoverConf *conf= CAST_PTR(SumaHandoverConf,signal->getDataPtrSend());
tmp.copyto(BUCKET_MASK_SIZE, conf->theBucketMask);
conf->gci = start_gci;
conf->nodeId = getOwnNodeId();
conf->requestType = requestType;
sendSignal(calcSumaBlockRef(nodeId), GSN_SUMA_HANDOVER_CONF, signal,
SumaHandoverConf::SignalLength, JBB);
}
DBUG_VOID_RETURN;
ref:
signal->theData[0] = 111;
signal->theData[1] = getOwnNodeId();
signal->theData[2] = nodeId;
sendSignal(calcSumaBlockRef(nodeId), GSN_SUMA_HANDOVER_REF, signal, 3, JBB);
DBUG_VOID_RETURN;
}
// only run on all but restarting suma
void
Suma::execSUMA_HANDOVER_REF(Signal* signal)
{
ndbrequire(false);
}
void
Suma::execSUMA_HANDOVER_CONF(Signal* signal) {
jamEntry();
DBUG_ENTER("Suma::execSUMA_HANDOVER_CONF");
const SumaHandoverConf * conf = CAST_CONSTPTR(SumaHandoverConf,
signal->getDataPtr());
CRASH_INSERTION(13043);
Uint32 gci = conf->gci;
Uint32 nodeId = conf->nodeId;
Uint32 requestType = conf->requestType;
Bucket_mask tmp;
tmp.assign(BUCKET_MASK_SIZE, conf->theBucketMask);
#ifdef HANDOVER_DEBUG
ndbout_c("Suma::execSUMA_HANDOVER_CONF, gci = %u", gci);
#endif
if (!ndbd_suma_stop_me(getNodeInfo(nodeId).m_version))
{
jam();
requestType = SumaHandoverReq::RT_START_NODE;
}
if (requestType == SumaHandoverReq::RT_START_NODE)
{
jam();
for (Uint32 i = 0; i < c_no_of_buckets; i++)
{
if (tmp.get(i))
{
if (DBG_3R)
ndbout_c("%u : %u %u", i, get_responsible_node(i), getOwnNodeId());
ndbrequire(get_responsible_node(i) == getOwnNodeId());
// We should run this bucket, but _nodeId_ is
c_buckets[i].m_switchover_gci = (Uint64(gci) << 32) - 1;
c_buckets[i].m_state |= Bucket::BUCKET_STARTING;
}
}
char buf[255];
tmp.getText(buf);
infoEvent("Suma: handover from node %u gci: %u buckets: %s (%u)",
nodeId, gci, buf, c_no_of_buckets);
g_eventLogger->info("Suma: handover from node %u gci: %u buckets: %s (%u)",
nodeId, gci, buf, c_no_of_buckets);
m_switchover_buckets.bitOR(tmp);
c_startup.m_handover_nodes.clear(nodeId);
DBUG_VOID_RETURN;
}
else if (requestType == SumaHandoverReq::RT_STOP_NODE)
{
jam();
for (Uint32 i = 0; i < c_no_of_buckets; i++)
{
if (tmp.get(i))
{
ndbrequire(get_responsible_node(i) == getOwnNodeId());
// We should run this bucket, but _nodeId_ is
c_buckets[i].m_switchover_node = getOwnNodeId();
c_buckets[i].m_switchover_gci = (Uint64(gci) << 32) - 1;
c_buckets[i].m_state |= Bucket::BUCKET_SHUTDOWN;
}
}
char buf[255];
tmp.getText(buf);
infoEvent("Suma: handover to node %u gci: %u buckets: %s (%u)",
nodeId, gci, buf, c_no_of_buckets);
g_eventLogger->info("Suma: handover to node %u gci: %u buckets: %s (%u)",
nodeId, gci, buf, c_no_of_buckets);
m_switchover_buckets.bitOR(tmp);
c_startup.m_handover_nodes.clear(nodeId);
DBUG_VOID_RETURN;
}
}
void
Suma::execSTOP_ME_REQ(Signal* signal)
{
jam();
StopMeReq req = * CAST_CONSTPTR(StopMeReq, signal->getDataPtr());
ndbrequire(refToNode(req.senderRef) == getOwnNodeId());
ndbrequire(c_shutdown.m_wait_handover == false);
c_shutdown.m_wait_handover = true;
c_shutdown.m_senderRef = req.senderRef;
c_shutdown.m_senderData = req.senderData;
for (Uint32 i = c_nodes_in_nodegroup_mask.find(0);
i != c_nodes_in_nodegroup_mask.NotFound ;
i = c_nodes_in_nodegroup_mask.find(i + 1))
{
/**
* Check that all SUMA nodes support graceful shutdown...
* and it's too late to stop it...
* Shutdown instead...
*/
if (!ndbd_suma_stop_me(getNodeInfo(i).m_version))
{
jam();
char buf[255];
BaseString::snprintf(buf, sizeof(buf),
"Not all versions support graceful shutdown (suma)."
" Shutdown directly instead");
progError(__LINE__,
NDBD_EXIT_GRACEFUL_SHUTDOWN_ERROR,
buf);
ndbrequire(false);
}
}
send_handover_req(signal, SumaHandoverReq::RT_STOP_NODE);
}
#ifdef NOT_USED
static
NdbOut&
operator<<(NdbOut & out, const Suma::Page_pos & pos)
{
out << "[ Page_pos:"
<< " m_page_id: " << pos.m_page_id
<< " m_page_pos: " << pos.m_page_pos
<< " m_max_gci: " << pos.m_max_gci
<< " ]";
return out;
}
#endif
Uint32*
Suma::get_buffer_ptr(Signal* signal, Uint32 buck, Uint64 gci, Uint32 sz)
{
sz += 1; // len
Bucket* bucket= c_buckets+buck;
Page_pos pos= bucket->m_buffer_head;
Buffer_page* page = 0;
Uint32 *ptr = 0;
if (likely(pos.m_page_id != RNIL))
{
page= c_page_pool.getPtr(pos.m_page_id);
ptr= page->m_data + pos.m_page_pos;
}
const bool same_gci = (gci == pos.m_last_gci) && (!ERROR_INSERTED(13022));
pos.m_page_pos += sz;
pos.m_last_gci = gci;
Uint64 max = pos.m_max_gci > gci ? pos.m_max_gci : gci;
if(likely(same_gci && pos.m_page_pos <= Buffer_page::DATA_WORDS))
{
pos.m_max_gci = max;
bucket->m_buffer_head = pos;
* ptr++ = (0x8000 << 16) | sz; // Same gci
return ptr;
}
else if(pos.m_page_pos + Buffer_page::GCI_SZ32 <= Buffer_page::DATA_WORDS)
{
loop:
pos.m_max_gci = max;
pos.m_page_pos += Buffer_page::GCI_SZ32;
bucket->m_buffer_head = pos;
* ptr++ = (sz + Buffer_page::GCI_SZ32);
* ptr++ = (Uint32)(gci >> 32);
* ptr++ = (Uint32)(gci & 0xFFFFFFFF);
return ptr;
}
else
{
/**
* new page
* 1) save header on last page
* 2) seize new page
*/
Uint32 next;
if(unlikely((next= seize_page()) == RNIL))
{
/**
* Out of buffer
*/
out_of_buffer(signal);
return 0;
}
if(likely(pos.m_page_id != RNIL))
{
page->m_max_gci_hi = (Uint32)(pos.m_max_gci >> 32);
page->m_max_gci_lo = (Uint32)(pos.m_max_gci & 0xFFFFFFFF);
page->m_words_used = pos.m_page_pos - sz;
page->m_next_page= next;
ndbassert(pos.m_max_gci != 0);
}
else
{
bucket->m_buffer_tail = next;
}
memset(&pos, 0, sizeof(pos));
pos.m_page_id = next;
pos.m_page_pos = sz;
pos.m_last_gci = gci;
page= c_page_pool.getPtr(pos.m_page_id);
page->m_next_page= RNIL;
ptr= page->m_data;
goto loop; //
}
}
void
Suma::out_of_buffer(Signal* signal)
{
if(m_out_of_buffer_gci)
{
return;
}
m_out_of_buffer_gci = m_last_complete_gci - 1;
infoEvent("Out of event buffer: nodefailure will cause event failures");
m_missing_data = false;
out_of_buffer_release(signal, 0);
}
void
Suma::out_of_buffer_release(Signal* signal, Uint32 buck)
{
Bucket* bucket= c_buckets+buck;
Uint32 tail= bucket->m_buffer_tail;
if(tail != RNIL)
{
Buffer_page* page= c_page_pool.getPtr(tail);
bucket->m_buffer_tail = page->m_next_page;
free_page(tail, page);
signal->theData[0] = SumaContinueB::OUT_OF_BUFFER_RELEASE;
signal->theData[1] = buck;
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 2, JBB);
return;
}
/**
* Clear head
*/
bucket->m_buffer_head.m_page_id = RNIL;
bucket->m_buffer_head.m_page_pos = Buffer_page::DATA_WORDS + 1;
buck++;
if(buck != c_no_of_buckets)
{
signal->theData[0] = SumaContinueB::OUT_OF_BUFFER_RELEASE;
signal->theData[1] = buck;
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 2, JBB);
return;
}
/**
* Finished will all release
* prepare for inclusion
*/
m_out_of_buffer_gci = m_max_seen_gci > m_last_complete_gci
? m_max_seen_gci : m_last_complete_gci;
m_missing_data = false;
}
Uint32
Suma::seize_page()
{
if (ERROR_INSERTED(13038))
{
jam();
CLEAR_ERROR_INSERT_VALUE;
ndbout_c("Simulating out of event buffer");
m_out_of_buffer_gci = m_max_seen_gci;
}
if(unlikely(m_out_of_buffer_gci))
{
return RNIL;
}
loop:
Ptr<Page_chunk> ptr;
Uint32 ref= m_first_free_page;
if(likely(ref != RNIL))
{
m_first_free_page = (c_page_pool.getPtr(ref))->m_next_page;
Uint32 chunk = (c_page_pool.getPtr(ref))->m_page_chunk_ptr_i;
c_page_chunk_pool.getPtr(ptr, chunk);
ndbassert(ptr.p->m_free);
ptr.p->m_free--;
return ref;
}
if(!c_page_chunk_pool.seize(ptr))
return RNIL;
Uint32 count = 16;
m_ctx.m_mm.alloc_pages(RT_DBTUP_PAGE, &ref, &count, 1);
if (count == 0)
return RNIL;
ndbout_c("alloc_chunk(%d %d) - ", ref, count);
m_first_free_page = ptr.p->m_page_id = ref;
ptr.p->m_size = count;
ptr.p->m_free = count;
Buffer_page* page;
LINT_INIT(page);
for(Uint32 i = 0; i<count; i++)
{
page = c_page_pool.getPtr(ref);
page->m_page_state= SUMA_SEQUENCE;
page->m_page_chunk_ptr_i = ptr.i;
page->m_next_page = ++ref;
}
page->m_next_page = RNIL;
goto loop;
}
void
Suma::free_page(Uint32 page_id, Buffer_page* page)
{
Ptr<Page_chunk> ptr;
ndbrequire(page->m_page_state == SUMA_SEQUENCE);
Uint32 chunk= page->m_page_chunk_ptr_i;
c_page_chunk_pool.getPtr(ptr, chunk);
ptr.p->m_free ++;
page->m_next_page = m_first_free_page;
ndbrequire(ptr.p->m_free <= ptr.p->m_size);
m_first_free_page = page_id;
}
void
Suma::release_gci(Signal* signal, Uint32 buck, Uint64 gci)
{
Bucket* bucket= c_buckets+buck;
Uint32 tail= bucket->m_buffer_tail;
Page_pos head= bucket->m_buffer_head;
Uint64 max_acked = bucket->m_max_acked_gci;
const Uint32 mask = Bucket::BUCKET_TAKEOVER | Bucket::BUCKET_RESEND;
if(unlikely(bucket->m_state & mask))
{
jam();
ndbout_c("release_gci(%d, %u/%u) 0x%x-> node failure -> abort",
buck, Uint32(gci >> 32), Uint32(gci), bucket->m_state);
return;
}
bucket->m_max_acked_gci = (max_acked > gci ? max_acked : gci);
if(unlikely(tail == RNIL))
{
return;
}
if(tail == head.m_page_id)
{
if(gci >= head.m_max_gci)
{
jam();
if (ERROR_INSERTED(13034))
{
jam();
SET_ERROR_INSERT_VALUE(13035);
return;
}
if (ERROR_INSERTED(13035))
{
CLEAR_ERROR_INSERT_VALUE;
NodeReceiverGroup rg(CMVMI, c_nodes_in_nodegroup_mask);
rg.m_nodes.clear(getOwnNodeId());
signal->theData[0] = 9999;
sendSignal(rg, GSN_NDB_TAMPER, signal, 1, JBA);
return;
}
head.m_page_pos = 0;
head.m_max_gci = gci;
head.m_last_gci = 0;
bucket->m_buffer_head = head;
}
return;
}
else
{
jam();
Buffer_page* page= c_page_pool.getPtr(tail);
Uint64 max_gci = page->m_max_gci_lo | (Uint64(page->m_max_gci_hi) << 32);
Uint32 next_page = page->m_next_page;
ndbassert(max_gci != 0);
if(gci >= max_gci)
{
jam();
free_page(tail, page);
bucket->m_buffer_tail = next_page;
signal->theData[0] = SumaContinueB::RELEASE_GCI;
signal->theData[1] = buck;
signal->theData[2] = (Uint32)(gci >> 32);
signal->theData[3] = (Uint32)(gci & 0xFFFFFFFF);
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 4, JBB);
return;
}
else
{
//ndbout_c("do nothing...");
}
}
}
static Uint32 g_cnt = 0;
void
Suma::start_resend(Signal* signal, Uint32 buck)
{
printf("start_resend(%d, ", buck);
/**
* Resend from m_max_acked_gci + 1 until max_gci + 1
*/
Bucket* bucket= c_buckets + buck;
Page_pos pos= bucket->m_buffer_head;
if(m_out_of_buffer_gci)
{
Ptr<Gcp_record> gcp;
c_gcp_list.last(gcp);
signal->theData[0] = NDB_LE_SubscriptionStatus;
signal->theData[1] = 2; // INCONSISTENT;
signal->theData[2] = 0; // Not used
signal->theData[3] = (Uint32) pos.m_max_gci;
signal->theData[4] = (Uint32) (gcp.p->m_gci >> 32);
sendSignal(CMVMI_REF, GSN_EVENT_REP, signal, 5, JBB);
m_missing_data = true;
return;
}
if(pos.m_page_id == RNIL)
{
jam();
m_active_buckets.set(buck);
m_gcp_complete_rep_count ++;
ndbout_c("empty bucket(RNIL) -> active max_acked: %u/%u max_gci: %u/%u",
Uint32(bucket->m_max_acked_gci >> 32),
Uint32(bucket->m_max_acked_gci),
Uint32(pos.m_max_gci >> 32),
Uint32(pos.m_max_gci));
return;
}
Uint64 min= bucket->m_max_acked_gci + 1;
Uint64 max = m_max_seen_gci;
ndbrequire(max <= m_max_seen_gci);
if(min > max)
{
ndbrequire(pos.m_page_id == bucket->m_buffer_tail);
m_active_buckets.set(buck);
m_gcp_complete_rep_count ++;
ndbout_c("empty bucket (%u/%u %u/%u) -> active",
Uint32(min >> 32), Uint32(min),
Uint32(max >> 32), Uint32(max));
return;
}
g_cnt = 0;
bucket->m_state |= (Bucket::BUCKET_TAKEOVER | Bucket::BUCKET_RESEND);
bucket->m_switchover_node = get_responsible_node(buck);
bucket->m_switchover_gci = max;
m_switchover_buckets.set(buck);
signal->theData[0] = SumaContinueB::RESEND_BUCKET;
signal->theData[1] = buck;
signal->theData[2] = (Uint32)(min >> 32);
signal->theData[3] = 0;
signal->theData[4] = 0;
signal->theData[5] = (Uint32)(min & 0xFFFFFFFF);
signal->theData[6] = 0;
sendSignal(reference(), GSN_CONTINUEB, signal, 7, JBB);
ndbout_c("min: %u/%u - max: %u/%u) page: %d",
Uint32(min >> 32), Uint32(min), Uint32(max >> 32), Uint32(max),
bucket->m_buffer_tail);
ndbrequire(max >= min);
}
void
Suma::resend_bucket(Signal* signal, Uint32 buck, Uint64 min_gci,
Uint32 pos, Uint64 last_gci)
{
Bucket* bucket= c_buckets+buck;
Uint32 tail= bucket->m_buffer_tail;
Buffer_page* page= c_page_pool.getPtr(tail);
Uint64 max_gci = page->m_max_gci_lo | (Uint64(page->m_max_gci_hi) << 32);
Uint32 next_page = page->m_next_page;
Uint32 *ptr = page->m_data + pos;
Uint32 *end = page->m_data + page->m_words_used;
bool delay = false;
ndbrequire(tail != RNIL);
if(tail == bucket->m_buffer_head.m_page_id)
{
max_gci= bucket->m_buffer_head.m_max_gci;
end= page->m_data + bucket->m_buffer_head.m_page_pos;
next_page= RNIL;
if(ptr == end)
{
delay = true;
goto next;
}
}
else if(pos == 0 && min_gci > max_gci)
{
free_page(tail, page);
tail = bucket->m_buffer_tail = next_page;
goto next;
}
#if 0
for(Uint32 i = 0; i<page->m_words_used; i++)
{
printf("%.8x ", page->m_data[i]);
if(((i + 1) % 8) == 0)
printf("\n");
}
printf("\n");
#endif
while(ptr < end)
{
Uint32 *src = ptr;
Uint32 tmp = * src++;
Uint32 sz = tmp & 0xFFFF;
ptr += sz;
if(! (tmp & (0x8000 << 16)))
{
ndbrequire(sz >= Buffer_page::GCI_SZ32);
sz -= Buffer_page::GCI_SZ32;
Uint32 last_gci_hi = * src++;
Uint32 last_gci_lo = * src++;
last_gci = last_gci_lo | (Uint64(last_gci_hi) << 32);
}
else
{
ndbrequire(ptr - sz > page->m_data);
}
if(last_gci < min_gci)
{
continue;
}
ndbrequire(sz);
sz --; // remove *len* part of sz
if(sz == 0)
{
SubGcpCompleteRep * rep = (SubGcpCompleteRep*)signal->getDataPtrSend();
rep->gci_hi = (Uint32)(last_gci >> 32);
rep->gci_lo = (Uint32)(last_gci & 0xFFFFFFFF);
rep->flags = (m_missing_data)
? SubGcpCompleteRep::MISSING_DATA
: 0;
rep->senderRef = reference();
rep->gcp_complete_rep_count = 1;
if (ERROR_INSERTED(13036))
{
jam();
CLEAR_ERROR_INSERT_VALUE;
ndbout_c("Simulating out of event buffer at node failure");
rep->flags |= SubGcpCompleteRep::MISSING_DATA;
}
char buf[255];
c_subscriber_nodes.getText(buf);
if (g_cnt)
{
ndbout_c("resending GCI: %u/%u rows: %d -> %s",
Uint32(last_gci >> 32), Uint32(last_gci), g_cnt, buf);
}
g_cnt = 0;
NodeReceiverGroup rg(API_CLUSTERMGR, c_subscriber_nodes);
sendSignal(rg, GSN_SUB_GCP_COMPLETE_REP, signal,
SubGcpCompleteRep::SignalLength, JBB);
}
else
{
const uint buffer_header_sz = 6;
g_cnt++;
Uint32 subPtrI = * src++ ;
Uint32 schemaVersion = * src++;
Uint32 event = * src >> 16;
Uint32 sz_1 = (* src ++) & 0xFFFF;
Uint32 any_value = * src++;
Uint32 transId1 = * src++;
Uint32 transId2 = * src++;
ndbassert(sz - buffer_header_sz >= sz_1);
LinearSectionPtr ptr[3];
const Uint32 nptr= reformat(signal, ptr,
src, sz_1,
src + sz_1, sz - buffer_header_sz - sz_1);
Uint32 ptrLen= 0;
for(Uint32 i =0; i < nptr; i++)
ptrLen+= ptr[i].sz;
/**
* Signal to subscriber(s)
*/
Ptr<Subscription> subPtr;
c_subscriptionPool.getPtr(subPtr, subPtrI);
Ptr<Table> tabPtr;
c_tablePool.getPtr(tabPtr, subPtr.p->m_table_ptrI);
Uint32 table = subPtr.p->m_tableId;
if (table_version_major(tabPtr.p->m_schemaVersion) ==
table_version_major(schemaVersion))
{
SubTableData * data = (SubTableData*)signal->getDataPtrSend();//trg;
data->gci_hi = (Uint32)(last_gci >> 32);
data->gci_lo = (Uint32)(last_gci & 0xFFFFFFFF);
data->tableId = table;
data->requestInfo = 0;
SubTableData::setOperation(data->requestInfo, event);
data->flags = 0;
data->anyValue = any_value;
data->totalLen = ptrLen;
data->transId1 = transId1;
data->transId2 = transId2;
{
LocalDLList<Subscriber> list(c_subscriberPool,
subPtr.p->m_subscribers);
SubscriberPtr subbPtr;
for(list.first(subbPtr); !subbPtr.isNull(); list.next(subbPtr))
{
data->senderData = subbPtr.p->m_senderData;
sendSignal(subbPtr.p->m_senderRef, GSN_SUB_TABLE_DATA, signal,
SubTableData::SignalLengthWithTransId, JBB, ptr, nptr);
}
}
}
}
break;
}
if(ptr == end && (tail != bucket->m_buffer_head.m_page_id))
{
/**
* release...
*/
free_page(tail, page);
tail = bucket->m_buffer_tail = next_page;
pos = 0;
last_gci = 0;
}
else
{
pos = Uint32(ptr - page->m_data);
}
next:
if(tail == RNIL)
{
bucket->m_state &= ~(Uint32)Bucket::BUCKET_RESEND;
ndbassert(! (bucket->m_state & Bucket::BUCKET_TAKEOVER));
ndbout_c("resend done...");
return;
}
signal->theData[0] = SumaContinueB::RESEND_BUCKET;
signal->theData[1] = buck;
signal->theData[2] = (Uint32)(min_gci >> 32);
signal->theData[3] = pos;
signal->theData[4] = (Uint32)(last_gci >> 32);
signal->theData[5] = (Uint32)(min_gci & 0xFFFFFFFF);
signal->theData[6] = (Uint32)(last_gci & 0xFFFFFFFF);
if(!delay)
sendSignal(SUMA_REF, GSN_CONTINUEB, signal, 7, JBB);
else
sendSignalWithDelay(SUMA_REF, GSN_CONTINUEB, signal, 10, 7);
}
void
Suma::execGCP_PREPARE(Signal *signal)
{
jamEntry();
const GCPPrepare *prep = (const GCPPrepare *)signal->getDataPtr();
m_current_gci = prep->gci_lo | (Uint64(prep->gci_hi) << 32);
}
Uint64
Suma::get_current_gci(Signal*)
{
return m_current_gci;
}
void
Suma::execCREATE_NODEGROUP_IMPL_REQ(Signal* signal)
{
CreateNodegroupImplReq reqCopy = *(CreateNodegroupImplReq*)
signal->getDataPtr();
CreateNodegroupImplReq *req = &reqCopy;
Uint32 err = 0;
Uint32 rt = req->requestType;
NdbNodeBitmask tmp;
for (Uint32 i = 0; i<NDB_ARRAY_SIZE(req->nodes) && req->nodes[i]; i++)
{
tmp.set(req->nodes[i]);
}
Uint32 cnt = tmp.count();
Uint32 group = req->nodegroupId;
switch(rt){
case CreateNodegroupImplReq::RT_ABORT:
jam();
break;
case CreateNodegroupImplReq::RT_PARSE:
jam();
break;
case CreateNodegroupImplReq::RT_PREPARE:
jam();
break;
case CreateNodegroupImplReq::RT_COMMIT:
jam();
break;
case CreateNodegroupImplReq::RT_COMPLETE:
jam();
CRASH_INSERTION(13043);
Uint64 gci = (Uint64(req->gci_hi) << 32) | req->gci_lo;
ndbrequire(gci > m_last_complete_gci);
Uint32 state = 0;
if (c_nodeGroup != RNIL)
{
jam();
NdbNodeBitmask check = tmp;
check.bitAND(c_nodes_in_nodegroup_mask);
ndbrequire(check.isclear());
ndbrequire(c_nodeGroup != group);
ndbrequire(cnt == c_nodes_in_nodegroup_mask.count());
state = Bucket::BUCKET_CREATED_OTHER;
}
else if (tmp.get(getOwnNodeId()))
{
jam();
c_nodeGroup = group;
c_nodes_in_nodegroup_mask.assign(tmp);
fix_nodegroup();
state = Bucket::BUCKET_CREATED_SELF;
}
if (state != 0)
{
for (Uint32 i = 0; i<c_no_of_buckets; i++)
{
jam();
m_switchover_buckets.set(i);
c_buckets[i].m_switchover_gci = gci - 1; // start from gci
c_buckets[i].m_state = state | (c_no_of_buckets << 8);
}
}
}
{
CreateNodegroupImplConf* conf =
(CreateNodegroupImplConf*)signal->getDataPtrSend();
conf->senderRef = reference();
conf->senderData = req->senderData;
sendSignal(req->senderRef, GSN_CREATE_NODEGROUP_IMPL_CONF, signal,
CreateNodegroupImplConf::SignalLength, JBB);
}
return;
//error:
CreateNodegroupImplRef *ref =
(CreateNodegroupImplRef*)signal->getDataPtrSend();
ref->senderRef = reference();
ref->senderData = req->senderData;
ref->errorCode = err;
sendSignal(req->senderRef, GSN_CREATE_NODEGROUP_IMPL_REF, signal,
CreateNodegroupImplRef::SignalLength, JBB);
return;
}
void
Suma::execDROP_NODEGROUP_IMPL_REQ(Signal* signal)
{
DropNodegroupImplReq reqCopy = *(DropNodegroupImplReq*)
signal->getDataPtr();
DropNodegroupImplReq *req = &reqCopy;
Uint32 err = 0;
Uint32 rt = req->requestType;
Uint32 group = req->nodegroupId;
switch(rt){
case DropNodegroupImplReq::RT_ABORT:
jam();
break;
case DropNodegroupImplReq::RT_PARSE:
jam();
break;
case DropNodegroupImplReq::RT_PREPARE:
jam();
break;
case DropNodegroupImplReq::RT_COMMIT:
jam();
break;
case DropNodegroupImplReq::RT_COMPLETE:
jam();
CRASH_INSERTION(13043);
Uint64 gci = (Uint64(req->gci_hi) << 32) | req->gci_lo;
ndbrequire(gci > m_last_complete_gci);
Uint32 state;
if (c_nodeGroup != group)
{
jam();
state = Bucket::BUCKET_DROPPED_OTHER;
break;
}
else
{
jam();
state = Bucket::BUCKET_DROPPED_SELF;
}
for (Uint32 i = 0; i<c_no_of_buckets; i++)
{
jam();
m_switchover_buckets.set(i);
if (c_buckets[i].m_state != 0)
{
jamLine(c_buckets[i].m_state);
ndbout_c("c_buckets[%u].m_state: %u", i, c_buckets[i].m_state);
}
ndbrequire(c_buckets[i].m_state == 0); // XXX todo
c_buckets[i].m_switchover_gci = gci - 1; // start from gci
c_buckets[i].m_state = state | (c_no_of_buckets << 8);
}
break;
}
{
DropNodegroupImplConf* conf =
(DropNodegroupImplConf*)signal->getDataPtrSend();
conf->senderRef = reference();
conf->senderData = req->senderData;
sendSignal(req->senderRef, GSN_DROP_NODEGROUP_IMPL_CONF, signal,
DropNodegroupImplConf::SignalLength, JBB);
}
return;
//error:
DropNodegroupImplRef *ref =
(DropNodegroupImplRef*)signal->getDataPtrSend();
ref->senderRef = reference();
ref->senderData = req->senderData;
ref->errorCode = err;
sendSignal(req->senderRef, GSN_DROP_NODEGROUP_IMPL_REF, signal,
DropNodegroupImplRef::SignalLength, JBB);
return;
}
template void append(DataBuffer<11>&,SegmentedSectionPtr,SectionSegmentPool&);
|
INCLUDE "hardware.inc"
INCLUDE "esp.inc"
xCOORD EQU $C003
yCOORD EQU $C004
SECTION "Interupt VBLANK", ROM0[$40]
jp VBlankHandler
SECTION "Header", ROM0[$100]
EntryPoint:
di
jp Start
REPT $150 - $104
db 0
ENDR
SECTION "Sprite Data", ROM0
Sprites:
.Sprite1
;; Remember that this number format hides the weirdness of tile data.
;; `31333332 is the same as %11111110 10111111. This is not obvious.
dw `31333332
dw `30303030
dw `03030303
dw `03030303
dw `03030303
dw `03030303
dw `03030303
dw `33333333
.AtSymbol
dw `00000000
dw `00333000
dw `03000300
dw `30033030
dw `30303030
dw `30030300
dw `03000000
dw `00333000
.Heart
;; Colour 2 is used to toggle filled/empty heart.
dw `33333333
dw `30030033
dw `02202203
dw `02222203
dw `02222203
dw `30222033
dw `33020333
dw `33303333
.ArrowR
dw `33333333
dw `00113333
dw `00111333
dw `00111133
dw `00111113
dw `00111133
dw `00111333
dw `00113333
SECTION "Game code", ROM0
Start:
.waitVBlank
ld a, [rLY]
cp 144 ; Check if the LCD is past VBlank
jr c, .waitVBlank
xor a ; ld a, 0
ld [rLCDC], a
ld hl, $8000
ld de, Sprites.ArrowR
ld b, 16
call memcpy
call clearOAM
;; Load OAM data for sprite.
ld hl, $FE00 ; OBJ space
ld a, 151 ; y position
ld [hli], a
ld a, 110 ; x position
ld [hli], a
ld a, 0
ld [hli], a
ld a, 0
ld [hli], a
;; Set sprite palette 0.
ld hl, rOBP0
ld [hl], %11100000
;; copy the font
ld hl, $9000
ld de, FontTiles
ld bc, FontTilesEnd - FontTiles
.copyFont
ld a, [de] ; Grab 1 byte from the source
ld [hli], a ; Place it at the destination, incrementing hl
inc de ; Move to next byte
dec bc ; Decrement count
ld a, b ; Check if count is 0, since `dec bc` doesn't update flags
or c
jr nz, .copyFont
ld hl, $9400
ld de, Sprites.AtSymbol
ld b, 16
call memcpy
;; copy connecting string
ld hl, $98E4 ; This will print the string roughly in the center
ld de, ConnectingString
.copyString
ld a, [de]
ld [hli], a
inc de
and a ; Check if the byte we just copied is zero
jr nz, .copyString ; Continue if it's not
; place window
ld hl, $ff4b
ld [hl], 7
ld hl, $ff4a
ld [hl], 135
;; Add an all black tile.
;; This is used to fill the window with black. It's tile index 128.
ld hl, $8800
ld a, $FF
ld d, 16
:
ld [hli], a
dec d
jr nz, :-
ld de, Sprites.Heart
ld b, 16
call memcpy
;; fill top two lines of window with black
ld d, 20 ; d is the column counter
ld e, 2 ; e is the line counter
ld hl, $9C00
:
ld a, 128
ld [hli], a
dec d
jr nz, :-
ld d, 20
;; add 12 to hl to get to the next line. The tilemap is 32 tiles wide.
;; HL is pointing to the 21st, adding 12 brings it to the first tile on
;; the next line.
ld bc, 12
add hl, bc
dec e
jr nz, :-
;; Place the heart.
ld hl, $9C0E
ld a, 129
ld [hli], a
; Set some display registers
; Set background and window pallet
ld a, %11110100
ld [rBGP], a
; Scroll to 0,0
xor a ; ld a, 0
ld [rSCY], a
ld [rSCX], a
;; Turn on LCD with sprites off and background on.
ld a, %11000001
ld [rLCDC], a
;; Turn on interupts for vblank.
;; My vblank interupt handler is just RETI.
;; This lets me use HALT to wait for vblank.
ld hl, rIE
ld [hl], IEF_VBLANK
ei
ld hl, $98EF
ld d, 20
.waitConnect
;; Check if the ESP is ready once a frame.
;; Blink the last period in the "Connecting.." string every 20 frames.
EspReadyToA
and 1
jr z, .connected
halt ; wait for vblank
dec d
jr nz, .waitConnect
ld d, 20
ld a, [hl]
;; $2E is the "." character in the tilemap. Doing an xor will change the
;; value to either 0 or $2E. The 0 tile is a blank tile.
xor $2E
ld [hl], a
jr .waitConnect
.connected
ld hl, $98E4
ld de, ConnectedString
.copyConnectedString
ld a, [de]
ld [hli], a
inc de
and a ; Check if the byte we just copied is zero
jr nz, .copyConnectedString
;; ready is 0
FromEspToA ; ignore the value
: ; loop until ready is 1
EspReadyToA
and 1
jr z, :-
;; wait 60 frames.
;; This is to keep "Conected!!" on the screen long enough to be read.
ld d, 60
:
halt
dec d
jr nz, :-
;; Display "Loading.." and blink the last "." while waiting for ready.
ld hl, $98E4
ld de, LoadingString
call HaltAndCopyString
ld d, 20
ld hl, $98EE
:
EspReadyToA
and 1
jr z, :+ ; 0 here is ready
halt
dec d
jr nz, :-
ld d, 20
ld a, [hl]
xor $2E
ld [hl], a
jr :-
: ;; done waiting
ld hl, $98E4
ld de, Strings.Clear
call HaltAndCopyString
halt
;; Turn off the display so that I can draw the tweet's text without
;; worrying about vblank.
xor a
ld [rLCDC], a
ld d, 20 ; columns
ld e, 18 ; rows
ld hl, $9800
:
FromEspToA
;; The text is 0 terminated.
cp 0
jp z, doneLoading
ld [hli], a
: ;; Wait for ready.
EspReadyToA
and 1
jr nz, :- ; not ready yet
dec d
jr nz, :-- ; line isn't full
;; line is full, go to next line.
ld bc, 12
add hl, bc
ld d, 20
dec e
jr nz, :-- ; more lines left
doneLoading:
;halt
ld a, %11100001
ld [rLCDC], a
;9813 9820
gameloop:
.gameloop
;; Read d-pad.
ld HL, rP1
ld a, %00100000
ld [hl], a
ld c, [hl]
ld [hl], $FF
;; check left
ld a, c
and %00000010
jr nz, .checkRight
.checkRight
ld a, c
and %00000001
jr nz, .checkA
;; Turn the Object/sprite layer on.
;; This displays the arrow sprite.
;; Once it's visible there's no way to turn it off right now. This is a
;; lazy way to get very minimal UI.
ld a, %11100011
ld [rLCDC], a
.checkA
;; Read action buttons
ld HL, rP1
ld a, %00010000
ld a, %11011111
ld [hl], a
ld c, [hl]
ld [hl], $FF
;; check A
ld a, c
and %00000001
jr nz, .AisNotPressed
;; A is pressed.
;; Check if already pressed
ld hl, $C000
ld a, [hl]
cp 0
jp nz, gameloop
;; wasn't already pressed
;; mark as pressed
ld [hl], 1
;; do stuff
ld a, "L"
ToEspFromA ; The ESP ignores this.
:
halt
EspReadyToA
and 1
jp nz, :-
FromEspToA
halt
ld a, %11000100
ld [rBGP], a
jp gameloop
.AisNotPressed
;; mark A as not pressed first
ld hl, $C000
ld [hl], 0
jp gameloop
VBlankHandler:
reti
SECTION "Font", ROM0
FontTiles:
INCBIN "font.chr"
FontTilesEnd:
SECTION "copy string function", ROM0
HaltAndCopyString:
halt
CopyString:
;; copy a 0 terminated string
;; from de to hl
;; doesn't check screen size
ld a, [de]
ld [hli], a
inc de
and a
jr nz, CopyString
ret
SECTION "Connecting string", ROM0
ConnectingString:
db "Connecting..", 0
SECTION "Connected string", rom0
ConnectedString:
db "Connected!!!", 0
SECTION "strings", ROM0
LoadingString:
Strings:
db " Loading.. ", 0
.Twitter
db " Twitter! ", 0
.Clear
db " ", 0
|
; A244633: a(n) = 26*n^2.
; 0,26,104,234,416,650,936,1274,1664,2106,2600,3146,3744,4394,5096,5850,6656,7514,8424,9386,10400,11466,12584,13754,14976,16250,17576,18954,20384,21866,23400,24986,26624,28314,30056,31850,33696,35594,37544,39546,41600,43706,45864,48074,50336,52650,55016,57434,59904,62426,65000,67626,70304,73034,75816,78650,81536,84474,87464,90506,93600,96746,99944,103194,106496,109850,113256,116714,120224,123786,127400,131066,134784,138554,142376,146250,150176,154154,158184,162266,166400,170586,174824,179114
pow $0,2
mul $0,26
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r13
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0xabd4, %rax
nop
nop
and %r10, %r10
mov $0x6162636465666768, %rcx
movq %rcx, %xmm1
movups %xmm1, (%rax)
nop
nop
nop
nop
inc %rbx
lea addresses_UC_ht+0x1073c, %rsi
lea addresses_WC_ht+0x10bd4, %rdi
nop
nop
nop
nop
nop
sub $175, %r11
mov $50, %rcx
rep movsw
nop
nop
nop
nop
cmp $60592, %rsi
lea addresses_WT_ht+0xffd4, %r10
nop
xor %rdi, %rdi
movw $0x6162, (%r10)
nop
and %rsi, %rsi
lea addresses_A_ht+0x1ebd4, %r11
nop
nop
nop
nop
add $9895, %rcx
vmovups (%r11), %ymm3
vextracti128 $1, %ymm3, %xmm3
vpextrq $0, %xmm3, %rax
nop
nop
nop
xor %r11, %r11
lea addresses_normal_ht+0x1efd4, %rsi
lea addresses_A_ht+0xafc4, %rdi
nop
nop
and %r11, %r11
mov $38, %rcx
rep movsb
nop
xor %r11, %r11
lea addresses_A_ht+0xe7d4, %rax
nop
nop
nop
nop
nop
add %rcx, %rcx
mov $0x6162636465666768, %rdi
movq %rdi, (%rax)
sub $57457, %r10
lea addresses_D_ht+0x1b1d4, %rbx
nop
nop
nop
xor %rsi, %rsi
movb (%rbx), %r11b
nop
nop
nop
nop
add $34899, %rsi
lea addresses_A_ht+0x12d84, %rbx
clflush (%rbx)
nop
nop
nop
nop
sub $39563, %r10
movups (%rbx), %xmm6
vpextrq $1, %xmm6, %rcx
nop
nop
xor %rbx, %rbx
lea addresses_normal_ht+0x2584, %r10
nop
nop
nop
sub %rsi, %rsi
vmovups (%r10), %ymm2
vextracti128 $1, %ymm2, %xmm2
vpextrq $1, %xmm2, %rax
nop
nop
add $24717, %r11
lea addresses_D_ht+0x10f54, %rbx
lfence
movl $0x61626364, (%rbx)
nop
nop
nop
add %rbx, %rbx
lea addresses_A_ht+0xd4ea, %rsi
lea addresses_normal_ht+0x1d554, %rdi
nop
nop
nop
nop
nop
xor %r13, %r13
mov $46, %rcx
rep movsw
nop
dec %rdi
lea addresses_A_ht+0x2104, %rsi
lea addresses_normal_ht+0x1edd4, %rdi
nop
nop
nop
nop
nop
add $43023, %r13
mov $44, %rcx
rep movsl
nop
nop
nop
nop
sub $29025, %rcx
lea addresses_D_ht+0xac34, %r11
nop
nop
nop
nop
add $15437, %r13
movb $0x61, (%r11)
dec %rdi
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r13
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r13
push %r14
push %r9
push %rcx
push %rdx
// Store
mov $0xfd4, %r14
nop
and %r13, %r13
movl $0x51525354, (%r14)
and %r9, %r9
// Store
lea addresses_A+0xa7d4, %r9
clflush (%r9)
nop
nop
nop
nop
xor $36279, %r10
movl $0x51525354, (%r9)
nop
and %r10, %r10
// Store
lea addresses_A+0x15bd8, %rdx
nop
nop
add %r14, %r14
mov $0x5152535455565758, %rcx
movq %rcx, (%rdx)
nop
nop
nop
nop
nop
sub $62918, %r10
// Load
lea addresses_UC+0x11fd4, %r9
nop
nop
nop
nop
cmp $30315, %r10
movb (%r9), %r13b
nop
and $8624, %rcx
// Faulty Load
lea addresses_A+0x4fd4, %rcx
nop
nop
add %r11, %r11
mov (%rcx), %r10
lea oracles, %r11
and $0xff, %r10
shlq $12, %r10
mov (%r11,%r10,1), %r10
pop %rdx
pop %rcx
pop %r9
pop %r14
pop %r13
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_P', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 11}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 2}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC', 'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 10}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_A', 'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 10}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 10, 'type': 'addresses_WC_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 10}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 9}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_normal_ht'}, 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_A_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 10}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 9}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 4}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 4}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_normal_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_normal_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 3}}
{'54': 15706}
54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54
*/
|
; Copyright 2000, 2002 Free Software Foundation, Inc.
;
; This file is part of the GNU MP Library.
;
; The GNU MP Library is free software; you can redistribute it and/or
; modify it under the terms of the GNU Lesser General Public License as
; published by the Free Software Foundation; either version 2.1 of the
; License, or (at your option) any later version.
;
; The GNU MP Library 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
; Lesser General Public License for more details.
;
; You should have received a copy of the GNU Lesser General Public
; License along with the GNU MP Library; see the file COPYING.LIB. If
; not, write to the Free Software Foundation, Inc., 59 Temple Place -
; Suite 330, Boston, MA 02111-1307, USA.
;
; Translation of AT&T syntax code by Brian Gladman
%include "..\..\x86i.inc"
%define REG_AAAAAAAAAAAAAAAA mm7
%define REG_3333333333333333 mm6
%define REG_0F0F0F0F0F0F0F0F mm5
%define REG_000000FF000000FF mm4
%ifndef PIC
section .data
align 8
Lrodata_AAAAAAAAAAAAAAAA:
dd 0AAAAAAAAh
dd 0AAAAAAAAh
Lrodata_3333333333333333:
dd 033333333h
dd 033333333h
Lrodata_0F0F0F0F0F0F0F0F:
dd 00F0F0F0Fh
dd 00F0F0F0Fh
Lrodata_000000FF000000FF:
dd 0000000FFh
dd 0000000FFh
%endif
%macro ph_fun 3
section .text
align 32
global %1%2
%ifdef DLL
export %1%2
%endif
%if %3 == 0
%ifdef PIC
nop ; avoid shrl crossing a 32-byte boundary
%endif
%endif
%1%2:
mov ecx, [PARAM_SIZE]
%ifdef PIC
mov eax, 0xAAAAAAAA
mov edx, 0x33333333
movd mm7,eax
movd mm6,edx
mov eax, 0x0F0F0F0F
mov edx, 0x000000FF
punpckldq mm7,mm7
punpckldq mm6,mm6
movd mm5,eax
movd mm4,edx
punpckldq mm5,mm5
punpckldq mm4,mm4
%else
movq mm7,[Lrodata_AAAAAAAAAAAAAAAA]
movq mm6,[Lrodata_3333333333333333]
movq mm5,[Lrodata_0F0F0F0F0F0F0F0F]
movq mm4,[Lrodata_000000FF000000FF]
%endif
mov eax,[PARAM_SRC]
%if %3 == 1
mov edx,[PARAM_SRC2]
%endif
pxor mm2,mm2
shr ecx,1
jnc %%Ltop
movd mm1,[eax+ecx*8] ; Zdisp( movd,0,(%eax,%ecx,8),%mm1)
%if %3 == 1
movd mm0,[edx+ecx*8] ; Zdisp( movd,0,(%edx,%ecx,8),%mm0)"
pxor mm1,mm0
%endif
inc ecx
jmp %%Lloaded
align 16
%if %3 == 0
nop
%endif
; eax src
; ebx
; ecx counter,qwords,decrementing
; edx [hamdist] src2
;
; mm0 (scratch)
; mm1 (scratch)
; mm2 total (low dword)
; mm3
; mm4 \
; mm5 | special constants
; mm6 |
; mm7 /
%%Ltop:
movq mm1,[eax+ecx*8-8]
%if %3 == 1
pxor mm1,[edx+ecx*8-8]
%endif
%%Lloaded:
movq mm0,mm1
pand mm1,REG_AAAAAAAAAAAAAAAA
psrlq mm1,1
%if %3 == 1
nop
%endif
psubd mm0,mm1 ; bit pairs
%if %3 == 1
nop
%endif
movq mm1,mm0
psrlq mm0,2
pand mm0,REG_3333333333333333
pand mm1,REG_3333333333333333
paddd mm0,mm1 ; nibbles
movq mm1,mm0
psrlq mm0,4
pand mm0,REG_0F0F0F0F0F0F0F0F
pand mm1,REG_0F0F0F0F0F0F0F0F
paddd mm0,mm1 ; bytes
movq mm1,mm0
psrlq mm0,8
paddb mm0,mm1 ; words
movq mm1,mm0
psrlq mm0,16
paddd mm0,mm1 ; dwords
pand mm0,REG_000000FF000000FF
paddd mm2,mm0 ; low to total
psrlq mm0,32
paddd mm2,mm0 ; high to total
loop %%Ltop
movd eax,mm2
emms
ret
%endmacro
%define PARAM_SIZE esp+frame+12
%define PARAM_SRC2 esp+frame+8
%define PARAM_SRC esp+frame+4
%define frame 0
; global ___gmpn_hamdist
ph_fun ___g,mpn_hamdist,1
end
|
;; @file
; Provide FSP API entry points.
;
; Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>
; SPDX-License-Identifier: BSD-2-Clause-Patent
;;
SECTION .text
;
; Following functions will be provided in C
;
extern ASM_PFX(Loader2PeiSwitchStack)
extern ASM_PFX(FspApiCallingCheck)
;
; Following functions will be provided in ASM
;
extern ASM_PFX(FspApiCommonContinue)
extern ASM_PFX(AsmGetFspInfoHeader)
;----------------------------------------------------------------------------
; FspApiCommon API
;
; This is the FSP API common entry point to resume the FSP execution
;
;----------------------------------------------------------------------------
global ASM_PFX(FspApiCommon)
ASM_PFX(FspApiCommon):
;
; EAX holds the API index
;
;
; Stack must be ready
;
push eax
add esp, 4
cmp eax, dword [esp - 4]
jz FspApiCommon1
mov eax, 080000003h
jmp exit
FspApiCommon1:
;
; Verify the calling condition
;
pushad
push DWORD [esp + (4 * 8 + 4)] ; push ApiParam
push eax ; push ApiIdx
call ASM_PFX(FspApiCallingCheck)
add esp, 8
cmp eax, 0
jz FspApiCommon2
mov dword [esp + (4 * 7)], eax
popad
exit:
ret
FspApiCommon2:
popad
cmp eax, 3 ; FspMemoryInit API
jz FspApiCommon3
call ASM_PFX(AsmGetFspInfoHeader)
jmp ASM_PFX(Loader2PeiSwitchStack)
FspApiCommon3:
jmp ASM_PFX(FspApiCommonContinue)
|
.n64
.relativeinclude on
.create "../roms/patched.z64", 0
.incbin "../roms/base.z64"
.include "macros.asm"
;==================================================================================================
; Constants
;==================================================================================================
.include "constants.asm"
.include "addresses.asm"
;==================================================================================================
; Base game editing region
;==================================================================================================
.include "boot.asm"
.include "hacks.asm"
.include "malon.asm"
.include "mido.asm"
;==================================================================================================
; New code region
;==================================================================================================
.headersize (0x80400000 - 0x03480000)
.org 0x80400000
.area 0x20000 //payload max memory
PAYLOAD_START:
.area 0x20, 0
RANDO_CONTEXT:
.word COOP_CONTEXT
.word COSMETIC_CONTEXT
.word extern_ctxt
.endarea
.include "coop_state.asm" ; This should always come first
.include "config.asm"
.include "init.asm"
.include "item_overrides.asm"
.include "cutscenes.asm"
.include "shop.asm"
.include "every_frame.asm"
.include "menu.asm"
.include "time_travel.asm"
.include "song_fix.asm"
.include "scarecrow.asm"
.include "empty_bomb_fix.asm"
.include "initial_save.asm"
.include "textbox.asm"
.include "fishing.asm"
.include "bgs_fix.asm"
.include "chus_in_logic.asm"
.include "rainbow_bridge.asm"
.include "lacs_condition.asm"
.include "gossip_hints.asm"
.include "potion_shop.asm"
.include "jabu_elevator.asm"
.include "dampe.asm"
.include "dpad.asm"
.include "chests.asm"
.include "bunny_hood.asm"
.include "magic_color.asm"
.include "debug.asm"
.include "extended_objects.asm"
.include "cow.asm"
.include "lake_hylia.asm"
.include "timers.asm"
.include "shooting_gallery.asm"
.include "damage.asm"
.include "bean_salesman.asm"
.include "grotto.asm"
.include "deku_mouth_condition.asm"
.include "audio.asm"
.include "king_zora.asm"
.include "agony.asm"
.importobj "../build/bundle.o"
.align 8
FONT_TEXTURE:
.incbin("../resources/font.bin")
DPAD_TEXTURE:
.incbin("../resources/dpad.bin")
TRIFORCE_ICON_TEXTURE:
.incbin("../resources/triforce_sprite.bin")
.align 0x10
PAYLOAD_END:
.endarea //payload max memory
AUDIO_THREAD_MEM_START:
.skip AUDIO_THREAD_MEM_SIZE
.close
|
; A326128: a(n) = n - A007913(n), where A007913 gives the squarefree part of n.
; 0,0,0,3,0,0,0,6,8,0,0,9,0,0,0,15,0,16,0,15,0,0,0,18,24,0,24,21,0,0,0,30,0,0,0,35,0,0,0,30,0,0,0,33,40,0,0,45,48,48,0,39,0,48,0,42,0,0,0,45,0,0,56,63,0,0,0,51,0,0,0,70,0,0,72,57,0,0,0,75,80,0,0,63,0,0,0,66,0,80,0,69,0,0,0,90,0,96,88,99,0,0,0,78,0,0,0,105,0,0,0,105,0,0,0,87,104,0,0,90,120,0,0,93,120,112,0,126,0,0,0,99,0,0,120,102,0,0,0,105,0,0,0,143,0,0,144,111,0,144,0,114,136,0,0,117,0,0,0,150,0,160,0,123,0,0,0,126,168,0,152,129,0,0,168,165,0,0,0,175,0,0,0,138,0,0,0,141,168,0,0,189,0,0,0,195,0,176,0,198,0,0,0,153,0,0,184,195,0,0,0,159,0,0,0,210,0,0,0,165,0,0,0,210,224,0,0,171,0,0,0,174,0,208,0,177,0,0,0,225,0,240,240,183,240,0,0,186,0,240
mov $1,$0
cal $0,7913 ; Squarefree part of n: a(n) is the smallest positive number m such that n/m is a square.
sub $0,1
sub $1,$0
|
section .data
source dw 1, 2, 3, 4, 5, 6
len equ ($ - source)/2
item dw 2
section .text
global _start
_start:
push word [item]
mov ax, len
dec ax
push ax
push word 0
push qword source
call binary_search
exit:
mov ebx, 0
mov eax, 1
int 80h
binary_search:
enter 14, 0
mov r8w, [rbp + 24]
mov [rbp - 2], r8w
mov r8w, [rbp + 26]
mov [rbp - 4], r8w
mov r8w, [rbp + 28]
mov [rbp - 6], r8w
mov r8, [rbp + 16]
mov [rbp - 14], r8
mov r8w, [rbp - 4]
mov r9w, [rbp - 2]
cmp r8w, r9w
jge end_not_less_than_start
mov ax, -1
leave
ret 14
end_not_less_than_start:
xor r8, r8
mov r8w, [rbp - 4]
sub r8w, [rbp - 2]
sar r8, 1
xor r9, r9
mov r9w, [rbp - 2]
add r8, r9
mov r9, [rbp - 14]
add r9, r8
add r9, r8
mov r10w, [r9]
mov r9w, [rbp - 6]
cmp r9w, r10w
jne not_equal
mov ax, r8w
leave
ret 14
not_equal:
cmp r9w, r10w
jnl not_lower
push word [rbp - 6]
mov ax, r8w
dec ax
push ax
push word [rbp - 2]
push qword [rbp - 14]
call binary_search
leave
ret 14
not_lower:
push word [rbp - 6]
push word [rbp - 4]
mov ax, r8w
inc ax
push ax
push qword [rbp - 14]
call binary_search
leave
ret 14
|
; _Noreturn void _exit(int status)
SECTION code_fcntl
PUBLIC __exit
EXTERN __exit_fastcall
__exit:
pop hl
pop hl
jp __exit_fastcall
|
#include <iostream>
#include <algorithm>
#include<memory.h>
using namespace std;
#define MAXE 2000002
#define MAXV 2000002
struct edge{int e, nxt;};
int V, E;
edge e[MAXE], er[MAXE];
int sp[MAXV], spr[MAXV];
int group_cnt, group_num[MAXV];
bool v[MAXV];
int stk[MAXV];
void fill_forward(int x)
{
int i;
v[x]=true;
for(i=sp[x];i;i=e[i].nxt) if(!v[e[i].e]) fill_forward(e[i].e);
stk[++stk[0]]=x;
}
void fill_backward(int x)
{
int i;
v[x]=false;
group_num[x]=group_cnt;
for(i=spr[x];i;i=er[i].nxt)
if(v[er[i].e])
fill_backward(er[i].e);
}
void add_edge(int v1, int v2) //add edge v1->v2
{
//cout<<v1<<v2<<"\n";
e [++E].e=v2; e [E].nxt=sp [v1]; sp [v1]=E;
er[E].e=v1; er[E].nxt=spr[v2]; spr[v2]=E;
}
void SCC()
{
int i;
stk[0]=0;
memset(v, false, sizeof(v));
for(i=1;i<=V;i++) if(!v[i]) fill_forward(i);
group_cnt=0;
for(i=stk[0];i>=1;i--)
if(v[stk[i]])
{
group_cnt++;
fill_backward(stk[i]);
}
}
int n;
int negation(int num){
if(num>n) return num-n;
else return num+n;
}
int main (int argc, char const* argv[])
{
cin>>n;
V = 2*n+1;
E = 2*n;
//1..n: +ve
//n+1....2n : -ve
for (int i = 0; i < n; i += 1)
{
int a,b; cin>>a>>b;
if(a<0) a = (n-a);
if(b<0) b = (n-b);
add_edge(negation(b),a);
add_edge(negation(a),b);
}
SCC();
for (int i = 1; i <= n; i += 1)
{
if(group_num[i]==group_num[i+n]) {
cout<<0;return 0;
}
//cout<<i<<":"<<group_num[i]<<" "<<group_num[n+i]<<"\n";
}
cout<<1;
}
|
;*****************************************************************************
;*++
;* Name : $RCSfile: dtriml.asm,v $
;* Title :
;* ASM Author : Rob Isherwood
;* Created : 15/1/97
;*
;* Copyright : 1995-2022 Imagination Technologies (c)
;* License : MIT
;*
;* Description : Pentium optimised Process loops from dtri.c
;*
;* Program Type: ASM module (.dll)
;*
;* RCS info:
;*
;* $Date: 1997/06/20 16:27:14 $
;* $Revision: 1.3 $
;* $Locker: $
;* $Log: dtriml.asm,v $
;; Revision 1.3 1997/06/20 16:27:14 sjf
;; Put in John C's change to fix the UV offset bug from the
;; WIN32 version. ARGGGHHH we really need to just use the WIN32 versions.
;;
;; Revision 1.2 1997/04/04 13:07:55 jop
;; Reverted to proper TEXTEQU syntax for MASM
;;
;; Revision 1.10 1997/03/20 18:25:54 jrc
;; Added underscore to function name so it'd build.
;;
;; Revision 1.9 1997/03/20 18:11:51 jop
;; Changed name of asm function to get rid of link errors
;;
;; Revision 1.8 1997/03/04 20:35:52 erf
;; XY offset fix. Enabled if MODIFYXY = 1 at start of file.
;; Adds fAddToXY to each of the vertices. Also region calculation
;; has changed. Region now calculated for X0, Y0, X1-1, Y1-1. This
;; prevents regions from having invalid plane info.
;;
;; Revision 1.7 1997/02/26 14:21:17 gdc
;; chnaged determinate based poly rejection criteria to match
;; that of sglmacro.h - i.e. 0.0625f. Need for monalisa->AK47
;;
;; Revision 1.6 1997/02/03 16:11:08 rgi
;; Added handling of D3D faces to ProcessTriCoreLite to get
;; the D3D applications back up to scratch.
;;
;; Revision 1.5 1997/01/30 17:20:45 rgi
;; Revised IBUFFERSIZE ala dtri.c change
;;
;; Revision 1.4 1997/01/27 13:51:35 rgi
;; Big change, removed D3DTriangle optimised version and added
;; newer ProcessTriCoreLite with inlined texture handling code.
;;
;; Revision 1.3 1997/01/24 09:17:59 rgi
;; Prepared for in-lining of ProcessFlatTex and ProcessD3DFlatTex
;; into dtriml.asm. Sadly this breaks ProcessD3DTriCore so it's
;; currently conditioned out.
;;
;; Revision 1.2 1997/01/20 17:34:46 rgi
;; First tru assembler version, appears to work with R4 and
;; Ultimate race.
;;
;; Revision 1.1 1997/01/16 13:05:09 rgi
;; Initial revision
;;
;*
;* This was all produced from compiler output of dtri.c's version with
;* the following options.
;*
;* The initial ProcessD3DTriCore was taken from dispml.asm
;*--
;*****************************************************************************
.386P
.387
_TEXT SEGMENT PARA PUBLIC USE32 'CODE'
_TEXT ENDS
_DATA SEGMENT PARA PUBLIC USE32 'DATA'
ALIGN 010H
_DATA ENDS
_BSS SEGMENT PARA PUBLIC USE32 'BSS'
ALIGN 010H
_BSS ENDS
_DATA1 SEGMENT PARA PUBLIC USE32 'DATA'
ALIGN 010H
_DATA1 ENDS
_TLS SEGMENT PARA PUBLIC USE32 'TLS'
_TLS ENDS
ASSUME CS:FLAT, DS:FLAT, SS:FLAT
;Constants
WORDS_PER_PLANE EQU (3*4)
IEEE_MANTISSA_MASK EQU 07FFFFFh
IEEE_ASSUMED_BIT EQU 0800000h
IBUFFERSIZE EQU 16
SGLTT_DISABLEZBUFFER EQU 02000h
SGLTT_FACESIND3DFORMAT EQU 00800h
D3DTRIFLAG_ODD equ 0000001eh
D3DTRIFLAG_EVEN equ 0000001fh
MASK_TRANS EQU 1024
MODIFYXY EQU 1 ; Enable/disable modify XY.
;PITRI structure
Adj0 EQU 0
Adj1 EQU 12
Adj2 EQU 24
f1OverDet EQU 36
fZ EQU 40
ITreg EQU 52
ITTSPControlWord EQU 56
ITBaseColour EQU 60
PITRI_SIZE EQU 64
;gPDC structure, we only know about stuff upto Context sub-struct
nPolys EQU 0
pVertices EQU 4
TSPControlWord EQU 8
pFace EQU 12
pV0 EQU 16
pV1 EQU 20
pV2 EQU 24
ShiftRegX EQU 28
TexAddress EQU 32
n32MipmapOffset EQU 36
invTexSize EQU 40
Ctx EQU 44
;SGLCONTEXT structure
bFogOn EQU 0
fFogR EQU 4
fFogG EQU 8
fFogB EQU 12
u32FogDensity EQU 16
bCullBackfacing EQU 20 ; (+Ctx = 64)
u32Flags EQU 24
nTextureName EQU 28
fTransPassDepth EQU 32
bDoClipping EQU 36
cBackColour EQU 40 ; 3 floats
eShadowLVolMode EQU 52
fShadowBright EQU 56
u32LVolColour EQU 56 ; union with previous
bFlipU EQU 60
bFlipV EQU 64
bDoUVTimesInvW EQU 68
FirstXRegion EQU 72 ; (+Ctx = 116)
LastXRegion EQU 76 ; (+Ctx = 120)
FirstYRegion EQU 80 ; (+Ctx = 124)
LastYRegion EQU 84 ; (+Ctx = 128)
;Vertex structure
V_fX EQU 0
V_fY EQU 4
V_fZ EQU 8
V_fInvW EQU 12
V_fu32Color EQU 16
V_fu32Specular EQU 20
V_fUOvW EQU 24
V_fVOvW EQU 28
; Material structure, essentially the TEXDATA structure defined in dtri.h
Tex EQU 0 ; We know that Tex is first
u0 EQU (Tex+ 0)
v0 EQU (Tex+ 4)
w0 EQU (Tex+ 8)
u1 EQU (Tex+12)
v1 EQU (Tex+16)
w1 EQU (Tex+20)
u2 EQU (Tex+24)
v2 EQU (Tex+28)
w2 EQU (Tex+32)
if 0
MinMaxSorted macro min, max, new
local Finished
cmp new, max
jle @F
mov max, new
jmp Finished
@@: cmp new, min
jge Finished
mov min, new
Finished:
endm
MinMaxUnsorted macro min, max, new
local Finished
cmp min, max
jle @F
xchg min, max
@@: cmp new, max
je Finished
jl @F
mov max, new
jmp Finished
@@: cmp new, min
jge Finished
mov min, new
Finished:
endm
Constrain macro min, max, lolim, hilim, bugout
cmp min, lolim
jge @F
mov min, lolim
cmp max, min
jl bugout
@@: cmp max, hilim
jle @F
mov max, hilim
cmp min, max
jg bugout
@@:
endm
ConstrainB macro min, max, lolim, hilim, bugout
cmp min, BYTE PTR lolim
jge @F
mov min, BYTE PTR lolim
cmp max, min
jl bugout
@@: cmp max, BYTE PTR hilim
jle @F
mov max, BYTE PTR hilim
cmp min, max
jg bugout
@@:
endm
endif
; mark_description "source.tmp\\pcx -Ie:\\sabre\\sgl\\D3DOPTIM\\source.tmp\\win32 -Ie:\\sabre\\SGL\\..\\vsgl -Gy -Zp4 -G5 -QIfdi";
; mark_description "v- -W0 -nologo -Qpc32 -Qrct -Op- -DDLL_METRIC=1 -O2 -Oy -Qip -Qmem -Qscope_alloc -QW0, -mo_alternate_loops, -m";
; mark_description "o_block_loops, -mo_strip_mine -Oi";
;ident "Intel Reference Release 5 Version 2.3.2 Beta B96061"
;ident "-DWIN32 -QWl, -force:multiple -QWl, -incremental:no -S -Fae:\sabre\sgl\D3DOPTIM\release.tmp\dtri.asm -DFULL_ON -DPVR2 -DPCX1 -DD"
.386P
.387
_DATA1 SEGMENT PARA PUBLIC USE32 'DATA'
_2_3_2il2floatpacket_13 DD 03f800000H ; xf32
_2_3_2il2floatpacket_10 DD 09e3ce508H ; xf32
_2_3_2il2floatpacket_7 DD 01e3ce508H ; xf32
_BogusZIncrementValue DD 030000000H
_DATA1 ENDS
ASSUME CS:FLAT, DS:FLAT, SS:FLAT
_DATA SEGMENT PARA PUBLIC USE32 'DATA'
EXTRN _gfBogusZ:DWORD
EXTRN _fMinZ:DWORD
EXTRN _gpTri:DWORD
EXTRN _ProcessFlatTexFn:DWORD
EXTRN _gpMatCurrent:DWORD
EXTRN _gpPDC:DWORD
EXTRN _gPDC:DWORD
if MODIFYXY
; Offset value to add to vertices.
EXTRN _fAddToXY:DWORD
endif
_DATA ENDS
_TEXT SEGMENT PARA PUBLIC USE32 'CODE'
EXTRN _ProcessD3DFlatTex:PROC
EXTRN _ProcessFlatTex:PROC
_TEXT ENDS
; -- Machine type P
; mark_description "Intel Reference Release 5 Version 2.3.2 Beta B96061";
; mark_description "-DWIN32 -QWl,-force:multiple -QWl,-incremental:no -S -Fae:\\sabre\\sgl\\SGLMID4\\release.tmp\\dtmp.asm -DFUL";
; mark_description "L_ON -DPCX1=1 -DD3DOPTIM=1 -DDDRAW -DWIN32=1 -DICL=1 -DVER_LIB_MAX=3 -DVER_LIB_MA=1 -DVER_LIB_MI=0 -DVER_LIB";
; mark_description "_MIN=0x0402 -DVER_LIB_TXT=\"3.1.0b2\" -Ie:\\sabre\\sgl\\SGLMID4\\source.tmp\\. -Ie:\\sabre\\sgl\\SGLMID4\\so";
; mark_description "urce.tmp\\pcx -Ie:\\sabre\\sgl\\SGLMID4\\source.tmp\\win32 -Ie:\\sabre\\SGL\\..\\vsgl -Gy -Zp4 -QIfdiv- -W0 ";
; mark_description "-nologo -Qpc32 -Qrct -Op- -G5 -O2 -Oy -Qip -Qmem -Qscope_alloc -QW0,-mo_alternate_loops,-mo_block_loops,-mo_";
; mark_description "strip_mine -Oi";
;ident "Intel Reference Release 5 Version 2.3.2 Beta B96061"
;ident "-DWIN32 -QWl,-force:multiple -QWl,-incremental:no -S -Fae:\sabre\sgl\SGLMID4\release.tmp\dtmp.asm -DFULL_ON -DPCX1=1 -DD3DOPTI"
.386P
.387
_TEXT SEGMENT PARA PUBLIC USE32 'CODE'
_TEXT ENDS
_DATA SEGMENT PARA PUBLIC USE32 'DATA'
ALIGN 010H
_DATA ENDS
_BSS SEGMENT PARA PUBLIC USE32 'BSS'
ALIGN 010H
_BSS ENDS
_DATA1 SEGMENT PARA PUBLIC USE32 'DATA'
ALIGN 010H
_DATA1 ENDS
_TLS SEGMENT PARA PUBLIC USE32 'TLS'
_TLS ENDS
ASSUME CS:FLAT,DS:FLAT,SS:FLAT
_BSS SEGMENT PARA PUBLIC USE32 'BSS'
uTCLDoneFirst DD 2 DUP (0) ; pad
if MODIFYXY
; Tempory variables to store XY coordinates
XYs DD 6 DUP (0)
endif
_BSS ENDS
_DATA SEGMENT PARA PUBLIC USE32 'DATA'
_DATA ENDS
_TEXT SEGMENT PARA PUBLIC USE32 'CODE'
; COMDAT _ProcessTriCoreLite
; -- Begin _ProcessTriCoreLite
; mark_begin;
ALIGN 4 ; 0
PUBLIC __ProcessTriCoreLite
__ProcessTriCoreLite PROC NEAR
LCallPara TEXTEQU <esp+ 0>
LfDet TEXTEQU <esp+ 4>
LuOrBackType TEXTEQU <esp+ 8>
LuDefaultType TEXTEQU <esp+ 12>
LuCurrentType TEXTEQU <esp+ 16>
LrX1 TEXTEQU <esp+ 20>
LrX0 TEXTEQU <esp+ 24>
LrY1 TEXTEQU <esp+ 28>
LrY0 TEXTEQU <esp+ 32>
Adjust TEXTEQU <36>
if MODIFYXY
; Local storage of XY coordinates
fX0 TEXTEQU <XYs+0>
fX1 TEXTEQU <XYs+4>
fX2 TEXTEQU <XYs+8>
fY0 TEXTEQU <XYs+12>
fY1 TEXTEQU <XYs+16>
fY2 TEXTEQU <XYs+20>
else
; Local storage of XY coordinates
fX0 TEXTEQU <rpV0[V_fX]>
fX1 TEXTEQU <rpV1[V_fX]>
fX2 TEXTEQU <rpV2[V_fX]>
fY0 TEXTEQU <rpV0[V_fY]>
fY1 TEXTEQU <rpV1[V_fY]>
fY2 TEXTEQU <rpV2[V_fY]>
endif
RSaveEBX TEXTEQU <esp+ 0+Adjust>
RSaveEBP TEXTEQU <esp+ 4+Adjust>
RSaveESI TEXTEQU <esp+ 8+Adjust>
RSaveEDI TEXTEQU <esp+ 12+Adjust>
RRetAddr TEXTEQU <esp+ 16+Adjust>
PpAddfn TEXTEQU <esp+ 20+Adjust> ; 152
PNewObject TEXTEQU <esp+ 24+Adjust> ; 156
push edi ; Save registers
push esi
push ebp
push ebx
sub esp,Adjust ; Preserve local space
mov esi,OFFSET FLAT: _gpTri ; ESI = gpTri
mov edx,_gPDC[TSPControlWord]; edx = TSPControlWord
xor eax,eax ; eax = 0
and edx,MASK_TRANS ; edx = MASK_TRANS bit or 0
je TCL_TSetup ; if 0 TCL_TSetup with eax,edx = 0
;
; Else translucent setup (rare for performance case)
;
mov ebx,[PNewObject] ; ebx = NewObject
mov edx,1 ; edx = 1 for uOrBackType
test ebx,ebx ; Flags = ebx & ebx
je @F ; If !NewObject skip reset
mov uTCLDoneFirst[0],eax ; uTCLDoneFirst[0] = 0
mov uTCLDoneFirst[4],eax ; uTCLDoneFirst[1] = 0
@@: mov eax,4 ; eax = 4 for u*Type
;
; Carry on with the main line
;
TCL_TSetup:
mov [LuDefaultType],eax ; uDefaultType = eax
mov [LuCurrentType],eax ; uCurrentType = eax
mov [LuOrBackType],edx ; uOrBackType = edx
TCL_Loop:
;
; Main loop: esi = pTri
; eax, ebx, ecx, edx, ebp, edi = undefined
;
mov eax,_gPDC[pFace] ; eax = pFace
mov ebx,_gPDC[nPolys] ; ebx = nPolys
dec ebx ; ebx = nPolys - 1
js TCL_Done ; If -ive nPolys then TCL_Done
mov _gPDC[nPolys],ebx ; nPolys = nPolys - 1 = ebx
mov ebx,_gPDC[Ctx][u32Flags]; ebx = u32Flags
and ebx,SGLTT_FACESIND3DFORMAT; Is this D3D case?
mov ecx,_gPDC[pVertices] ; ecx = pVertices
jz TCL_SGLFace ; No so use SGL Face format
TCL_D3DFace:
mov ebx,[eax][0] ; ebx = (Index1<<16) + Index0
mov edi,[eax][4] ; edi = (Flags<<16) + Index2
mov edx,ebx ; edx = ebx
add eax,8 ; eax = pFace + sizeof(SGLD3DFACE)
shr ebx,16 ; ebx = Index1
and edi,0ffffh ; edi = Index2
and edx,0ffffh ; edx = Index0
jmp TCL_FloatIt ; Carry on
TCL_SGLFace:
mov edx,[eax][0] ; edx = pFace[0]
mov ebx,[eax][4] ; ebx = pFace[1]
mov edi,[eax][8] ; edi = pFace[2]
add eax,12 ; eax = pFace + 3
TCL_FloatIt:
shl edi,5 ; edi *= sizeof(VERTEX)
mov _gPDC[pFace],eax ; pFace++ = eax
shl ebx,5 ; ebx *= sizeof(VERTEX)
add edi,ecx ; EDI = pVertices + (edi*Size)
shl edx,5 ; edx *= sizeof(VERTEX)
add ebx,ecx ; EBX = pVertices + (ebx*Size)
add edx,ecx ; EDX = pVertices + (edx*Size)
mov eax,_gPDC[TSPControlWord]; eax = gPDC.TSPControlWord
rpV0 TEXTEQU <[edx]> ; Vertex pointers available
rpV1 TEXTEQU <[ebx]>
rpV2 TEXTEQU <[edi]>
if MODIFYXY
; Add offset value to XY coordinates
fld DWORD PTR rpV0[V_fX] ; X0
fadd DWORD PTR _fAddToXY
fld DWORD PTR rpV1[V_fX] ; X1
fadd DWORD PTR _fAddToXY
fxch ST(1)
fstp DWORD PTR fX0
fld DWORD PTR rpV2[V_fX] ; X2
fadd DWORD PTR _fAddToXY
fxch ST(1)
fstp DWORD PTR fX1
fld DWORD PTR rpV0[V_fY] ; Y0
fadd DWORD PTR _fAddToXY
fxch ST(1)
fstp DWORD PTR fX2
fld DWORD PTR rpV1[V_fY] ; Y1
fadd DWORD PTR _fAddToXY
fxch ST(1)
fstp DWORD PTR fY0
fld DWORD PTR rpV2[V_fY] ; Y2
fadd DWORD PTR _fAddToXY
fxch ST(1)
fstp DWORD PTR fY1
fstp DWORD PTR fY2
endif
fld DWORD PTR fY1 ; Y1
fmul DWORD PTR fX2 ; X2*Y1
fld DWORD PTR fY2 ; Y2,X2*Y1
fmul DWORD PTR fX1 ; X1*Y2,X2*Y1
fld DWORD PTR fX2 ; X2,X1*Y2,X2*Y1
fmul DWORD PTR fY0 ; X2*Y0,X1*Y2,X2*Y1
fld DWORD PTR fX0 ; X0,X2*Y0,X1*Y2,X2*Y1
fmul DWORD PTR fY2 ; X0*Y2,X2*Y0,X1*Y2,X2*Y1
fld DWORD PTR fX0 ; X0,X0*Y2,X2*Y0,X1*Y2,X2*Y1
fmul DWORD PTR fY1 ; X0*Y1,X0*Y2,X2*Y0,X1*Y2,X2*Y1
fld DWORD PTR fX1 ; X1,X0*Y1,X0*Y2,X2*Y0,X1*Y2,X2*Y1
fmul DWORD PTR fY0 ; X1*Y0,X0*Y1,X0*Y2,X2*Y0,X1*Y2,X2*Y1
fxch st(5) ; X2*Y1,X0*Y1,X0*Y2,X2*Y0,X1*Y2,X1*Y0
fsubp st(4),st ; X0*Y1,X0*Y2,X2*Y0,AdjX0,X1*Y0
fxch st(1) ; X0*Y2,X0*Y1,X2*Y0,AdjX0,X1*Y0
fsubp st(2),st ; X0*Y1,AdjX1,AdjX0,X1*Y0
fsubrp st(3),st ; AdjX1,AdjX0,AdjX2
fld st(1) ; AdjX0,AdjX1,AdjX0,AdjX2
fadd st,st(1) ; AdjX0+AdjX1,AdjX1,AdjX0,AdjX2
fxch st(1) ; AdjX1,AdjX0+AdjX1,AdjX0,AdjX2
fstp DWORD PTR [esi][Adj2][4]; pTri->Adj2[1]=,AdjX0+AdjX1,AdjX0,AdjX2
fadd st,st(2) ; AdjX0+AdjX1+AdjX2,AdjX0,AdjX2
; Stalls 3 but can do integer
mov [esi][ITTSPControlWord],eax; pTri->TSPControlWord = eax
mov eax,[edx+16] ; eax = pV0->u32Colour
mov _gPDC[pV2],edi ; gPDC.pV2 = edi
mov _gPDC[pV0],edx ; gPDC.pV0 = edx
mov ebp,03d800000h ; ebp = MAGIC_NUM
mov _gPDC[pV1],ebx ; gPDC.pV1 = ebx
fstp DWORD PTR [LfDet] ; LfDet=,AdjX0,AdjX2
mov [esi][ITBaseColour],eax ; pTri->BaseColour = eax
mov eax,[LfDet] ; eax = fDet
cmp eax,ebp ; Flags = eax - MAGIC_NUM
jge TCL_NormDet ; if fDet >= MAGIC_NUM then TCL_NormDet
;
; Determinate is very small or negative
;
mov ecx,_gPDC[Ctx][bCullBackfacing]; ecx = bCullBackfacing
xor eax,080000000h ; eax = - fDet
test ecx,ecx ; Flags = bCullBackFacing
jne TCL_ShortCut2 ; If culling then TCL_ShortCut2
;
; Invert the Determinate
;
cmp eax,ebp ; Flags = fDet - MAGIC_NUM
jl TCL_ShortCut2 ; if fDet < MAGIC_NUM TCL_ShortCut2
;
; Determinate is significant and was negative, invert/swap related values
;
fchs ; -AdjX0,AdjX2
fxch st(1) ; AdjX2,-AdjX0
fchs ; -AdjX2,-AdjX0
mov [LfDet],eax ; fDet = eax = -fDet
mov ecx,[LuCurrentType] ; ecx = uCurrentType
mov eax,[esi][Adj2][4] ; eax = AdjX1 = pTri->Adj2[1]
or ecx,[LuOrBackType] ; ecx |= uOrBackType
xor eax,080000000h ; eax = -AdjX1
mov [LuCurrentType],ecx ; uCurrentType |= uOrBackType
mov [esi][Adj2][4],eax ; pTri->Adj2[1] = -AdjX1
mov eax,edx ; eax = edx = pV0
mov edx,edi ; edx = edi = pV2
mov edi,eax ; edi = eax = pV0
mov _gPDC[pV2],edi ; gPDC.pV2 = edi
mov _gPDC[pV0],edx ; gPDC.pV0 = edx
if MODIFYXY
; Swap X0, X2 and Y0, Y2.
mov eax, fX0
mov ecx, fX2
mov fX2, eax
mov fX0, ecx
mov eax, fY0
mov ecx, fY2
mov fY2, eax
mov fY0, ecx
endif
TCL_NormDet:
;
; Registers: esi = pTri, edx = pV0, ebx = pV1, edi = pV2
;
fstp DWORD PTR [esi][Adj2][0]; pTri->Adj2[0]=AdjX0
fstp DWORD PTR [esi][Adj2][8]; pTri->Adj2[2]=AdjX2
fld DWORD PTR fY0 ; pV0->fY
fsub DWORD PTR fY1 ; pV0->fY-pV1->fY
fld DWORD PTR fY1 ; pV1->fY,pV0->fY-pV1->fY
fsub DWORD PTR fY2 ; pV1->fY-pV2->fY,pV0->fY-pV1->fY
fld DWORD PTR fY2 ; pV2->fY,pV1->fY-pV2->fY,pV0->fY-pV1->fY
fsub DWORD PTR fY0 ; pV2->fY-pV0->fY,pV1->fY-pV2->fY,pV0->fY-pV1->fY
fxch st(2) ; pV0->fY-pV1->fY,pV1->fY-pV2->fY,pV2->fY-pV0->fY
fstp DWORD PTR [esi][Adj0][8]; pTri->Adj0[2]=,pV1->fY-pV2->fY,pV2->fY-pV0->fY
fstp DWORD PTR [esi][Adj0][0]; pTri->Adj0[0]=,pV2->fY-pV0->fY
fstp DWORD PTR [esi][Adj0][4]; pTri->Adj0[1]=
fld DWORD PTR fX1 ; pV1->fX
fsub DWORD PTR fX0 ; pV1->fX-pV0->fX
fld DWORD PTR fX0 ; pV0->fX,pV1->fX-pV0->fX
fsub DWORD PTR fX2 ; pV0->fX-pV2->fX,pV1->fX-pV0->fX
fld DWORD PTR fX2 ; pV2->fX,pV0->fX-pV2->fX,pV1->fX-pV0->fX
fsub DWORD PTR fX1 ; pV2->fX-pV1->fX,pV0->fX-pV2->fX,pV1->fX-pV0->fX
fxch st(2) ; pV1->fX-pV0->fX,pV0->fX-pV2->fX,pV2->fX-pV1->fX
fstp DWORD PTR [esi][Adj1][8]; pTri->Adj1[2]=,pV0->fX-pV2->fX,pV2->fX-pV1->fX
fstp DWORD PTR [esi][Adj1][4]; pTri->Adj1[1]=,pV2->fX-pV1->fX
fstp DWORD PTR [esi][Adj1][0]; pTri->Adj1[0]=,
mov ecx,OFFSET FLAT: _ProcessFlatTex
mov eax,DWORD PTR _ProcessFlatTexFn
cmp eax,ecx
; Revert to C code for texture processing. This is not the best solution.
; The offset code should be added in the assembler.
; jne TCL_CheckD3D
jmp TCL_CheckD3D
;
; Process Flat Texture code (same as D3D without the *InvWs)
;
mov ebp, DWORD PTR _gpMatCurrent ; EBP = gpMatCurrent
fld DWORD PTR rpV0[V_fUOvW] ; U0
fld DWORD PTR rpV1[V_fUOvW] ; U1,U0
fld DWORD PTR [esi][Adj2][0]; A20,U1,U0
fmul st, st(2) ; A20*U0(2),U1,U0
fld DWORD PTR rpV2[V_fUOvW] ; U2,A20*U0(1),U1,U0
fld DWORD PTR [esi][Adj2][4]; A21,U2,A20*U0,U1,U0
fmul st, st(3) ; A21*U1(2),U2,A20*U0,U1,U0
fxch st(1) ; U2,A21*U1(2),A20*U0,U1,U0
fsub st(4),st ; U2,A21*U1(1),A20*U0,U1,o0(2)
fld DWORD PTR [esi][Adj2][8]; A22,U2,A21*U1,A20*U0,U1,o0(1)
fmul st, st(1) ; A22*U2(2),U2,A21*U1,A20*U0,U1,o0
fxch st(1) ; U2,A22*U2(2),A21*U1,A20*U0,U1,o0
fsubp st(4), st ; A22*U2(1),A21*U1,A20*U0,o1(2),o0
fld DWORD PTR [esi][Adj0][0]; A00,A22*U2,A21*U1,A20*U0,o1(1),o0
fmul st, st(5) ; A00*o0(2),A22*U2,A21*U1,A20*U0,o1,o0
fxch st(2) ; A21*U1,A22*U2,A00*o0(2),A20*U0,o1,o0
faddp st(3), st ; A22*U2,A00*o0(1),A20*U0+A21*U1(2),o1,o0
fxch st(4) ; o0,A00*o0(1),A20*U0+A21*U1(2),o1,A22*U2
fmul DWORD PTR [esi][Adj1][0]; A10*o0(2),A00*o0,A20*U0+A21*U1(1),o1,A22*U2
fld DWORD PTR [esi][Adj0][4]; A01,A10*o0(1),A00*o0,A20*U0+A21*U1,o1,A22*U2
fmul st, st(4) ; A01*o1(2),A10*o0,A00*o0,A20*U0+A21*U1,o1,A22*U2
fxch st(3) ; A20*U0+A21*U1,A10*o0,A00*o0,A01*o1(2),o1,A22*U2
faddp st(5), st ; A10*o0,A00*o0,A01*o1(1),o1,ut2(2)
fxch st(3) ; o1,A00*o0,A01*o1(1),A10*o0,ut2(2)
fmul DWORD PTR [esi][Adj1][4]; A11*o1(2),A00*o0,A01*o1,A10*o0,ut2(1)
fxch st(2) ; A01*o1,A00*o0,A11*o1(2),A10*o0,ut2(1)
faddp st(1), st ; ut0(2),A11*o1(1),A10*o0,ut2
fxch st(3) ; ut2,A11*o1(1),A10*o0,ut0(2)
fld DWORD PTR rpV0[V_fVOvW] ; V0,ut2(-1),A11*o1,A10*o0,ut0(1)
fxch st(2) ; A11*o1,ut2(-1),V0,A10*o0,ut0(1)
faddp st(3), st ; ut2(-2),V0,ut1(2),ut0
fstp DWORD PTR [ebp][u2] ; Tex.u2=,V0,ut1,ut0(-2)
fxch st(2) ; ut0(-2),ut1,V0
fstp DWORD PTR [ebp][u0] ; Tex.u0=,ut1(-2),V0
fstp DWORD PTR [ebp][u1] ; Tex.u1=,V0
; Now for V
fld DWORD PTR rpV1[V_fVOvW] ; V1,V0
fld DWORD PTR [esi][Adj2][0]; A20,V1,V0
fmul st, st(2) ; A20*V0(2),V1,V0
fld DWORD PTR rpV2[V_fVOvW] ; V2,A20*V0(1),V1,V0
fld DWORD PTR [esi][Adj2][4]; A21,V2,A20*V0,V1,V0
fmul st, st(3) ; A21*V1(2),V2,A20*V0,V1,V0
fxch st(1) ; V2,A21*V1(2),A20*V0,V1,V0
fsub st(4),st ; V2,A21*V1(1),A20*V0,V1,o0(2)
fld DWORD PTR [esi][Adj2][8]; A22,V2,A21*V1,A20*V0,V1,o0(1)
fmul st, st(1) ; A22*V2(2),V2,A21*V1,A20*V0,V1,o0
fxch st(1) ; V2,A22*V2(2),A21*V1,A20*V0,V1,o0
fsubp st(4), st ; A22*V2(1),A21*V1,A20*V0,o1(2),o0
fld DWORD PTR [esi][Adj0][0]; A00,A22*V2,A21*V1,A20*V0,o1(1),o0
fmul st, st(5) ; A00*o0(2),A22*V2,A21*V1,A20*V0,o1,o0
fxch st(2) ; A21*V1,A22*V2,A00*o0(2),A20*V0,o1,o0
faddp st(3), st ; A22*V2,A00*o0(1),A20*V0+A21*V1(2),o1,o0
fxch st(4) ; o0,A00*o0(1),A20*V0+A21*V1(2),o1,A22*V2
fmul DWORD PTR [esi][Adj1][0]; A10*o0(2),A00*o0,A20*V0+A21*V1(1),o1,A22*V2
fld DWORD PTR [esi][Adj0][4]; A01,A10*o0(1),A00*o0,A20*V0+A21*V1,o1,A22*V2
fmul st, st(4) ; A01*o1(2),A10*o0,A00*o0,A20*V0+A21*V1,o1,A22*V2
fxch st(3) ; A20*V0+A21*V1,A10*o0,A00*o0,A01*o1(2),o1,A22*V2
faddp st(5), st ; A10*o0,A00*o0,A01*o1(1),o1,vt2(2)
fxch st(3) ; o1,A00*o0,A01*o1(1),A10*o0,vt2(2)
fmul DWORD PTR [esi][Adj1][4]; A11*o1(2),A00*o0,A01*o1,A10*o0,vt2(1)
fxch st(2) ; A01*o1,A00*o0,A11*o1(2),A10*o0,vt2(1)
faddp st(1), st ; vt0(2),A11*o1(1),A10*o0,vt2
fxch st(3) ; vt2,A11*o1(1),A10*o0,vt0(2)
fld DWORD PTR rpV0[V_fInvW] ; W0,vt2(-1),A11*o1,A10*o0,vt0(1)
fxch st(2) ; A11*o1,vt2(-1),W0,A10*o0,vt0(1)
faddp st(3), st ; vt2(-2),W0,vt1(2),vt0
fstp DWORD PTR [ebp][v2] ; Tex.v2=,W0,vt1,vt0(-2)
fxch st(2) ; vt0(-2),vt1,W0
fstp DWORD PTR [ebp][v0] ; Tex.v0=,vt1(-2),W0
fstp DWORD PTR [ebp][v1] ; Tex.v1=,W0
jmp TCL_DoWTex
TCL_ShortCut2: ; Discard 2 fpu values
fstp st(0)
fstp st(0)
jmp TCL_Loop ; Next poly please
TCL_ByPtr:
push edx ; Save edx and pass pTri as
push esi ; only para.
call eax ; Call _ProcessFlatTexFn
pop esi ; Recover state; edx is the
pop edx ; only reg is use not saved
jmp TCL_DoneTex ; by the Intel compiler.
TCL_CheckD3D:
or eax,eax
jz TCL_DoneTex
cmp eax,OFFSET FLAT: _ProcessD3DFlatTex
jne TCL_ByPtr
;
; Process D3D Texture code, must do one mul for every add/sub/ld or we will
; run out of non multiply operations like the compiler does.
;
mov ebp, DWORD PTR _gpMatCurrent ; EBP = gpMatCurrent
fld DWORD PTR rpV0[V_fUOvW] ; U0
fmul DWORD PTR rpV0[V_fInvW] ; U0*W0(2)
fld DWORD PTR rpV1[V_fUOvW] ; U1,U0(1)
fmul DWORD PTR rpV1[V_fInvW] ; U1*W1(2),U0
fld DWORD PTR [esi][Adj2][0]; A20,U1(1),U0
fmul st, st(2) ; A20*U0(2),U1,U0
fld DWORD PTR rpV2[V_fUOvW] ; U2,A20*U0(1),U1,U0
fmul DWORD PTR rpV2[V_fInvW] ; U2*W2(2),A20*U0,U1,U0
fld DWORD PTR [esi][Adj2][4]; A21,U2(1),A20*U0,U1,U0
fmul st, st(3) ; A21*U1(2),U2,A20*U0,U1,U0
fxch st(1) ; U2,A21*U1(2),A20*U0,U1,U0
fsub st(4),st ; U2,A21*U1(1),A20*U0,U1,o0(2)
fld DWORD PTR [esi][Adj2][8]; A22,U2,A21*U1,A20*U0,U1,o0(1)
fmul st, st(1) ; A22*U2(2),U2,A21*U1,A20*U0,U1,o0
fxch st(1) ; U2,A22*U2(2),A21*U1,A20*U0,U1,o0
fsubp st(4), st ; A22*U2(1),A21*U1,A20*U0,o1(2),o0
fld DWORD PTR [esi][Adj0][0]; A00,A22*U2,A21*U1,A20*U0,o1(1),o0
fmul st, st(5) ; A00*o0(2),A22*U2,A21*U1,A20*U0,o1,o0
fxch st(2) ; A21*U1,A22*U2,A00*o0(2),A20*U0,o1,o0
faddp st(3), st ; A22*U2,A00*o0(1),A20*U0+A21*U1(2),o1,o0
fxch st(4) ; o0,A00*o0(1),A20*U0+A21*U1(2),o1,A22*U2
fmul DWORD PTR [esi][Adj1][0]; A10*o0(2),A00*o0,A20*U0+A21*U1(1),o1,A22*U2
fld DWORD PTR [esi][Adj0][4]; A01,A10*o0(1),A00*o0,A20*U0+A21*U1,o1,A22*U2
fmul st, st(4) ; A01*o1(2),A10*o0,A00*o0,A20*U0+A21*U1,o1,A22*U2
fxch st(3) ; A20*U0+A21*U1,A10*o0,A00*o0,A01*o1(2),o1,A22*U2
faddp st(5), st ; A10*o0,A00*o0,A01*o1(1),o1,ut2(2)
fxch st(3) ; o1,A00*o0,A01*o1(1),A10*o0,ut2(2)
fmul DWORD PTR [esi][Adj1][4]; A11*o1(2),A00*o0,A01*o1,A10*o0,ut2(1)
fxch st(2) ; A01*o1,A00*o0,A11*o1(2),A10*o0,ut2(1)
faddp st(1), st ; ut0(2),A11*o1(1),A10*o0,ut2
fxch st(3) ; ut2,A11*o1(1),A10*o0,ut0(2)
fld DWORD PTR rpV0[V_fVOvW] ; V0,ut2(-1),A11*o1,A10*o0,ut0(1)
fxch st(2) ; A11*o1,ut2(-1),V0,A10*o0,ut0(1)
faddp st(3), st ; ut2(-2),V0,ut1(2),ut0
fstp DWORD PTR [ebp][u2] ; Tex.u2=,V0,ut1,ut0(-2)
fxch st(2) ; ut0(-2),ut1,V0
fstp DWORD PTR [ebp][u0] ; Tex.u0=,ut1(-2),V0
fstp DWORD PTR [ebp][u1] ; Tex.u1=,V0
; Now for V
fmul DWORD PTR rpV0[V_fInvW] ; V0*W0(2)
fld DWORD PTR rpV1[V_fVOvW] ; V1,V0(1)
fmul DWORD PTR rpV1[V_fInvW] ; V1*W1(2),V0
fld DWORD PTR [esi][Adj2][0]; A20,V1(1),V0
fmul st, st(2) ; A20*V0(2),V1,V0
fld DWORD PTR rpV2[V_fVOvW] ; V2,A20*V0(1),V1,V0
fmul DWORD PTR rpV2[V_fInvW] ; V2*W2(2),A20*V0,V1,V0
fld DWORD PTR [esi][Adj2][4]; A21,V2(1),A20*V0,V1,V0
fmul st, st(3) ; A21*V1(2),V2,A20*V0,V1,V0
fxch st(1) ; V2,A21*V1(2),A20*V0,V1,V0
fsub st(4),st ; V2,A21*V1(1),A20*V0,V1,o0(2)
fld DWORD PTR [esi][Adj2][8]; A22,V2,A21*V1,A20*V0,V1,o0(1)
fmul st, st(1) ; A22*V2(2),V2,A21*V1,A20*V0,V1,o0
fxch st(1) ; V2,A22*V2(2),A21*V1,A20*V0,V1,o0
fsubp st(4), st ; A22*V2(1),A21*V1,A20*V0,o1(2),o0
fld DWORD PTR [esi][Adj0][0]; A00,A22*V2,A21*V1,A20*V0,o1(1),o0
fmul st, st(5) ; A00*o0(2),A22*V2,A21*V1,A20*V0,o1,o0
fxch st(2) ; A21*V1,A22*V2,A00*o0(2),A20*V0,o1,o0
faddp st(3), st ; A22*V2,A00*o0(1),A20*V0+A21*V1(2),o1,o0
fxch st(4) ; o0,A00*o0(1),A20*V0+A21*V1(2),o1,A22*V2
fmul DWORD PTR [esi][Adj1][0]; A10*o0(2),A00*o0,A20*V0+A21*V1(1),o1,A22*V2
fld DWORD PTR [esi][Adj0][4]; A01,A10*o0(1),A00*o0,A20*V0+A21*V1,o1,A22*V2
fmul st, st(4) ; A01*o1(2),A10*o0,A00*o0,A20*V0+A21*V1,o1,A22*V2
fxch st(3) ; A20*V0+A21*V1,A10*o0,A00*o0,A01*o1(2),o1,A22*V2
faddp st(5), st ; A10*o0,A00*o0,A01*o1(1),o1,vt2(2)
fxch st(3) ; o1,A00*o0,A01*o1(1),A10*o0,vt2(2)
fmul DWORD PTR [esi][Adj1][4]; A11*o1(2),A00*o0,A01*o1,A10*o0,vt2(1)
fxch st(2) ; A01*o1,A00*o0,A11*o1(2),A10*o0,vt2(1)
faddp st(1), st ; vt0(2),A11*o1(1),A10*o0,vt2
fxch st(3) ; vt2,A11*o1(1),A10*o0,vt0(2)
fld DWORD PTR rpV0[V_fInvW] ; W0,vt2(-1),A11*o1,A10*o0,vt0(1)
fxch st(2) ; A11*o1,vt2(-1),W0,A10*o0,vt0(1)
faddp st(3), st ; vt2(-2),W0,vt1(2),vt0
fstp DWORD PTR [ebp][v2] ; Tex.v2=,W0,vt1,vt0(-2)
fxch st(2) ; vt0(-2),vt1,W0
fstp DWORD PTR [ebp][v0] ; Tex.v0=,vt1(-2),W0
fstp DWORD PTR [ebp][v1] ; Tex.v1=,W0
TCL_DoWTex:
;
; The code for W is common between D3D and true SGL Lite texture formats
;
fld DWORD PTR rpV1[V_fInvW] ; W1,W0
fld DWORD PTR [esi][Adj2][0]; A20,W1,W0
fmul st, st(2) ; A20*W0(2),W1,W0
fld DWORD PTR rpV2[V_fInvW] ; W2,A20*W0(1),W1,W0
fld DWORD PTR [esi][Adj2][4]; A21,W2,A20*W0,W1,W0
fmul st, st(3) ; A21*W1(2),W2,A20*W0,W1,W0
fxch st(1) ; W2,A21*W1(2),A20*W0,W1,W0
fsub st(4),st ; W2,A21*W1(1),A20*W0,W1,o0(2)
fld DWORD PTR [esi][Adj2][8]; A22,W2,A21*W1,A20*W0,W1,o0(1)
fmul st, st(1) ; A22*W2(2),W2,A21*W1,A20*W0,W1,o0
fxch st(1) ; W2,A22*W2(2),A21*W1,A20*W0,W1,o0
fsubp st(4), st ; A22*W2(1),A21*W1,A20*W0,o1(2),o0
fld DWORD PTR [esi][Adj0][0]; A00,A22*W2,A21*W1,A20*W0,o1(1),o0
fmul st, st(5) ; A00*o0(2),A22*W2,A21*W1,A20*W0,o1,o0
fxch st(2) ; A21*W1,A22*W2,A00*o0(2),A20*W0,o1,o0
faddp st(3), st ; A22*W2,A00*o0(1),A20*W0+A21*W1(2),o1,o0
fxch st(4) ; o0,A00*o0(1),A20*W0+A21*W1(2),o1,A22*W2
fmul DWORD PTR [esi][Adj1][0]; A10*o0(2),A00*o0,A20*W0+A21*W1(1),o1,A22*W2
fld DWORD PTR [esi][Adj0][4]; A01,A10*o0(1),A00*o0,A20*W0+A21*W1,o1,A22*W2
fmul st, st(4) ; A01*o1(2),A10*o0,A00*o0,A20*W0+A21*W1,o1,A22*W2
fxch st(3) ; A20*W0+A21*W1,A10*o0,A00*o0,A01*o1(2),o1,A22*W2
faddp st(5), st ; A10*o0,A00*o0,A01*o1(1),o1,nwt2(2)
fxch st(3) ; o1,A00*o0,A01*o1(1),A10*o0,nwt2(2)
fmul DWORD PTR [esi][Adj1][4]; A11*o1(2),A00*o0,A01*o1,A10*o0,nwt2(1)
fxch st(2) ; A01*o1,A00*o0,A11*o1(2),A10*o0,nwt2(1)
faddp st(1), st ; nwt0(2),A11*o1(1),A10*o0,nwt2
fxch st(3) ; nwt2,A11*o1(1),A10*o0,nwt0(2)
fmul DWORD PTR _gPDC[invTexSize];wt2(2),A11*o1,A10*o0,nwt0(1)
fxch st(1) ; A11*o1,wt2(2),A10*o0,nwt0(1)
faddp st(2),st ; wt2(1),nwt1(2),nwt0
fxch st(2) ; nwt0,nwt1(2),wt2(1)
fmul DWORD PTR _gPDC[invTexSize];wt0(2),nwt1(1),wt2
fxch st(2) ; wt2,nwt1(1),wt0(2)
fstp DWORD PTR [ebp][w2] ; Tex.w2=,nwt1,wt0
fmul DWORD PTR _gPDC[invTexSize];wt1(2),wt0
fxch st(1) ; wt0,wt1(2)
fstp DWORD PTR [ebp][w0] ; Tex.w0=,wt1
; Stall of 1
fstp DWORD PTR [ebp][w1] ; Tex.w1=,
TCL_DoneTex:
mov eax,_gPDC[Ctx][u32Flags]; eax = gPDC.Context.u32Flags
mov ecx,8192 ; ecx = ZBUFFER_MASK
test eax,ecx ; Flags = u32Flags & ZBUFFER_MASK
jne TCL_NoZBuff ; If u32Flags & 8192 then TCL_NoZBuff
fld DWORD PTR _fMinZ ; MinZ
fmul DWORD PTR rpV0[V_fInvW] ; MinZ*pV0->fInvW
fld DWORD PTR rpV2[V_fInvW] ; pV2->fInvW,MinZ*pV0->fInvW
fmul DWORD PTR _fMinZ ; pV2->fInvW*MinZ,MinZ*pV0->fInvW
fld DWORD PTR rpV1[V_fInvW] ; pV1->fInvW,pV2->fInvW*MinZ,MinZ*pV0->fInvW
fmul DWORD PTR _fMinZ ; MinZ*pV1->fInvW,pV2->fInvW*MinZ,MinZ*pV0->fInvW
fxch st(2) ; MinZ*pV0->fInvW,pV2->fInvW*MinZ,MinZ*pV1->fInvW
fstp DWORD PTR [esi][fZ][0] ; pTri->fZ[0]=,pV2->fInvW*MinZ,MinZ*pV1->fInvW
fstp DWORD PTR [esi][fZ][8] ; pTri->fZ[2]=,MinZ*pV1->fInvW
fstp DWORD PTR [esi][fZ][4] ; pTri->fZ[1]=
jmp TCL_Cont1 ; goto TCL_Cont1
TCL_ShortCut1: ; Dicard 1 fpu value
fstp st(0)
TCL_ShortCut0:
jmp TCL_Loop ; Next poly please
TCL_NoZBuff:
fld QWORD PTR _2_1_float_13; c1=BOGUSZ_INCREMENT
fadd DWORD PTR _gfBogusZ ; c1+gfBogusZ
mov eax,_gfBogusZ ; eax=gfBogusZ
mov [esi][fZ][0],eax ; pTri->fZ[0]=eax
mov [esi][fZ][4],eax ; pTri->fZ[1]=eax
mov [esi][fZ][8],eax ; pTri->fZ[2]=eax
fstp DWORD PTR _gfBogusZ ; gfBogusZ=
TCL_Cont1:
;
; Using integer comparisons set ecx to min X and eax to max X
;
mov eax,DWORD PTR fX0 ; eax = pV0->fX
mov ecx,DWORD PTR fX1 ; ecx = pV1->fX
cmp eax,ecx ; Flags = pV0->fX - pV1->fX
jge @F ; If eax >= ecx carry on
mov eax,ecx ; eax = Max value
mov ecx,DWORD PTR fX0 ; ecx = Min value
@@: cmp eax,DWORD PTR fX2 ; Flags = Max value - pV2->fX
jge @F ; If Max value > pV2->fX carry on
mov eax,DWORD PTR fX2 ; Max value = pV2->fX
jmp TCL_XDone ; goto TCL_XDone (cannot be min too)
@@: cmp ecx,DWORD PTR fX2 ; Flags = Min value - pV2->fX
jle TCL_XDone ; If Min value < pV2->fX carry on
mov ecx,DWORD PTR fX2 ; Min value = pV2->fX
;
; Now eax = X1 (Max X) and ecx = X0 (Min X) as floating point, we check here
; if X1 (Max X) is negative as this indicates an off-screen poly that can
; be skipped. If X1 is +ive but X0 is -ive then we set X0 to 0.
; This saves us coping with negative values during the quicky float to
; integer conversions later.
;
TCL_XDone:
or eax,eax ; Flags = eax & eax (Max X)
js TCL_ShortCut0 ; if ( Max X < 0 ) next poly please
or ecx,ecx ; Flags = ecx & ecx (Min X)
jns @F ; if ( Min X >= 0 ) carry on
xor ecx,ecx ; Make MinX = 0
;
; Using integer comparisons set ecx to min Y and eax to max Y
;
@@: mov DWORD PTR [LrX0],ecx ; Store minX as rX0
mov ecx,DWORD PTR fY1 ; ecx = pV1->fY
mov DWORD PTR [LrX1],eax ; Store maxX as rX1
mov eax,DWORD PTR fY0 ; eax = pV0->fY
mov edi,DWORD PTR fY2 ; edi = pV2->fY
mov edx,eax ; edx = copy of pV0->fY
rpV2 TEXTEQU <ErrorpV2> ; We have lost at least one of the
rpV0 TEXTEQU <ErrorpV0> ; vertex pointers!
rpV1 TEXTEQU <ErrorpV1>
cmp eax,ecx ; Flags = pV0->fY - pV1->fY
jge @F ; If eax >= ecx carry on
mov eax,ecx ; eax = Max value
mov ecx,edx ; ecx = Min value
@@: cmp eax,edi ; Flags = Max value - pV2->fY
jge @F ; If Max value > pV2->fY carry on
mov eax,edi ; Max value = pV2->fY (cannot be min)
jmp TCL_YDone ; goto TCL_YDone
@@: cmp ecx,edi ; Flags = Min value - pV2->fY
jle TCL_YDone ; If Min value < pV2->fY TCL_YDone
mov ecx,edi ; Store Min value = pV2->fY
TCL_YDone:
;
; Now eax = Y1 (Max Y) and ecx = Y0 (Min Y) as floating point, we check here
; if Y1 (Max Y) is negative as this indicates an off-screen poly that can
; be skipped. If Y1 is +ive but Y0 is -ive then we set Y0 to 0.
; This saves us coping with negative values during the quicky float to
; integer conversions later.
;
or eax,eax ; Flags = eax & eax (Max Y)
js TCL_ShortCut0 ; if ( Max Y < 0 ) next poly please
or ecx,ecx ; Flags = ecx & ecx (Min Y)
jns @F ; if ( Min Y >= 0 ) carry on
xor ecx,ecx ; Make MinY = 0
@@: mov DWORD PTR [LrY1],eax ; Store Max value = eax
mov DWORD PTR [LrY0],ecx ; Store Min value = ecx
;
; Now we need to convert rX0,rX1,rY0,rY1 to integers
; use the registers ebx-edx,edi-ecx to store the bounding box.
;
fld DWORD PTR _float_to_int22; Integer conversion value
fld DWORD PTR [LrX0] ; fMinX,icv
fadd st,st(1) ; I_MinX,icv
fld DWORD PTR [LrX1] ; fMaxX,I_MinX,icv
fadd st,st(2) ; I_MaxX,I_MinX,icv
fld DWORD PTR [LrY0] ; fMinY,I_MaxX,I_MinX,icv
fadd st,st(3) ; I_MinY,I_MaxX,I_MinX,icv
fxch st(3) ; icv,I_MaxX,I_MinX,I_MinY
fadd DWORD PTR [LrY1] ; I_MaxY,I_MaxX,I_MinX,I_MinY
fxch st(2) ; I_MinX,I_MaxX,I_MaxY,I_MinY
fstp DWORD PTR [LrX0] ; rX0 = INT32 fMinX
fstp DWORD PTR [LrX1] ; rX1 = INT32 fMaxX
fstp DWORD PTR [LrY1] ; rY1 = INT32 fMaxY
fstp DWORD PTR [LrY0] ; rY0 = INT32 fMinY
fld DWORD PTR _2_1_float_18 ; 1.0f
fdiv DWORD PTR [LfDet] ; 1.0f/fDet about 30 odd cycles later
;
; X0-X1, Y0-Y1 are now 22 bit +ive integer values with 10 bits of exponent
; etc in the MSBs. We have to load them up and and off the 'fpu_junk'.
;
; By rather deviously leaving off the LSB of the mask we avoid the need
; to apply the Y_SHIFT down by 1 to the Y values before encoding them
; later on. The Y limit values should not care about the LSB anyway and the X
; values are going to be sar'd by atleast 5 after masking so we are okay.
;
mov ebx,[LrX0] ; ebx = rX0 + fpu_junk
mov edx,[LrX1] ; edx = rX1 + fpu_junk
;
; Need to generate regions for X0+1, Y0+1, X1, Y1
; Always enabled since it is required for offset correction and
; no offset correct
cmp ebx, DWORD PTR [LrX1]
; Need to add 1 to LrX0 if carry set.
adc ebx,0
;
mov edi,0003ffffeh ; edi = significant bits mask
mov eax,5 ; eax = likely shift factor
and ebx,edi ; ebx = rX0
and edx,edi ; edx = rX1
sar ebx,5 ; ebx >>= 5 (ShiftRegX is 5 or 6)
sub eax,_gPDC[ShiftRegX] ; Flags = eax = 5 - gPDC.ShiftRegX
mov ecx,[LrY1] ; ecx = rY1 + fpu_junk
mov eax,[LrY0] ; eax = rY0
je @F ; If ShiftRegX == 5 carry on
sar ebx,1 ; Extra shift of 1 for ebx
sar edx,1 ; Extra shift of 1 for edx
@@: sar edx,5 ; edx >>= 5 (ShiftRegX is 5 or 6)
;
; Need to generate regions for X0+1, Y0+1, X1, Y1
; Always enabled since it is required for offset correction and
; no offset correct
cmp eax, ecx
; Need to add 1 to LrY0 if carry set.
adc eax,0 ; eax++ if carry set.
;
and ecx,edi ; ecx = rY1
and edi,eax ; edi = rY0
mov eax,_gPDC[Ctx][bDoClipping]; eax = bDoClipping
or eax,eax ; Flags = eax | eax
je TCL_NoLimits ; if ( !bDoClipping ) TCL_NoLimits
;
; Apply [First/Last][X/Y]Region if required, likely case is for no clipping
; to occur.
;
mov eax,_gPDC[Ctx][FirstXRegion] ; eax = FirstXRegion
mov ebp,_gPDC[Ctx][LastXRegion] ; ebp = LastXRegion
cmp ebx,eax ; Flags = rX0 - FirstXReg
jge @F ; If rX0 >= FirstXReg skip clip
cmp edx,eax ; Flags = rX1 - FirstXReg
jl TCL_ShortCut1 ; If rX1 < FirstXReg skip poly
mov ebx,eax ; rX0 = FirstXReg (very rare)
@@: cmp edx,ebp ; Flags = rX1 - LastXReg
jle @F ; If rX1 <= LastXReg skip clip
cmp ebx,ebp ; Flags = rX0 - LastXReg
jg TCL_ShortCut1 ; If rX1 > LastXReg skip poly
mov edx,ebp ; rX1 = LastXReg (very rare)
@@: mov eax,_gPDC[Ctx][FirstYRegion] ; eax = FirstYRegion
mov ebp,_gPDC[Ctx][LastYRegion] ; ebp = LastYRegion
cmp edi,eax ; Flags = rY0 - FirstYReg
jge @F ; If rY0 >= FirstYReg skip clip
cmp ecx,eax ; Flags = rY1 - FirstYReg
jl TCL_ShortCut1 ; If rY1 < FirstYReg skip poly
mov edi,eax ; rY0 = FirstYReg (very rare)
and edi,0fffffffeh ; ensure LSB of Y value stays zero
@@: cmp ecx,ebp ; Flags = rY1 - LastYReg
jle @F ; If rY1 <= LastYReg skip clip
cmp edi,ebp ; Flags = rY0 - LastYReg
jg TCL_ShortCut1 ; If rY1 > LastYReg skip poly
mov ecx,ebp ; rY1 = LastYReg (very rare)
and ecx,0fffffffeh ; ensure LSB of Y value stays zero
@@:
;
; Region bounding box now established in ebx-edx,edi-ecx
;
TCL_NoLimits:
shl ebx,5 ; ebx <<= 5 (X0)
mov eax,MASK_TRANS ; eax = MASK_TRANS
mov ebp,[LuCurrentType] ; ebp = uCurrentType
add ebx,edx ; ebx = (X0<<5)+X1
and eax,_gPDC[TSPControlWord]; eax = gPDC.TSPControlWord & MASK_TRANS
je @F ; If not transparent @@
;
; Transparent case is not ideal, but not a performance issue as such
;
mov eax,ebp ; eax = uCurrentType
and eax,1 ; eax &= 1
mov edx,uTCLDoneFirst[eax*4]; AGI 1: edx = uTCLDoneFirst[eax]
test edx,edx ; Flags = edx & edx
jne @F ; If already set skip below
or ebp,2 ; ebp |= PACKED_TRANSTYPE_SETMASK
mov DWORD PTR uTCLDoneFirst[eax*4],1; uTCLDoneFirst[eax] = 1
;
; Back to the main track, ebp = uCurrentType, bounding box = ebx-edx,edi-ecx
; (LSBs of Y values have already been masked off earlier).
@@:
shl ebp,29 ; ebp = uCurrentType<<29
mov eax,[LuDefaultType] ; eax = uDefaultType
shl edi,18 ; edi <<= (19-1) (Y0)
mov [LuCurrentType],eax ; uCurrentType = eax
mov eax,DWORD PTR [PpAddfn] ; eax = pAddfn
add ebp,edi ; ebp += edi (Y0)
shl ecx,9 ; ecx <<= (9-1) (Y1)
add ebp,ebx ; ebp += ebx = (X0<<5) + X1
add ebp,ecx ; ebp += ecx (Y1)
or eax,eax ; Flags = pAddFn | pAddFn
mov [esi][ITreg],ebp ; pTri->reg = ebp
mov ebp, DWORD PTR _gpMatCurrent
fstp DWORD PTR [esi][f1OverDet]; pTri->f1OverDet= (late as pos.)
mov DWORD PTR [esp],esi ; Pass pTri as only para
je @F ; If no pAddFn skip call
call [PpAddFn] ; Call pAddFn
@@: add ebp,64 ; gpMatCurrent++
add esi,64 ; pTri++
mov eax,[OFFSET FLAT: _gpTri][PITRI_SIZE*IBUFFERSIZE]
mov DWORD PTR _gpMatCurrent, ebp
cmp eax,esi ; Flags = gpTri[IBUFFERSIZE]-pTri
jne TCL_Loop ; If not at end of buffer TCL_Loop
TCL_Done:
add esp,Adjust ; Lose locals
mov eax,esi ; eax = pTri
sub eax,OFFSET FLAT: _gpTri ; eax = pTri - gpTri
pop ebx ; AGI 1 cycle with stack adjust
shr eax,6 ; eax /= PITRI_SIZE
pop ebp ; Recover remaining registers
pop esi
pop edi
ret
ALIGN 4
__ProcessTriCoreLite ENDP
;_ProcessTriCoreLite ENDS
_TEXT ENDS
_DATA1 SEGMENT PARA PUBLIC USE32 'DATA'
_2_1_float_13 DD 000000000H,03e000000H ; xf64
_2_1_float_18 DD 03f800000H ; xf32
_2_1_float_18_d DD 000000000H,03ff00000H ; xf32
_float_to_int22 DD 04B400000H ; MAGIC_FLOAT TO INT22 VALUE
_DATA1 ENDS
_DATA SEGMENT PARA PUBLIC USE32 'DATA'
_DATA ENDS
; -- End _ProcessTriCoreLite
EXTRN __fltused:BYTE
END
|
;RLE decompressor by Shiru (NESASM version)
;uses 4 bytes in zero page
;decompress data from an address in X/Y to PPU_DATA
RLE_LOW equ $00
RLE_HIGH equ RLE_LOW+1
RLE_TAG equ RLE_HIGH+1
RLE_BYTE equ RLE_TAG+1
unrle
stx RLE_LOW
sty RLE_HIGH
ldy #0
jsr rle_byte
sta RLE_TAG
.1
jsr rle_byte
cmp RLE_TAG
beq .2
sta PPU_DATA
sta RLE_BYTE
bne .1
.2
jsr rle_byte
cmp #0
beq .4
tax
lda RLE_BYTE
.3
sta PPU_DATA
dex
bne .3
beq .1
.4
rts
rle_byte
lda [RLE_LOW],y
inc RLE_LOW
bne .1
inc RLE_HIGH
.1
rts |
;
; Startup stub for z88 Shell programs
;
; Created 12/2/2002 djm
;
; $Id: z88s_crt0.asm,v 1.8 2007/06/27 20:49:28 dom Exp $
INCLUDE "#stdio.def"
INCLUDE "#error.def"
INCLUDE "#shellapi.def"
org shell_loadaddr-shell_headerlen
.header_start
defm "!bin"
defb shell_verh
defb shell_verm
defb shell_verl
defb 13
.shell_length
defw 0 ; Fill in by make program
defw start
;-----------
; Code starts executing from here
;-----------
.start
push bc ; Preserve registers that need to be
push de
ld (saveix),ix
ld (saveiy),iy
ld (start1+1),sp ;Save starting stack
ld hl,(shell_cmdlen)
ld de,(shell_cmdaddr)
add hl,de
ld (hl),0 ; terminate command line
ld hl,-100 ; atexit stack (64) + argv space
add hl,sp
ld sp,hl
ld (exitsp),sp
call doerrhan ;Initialise a laughable error handler
;-----------
; Initialise the (ANSI) stdio descriptors so we can be called agin
;-----------
IF DEFINED_ANSIstdio
ld hl,__sgoioblk+2
ld (hl),19 ;stdin
ld hl,__sgoioblk+6
ld (hl),21 ;stdout
ld hl,__sgoioblk+10
ld (hl),21 ;stderr
ENDIF
;; Read in argc/argv
ld hl,0 ; NULL pointer at end just in case
push hl
;; Try and work out the length available
ld hl,(shell_cmdlen)
ld de,(shell_cmdaddr)
add hl,de ; points to end
ex de,hl ; end now in de, hl=cmdaddr
ld bc,(shell_cmdptr)
add hl,bc ; start in hl
push de ; save end
ex de,hl ; hl = end, de = start
and a
sbc hl,de ; hl is length available
ex de,hl ; is now in de
pop hl ; points to terminator
ld c,0 ; number of arguments
ld a,d
or e
jr z,argv_none
dec hl
dec de ; available length
.argv_loop
ld a,d
or e
jr z,argv_exit
ld a,(hl)
cp ' '
jr nz,argv_loop2
ld (hl),0 ; terminate previous one
inc hl
inc c
push hl
dec hl
.argv_loop2
dec hl
dec de
jr argv_loop
.argv_exit
push hl ; first real argument
inc c
.argv_none
ld hl,end ; program name
inc c
push hl
ld hl,0
add hl,sp ; address of argv
ld b,0
push bc ; argc
push hl ; argv
ld hl,(shell_cmdlen)
ld (shell_cmdptr),hl
call_oz(gn_nln) ; Start a new line...
IF DEFINED_farheapsz
call init_far ;Initialise far memory if required
ENDIF
call _main ;Run the program
IF DEFINED_farheapsz
call freeall_far ;Initialise far memory if required
ENDIF
pop bc ; kill argv
pop bc ; kill argc
.cleanup ;Jump back here from exit() if needed
IF DEFINED_ANSIstdio
LIB closeall
call closeall ;Close any open files (fopen)
ENDIF
call resterrhan ;Restore the original error handler
.start1 ld sp,0 ;Restore stack to entry value
ld ix,(saveix) ;Get back those registers
ld iy,(saveiy)
pop de
pop bc
jp shell_next ; phew! back to Forth at last.
;-----------
; Install the error handler
;-----------
.doerrhan
xor a
ld (exitcount),a
ld b,0
ld hl,errhand
call_oz(os_erh)
ld (l_erraddr),hl
ld (l_errlevel),a
ret
;-----------
; Restore BASICs error handler
;-----------
.resterrhan
ld hl,(l_erraddr)
ld a,(l_errlevel)
ld b,0
call_oz(os_erh)
.processcmd ;processcmd is called after os_tin
ld hl,0
ret
;-----------
; The error handler
;-----------
.errhand
ret z ;Fatal error
cp rc_esc
jr z,errescpressed
ld hl,(l_erraddr) ;Pass everything to BASIC's handler
scf
.l_dcal jp (hl) ;Used for function pointer calls also
.errescpressed
call_oz(os_esc) ;Acknowledge escape pressed
jr cleanup ;Exit the program
;-----------
; Select which vfprintf routine is needed
;-----------
._vfprintf
IF DEFINED_floatstdio
LIB vfprintf_fp
jp vfprintf_fp
ELSE
IF DEFINED_complexstdio
LIB vfprintf_comp
jp vfprintf_comp
ELSE
IF DEFINED_ministdio
LIB vfprintf_mini
jp vfprintf_mini
ENDIF
ENDIF
ENDIF
;--------
; Far memory setup
;--------
IF DEFINED_farheapsz
LIB freeall_far
XDEF farpages
XDEF malloc_table
XDEF farmemspec
XDEF pool_table
INCLUDE "#init_far.asm"
; Variables that can't be place in the normal defvars
.copybuff defs 258
.actual_malloc-table
defs ((farheapsz/256)+1)*2
; Now some memory shared with Forth - same as application setup
DEFVARS 8192
{
pool_table ds.b 224
malloc_table ds.w 1
farpages ds.w 1
farmemspec ds.b 1
}
ENDIF
;--------
; This bit of code allows us to use OZ ptrs transparently
; We copy any data from up far to a near buffer so that OZ
; is happy about it
; Prototype is extern void __FASTCALL__ *cpfar2near(far void *)
;--------
IF DEFINED_farheapsz
LIB strcpy_far
._cpfar2near
pop bc ;ret address
pop hl
pop de ;far ptr
push bc ;keep ret address
ld a,e
and a
ret z ;already local
push ix ;keep ix safe
ld bc,0 ;local
push bc
ld bc,copybuff
push bc ;dest
push de ;source
push hl
call strcpy_far
pop bc ;dump args
pop bc
pop bc
pop bc
pop ix ;get ix back
ld hl,copybuff
ret
ELSE
; We have no far code installed so all we have to do is fix the stack
._cpfar2near
pop bc
pop hl
pop de
push bc
ret
ENDIF
;----------
; The system() function for the shell
;----------
XDEF _system
._system
pop de ; DE=return address
pop bc ; BC=command address
push bc
push de
push bc ; Forth stack: addr--
ld hl,system_forthcode
call _shellapi
; Forth stack: flag--
pop hl ; HL=0 or error code
ret
.system_forthcode
defw shell_also,shell_internal,shell_ztos,shell_eval,shell_previous
defw shellapi_back
;----------
; The shellapi() interface
;----------
XDEF _shellapi
._shellapi
push hl
call resterrhan ;restore forth error handler
pop de ; DE=Forth's IP
ld iy,(saveiy) ; IY=Forth's UP
ld ix,(saveix) ; IX=Forth's RSP
pop hl
dec ix
ld (ix+0),h ; save return address on Forth's return stack
dec ix
ld (ix+0),l
pop bc ; BC=TOS
jp shell_next ; execute Forth code
.shellapi_back
push bc ; stack TOS
ld e,(ix+0)
ld d,(ix+1)
push de ; stack return address
call doerrhan ;put c error hander back
ret
;-----------
; Define the stdin/out/err area. For the z88 we have two models - the
; classic (kludgey) one and "ANSI" model
;-----------
.__sgoioblk
IF DEFINED_ANSIstdio
INCLUDE "#stdio_fp.asm"
ELSE
defw -11,-12,-10
ENDIF
;-----------
; Now some variables
;-----------
.l_erraddr defw 0 ; BASIC error handler address
.l_errlevel defb 0 ; And error level
.coords defw 0 ; Current graphics xy coordinates
.base_graphics defw 0 ; Address of the Graphics map
.gfx_bank defb 0 ; And the bank
._std_seed defw 0 ; Seed for integer rand() routines
.exitsp defw 0 ; Address of where the atexit() stack is
.exitcount defb 0 ; How many routines on the atexit() stack
IF DEFINED_NEED1bitsound
.snd_asave defb 0 ; Sound variable
.snd_tick defb 0 ; " "
ENDIF
.heaplast defw 0 ; Address of last block on heap
.heapblocks defw 0 ; Number of blocks
.packintrout defw 0 ; Address of user interrupt routine
.saveix defw 0 ; Save ix for system() calls
.saveiy defw 0 ; Save iy for system() calls
;-----------
; Unnecessary file signature
;-----------
defm "Small C+ z88shell"
.end defb 0
;-----------
; Floating point
;-----------
IF NEED_floatpack
INCLUDE "#float.asm"
.fp_seed defb $80,$80,0,0,0,0 ; FP seed (unused ATM)
.extra defs 6 ; Extra register temp store
.fa defs 6 ; ""
.fasign defb 0 ; ""
ENDIF
|
<%
from pwnlib.shellcraft.arm.linux import syscall
%>
<%page args="fd, iovec, count, offset"/>
<%docstring>
Invokes the syscall pwritev. See 'man 2 pwritev' for more information.
Arguments:
fd(int): fd
iovec(iovec): iovec
count(int): count
offset(off_t): offset
</%docstring>
${syscall('SYS_pwritev', fd, iovec, count, offset)}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r15
push %rax
push %rbp
push %rdx
push %rsi
lea addresses_normal_ht+0xc3ee, %rdx
nop
sub $21923, %rsi
mov $0x6162636465666768, %r10
movq %r10, %xmm3
movups %xmm3, (%rdx)
nop
inc %rdx
lea addresses_WT_ht+0x1b41c, %rbp
nop
nop
nop
nop
add %r11, %r11
movw $0x6162, (%rbp)
nop
nop
inc %rbp
lea addresses_WT_ht+0xa18e, %rsi
nop
nop
cmp $55771, %rax
mov $0x6162636465666768, %r10
movq %r10, (%rsi)
nop
nop
nop
xor $23388, %rdx
lea addresses_D_ht+0x1bf8e, %r10
and %r15, %r15
movb $0x61, (%r10)
add $27190, %r15
lea addresses_WT_ht+0xfa9c, %rsi
nop
xor %r15, %r15
mov $0x6162636465666768, %r10
movq %r10, %xmm6
vmovups %ymm6, (%rsi)
nop
add %rsi, %rsi
lea addresses_WC_ht+0x1d98e, %rsi
nop
nop
sub $43017, %rdx
movl $0x61626364, (%rsi)
nop
nop
nop
nop
nop
sub $37949, %r10
lea addresses_UC_ht+0x10c8e, %rdx
nop
nop
nop
and %rax, %rax
movb $0x61, (%rdx)
nop
nop
nop
and $52249, %r15
lea addresses_normal_ht+0x720e, %rax
nop
nop
nop
nop
sub %r10, %r10
movw $0x6162, (%rax)
nop
xor $45426, %r15
lea addresses_D_ht+0xaf5e, %r10
dec %rdx
movb (%r10), %al
nop
nop
dec %rdx
lea addresses_WT_ht+0xe98e, %r11
nop
nop
nop
nop
and %rbp, %rbp
mov (%r11), %r15d
nop
nop
nop
nop
nop
cmp %r10, %r10
lea addresses_WC_ht+0x1eee, %rdx
nop
nop
nop
nop
nop
and %rbp, %rbp
mov $0x6162636465666768, %r10
movq %r10, %xmm6
movups %xmm6, (%rdx)
nop
nop
dec %r15
pop %rsi
pop %rdx
pop %rbp
pop %rax
pop %r15
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r14
push %r8
push %rbp
push %rbx
push %rcx
push %rdi
// Faulty Load
lea addresses_normal+0x598e, %rdi
and $37041, %rcx
movb (%rdi), %r8b
lea oracles, %r14
and $0xff, %r8
shlq $12, %r8
mov (%r14,%r8,1), %r8
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r8
pop %r14
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': False, 'type': 'addresses_normal'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': True, 'type': 'addresses_normal'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 4, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 10, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 9, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 9, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 7, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'}
{'dst': {'NT': True, 'AVXalign': False, 'size': 2, 'congruent': 4, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 4, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 9, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 4, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
;***************************************************************************
;*
;* Title: ppg_III_pos_edge_ints
;* Author: Seyi Olajuyi & Bassel El Amine
;* Version: 1.0
;* Last updated: 2019/11/21
;* Target: ATmega 324
;*
;* DESCRIPTION
;*
;*
;*
;*
;* VERSION HISTORY
;* 1.0 Original version
;***************************************************************************
.nolist
.include "m324adef.inc"
.list
.dseg ;The variable below are in SRAM
burst_count_setting_bcd: .byte 3; setting unpacked BCD ;THIS HAS THREE BTYE allocated to the variable name
burst_count: .byte 1; pulses left to generated in burst
keyvalue: .byte 1; stores the keyvalue into a variable
polling_for_keypad: .byte 1; used to store the values in the external interrupt flag register
polling_for_button: .byte 1; used to store the values in the external interrupt flag register
;burst_count_setting_bcd is right most digit and
; (burst_count_setting_bcd + 2) is the left most digit
.cseg
reset:
.org RESET ;reset interrupt vector
rjmp start ;program starts here at reset
.org INT0addr ;INT0 interrupt vector
rjmp keypress_ISR
.org INT1addr
rjmp pb_press_ISR
;**********************************************************************
;************* M A I N A P P L I C A T I O N C O D E *************
;**********************************************************************
start:
ldi r16, LOW(RAMEND) ;initialize SP to point to top of stack
out SPL, r16
ldi r16, HIGH(RAMEND)
out SPH, r16
ldi r16, (1 << ISC00) | (1 << ISC01) | (1 << ISC10) | (1 << ISC11)
sts EICRA, r16
ldi r16, $03 ; Enable interrupt request at INTO & INT1
out EIMSK, r16
ldi r16, $ff ; load r16 with all 1s.
out DDRB, r16 ; set portB = output
ldi r16, $03 ; Set pin 0 & pin 1 to output, everyother pin is an input
out DDRD, r16
sbi DDRA, 7 ; Set pin 7 on PORTA to output
sbi portB, 4 ; set /SS of DOG LCD = 1 (Deselected)
rcall init_lcd_dog ; init display, using SPI serial interface
rcall clr_dsp_buffs ; clear all three buffer lines
rcall update_lcd_dog ; update the display
ldi YH, high (dsp_buff_1) ; Load YH and YL as a pointer to 1st
ldi YL, low (dsp_buff_1) ; byte of dsp_buff_1 (Note - assuming
; (dsp_buff_1 for now).
sei ;set global interrupt enable
variable_reset:
; RESET THE VARIABLES WITH ZERO
ldi r17, $00
sts burst_count_setting_bcd + 2, r17
sts burst_count_setting_bcd + 1, r17
sts burst_count_setting_bcd + 0, r17
sts polling_for_keypad, r17
sts polling_for_button, r17
sts burst_count, r17
sts keyvalue, r17
;****************************************************************
;***********************CODE BEGINS******************************
;****************************************************************
;This runs after the peripherals are initalized
state_1:
; Reset the polling for the keypad press, this is important because state_2 jumps to this label
ldi r17, $00
sts polling_for_keypad, r17
;This Convert the registers to PACKED BCD
convert_to_Packed_BCD:
lds r16, burst_count_setting_bcd ; Retrieve the value store in the FIRST byte of burst_count_setting_bcd and store it in r16
lds r17, burst_count_setting_bcd + 1 ; Retrieve the value store in the SECOND byte of burst_count_setting_bcd and store it in r17
lds r18, burst_count_setting_bcd + 2 ; Retrieve the value store in the THIRD byte of burst_count_setting_bcd and store it in r18
swap r17 ; Swap the nibble in r17
or r16, r17 ; Or r16 & r17, Combine the two contents of two registers into one register (r16)
andi r18, $0F ; AND r18 & $0F, clear the high nibble of r18
mov r17, r18 ; Move the content of r18 into r17
ldi r18, $00 ; Load r18 with zero, this will be useful when we are trying to convert
; Packed BCD into a 16-bit R16 0x0a byte{registers}@R16bianry value
;This converts the Packed BCD into the 16-bit binary
convert_BCD_to_Binary:
call BCD2bin16
mov r19, r14 ; Moves the low byte of the 16-bit binary value into r17
sts burst_count, r19 ; Store the value of r17 into burst_count_bin
lds r16, polling_for_button
cpi r16, 1
breq state_2
rcall display_the_value
rjmp state_1
state_2:
ldi r16, 0 ; Reset the flag that polls the push button
sts polling_for_button, r16
; Reinitialize the Burst count
ldi r16, 10 ; Load ten into r16, This is to create the 1 ms delay
lds r19, burst_count ; This loads r19 with the orginal binary value
check_zero:
cpi r19, $00 ; Branch to generate a pulse if burst count = 0
breq generate_a_pulse
;This generate a pulse that is supposed to be 1 ms wide
pulse_generator:
sbi PORTA, 7 ; set bit for pulse
rcall var_delay
ldi r16, 10 ; pulse width delay
cbi PORTA, 7 ; clear bit for pulse
rcall var_delay
ldi r16, 10 ; time between pulses delay
dec r19 ; decrement the binary value
brne pulse_generator
;This part is reached if the burst count is equal to zero
check_flag_2:
lds r20, polling_for_button
lds r21, polling_for_keypad
cpi r20, 1 ; Check if the pushbutton is pressed
breq state_2
cpi r21, 1 ; Check if the pushbutton is pressed
breq service_keypad_input
rjmp check_flag_2
service_keypad_input:
lds r18, keyvalue
cpi r18, $0A ; checks if the key value is equal to CLEAR
breq state_1 ; goes to the beginning if the key value is equal to CLEAR
rjmp check_flag_2 ; goes back to generate another set of pulses
; This is branched if burst count is equal to zero
generate_a_pulse:
sbi PORTA, 7 ; set bit for pulse
rcall var_delay
ldi r16, 10 ; pulse width delay
cbi PORTA, 7 ; clear bit for pulse
rcall var_delay
ldi r16, 10
; time between pulses delay
lds r20, polling_for_keypad
sbrs r20, 0 ; Skips the rjmp instruction if the value in polling_for_keypad = 1
rjmp generate_a_pulse
lds r18, keyvalue
cpi r18, $0A ; Check if key value is equal to clear
breq prompt1
; Reset the polling for the keypad
ldi r17, $00
sts polling_for_keypad, r17
rjmp generate_a_pulse
prompt1:
rjmp variable_reset
;---------------------------- SUBROUTINES ----------------------------
;************************
;NAME: clr_dsp_buffs
;FUNCTION: Initializes dsp_buffers 1, 2, and 3 with blanks (0x20)
;ASSUMES: Three CONTIGUOUS 16-byte dram based buffers named
; dsp_buff_1, dsp_buff_2, dsp_buff_3.
;RETURNS: nothing.
;MODIFIES: r25,r26, Z-ptr
;CALLS: none
;CALLED BY: main application and diagnostics
;********************************************************************
clr_dsp_buffs:
ldi R25, 48 ; load total length of both buffer.
ldi R26, ' ' ; load blank/space into R26.
ldi ZH, high (dsp_buff_1) ; Load ZH and ZL as a pointer to 1st
ldi ZL, low (dsp_buff_1) ; byte of buffer for line 1.
;set DDRAM address to 1st position of first line.
store_bytes:
st Z+, R26 ; store ' ' into 1st/next buffer byte and
; auto inc ptr to next location.
dec R25 ;
brne store_bytes ; cont until r25=0, all bytes written.
ret
;**********************************************
;SUBROUTINE FOR DISPLAYING THE INPUT TO LCD
;**********************************************
display_the_value:
ldi YH, high (dsp_buff_1) ; Load YH and YL as a pointer to 1st
ldi YL, low (dsp_buff_1) ; byte of dsp_buff_1 (Note - assuming
; (dsp_buff_1 for now).
ldi r16, 'n'
st Y+, r16
ldi r16, ' '
st Y+, r16
ldi r16, '='
st Y+, r16
ldi r16, ' '
st Y+, r16
ldi r17, $30 ; Load $30 into r16
; store the ascii representation of the digit in the buffer
lds r16, (burst_count_setting_bcd + 2) ; Store the leftmost keyvalue into r16
or r16, r17 ; Adds $30 to the keyvalue, which turn the keyvalue into ASCII
st Y+, r16 ; Put the value into the display buffer
lds r16, (burst_count_setting_bcd + 1) ;
or r16, r17 ; Adds $30 to the keyvalue, which turn the keyvalue into ASCII
st Y+, r16
lds r16, (burst_count_setting_bcd + 0) ; Store the rightmost keyvalue into r16
or r16, r17 ; Adds $30 to the keyvalue, which turn the keyvalue into ASCII
st Y+, r16 ; Put the value into the display buffer
call update_lcd_dog ; update the display
ret
;***********************************************
;SUBROUTINE FOR STORING THE VALUE INTO THE Variable
;**********************************************
store_value:
;r18 is the value read by the input
lds r18, keyvalue
lds r16, burst_count_setting_bcd + 1 ; Load r16 with the middle digit
sts burst_count_setting_bcd + 2, r16 ; Put the middle digit into the leftmost digit
lds r16, burst_count_setting_bcd + 0 ; Load r16 with the Rightmost digit
sts burst_count_setting_bcd + 1, r16 ; Put the rightmost digit into the middle digit
sts burst_count_setting_bcd + 0, r18 ; Store the new number into the rightmost digit
ret
;**********************************
;SUBROUTINE FOR RETRIEVING INPUT(PART 2)
;*********************************
get_key_value:
in r18, PIND ; Store the Input into r18
andi r18, $F0 ; Clear the low nibble of r18
swap r18 ; Swap the nibble
call keycode2keyvalue ; Convert the input into HEXVALUES (NOT ASCII)
ret
;********************************
;SUBROUTINE FOR LOOKUP TABLE
;******************************
keycode2keyvalue:
lookup:
ldi ZH, high (keytable * 2) ;set Z to point to start of table
ldi ZL, low (keytable * 2)
ldi r16, $00 ;add offset to Z pointer
add ZL, r18 ;originally r18
add ZH, r16
lpm r18, Z
ret
;**************************
;SUBROUTINE FOR DELAY
;************************
var_delay: ;delay for ATmega324 @ 1MHz = r16 * 0.1 ms
outer_loop:; r16 should equal to 10
ldi r17, 32
inner_loop:
dec r17
brne inner_loop
dec r16
brne outer_loop
ret
;***************************************************************************
;*
;* "BCD2bin16" - BCD to 16-Bit Binary Conversion
;*
;* This subroutine converts a 5-digit packed BCD number represented by
;* 3 bytes (fBCD2:fBCD1:fBCD0) to a 16-bit number (tbinH:tbinL).
;* MSD of the 5-digit number must be placed in the lowermost nibble of fBCD2.
;*
;* Let "abcde" denote the 5-digit number. The conversion is done by
;* computing the formula: 10(10(10(10a+b)+c)+d)+e.
;* The subroutine "mul10a"/"mul10b" does the multiply-and-add operation
;* which is repeated four times during the computation.
;*
;* Number of words :30
;* Number of cycles :108
;* Low registers used :4 (copyL,copyH,mp10L/tbinL,mp10H/tbinH)
;* High registers used :4 (fBCD0,fBCD1,fBCD2,adder)
;*
;***************************************************************************
;***** "mul10a"/"mul10b" Subroutine Register Variables
.def copyL =r12 ;temporary register
.def copyH =r13 ;temporary register
.def mp10L =r14 ;Low byte of number to be multiplied by 10
.def mp10H =r15 ;High byte of number to be multiplied by 10
.def adder =r19 ;value to add after multiplication
;***** Code
mul10a: ;***** multiplies "mp10H:mp10L" with 10 and adds "adder" high nibble
swap adder
mul10b: ;***** multiplies "mp10H:mp10L" with 10 and adds "adder" low nibble
mov copyL,mp10L ;make copy
mov copyH,mp10H
lsl mp10L ;multiply original by 2
rol mp10H
lsl copyL ;multiply copy by 2
rol copyH
lsl copyL ;multiply copy by 2 (4)
rol copyH
lsl copyL ;multiply copy by 2 (8)
rol copyH
add mp10L,copyL ;add copy to original
adc mp10H,copyH
andi adder,0x0f ;mask away upper nibble of adder
add mp10L,adder ;add lower nibble of adder
brcc m10_1 ;if carry not cleared
inc mp10H ; inc high byte
m10_1: ret
;***** Main Routine Register Variables
.def tbinL =r14 ;Low byte of binary result (same as mp10L)
.def tbinH =r15 ;High byte of binary result (same as mp10H)
.def fBCD0 =r16 ;BCD value digits 1 and 0
.def fBCD1 =r17 ;BCD value digits 2 and 3
.def fBCD2 =r18 ;BCD value digit 5
;***** Code
BCD2bin16:
andi fBCD2,0x0f ;mask away upper nibble of fBCD2
clr mp10H
mov mp10L,fBCD2 ;mp10H:mp10L = a
mov adder,fBCD1
rcall mul10a ;mp10H:mp10L = 10a+b
mov adder,fBCD1
rcall mul10b ;mp10H:mp10L = 10(10a+b)+c
mov adder,fBCD0
rcall mul10a ;mp10H:mp10L = 10(10(10a+b)+c)+d
mov adder,fBCD0
rcall mul10b ;mp10H:mp10L = 10(10(10(10a+b)+c)+d)+e
ret
;***************************************************************************
;*
;* "keypress_ISR" - Check Interrupts at INT0
;*
;* Description: Get the keyvalue if the key is pressed, the keyvalue is stored if the key is a number
;*
;* Author: Seyi Olajuyi & Bassel El Amine
;* Version:
;* Last updated: 11/21/19
;* Target: ATmega324A
;* Number of words:
;* Number of cycles: N/A
;* Low registers modified: none
;* High registers modified: none
;*
;* Parameters:
;* Notes:
;*
;***************************************************************************
;INT0 interrupt service routine
keypress_ISR:
push r18
push r16 ;save r16
in r16, SREG ;save SREG
push r16
ldi r16 ,1 ; Set polling_for_keypad
sts polling_for_keypad, r16 ; Use to find out if the keypad was pressed
ldi r16, (1 <<INTF0)
out EIFR, r16
rcall get_key_value
cpi r18, $0A
sts keyvalue, r18 ; if key value is not a number, end the subroutine.
brlo skip_line_1
restore_values_1:
pop r16 ;restore SREG
out SREG,r16
pop r16 ;restore r16
pop r18 ;restore r18
reti ;return from interrupt
skip_line_1:
rcall store_value
rjmp restore_values_1
;***************************************************************************
;*
;* "pb_press_ISR" - Check Interrupts at INT1
;*
;* Description: Checks if the push button is pressed
;*
;* Author: Ken Short
;* Version:
;* Last updated: 11/21/19
;* Target: ATmega324A
;* Number of words:
;* Number of cycles: 16
;* Low registers modified: none
;* High registers modified: none
;*
;* Parameters: Uses PORTB register to hold the count and drive LEDs
;* connected to that port.
;*
;* Notes:
;*
;***************************************************************************
;INT1 interrupt service routine
pb_press_ISR:
push r16 ;save r16
in r16, SREG ;save SREG
push r16
wait_for_bounce_1:
sbic PIND, 3
rjmp wait_for_bounce_1
ldi r16, 100
rcall var_delay
sbic PIND, 3
rjmp wait_for_bounce_1
ldi r16, (1 <<INTF1)
out EIFR, r16
ldi r16 ,1 ; Set polling_for_button
sts polling_for_button, r16 ; Use to find out if the button was pressed
restore_value_2:
pop r16 ;restore SREG
out SREG,r16
pop r16 ;restore r16
reti ;return from interrupt
keytable: .db $01, $02, $03, $0F, $04, $05, $06, $0E, $07, $08, $09, $0D
.db $0A, $00, $0B, $0C
.nolist
.include "lcd_dog_asm_driver_m324a.inc"
.list
|
STACK SEGMENT STACK
DB 256 DUP (0)
STACK ENDS
DATA SEGMENT
ARY1 DB 10 DUP (3)
SUM1 DW ?
ARY2 DB 8 DUP (5)
SUM2 DW ?
ARY3 DB 6 DUP (8)
SUM3 DW ?
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE,DS:DATA,SS:STACK
START: MOV AX,DATA
MOV DS,AX
MOV AX,SIZE ARY1
PUSH AX
MOV AX,OFFSET ARY1
PUSH AX
CALL SUM
MOV AX,SIZE ARY2
PUSH AX
MOV AX,OFFSET ARY2
PUSH AX
CALL SUM
MOV AX,SIZE ARY3
PUSH AX
MOV AX,OFFSET ARY3
PUSH AX
CALL SUM
MOV AH,4CH
INT 21H
SUM PROC NEAR
PUSH AX
PUSH BX
PUSH CX
PUSH BP
MOV BP,SP
PUSHF
MOV CX,[BP+12]
MOV BX,[BP+10]
MOV AX,0
AGAIN: ADD AL,[BX]
INC BX
ADC AH,0
LOOP AGAIN
MOV [BX],AX
POPF
POP BP
POP CX
POP BX
POP AX
RET 4
SUM ENDP
CODE ENDS
END START
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "TankMovementComponent.h"
#include "TankTrack.h"
#include "BattleTank.h"
void UTankMovementComponent::Initialise(UTankTrack* LeftTrackToSet, UTankTrack* RightTrackToSet)
{
LeftTrack = LeftTrackToSet;
RightTrack = RightTrackToSet;
}
void UTankMovementComponent::IntendMoveForward(float Throw)
{
if (!ensure(LeftTrack && RightTrack)) { return; }
LeftTrack->SetThrottle(Throw);
RightTrack->SetThrottle(Throw);
// TODO pervent double speed?
// TODO fix forces and/or collisions: tank goes crazy when speeding and changing directions
}
void UTankMovementComponent::IntendMoveBackwards(float Throw)
{
if (!ensure(LeftTrack && RightTrack)) { return; }
LeftTrack->SetThrottle(-Throw);
RightTrack->SetThrottle(-Throw);
// TODO pervent double speed?
// TODO fix forces and/or collisions: tank goes crazy when speeding and changing directions
}
void UTankMovementComponent::IntendTurnRight(float Throw)
{
if (!ensure(LeftTrack && RightTrack)) { return; }
LeftTrack->SetThrottle(Throw);
RightTrack->SetThrottle(-Throw);
// TODO pervent double speed?
// TODO fix forces and/or collisions: tank goes crazy when speeding and changing directions
}
void UTankMovementComponent::IntendTurnLeft(float Throw)
{
if (!ensure(LeftTrack && RightTrack)) { return; }
LeftTrack->SetThrottle(-Throw);
RightTrack->SetThrottle(Throw);
// TODO pervent double speed?
// TODO fix forces and/or collisions: tank goes crazy when speeding and changing directions
}
void UTankMovementComponent::RequestDirectMove(const FVector& MoveVelocity, bool bForceMaxSpeed)
{
// No need to call Super as we're replacing functionality
auto TankForward = GetOwner()->GetActorForwardVector().GetSafeNormal();
auto AIForwardIntention = MoveVelocity.GetSafeNormal();
// TODO do the same as tunrning right, for the backwards move
auto ForwardThrow = FVector::DotProduct(TankForward, AIForwardIntention);
IntendMoveForward(ForwardThrow);
// TODO don't make full turn right when angle is 270, instead turn left
auto RightThrow = FVector::CrossProduct(TankForward, AIForwardIntention).Z;
IntendTurnRight(RightThrow);
}
|
; A175827: Partial sums of ceiling(n^2/10).
; 0,1,2,3,5,8,12,17,24,33,43,56,71,88,108,131,157,186,219,256,296,341,390,443,501,564,632,705,784,869,959,1056,1159,1268,1384,1507,1637,1774,1919,2072,2232,2401,2578,2763,2957,3160,3372,3593,3824,4065,4315,4576,4847,5128,5420,5723,6037,6362,6699,7048,7408,7781,8166,8563,8973,9396,9832,10281,10744,11221,11711,12216,12735,13268,13816,14379,14957,15550,16159,16784,17424,18081,18754,19443,20149,20872,21612,22369,23144,23937,24747,25576,26423,27288,28172,29075,29997,30938,31899,32880,33880,34901,35942,37003,38085,39188,40312,41457,42624,43813,45023,46256,47511,48788,50088,51411,52757,54126,55519,56936,58376,59841,61330,62843,64381,65944,67532,69145,70784,72449,74139,75856,77599,79368,81164,82987,84837,86714,88619,90552,92512,94501,96518,98563,100637,102740,104872,107033,109224,111445,113695,115976,118287,120628,123000,125403,127837,130302,132799,135328,137888,140481,143106,145763,148453,151176,153932,156721,159544,162401,165291,168216,171175,174168,177196,180259,183357,186490,189659,192864,196104,199381,202694,206043,209429,212852,216312,219809,223344,226917,230527,234176,237863,241588,245352,249155,252997,256878,260799,264760,268760,272801,276882,281003,285165,289368,293612,297897,302224,306593,311003,315456,319951,324488,329068,333691,338357,343066,347819,352616,357456,362341,367270,372243,377261,382324,387432,392585,397784,403029,408319,413656,419039,424468,429944,435467,441037,446654,452319,458032,463792,469601,475458,481363,487317,493320,499372,505473,511624,517825
mov $4,$0
mov $5,$0
lpb $5,1
mov $0,$4
sub $5,1
sub $0,$5
mov $3,$0
mul $3,$0
add $3,9
mov $2,$3
div $2,10
add $1,$2
lpe
|
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017 The Corallium developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "chainparams.h"
#include "main.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/foreach.hpp>
namespace Checkpoints
{
/**
* How many times we expect transactions after the last checkpoint to
* be slower. This number is a compromise, as it can't be accurate for
* every system. When reindexing from a fast disk with a slow CPU, it
* can be up to 20, while when downloading from a slow network with a
* fast multicore CPU, it won't be much higher than 1.
*/
static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;
bool fEnabled = true;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!fEnabled)
return true;
const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
//! Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex* pindex, bool fSigchecks)
{
if (pindex == NULL)
return 0.0;
int64_t nNow = time(NULL);
double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkpoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData& data = Params().Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint) / 86400.0 * data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter * fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->GetBlockTime()) / 86400.0 * data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore * fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter * fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!fEnabled)
return 0;
const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint()
{
if (!fEnabled)
return NULL;
const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH (const MapCheckpoints::value_type& i, checkpoints) {
const uint256& hash = i.second;
BlockMap::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
} // namespace Checkpoints
|
GLOBAL getMem
GLOBAL _time
GLOBAL _temperature
GLOBAL _information
GLOBAL _model
GLOBAL _invalidOpcodeException
GLOBAL _inforeg
GLOBAL _ps
GLOBAL _nice
GLOBAL _block
GLOBAL _unblock
GLOBAL _pipeInfo
GLOBAL _kill
GLOBAL _yield
section .text
;Recibe en rdi el buffer donde guardar lo leido del puntero recibido en rsi. Guarda la cantidad de bytes recibidos en rdx
getMem:
push rbp
mov rbp,rsp
push rax
mov rax,4
int 80h
pop rax
mov rsp,rbp
pop rbp
ret
;Recibe en rdi el puntero a un buffer de size 9 para guardar la hora
_time:
push rbp
mov rbp,rsp
push rax
mov rax,5
int 80h
pop rax
mov rsp,rbp
pop rbp
ret
;Recibe en rdi el string donde escribir
_information:
push rbp
mov rbp,rsp
push rax
mov rax,6
int 80h
pop rax
mov rsp,rbp
pop rbp
ret
_model:
push rbp
mov rbp,rsp
mov rax,8
int 80h
mov rsp,rbp
pop rbp
ret
_temperature:
push rbp
mov rbp,rsp
mov rax,7
int 80h
mov rsp,rbp
pop rbp
ret
_invalidOpcodeException:
push rbp
mov rbp,rsp
ud2
mov rsp,rbp
pop rbp
ret
;Funcion que retorna un vector con los valores de los registros
_inforeg:
push rbp
mov rbp,rsp
mov rax,9
int 80h
mov rsp,rbp
pop rbp
ret
_ps:
push rbp
mov rbp,rsp
mov rax, 13
int 80h
mov rsp,rbp
pop rbp
ret
_block:
push rbp
mov rbp,rsp
mov rax,14
int 80h
mov rsp,rbp
pop rbp
ret
_nice:
push rbp
mov rbp,rsp
mov rax,15
int 80h
mov rsp,rbp
pop rbp
ret
_kill:
push rbp
mov rbp,rsp
mov rax,16
int 80h
mov rsp,rbp
pop rbp
ret
_yield:
push rbp
mov rbp,rsp
mov rax,19
int 80h
mov rsp,rbp
pop rbp
ret
_unblock:
push rbp
mov rbp,rsp
mov rax,33
int 80h
mov rsp,rbp
pop rbp
ret
_pipeInfo:
push rbp
mov rbp,rsp
mov rax,34
int 80h
mov rsp,rbp
pop rbp
ret |
/// @ref core
/// @file glm/trigonometric.hpp
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
///
/// @defgroup core_func_trigonometric Angle and Trigonometry Functions
/// @ingroup core
///
/// Function parameters specified as angle are assumed to be in units of radians.
/// In no case will any of these functions result in a divide by zero error. If
/// the divisor of a ratio is 0, then results will be undefined.
///
/// These all operate component-wise. The description is per component.
///
/// Include <glm/trigonometric.hpp> to use these core features.
///
/// @see ext_vector_trigonometric
#pragma once
#include "detail/setup.hpp"
#include "detail/qualifier.hpp"
namespace glm
{
/// @addtogroup core_func_trigonometric
/// @{
/// Converts degrees to radians and returns the result.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/radians.xml">GLSL radians man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<L, T, Q> radians(vec<L, T, Q> const& degrees);
/// Converts radians to degrees and returns the result.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/degrees.xml">GLSL degrees man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<L, T, Q> degrees(vec<L, T, Q> const& radians);
/// The standard trigonometric sine function.
/// The values returned by this function will range from [-1, 1].
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/sin.xml">GLSL sin man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> sin(vec<L, T, Q> const& angle);
/// The standard trigonometric cosine function.
/// The values returned by this function will range from [-1, 1].
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/cos.xml">GLSL cos man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> cos(vec<L, T, Q> const& angle);
/// The standard trigonometric tangent function.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/tan.xml">GLSL tan man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> tan(vec<L, T, Q> const& angle);
/// Arc sine. Returns an angle whose sine is x.
/// The range of values returned by this function is [-PI/2, PI/2].
/// Results are undefined if |x| > 1.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/asin.xml">GLSL asin man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> asin(vec<L, T, Q> const& x);
/// Arc cosine. Returns an angle whose cosine is x.
/// The range of values returned by this function is [0, PI].
/// Results are undefined if |x| > 1.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/acos.xml">GLSL acos man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> acos(vec<L, T, Q> const& x);
/// Arc tangent. Returns an angle whose tangent is y/x.
/// The signs of x and y are used to determine what
/// quadrant the angle is in. The range of values returned
/// by this function is [-PI, PI]. Results are undefined
/// if x and y are both 0.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/atan.xml">GLSL atan man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> atan(vec<L, T, Q> const& y, vec<L, T, Q> const& x);
/// Arc tangent. Returns an angle whose tangent is y_over_x.
/// The range of values returned by this function is [-PI/2, PI/2].
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/atan.xml">GLSL atan man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> atan(vec<L, T, Q> const& y_over_x);
/// Returns the hyperbolic sine function, (exp(x) - exp(-x)) / 2
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/sinh.xml">GLSL sinh man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> sinh(vec<L, T, Q> const& angle);
/// Returns the hyperbolic cosine function, (exp(x) + exp(-x)) / 2
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/cosh.xml">GLSL cosh man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> cosh(vec<L, T, Q> const& angle);
/// Returns the hyperbolic tangent function, sinh(angle) / cosh(angle)
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/tanh.xml">GLSL tanh man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> tanh(vec<L, T, Q> const& angle);
/// Arc hyperbolic sine; returns the inverse of sinh.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/asinh.xml">GLSL asinh man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> asinh(vec<L, T, Q> const& x);
/// Arc hyperbolic cosine; returns the non-negative inverse
/// of cosh. Results are undefined if x < 1.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/acosh.xml">GLSL acosh man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> acosh(vec<L, T, Q> const& x);
/// Arc hyperbolic tangent; returns the inverse of tanh.
/// Results are undefined if abs(x) >= 1.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point scalar types
/// @tparam Q Value from qualifier enum
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/atanh.xml">GLSL atanh man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.1 Angle and Trigonometry Functions</a>
template <length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> atanh(vec<L, T, Q> const& x);
/// @}
}//namespace glm
#include "detail/func_trigonometric.inl"
|
/* Copyright 2020 Alibaba Group Holding Limited. 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 <cmath>
#include <random>
#include "graphlearn/core/operator/sampler/sampler.h"
#include "graphlearn/include/config.h"
namespace graphlearn {
namespace op {
class RandomSampler : public Sampler {
public:
virtual ~RandomSampler() {}
Status Sample(const SamplingRequest* req,
SamplingResponse* res) override {
int32_t count = req->NeighborCount();
int32_t batch_size = req->BatchSize();
res->SetBatchSize(batch_size);
res->SetNeighborCount(count);
res->InitNeighborIds(batch_size * count);
res->InitEdgeIds(batch_size * count);
const std::string& edge_type = req->Type();
Graph* graph = graph_store_->GetGraph(edge_type);
auto storage = graph->GetLocalStorage();
thread_local static std::random_device rd;
thread_local static std::mt19937 engine(rd());
const int64_t* src_ids = req->GetSrcIds();
const int64_t* filters = req->GetFilters();
for (int32_t i = 0; i < batch_size; ++i) {
int64_t src_id = src_ids[i];
auto neighbor_ids = storage->GetNeighbors(src_id);
if (!neighbor_ids || (filters && neighbor_ids.Size() == 1
&& neighbor_ids[0] == filters[i])) {
res->FillWith(GLOBAL_FLAG(DefaultNeighborId), -1);
} else {
auto edge_ids = storage->GetOutEdges(src_id);
std::uniform_int_distribution<> dist(0, neighbor_ids.Size() - 1);
for (int32_t j = 0; j < count;) {
int32_t idx = dist(engine);
if (!filters || filters[i] != neighbor_ids[idx]) {
res->AppendNeighborId(neighbor_ids[idx]);
res->AppendEdgeId(edge_ids[idx]);
++j;
}
}
}
}
return Status::OK();
}
};
REGISTER_OPERATOR("RandomSampler", RandomSampler);
} // namespace op
} // namespace graphlearn
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1990 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: Print Spooler
FILE: processGraphics.asm
AUTHOR: Jim DeFrisco, 28 March 1990
ROUTINES:
Name Description
---- -----------
DoGraphicsPrinting Handles printing in graphics modes
REVISION HISTORY:
Name Date Description
---- ---- -----------
Jim 3/28/90 Initial revision
DESCRIPTION:
This file contains routines to handle graphics printing
$Id: processGraphics.asm,v 1.1 97/04/07 11:11:35 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrintGraphics segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DoGraphicsInit
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Do some initialization to print a graphics page
CALLED BY: INTERNAL
PrintDocument
PASS: inherits lots of local variables from SpoolerLoop
RETURN: ax - error flag - 0 = no error
non-zero = unrecoverable error
DESTROYED: just about everything
PSEUDO CODE/STRATEGY:
Allocate a bitmap;
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Jim 03/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
CREATE_BM_FLAGS equ <mask BMC_GSTATE or mask BMC_WINDOW or mask BMC_INIT_FILL or mask BMC_OD>
DoGraphicsInit proc far
curJob local SpoolJobInfo
.enter inherit
; printer is all initialized (in PrintFile) so create bitmap
; first, make sure our file is there...
call FilePushDir ; save dir state
mov ax, SP_SPOOL ; go to spool directory
call FileSetStandardPath
call CreateBitmapFile ; create unique file
call FilePopDir ; restore directory
LONG jc exit ; couldn't create
mov cx, curJob.SJI_bandW ; get width
mov dx, curJob.SJI_swathH ; get height
mov al, curJob.SJI_colorFormat ; get color mode
call GeodeGetProcessHandle
mov di, bx
mov bx, curJob.SJI_bmFileHan ; get vm file handle
call GrCreateBitmap ;
mov curJob.SJI_bmHan, ax ; save bm han for later
mov curJob.SJI_gstate, di ; save gstate han
call GrGetWinHandle ; ax = window handle
mov curJob.SJI_bmWinHan, ax ; save it
mov dx, curJob.SJI_colorCorrection
mov ax, mask BM_CLUSTERED_DITHER ; use clustered mode
call GrSetBitmapMode ; set clustered dither
; We set the bitmap res to be that of the fax if tiramisu
; and postscipt.
test curJob.SJI_printState, mask SPS_TIRAMISU_PRINTING
jz beginUpdate
; Check to see if postscript.
push ax
mov al, curJob.SJI_printState ; check for PDL printer
and al, mask SPS_SMARTS ; is it PostScript ?
cmp al, PS_PDL
pop ax
jne beginUpdate ; no, begin update
push ax, bx, di
mov ax, curJob.SJI_pXres
mov bx, curJob.SJI_pYres
mov di, curJob.SJI_gstate
call GrSetBitmapRes
pop ax, bx, di
; at this point, the window is invalid, since WinOpen (via
; GrCreateBitmap) creates it that way. This is bad, since
; we're not going to get any MSG_META_EXPOSED for it (not being
; a real process). So lets fake an update now.
beginUpdate::
call GrBeginUpdate ; start it
call GrEndUpdate ; end it
clr ax ; signal no error
if _DUAL_THREADED_PRINTING
mov cx, curJob.SJI_bandW ; get width
mov dx, curJob.SJI_swathH ; get height
mov al, curJob.SJI_colorFormat ; get color mode
call GeodeGetProcessHandle
mov di, bx
mov bx, curJob.SJI_bmFileHan ; get vm file handle
call GrCreateBitmap ;
mov curJob.SJI_bmHan2, ax ; save bm han for later
mov curJob.SJI_gstate2, di ; save gstate han
call GrGetWinHandle ; ax = window handle
mov curJob.SJI_bmWinHan2, ax ; save it
mov dx, curJob.SJI_colorCorrection
mov ax, mask BM_CLUSTERED_DITHER ; use clustered mode
call GrSetBitmapMode ; set clustered dither
; at this point, the window is invalid, since WinOpen (via
; GrCreateBitmap) creates it that way. This is bad, since
; we're not going to get any MSG_META_EXPOSED for it (not being
; a real process). So lets fake an update now.
call GrBeginUpdate ; start it
call GrEndUpdate ; end it
clr ax ; signal no error
endif ; _DUAL_THREADED_PRINTING
exit:
.leave
ret
DoGraphicsInit endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CreateBitmapFile
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Create a unique file for the bitmap
CALLED BY: INTERNAL
DoGraphicsInit
PASS: curJob - inherited stack frame
RETURN: carry - clear (file was successfully created)
- or -
carry - set (file was not created)
DESTROYED: ax, cx, dx
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jim 3/10/93 Initial version
don 3/ 9/94 Added setting of VMAttributes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
; VMA_SINGLE_THREAD_ACCESS will speed up VMLock, since no check for
; multiple locking threads will need to occur.
; VMA_SYNC_UPDATE essentially forces the bitmap data to never be written
; to the disk, since VMUpdate is never called.
if _DISK_SPACE_OPTS
SPOOL_FILE_VM_ATTRS equ mask VMA_SINGLE_THREAD_ACCESS or \
mask VMA_SYNC_UPDATE
else
SPOOL_FILE_VM_ATTRS equ mask VMA_SINGLE_THREAD_ACCESS
endif
CreateBitmapFile proc near
uses ds
curJob local SpoolJobInfo
.enter inherit
; first copy over the template name
mov curJob.SJI_bmFileName[0], 0 ; make it empty so
; VMOpen creates it
; in the current dir
segmov ds, ss
lea dx, curJob.SJI_bmFileName ; ds:dx -> filename
; buffer
mov ax, (VMO_TEMP_FILE shl 8) or \
mask VMAF_FORCE_READ_WRITE or \
mask VMAF_FORCE_DENY_WRITE or \
mask VMAF_USE_BLOCK_LEVEL_SYNCHRONIZATION
clr cx ; default compression
call VMOpen
jc done
; set the VM attributes, if the file was created
mov curJob.SJI_bmFileHan, bx ; save file handle
mov ax, SPOOL_FILE_VM_ATTRS
call VMSetAttributes ; new attrs -> al
EC < cmp al, SPOOL_FILE_VM_ATTRS ; verify attrs >
EC < ERROR_NE SPOOL_BAD_VM_FILE_ATTRS >
clc ; indicate success
done:
.leave
ret
CreateBitmapFile endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DoGraphicsCleanup
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Cleanup from graphics printing
CALLED BY: EXTERNAL
PrintDocument
PASS: stuff in curJob stack frame
RETURN: nothing
DESTROYED: di,al, dx
PSEUDO CODE/STRATEGY:
free the bitmap/gstate/window we allocated
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Jim 06/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
DoGraphicsCleanup proc far
uses ds
curJob local SpoolJobInfo
.enter inherit
; check for smart device here. don't destroy the bitmap,
; since we didn't create one. Perhaps call a driver cleanup
; function...
mov di, curJob.SJI_gstate ; setup to kill bitmap
mov al, BMD_LEAVE_DATA ; we're gonna kill the
call GrDestroyBitmap ; file anyway
if _DUAL_THREADED_PRINTING
mov di, curJob.SJI_gstate2 ; setup to kill bitmap
mov al, BMD_LEAVE_DATA ; we're gonna kill the
call GrDestroyBitmap ; file anyway
endif ; _DUAL_THREADED_PRINTING
mov bx, curJob.SJI_bmFileHan ; fetch vm file handle
mov al, FILE_NO_ERRORS
call VMClose ; close it, then...
; nuke the file we created for the bitmap
call FilePushDir ; save dir state
mov ax, SP_SPOOL ; go to spool directory
call FileSetStandardPath
segmov ds, ss
lea dx, curJob.SJI_bmFileName ; ds:dx -> filename
call FileDelete ; ..nuke it
call FilePopDir ; restore dir
.leave
ret
DoGraphicsCleanup endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrintGraphicsPage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Print out a single page in graphics mode
CALLED BY: INTERNAL
DoGraphicsPrinting
PASS: inherits stack frame
RETURN: ax - code returned from DrawString
DESTROYED: just about everything
PSEUDO CODE/STRATEGY:
handle the printing of a single page (of paper, not a page
of the document)
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Jim 05/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrintGraphicsPage proc far
curJob local SpoolJobInfo
.enter inherit
if _LABELS
; if printing labels, use a different approach.
test curJob.SJI_info.JP_paperSizeInfo.PSR_layout, PT_LABEL
jz printPage
call PrintGraphicsLabels
.leave
ret
endif
printPage::
if (0) ; if 0'd for now because GrGetGStringBounds takes an eternity.
; Figure out the bounds of the page so we can skip over
; white space at the bottom of the page.
mov cx, GST_STREAM ; type of gstring it is
mov bx, curJob.SJI_fHan ; bx gets file handle
call GrLoadGString ; si = string handle
clr di ; no gstate
mov dx, mask GSC_NEW_PAGE ; stop at end of page
call GrGetGStringBounds
jc noBounds
movdw bxax, curJob.SJI_pYscale ; bx.ax = y scale
clr cx ; dx.cx = 72dpi yoffset
call GrMulWWFixed ; dx.cx = 300dpi yoffst
inc dx ; in case cx <> 0
cmp curJob.SJI_pageH.low, dx ; is it smaller?
jb noBounds
mov curJob.SJI_pageH.low, dx ; new page height
noBounds:
mov dl, GSKT_LEAVE_DATA ; don't kill the data
call GrDestroyGString ; si = string handle
; set the file position back to start of page
call ResetFilePosition ; set to start o page
endif
; starting with a fresh transformation matrix, so apply
; our stuff to fit output to the printer resolution
mov di, curJob.SJI_bmWinHan ; get win handle in di
; Don't scale the window if tiramisu, postscript, and the
; first page. That's because the window's scale gets set during
; graphics init, but gets cleared out after every page.
mov al, curJob.SJI_printState ; check for PDL printer
and al, mask SPS_SMARTS ; is it PostScript ?
cmp al, PS_PDL
jne applyScale ; no, apply scale
test curJob.SJI_printState, mask SPS_TIRAMISU_PRINTING
jz applyScale
call GetPageNumber ; cx <- zero-based page number
jcxz setDefaultMatrix
applyScale:
movwwf dxcx, curJob.SJI_pXscale ; set up xscale factor
movwwf bxax, curJob.SJI_pYscale ; set up yscale factor
mov si, WIF_DONT_INVALIDATE ; don't force a redraw
call WinApplyScale ;
if _DUAL_THREADED_PRINTING
push di
mov di, curJob.SJI_bmWinHan2 ; get win handle in di
call WinApplyScale ;
pop di
endif ; _DUAL_THREADED_PRINTING
; set the default transformation matrix. This was determined
; by CalcDocOrientation, and handles the automatic rotation
; of documents to fit on the paper better.
setDefaultMatrix:
segmov ds, ss, si
lea si, curJob.SJI_defMatrix ; set it from here
mov cx, WIF_DONT_INVALIDATE ; don't force a redraw
call WinApplyTransform ; set the TMatrix
if _DUAL_THREADED_PRINTING
mov di, curJob.SJI_bmWinHan2 ; get win handle in di
call WinApplyTransform ; set the TMatrix
lea si, curJob.SJI_oldMatrix ; ds:si->buffer space
mov di, curJob.SJI_bmWinHan2 ; window handle
call WinGetTransform ; get old TMatrix
mov cx, WIF_DONT_INVALIDATE
call WinSetNullTransform ; set things back
mov bx, curJob.SJI_swathH ; translate this much
clr ax ; ax = x translation
call TranslateThePage ; DONT_INVAL still ok
mov cx, WIF_DONT_INVALIDATE
lea si, curJob.SJI_oldMatrix ; ds:si->buffer space
call WinApplyTransform ; apply old one
endif ; _DUAL_THREADED_PRINTING
; the code from here on down is responsible for the printing
; of a single DOCUMENT page (as opposed to just a PAPER page).
; That means we have to deal with tiling the output if the
; document is larger than will fit on a single piece of paper.
; We print across, then down, so handle the y loop on the
; outside and the xloop on the inside.
mov cx, curJob.SJI_yPages ; init y loop variable
mov curJob.SJI_curyPage, cx
tileInY:
lea si, curJob.SJI_yloopTM ; ds:si->buffer space
call GetOurTransformation ; save current TMatrix
if _DUAL_THREADED_PRINTING
; Save TMatrix for other bitmap window
push curJob.SJI_bmWinHan ; save SJI_bmWinHan
mov si, curJob.SJI_bmWinHan2 ; si <- bmWinHan2
mov curJob.SJI_bmWinHan, si ; bmWinHan = bmWinHan2
lea si, curJob.SJI_yloopTM2 ; ds:si->buffer space
call GetOurTransformation ; save current TMatrix
pop curJob.SJI_bmWinHan ; restore SJI_bmWinHan
endif ; _DUAL_THREADED_PRINTING
mov cx, curJob.SJI_xPages ; init #pages across
mov curJob.SJI_curxPage, cx
; next we implement the loop to tile across. Like the y loop
; we need to keep track of the current TM
tileInX:
call BumpPhysPageNumber
segmov ds, ss, si ; ds -> stack
lea si, curJob.SJI_xloopTM ; ds:si->buffer space
call GetOurTransformation ; save current TMatrix
if _DUAL_THREADED_PRINTING
; Save TMatrix for other bitmap window
push curJob.SJI_bmWinHan ; save SJI_bmWinHan
mov si, curJob.SJI_bmWinHan2 ; si <- bmWinHan2
mov curJob.SJI_bmWinHan, si ; bmWinHan = bmWinHan2
lea si, curJob.SJI_xloopTM2 ; ds:si->buffer space
call GetOurTransformation ; save current TMatrix
pop curJob.SJI_bmWinHan ; restore SJI_bmWinHan
endif ; _DUAL_THREADED_PRINTING
; let the printer know we're starting a page
if _NONSPOOL ;--------------------------------------------------------------
push ds
mov bx, curJob.SJI_pstate
call MemLock
mov ds, ax
test ds:[PS_paperInput], mask PIO_MANUAL
call MemUnlock ; (preserves flags)
pop ds
jz startPage ; no, auto-fed paper
checkPaper::
mov di, DR_PRINT_ESC_WAIT_FOR_MECH ; wait for print engine
mov bx, curJob.SJI_pstate
call curJob.SJI_pDriver
mov di, DR_PRINT_ESC_GET_ERRORS ; set the code
mov al, PJLP_noupdate
call curJob.SJI_pDriver ; call the driver
test al, mask PER_MPE ; paper present?
jnz askForPaper
startPage:
call ProcessStartPage
; This should load a sheet of paper, and now we will test for
; errors on the load.
call GetPrinterReturnCode
cmp ax, PDR_PAPER_JAM_OR_EMPTY ; jammed or empty?
jne startSwathes ; if not, let er rip...
askForPaper:
call NonSpoolPaperFeedBox
cmp ax, IC_OK
je startPage ; start page
jmp shutdownHere ; else shutdown
else ; not _NONSPOOL -------------------------------------------------------
call ProcessStartPage
jnc startSwathes ; check for errors
mov ax, GSRT_FAULT ; make like something
jmp doneDocPage ; bad happened
endif ; _NONSPOOL ---------------------------------------------------
; set whatever page-bound variables we need to
startSwathes:
movdw curJob.SJI_curScan, 0 ; start at top of page
; This loop draws the page over and over into each swath,
; and sends the swath off to be printed. Start by re-initing
; the bitmap.
swathLoop:
mov di, curJob.SJI_gstate ; get string handle
call GrClearBitmap ; di = bitmap gstate
; the file is already open, associate it with a graphics
; string handle
mov cx, GST_STREAM ; type of gstring it is
mov bx, curJob.SJI_fHan ; bx gets file handle
call GrLoadGString ; si = string handle
mov curJob.SJI_gstring, si ; store the handle
; now draw the document
mov di, curJob.SJI_gstate ; get string handle
test curJob.SJI_printState, mask SPS_TIRAMISU_PRINTING
jz normal
; Tiramisu printing: call swath library to fill bitmap.
push si
mov si, curJob.SJI_tiramisu.TP_jobToken
movdw bxax, curJob.SJI_tiramisu.TP_fetchSwath
call GetPageNumber ; cx = page number
call ProcCallFixedOrMovable ; call swath library
pop si
jmp postDraw
normal: ; Normal printing: call graphics system to fill bitmap.
clr ax ; no parameters
clr bx ; draw at (0,0)
; stop at end of page
mov dx, mask GSC_NEW_PAGE
call GrSaveState
call GrDrawGString ; draw the string
call GrRestoreState
postDraw:
push dx, cx ; save GSRetType & data
; this swath is done, destroy the string so we can start it
; up again.
mov dl, GSKT_LEAVE_DATA ; don't kill the data
call GrDestroyGString ; si = string handle
if _NONSPOOL ;--------------------------------------------------------------
call SpoolLockPrintJob ; set the semaphore.
; OK, it's built out, so send it on down to be printed
mov dx, curJob.SJI_bmFileHan ; pass huge arr handle
mov cx, curJob.SJI_bmHan
mov bx, curJob.SJI_pstate ; pass the pstate
if _DUAL_THREADED_PRINTING
call PrintSwathNoBlocking ; print it
else
mov di, DR_PRINT_SWATH ; the big one
call curJob.SJI_pDriver ; print it
endif
LONG jc ejectPaper
call SpoolUnlockPrintJob ; reset the semaphore.
; General check Error handling goes here.
; Make sure things are still ok after printing a swath.
call SpoolProcessErrors
LONG jc exitErr ; catastophic error?
cmp ax,GSRT_FAULT ; fault?
LONG je ejectPaper ; yes - eject paper
else ; not _NONSPOOL -------------------------------------------------------
; OK, it's built out, so send it on down to be printed
mov dx, curJob.SJI_bmFileHan ; pass huge arr handle
mov cx, curJob.SJI_bmHan
mov bx, curJob.SJI_pstate ; pass the pstate
if _DUAL_THREADED_PRINTING
call PrintSwathNoBlocking ; print it
else
mov di, DR_PRINT_SWATH ; the big one
call curJob.SJI_pDriver ; print it
endif
LONG jc exitErr
endif ; _NONSPOOL ---------------------------------------------------
if _DUAL_THREADED_PRINTING
; Now we need to switch the bitmaps so the printing thread
; can use the last bitmap while we're drawing a new bitmap
mov ax, curJob.SJI_bmHan
xchg ax, curJob.SJI_bmHan2
mov curJob.SJI_bmHan, ax
mov ax, curJob.SJI_bmWinHan
xchg ax, curJob.SJI_bmWinHan2
mov curJob.SJI_bmWinHan, ax
mov ax, curJob.SJI_gstate
xchg ax, curJob.SJI_gstate2
mov curJob.SJI_gstate, ax
endif ; _DUAL_THREADED_PRINTING
; see if we have more to print, update all the nice vars
movdw dxbx, curJob.SJI_curScan ; get current position
add bx, curJob.SJI_swathH ; calc new position
adc dx, 0
movdw curJob.SJI_curScan, dxbx ; update position
cmpdw dxbx, curJob.SJI_pageH ; done ?
pop ax, cx ; restore GSRetType,data
LONG jae donePage ; yes, time to reset
push ax, cx ; save GSRetType & data
subdw dxbx, curJob.SJI_pageH ; see if getting close
negdw dxbx
tst dx ; if still large
jnz applyTranslation
cmp bx, curJob.SJI_swathH ; < 1 swath left ?
jae applyTranslation ; no, continue
mov di, curJob.SJI_gstate ; pass bitmap handle
call GrClearBitmap
; since we are on the last swath, make sure that the
; bitmap height field in the Huge bitmap reflects how
; much we are actually going to send to the print driver.
mov dx, bx ; save word of height
call AdjustBitmapHeight
; apply proper window translation to draw the next piece
applyTranslation:
segmov ds, ss, si ; ds -> stack
lea si, curJob.SJI_oldMatrix ; ds:si->buffer space
mov di, curJob.SJI_bmWinHan ; window handle
call WinGetTransform ; get old TMatrix
mov cx, WIF_DONT_INVALIDATE
call WinSetNullTransform ; set things back
mov bx, curJob.SJI_swathH ; translate this much
if _DUAL_THREADED_PRINTING
shl bx, 1
endif
neg bx ; bx = y translation
clr ax ; ax = x translation
call TranslateThePage ; DONT_INVAL still ok
mov cx, WIF_DONT_INVALIDATE
lea si, curJob.SJI_oldMatrix ; ds:si->buffer space
call WinApplyTransform ; apply old one
; set the file position back to start of page
call ResetFilePosition ; set to start o page
; check queue info to see if we need to quit
call CheckForErrors ; check flag in q info
pop ax, cx ; restore GSRetType,data
jc abortDoc ; yes, abort the job
cmp ax, GSRT_FAULT ; something bad ?
je donePage ; yes, die
jmp swathLoop ; else print next swath
; printing interrupted
abortDoc:
mov ax, GSRT_FAULT ; fake completion
; done with the current page, so tell the printer driver
donePage:
if _DUAL_THREADED_PRINTING
call PrintBlockOnPrintThread
endif
mov bx, cx
call ProcessEndPage
; since we are on the last swath, make sure that the
; bitmap height field in the Huge bitmap reflects how
; much we are actually going to send to the print driver.
pushf ; save carry
mov dx, curJob.SJI_swathH ; get swath height
call AdjustBitmapHeight
popf ; restore carry status
if _DUAL_THREADED_PRINTING
pushf ; save carry
mov di, curJob.SJI_bmHan2 ;
xchg di, curJob.SJI_bmHan ; swap Bitmap handles
call AdjustBitmapHeight ; adjust SJI_bmHan2
mov curJob.SJI_bmHan, di ; restore SJI_bmHan
popf ; restore carry status
endif ; _DUAL_THREADED_PRINTING
if _NONSPOOL ;--------------------------------------------------------------
checkEndReturnCode:
LONG jc shutdownHere
cmp ax, GSRT_FAULT ; done ?
LONG je doneDocPage ; yes, all done
push ax ; save GSRet code.
call GetPrinterReturnCode ; get returns.
cmp ax, PDR_NO_RETURN
pop ax ; get back GSRet code.
je printNextPage
mov cx, PERROR_PAPER_MISFEED ; set jammed error code
clr dx
call SpoolErrorBox ; he can only answer OK
TestUserStandardDialogResponses\
SPOOL_BAD_USER_STANDARD_DIALOG_RESPONSE, IC_OK, IC_DISMISS
cmp ax, IC_OK ; if affirmative
LONG jne shutdownHere ; if not OK, quit...
; if OK, try again...
if _DUAL_THREADED_PRINTING
call PrintBlockOnPrintThread
endif
mov di, DR_PRINT_END_PAGE ; spit the paper out
mov bx, curJob.SJI_pstate ; pass the pstate
call curJob.SJI_pDriver
mov ax, GSRT_COMPLETE ; dumy GString ret code
jmp checkEndReturnCode
else ; not _NONSPOOL -------------------------------------------------------
jnc checkFault
mov ax, GSRT_FAULT ; there's a problem
jmp doneDocPage
; see if we REALLY need to quit (some fault). Otherwise
; handle the tiling stuff
checkFault:
cmp ax, GSRT_FAULT ; done ?
jne printNextPage ; yes, all done
jmp doneDocPage ; yes, all done
endif ; _NONSPOOL ---------------------------------------------------
; handle printing the next page to the right for tiled output
; the xloop is on the inside, so do that one first
printNextPage:
sub curJob.SJI_curxPage, 1 ; one less page to do
jle nextPassAcross ; finished this swoosh
; set the file position back to start of page
call ResetFilePosition ; set to start o page
; still have more to do across a swoosh (this is a technical
; term describing one pass of "pages" across the document ;)
lea si, curJob.SJI_xloopTM ; ds:si->buffer space
call SetOurTransformation ; apply old one
; assume tiling upright, but check rotated case
mov ax, curJob.SJI_printWidth ; translate this much
neg ax
clr bx
call TranslateThePage ; DONT_INVAL still ok
if _DUAL_THREADED_PRINTING ; Now do the same thing for other bitmap window
; still have more to do across a swoosh (this is a technical
; term describing one pass of "pages" across the document ;)
push curJob.SJI_bmWinHan ; save SJI_bmWinHan
mov si, curJob.SJI_bmWinHan2 ; si <- bmWinHan2
mov curJob.SJI_bmWinHan, si ; bmWinHan = bmWinHan2
lea si, curJob.SJI_xloopTM2 ; ds:si->buffer space
call SetOurTransformation ; save current TMatrix
pop curJob.SJI_bmWinHan ; restore SJI_bmWinHan
; assume tiling upright, but check rotated case
mov ax, curJob.SJI_printWidth ; translate this much
neg ax
clr bx
call TranslateThePage ; DONT_INVAL still ok
endif ; _DUAL_THREADED_PRINTING
if not _NONSPOOL ;-------------------------------------------------------------
call AskForNextPage
cmp ax, IC_DISMISS ; only happens if we're
je shutdownHere ; shutting down...
endif ;--------------------------------------------------------------
jmp tileInX ; more of swoosh to do
nextPassAcross:
sub curJob.SJI_curyPage, 1 ; one less page to do
LONG jle doneDocPage ; all done with doc pg
; set the file position back to start of page
call ResetFilePosition ; set to start o page
; still have more swooshes to do
lea si, curJob.SJI_yloopTM ; ds:si->buffer space
call SetOurTransformation ; apply old one
mov bx, curJob.SJI_printHeight ; translate this much
neg bx
clr ax
test curJob.SJI_printState, mask SPS_ROTATED
jz applyYTrans
xchg ax, bx ; swap amounts if so
applyYTrans:
call TranslateThePage ; DONT_INVAL still ok
if _DUAL_THREADED_PRINTING ; Now do the same thing for other bitmap window
; still have more swooshes to do
push curJob.SJI_bmWinHan ; save SJI_bmWinHan
mov si, curJob.SJI_bmWinHan2 ; si <- bmWinHan2
mov curJob.SJI_bmWinHan, si ; bmWinHan = bmWinHan2
lea si, curJob.SJI_yloopTM2 ; ds:si->buffer space
call SetOurTransformation ; apply old one
pop curJob.SJI_bmWinHan
mov bx, curJob.SJI_printHeight ; translate this much
neg bx
clr ax
test curJob.SJI_printState, mask SPS_ROTATED
jz applyYTrans2
xchg ax, bx ; swap amounts if so
applyYTrans2:
call TranslateThePage ; DONT_INVAL still ok
endif ; _DUAL_THREADED_PRINTING
if not _NONSPOOL ;-------------------------------------------------------------
call AskForNextPage
cmp ax, IC_DISMISS ; only happens if we're
je shutdownHere ; shutting down...
endif ;--------------------------------------------------------------
jmp tileInY ; do another swoosh
if _NONSPOOL ;--------------------------------------------------------------
ejectPaper:
if _DUAL_THREADED_PRINTING
call PrintBlockOnPrintThread
endif
mov di, DR_PRINT_END_PAGE ; spit the paper out
mov bx, curJob.SJI_pstate ; pass the pstate
call curJob.SJI_pDriver
call GetPrinterReturnCode ; get returns.
cmp ax, PDR_NO_RETURN
je exitErr
mov cx, PERROR_PAPER_MISFEED ; set jammed error code
clr dx
call SpoolErrorBox ; can only answer OK
TestUserStandardDialogResponses \
SPOOL_BAD_USER_STANDARD_DIALOG_RESPONSE, IC_OK, IC_DISMISS
cmp ax, IC_OK ; if affirmative
je ejectPaper ; if OK, try again...
endif ; _NONSPOOL ---------------------------------------------------
; there was an error in printing. just exit
exitErr:
pop ax, ax ; restore stack
shutdownHere:
mov ax, GSRT_FAULT ; pretend a problem
doneDocPage:
mov di, curJob.SJI_bmWinHan ; get window handle
mov cx, WIF_DONT_INVALIDATE ; dont inval the window
call WinSetNullTransform ; set it back
if _DUAL_THREADED_PRINTING
mov di, curJob.SJI_bmWinHan2 ; get window handle
mov cx, WIF_DONT_INVALIDATE ; dont inval the window
call WinSetNullTransform ; set it back
endif ; _DUAL_THREADED_PRINTING
.leave
ret
PrintGraphicsPage endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
AskForNextPage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Ask for the next piece of paper for manual feed, if needed
CALLED BY: GLOBAL
PASS: nothing
RETURN: ax - Dialog box results.
DESTROYED: bx,cx,dx
PSEUDO CODE/STRATEGY:
check manual feed flag and do the right thing
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Jim 03/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
if not _NONSPOOL ;-------------------------------------------------------------
AskForNextPage proc near
curJob local SpoolJobInfo
.enter inherit
push ds
mov bx, curJob.SJI_pstate
call MemLock
mov ds, ax
test ds:[PS_paperInput], mask PIO_MANUAL
call MemUnlock ; (preserves flags)
pop ds
jz done ; no, auto-fed paper
; we have a manual feed situation. Ask the user to stick
; another piece (but nicely)
mov cx, SERROR_MANUAL_PAPER_FEED ; ask for next piece
clr dx
call SpoolErrorBox ; he can only answer OK
TestUserStandardDialogResponses SPOOL_BAD_USER_STANDARD_DIALOG_RESPONSE, IC_OK, IC_DISMISS
done:
.leave
ret
AskForNextPage endp
endif ; not _NONSPOOL -------------------------------------------------------
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ResetFilePosition
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Reset the file position to read from the start of the page
CALLED BY: PrintGraphicsPage, PrintGraphicsLabels
PASS: nothing
RETURN:
DESTROYED: ax,bx,cx,dx
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Dave 12/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
ResetFilePosition proc far
curJob local SpoolJobInfo
.enter inherit
mov al, FILE_POS_START
mov bx, curJob.SJI_fHan ; fetch file handle
mov dx, {word} curJob.SJI_fPos ; and postion
mov cx, {word} curJob.SJI_fPos+2
call FilePos ; set to start o page
.leave
ret
ResetFilePosition endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
AdjustBitmapHeight
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Adjust the height of the bitmap to be the correct fraction
of a normal bitmap height
CALLED BY: PrintGraphicsPage, PrintGraphicsLabels
PASS: dx - height of the bitmap to set.
RETURN: nothing
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
since we are on the last swath, make sure that the
bitmap height field in the Huge bitmap reflects how
much we are actually going to send to the print driver.
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Dave 12/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
AdjustBitmapHeight proc far
uses ax,bx,di,ds
curJob local SpoolJobInfo
.enter inherit
mov di, curJob.SJI_bmHan ; get HugeArray handle
mov bx, curJob.SJI_bmFileHan ;
call HugeArrayLockDir ; lock dir block
mov ds, ax
mov ds:[size HugeArrayDirectory].B_height, dx
call HugeArrayDirty
call HugeArrayUnlockDir
.leave
ret
AdjustBitmapHeight endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
GetOurTransformation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: get the transformation matrix into curJob
CALLED BY: PrintGraphicsPage, PrintGraphicsLabels
PASS: si - pointer to TransMatrix buffer (in stack frame)
RETURN: nothing
DESTROYED: ax,bx,cx,dx
PSEUDO CODE/STRATEGY:
call WinGetTransform to fill the buffer in the stack frame
pointed at by si
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Dave 12/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
GetOurTransformation proc far
curJob local SpoolJobInfo
.enter inherit
segmov ds, ss, di ; ds -> stack
mov di, curJob.SJI_bmWinHan ; window handle
call WinGetTransform ; save current TMatrix
.leave
ret
GetOurTransformation endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SetOurTransformation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set our tmatrix into the W_TMatrix
CALLED BY: PrintGraphicsPage
PASS: si - pointer to TransMatrix buffer (in stack frame)
RETURN: nothing
DESTROYED: ax,bx,cx,dx
PSEUDO CODE/STRATEGY:
call WinSetTransform to fill the Window tmatrix from the
buffer in the stack frame pointed at by si
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Dave 12/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SetOurTransformation proc near
curJob local SpoolJobInfo
.enter inherit
segmov ds, ss, di
mov di, curJob.SJI_bmWinHan ; get window handle
mov cx, WIF_DONT_INVALIDATE
call WinSetTransform ; apply old one
.leave
ret
SetOurTransformation endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
TranslateThePage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Ask for the next piece of paper for manual feed, if needed
CALLED BY: PrintGraphicsPage
PASS: ax - translation in X
bx - translation in Y
cx - invalidation flag
RETURN: nothing
DESTROYED: ax,bx,cx,dx
PSEUDO CODE/STRATEGY:
check manual feed flag and do the right thing
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Dave 12/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
TranslateThePage proc near
curJob local SpoolJobInfo
.enter inherit
mov si, cx ; si get INVAL flag
test curJob.SJI_printState, mask SPS_ROTATED
jz applyTrans
xchg ax, bx ; swap amounts if so
applyTrans:
mov dx, ax ; x in dx.cx
clr cx
clr ax ; y in bx.ax
call WinApplyTranslation ; DONT_INVAL still ok
.leave
ret
TranslateThePage endp
PrintGraphics ends
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.